KMLeftSideViewController+Note.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. //
  2. // KMLeftSideViewController+Note.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/12/23.
  6. //
  7. import Foundation
  8. extension KMLeftSideViewController.Key {
  9. static let noteAscendSortKey = "KMLeftSideViewAscendSortBoolKey"
  10. static let noteSortTypeKey = "KMLeftSideViewNoteSortTypeKey"
  11. static let noteTableColumn = "KMNoteOutlineViewTableColumnKey"
  12. static let noteFilterPage = "kKMNoteFilterAnnotationPageKey"
  13. static let noteFilterTime = "kKMNoteFilterAnnotationTimeKey"
  14. static let noteFilterAuther = "kKMNoteFilterAnnotationAutherKey"
  15. }
  16. // MARK: - Action
  17. extension KMLeftSideViewController {
  18. func note_initSubViews() {
  19. self.noteSearchField.backgroundColor = KMAppearance.Layout.l_1Color()
  20. self.noteSearchField.wantsLayer = true
  21. self.noteSearchField.layer?.backgroundColor = KMAppearance.Layout.l_1Color().cgColor
  22. self.noteSearchField.layer?.borderWidth = 1.0
  23. self.noteMoreButton.target = self
  24. self.noteMoreButton.tag = 304
  25. self.noteMoreButton.action = #selector(leftSideViewMoreButtonAction)
  26. self.moreButtonLayer = KMButtonLayer()
  27. self.noteMoreButton.layer?.addSublayer(self.moreButtonLayer!)
  28. self.moreButtonLayer?.frame = CGRectMake(0, 0, CGRectGetWidth(self.noteMoreButton.bounds), CGRectGetHeight(self.noteMoreButton.bounds))
  29. self.noteFilterButton.target = self
  30. self.noteFilterButton.action = #selector(noteFilterAction)
  31. self.filterButtonLayer = NSView()
  32. self.noteFilterButton.addSubview(self.filterButtonLayer!)
  33. self.filterButtonLayer?.frame = CGRectMake(14, 2, 8, 8)
  34. self.noteDoneButton.action = #selector(leftSideViewDoneButtonAction)
  35. self.noteDoneButton.target = self
  36. self.noteDoneButton.tag = 311
  37. self.noteDoneButton.isHidden = true
  38. self.noteSearchField.delegate = self
  39. self.noteSearchField.isHidden = true
  40. self.noteSearchField.endEditCallBack = { [unowned self] isEndEdit in
  41. // if (isEndEdit) {
  42. // self.noteSearchField.isHidden = true
  43. // self.noteSearchButton.isHidden = false
  44. // self.noteTitleLabel.isHidden = false
  45. // }
  46. }
  47. self.sortTypeBox.downCallback = { [unowned self] downEntered, mouseBox, _ in
  48. if (downEntered) {
  49. let menu = NSMenu()
  50. let timeItem = menu.addItem(title: KMLocalizedString("Time", nil), action: #selector(sortTypeAction), target: self)
  51. timeItem?.representedObject = self
  52. timeItem?.tag = 0
  53. let pageItem = menu.addItem(title: KMLocalizedString("Page", nil), action: #selector(sortTypeAction), target: self)
  54. pageItem?.representedObject = self
  55. timeItem?.tag = 1
  56. if (self.noteSortType == .time) {
  57. timeItem?.state = .on
  58. pageItem?.state = .off
  59. } else if (self.noteSortType == .page) {
  60. timeItem?.state = .off
  61. pageItem?.state = .on
  62. }
  63. menu.popUp(positioning: nil, at: CGPointMake(-10, 0), in: self.sortTypeBox)
  64. }
  65. }
  66. self.noteOutlineView.delegate = self
  67. self.noteOutlineView.dataSource = self
  68. self.noteOutlineView.botaDelegate = self
  69. self.noteOutlineView.botaDataSource = self
  70. self.noteOutlineView.noteDelegate = self
  71. self.noteOutlineView.menu = NSMenu()
  72. self.noteOutlineView.menu?.delegate = self
  73. self.noteOutlineView.typeSelectHelper = SKTypeSelectHelper(matchOption: .SKSubstringMatch)
  74. self.noteOutlineView.registerForDraggedTypes(NSColor.readableTypes(for: NSPasteboard(name: .drag)))
  75. self.noteOutlineView.target = self
  76. self.noteOutlineView.doubleAction = #selector(selectSelectedNote)
  77. }
  78. func note_initDefalutValue() {
  79. self.noteView.wantsLayer = true
  80. self.noteView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  81. let sud = UserDefaults.standard
  82. if let dict = sud.dictionary(forKey: Self.Key.noteTableColumn) {
  83. self.noteTypeDict = dict
  84. } else {
  85. self.noteTypeDict = [Self.Key.noteFilterPage : false,
  86. Self.Key.noteFilterTime : false,
  87. Self.Key.noteFilterAuther : false]
  88. sud.sync_setValue(self.noteTypeDict, forKey: Self.Key.noteTableColumn)
  89. }
  90. self.caseInsensitiveNoteSearch = sud.bool(forKey: SKCaseInsensitiveNoteSearchKey)
  91. self.isAscendSort = KMDataManager.ud_bool(forKey: Self.Key.noteAscendSortKey)
  92. self.noteTitleLabel.stringValue = KMLocalizedString("Notes", nil);
  93. self.noteTitleLabel.textColor = KMAppearance.Layout.h0Color()
  94. self.noteSearchField.layer?.borderColor = KMAppearance.Interactive.a0Color().cgColor
  95. self.noteMoreButton.wantsLayer = true
  96. self.moreButtonLayer?.layerType = .none
  97. self.moreButtonLayer?.isHidden = true
  98. self.noteFilterButton.toolTip = KMLocalizedString("Sort", nil)
  99. self.noteFilterButton.wantsLayer = true
  100. self.filterButtonLayer?.isHidden = true
  101. self.filterButtonLayer?.wantsLayer = true
  102. self.filterButtonLayer?.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  103. self.filterButtonLayer?.layer?.cornerRadius = 4.0
  104. if (self.isAscendSort) {
  105. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankReverse)
  106. self.noteSortButton.toolTip = KMLocalizedString("ascending sort", nil)
  107. } else {
  108. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankPositive)
  109. self.noteSortButton.toolTip = KMLocalizedString("descending sort", nil)
  110. }
  111. self.noteSearchButton.toolTip = KMLocalizedString("Search", nil)
  112. self.noteDoneButton.title = KMLocalizedString("Done", nil)
  113. self.noteDoneButton.toolTip = KMLocalizedString("Done", nil)
  114. self.noteDoneButton.setTitleColor(KMAppearance.Layout.w0Color())
  115. self.noteDoneButton.wantsLayer = true
  116. self.noteDoneButton.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  117. self.noteDoneButton.layer?.cornerRadius = 4.0
  118. self.noteHeaderView.wantsLayer = true
  119. self.noteHeaderView.layer?.backgroundColor = KMAppearance.Else.textTagColor().cgColor
  120. self.noteHeaderView.layer?.cornerRadius = 1.0
  121. let sortType = KMDataManager.ud_integer(forKey: Self.Key.noteSortTypeKey)
  122. if (sortType == 1) {
  123. self.noteSortType = KMNoteSortType(rawValue: sortType) ?? .none
  124. if (self.noteSortType == .time) {
  125. self.sortTypeLabel.stringValue = KMLocalizedString("Time", nil)
  126. self.sortTypeBox.toolTip = KMLocalizedString("Time", nil)
  127. } else if (self.noteSortType == .page) {
  128. self.sortTypeLabel.stringValue = KMLocalizedString("Page", nil)
  129. self.sortTypeBox.toolTip = KMLocalizedString("Page", nil)
  130. }
  131. } else {
  132. self.noteSortType = .time
  133. self.sortTypeLabel.stringValue = KMLocalizedString("Time", nil)
  134. }
  135. self.sortTypeLabel.textColor = KMAppearance.Layout.h1Color()
  136. self.noteOutlineView.backgroundColor = KMAppearance.Layout.l0Color()
  137. self.noteOutlineView.autoresizesOutlineColumn = false
  138. self.noteOutlineView.indentationPerLevel = 0
  139. }
  140. func annoListIsShowPage() -> Bool {
  141. return !(self.noteTypeDict[Self.Key.noteFilterPage] as? Bool ?? false)
  142. }
  143. func annoListIsShowTime() -> Bool {
  144. return !(self.noteTypeDict[Self.Key.noteFilterTime] as? Bool ?? false)
  145. }
  146. func annoListIsShowAnther() -> Bool {
  147. return !(self.noteTypeDict[Self.Key.noteFilterAuther] as? Bool ?? false)
  148. }
  149. }
  150. // MARK: - Menu
  151. extension KMLeftSideViewController {
  152. func annoListMenu(_ menu: NSMenu) {
  153. var item: NSMenuItem?
  154. var items: NSArray?
  155. var rowIndexes = self.noteOutlineView.selectedRowIndexes
  156. let row = self.noteOutlineView.clickedRow
  157. if row == -1 {
  158. _ = self._addExportPDFMenu(menu)
  159. _ = self._addDeleteAllAnnoItem(menu)
  160. return
  161. }
  162. if rowIndexes.contains(row) == false {
  163. rowIndexes = IndexSet(integer: row)
  164. }
  165. items = self.noteOutlineView.itemsAtRowIndexes(rowIndexes) as NSArray
  166. guard let model = self.fetchAnnoModel(for: row) else {
  167. return
  168. }
  169. var isFold = model.isFold()
  170. item = menu.addItem(title: KMLocalizedString("Expand", nil), action: #selector(unfoldNoteAction), target: self)
  171. item?.state = isFold ? .off : .on
  172. item?.representedObject = items
  173. item = menu.addItem(title: KMLocalizedString("Collapse", nil), action: #selector(foldNoteAction), target: self)
  174. item?.state = isFold ? .on : .off
  175. item?.representedObject = items
  176. menu.addItem(.separator())
  177. let hideNotes = self.hideNotes()
  178. if hideNotes == false && (items?.count ?? 0) == 1 {
  179. let annotation = self.noteItems(items!).lastObject as? CPDFAnnotation
  180. if let data = annotation?.isEditable(), data {
  181. if annotation?.type == nil {
  182. let isNote = annotation?.isNote() ?? false
  183. if isNote {
  184. // [NSLocalizedString(@"Edit", @"Menu item title") stringByAppendingEllipsis]
  185. item = menu.addItem(title: KMLocalizedString("Edit", "Menu item title"), action: #selector(editNoteTextFromTable), target: self)
  186. item?.representedObject = annotation
  187. }
  188. } else if let data = self.noteOutlineView.tableColumn(withIdentifier: NSUserInterfaceItemIdentifier("note"))?.isHidden, data {
  189. // [NSLocalizedString(@"Edit", @"Menu item title") stringByAppendingEllipsis]
  190. item = menu.addItem(title: KMLocalizedString("Edit", "Menu item title"), action: #selector(editThisAnnotation), target: self)
  191. item?.representedObject = annotation
  192. } else {
  193. item = menu.addItem(title: KMLocalizedString("Edit", "Menu item title"), action: #selector(editNoteFromTable), target: self)
  194. item?.representedObject = annotation
  195. item = menu.addItem(title: KMLocalizedString("Edit", "Menu item title"), action: #selector(editThisAnnotation), target: self)
  196. item?.representedObject = annotation
  197. item?.keyEquivalentModifierMask = [.option]
  198. item?.isAlternate = true
  199. }
  200. }
  201. }
  202. if menu.numberOfItems > 0 {
  203. _ = self._addExportPDFMenu(menu)
  204. menu.addItem(.separator())
  205. if self.outlineView(self.noteOutlineView, canDeleteItems: items as? [Any] ?? []) {
  206. item = menu.addItem(title: KMLocalizedString("Delete", "Menu item title"), action: #selector(deleteNotes), target: self)
  207. item?.representedObject = items
  208. }
  209. _ = self._addDeleteAllAnnoItem(menu)
  210. }
  211. }
  212. private func _addExportPDFMenu(_ menu: NSMenu) -> NSMenu {
  213. var item = menu.addItem(title: NSLocalizedString("Export Annotations…", tableName: "", comment: ""), action: nil, target: self)
  214. let subMenu = NSMenu()
  215. item?.submenu = subMenu
  216. item = subMenu.addItem(title: NSLocalizedString("PDF", tableName: "", comment: ""), action: #selector(exportAnnotationNotes), target: self)
  217. item?.tag = 0
  218. item = subMenu.addItem(title: NSLocalizedString("PDF Bundle", tableName: "", comment: ""), action: #selector(exportAnnotationNotes), target: self)
  219. item?.tag = 1
  220. item = subMenu.addItem(title: NSLocalizedString("PDF Reader Pro Edition Notes", tableName: "", comment: ""), action: #selector(exportAnnotationNotes), target: self)
  221. item?.tag = 2
  222. item = subMenu.addItem(title: NSLocalizedString("Notes as Texts", tableName: "", comment: ""), action: #selector(exportAnnotationNotes), target: self)
  223. item?.tag = 3
  224. item = subMenu.addItem(title: NSLocalizedString("Notes as RTF", tableName: "", comment: ""), action: #selector(exportAnnotationNotes), target: self)
  225. item?.tag = 4
  226. item = subMenu.addItem(title: NSLocalizedString("Notes as RTFD", tableName: "", comment: ""), action: #selector(exportAnnotationNotes), target: self)
  227. item?.tag = 5
  228. item = subMenu.addItem(title: NSLocalizedString("Notes as FDF", tableName: "", comment: ""), action: #selector(exportAnnotationNotes), target: self)
  229. item?.tag = 6
  230. return menu
  231. }
  232. private func _addDeleteAllAnnoItem(_ menu: NSMenu) -> NSMenuItem? {
  233. return menu.addItem(title: NSLocalizedString("Remove All Annotations", tableName: "", comment: ""), action: #selector(removeAllAnnotations), target: self)
  234. }
  235. func annoListMoreMenu(_ view: NSButton) {
  236. let menu = NSMenu()
  237. let object = KMPopupMenuObject()
  238. object.menuTag = 1001
  239. menu.delegate = object
  240. object.enterControllerCallback = { [weak self] isEnter in
  241. if (isEnter) {
  242. self?.moreButtonLayer?.isHidden = false
  243. } else {
  244. self?.moreButtonLayer?.isHidden = true
  245. }
  246. }
  247. let expandAllItem = menu.addItem(title: KMLocalizedString("Expand All", nil), action: #selector(note_expandAllComments), target: self)
  248. expandAllItem?.representedObject = self.noteOutlineView
  249. let foldAllItem = menu.addItem(title: KMLocalizedString("Collapse All", nil), action: #selector(note_foldAllComments), target: self)
  250. foldAllItem?.representedObject = self.noteOutlineView
  251. expandAllItem?.state = self.foldType == .unfold ? .on : .off
  252. foldAllItem?.state = self.foldType == .fold ? .on : .off
  253. let showItem = menu.addItem(title: KMLocalizedString("Show Note", nil), action: nil, target: self)
  254. let subMenu = NSMenu()
  255. let pageItem = subMenu.addItem(title: KMLocalizedString("Page", nil), action: #selector(noteShowNoteAction), target: self)
  256. pageItem?.state = self.annoListIsShowPage() ? .on : .off
  257. pageItem?.representedObject = self.noteOutlineView
  258. pageItem?.tag = 101
  259. let timeItem = subMenu.addItem(title: KMLocalizedString("Time", nil) , action: #selector(noteShowNoteAction), target: self)
  260. timeItem?.state = self.annoListIsShowTime() ? .on : .off
  261. timeItem?.representedObject = self.noteOutlineView
  262. timeItem?.tag = 102
  263. let authorItem = subMenu.addItem(title: KMLocalizedString("Author", nil) , action: #selector(noteShowNoteAction), target: self)
  264. authorItem?.state = self.annoListIsShowAnther() ? .on : .off
  265. authorItem?.representedObject = self.noteOutlineView
  266. authorItem?.tag = 103
  267. showItem?.submenu = subMenu
  268. menu.addItem(.separator())
  269. _ = self._addExportPDFMenu(menu)
  270. menu.addItem(.separator())
  271. _ = self._addDeleteAllAnnoItem(menu)
  272. if let data = NSApp.currentEvent {
  273. NSMenu.popUpContextMenu(menu, with: data, for: view, with: nil)
  274. }
  275. }
  276. func annoListValidateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  277. let action = menuItem.action
  278. if (action == #selector(note_expandAllComments) ||
  279. action == #selector(note_foldAllComments) ||
  280. action == #selector(exportAnnotationNotes) ||
  281. action == #selector(removeAllAnnotations)) {
  282. let cnt = self.annoListModel?.datas.count ?? 0
  283. return cnt > 0
  284. } else if (action == #selector(unfoldNoteAction) ||
  285. action == #selector(foldNoteAction)) {
  286. let row = self.noteOutlineView.clickedRow
  287. let foldNote = self.fetchNote(for: row)
  288. // SKNPDFAnnotationNote
  289. if foldNote is CPDFMarkupAnnotation || foldNote is CPDFTextAnnotation {
  290. return true
  291. } else {
  292. return false
  293. }
  294. } else if (action == #selector(editNoteFromTable)) {
  295. let row = self.noteOutlineView.clickedRow
  296. let foldNote = self.fetchNote(for: row)
  297. // if (@available(macOS 10.13, *)) {
  298. // if ([foldNote.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeSignature]) {
  299. // return NO;
  300. // }
  301. // }
  302. if foldNote is CPDFStampAnnotation || foldNote is KMAnnotationStamp || foldNote is CPDFListStampAnnotation {
  303. return false
  304. } else {
  305. return true
  306. }
  307. }
  308. return true
  309. }
  310. @IBAction func note_expandAllComments(_ sender: AnyObject?) {
  311. if (self.foldType == .unfold) { // 已全部展开
  312. return
  313. }
  314. // 设置全部展开的标识
  315. self.foldType = .unfold
  316. // 加载数据
  317. self.loadUnfoldDate(.none)
  318. // 刷新UI
  319. self.noteOutlineView.reloadData()
  320. }
  321. @IBAction func note_foldAllComments(_ sender: AnyObject?) {
  322. if (self.foldType == .fold) {
  323. return
  324. }
  325. self.foldType = .fold
  326. self.loadUnfoldDate(.none)
  327. self.noteOutlineView.reloadData()
  328. }
  329. @IBAction func noteShowNoteAction(_ sender: AnyObject?) {
  330. let item = sender as? NSMenuItem
  331. let tag = item?.tag ?? 0
  332. if (tag == 100) {
  333. } else if (tag == 101) {
  334. let isPage = !self.annoListIsShowPage()
  335. self.noteTypeDict[Self.Key.noteFilterPage] = !isPage
  336. } else if (tag == 102) {
  337. let isTime = !self.annoListIsShowTime()
  338. self.noteTypeDict[Self.Key.noteFilterTime] = !isTime
  339. } else if (tag == 103) {
  340. let isAuther = !self.annoListIsShowAnther()
  341. self.noteTypeDict[Self.Key.noteFilterAuther] = !isAuther
  342. }
  343. UserDefaults.standard.sync_setValue(self.noteTypeDict, forKey: Self.Key.noteTableColumn)
  344. let selectRow = self.noteOutlineView.selectedRow
  345. self.noteOutlineView.reloadData()
  346. self.noteOutlineView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  347. }
  348. @objc func exportAnnotationNotes(_ sender: AnyObject?) {
  349. let doc = self.view.window?.windowController?.document as? NSDocument
  350. doc?.saveTo(sender)
  351. }
  352. // 展开
  353. @objc func unfoldNoteAction(_ sender: NSMenuItem) {
  354. if sender.state == .on {
  355. return
  356. }
  357. let row = self.noteOutlineView.clickedRow
  358. guard let model = self.fetchAnnoModel(for: row) else {
  359. return
  360. }
  361. // if self.allFoldNotes.count == self.canFoldNotes.count {
  362. // self.foldType = .unfold
  363. // } else {
  364. // self.foldType = .none
  365. // }
  366. model.foldType = .unfold
  367. let viewS = self.noteOutlineView.view(atColumn: 0, row: row, makeIfNecessary: true)
  368. (viewS as? KMNoteTableViewCell)?.isFold = false
  369. }
  370. @objc func foldNoteAction(_ sender: NSMenuItem) {
  371. if sender.state == .on {
  372. return
  373. }
  374. let row = self.noteOutlineView.clickedRow
  375. guard let model = self.fetchAnnoModel(for: row) else {
  376. return
  377. }
  378. // if (self.allFoldNotes.count == 0) {
  379. // self.foldType = .fold
  380. // } else {
  381. // self.foldType = .none
  382. // }
  383. model.foldType = .fold
  384. let viewS = self.noteOutlineView.view(atColumn: 0, row: row, makeIfNecessary: true)
  385. (viewS as? KMNoteTableViewCell)?.isFold = true
  386. }
  387. @objc func deleteNotes(_ sender: NSMenuItem) {
  388. self.outlineView(self.noteOutlineView, deleteItems: sender.representedObject as? [Any] ?? [])
  389. }
  390. @objc func removeAllAnnotations(_ sender: AnyObject?) {
  391. guard let doc = self.pdfDocument() else {
  392. return
  393. }
  394. Task {
  395. let response = await KMAlertTool.runModel(message: KMLocalizedString("This will permanently remove all annotations. Are you sure to continue?", nil), buttons: [KMLocalizedString("Yes", nil), KMLocalizedString("No", nil)])
  396. if response == .alertFirstButtonReturn {
  397. var annos: [CPDFAnnotation] = []
  398. for i in 0 ..< doc.pageCount {
  399. let page = self.pdfDocument()?.page(at: i)
  400. for anno in page?.annotations ?? [] {
  401. if anno is CPDFTextWidgetAnnotation || anno is CPDFButtonWidgetAnnotation || anno is CPDFChoiceWidgetAnnotation {
  402. continue
  403. }
  404. // if ([annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeSignature]) {
  405. // continue;
  406. // }
  407. annos.append(anno)
  408. }
  409. }
  410. for anno in annos {
  411. self.listView?.remove(anno)
  412. }
  413. self.reloadAnnotation()
  414. }
  415. }
  416. }
  417. @objc func editNoteTextFromTable(_ sender: NSMenuItem) {
  418. // PDFAnnotation *annotation = [sender representedObject];
  419. guard let annotation = sender.representedObject as? CPDFAnnotation else {
  420. return
  421. }
  422. self.listView?.scrollAnnotationToVisible(annotation)
  423. // self.listView.activeAnnotation = annotation
  424. // [self showNote:annotation];
  425. // SKNoteWindowController *noteController = (SKNoteWindowController *)[self windowControllerForNote:annotation];
  426. // [[noteController window] makeFirstResponder:[noteController textView]];
  427. // [[noteController textView] selectAll:nil];
  428. }
  429. @objc func editThisAnnotation(_ sender: AnyObject?) {
  430. KMPrint("editThisAnnotation ...")
  431. }
  432. @objc func editNoteFromTable(_ sender: AnyObject?) {
  433. KMPrint("editNoteFromTable ...")
  434. }
  435. @IBAction func noteSortAction(_ sender: AnyObject?) {
  436. if (self.isAscendSort) {
  437. self.isAscendSort = false
  438. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankPositive)
  439. self.noteSortButton.toolTip = KMLocalizedString("descending sort", nil)
  440. } else {
  441. self.isAscendSort = true
  442. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankReverse)
  443. self.noteSortButton.toolTip = KMLocalizedString("ascending sort", nil)
  444. }
  445. KMDataManager.ud_set(self.isAscendSort, forKey: Self.Key.noteAscendSortKey)
  446. self.reloadAnnotation()
  447. }
  448. @IBAction func noteSearchAction(_ sender: NSButton) {
  449. self.noteSearchField.isHidden = false
  450. self.noteTitleLabel.isHidden = true
  451. self.noteSearchButton.isHidden = true
  452. self.noteDoneButton.isHidden = false
  453. self.noteFilterButton.isHidden = true
  454. self.noteMoreButton.isHidden = true
  455. self.noteSearchField.becomeFirstResponder()
  456. }
  457. @IBAction func noteFilterAction(_ sender: AnyObject?) {
  458. let button = sender as? NSButton
  459. let menu = NSMenu()
  460. let filterViewController = KMNoteOutlineFilterViewController()
  461. filterViewController.listView = self.listView
  462. filterViewController.view.layer?.backgroundColor = .clear
  463. var notes = NSMutableArray()
  464. // for section in self._annotations {
  465. // if section.annotations?.count != 0 {
  466. // for item in section.annotations! {
  467. // notes.add(item.annotation!)
  468. // }
  469. // }
  470. // }
  471. filterViewController.setNotesArray(self.allAnnotations as NSArray)
  472. filterViewController.applyFilterCallback = { [weak self] typeArr, colorArr, authorArr, isEmpty in
  473. menu.cancelTracking()
  474. if (isEmpty) {
  475. self?.filterButtonLayer?.isHidden = true
  476. } else {
  477. self?.filterButtonLayer?.isHidden = false
  478. }
  479. self?.reloadAnnotation()
  480. }
  481. filterViewController.cancelCallback = { isCancel in
  482. if (isCancel) {
  483. menu.cancelTracking()
  484. }
  485. }
  486. let item = menu.addItem(withTitle: "", action: nil, keyEquivalent: "")
  487. item.target = self
  488. item.representedObject = filterViewController
  489. item.view = filterViewController.view
  490. menu.popUp(positioning: nil, at: CGPointMake(-130, 30), in: button)
  491. }
  492. func fetchNote(for index: Int) -> CPDFAnnotation? {
  493. return self.fetchAnnoModel(for: index)?.anno
  494. }
  495. func fetchAnnoModel(for index: Int) -> KMBotaAnnotationModel? {
  496. if self.noteSearchMode { // 搜索模式
  497. return self.noteSearchArray.safe_element(for: index) as? KMBotaAnnotationModel
  498. } else { // 常规模式(非搜索)
  499. return self.annoListModel?.datas.safe_element(for: index) as? KMBotaAnnotationModel
  500. }
  501. }
  502. @IBAction @objc func sortTypeAction(_ sender: NSMenuItem) {
  503. let item = sender
  504. let tag = item.tag
  505. if (item.state == .on) {
  506. item.state = .off
  507. } else {
  508. item.state = .on
  509. }
  510. if (tag == 0) {
  511. self.noteSortType = .page
  512. self.sortTypeLabel.stringValue = KMLocalizedString("Page", nil)
  513. self.sortTypeBox.toolTip = KMLocalizedString("Page", nil)
  514. } else if (tag == 1) {
  515. self.noteSortType = .time
  516. self.sortTypeLabel.stringValue = KMLocalizedString("Time", nil)
  517. self.sortTypeBox.toolTip = KMLocalizedString("Time", nil)
  518. }
  519. KMDataManager.ud_set(self.noteSortType.rawValue, forKey: Self.Key.noteSortTypeKey)
  520. self.reloadAnnotation()
  521. }
  522. func showNoteEmptyView() {
  523. let view = self.noteOutlineView.enclosingScrollView?.documentView
  524. let viewFrame = view?.frame ?? .zero
  525. let emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  526. self.leftSideEmptyVC.emptyAnnotationView.frame = NSMakeRect((viewFrame.size.width-emptyVcSize.width)/2.0,(viewFrame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height)
  527. self.leftSideEmptyVC.emptyAnnotationView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  528. self.noteOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyAnnotationView)
  529. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = false
  530. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = false
  531. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  532. self.noteHeaderView.isHidden = true
  533. self.toolButtonBoxLayoutConstraint.constant = 40.0
  534. }
  535. }
  536. func hideNoteEmptyView() {
  537. self.leftSideEmptyVC.emptyAnnotationView.removeFromSuperview()
  538. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = true
  539. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = true
  540. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  541. self.noteHeaderView.isHidden = false
  542. self.toolButtonBoxLayoutConstraint.constant = 64.0
  543. }
  544. }
  545. }
  546. // MARK: - Note
  547. extension KMLeftSideViewController {
  548. func note_refrshUIIfNeed() {
  549. if self.type.methodType != .Annotation {
  550. return
  551. }
  552. Task { @MainActor in
  553. self.noteOutlineView.reloadData()
  554. }
  555. }
  556. func note_reloadDataIfNeed() {
  557. if self.type.methodType != .Annotation {
  558. return
  559. }
  560. self.reloadAnnotation()
  561. }
  562. func note_reloadDataForAnnoIfNeed(anno: CPDFAnnotation) {
  563. if self.type.methodType != .Annotation {
  564. return
  565. }
  566. if anno is CPDFLineAnnotation || anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation || anno is CPDFInkAnnotation {
  567. // 形状注释 + Ink 需要显示框住的内容【刷新】
  568. for item in self.annoListModel?.datas ?? [] {
  569. if anno.isEqual(to: item.anno) {
  570. self.noteOutlineView.reloadItem(item)
  571. break
  572. }
  573. }
  574. }
  575. }
  576. func reloadAnnotation() {
  577. if self.listView != nil {
  578. let filterKey = self.pdfDocument()?.documentURL.path ?? ""
  579. let typeArr: [Any] = KMBotaTools.noteFilterAnnoTypes(key: filterKey)
  580. let colorArr: [Any] = KMBotaTools.noteFilterColors(key: filterKey)
  581. let authorArr: [Any] = KMBotaTools.noteFilterAuthors(key: filterKey)
  582. if typeArr.count == 0 && colorArr.count == 0 && authorArr.count == 0 {
  583. // self.filtrateButton.image = NSImage(named: "KMImageNameAnnotationsFiltrate")
  584. self.filterButtonLayer?.isHidden = true
  585. } else {
  586. // self.filtrateButton.image = NSImage(named: "icon_annotation_screening_select")self.filterButtonLayer?.isHidden = true
  587. self.filterButtonLayer?.isHidden = false
  588. }
  589. var annotationArray: [CPDFAnnotation] = []
  590. var allAnnotation: [CPDFAnnotation] = []
  591. for i in 0 ..< self.pageCount() {
  592. let page = self.pdfDocument()?.page(at: UInt(i))
  593. var annos: [CPDFAnnotation] = []
  594. // 处理过滤
  595. if typeArr.count == 0 && colorArr.count == 0 && authorArr.count == 0 {
  596. let types = ["Highlight","Underline","Strikeout","Freehand","FreeText","Note","Square","Circle","Line","Stamp","Arrow","Image","Redact","Sign"]
  597. annos = KMOCToolClass.filterAnnotation(annotations: page?.annotations ?? [],types: types) as? [CPDFAnnotation] ?? []
  598. } else {
  599. var filterAnnos: [CPDFAnnotation] = page?.annotations ?? []
  600. if typeArr.count > 0 {
  601. filterAnnos = (KMOCToolClass.filterAnnotation(annotations: filterAnnos, types: typeArr) as? [CPDFAnnotation]) ?? []
  602. }
  603. if (colorArr.count > 0) {
  604. filterAnnos = (KMOCToolClass.filterAnnotation(annotations: filterAnnos,colors: colorArr) as? [CPDFAnnotation]) ?? []
  605. }
  606. if (authorArr.count > 0) {
  607. filterAnnos = (KMOCToolClass.filterAnnotation(annotations: filterAnnos,authors: authorArr) as? [CPDFAnnotation]) ?? []
  608. }
  609. annos = filterAnnos
  610. }
  611. //添加签名注释
  612. for annotation in page?.annotations ?? [] {
  613. if annotation.isKind(of: CPDFSignatureAnnotation.self) {
  614. annos.append(annotation)
  615. }
  616. }
  617. for annotation in annos {
  618. if annotation.annotationShouldDisplay() == false {
  619. annos.removeObject(annotation)
  620. }
  621. }
  622. // 添加刷选后的注释
  623. allAnnotation += annos
  624. //添加所有annotation 用于筛选
  625. annotationArray += (page?.annotations ?? [])
  626. }
  627. // 处理排序
  628. if self.noteSortType == .page {
  629. /// 排序(升序)
  630. if self.isAscendSort {
  631. allAnnotation.sort {
  632. let idx0 = $0.page?.pageIndex() ?? 0
  633. let idx1 = $1.page?.pageIndex() ?? 0
  634. return idx0 <= idx1
  635. }
  636. } else {
  637. allAnnotation.sort {
  638. let idx0 = $0.page?.pageIndex() ?? 0
  639. let idx1 = $1.page?.pageIndex() ?? 0
  640. return idx0 > idx1
  641. }
  642. }
  643. } else if self.noteSortType == .time {
  644. /// 排序(升序)
  645. if self.isAscendSort {
  646. allAnnotation.sort {
  647. if $0.modificationDate() == nil {
  648. return false
  649. }
  650. if $1.modificationDate() == nil {
  651. return false
  652. }
  653. return $0.modificationDate() <= $1.modificationDate()
  654. }
  655. } else {
  656. allAnnotation.sort {
  657. if $0.modificationDate() == nil {
  658. return false
  659. }
  660. if $1.modificationDate() == nil {
  661. return false
  662. }
  663. return $0.modificationDate() > $1.modificationDate()
  664. }
  665. }
  666. }
  667. // 数据模型\化
  668. let model = KMAnnotationListModel()
  669. var datas: [KMBotaAnnotationModel] = []
  670. for anno in allAnnotation {
  671. let item = KMBotaAnnotationModel()
  672. item.anno = anno
  673. item.showPage = self.annoListIsShowPage()
  674. item.showTime = self.annoListIsShowTime()
  675. item.showAuthor = self.annoListIsShowAnther()
  676. datas.append(item)
  677. }
  678. model.datas = datas
  679. self.annoListModel = model
  680. // 转换对象,用于数据显示
  681. self.allAnnotations = annotationArray
  682. // if self.annotations.count < 1 {
  683. // self.filtrateButton.isEnabled = false
  684. // } else {
  685. // self.filtrateButton.isEnabled = true
  686. // }
  687. }
  688. Task { @MainActor in
  689. self.noteOutlineView.reloadData()
  690. }
  691. }
  692. // 搜索 Action
  693. func updateNoteFilterPredicate() {
  694. var stringValue = self.noteSearchField.stringValue
  695. if self.caseInsensitiveNoteSearch { // 忽略大小写
  696. stringValue = stringValue.lowercased()
  697. }
  698. // 清空数据
  699. self.noteSearchArray.removeAll()
  700. if stringValue.isEmpty {
  701. for model in self.annoListModel?.datas ?? [] {
  702. guard let note = model.anno else {
  703. continue
  704. }
  705. self.noteSearchArray.append(model)
  706. }
  707. } else {
  708. for model in self.annoListModel?.datas ?? [] {
  709. guard let note = model.anno else {
  710. continue
  711. }
  712. var noteString = KMBOTAAnnotationTool.fetchContentLabelString(annotation: note)
  713. if let anno = note as? CPDFMarkupAnnotation {
  714. noteString = anno.markupContent()
  715. }
  716. if self.caseInsensitiveNoteSearch {
  717. noteString = noteString.lowercased()
  718. }
  719. if noteString.contains(stringValue) {
  720. self.noteSearchArray.append(model)
  721. }
  722. }
  723. }
  724. // 刷新 UI
  725. Task { @MainActor in
  726. self.noteOutlineView.reloadData()
  727. }
  728. }
  729. @objc func selectSelectedNote(_ sender: AnyObject?) {
  730. if self.hideNotes() == false {
  731. let selectedNotes = self.selectedNotes()
  732. if selectedNotes.count == 1 {
  733. let annotation = selectedNotes.last!
  734. self.listView?.go(to: annotation.bounds, on: annotation.page, animated: true)
  735. // [pdfView scrollAnnotationToVisible:annotation];
  736. // [pdfView setActiveAnnotation:annotation];
  737. self.listView?.updateActiveAnnotations([annotation])
  738. self.listView?.setNeedsDisplayAnnotationViewForVisiblePages()
  739. // }
  740. }
  741. // NSInteger column = [sender clickedColumn];
  742. // if (column != -1) {
  743. // NSString *colID = [[[sender tableColumns] objectAtIndex:column] identifier];
  744. //
  745. // if ([colID isEqualToString:@"color"]){
  746. // for (PDFAnnotation *annotation in self.pdfView.activeAnnotations) {
  747. // if (![annotation isKindOfClass:[PDFAnnotationChoiceWidget class]] &&
  748. // ![annotation isKindOfClass:[PDFAnnotationButtonWidget class]] &&
  749. // ![annotation isKindOfClass:[PDFAnnotationTextWidget class]]) {
  750. // [[NSColorPanel sharedColorPanel] orderFront:nil];
  751. // break;
  752. // }
  753. //
  754. // }
  755. // }
  756. // }
  757. }
  758. }
  759. func selectedNotes() -> [CPDFAnnotation] {
  760. var selectedNotes: [CPDFAnnotation] = []
  761. let rowIndexes = self.noteOutlineView.selectedRowIndexes
  762. for row in rowIndexes {
  763. let item = self.noteOutlineView.item(atRow: row)
  764. if item is KMBotaAnnotationModel {
  765. if let anno = (item as! KMBotaAnnotationModel).anno {
  766. // if anno.type == nil {
  767. // item = [(SKNoteText *)item note];
  768. // }
  769. if selectedNotes.contains(anno) == false {
  770. selectedNotes.append(anno)
  771. }
  772. }
  773. }
  774. }
  775. return selectedNotes
  776. }
  777. func clearAnnotationFilterData() {
  778. if let _key = self.pdfDocument()?.documentURL?.path {
  779. let userDefaults = UserDefaults.standard
  780. let typeData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  781. userDefaults.set(typeData, forKey: NoteFilterVC.filterSelectTypeKey + _key)
  782. let colorData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  783. userDefaults.set(colorData, forKey: NoteFilterVC.filterSelectColorKey + _key)
  784. let authorData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  785. userDefaults.set(authorData, forKey: NoteFilterVC.filterSelectAuthorKey + _key)
  786. userDefaults.synchronize()
  787. }
  788. }
  789. func loadUnfoldDate(_ foldType: KMFoldType) {
  790. var mutableArray: [CPDFAnnotation] = []
  791. if self.noteSearchMode {
  792. for model in self.noteSearchArray {
  793. if let note = model.anno as? CPDFMarkupAnnotation {
  794. mutableArray.append(note)
  795. }
  796. }
  797. } else {
  798. for model in self.annoListModel?.datas ?? [] {
  799. if let note = model.anno, note is CPDFMarkupAnnotation {
  800. mutableArray.append(note)
  801. }
  802. }
  803. }
  804. // for note in self.notes {
  805. // if note is CPDFMarkupAnnotation {
  806. // mutableArray.append(note)
  807. // }
  808. // }
  809. self.canFoldNotes = mutableArray
  810. }
  811. }