123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908 |
- //
- // KMBotaSearchViewController.swift
- // PDF Reader Pro
- //
- // Created by tangchao on 2023/11/16.
- //
- import Cocoa
- import KMComponentLibrary
- extension KMNSearchKey.wholeWords {
- static let botaSearch = "BotaSearchWholeWordsKey"
- }
- extension KMNSearchKey.caseSensitive {
- static let botaSearch = "BotaSearchCaseSensitiveKey"
- }
- enum KMNBotaSearchType: Int {
- case none = 0
- case search = 1
- case replace = 2
- }
- @objc protocol KMBotaSearchViewControllerDelegate: NSObjectProtocol {
- @objc optional func switchSearchPopWindow(controller: KMBotaSearchViewController)
- @objc optional func searchTypeDidChange(controller: KMBotaSearchViewController)
- }
- class KMBotaSearchViewController: KMNBotaBaseViewController {
- @IBOutlet weak var topView: NSBox!
- @IBOutlet weak var topHeightConst: NSLayoutConstraint!
-
- var contentView: NSView? {
- didSet {
- if let view = self.contentView {
- self.box.contentView = view
- }
- }
- }
- @IBOutlet weak var emptyBox: NSBox!
-
- @IBOutlet weak var box: NSBox!
- @IBOutlet weak var emptySearchLabel: NSTextField!
- // @IBOutlet weak var searchLabel: NSTextField!
- // @IBOutlet weak var searchTips: NSTextField!
- // @IBOutlet weak var pageLabel: NSTextField!
-
- @IBOutlet var scrollView: NSScrollView!
- @IBOutlet weak var tableView: KMBotaTableView!
-
- private lazy var topContentView_: KMNBotaSearchTopView? = {
- let view = KMNBotaSearchTopView.createFromNib()
- return view
- }()
-
- private var emptyView_: ComponentEmpty = {
- let view = ComponentEmpty()
- view.properties = ComponentEmptyProperty(emptyType: .noSearch, state: .normal, text: KMLocalizedString("No Results"), subText: KMLocalizedString(""))
- return view
- }()
-
- var previousButton: ComponentButton? {
- get {
- return topContentView_?.previousButton
- }
- }
- var nextButton: ComponentButton? {
- get {
- return topContentView_?.nextButton
- }
- }
- var replaceAllButton: ComponentButton? {
- get {
- return topContentView_?.replaceAllButton
- }
- }
- var replaceButton: ComponentButton? {
- get {
- return topContentView_?.replaceButton
- }
- }
-
- private var menuGroupView_: ComponentGroup?
- private var menuSections_: [CPDFSelection] = []
- private var menuType_: CAnnotationType = .circle
-
- var handdler = KMNSearchHanddler() {
- didSet {
- self.reloadData()
- }
- }
- weak var delegate: KMBotaSearchViewControllerDelegate?
-
- var searchResults : [KMBotaSearchSectionModel] = [] {
- didSet {
- self.updataLeftSideFindView()
- }
- }
-
- private var datas: [Any] = []
- private var searchResultIndex_: Int = -1
-
- private var currentSel: CPDFSelection?
- private var currentModel_: KMSearchMode?
-
- override func loadView() {
- super.loadView()
-
- topView.borderWidth = 0
- topView.fillColor = .clear
- topView.contentView = topContentView_
- topContentView_?.itemClick = { [unowned self] idx, params in
- if idx == KMNBotaSearchTopItemKey.search.rawValue {
- if let data = params.first as? ComponentButton {
- showSearchGroupView(sender: data)
- }
- } else if idx == KMNBotaSearchTopItemKey.replace.rawValue {
- if handdler.type == .search {
- showReplaceView(needSearch: true)
- } else {
- showSearchView(needSearch: true)
- }
- } else if idx == KMNBotaSearchTopItemKey.switch.rawValue {
- delegate?.switchSearchPopWindow?(controller: self)
- } else if idx == KMNBotaSearchTopItemKey.previous.rawValue {
- tableViewMoveUp(tableView)
- _previousAction(NSButton())
- } else if idx == KMNBotaSearchTopItemKey.next.rawValue {
- tableViewMoveDown(tableView)
- _nextAction(NSButton())
- } else if idx == KMNBotaSearchTopItemKey.replaceText.rawValue {
- _replaceAction(NSButton())
- } else if idx == KMNBotaSearchTopItemKey.replaceAllText.rawValue {
- _replaceAllAction(NSButton())
- }
-
- self.updateButtonState()
- }
-
- showSearchView()
- topContentView_?.valueDidChange = { [unowned self] sender, info in
- guard let string = info?[.newKey] as? String else {
- return
- }
-
- updateButtonState()
- currentSel = nil
- currentModel_ = nil
- self.search(keyword: string)
- }
-
- topContentView_?.replaceValueDidChange = { [unowned self] sender, info in
- guard let string = info?[.newKey] as? String else {
- return
- }
- handdler.replaceKey = string
- }
-
- emptyBox.contentView?.addSubview(emptyView_)
- emptyView_.km_add_top_constraint(constant: 232)
- emptyView_.km_add_bottom_constraint()
- emptyView_.km_add_leading_constraint()
- emptyView_.km_add_trailing_constraint()
-
- self.emptySearchLabel.stringValue = KMLocalizedString("")
- self.emptySearchLabel.textColor = KMAppearance.Layout.h1Color()
-
- contentView = tableView.enclosingScrollView
- tableView.menuClickedAction = { [unowned self] point in
- let idxs = self.tableView.selectedRowIndexes.count
-
- let convertP = self.tableView.convert(point, from: nil)
- let row = self.tableView.row(at: convertP)
- if row == -1 {
- return NSMenu()
- }
-
- let hideNotes = handdler.hideNotes()
- let allowsNotes = handdler.allowsNotes()
- if hideNotes || allowsNotes == false {
- return NSMenu()
- }
-
- guard let model = self.datas[row] as? KMSearchMode else {
- return NSMenu()
- }
-
- var viewHeight: CGFloat = 0
- let items: [String] = ["Add New Circle", "Add New Rectangle", "Add New Highlight", "Add New Underline", "Add New Strikethrough"]
- var menuItemArr: [ComponentMenuitemProperty] = []
- for value in items {
- let properties_Menuitem: ComponentMenuitemProperty = ComponentMenuitemProperty(multipleSelect: false,
- itemSelected: false,
- isDisabled: false,
- keyEquivalent: nil,
- text: KMLocalizedString(value),
- identifier: value)
-
- menuItemArr.append(properties_Menuitem)
- viewHeight += 36
- }
-
- self.menuGroupView_ = ComponentGroup.createFromNib(in: ComponentLibrary.shared.componentBundle())
- self.menuGroupView_?.clickedAutoHide = true
- self.menuGroupView_?.groupDelegate = self
- self.menuGroupView_?.frame = CGRectMake(0, 0, 180, viewHeight)
- self.menuGroupView_?.updateGroupInfo(menuItemArr)
-
- self.menuSections_ = [model.selection]
-
- self.menuGroupView_?.showWithPoint(CGPoint(x: point.x, y: point.y - viewHeight), relativeTo: nil)
- return NSMenu()
- }
- }
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
- tableView.delegate = self
- tableView.dataSource = self
- tableView.botaDelegate = self
- tableView.hasImageToolTips = true
-
- updateButtonState()
- }
-
- override func viewDidAppear() {
- super.viewDidAppear()
-
- view.window?.makeFirstResponder(topContentView_?.searchInput)
- }
-
- override func updateUILanguage() {
- super.updateUILanguage()
-
- KMMainThreadExecute {
- self.topContentView_?.resultLabel.stringValue = KMLocalizedString("Result:") + " " + "\(self.handdler.searchResults.count)"
-
- self.tableView.reloadData()
- }
- }
-
- override func updateUIThemeColor() {
- super.updateUIThemeColor()
-
- KMMainThreadExecute {
- self.view.wantsLayer = true
- let color = KMNColorTools.colorBg_layoutMiddle()
- self.view.layer?.backgroundColor = color.cgColor
-
- self.tableView.backgroundColor = color
- self.topContentView_?.replaceInput.properties.leftIcon = NSImage(named: "KMImagenameBotaSearchInputPrefiex")
- self.topContentView_?.replaceInput.reloadData()
- self.topContentView_?.resultLabel.textColor = KMNColorTools.colorText_3()
- self.topContentView_?.bottomLine.layer?.backgroundColor = KMNColorTools.colorPrimary_border1().cgColor
-
- self.tableView.reloadData()
- }
- }
-
- func reloadData() {
- let handdler = self.handdler
- topContentView_?.inputValue = handdler.searchKey ?? ""
- topContentView_?.replaceText = handdler.replaceKey ?? ""
-
- self.searchResults = handdler.searchSectionResults
-
- var index = handdler.showIdx
- var row = 0
- var searchModel = KMSearchMode()
- if handdler.showIdx != 0 {
- searchModel = self.handdler.searchResults[handdler.showIdx]
- self.handdler.showSelection(searchModel.selection)
- } else {
- // 显示第一个匹配项的选择框
- let sels = self.handdler.searchResults
- if let firstSelection = sels.first?.selection {
- searchModel = sels.first!
- self.handdler.showSelection(firstSelection)
- } else {
- self.handdler.showSelection(CPDFSelection())
- }
- index = 0
- }
-
- // 展开所有结果
- for model in handdler.searchSectionResults {
- model.isExpand = true
- }
-
- // 更新当前模型并刷新表格
- self.currentModel_ = searchModel
- self.tableView.reloadData()
-
-
- if handdler.showIdx != 0 {
- // 查找匹配的 model
- if let result = datas.firstIndex(where: {
- // 尝试将元素转换为 MyModel 类型
- if let model = $0 as? KMSearchMode {
- return model == searchModel // 如果转换成功,进行比较
- }
- return false
- }) {
- print("Found at index: \(index)")
- row = result
- } else {
- print("Model not found")
- row = 1
- }
- } else {
- row = 1
- }
-
- self.tableView.km_safe_selectRowIndexes(.init(integer: row), byExtendingSelection: false)
- self.tableView.scrollRowToVisible(self.tableView.selectedRow)
-
- self.showResult()
- updateButtonState()
- }
-
- func showSearchView(needSearch: Bool = false) {
- handdler.type = .search
- topContentView_?.showSearch()
-
- topHeightConst.constant = topContentView_?.fetchContentHeight(type: handdler.type, hasResult: handdler.searchResults.isEmpty == false) ?? 0
-
- delegate?.searchTypeDidChange?(controller: self)
-
- if needSearch {
- if let keyword = topContentView_?.inputValue, keyword.isEmpty == false {
- DispatchQueue.main.async {
- self.search(keyword: keyword)
- }
- }
- }
- }
-
- func showReplaceView(needSearch: Bool = false) {
- if KMMemberInfo.shared.isLogin == false {
- KMLoginWindowsController.shared.showWindow(nil)
- return
- }
-
- handdler.type = .replace
- topContentView_?.showReplace()
-
- topHeightConst.constant = topContentView_?.fetchContentHeight(type: handdler.type, hasResult: handdler.searchResults.isEmpty == false) ?? 0
-
- delegate?.searchTypeDidChange?(controller: self)
-
-
- if needSearch {
- if let keyword = topContentView_?.inputValue, keyword.isEmpty == false {
- DispatchQueue.main.async {
- self.search(keyword: keyword)
- }
- }
- }
- }
-
- func showResult() {
- topContentView_?.showResult(type: handdler.type)
-
- var count = 0
- if self.datas.isEmpty {
- topContentView_?.resultLabel.stringValue = ""
- } else {
- count = self.handdler.searchResults.count
- var i = 0
- var sectionCount = 0
- for model in self.datas {
- if i > self.tableView.selectedRow {
- break
- }
- if let data = model as? KMBotaSearchSectionModel {
- sectionCount += 1
- }
- i += 1
- }
-
- let theIdx = max(i-sectionCount, 1)
-
- topContentView_?.resultLabel.stringValue = KMLocalizedString("Result:") + " \(theIdx)/" + "\(count)"
- self.handdler.showIdx = theIdx - 1
- }
- topHeightConst.constant = topContentView_?.fetchContentHeight(type: handdler.type, hasResult: searchResults.isEmpty == false) ?? 0
-
- self.updateButtonState()
- }
-
- private func fetchSearchOptions() -> CPDFSearchOptions {
- var opt = CPDFSearchOptions()
- let isCase = KMDataManager.ud_bool(forKey: KMNSearchKey.caseSensitive.botaSearch)
- let isWholeWord = KMDataManager.ud_bool(forKey: KMNSearchKey.wholeWords.botaSearch)
- if isCase {
- opt.insert(.caseSensitive)
- }
- if isWholeWord {
- opt.insert(.matchWholeWord)
- }
- return opt
- }
-
- func updateButtonState() {
- let value = topContentView_?.inputValue ?? ""
- if value.isEmpty || self.handdler.searchResults.isEmpty{
- previousButton?.properties.isDisabled = true
- previousButton?.reloadData()
- nextButton?.properties.isDisabled = true
- nextButton?.reloadData()
- replaceButton?.properties.isDisabled = true
- replaceButton?.reloadData()
- replaceAllButton?.properties.isDisabled = true
- replaceAllButton?.reloadData()
- } else {
- replaceButton?.properties.isDisabled = false
- replaceButton?.reloadData()
- replaceAllButton?.properties.isDisabled = false
- replaceAllButton?.reloadData()
-
- previousButton?.properties.isDisabled = (self.handdler.showIdx == 0) ? true : false
- previousButton?.reloadData()
- nextButton?.properties.isDisabled = ((self.handdler.showIdx == self.handdler.resultCount - 1) || self.handdler.resultCount == 0)
- nextButton?.reloadData()
- }
- }
-
- private func _showNoResultsAlert() {
- _ = _showAlert(style: .critical, message: KMLocalizedString("No related content found, please change keyword."), info: "", buttons: [KMLocalizedString("OK", comment: "")])
- }
-
- private func _showAlert(style: NSAlert.Style, message: String, info: String, buttons: [String]) -> NSApplication.ModalResponse {
- let alert = NSAlert()
- alert.alertStyle = style
- alert.messageText = message
- alert.informativeText = info
- for button in buttons {
- alert.addButton(withTitle: button)
- }
- return alert.runModal()
- }
-
- func updataLeftSideFindView() {
- if (self.searchResults.count > 0) {
- self.emptyBox.isHidden = true
- } else {
- self.emptyBox.isHidden = false
- }
- }
-
- func updateFindResultHighlightsForDirection(_ direction: NSWindow.SelectionDirection) {
- let findResults: [KMSearchMode] = handdler.searchResults
- if (findResults.count == 0) {
- handdler.showSelection(nil)
- } else {
- if direction == .directSelection {
- self.searchResultIndex_ = 0
- } else if (direction == .selectingNext) {
- self.searchResultIndex_ += 1
- if self.searchResultIndex_ >= findResults.count {
- self.searchResultIndex_ = 0
- }
- } else if (direction == .selectingPrevious) {
- self.searchResultIndex_ -= 1
- if self.searchResultIndex_ < 0 {
- self.searchResultIndex_ = findResults.count-1
- }
- }
- let currentSel = findResults[self.searchResultIndex_].selection
- if currentSel.hasCharacters() {
- let page = currentSel.safeFirstPage()
- var rect = NSZeroRect
- for model in findResults {
- if let data = page, model.selection.pages().contains(data) {
- rect = NSUnionRect(rect, model.selection.bounds(for: data))
- }
- }
- let FIND_RESULT_MARGIN = 50.0
- rect = NSIntersectionRect(NSInsetRect(rect, -FIND_RESULT_MARGIN, -FIND_RESULT_MARGIN), page?.bounds(for: .cropBox) ?? .zero)
- handdler.pdfView?.go(to: page)
- handdler.pdfView?.go(to: rect, on: page)
- }
-
- if currentSel.hasCharacters() {
- let bColor = NSColor(red: 236/255.0, green: 241/255.0, blue: 83/255.0, alpha: 0.5)
- let color = NSColor(red: 219/255.0, green: 220/255.0, blue: 3/255.0, alpha: 0.5)
- handdler.pdfView?.setHighlight(currentSel, forBorderColor: .clear, fill: color, animated: true)
- handdler.pdfView?.go(to: currentSel, animated: true)
- handdler.pdfView?.setCurrentSelection(currentSel, animate: true)
- }
- }
- }
- }
- //MARK: Action
- extension KMBotaSearchViewController {
- @objc private func _previousAction(_ sender: NSButton) {
- let index = self.handdler.previous()
- if index < self.handdler.searchResults.count && index >= 0{
- // let model = self.handdler.searchResults[index]
- // self.handdler.showSelection(model.selection)
- self.updateButtonState()
- }
- }
-
- @objc private func _nextAction(_ sender: NSButton) {
- let index = self.handdler.next()
- if index < self.handdler.searchResults.count && index >= 0 {
- // let model = self.handdler.searchResults[index]
- // self.handdler.showSelection(model.selection)
- self.updateButtonState()
- }
- }
-
- @objc private func _replaceAction(_ sender: NSButton) {
- let isEditing = self.handdler.pdfView?.isEditing() ?? false
- if isEditing == false {
- NSSound.beep()
- return
- }
- if let sel = self.currentSel {
- let searchS = self.topContentView_?.inputValue ?? ""
- let replaceS = self.topContentView_?.replaceText ?? ""
- self.handdler.replace(searchS: searchS, replaceS: replaceS, sel: sel) { [weak self] newSel in
- self?.handdler.showSelection(newSel)
- if let data = newSel {
- self?.currentModel_?.selection = data
- self?.tableView.reloadData()
- }
- }
- }
- }
-
- @objc private func _replaceAllAction(_ sender: NSButton) {
- let isEditing = self.handdler.pdfView?.isEditing() ?? false
- if isEditing == false {
- NSSound.beep()
- return
- }
-
- let datas = self.handdler.searchSectionResults
- if datas.isEmpty {
- _showNoResultsAlert()
- return
- }
-
- let searchS = self.topContentView_?.inputValue ?? ""
- let replaceS = self.topContentView_?.replaceText ?? ""
- self.beginLoading()
- DispatchQueue.global().async {
- self.handdler.pdfView?.document.replaceAllEditText(with: searchS, toReplace: replaceS)
- self.currentSel = nil
-
- DispatchQueue.main.async {
- self.endLoading()
- self.handdler.pdfView?.setHighlightedSelection(nil, animated: false)
- self.handdler.pdfView?.setNeedsDisplayForVisiblePages()
- }
- }
- }
- }
- // MARK: - NSTableViewDelegate, NSTableViewDataSource
- extension KMBotaSearchViewController: NSTableViewDelegate, NSTableViewDataSource {
- func numberOfRows(in tableView: NSTableView) -> Int {
- var datas: [Any] = []
- for sectionM in self.handdler.searchSectionResults {
- if sectionM.items.count > 0 {
- datas.append(sectionM)
- if sectionM.isExpand == false {
- continue
- }
- for item in sectionM.items {
- datas.append(item)
- }
- }
- }
- self.datas = datas
- return datas.count
- }
-
- func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
- let model = self.datas[row]
- if let data = model as? KMBotaSearchSectionModel {
- var cell = tableView.makeView(withIdentifier: KMSectionCellView.km_identifier, owner: nil) as? KMSectionCellView
- if cell == nil {
- cell = KMSectionCellView.createFromNib()
- }
-
- cell?.titleLabel.font = ComponentLibrary.shared.getFontFromKey("mac/body-s-medium")
- cell?.countLabel.font = ComponentLibrary.shared.getFontFromKey("mac/body-s-regular")
- cell?.titleLabel.textColor = KMNColorTools.colorText_1()
- cell?.countLabel.textColor = KMNColorTools.colorText_3()
- cell?.titleLabel.isEditable = false
-
- cell?.isExpand = data.isExpand
- let pageIndex = data.pageIndex
- cell?.titleLabel.stringValue = KMLocalizedString("Page") + " \(pageIndex + 1)"
- cell?.countLabel.stringValue = "\(data.itemCount)"
-
- cell?.bottomLine.wantsLayer = true
- cell?.bottomLine.layer?.backgroundColor = KMNColorTools.colorBorder_divider().cgColor
-
-
- cell?.itemClick = { [weak self] idx, _ in
- if idx == 1 { // 收取 & 展开
- data.isExpand = !data.isExpand
-
- self?.tableView.reloadData()
- }
- }
- return cell
- }
-
- if let data = model as? KMSearchMode {
- var cell = tableView.makeView(withIdentifier: KMNBotaSearchCellView.km_identifier, owner: self) as? KMNBotaSearchCellView
- if cell == nil {
- cell = KMNBotaSearchCellView()
- }
-
- cell?.label.attributedStringValue = data.attributedString
- cell?.label.isEnabled = false
- return cell
- }
- return nil
- }
-
- func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
- let model = datas[row]
- if model is KMBotaSearchSectionModel {
- return 40.0
- }
- if let data = model as? KMSearchMode {
- let width = NSWidth(self.view.frame)
- let rect = data.attributedString.boundingRect(with: .init(width: width-24*2, height: CGFLOAT_MAX), options: [.usesLineFragmentOrigin, .usesLineFragmentOrigin])
- return rect.size.height + 12 * 2
- }
- return 40.0
- }
-
- func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
- let model = datas[row]
- if model is KMBotaSearchSectionModel {
- let rowView = KMTableRowView()
- rowView.selectionBackgroundColorBlock = {
- return .clear
- }
- return rowView
- }
- let rowView = KMTableRowView()
- rowView.selectionRadius = ComponentLibrary.shared.getComponentValueFromKey("radius/xs") as? CGFloat ?? 4
- rowView.selectionBackgroundColorBlock = {
- return KMNColorTools.colorPrimary_bgOpacityDark()
- }
- rowView.selectionInset = .init(top: 8, left: 16, bottom: 8, right: 16)
- return rowView
- }
-
- func tableViewSelectionDidChange(_ notification: Notification) {
- let row = self.tableView.selectedRow
- if row < 0 || row >= datas.count {
- return
- }
- guard let model = datas[row] as? KMSearchMode else {
- return
- }
-
- handdler.showSelection(model.selection)
- currentSel = model.selection
- currentModel_ = model
-
- self.showResult()
- }
-
- func tableView(_ aTableView: NSTableView, copyRowsWithIndexes rowIndexes: IndexSet) {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- return
- }
-
- var string = ""
- for idx in rowIndexes {
- if idx < 0 || idx >= datas.count {
- continue
- }
- guard let model = datas[idx] as? KMSearchMode else {
- continue
- }
-
- let match = model.selection
- string.append("* ")
- string = string.appendingFormat(KMLocalizedString("Page %@"), "\(match.safeFirstPage()?.pageIndex() ?? 0)")
- string = string.appendingFormat(": %@\n", match.string() ?? "")
- }
- let pboard = NSPasteboard.general
- pboard.clearContents()
- pboard.writeObjects([string as NSPasteboardWriting])
- }
- }
- // MARK: - KMBotaTableViewDelegate
- extension KMBotaSearchViewController: KMBotaTableViewDelegate {
- func tableView(_ aTableView: NSTableView, canCopyRowsWithIndexes rowIndexes: IndexSet) -> Bool {
- return rowIndexes.count > 0
- }
-
- func tableViewMoveRight(_ aTableView: NSTableView) {
- updateFindResultHighlightsForDirection(.selectingNext)
- }
-
- func tableViewMoveUp(_ aTableView: NSTableView) {
- var theRow = self.tableView.selectedRow-1
- if theRow < 0 || theRow >= self.datas.count {
- return
- }
- let model = self.datas[theRow]
- if let _ = model as? KMBotaSearchSectionModel {
- theRow -= 1
- }
- self.tableView.km_safe_selectRowIndexes(.init(integer: theRow), byExtendingSelection: false)
- self.tableView.scrollRowToVisible(self.tableView.selectedRow)
- }
-
- func tableViewMoveDown(_ aTableView: NSTableView) {
- var theRow = self.tableView.selectedRow + 1
- if theRow < 0 || theRow >= self.datas.count {
- return
- }
- let model = self.datas[theRow]
- if let _ = model as? KMBotaSearchSectionModel {
- theRow += 1
- }
- self.tableView.km_safe_selectRowIndexes(.init(integer: theRow), byExtendingSelection: false)
- self.tableView.scrollRowToVisible(self.tableView.selectedRow)
- }
-
- func tableView(_ aTableView: NSTableView, imageContextForRow rowIndex: Int) -> AnyObject? {
- if rowIndex < 0 || rowIndex >= datas.count {
- return nil
- }
- guard let model = datas[rowIndex] as? KMSearchMode else {
- return -1 as AnyObject
- }
-
- let selection = model.selection
- let x = selection.bounds.origin.x + NSWidth(selection.bounds) * 0.5
- let y = selection.bounds.origin.y + NSHeight(selection.bounds) * 0.5
- let point = NSPoint(x: x, y: y)
- return CPDFDestination(document: handdler.pdfDocument(), pageIndex: Int(model.selectionPageIndex), at: point, zoom: handdler.scaleFactor() ?? 0)
- }
-
- }
- //MARK: - ComponentGroupDelegate
- extension KMBotaSearchViewController: ComponentGroupDelegate {
- func showSearchGroupView(sender: ComponentButton) {
- var viewHeight: CGFloat = 8
- var menuItemArr: [ComponentMenuitemProperty] = []
- let titles = ["Search", "Find and Replace", "", "Whole Words", "Case Sensitive"]
- for i in titles {
- if i.isEmpty {
- let menuI = ComponentMenuitemProperty.divider()
- menuItemArr.append(menuI)
- viewHeight += 8
- } else {
- let menuI = ComponentMenuitemProperty(text: KMLocalizedString(i))
- menuItemArr.append(menuI)
- viewHeight += 36
- }
- }
-
- if handdler.type == .search {
- menuItemArr.first?.righticon = NSImage(named: "KMNImageNameMenuSelect")
- } else if handdler.type == .replace {
- let info = menuItemArr.safe_element(for: 1) as? ComponentMenuitemProperty
- info?.righticon = NSImage(named: "KMNImageNameMenuSelect")
- }
- if let info = menuItemArr.safe_element(for: 3) as? ComponentMenuitemProperty {
- if KMDataManager.ud_bool(forKey: KMNSearchKey.wholeWords.botaSearch) {
- info.righticon = NSImage(named: "KMNImageNameMenuSelect")
- }
- }
- if let info = menuItemArr.last {
- if KMDataManager.ud_bool(forKey: KMNSearchKey.caseSensitive.botaSearch) {
- info.righticon = NSImage(named: "KMNImageNameMenuSelect")
- }
- }
-
- let groupView = ComponentGroup.createFromNib(in: ComponentLibrary.shared.componentBundle())
- searchGroupView = groupView
- groupView?.groupDelegate = self
- groupView?.frame = CGRectMake(310, 0, 200, viewHeight)
- groupView?.updateGroupInfo(menuItemArr)
-
- var point = sender.convert(sender.frame.origin, to: nil)
- point.y -= viewHeight
- groupView?.showWithPoint(point, relativeTo: sender)
- searchGroupTarget = sender
- }
-
- func componentGroupDidDismiss(group: ComponentGroup?) {
- if group == menuGroupView_ {
- // group?.removeFromSuperview()
- // menuGroupView_ = nil
- } else if group == searchGroupView {
- searchGroupTarget?.properties.state = .normal
- searchGroupTarget?.reloadData()
- searchGroupTarget = nil
- }
- }
-
- func componentGroupDidSelect(group: ComponentGroup?, menuItemProperty: ComponentMenuitemProperty?) {
- if group == menuGroupView_ {
- if let selItem = menuItemProperty {
- let index = group?.menuItemArr.firstIndex(of: selItem)
- if index == 0 {
- menuType_ = .circle
- addAnnotationsForSelections(NSMenuItem())
- } else if index == 1 {
- menuType_ = .square
- addAnnotationsForSelections(NSMenuItem())
- } else if index == 2 {
- menuType_ = .highlight
- addAnnotationsForSelections(NSMenuItem())
- } else if index == 3 {
- menuType_ = .underline
- addAnnotationsForSelections(NSMenuItem())
- } else if index == 4 {
- menuType_ = .strikeOut
- addAnnotationsForSelections(NSMenuItem())
- }
- }
- } else if group == searchGroupView {
- guard let menuI = menuItemProperty else {
- return
- }
- let idx = group?.menuItemArr.firstIndex(of: menuI)
- if idx == 0 { // search
- showSearchView()
- } else if idx == 1 { // replace
- showReplaceView()
- } else if idx == 3 {
- let key = KMNSearchKey.wholeWords.botaSearch
- let value = KMDataManager.ud_bool(forKey: key)
- KMDataManager.ud_set(!value, forKey: key)
-
- currentSel = nil
- currentModel_ = nil
- if let data = topContentView_?.inputValue, data.isEmpty == false {
- search(keyword: data)
- }
- } else if idx == 4 {
- let key = KMNSearchKey.caseSensitive.botaSearch
- let value = KMDataManager.ud_bool(forKey: key)
- KMDataManager.ud_set(!value, forKey: key)
-
- currentSel = nil
- currentModel_ = nil
- if let data = topContentView_?.inputValue, data.isEmpty == false {
- search(keyword: data)
- }
- }
- }
- }
-
- @objc func addAnnotationsForSelections(_ sender: NSMenuItem) {
- let listView = handdler.pdfView as? CPDFListView
- for selection in menuSections_ {
- // if menuType_ == .circle {
- listView?.addAnnotation(with: menuType_, selection: selection, page: selection.page, bounds: selection.bounds)
- // }
- }
- }
- }
- //MARK: Search
- extension KMBotaSearchViewController {
- func search(keyword: String) {
- // 调用实际搜索函数
- let isCase = KMDataManager.ud_bool(forKey: KMNSearchKey.caseSensitive.botaSearch)
- let isWholeWord = KMDataManager.ud_bool(forKey: KMNSearchKey.wholeWords.botaSearch)
- let isEditing = self.handdler.pdfView?.isEditing() ?? false
-
- handdler.search(keyword: keyword, isCase: isCase, isWholeWord: isWholeWord, isEdit: isEditing) { [weak self] datas in
- self?.reloadData()
- }
- }
- }
- //MARK: Load
- extension KMBotaSearchViewController {
- private func beginLoading() {
- self.view.beginLoading()
- }
-
- private func endLoading() {
- self.view.endLoading()
- }
- }
|