KMBotaSearchViewController.swift 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  1. //
  2. // KMBotaSearchViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/11/16.
  6. //
  7. import Cocoa
  8. import KMComponentLibrary
  9. extension KMNSearchKey.wholeWords {
  10. static let botaSearch = "BotaSearchWholeWordsKey"
  11. }
  12. extension KMNSearchKey.caseSensitive {
  13. static let botaSearch = "BotaSearchCaseSensitiveKey"
  14. }
  15. enum KMNBotaSearchType: Int {
  16. case none = 0
  17. case search = 1
  18. case replace = 2
  19. }
  20. @objc protocol KMBotaSearchViewControllerDelegate: NSObjectProtocol {
  21. @objc optional func switchSearchPopWindow(controller: KMBotaSearchViewController)
  22. @objc optional func searchTypeDidChange(controller: KMBotaSearchViewController)
  23. }
  24. class KMBotaSearchViewController: KMNBotaBaseViewController {
  25. @IBOutlet weak var topView: NSBox!
  26. @IBOutlet weak var topHeightConst: NSLayoutConstraint!
  27. var contentView: NSView? {
  28. didSet {
  29. if let view = self.contentView {
  30. self.box.contentView = view
  31. }
  32. }
  33. }
  34. @IBOutlet weak var emptyBox: NSBox!
  35. @IBOutlet weak var box: NSBox!
  36. @IBOutlet weak var emptySearchLabel: NSTextField!
  37. // @IBOutlet weak var searchLabel: NSTextField!
  38. // @IBOutlet weak var searchTips: NSTextField!
  39. // @IBOutlet weak var pageLabel: NSTextField!
  40. @IBOutlet var scrollView: NSScrollView!
  41. @IBOutlet weak var tableView: KMBotaTableView!
  42. private lazy var topContentView_: KMNBotaSearchTopView? = {
  43. let view = KMNBotaSearchTopView.createFromNib()
  44. return view
  45. }()
  46. private var emptyView_: ComponentEmpty = {
  47. let view = ComponentEmpty()
  48. view.properties = ComponentEmptyProperty(emptyType: .noSearch, state: .normal, text: KMLocalizedString("No Results"), subText: KMLocalizedString(""))
  49. return view
  50. }()
  51. var previousButton: ComponentButton? {
  52. get {
  53. return topContentView_?.previousButton
  54. }
  55. }
  56. var nextButton: ComponentButton? {
  57. get {
  58. return topContentView_?.nextButton
  59. }
  60. }
  61. var replaceAllButton: ComponentButton? {
  62. get {
  63. return topContentView_?.replaceAllButton
  64. }
  65. }
  66. var replaceButton: ComponentButton? {
  67. get {
  68. return topContentView_?.replaceButton
  69. }
  70. }
  71. private var menuGroupView_: ComponentGroup?
  72. private var menuSections_: [CPDFSelection] = []
  73. private var menuType_: CAnnotationType = .circle
  74. var handdler = KMNSearchHanddler()
  75. weak var delegate: KMBotaSearchViewControllerDelegate?
  76. var searchResults : [KMBotaSearchSectionModel] = [] {
  77. didSet {
  78. self.updataLeftSideFindView()
  79. }
  80. }
  81. private var datas: [Any] = []
  82. private var searchResultIndex_: Int = -1
  83. private var currentSel: CPDFSelection?
  84. private var currentModel_: KMSearchMode?
  85. private var finding_ = false
  86. override func loadView() {
  87. super.loadView()
  88. topView.borderWidth = 0
  89. topView.fillColor = .clear
  90. topView.contentView = topContentView_
  91. topContentView_?.itemClick = { [unowned self] idx, params in
  92. if idx == KMNBotaSearchTopItemKey.search.rawValue {
  93. if let data = params.first as? ComponentButton {
  94. showSearchGroupView(sender: data)
  95. }
  96. } else if idx == KMNBotaSearchTopItemKey.replace.rawValue {
  97. if handdler.type == .search {
  98. showReplaceView()
  99. } else {
  100. showSearchView()
  101. }
  102. } else if idx == KMNBotaSearchTopItemKey.switch.rawValue {
  103. delegate?.switchSearchPopWindow?(controller: self)
  104. } else if idx == KMNBotaSearchTopItemKey.previous.rawValue {
  105. if handdler.isEditing() == false {
  106. tableViewMoveUp(tableView)
  107. } else {
  108. tableViewMoveUp(tableView)
  109. _previousAction(NSButton())
  110. }
  111. } else if idx == KMNBotaSearchTopItemKey.next.rawValue {
  112. if handdler.isEditing() == false {
  113. tableViewMoveDown(tableView)
  114. } else {
  115. tableViewMoveDown(tableView)
  116. _nextAction(NSButton())
  117. }
  118. } else if idx == KMNBotaSearchTopItemKey.replaceText.rawValue {
  119. _replaceAction(NSButton())
  120. } else if idx == KMNBotaSearchTopItemKey.replaceAllText.rawValue {
  121. _replaceAllAction(NSButton())
  122. }
  123. }
  124. showSearchView()
  125. topContentView_?.valueDidChange = { [unowned self] sender, info in
  126. guard let string = info?[.newKey] as? String else {
  127. return
  128. }
  129. updateButtonStatus()
  130. currentSel = nil
  131. currentModel_ = nil
  132. self.search(keyword: string) { [unowned self] results in }
  133. }
  134. emptyBox.contentView?.addSubview(emptyView_)
  135. emptyView_.km_add_top_constraint(constant: 232)
  136. emptyView_.km_add_bottom_constraint()
  137. emptyView_.km_add_leading_constraint()
  138. emptyView_.km_add_trailing_constraint()
  139. self.emptySearchLabel.stringValue = KMLocalizedString("")
  140. self.emptySearchLabel.textColor = KMAppearance.Layout.h1Color()
  141. contentView = tableView.enclosingScrollView
  142. tableView.menuClickedAction = { [unowned self] point in
  143. let idxs = self.tableView.selectedRowIndexes.count
  144. let convertP = self.tableView.convert(point, from: nil)
  145. let row = self.tableView.row(at: convertP)
  146. if row == -1 {
  147. return NSMenu()
  148. }
  149. let hideNotes = handdler.hideNotes()
  150. let allowsNotes = handdler.allowsNotes()
  151. if hideNotes || allowsNotes == false {
  152. return NSMenu()
  153. }
  154. guard let model = self.datas[row] as? KMSearchMode else {
  155. return NSMenu()
  156. }
  157. var viewHeight: CGFloat = 0
  158. let items: [String] = ["Add New Circle", "Add New Rectangle", "Add New Highlight", "Add New Underline", "Add New Strikethrough"]
  159. var menuItemArr: [ComponentMenuitemProperty] = []
  160. for value in items {
  161. let properties_Menuitem: ComponentMenuitemProperty = ComponentMenuitemProperty(multipleSelect: false,
  162. itemSelected: false,
  163. isDisabled: false,
  164. keyEquivalent: nil,
  165. text: KMLocalizedString(value),
  166. identifier: value)
  167. menuItemArr.append(properties_Menuitem)
  168. viewHeight += 36
  169. }
  170. self.menuGroupView_ = ComponentGroup.createFromNib(in: ComponentLibrary.shared.componentBundle())
  171. self.menuGroupView_?.clickedAutoHide = false
  172. self.menuGroupView_?.groupDelegate = self
  173. self.menuGroupView_?.frame = CGRectMake(0, 0, 180, viewHeight)
  174. self.menuGroupView_?.updateGroupInfo(menuItemArr)
  175. self.menuSections_ = [model.selection]
  176. self.menuGroupView_?.showWithPoint(CGPoint(x: point.x, y: point.y - viewHeight), relativeTo: self.tableView)
  177. return NSMenu()
  178. }
  179. }
  180. override func viewDidLoad() {
  181. super.viewDidLoad()
  182. tableView.delegate = self
  183. tableView.dataSource = self
  184. tableView.botaDelegate = self
  185. tableView.hasImageToolTips = true
  186. updateButtonStatus()
  187. }
  188. override func viewDidAppear() {
  189. super.viewDidAppear()
  190. view.window?.makeFirstResponder(topContentView_?.searchInput)
  191. }
  192. override func updateUILanguage() {
  193. super.updateUILanguage()
  194. KMMainThreadExecute {
  195. self.topContentView_?.resultLabel.stringValue = KMLocalizedString("Result:") + " " + "\(self.handdler.searchResults.count)"
  196. self.tableView.reloadData()
  197. }
  198. }
  199. override func updateUIThemeColor() {
  200. super.updateUIThemeColor()
  201. KMMainThreadExecute {
  202. self.view.wantsLayer = true
  203. let color = KMNColorTools.colorBg_layoutMiddle()
  204. self.view.layer?.backgroundColor = color.cgColor
  205. self.tableView.backgroundColor = color
  206. self.topContentView_?.replaceInput.properties.leftIcon = NSImage(named: "KMImagenameBotaSearchInputPrefiex")
  207. self.topContentView_?.replaceInput.reloadData()
  208. self.topContentView_?.resultLabel.textColor = KMNColorTools.colorText_3()
  209. self.topContentView_?.bottomLine.layer?.backgroundColor = KMNColorTools.colorPrimary_border1().cgColor
  210. self.tableView.reloadData()
  211. }
  212. }
  213. func showSearchView() {
  214. handdler.type = .search
  215. topContentView_?.showSearch()
  216. topHeightConst.constant = topContentView_?.fetchContentHeight(type: handdler.type, hasResult: handdler.searchResults.isEmpty == false) ?? 0
  217. delegate?.searchTypeDidChange?(controller: self)
  218. }
  219. func showReplaceView() {
  220. if IAPProductsManager.default().isAvailableAllFunction() == false {
  221. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  222. return
  223. }
  224. handdler.type = .replace
  225. topContentView_?.showReplace()
  226. topHeightConst.constant = topContentView_?.fetchContentHeight(type: handdler.type, hasResult: handdler.searchResults.isEmpty == false) ?? 0
  227. delegate?.searchTypeDidChange?(controller: self)
  228. if let keyword = topContentView_?.inputValue, keyword.isEmpty == false {
  229. DispatchQueue.main.async {
  230. self.search(keyword: keyword) { models in }
  231. }
  232. }
  233. }
  234. func showResult() {
  235. topContentView_?.showResult(type: handdler.type)
  236. var theIdx = 0
  237. var count = 0
  238. if self.datas.isEmpty {
  239. topContentView_?.resultLabel.stringValue = ""
  240. } else {
  241. count = self.handdler.searchResults.count
  242. var i = 0
  243. var sectionCount = 0
  244. for model in self.datas {
  245. if i > self.tableView.selectedRow {
  246. break
  247. }
  248. if let data = model as? KMBotaSearchSectionModel {
  249. sectionCount += 1
  250. }
  251. i += 1
  252. }
  253. let theIdx = max(i-sectionCount, 1)
  254. topContentView_?.resultLabel.stringValue = KMLocalizedString("Result:") + " \(theIdx)/" + "\(count)"
  255. }
  256. topHeightConst.constant = topContentView_?.fetchContentHeight(type: handdler.type, hasResult: searchResults.isEmpty == false) ?? 0
  257. self.updateReplaceButtonState()
  258. }
  259. func update(keyborad: String?, replaceKey: String?, results: [KMBotaSearchSectionModel]) {
  260. topContentView_?.inputValue = keyborad
  261. topContentView_?.replaceText = replaceKey
  262. handdler.searchKey = keyborad
  263. handdler.replaceKey = replaceKey
  264. if let data = keyborad, data.isEmpty == false {
  265. self.search(keyword: data) { models in}
  266. }
  267. updateButtonStatus()
  268. }
  269. private func fetchSearchOptions() -> CPDFSearchOptions {
  270. var opt = CPDFSearchOptions()
  271. let isCase = KMDataManager.ud_bool(forKey: KMNSearchKey.caseSensitive.botaSearch)
  272. let isWholeWord = KMDataManager.ud_bool(forKey: KMNSearchKey.wholeWords.botaSearch)
  273. if isCase {
  274. opt.insert(.caseSensitive)
  275. }
  276. if isWholeWord {
  277. opt.insert(.matchWholeWord)
  278. }
  279. return opt
  280. }
  281. func updateButtonStatus() {
  282. let value = topContentView_?.inputValue ?? ""
  283. if value.isEmpty {
  284. previousButton?.properties.isDisabled = true
  285. previousButton?.reloadData()
  286. nextButton?.properties.isDisabled = true
  287. nextButton?.reloadData()
  288. replaceButton?.properties.isDisabled = true
  289. replaceButton?.reloadData()
  290. replaceAllButton?.properties.isDisabled = true
  291. replaceAllButton?.reloadData()
  292. } else {
  293. previousButton?.properties.isDisabled = false
  294. previousButton?.reloadData()
  295. nextButton?.properties.isDisabled = false
  296. nextButton?.reloadData()
  297. replaceButton?.properties.isDisabled = false
  298. replaceButton?.reloadData()
  299. replaceAllButton?.properties.isDisabled = false
  300. replaceAllButton?.reloadData()
  301. }
  302. }
  303. func updateReplaceButtonState() {
  304. if self.datas.isEmpty {
  305. previousButton?.properties.isDisabled = true
  306. previousButton?.reloadData()
  307. nextButton?.properties.isDisabled = true
  308. nextButton?.reloadData()
  309. replaceButton?.properties.isDisabled = true
  310. replaceButton?.reloadData()
  311. replaceAllButton?.properties.isDisabled = true
  312. replaceAllButton?.reloadData()
  313. } else {
  314. previousButton?.properties.isDisabled = false
  315. previousButton?.reloadData()
  316. nextButton?.properties.isDisabled = false
  317. nextButton?.reloadData()
  318. replaceButton?.properties.isDisabled = false
  319. replaceButton?.reloadData()
  320. replaceAllButton?.properties.isDisabled = false
  321. replaceAllButton?.reloadData()
  322. }
  323. }
  324. private func _showNoResultsAlert() {
  325. _ = _showAlert(style: .critical, message: KMLocalizedString("No related content found, please change keyword."), info: "", buttons: [KMLocalizedString("OK", comment: "")])
  326. }
  327. private func _showAlert(style: NSAlert.Style, message: String, info: String, buttons: [String]) -> NSApplication.ModalResponse {
  328. let alert = NSAlert()
  329. alert.alertStyle = style
  330. alert.messageText = message
  331. alert.informativeText = info
  332. for button in buttons {
  333. alert.addButton(withTitle: button)
  334. }
  335. return alert.runModal()
  336. }
  337. private func updateResults(results: [[CPDFSelection]]?) {
  338. let theKeyword = handdler.searchKey?.decomposedStringWithCompatibilityMapping ?? ""
  339. var datas: [KMBotaSearchSectionModel] = []
  340. var models: [KMSearchMode] = []
  341. for sels in results ?? [] {
  342. let sectionM = KMBotaSearchSectionModel()
  343. sectionM.pageIndex = Int(sels.first?.page.pageIndex() ?? 0)
  344. for sel in sels {
  345. let mode : KMSearchMode = KMSearchMode()
  346. mode.selection = sel
  347. mode.attributedString = KMOCToolClass.getAttributedString(selection: sel, keyword: theKeyword)
  348. mode.selectionPageIndex = handdler.pdfDocument()?.index(for: sel.page) ?? 0
  349. sectionM.items.append(mode)
  350. sel.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  351. models.append(mode)
  352. }
  353. datas.append(sectionM)
  354. }
  355. handdler.searchResults = models
  356. handdler.searchSectionResults = datas
  357. self.searchResults = datas
  358. // self.searchResults.first?.isExpand = true
  359. for model in self.searchResults {
  360. model.isExpand = true
  361. }
  362. self.currentModel_ = datas.first?.items.first
  363. self.tableView.reloadData()
  364. self.showResult()
  365. }
  366. @objc private func _previousAction(_ sender: NSButton) {
  367. let isEditing = self.handdler.pdfView?.isEditing() ?? false
  368. if isEditing == false {
  369. let index = self.handdler.previous()
  370. let model = self.handdler.searchResults[index]
  371. self.handdler.showSelection(model.selection)
  372. } else {
  373. if let _ = self.currentSel {
  374. self.currentSel = self.handdler.pdfView?.document.findForwardEditText()
  375. if let sel = self.currentSel {
  376. self.handdler.showSelection(sel)
  377. } else {
  378. _showNoResultsAlert()
  379. return
  380. }
  381. } else {
  382. if self.finding_ {
  383. return
  384. }
  385. self.finding_ = true
  386. let searchS = self.topContentView_?.inputValue ?? ""
  387. let opt = self.fetchSearchOptions()
  388. // self._beginLoading()
  389. DispatchQueue.global().async {
  390. let datas = self.handdler.pdfView?.document.startFindEditText(from: nil, with: searchS, options: opt)
  391. DispatchQueue.main.async {
  392. // self._endLoading()
  393. self.finding_ = false
  394. let sel = datas?.first?.first
  395. self.currentSel = sel
  396. self.handdler.showSelection(sel)
  397. self.updateResults(results: datas)
  398. }
  399. }
  400. }
  401. }
  402. }
  403. @objc private func _nextAction(_ sender: NSButton) {
  404. let isEditing = self.handdler.pdfView?.isEditing() ?? false
  405. if isEditing == false {
  406. let index = self.handdler.next()
  407. let model = self.handdler.searchResults[index]
  408. self.handdler.showSelection(model.selection)
  409. } else {
  410. if let _ = self.currentSel {
  411. self.currentSel = self.handdler.pdfView?.document.findBackwordEditText()
  412. if let sel = self.currentSel {
  413. self.handdler.showSelection(sel)
  414. } else {
  415. _showNoResultsAlert()
  416. }
  417. } else {
  418. if self.finding_ {
  419. return
  420. }
  421. self.finding_ = true
  422. let searchS = self.topContentView_?.inputValue ?? ""
  423. let opt = self.fetchSearchOptions()
  424. // self._beginLoading()
  425. DispatchQueue.global().async {
  426. let datas = self.handdler.pdfView?.document.startFindEditText(from: nil, with: searchS, options: opt)
  427. DispatchQueue.main.async {
  428. // self._endLoading()
  429. self.finding_ = false
  430. let sel = datas?.first?.first
  431. self.currentSel = sel
  432. self.handdler.showSelection(sel)
  433. }
  434. }
  435. }
  436. }
  437. }
  438. @objc private func _replaceAction(_ sender: NSButton) {
  439. let isEditing = self.handdler.pdfView?.isEditing() ?? false
  440. if isEditing == false {
  441. NSSound.beep()
  442. return
  443. }
  444. if let sel = self.currentSel {
  445. let searchS = self.topContentView_?.inputValue ?? ""
  446. let replaceS = self.topContentView_?.replaceText ?? ""
  447. let success = self.handdler.replace(searchS: searchS, replaceS: replaceS, sel: sel) { [weak self] newSel in
  448. self?.handdler.showSelection(newSel)
  449. if let data = newSel {
  450. self?.currentModel_?.selection = data
  451. // self?.currentModel_?.attributedString = KMOCToolClass.getAttributedString(selection: data, keyword: replaceS)
  452. self?.tableView.reloadData()
  453. }
  454. }
  455. } else { // 先查找
  456. if self.finding_ {
  457. return
  458. }
  459. self.finding_ = true
  460. let searchS = self.topContentView_?.inputValue ?? ""
  461. let opt = self.fetchSearchOptions()
  462. DispatchQueue.global().async {
  463. let datas = self.handdler.pdfView?.document.startFindEditText(from: nil, with: searchS, options: opt)
  464. DispatchQueue.main.async {
  465. self.finding_ = false
  466. let sel = datas?.first?.first
  467. self.currentSel = sel
  468. self.handdler.showSelection(sel)
  469. self.updateResults(results: datas)
  470. }
  471. }
  472. }
  473. }
  474. @objc private func _replaceAllAction(_ sender: NSButton) {
  475. let isEditing = self.handdler.pdfView?.isEditing() ?? false
  476. if isEditing == false {
  477. NSSound.beep()
  478. return
  479. }
  480. let datas = self.handdler.pdfView?.document.findEditSelections() ?? []
  481. if datas.isEmpty {
  482. _showNoResultsAlert()
  483. return
  484. }
  485. if self.finding_ {
  486. return
  487. }
  488. self.finding_ = true
  489. let searchS = self.topContentView_?.inputValue ?? ""
  490. let replaceS = self.topContentView_?.replaceText ?? ""
  491. // self._beginLoading()
  492. DispatchQueue.global().async {
  493. self.handdler.pdfView?.document.replaceAllEditText(with: searchS, toReplace: replaceS)
  494. self.currentSel = nil
  495. DispatchQueue.main.async {
  496. // self._endLoading()
  497. self.finding_ = false
  498. self.handdler.pdfView?.setHighlightedSelection(nil, animated: false)
  499. self.handdler.pdfView?.setNeedsDisplayForVisiblePages()
  500. }
  501. }
  502. }
  503. // MARK: - Group View
  504. func showSearchGroupView(sender: ComponentButton) {
  505. var viewHeight: CGFloat = 8
  506. var menuItemArr: [ComponentMenuitemProperty] = []
  507. let titles = ["Search", "Find and Replace", "", "Whole Words", "Case Sensitive"]
  508. for i in titles {
  509. if i.isEmpty {
  510. let menuI = ComponentMenuitemProperty.divider()
  511. menuItemArr.append(menuI)
  512. viewHeight += 8
  513. } else {
  514. let menuI = ComponentMenuitemProperty(text: KMLocalizedString(i))
  515. menuItemArr.append(menuI)
  516. viewHeight += 36
  517. }
  518. }
  519. if handdler.type == .search {
  520. menuItemArr.first?.righticon = NSImage(named: "KMNImageNameMenuSelect")
  521. } else if handdler.type == .replace {
  522. let info = menuItemArr.safe_element(for: 1) as? ComponentMenuitemProperty
  523. info?.righticon = NSImage(named: "KMNImageNameMenuSelect")
  524. }
  525. if let info = menuItemArr.safe_element(for: 3) as? ComponentMenuitemProperty {
  526. if KMDataManager.ud_bool(forKey: KMNSearchKey.wholeWords.botaSearch) {
  527. info.righticon = NSImage(named: "KMNImageNameMenuSelect")
  528. }
  529. }
  530. if let info = menuItemArr.last {
  531. if KMDataManager.ud_bool(forKey: KMNSearchKey.caseSensitive.botaSearch) {
  532. info.righticon = NSImage(named: "KMNImageNameMenuSelect")
  533. }
  534. }
  535. let groupView = ComponentGroup.createFromNib(in: ComponentLibrary.shared.componentBundle())
  536. searchGroupView = groupView
  537. groupView?.groupDelegate = self
  538. groupView?.frame = CGRectMake(310, 0, 200, viewHeight)
  539. groupView?.updateGroupInfo(menuItemArr)
  540. var point = sender.convert(sender.frame.origin, to: nil)
  541. point.y -= viewHeight
  542. groupView?.showWithPoint(point, relativeTo: sender)
  543. searchGroupTarget = sender
  544. }
  545. @objc func goToSelectedFindResults(_ sender: AnyObject?) {
  546. // guard let olView = sender as? NSTableView, olView.clickedRow != -1 else {
  547. // NSSound.beep()
  548. // return
  549. // }
  550. // self.updateFindResultHighlightsForDirection(.directSelection)
  551. }
  552. @objc func addAnnotationsForSelections(_ sender: NSMenuItem) {
  553. let listView = handdler.pdfView as? CPDFListView
  554. for selection in menuSections_ {
  555. // if menuType_ == .circle {
  556. listView?.addAnnotation(with: menuType_, selection: selection, page: selection.page, bounds: selection.bounds)
  557. // }
  558. }
  559. }
  560. func updataLeftSideFindView() {
  561. if (self.searchResults.count > 0) {
  562. self.emptyBox.isHidden = true
  563. } else {
  564. self.emptyBox.isHidden = false
  565. }
  566. }
  567. func updateFindResultHighlightsForDirection(_ direction: NSWindow.SelectionDirection) {
  568. var findResults: [KMSearchMode] = handdler.searchResults
  569. if (findResults.count == 0) {
  570. handdler.showSelection(nil)
  571. } else {
  572. if direction == .directSelection {
  573. self.searchResultIndex_ = 0
  574. } else if (direction == .selectingNext) {
  575. self.searchResultIndex_ += 1
  576. if self.searchResultIndex_ >= findResults.count {
  577. self.searchResultIndex_ = 0
  578. }
  579. } else if (direction == .selectingPrevious) {
  580. self.searchResultIndex_ -= 1
  581. if self.searchResultIndex_ < 0 {
  582. self.searchResultIndex_ = findResults.count-1
  583. }
  584. }
  585. let currentSel = findResults[self.searchResultIndex_].selection
  586. if currentSel.hasCharacters() {
  587. let page = currentSel.safeFirstPage()
  588. var rect = NSZeroRect
  589. for model in findResults {
  590. if let data = page, model.selection.pages().contains(data) {
  591. rect = NSUnionRect(rect, model.selection.bounds(for: data))
  592. }
  593. }
  594. let FIND_RESULT_MARGIN = 50.0
  595. rect = NSIntersectionRect(NSInsetRect(rect, -FIND_RESULT_MARGIN, -FIND_RESULT_MARGIN), page?.bounds(for: .cropBox) ?? .zero)
  596. handdler.pdfView?.go(to: page)
  597. handdler.pdfView?.go(to: rect, on: page)
  598. }
  599. if currentSel.hasCharacters() {
  600. let bColor = NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5)
  601. let color = NSColor(red: 219/255.0, green: 220/255.0, blue: 3/255.0, alpha: 0.5)
  602. handdler.pdfView?.setHighlight(currentSel, forBorderColor: .clear, fill: color, animated: true)
  603. handdler.pdfView?.go(to: currentSel, animated: true)
  604. handdler.pdfView?.setCurrentSelection(currentSel, animate: true)
  605. }
  606. // let mode = self.listView?.toolMode ?? .none
  607. // if mode == .moveToolMode || mode == .magnifyToolMode || mode == .selectToolMode {
  608. // self.listView?.setCurrentSelection(nil, animate: false)
  609. // }
  610. }
  611. }
  612. }
  613. // MARK: - NSTableViewDelegate, NSTableViewDataSource
  614. extension KMBotaSearchViewController: NSTableViewDelegate, NSTableViewDataSource {
  615. func numberOfRows(in tableView: NSTableView) -> Int {
  616. var datas: [Any] = []
  617. for sectionM in self.handdler.searchSectionResults {
  618. if sectionM.items.count > 0 {
  619. datas.append(sectionM)
  620. if sectionM.isExpand == false {
  621. continue
  622. }
  623. for item in sectionM.items {
  624. datas.append(item)
  625. }
  626. }
  627. }
  628. self.datas = datas
  629. return datas.count
  630. }
  631. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  632. let model = self.datas[row]
  633. if let data = model as? KMBotaSearchSectionModel {
  634. var cell = tableView.makeView(withIdentifier: KMSectionCellView.km_identifier, owner: nil) as? KMSectionCellView
  635. if cell == nil {
  636. cell = KMSectionCellView.createFromNib()
  637. }
  638. cell?.titleLabel.font = ComponentLibrary.shared.getFontFromKey("mac/body-s-medium")
  639. cell?.countLabel.font = ComponentLibrary.shared.getFontFromKey("mac/body-s-regular")
  640. cell?.titleLabel.textColor = KMNColorTools.colorText_1()
  641. cell?.countLabel.textColor = KMNColorTools.colorText_3()
  642. cell?.titleLabel.isEditable = false
  643. cell?.isExpand = data.isExpand
  644. let pageIndex = data.pageIndex
  645. cell?.titleLabel.stringValue = KMLocalizedString("Page") + " \(pageIndex + 1)"
  646. cell?.countLabel.stringValue = "\(data.itemCount)"
  647. cell?.bottomLine.wantsLayer = true
  648. cell?.bottomLine.layer?.backgroundColor = KMNColorTools.colorBorder_divider().cgColor
  649. cell?.itemClick = { [weak self] idx, _ in
  650. if idx == 1 { // 收取 & 展开
  651. data.isExpand = !data.isExpand
  652. self?.tableView.reloadData()
  653. }
  654. }
  655. return cell
  656. }
  657. if let data = model as? KMSearchMode {
  658. var cell = tableView.makeView(withIdentifier: KMNBotaSearchCellView.km_identifier, owner: self) as? KMNBotaSearchCellView
  659. if cell == nil {
  660. cell = KMNBotaSearchCellView()
  661. }
  662. cell?.label.attributedStringValue = data.attributedString
  663. cell?.label.isEnabled = false
  664. return cell
  665. }
  666. return nil
  667. }
  668. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  669. let model = datas[row]
  670. if model is KMBotaSearchSectionModel {
  671. return 40.0
  672. }
  673. if let data = model as? KMSearchMode {
  674. let width = NSWidth(self.view.frame)
  675. let rect = data.attributedString.boundingRect(with: .init(width: width-24*2, height: CGFLOAT_MAX), options: [.usesLineFragmentOrigin, .usesLineFragmentOrigin])
  676. return rect.size.height + 12 * 2
  677. }
  678. return 40.0
  679. }
  680. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  681. let model = datas[row]
  682. if model is KMBotaSearchSectionModel {
  683. let rowView = KMTableRowView()
  684. rowView.selectionBackgroundColorBlock = {
  685. return .clear
  686. }
  687. return rowView
  688. }
  689. let rowView = KMTableRowView()
  690. rowView.selectionRadius = ComponentLibrary.shared.getComponentValueFromKey("radius/xs") as? CGFloat ?? 4
  691. rowView.selectionBackgroundColorBlock = {
  692. return KMNColorTools.colorPrimary_bgOpacityDark()
  693. }
  694. rowView.selectionInset = .init(top: 8, left: 16, bottom: 8, right: 16)
  695. return rowView
  696. }
  697. func tableViewSelectionDidChange(_ notification: Notification) {
  698. let row = self.tableView.selectedRow
  699. if row < 0 || row >= datas.count {
  700. return
  701. }
  702. guard let model = datas[row] as? KMSearchMode else {
  703. return
  704. }
  705. handdler.showSelection(model.selection)
  706. currentSel = model.selection
  707. currentModel_ = model
  708. var i = 0
  709. var sectionCount = 0
  710. for model in self.datas {
  711. if i > self.tableView.selectedRow {
  712. break
  713. }
  714. if let data = model as? KMBotaSearchSectionModel {
  715. sectionCount += 1
  716. }
  717. i += 1
  718. }
  719. let theIdx = max(i-sectionCount, 1)
  720. topContentView_?.resultLabel.stringValue = KMLocalizedString("Result:") + " \(theIdx)/" + "\(self.handdler.searchResults.count)"
  721. }
  722. func tableView(_ aTableView: NSTableView, copyRowsWithIndexes rowIndexes: IndexSet) {
  723. if IAPProductsManager.default().isAvailableAllFunction() == false {
  724. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  725. return
  726. }
  727. var string = ""
  728. for idx in rowIndexes {
  729. if idx < 0 || idx >= datas.count {
  730. continue
  731. }
  732. guard let model = datas[idx] as? KMSearchMode else {
  733. continue
  734. }
  735. let match = model.selection
  736. string.append("* ")
  737. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [match firstPageLabel]];
  738. string = string.appendingFormat(KMLocalizedString("Page %@"), "\(match.safeFirstPage()?.pageIndex() ?? 0)")
  739. // [string appendFormat:@"", [[match contextString] string]];
  740. string = string.appendingFormat(": %@\n", match.string() ?? "")
  741. }
  742. let pboard = NSPasteboard.general
  743. pboard.clearContents()
  744. pboard.writeObjects([string as NSPasteboardWriting])
  745. }
  746. }
  747. // MARK: - KMBotaTableViewDelegate
  748. extension KMBotaSearchViewController: KMBotaTableViewDelegate {
  749. func tableView(_ aTableView: NSTableView, canCopyRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  750. return rowIndexes.count > 0
  751. }
  752. func tableViewMoveRight(_ aTableView: NSTableView) {
  753. updateFindResultHighlightsForDirection(.selectingNext)
  754. }
  755. func tableViewMoveUp(_ aTableView: NSTableView) {
  756. var theRow = self.tableView.selectedRow-1
  757. if theRow < 0 || theRow >= self.datas.count {
  758. return
  759. }
  760. let model = self.datas[theRow]
  761. if let _ = model as? KMBotaSearchSectionModel {
  762. theRow -= 1
  763. }
  764. self.tableView.km_safe_selectRowIndexes(.init(integer: theRow), byExtendingSelection: false)
  765. self.tableView.scrollRowToVisible(self.tableView.selectedRow)
  766. }
  767. func tableViewMoveDown(_ aTableView: NSTableView) {
  768. var theRow = self.tableView.selectedRow+1
  769. if theRow < 0 || theRow >= self.datas.count {
  770. return
  771. }
  772. let model = self.datas[theRow]
  773. if let _ = model as? KMBotaSearchSectionModel {
  774. theRow += 1
  775. }
  776. self.tableView.km_safe_selectRowIndexes(.init(integer: theRow), byExtendingSelection: false)
  777. self.tableView.scrollRowToVisible(self.tableView.selectedRow)
  778. }
  779. func tableView(_ aTableView: NSTableView, imageContextForRow rowIndex: Int) -> AnyObject? {
  780. if rowIndex < 0 || rowIndex >= datas.count {
  781. return nil
  782. }
  783. guard let model = datas[rowIndex] as? KMSearchMode else {
  784. return -1 as AnyObject
  785. }
  786. let selection = model.selection
  787. let x = selection.bounds.origin.x + NSWidth(selection.bounds) * 0.5
  788. let y = selection.bounds.origin.y + NSHeight(selection.bounds) * 0.5
  789. let point = NSPoint(x: x, y: y)
  790. return CPDFDestination(document: handdler.pdfDocument(), pageIndex: Int(model.selectionPageIndex), at: point, zoom: handdler.scaleFactor() ?? 0)
  791. }
  792. }
  793. //MARK: - ComponentGroupDelegate
  794. extension KMBotaSearchViewController: ComponentGroupDelegate {
  795. func componentGroupDidDismiss(group: ComponentGroup?) {
  796. if group == menuGroupView_ {
  797. group?.removeFromSuperview()
  798. menuGroupView_ = nil
  799. } else if group == searchGroupView {
  800. searchGroupTarget?.properties.state = .normal
  801. searchGroupTarget?.reloadData()
  802. searchGroupTarget = nil
  803. }
  804. }
  805. func componentGroupDidSelect(group: ComponentGroup?, menuItemProperty: ComponentMenuitemProperty?) {
  806. if group == menuGroupView_ {
  807. if let selItem = menuItemProperty {
  808. let index = group?.menuItemArr.firstIndex(of: selItem)
  809. if index == 0 {
  810. menuType_ = .circle
  811. addAnnotationsForSelections(NSMenuItem())
  812. } else if index == 1 {
  813. menuType_ = .square
  814. addAnnotationsForSelections(NSMenuItem())
  815. } else if index == 2 {
  816. menuType_ = .highlight
  817. addAnnotationsForSelections(NSMenuItem())
  818. } else if index == 3 {
  819. menuType_ = .underline
  820. addAnnotationsForSelections(NSMenuItem())
  821. } else if index == 4 {
  822. menuType_ = .strikeOut
  823. addAnnotationsForSelections(NSMenuItem())
  824. }
  825. group?.removeFromSuperview()
  826. }
  827. } else if group == searchGroupView {
  828. guard let menuI = menuItemProperty else {
  829. return
  830. }
  831. let idx = group?.menuItemArr.firstIndex(of: menuI)
  832. if idx == 0 { // search
  833. showSearchView()
  834. } else if idx == 1 { // replace
  835. showReplaceView()
  836. } else if idx == 3 {
  837. let key = KMNSearchKey.wholeWords.botaSearch
  838. let value = KMDataManager.ud_bool(forKey: key)
  839. KMDataManager.ud_set(!value, forKey: key)
  840. currentSel = nil
  841. currentModel_ = nil
  842. if let data = topContentView_?.inputValue, data.isEmpty == false {
  843. search(keyword: data) { [weak self] results in }
  844. }
  845. } else if idx == 4 {
  846. let key = KMNSearchKey.caseSensitive.botaSearch
  847. let value = KMDataManager.ud_bool(forKey: key)
  848. KMDataManager.ud_set(!value, forKey: key)
  849. currentSel = nil
  850. currentModel_ = nil
  851. if let data = topContentView_?.inputValue, data.isEmpty == false {
  852. search(keyword: data) { [weak self] results in }
  853. }
  854. }
  855. }
  856. }
  857. }
  858. //MARK: Sarch搜索功能
  859. // 定义一个属性来保存搜索的延迟定时器
  860. private var searchTimer: Timer?
  861. // 设置一个时间间隔来进行debounce
  862. private let debounceInterval: TimeInterval = 0.3 // 0.3秒的延迟
  863. extension KMBotaSearchViewController {
  864. // func search(keyword: String, callback: @escaping (([KMBotaSearchSectionModel]?) -> Void)) {
  865. // //如果关键字为nil 则直接清空
  866. // if keyword.isEmpty {
  867. // self.updateResults(results: [])
  868. // return
  869. // }
  870. //
  871. // let isCase = KMDataManager.ud_bool(forKey: KMNSearchKey.caseSensitive.botaSearch)
  872. // let isWholeWord = KMDataManager.ud_bool(forKey: KMNSearchKey.wholeWords.botaSearch)
  873. //// handdler.search(keyword: keyword, isCase: isCase, isWholeWord: isWholeWord, callback: callback)
  874. //
  875. // let isEditing = self.handdler.pdfView?.isEditing() ?? false
  876. // if isEditing == false {
  877. // if self.finding_ {
  878. // return
  879. // }
  880. // self.finding_ = true
  881. // self.handdler.search(keyword: keyword, isCase: isCase, isWholeWord: isWholeWord, callback: { [weak self] datas in
  882. // self?.finding_ = false
  883. // self?.searchResults = datas
  884. // let sels = self?.handdler.searchResults
  885. // if let sel = sels?.first?.selection {
  886. // self?.handdler.showIdx = 1
  887. // self?.handdler.showSelection(sel)
  888. // }
  889. //
  890. //// self?.searchResults.first?.isExpand = true
  891. // for model in self?.searchResults ?? [] {
  892. // model.isExpand = true
  893. // }
  894. // self?.currentModel_ = datas.first?.items.first
  895. //
  896. // self?.tableView.reloadData()
  897. // self?.showResult()
  898. // })
  899. // } else {
  900. // if self.finding_ {
  901. // return
  902. // }
  903. // self.finding_ = true
  904. // let searchS = keyword
  905. // if searchS.isEmpty {
  906. // self.updateResults(results: [])
  907. // return
  908. // }
  909. // let opt = self.fetchSearchOptions()
  910. // DispatchQueue.global().async {
  911. // let datas = self.handdler.pdfView?.document.findEditAllPageString(searchS, with: opt) ?? []
  912. // DispatchQueue.main.async {
  913. // self.finding_ = false
  914. // self.currentSel = datas.first?.first
  915. // if let sel = self.currentSel {
  916. // self.handdler.showSelection(sel)
  917. // }
  918. //
  919. // self.updateResults(results: datas)
  920. // }
  921. // }
  922. // }
  923. // }
  924. func search(keyword: String, callback: @escaping (([Any]?) -> Void)) {
  925. // 如果已经存在定时器,则取消之前的搜索
  926. searchTimer?.invalidate()
  927. // 创建新的定时器,触发实际搜索操作
  928. searchTimer = Timer.scheduledTimer(withTimeInterval: debounceInterval, repeats: false) { [weak self] _ in
  929. // 关键字为空直接清空
  930. guard !keyword.isEmpty else {
  931. self?.updateResults(results: [])
  932. return
  933. }
  934. // 调用实际搜索函数
  935. let isCase = KMDataManager.ud_bool(forKey: KMNSearchKey.caseSensitive.botaSearch)
  936. let isWholeWord = KMDataManager.ud_bool(forKey: KMNSearchKey.wholeWords.botaSearch)
  937. let isEditing = self?.handdler.pdfView?.isEditing() ?? false
  938. // 如果不是编辑状态,执行普通搜索
  939. if !isEditing {
  940. self?.searchInNormalMode(keyword: keyword, isCase: isCase, isWholeWord: isWholeWord, callback: callback)
  941. } else {
  942. self?.searchInEditingMode(keyword: keyword, callback: callback)
  943. }
  944. }
  945. }
  946. private func searchInNormalMode(keyword: String, isCase: Bool, isWholeWord: Bool, callback: @escaping (([KMBotaSearchSectionModel]?) -> Void)) {
  947. guard !finding_ else { return } // 防止重复搜索
  948. finding_ = true
  949. handdler.search(keyword: keyword, isCase: isCase, isWholeWord: isWholeWord) { [weak self] datas in
  950. self?.finding_ = false
  951. self?.searchResults = datas
  952. // 显示第一个匹配项的选择框
  953. let sels = self?.handdler.searchResults
  954. if let firstSelection = sels?.first?.selection {
  955. self?.handdler.showIdx = 1
  956. self?.handdler.showSelection(firstSelection)
  957. }
  958. // 展开所有结果
  959. for model in datas {
  960. model.isExpand = true
  961. }
  962. // 更新当前模型并刷新表格
  963. self?.currentModel_ = datas.first?.items.first
  964. self?.tableView.reloadData()
  965. self?.showResult()
  966. // 调用回调
  967. callback(datas)
  968. }
  969. }
  970. private func searchInEditingMode(keyword: String, callback: @escaping (([[CPDFSelection]]?) -> Void)) {
  971. guard !finding_ else { return } // 防止重复搜索
  972. finding_ = true
  973. // 在编辑模式下,执行搜索操作
  974. let searchS = keyword
  975. let opt = self.fetchSearchOptions()
  976. DispatchQueue.global(qos: .userInitiated).async {
  977. let datas = self.handdler.pdfView?.document.findEditAllPageString(searchS, with: opt) ?? []
  978. // 在主线程更新UI
  979. DispatchQueue.main.async {
  980. self.finding_ = false
  981. self.currentSel = datas.first?.first
  982. if let sel = self.currentSel {
  983. self.handdler.showSelection(sel)
  984. }
  985. self.handdler.searchKey = keyword
  986. self.updateResults(results: datas)
  987. // 调用回调
  988. callback(datas)
  989. }
  990. }
  991. }
  992. }