KMNSearchHanddler.swift 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 searchResults: [KMSearchMode] = []
  11. func search(keyword: String, isCase: Bool, isWholeWord: Bool, callback: @escaping (([KMSearchMode]?) -> Void)) {
  12. guard let document = self.pdfView?.document else {
  13. NSSound.beep()
  14. callback(nil)
  15. return
  16. }
  17. if document.isFinding {
  18. document.cancelFindString()
  19. }
  20. if keyword.isEmpty {
  21. callback(nil)
  22. return
  23. }
  24. let theKeyword = keyword.decomposedStringWithCompatibilityMapping
  25. var opt = CPDFSearchOptions()
  26. if isCase {
  27. opt.insert(.caseSensitive)
  28. }
  29. if isWholeWord {
  30. opt.insert(.matchWholeWord)
  31. }
  32. DispatchQueue.global().async {
  33. let result = document.findString(theKeyword, with: opt)
  34. self.searchResults.removeAll()
  35. for sels in result ?? [] {
  36. for sel in sels {
  37. let mode : KMSearchMode = KMSearchMode()
  38. mode.selection = sel
  39. mode.attributedString = KMOCToolClass.getAttributedString(selection: sel, keyword: theKeyword)
  40. mode.selectionPageIndex = document.index(for: sel.page)
  41. self.searchResults.insert(mode, at: self.searchResults.count)
  42. sel.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  43. }
  44. }
  45. DispatchQueue.main.async {
  46. callback(self.searchResults)
  47. }
  48. }
  49. }
  50. }