KMBotaSearchViewController.swift 39 KB

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