KMNSearchHanddler.swift 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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: [KMSearchMode] = []
  12. func search(keyword: String, isCase: Bool, isWholeWord: Bool, callback: @escaping (([KMSearchMode]?) -> 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. for sel in sels {
  38. let mode : KMSearchMode = KMSearchMode()
  39. mode.selection = sel
  40. mode.attributedString = KMOCToolClass.getAttributedString(selection: sel, keyword: theKeyword)
  41. mode.selectionPageIndex = document.index(for: sel.page)
  42. self.searchResults.insert(mode, at: self.searchResults.count)
  43. sel.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  44. }
  45. }
  46. DispatchQueue.main.async {
  47. callback(self.searchResults)
  48. }
  49. }
  50. }
  51. }