KMNSearchHanddler.swift 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //
  2. // KMNSearchHanddler.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by User-Tangchao on 2024/12/1.
  6. //
  7. import Cocoa
  8. class KMNSearchHanddler: NSObject {
  9. weak var pdfView: CPDFView?
  10. var type: KMNBotaSearchType = .search
  11. var searchResults: [KMBotaSearchSectionModel] = []
  12. func search(keyword: String, isCase: Bool, isWholeWord: Bool, callback: @escaping (([KMBotaSearchSectionModel]?) -> Void)) {
  13. guard let document = self.pdfView?.document else {
  14. NSSound.beep()
  15. callback(nil)
  16. return
  17. }
  18. if document.isFinding {
  19. document.cancelFindString()
  20. }
  21. if keyword.isEmpty {
  22. callback(nil)
  23. return
  24. }
  25. let theKeyword = keyword.decomposedStringWithCompatibilityMapping
  26. var opt = CPDFSearchOptions()
  27. if isCase {
  28. opt.insert(.caseSensitive)
  29. }
  30. if isWholeWord {
  31. opt.insert(.matchWholeWord)
  32. }
  33. DispatchQueue.global().async {
  34. let result = document.findString(theKeyword, with: opt)
  35. self.searchResults.removeAll()
  36. for sels in result ?? [] {
  37. let sectionM = KMBotaSearchSectionModel()
  38. sectionM.pageIndex = Int(sels.first?.page.pageIndex() ?? 0)
  39. for sel in sels {
  40. let mode : KMSearchMode = KMSearchMode()
  41. mode.selection = sel
  42. mode.attributedString = KMOCToolClass.getAttributedString(selection: sel, keyword: theKeyword)
  43. mode.selectionPageIndex = document.index(for: sel.page)
  44. sectionM.items.append(mode)
  45. sel.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  46. }
  47. self.searchResults.append(sectionM)
  48. }
  49. DispatchQueue.main.async {
  50. callback(self.searchResults)
  51. }
  52. }
  53. }
  54. }