KMBotaSearchViewController.swift 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  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. }
  258. func update(keyborad: String?, replaceKey: String?, results: [KMBotaSearchSectionModel]) {
  259. topContentView_?.inputValue = keyborad
  260. topContentView_?.replaceText = replaceKey
  261. handdler.searchKey = keyborad
  262. handdler.replaceKey = replaceKey
  263. if let data = keyborad, data.isEmpty == false {
  264. self.search(keyword: data) { models in}
  265. }
  266. updateButtonStatus()
  267. }
  268. private func fetchSearchOptions() -> CPDFSearchOptions {
  269. var opt = CPDFSearchOptions()
  270. let isCase = KMDataManager.ud_bool(forKey: KMNSearchKey.caseSensitive.botaSearch)
  271. let isWholeWord = KMDataManager.ud_bool(forKey: KMNSearchKey.wholeWords.botaSearch)
  272. if isCase {
  273. opt.insert(.caseSensitive)
  274. }
  275. if isWholeWord {
  276. opt.insert(.matchWholeWord)
  277. }
  278. return opt
  279. }
  280. func updateButtonStatus() {
  281. let value = topContentView_?.inputValue ?? ""
  282. if value.isEmpty {
  283. previousButton?.properties.isDisabled = true
  284. previousButton?.reloadData()
  285. nextButton?.properties.isDisabled = true
  286. nextButton?.reloadData()
  287. replaceButton?.properties.isDisabled = true
  288. replaceButton?.reloadData()
  289. replaceAllButton?.properties.isDisabled = true
  290. replaceAllButton?.reloadData()
  291. } else {
  292. previousButton?.properties.isDisabled = false
  293. previousButton?.reloadData()
  294. nextButton?.properties.isDisabled = false
  295. nextButton?.reloadData()
  296. replaceButton?.properties.isDisabled = false
  297. replaceButton?.reloadData()
  298. replaceAllButton?.properties.isDisabled = false
  299. replaceAllButton?.reloadData()
  300. }
  301. }
  302. private func _showNoResultsAlert() {
  303. _ = _showAlert(style: .critical, message: KMLocalizedString("No related content found, please change keyword."), info: "", buttons: [KMLocalizedString("OK", comment: "")])
  304. }
  305. private func _showAlert(style: NSAlert.Style, message: String, info: String, buttons: [String]) -> NSApplication.ModalResponse {
  306. let alert = NSAlert()
  307. alert.alertStyle = style
  308. alert.messageText = message
  309. alert.informativeText = info
  310. for button in buttons {
  311. alert.addButton(withTitle: button)
  312. }
  313. return alert.runModal()
  314. }
  315. private func updateResults(results: [[CPDFSelection]]?) {
  316. let theKeyword = handdler.searchKey?.decomposedStringWithCompatibilityMapping ?? ""
  317. var datas: [KMBotaSearchSectionModel] = []
  318. var models: [KMSearchMode] = []
  319. for sels in results ?? [] {
  320. let sectionM = KMBotaSearchSectionModel()
  321. sectionM.pageIndex = Int(sels.first?.page.pageIndex() ?? 0)
  322. for sel in sels {
  323. let mode : KMSearchMode = KMSearchMode()
  324. mode.selection = sel
  325. mode.attributedString = KMOCToolClass.getAttributedString(selection: sel, keyword: theKeyword)
  326. mode.selectionPageIndex = handdler.pdfDocument()?.index(for: sel.page) ?? 0
  327. sectionM.items.append(mode)
  328. sel.setColor(NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5))
  329. models.append(mode)
  330. }
  331. datas.append(sectionM)
  332. }
  333. handdler.searchResults = models
  334. handdler.searchSectionResults = datas
  335. self.searchResults = datas
  336. // self.searchResults.first?.isExpand = true
  337. for model in self.searchResults {
  338. model.isExpand = true
  339. }
  340. self.currentModel_ = datas.first?.items.first
  341. self.tableView.reloadData()
  342. self.showResult()
  343. }
  344. @objc private func _previousAction(_ sender: NSButton) {
  345. let isEditing = self.handdler.pdfView?.isEditing() ?? false
  346. if isEditing == false {
  347. let index = self.handdler.previous()
  348. let model = self.handdler.searchResults[index]
  349. self.handdler.showSelection(model.selection)
  350. } else {
  351. if let _ = self.currentSel {
  352. self.currentSel = self.handdler.pdfView?.document.findForwardEditText()
  353. if let sel = self.currentSel {
  354. self.handdler.showSelection(sel)
  355. } else {
  356. _showNoResultsAlert()
  357. return
  358. }
  359. } else {
  360. if self.finding_ {
  361. return
  362. }
  363. self.finding_ = true
  364. let searchS = self.topContentView_?.inputValue ?? ""
  365. let opt = self.fetchSearchOptions()
  366. // self._beginLoading()
  367. DispatchQueue.global().async {
  368. let datas = self.handdler.pdfView?.document.startFindEditText(from: nil, with: searchS, options: opt)
  369. DispatchQueue.main.async {
  370. // self._endLoading()
  371. self.finding_ = false
  372. let sel = datas?.first?.first
  373. self.currentSel = sel
  374. self.handdler.showSelection(sel)
  375. self.updateResults(results: datas)
  376. }
  377. }
  378. }
  379. }
  380. }
  381. @objc private func _nextAction(_ sender: NSButton) {
  382. let isEditing = self.handdler.pdfView?.isEditing() ?? false
  383. if isEditing == false {
  384. let index = self.handdler.next()
  385. let model = self.handdler.searchResults[index]
  386. self.handdler.showSelection(model.selection)
  387. } else {
  388. if let _ = self.currentSel {
  389. self.currentSel = self.handdler.pdfView?.document.findBackwordEditText()
  390. if let sel = self.currentSel {
  391. self.handdler.showSelection(sel)
  392. } else {
  393. _showNoResultsAlert()
  394. }
  395. } else {
  396. if self.finding_ {
  397. return
  398. }
  399. self.finding_ = true
  400. let searchS = self.topContentView_?.inputValue ?? ""
  401. let opt = self.fetchSearchOptions()
  402. // self._beginLoading()
  403. DispatchQueue.global().async {
  404. let datas = self.handdler.pdfView?.document.startFindEditText(from: nil, with: searchS, options: opt)
  405. DispatchQueue.main.async {
  406. // self._endLoading()
  407. self.finding_ = false
  408. let sel = datas?.first?.first
  409. self.currentSel = sel
  410. self.handdler.showSelection(sel)
  411. }
  412. }
  413. }
  414. }
  415. }
  416. @objc private func _replaceAction(_ sender: NSButton) {
  417. let isEditing = self.handdler.pdfView?.isEditing() ?? false
  418. if isEditing == false {
  419. NSSound.beep()
  420. return
  421. }
  422. if let sel = self.currentSel {
  423. let searchS = self.topContentView_?.inputValue ?? ""
  424. let replaceS = self.topContentView_?.replaceText ?? ""
  425. let success = self.handdler.replace(searchS: searchS, replaceS: replaceS, sel: sel) { [weak self] newSel in
  426. self?.handdler.showSelection(newSel)
  427. if let data = newSel {
  428. self?.currentModel_?.selection = data
  429. // self?.currentModel_?.attributedString = KMOCToolClass.getAttributedString(selection: data, keyword: replaceS)
  430. self?.tableView.reloadData()
  431. }
  432. }
  433. } else { // 先查找
  434. if self.finding_ {
  435. return
  436. }
  437. self.finding_ = true
  438. let searchS = self.topContentView_?.inputValue ?? ""
  439. let opt = self.fetchSearchOptions()
  440. DispatchQueue.global().async {
  441. let datas = self.handdler.pdfView?.document.startFindEditText(from: nil, with: searchS, options: opt)
  442. DispatchQueue.main.async {
  443. self.finding_ = false
  444. let sel = datas?.first?.first
  445. self.currentSel = sel
  446. self.handdler.showSelection(sel)
  447. self.updateResults(results: datas)
  448. }
  449. }
  450. }
  451. }
  452. @objc private func _replaceAllAction(_ sender: NSButton) {
  453. let isEditing = self.handdler.pdfView?.isEditing() ?? false
  454. if isEditing == false {
  455. NSSound.beep()
  456. return
  457. }
  458. let datas = self.handdler.pdfView?.document.findEditSelections() ?? []
  459. if datas.isEmpty {
  460. _showNoResultsAlert()
  461. return
  462. }
  463. if self.finding_ {
  464. return
  465. }
  466. self.finding_ = true
  467. let searchS = self.topContentView_?.inputValue ?? ""
  468. let replaceS = self.topContentView_?.replaceText ?? ""
  469. // self._beginLoading()
  470. DispatchQueue.global().async {
  471. self.handdler.pdfView?.document.replaceAllEditText(with: searchS, toReplace: replaceS)
  472. self.currentSel = nil
  473. DispatchQueue.main.async {
  474. // self._endLoading()
  475. self.finding_ = false
  476. self.handdler.pdfView?.setHighlightedSelection(nil, animated: false)
  477. self.handdler.pdfView?.setNeedsDisplayForVisiblePages()
  478. }
  479. }
  480. }
  481. // MARK: - Group View
  482. func showSearchGroupView(sender: ComponentButton) {
  483. var viewHeight: CGFloat = 8
  484. var menuItemArr: [ComponentMenuitemProperty] = []
  485. let titles = ["Search", "Find and Replace", "", "Whole Words", "Case Sensitive"]
  486. for i in titles {
  487. if i.isEmpty {
  488. let menuI = ComponentMenuitemProperty.divider()
  489. menuItemArr.append(menuI)
  490. viewHeight += 8
  491. } else {
  492. let menuI = ComponentMenuitemProperty(text: KMLocalizedString(i))
  493. menuItemArr.append(menuI)
  494. viewHeight += 36
  495. }
  496. }
  497. if handdler.type == .search {
  498. menuItemArr.first?.righticon = NSImage(named: "KMNImageNameMenuSelect")
  499. } else if handdler.type == .replace {
  500. let info = menuItemArr.safe_element(for: 1) as? ComponentMenuitemProperty
  501. info?.righticon = NSImage(named: "KMNImageNameMenuSelect")
  502. }
  503. if let info = menuItemArr.safe_element(for: 3) as? ComponentMenuitemProperty {
  504. if KMDataManager.ud_bool(forKey: KMNSearchKey.wholeWords.botaSearch) {
  505. info.righticon = NSImage(named: "KMNImageNameMenuSelect")
  506. }
  507. }
  508. if let info = menuItemArr.last {
  509. if KMDataManager.ud_bool(forKey: KMNSearchKey.caseSensitive.botaSearch) {
  510. info.righticon = NSImage(named: "KMNImageNameMenuSelect")
  511. }
  512. }
  513. let groupView = ComponentGroup.createFromNib(in: ComponentLibrary.shared.componentBundle())
  514. searchGroupView = groupView
  515. groupView?.groupDelegate = self
  516. groupView?.frame = CGRectMake(310, 0, 200, viewHeight)
  517. groupView?.updateGroupInfo(menuItemArr)
  518. var point = sender.convert(sender.frame.origin, to: nil)
  519. point.y -= viewHeight
  520. groupView?.showWithPoint(point, relativeTo: sender)
  521. searchGroupTarget = sender
  522. }
  523. @objc func goToSelectedFindResults(_ sender: AnyObject?) {
  524. // guard let olView = sender as? NSTableView, olView.clickedRow != -1 else {
  525. // NSSound.beep()
  526. // return
  527. // }
  528. // self.updateFindResultHighlightsForDirection(.directSelection)
  529. }
  530. @objc func addAnnotationsForSelections(_ sender: NSMenuItem) {
  531. let listView = handdler.pdfView as? CPDFListView
  532. for selection in menuSections_ {
  533. // if menuType_ == .circle {
  534. listView?.addAnnotation(with: menuType_, selection: selection, page: selection.page, bounds: selection.bounds)
  535. // }
  536. }
  537. }
  538. func updataLeftSideFindView() {
  539. if (self.searchResults.count > 0) {
  540. self.emptyBox.isHidden = true
  541. } else {
  542. self.emptyBox.isHidden = false
  543. }
  544. }
  545. func updateFindResultHighlightsForDirection(_ direction: NSWindow.SelectionDirection) {
  546. var findResults: [KMSearchMode] = handdler.searchResults
  547. if (findResults.count == 0) {
  548. handdler.showSelection(nil)
  549. } else {
  550. if direction == .directSelection {
  551. self.searchResultIndex_ = 0
  552. } else if (direction == .selectingNext) {
  553. self.searchResultIndex_ += 1
  554. if self.searchResultIndex_ >= findResults.count {
  555. self.searchResultIndex_ = 0
  556. }
  557. } else if (direction == .selectingPrevious) {
  558. self.searchResultIndex_ -= 1
  559. if self.searchResultIndex_ < 0 {
  560. self.searchResultIndex_ = findResults.count-1
  561. }
  562. }
  563. let currentSel = findResults[self.searchResultIndex_].selection
  564. if currentSel.hasCharacters() {
  565. let page = currentSel.safeFirstPage()
  566. var rect = NSZeroRect
  567. for model in findResults {
  568. if let data = page, model.selection.pages().contains(data) {
  569. rect = NSUnionRect(rect, model.selection.bounds(for: data))
  570. }
  571. }
  572. let FIND_RESULT_MARGIN = 50.0
  573. rect = NSIntersectionRect(NSInsetRect(rect, -FIND_RESULT_MARGIN, -FIND_RESULT_MARGIN), page?.bounds(for: .cropBox) ?? .zero)
  574. handdler.pdfView?.go(to: page)
  575. handdler.pdfView?.go(to: rect, on: page)
  576. }
  577. if currentSel.hasCharacters() {
  578. let bColor = NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5)
  579. let color = NSColor(red: 219/255.0, green: 220/255.0, blue: 3/255.0, alpha: 0.5)
  580. handdler.pdfView?.setHighlight(currentSel, forBorderColor: .clear, fill: color, animated: true)
  581. handdler.pdfView?.go(to: currentSel, animated: true)
  582. handdler.pdfView?.setCurrentSelection(currentSel, animate: true)
  583. }
  584. // let mode = self.listView?.toolMode ?? .none
  585. // if mode == .moveToolMode || mode == .magnifyToolMode || mode == .selectToolMode {
  586. // self.listView?.setCurrentSelection(nil, animate: false)
  587. // }
  588. }
  589. }
  590. }
  591. // MARK: - NSTableViewDelegate, NSTableViewDataSource
  592. extension KMBotaSearchViewController: NSTableViewDelegate, NSTableViewDataSource {
  593. func numberOfRows(in tableView: NSTableView) -> Int {
  594. var datas: [Any] = []
  595. for sectionM in self.handdler.searchSectionResults {
  596. if sectionM.items.count > 0 {
  597. datas.append(sectionM)
  598. if sectionM.isExpand == false {
  599. continue
  600. }
  601. for item in sectionM.items {
  602. datas.append(item)
  603. }
  604. }
  605. }
  606. self.datas = datas
  607. return datas.count
  608. }
  609. func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  610. let model = self.datas[row]
  611. if let data = model as? KMBotaSearchSectionModel {
  612. var cell = tableView.makeView(withIdentifier: KMSectionCellView.km_identifier, owner: nil) as? KMSectionCellView
  613. if cell == nil {
  614. cell = KMSectionCellView.createFromNib()
  615. }
  616. cell?.titleLabel.font = ComponentLibrary.shared.getFontFromKey("mac/body-s-medium")
  617. cell?.countLabel.font = ComponentLibrary.shared.getFontFromKey("mac/body-s-regular")
  618. cell?.titleLabel.textColor = KMNColorTools.colorText_1()
  619. cell?.countLabel.textColor = KMNColorTools.colorText_3()
  620. cell?.titleLabel.isEditable = false
  621. cell?.isExpand = data.isExpand
  622. let pageIndex = data.pageIndex
  623. cell?.titleLabel.stringValue = KMLocalizedString("Page") + " \(pageIndex + 1)"
  624. cell?.countLabel.stringValue = "\(data.itemCount)"
  625. cell?.bottomLine.wantsLayer = true
  626. cell?.bottomLine.layer?.backgroundColor = KMNColorTools.colorBorder_divider().cgColor
  627. cell?.itemClick = { [weak self] idx, _ in
  628. if idx == 1 { // 收取 & 展开
  629. data.isExpand = !data.isExpand
  630. self?.tableView.reloadData()
  631. }
  632. }
  633. return cell
  634. }
  635. if let data = model as? KMSearchMode {
  636. var cell = tableView.makeView(withIdentifier: KMNBotaSearchCellView.km_identifier, owner: self) as? KMNBotaSearchCellView
  637. if cell == nil {
  638. cell = KMNBotaSearchCellView()
  639. }
  640. cell?.label.attributedStringValue = data.attributedString
  641. return cell
  642. }
  643. return nil
  644. }
  645. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  646. let model = datas[row]
  647. if model is KMBotaSearchSectionModel {
  648. return 40.0
  649. }
  650. if let data = model as? KMSearchMode {
  651. let width = NSWidth(self.view.frame)
  652. let rect = data.attributedString.boundingRect(with: .init(width: width-24*2, height: CGFLOAT_MAX), options: [.usesLineFragmentOrigin, .usesLineFragmentOrigin])
  653. return rect.size.height + 12 * 2
  654. }
  655. return 40.0
  656. }
  657. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  658. let model = datas[row]
  659. if model is KMBotaSearchSectionModel {
  660. let rowView = KMTableRowView()
  661. rowView.selectionBackgroundColorBlock = {
  662. return .clear
  663. }
  664. return rowView
  665. }
  666. let rowView = KMTableRowView()
  667. rowView.selectionRadius = ComponentLibrary.shared.getComponentValueFromKey("radius/xs") as? CGFloat ?? 4
  668. rowView.selectionBackgroundColorBlock = {
  669. return KMNColorTools.colorPrimary_bgOpacityDark()
  670. }
  671. rowView.selectionInset = .init(top: 8, left: 16, bottom: 8, right: 16)
  672. return rowView
  673. }
  674. func tableViewSelectionDidChange(_ notification: Notification) {
  675. let row = self.tableView.selectedRow
  676. if row < 0 || row >= datas.count {
  677. return
  678. }
  679. guard let model = datas[row] as? KMSearchMode else {
  680. return
  681. }
  682. handdler.showSelection(model.selection)
  683. currentSel = model.selection
  684. currentModel_ = model
  685. var i = 0
  686. var sectionCount = 0
  687. for model in self.datas {
  688. if i > self.tableView.selectedRow {
  689. break
  690. }
  691. if let data = model as? KMBotaSearchSectionModel {
  692. sectionCount += 1
  693. }
  694. i += 1
  695. }
  696. let theIdx = max(i-sectionCount, 1)
  697. topContentView_?.resultLabel.stringValue = KMLocalizedString("Result:") + " \(theIdx)/" + "\(self.handdler.searchResults.count)"
  698. }
  699. func tableView(_ aTableView: NSTableView, copyRowsWithIndexes rowIndexes: IndexSet) {
  700. if IAPProductsManager.default().isAvailableAllFunction() == false {
  701. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  702. return
  703. }
  704. var string = ""
  705. for idx in rowIndexes {
  706. if idx < 0 || idx >= datas.count {
  707. continue
  708. }
  709. guard let model = datas[idx] as? KMSearchMode else {
  710. continue
  711. }
  712. let match = model.selection
  713. string.append("* ")
  714. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [match firstPageLabel]];
  715. string = string.appendingFormat(KMLocalizedString("Page %@"), "\(match.safeFirstPage()?.pageIndex() ?? 0)")
  716. // [string appendFormat:@"", [[match contextString] string]];
  717. string = string.appendingFormat(": %@\n", match.string() ?? "")
  718. }
  719. let pboard = NSPasteboard.general
  720. pboard.clearContents()
  721. pboard.writeObjects([string as NSPasteboardWriting])
  722. }
  723. }
  724. // MARK: - KMBotaTableViewDelegate
  725. extension KMBotaSearchViewController: KMBotaTableViewDelegate {
  726. func tableView(_ aTableView: NSTableView, canCopyRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  727. return rowIndexes.count > 0
  728. }
  729. func tableViewMoveRight(_ aTableView: NSTableView) {
  730. updateFindResultHighlightsForDirection(.selectingNext)
  731. }
  732. func tableViewMoveUp(_ aTableView: NSTableView) {
  733. var theRow = self.tableView.selectedRow-1
  734. if theRow < 0 || theRow >= self.datas.count {
  735. return
  736. }
  737. let model = self.datas[theRow]
  738. if let _ = model as? KMBotaSearchSectionModel {
  739. theRow -= 1
  740. }
  741. self.tableView.km_safe_selectRowIndexes(.init(integer: theRow), byExtendingSelection: false)
  742. self.tableView.scrollRowToVisible(self.tableView.selectedRow)
  743. }
  744. func tableViewMoveDown(_ aTableView: NSTableView) {
  745. var theRow = self.tableView.selectedRow+1
  746. if theRow < 0 || theRow >= self.datas.count {
  747. return
  748. }
  749. let model = self.datas[theRow]
  750. if let _ = model as? KMBotaSearchSectionModel {
  751. theRow += 1
  752. }
  753. self.tableView.km_safe_selectRowIndexes(.init(integer: theRow), byExtendingSelection: false)
  754. self.tableView.scrollRowToVisible(self.tableView.selectedRow)
  755. }
  756. func tableView(_ aTableView: NSTableView, imageContextForRow rowIndex: Int) -> AnyObject? {
  757. if rowIndex < 0 || rowIndex >= datas.count {
  758. return nil
  759. }
  760. guard let model = datas[rowIndex] as? KMSearchMode else {
  761. return -1 as AnyObject
  762. }
  763. let selection = model.selection
  764. let x = selection.bounds.origin.x + NSWidth(selection.bounds) * 0.5
  765. let y = selection.bounds.origin.y + NSHeight(selection.bounds) * 0.5
  766. let point = NSPoint(x: x, y: y)
  767. return CPDFDestination(document: handdler.pdfDocument(), pageIndex: Int(model.selectionPageIndex), at: point, zoom: handdler.scaleFactor() ?? 0)
  768. }
  769. }
  770. //MARK: - ComponentGroupDelegate
  771. extension KMBotaSearchViewController: ComponentGroupDelegate {
  772. func componentGroupDidDismiss(group: ComponentGroup?) {
  773. if group == menuGroupView_ {
  774. group?.removeFromSuperview()
  775. menuGroupView_ = nil
  776. } else if group == searchGroupView {
  777. searchGroupTarget?.properties.state = .normal
  778. searchGroupTarget?.reloadData()
  779. searchGroupTarget = nil
  780. }
  781. }
  782. func componentGroupDidSelect(group: ComponentGroup?, menuItemProperty: ComponentMenuitemProperty?) {
  783. if group == menuGroupView_ {
  784. if let selItem = menuItemProperty {
  785. let index = group?.menuItemArr.firstIndex(of: selItem)
  786. if index == 0 {
  787. menuType_ = .circle
  788. addAnnotationsForSelections(NSMenuItem())
  789. } else if index == 1 {
  790. menuType_ = .square
  791. addAnnotationsForSelections(NSMenuItem())
  792. } else if index == 2 {
  793. menuType_ = .highlight
  794. addAnnotationsForSelections(NSMenuItem())
  795. } else if index == 3 {
  796. menuType_ = .underline
  797. addAnnotationsForSelections(NSMenuItem())
  798. } else if index == 4 {
  799. menuType_ = .strikeOut
  800. addAnnotationsForSelections(NSMenuItem())
  801. }
  802. group?.removeFromSuperview()
  803. }
  804. } else if group == searchGroupView {
  805. guard let menuI = menuItemProperty else {
  806. return
  807. }
  808. let idx = group?.menuItemArr.firstIndex(of: menuI)
  809. if idx == 0 { // search
  810. showSearchView()
  811. } else if idx == 1 { // replace
  812. showReplaceView()
  813. } else if idx == 3 {
  814. let key = KMNSearchKey.wholeWords.botaSearch
  815. let value = KMDataManager.ud_bool(forKey: key)
  816. KMDataManager.ud_set(!value, forKey: key)
  817. currentSel = nil
  818. currentModel_ = nil
  819. if let data = topContentView_?.inputValue, data.isEmpty == false {
  820. search(keyword: data) { [weak self] results in }
  821. }
  822. } else if idx == 4 {
  823. let key = KMNSearchKey.caseSensitive.botaSearch
  824. let value = KMDataManager.ud_bool(forKey: key)
  825. KMDataManager.ud_set(!value, forKey: key)
  826. currentSel = nil
  827. currentModel_ = nil
  828. if let data = topContentView_?.inputValue, data.isEmpty == false {
  829. search(keyword: data) { [weak self] results in }
  830. }
  831. }
  832. }
  833. }
  834. }
  835. //MARK: Sarch搜索功能
  836. // 定义一个属性来保存搜索的延迟定时器
  837. private var searchTimer: Timer?
  838. // 设置一个时间间隔来进行debounce
  839. private let debounceInterval: TimeInterval = 0.3 // 0.3秒的延迟
  840. extension KMBotaSearchViewController {
  841. // func search(keyword: String, callback: @escaping (([KMBotaSearchSectionModel]?) -> Void)) {
  842. // //如果关键字为nil 则直接清空
  843. // if keyword.isEmpty {
  844. // self.updateResults(results: [])
  845. // return
  846. // }
  847. //
  848. // let isCase = KMDataManager.ud_bool(forKey: KMNSearchKey.caseSensitive.botaSearch)
  849. // let isWholeWord = KMDataManager.ud_bool(forKey: KMNSearchKey.wholeWords.botaSearch)
  850. //// handdler.search(keyword: keyword, isCase: isCase, isWholeWord: isWholeWord, callback: callback)
  851. //
  852. // let isEditing = self.handdler.pdfView?.isEditing() ?? false
  853. // if isEditing == false {
  854. // if self.finding_ {
  855. // return
  856. // }
  857. // self.finding_ = true
  858. // self.handdler.search(keyword: keyword, isCase: isCase, isWholeWord: isWholeWord, callback: { [weak self] datas in
  859. // self?.finding_ = false
  860. // self?.searchResults = datas
  861. // let sels = self?.handdler.searchResults
  862. // if let sel = sels?.first?.selection {
  863. // self?.handdler.showIdx = 1
  864. // self?.handdler.showSelection(sel)
  865. // }
  866. //
  867. //// self?.searchResults.first?.isExpand = true
  868. // for model in self?.searchResults ?? [] {
  869. // model.isExpand = true
  870. // }
  871. // self?.currentModel_ = datas.first?.items.first
  872. //
  873. // self?.tableView.reloadData()
  874. // self?.showResult()
  875. // })
  876. // } else {
  877. // if self.finding_ {
  878. // return
  879. // }
  880. // self.finding_ = true
  881. // let searchS = keyword
  882. // if searchS.isEmpty {
  883. // self.updateResults(results: [])
  884. // return
  885. // }
  886. // let opt = self.fetchSearchOptions()
  887. // DispatchQueue.global().async {
  888. // let datas = self.handdler.pdfView?.document.findEditAllPageString(searchS, with: opt) ?? []
  889. // DispatchQueue.main.async {
  890. // self.finding_ = false
  891. // self.currentSel = datas.first?.first
  892. // if let sel = self.currentSel {
  893. // self.handdler.showSelection(sel)
  894. // }
  895. //
  896. // self.updateResults(results: datas)
  897. // }
  898. // }
  899. // }
  900. // }
  901. func search(keyword: String, callback: @escaping (([Any]?) -> Void)) {
  902. // 如果已经存在定时器,则取消之前的搜索
  903. searchTimer?.invalidate()
  904. // 创建新的定时器,触发实际搜索操作
  905. searchTimer = Timer.scheduledTimer(withTimeInterval: debounceInterval, repeats: false) { [weak self] _ in
  906. // 关键字为空直接清空
  907. guard !keyword.isEmpty else {
  908. self?.updateResults(results: [])
  909. return
  910. }
  911. // 调用实际搜索函数
  912. let isCase = KMDataManager.ud_bool(forKey: KMNSearchKey.caseSensitive.botaSearch)
  913. let isWholeWord = KMDataManager.ud_bool(forKey: KMNSearchKey.wholeWords.botaSearch)
  914. let isEditing = self?.handdler.pdfView?.isEditing() ?? false
  915. // 如果不是编辑状态,执行普通搜索
  916. if !isEditing {
  917. self?.searchInNormalMode(keyword: keyword, isCase: isCase, isWholeWord: isWholeWord, callback: callback)
  918. } else {
  919. self?.searchInEditingMode(keyword: keyword, callback: callback)
  920. }
  921. }
  922. }
  923. private func searchInNormalMode(keyword: String, isCase: Bool, isWholeWord: Bool, callback: @escaping (([KMBotaSearchSectionModel]?) -> Void)) {
  924. guard !finding_ else { return } // 防止重复搜索
  925. finding_ = true
  926. handdler.search(keyword: keyword, isCase: isCase, isWholeWord: isWholeWord) { [weak self] datas in
  927. self?.finding_ = false
  928. self?.searchResults = datas
  929. // 显示第一个匹配项的选择框
  930. let sels = self?.handdler.searchResults
  931. if let firstSelection = sels?.first?.selection {
  932. self?.handdler.showIdx = 1
  933. self?.handdler.showSelection(firstSelection)
  934. }
  935. // 展开所有结果
  936. for model in datas {
  937. model.isExpand = true
  938. }
  939. // 更新当前模型并刷新表格
  940. self?.currentModel_ = datas.first?.items.first
  941. self?.tableView.reloadData()
  942. self?.showResult()
  943. // 调用回调
  944. callback(datas)
  945. }
  946. }
  947. private func searchInEditingMode(keyword: String, callback: @escaping (([[CPDFSelection]]?) -> Void)) {
  948. guard !finding_ else { return } // 防止重复搜索
  949. finding_ = true
  950. // 在编辑模式下,执行搜索操作
  951. let searchS = keyword
  952. let opt = self.fetchSearchOptions()
  953. DispatchQueue.global(qos: .userInitiated).async {
  954. let datas = self.handdler.pdfView?.document.findEditAllPageString(searchS, with: opt) ?? []
  955. // 在主线程更新UI
  956. DispatchQueue.main.async {
  957. self.finding_ = false
  958. self.currentSel = datas.first?.first
  959. if let sel = self.currentSel {
  960. self.handdler.showSelection(sel)
  961. }
  962. self.handdler.searchKey = keyword
  963. self.updateResults(results: datas)
  964. // 调用回调
  965. callback(datas)
  966. }
  967. }
  968. }
  969. }