// // KMNSearchHanddler.swift // PDF Reader Pro // // Created by User-Tangchao on 2024/12/1. // import Cocoa class KMNSearchHanddler: NSObject { weak var pdfView: CPDFView? var type: KMNBotaSearchType = .search var searchResults: [KMBotaSearchSectionModel] = [] func search(keyword: String, isCase: Bool, isWholeWord: Bool, callback: @escaping (([KMBotaSearchSectionModel]?) -> Void)) { guard let document = self.pdfView?.document else { NSSound.beep() callback(nil) return } if document.isFinding { document.cancelFindString() } if keyword.isEmpty { callback(nil) return } let theKeyword = keyword.decomposedStringWithCompatibilityMapping var opt = CPDFSearchOptions() if isCase { opt.insert(.caseSensitive) } if isWholeWord { opt.insert(.matchWholeWord) } DispatchQueue.global().async { let result = document.findString(theKeyword, with: opt) self.searchResults.removeAll() for sels in result ?? [] { let sectionM = KMBotaSearchSectionModel() sectionM.pageIndex = Int(sels.first?.page.pageIndex() ?? 0) for sel in sels { let mode : KMSearchMode = KMSearchMode() mode.selection = sel mode.attributedString = KMOCToolClass.getAttributedString(selection: sel, keyword: theKeyword) mode.selectionPageIndex = document.index(for: sel.page) sectionM.items.append(mode) sel.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5)) } self.searchResults.append(sectionM) } DispatchQueue.main.async { callback(self.searchResults) } } } }