KMBotaSearchViewController.swift 39 KB

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