KMBotaSearchViewController.swift 39 KB

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