KMBotaSearchViewController.swift 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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. cell?.label.isEnabled = false
  642. return cell
  643. }
  644. return nil
  645. }
  646. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
  647. let model = datas[row]
  648. if model is KMBotaSearchSectionModel {
  649. return 40.0
  650. }
  651. if let data = model as? KMSearchMode {
  652. let width = NSWidth(self.view.frame)
  653. let rect = data.attributedString.boundingRect(with: .init(width: width-24*2, height: CGFLOAT_MAX), options: [.usesLineFragmentOrigin, .usesLineFragmentOrigin])
  654. return rect.size.height + 12 * 2
  655. }
  656. return 40.0
  657. }
  658. func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
  659. let model = datas[row]
  660. if model is KMBotaSearchSectionModel {
  661. let rowView = KMTableRowView()
  662. rowView.selectionBackgroundColorBlock = {
  663. return .clear
  664. }
  665. return rowView
  666. }
  667. let rowView = KMTableRowView()
  668. rowView.selectionRadius = ComponentLibrary.shared.getComponentValueFromKey("radius/xs") as? CGFloat ?? 4
  669. rowView.selectionBackgroundColorBlock = {
  670. return KMNColorTools.colorPrimary_bgOpacityDark()
  671. }
  672. rowView.selectionInset = .init(top: 8, left: 16, bottom: 8, right: 16)
  673. return rowView
  674. }
  675. func tableViewSelectionDidChange(_ notification: Notification) {
  676. let row = self.tableView.selectedRow
  677. if row < 0 || row >= datas.count {
  678. return
  679. }
  680. guard let model = datas[row] as? KMSearchMode else {
  681. return
  682. }
  683. handdler.showSelection(model.selection)
  684. currentSel = model.selection
  685. currentModel_ = model
  686. var i = 0
  687. var sectionCount = 0
  688. for model in self.datas {
  689. if i > self.tableView.selectedRow {
  690. break
  691. }
  692. if let data = model as? KMBotaSearchSectionModel {
  693. sectionCount += 1
  694. }
  695. i += 1
  696. }
  697. let theIdx = max(i-sectionCount, 1)
  698. topContentView_?.resultLabel.stringValue = KMLocalizedString("Result:") + " \(theIdx)/" + "\(self.handdler.searchResults.count)"
  699. }
  700. func tableView(_ aTableView: NSTableView, copyRowsWithIndexes rowIndexes: IndexSet) {
  701. if IAPProductsManager.default().isAvailableAllFunction() == false {
  702. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  703. return
  704. }
  705. var string = ""
  706. for idx in rowIndexes {
  707. if idx < 0 || idx >= datas.count {
  708. continue
  709. }
  710. guard let model = datas[idx] as? KMSearchMode else {
  711. continue
  712. }
  713. let match = model.selection
  714. string.append("* ")
  715. // [string appendFormat:NSLocalizedString(@"Page %@", @""), [match firstPageLabel]];
  716. string = string.appendingFormat(KMLocalizedString("Page %@"), "\(match.safeFirstPage()?.pageIndex() ?? 0)")
  717. // [string appendFormat:@"", [[match contextString] string]];
  718. string = string.appendingFormat(": %@\n", match.string() ?? "")
  719. }
  720. let pboard = NSPasteboard.general
  721. pboard.clearContents()
  722. pboard.writeObjects([string as NSPasteboardWriting])
  723. }
  724. }
  725. // MARK: - KMBotaTableViewDelegate
  726. extension KMBotaSearchViewController: KMBotaTableViewDelegate {
  727. func tableView(_ aTableView: NSTableView, canCopyRowsWithIndexes rowIndexes: IndexSet) -> Bool {
  728. return rowIndexes.count > 0
  729. }
  730. func tableViewMoveRight(_ aTableView: NSTableView) {
  731. updateFindResultHighlightsForDirection(.selectingNext)
  732. }
  733. func tableViewMoveUp(_ aTableView: NSTableView) {
  734. var theRow = self.tableView.selectedRow-1
  735. if theRow < 0 || theRow >= self.datas.count {
  736. return
  737. }
  738. let model = self.datas[theRow]
  739. if let _ = model as? KMBotaSearchSectionModel {
  740. theRow -= 1
  741. }
  742. self.tableView.km_safe_selectRowIndexes(.init(integer: theRow), byExtendingSelection: false)
  743. self.tableView.scrollRowToVisible(self.tableView.selectedRow)
  744. }
  745. func tableViewMoveDown(_ aTableView: NSTableView) {
  746. var theRow = self.tableView.selectedRow+1
  747. if theRow < 0 || theRow >= self.datas.count {
  748. return
  749. }
  750. let model = self.datas[theRow]
  751. if let _ = model as? KMBotaSearchSectionModel {
  752. theRow += 1
  753. }
  754. self.tableView.km_safe_selectRowIndexes(.init(integer: theRow), byExtendingSelection: false)
  755. self.tableView.scrollRowToVisible(self.tableView.selectedRow)
  756. }
  757. func tableView(_ aTableView: NSTableView, imageContextForRow rowIndex: Int) -> AnyObject? {
  758. if rowIndex < 0 || rowIndex >= datas.count {
  759. return nil
  760. }
  761. guard let model = datas[rowIndex] as? KMSearchMode else {
  762. return -1 as AnyObject
  763. }
  764. let selection = model.selection
  765. let x = selection.bounds.origin.x + NSWidth(selection.bounds) * 0.5
  766. let y = selection.bounds.origin.y + NSHeight(selection.bounds) * 0.5
  767. let point = NSPoint(x: x, y: y)
  768. return CPDFDestination(document: handdler.pdfDocument(), pageIndex: Int(model.selectionPageIndex), at: point, zoom: handdler.scaleFactor() ?? 0)
  769. }
  770. }
  771. //MARK: - ComponentGroupDelegate
  772. extension KMBotaSearchViewController: ComponentGroupDelegate {
  773. func componentGroupDidDismiss(group: ComponentGroup?) {
  774. if group == menuGroupView_ {
  775. group?.removeFromSuperview()
  776. menuGroupView_ = nil
  777. } else if group == searchGroupView {
  778. searchGroupTarget?.properties.state = .normal
  779. searchGroupTarget?.reloadData()
  780. searchGroupTarget = nil
  781. }
  782. }
  783. func componentGroupDidSelect(group: ComponentGroup?, menuItemProperty: ComponentMenuitemProperty?) {
  784. if group == menuGroupView_ {
  785. if let selItem = menuItemProperty {
  786. let index = group?.menuItemArr.firstIndex(of: selItem)
  787. if index == 0 {
  788. menuType_ = .circle
  789. addAnnotationsForSelections(NSMenuItem())
  790. } else if index == 1 {
  791. menuType_ = .square
  792. addAnnotationsForSelections(NSMenuItem())
  793. } else if index == 2 {
  794. menuType_ = .highlight
  795. addAnnotationsForSelections(NSMenuItem())
  796. } else if index == 3 {
  797. menuType_ = .underline
  798. addAnnotationsForSelections(NSMenuItem())
  799. } else if index == 4 {
  800. menuType_ = .strikeOut
  801. addAnnotationsForSelections(NSMenuItem())
  802. }
  803. group?.removeFromSuperview()
  804. }
  805. } else if group == searchGroupView {
  806. guard let menuI = menuItemProperty else {
  807. return
  808. }
  809. let idx = group?.menuItemArr.firstIndex(of: menuI)
  810. if idx == 0 { // search
  811. showSearchView()
  812. } else if idx == 1 { // replace
  813. showReplaceView()
  814. } else if idx == 3 {
  815. let key = KMNSearchKey.wholeWords.botaSearch
  816. let value = KMDataManager.ud_bool(forKey: key)
  817. KMDataManager.ud_set(!value, forKey: key)
  818. currentSel = nil
  819. currentModel_ = nil
  820. if let data = topContentView_?.inputValue, data.isEmpty == false {
  821. search(keyword: data) { [weak self] results in }
  822. }
  823. } else if idx == 4 {
  824. let key = KMNSearchKey.caseSensitive.botaSearch
  825. let value = KMDataManager.ud_bool(forKey: key)
  826. KMDataManager.ud_set(!value, forKey: key)
  827. currentSel = nil
  828. currentModel_ = nil
  829. if let data = topContentView_?.inputValue, data.isEmpty == false {
  830. search(keyword: data) { [weak self] results in }
  831. }
  832. }
  833. }
  834. }
  835. }
  836. //MARK: Sarch搜索功能
  837. // 定义一个属性来保存搜索的延迟定时器
  838. private var searchTimer: Timer?
  839. // 设置一个时间间隔来进行debounce
  840. private let debounceInterval: TimeInterval = 0.3 // 0.3秒的延迟
  841. extension KMBotaSearchViewController {
  842. // func search(keyword: String, callback: @escaping (([KMBotaSearchSectionModel]?) -> Void)) {
  843. // //如果关键字为nil 则直接清空
  844. // if keyword.isEmpty {
  845. // self.updateResults(results: [])
  846. // return
  847. // }
  848. //
  849. // let isCase = KMDataManager.ud_bool(forKey: KMNSearchKey.caseSensitive.botaSearch)
  850. // let isWholeWord = KMDataManager.ud_bool(forKey: KMNSearchKey.wholeWords.botaSearch)
  851. //// handdler.search(keyword: keyword, isCase: isCase, isWholeWord: isWholeWord, callback: callback)
  852. //
  853. // let isEditing = self.handdler.pdfView?.isEditing() ?? false
  854. // if isEditing == false {
  855. // if self.finding_ {
  856. // return
  857. // }
  858. // self.finding_ = true
  859. // self.handdler.search(keyword: keyword, isCase: isCase, isWholeWord: isWholeWord, callback: { [weak self] datas in
  860. // self?.finding_ = false
  861. // self?.searchResults = datas
  862. // let sels = self?.handdler.searchResults
  863. // if let sel = sels?.first?.selection {
  864. // self?.handdler.showIdx = 1
  865. // self?.handdler.showSelection(sel)
  866. // }
  867. //
  868. //// self?.searchResults.first?.isExpand = true
  869. // for model in self?.searchResults ?? [] {
  870. // model.isExpand = true
  871. // }
  872. // self?.currentModel_ = datas.first?.items.first
  873. //
  874. // self?.tableView.reloadData()
  875. // self?.showResult()
  876. // })
  877. // } else {
  878. // if self.finding_ {
  879. // return
  880. // }
  881. // self.finding_ = true
  882. // let searchS = keyword
  883. // if searchS.isEmpty {
  884. // self.updateResults(results: [])
  885. // return
  886. // }
  887. // let opt = self.fetchSearchOptions()
  888. // DispatchQueue.global().async {
  889. // let datas = self.handdler.pdfView?.document.findEditAllPageString(searchS, with: opt) ?? []
  890. // DispatchQueue.main.async {
  891. // self.finding_ = false
  892. // self.currentSel = datas.first?.first
  893. // if let sel = self.currentSel {
  894. // self.handdler.showSelection(sel)
  895. // }
  896. //
  897. // self.updateResults(results: datas)
  898. // }
  899. // }
  900. // }
  901. // }
  902. func search(keyword: String, callback: @escaping (([Any]?) -> Void)) {
  903. // 如果已经存在定时器,则取消之前的搜索
  904. searchTimer?.invalidate()
  905. // 创建新的定时器,触发实际搜索操作
  906. searchTimer = Timer.scheduledTimer(withTimeInterval: debounceInterval, repeats: false) { [weak self] _ in
  907. // 关键字为空直接清空
  908. guard !keyword.isEmpty else {
  909. self?.updateResults(results: [])
  910. return
  911. }
  912. // 调用实际搜索函数
  913. let isCase = KMDataManager.ud_bool(forKey: KMNSearchKey.caseSensitive.botaSearch)
  914. let isWholeWord = KMDataManager.ud_bool(forKey: KMNSearchKey.wholeWords.botaSearch)
  915. let isEditing = self?.handdler.pdfView?.isEditing() ?? false
  916. // 如果不是编辑状态,执行普通搜索
  917. if !isEditing {
  918. self?.searchInNormalMode(keyword: keyword, isCase: isCase, isWholeWord: isWholeWord, callback: callback)
  919. } else {
  920. self?.searchInEditingMode(keyword: keyword, callback: callback)
  921. }
  922. }
  923. }
  924. private func searchInNormalMode(keyword: String, isCase: Bool, isWholeWord: Bool, callback: @escaping (([KMBotaSearchSectionModel]?) -> Void)) {
  925. guard !finding_ else { return } // 防止重复搜索
  926. finding_ = true
  927. handdler.search(keyword: keyword, isCase: isCase, isWholeWord: isWholeWord) { [weak self] datas in
  928. self?.finding_ = false
  929. self?.searchResults = datas
  930. // 显示第一个匹配项的选择框
  931. let sels = self?.handdler.searchResults
  932. if let firstSelection = sels?.first?.selection {
  933. self?.handdler.showIdx = 1
  934. self?.handdler.showSelection(firstSelection)
  935. }
  936. // 展开所有结果
  937. for model in datas {
  938. model.isExpand = true
  939. }
  940. // 更新当前模型并刷新表格
  941. self?.currentModel_ = datas.first?.items.first
  942. self?.tableView.reloadData()
  943. self?.showResult()
  944. // 调用回调
  945. callback(datas)
  946. }
  947. }
  948. private func searchInEditingMode(keyword: String, callback: @escaping (([[CPDFSelection]]?) -> Void)) {
  949. guard !finding_ else { return } // 防止重复搜索
  950. finding_ = true
  951. // 在编辑模式下,执行搜索操作
  952. let searchS = keyword
  953. let opt = self.fetchSearchOptions()
  954. DispatchQueue.global(qos: .userInitiated).async {
  955. let datas = self.handdler.pdfView?.document.findEditAllPageString(searchS, with: opt) ?? []
  956. // 在主线程更新UI
  957. DispatchQueue.main.async {
  958. self.finding_ = false
  959. self.currentSel = datas.first?.first
  960. if let sel = self.currentSel {
  961. self.handdler.showSelection(sel)
  962. }
  963. self.handdler.searchKey = keyword
  964. self.updateResults(results: datas)
  965. // 调用回调
  966. callback(datas)
  967. }
  968. }
  969. }
  970. }