KMLeftSideViewController+Note.swift 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  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 foldNote = self.fetchNote(for: row) else {
  167. return
  168. }
  169. var isFold = true
  170. if self.allFoldNotes.contains(foldNote) {
  171. isFold = false
  172. }
  173. item = menu.addItem(title: KMLocalizedString("Expand", nil), action: #selector(unfoldNoteAction), target: self)
  174. if (isFold) {
  175. item?.state = .off
  176. } else {
  177. item?.state = .on
  178. }
  179. item?.representedObject = items
  180. item = menu.addItem(title: KMLocalizedString("Collapse", nil), action: #selector(foldNoteAction), target: self)
  181. if (isFold) {
  182. item?.state = .on
  183. } else {
  184. item?.state = .off
  185. }
  186. item?.representedObject = items
  187. menu.addItem(.separator())
  188. let hideNotes = self.hideNotes()
  189. if hideNotes == false && (items?.count ?? 0) == 1 {
  190. let annotation = self.noteItems(items!).lastObject as? CPDFAnnotation
  191. if let data = annotation?.isEditable(), data {
  192. if annotation?.type == nil {
  193. let isNote = annotation?.isNote() ?? false
  194. if isNote {
  195. // [NSLocalizedString(@"Edit", @"Menu item title") stringByAppendingEllipsis]
  196. item = menu.addItem(title: KMLocalizedString("Edit", "Menu item title"), action: #selector(editNoteTextFromTable), target: self)
  197. item?.representedObject = annotation
  198. }
  199. } else if let data = self.noteOutlineView.tableColumn(withIdentifier: NSUserInterfaceItemIdentifier("note"))?.isHidden, data {
  200. // [NSLocalizedString(@"Edit", @"Menu item title") stringByAppendingEllipsis]
  201. item = menu.addItem(title: KMLocalizedString("Edit", "Menu item title"), action: #selector(editThisAnnotation), target: self)
  202. item?.representedObject = annotation
  203. } else {
  204. item = menu.addItem(title: KMLocalizedString("Edit", "Menu item title"), action: #selector(editNoteFromTable), target: self)
  205. item?.representedObject = annotation
  206. item = menu.addItem(title: KMLocalizedString("Edit", "Menu item title"), action: #selector(editThisAnnotation), target: self)
  207. item?.representedObject = annotation
  208. item?.keyEquivalentModifierMask = [.option]
  209. item?.isAlternate = true
  210. }
  211. }
  212. }
  213. if menu.numberOfItems > 0 {
  214. _ = self._addExportPDFMenu(menu)
  215. menu.addItem(.separator())
  216. if self.outlineView(self.noteOutlineView, canDeleteItems: items as? [Any] ?? []) {
  217. item = menu.addItem(title: KMLocalizedString("Delete", "Menu item title"), action: #selector(deleteNotes), target: self)
  218. item?.representedObject = items
  219. }
  220. _ = self._addDeleteAllAnnoItem(menu)
  221. }
  222. }
  223. private func _addExportPDFMenu(_ menu: NSMenu) -> NSMenu {
  224. var item = menu.addItem(title: NSLocalizedString("Export Annotations…", tableName: "", comment: ""), action: nil, target: self)
  225. let subMenu = NSMenu()
  226. item?.submenu = subMenu
  227. item = subMenu.addItem(title: NSLocalizedString("PDF", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  228. item?.tag = 0
  229. item = subMenu.addItem(title: NSLocalizedString("PDF Bundle", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  230. item?.tag = 1
  231. item = subMenu.addItem(title: NSLocalizedString("PDF Reader Pro Edition Notes", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  232. item?.tag = 2
  233. item = subMenu.addItem(title: NSLocalizedString("Notes as Texts", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  234. item?.tag = 3
  235. item = subMenu.addItem(title: NSLocalizedString("Notes as RTF", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  236. item?.tag = 4
  237. item = subMenu.addItem(title: NSLocalizedString("Notes as RTFD", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  238. item?.tag = 5
  239. item = subMenu.addItem(title: NSLocalizedString("Notes as FDF", tableName: "MainMenu", comment: "Menu item title"), action: #selector(exportAnnotationNotes), target: self)
  240. item?.tag = 6
  241. return menu
  242. }
  243. private func _addDeleteAllAnnoItem(_ menu: NSMenu) -> NSMenuItem? {
  244. return menu.addItem(title: NSLocalizedString("Remove All Annotations", tableName: "", comment: ""), action: #selector(removeAllAnnotations), target: self)
  245. }
  246. func annoListMoreMenu(_ view: NSButton) {
  247. let menu = NSMenu()
  248. let object = KMPopupMenuObject()
  249. object.menuTag = 1001
  250. menu.delegate = object
  251. object.enterControllerCallback = { [weak self] isEnter in
  252. if (isEnter) {
  253. self?.moreButtonLayer?.isHidden = false
  254. } else {
  255. self?.moreButtonLayer?.isHidden = true
  256. }
  257. }
  258. let expandAllItem = menu.addItem(title: KMLocalizedString("Expand All", nil), action: #selector(note_expandAllComments), target: self)
  259. expandAllItem?.representedObject = self.noteOutlineView
  260. let foldAllItem = menu.addItem(title: KMLocalizedString("Collapse All", nil), action: #selector(note_foldAllComments), target: self)
  261. foldAllItem?.representedObject = self.noteOutlineView
  262. expandAllItem?.state = self.foldType == .unfold ? .on : .off
  263. foldAllItem?.state = self.foldType == .fold ? .on : .off
  264. let showItem = menu.addItem(title: KMLocalizedString("Show Note", nil), action: nil, target: self)
  265. let subMenu = NSMenu()
  266. let pageItem = subMenu.addItem(title: KMLocalizedString("Page", nil), action: #selector(noteShowNoteAction), target: self)
  267. pageItem?.state = self.annoListIsShowPage() ? .on : .off
  268. pageItem?.representedObject = self.noteOutlineView
  269. pageItem?.tag = 101
  270. let timeItem = subMenu.addItem(title: KMLocalizedString("Time", nil) , action: #selector(noteShowNoteAction), target: self)
  271. timeItem?.state = self.annoListIsShowTime() ? .on : .off
  272. timeItem?.representedObject = self.noteOutlineView
  273. timeItem?.tag = 102
  274. let authorItem = subMenu.addItem(title: KMLocalizedString("Author", nil) , action: #selector(noteShowNoteAction), target: self)
  275. authorItem?.state = self.annoListIsShowAnther() ? .on : .off
  276. authorItem?.representedObject = self.noteOutlineView
  277. authorItem?.tag = 103
  278. showItem?.submenu = subMenu
  279. menu.addItem(.separator())
  280. _ = self._addExportPDFMenu(menu)
  281. menu.addItem(.separator())
  282. _ = self._addDeleteAllAnnoItem(menu)
  283. if let data = NSApp.currentEvent {
  284. NSMenu.popUpContextMenu(menu, with: data, for: view, with: nil)
  285. }
  286. }
  287. func annoListValidateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  288. let action = menuItem.action
  289. if (action == #selector(note_expandAllComments) ||
  290. action == #selector(note_foldAllComments) ||
  291. action == #selector(exportAnnotationNotes) ||
  292. action == #selector(removeAllAnnotations)) {
  293. return self.annotations.count > 0
  294. } else if (action == #selector(unfoldNoteAction) ||
  295. action == #selector(foldNoteAction)) {
  296. let row = self.noteOutlineView.clickedRow
  297. let foldNote = self.fetchNote(for: row)
  298. // SKNPDFAnnotationNote
  299. if foldNote is CPDFMarkupAnnotation || foldNote is CPDFTextAnnotation {
  300. return true
  301. } else {
  302. return false
  303. }
  304. } else if (action == #selector(editNoteFromTable)) {
  305. let row = self.noteOutlineView.clickedRow
  306. let foldNote = self.fetchNote(for: row)
  307. // if (@available(macOS 10.13, *)) {
  308. // if ([foldNote.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeSignature]) {
  309. // return NO;
  310. // }
  311. // }
  312. if foldNote is CPDFStampAnnotation || foldNote is KMAnnotationStamp || foldNote is CPDFListStampAnnotation {
  313. return false
  314. } else {
  315. return true
  316. }
  317. }
  318. return true
  319. }
  320. @IBAction func note_expandAllComments(_ sender: AnyObject?) {
  321. if (self.foldType == .unfold) { // 已全部展开
  322. return
  323. }
  324. // 设置全部展开的标识
  325. self.foldType = .unfold
  326. // 加载数据
  327. self.loadUnfoldDate(.none)
  328. // 刷新UI
  329. self.noteOutlineView.reloadData()
  330. }
  331. @IBAction func note_foldAllComments(_ sender: AnyObject?) {
  332. if (self.foldType == .fold) {
  333. return
  334. }
  335. self.foldType = .fold
  336. self.loadUnfoldDate(.none)
  337. self.noteOutlineView.reloadData()
  338. }
  339. @IBAction func noteShowNoteAction(_ sender: AnyObject?) {
  340. let item = sender as? NSMenuItem
  341. let tag = item?.tag ?? 0
  342. if (tag == 100) {
  343. } else if (tag == 101) {
  344. let isPage = !self.annoListIsShowPage()
  345. self.noteTypeDict[Self.Key.noteFilterPage] = !isPage
  346. } else if (tag == 102) {
  347. let isTime = !self.annoListIsShowTime()
  348. self.noteTypeDict[Self.Key.noteFilterTime] = !isTime
  349. } else if (tag == 103) {
  350. let isAuther = !self.annoListIsShowAnther()
  351. self.noteTypeDict[Self.Key.noteFilterAuther] = !isAuther
  352. }
  353. UserDefaults.standard.sync_setValue(self.noteTypeDict, forKey: Self.Key.noteTableColumn)
  354. let selectRow = self.noteOutlineView.selectedRow
  355. self.noteOutlineView.reloadData()
  356. self.noteOutlineView.selectRowIndexes(IndexSet(integer: selectRow), byExtendingSelection: false)
  357. }
  358. @objc func exportAnnotationNotes(_ sender: AnyObject?) {
  359. let doc = self.view.window?.windowController?.document as? NSDocument
  360. doc?.saveTo(sender)
  361. }
  362. @objc func unfoldNoteAction(_ sender: NSMenuItem) {
  363. if sender.state == .on {
  364. return
  365. }
  366. let row = self.noteOutlineView.clickedRow
  367. guard let foldNote = self.fetchNote(for: row) else {
  368. return
  369. }
  370. if self.allFoldNotes.contains(foldNote) == false {
  371. self.allFoldNotes.append(foldNote)
  372. }
  373. if self.allFoldNotes.count == self.canFoldNotes.count {
  374. self.foldType = .unfold
  375. } else {
  376. self.foldType = .none
  377. }
  378. let viewS = self.noteOutlineView.view(atColumn: 0, row: row, makeIfNecessary: true)
  379. (viewS as? KMNoteTableViewCell)?.isFold = false
  380. }
  381. @objc func foldNoteAction(_ sender: NSMenuItem) {
  382. // if sender.state == .on {
  383. // return
  384. // }
  385. let row = self.noteOutlineView.clickedRow
  386. guard let foldNote = self.fetchNote(for: row) else {
  387. return
  388. }
  389. if self.allFoldNotes.contains(foldNote) == false {
  390. self.allFoldNotes.append(foldNote)
  391. }
  392. if (self.allFoldNotes.count == 0) {
  393. self.foldType = .fold
  394. } else {
  395. self.foldType = .none
  396. }
  397. let viewS = self.noteOutlineView.view(atColumn: 0, row: row, makeIfNecessary: true)
  398. (viewS as? KMNoteTableViewCell)?.isFold = true
  399. }
  400. @objc func deleteNotes(_ sender: NSMenuItem) {
  401. self.outlineView(self.noteOutlineView, deleteItems: sender.representedObject as? [Any] ?? [])
  402. }
  403. @objc func removeAllAnnotations(_ sender: AnyObject?) {
  404. guard let doc = self.pdfDocument() else {
  405. return
  406. }
  407. Task {
  408. 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)])
  409. if response == .alertFirstButtonReturn {
  410. var annos: [CPDFAnnotation] = []
  411. for i in 0 ..< doc.pageCount {
  412. let page = self.pdfDocument()?.page(at: i)
  413. for anno in page?.annotations ?? [] {
  414. if anno is CPDFTextWidgetAnnotation || anno is CPDFButtonWidgetAnnotation || anno is CPDFChoiceWidgetAnnotation {
  415. continue
  416. }
  417. // if ([annotation.widgetFieldType isEqualToString:PDFAnnotationWidgetSubtypeSignature]) {
  418. // continue;
  419. // }
  420. annos.append(anno)
  421. }
  422. }
  423. for anno in annos {
  424. self.listView?.remove(anno)
  425. }
  426. self.reloadAnnotation()
  427. }
  428. }
  429. }
  430. @objc func editNoteTextFromTable(_ sender: NSMenuItem) {
  431. // PDFAnnotation *annotation = [sender representedObject];
  432. guard let annotation = sender.representedObject as? CPDFAnnotation else {
  433. return
  434. }
  435. self.listView?.scrollAnnotationToVisible(annotation)
  436. // self.listView.activeAnnotation = annotation
  437. // [self showNote:annotation];
  438. // SKNoteWindowController *noteController = (SKNoteWindowController *)[self windowControllerForNote:annotation];
  439. // [[noteController window] makeFirstResponder:[noteController textView]];
  440. // [[noteController textView] selectAll:nil];
  441. }
  442. @objc func editThisAnnotation(_ sender: AnyObject?) {
  443. KMPrint("editThisAnnotation ...")
  444. }
  445. @objc func editNoteFromTable(_ sender: AnyObject?) {
  446. KMPrint("editNoteFromTable ...")
  447. }
  448. @IBAction func noteSortAction(_ sender: AnyObject?) {
  449. if (self.isAscendSort) {
  450. self.isAscendSort = false
  451. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankPositive)
  452. self.noteSortButton.toolTip = KMLocalizedString("descending sort", nil)
  453. } else {
  454. self.isAscendSort = true
  455. self.noteSortButton.image = NSImage(named: KMImageNameBtnSidebarRankReverse)
  456. self.noteSortButton.toolTip = KMLocalizedString("ascending sort", nil)
  457. }
  458. KMDataManager.ud_set(self.isAscendSort, forKey: Self.Key.noteAscendSortKey)
  459. // self.annotationSort(sortArray: [])
  460. self.reloadAnnotation()
  461. }
  462. @IBAction func noteSearchAction(_ sender: NSButton) {
  463. self.noteSearchField.isHidden = false
  464. self.noteTitleLabel.isHidden = true
  465. self.noteSearchButton.isHidden = true
  466. self.noteDoneButton.isHidden = false
  467. self.noteFilterButton.isHidden = true
  468. self.noteMoreButton.isHidden = true
  469. self.noteSearchField.becomeFirstResponder()
  470. }
  471. @IBAction func noteFilterAction(_ sender: AnyObject?) {
  472. let button = sender as? NSButton
  473. let menu = NSMenu()
  474. let filterViewController = KMNoteOutlineFilterViewController()
  475. filterViewController.listView = self.listView
  476. filterViewController.view.layer?.backgroundColor = .clear
  477. var notes = NSMutableArray()
  478. // for section in self._annotations {
  479. // if section.annotations?.count != 0 {
  480. // for item in section.annotations! {
  481. // notes.add(item.annotation!)
  482. // }
  483. // }
  484. // }
  485. filterViewController.setNotesArray(self.allAnnotations as NSArray)
  486. filterViewController.applyFilterCallback = { [weak self] typeArr, colorArr, authorArr, isEmpty in
  487. menu.cancelTracking()
  488. if (isEmpty) {
  489. self?.filterButtonLayer?.isHidden = true
  490. } else {
  491. self?.filterButtonLayer?.isHidden = false
  492. }
  493. self?.reloadAnnotation()
  494. }
  495. filterViewController.cancelCallback = { isCancel in
  496. if (isCancel) {
  497. menu.cancelTracking()
  498. }
  499. }
  500. let item = menu.addItem(withTitle: "", action: nil, keyEquivalent: "")
  501. item.target = self
  502. item.representedObject = filterViewController
  503. item.view = filterViewController.view
  504. menu.popUp(positioning: nil, at: CGPointMake(-130, 30), in: button)
  505. }
  506. func fetchNote(for index: Int) -> CPDFAnnotation? {
  507. if self.noteSearchMode { // 搜索模式
  508. return self.noteSearchArray.safe_element(for: index) as? CPDFAnnotation
  509. } else { // 常规模式(非搜索)
  510. let section = self.annotations.safe_element(for: index) as? KMBOTAAnnotationSection
  511. return section?.annotations?.first?.annotation
  512. }
  513. }
  514. @IBAction @objc func sortTypeAction(_ sender: NSMenuItem) {
  515. let item = sender
  516. let tag = item.tag
  517. if (item.state == .on) {
  518. item.state = .off
  519. } else {
  520. item.state = .on
  521. }
  522. if (tag == 0) {
  523. self.noteSortType = .page
  524. self.sortTypeLabel.stringValue = KMLocalizedString("Page", nil)
  525. self.sortTypeBox.toolTip = KMLocalizedString("Page", nil)
  526. } else if (tag == 1) {
  527. self.noteSortType = .time
  528. self.sortTypeLabel.stringValue = KMLocalizedString("Time", nil)
  529. self.sortTypeBox.toolTip = KMLocalizedString("Time", nil)
  530. }
  531. KMDataManager.ud_set(self.noteSortType.rawValue, forKey: Self.Key.noteSortTypeKey)
  532. // self.annotationSort(sortArray: [])
  533. self.reloadAnnotation()
  534. }
  535. func showNoteEmptyView() {
  536. let view = self.noteOutlineView.enclosingScrollView?.documentView
  537. let viewFrame = view?.frame ?? .zero
  538. let emptyVcSize = self.leftSideEmptyVC.emptyAnnotationView.frame.size
  539. self.leftSideEmptyVC.emptyAnnotationView.frame = NSMakeRect((viewFrame.size.width-emptyVcSize.width)/2.0,(viewFrame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height)
  540. self.leftSideEmptyVC.emptyAnnotationView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  541. self.noteOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyAnnotationView)
  542. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = false
  543. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = false
  544. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  545. self.noteHeaderView.isHidden = true
  546. self.toolButtonBoxLayoutConstraint.constant = 40.0
  547. }
  548. }
  549. func hideNoteEmptyView() {
  550. self.leftSideEmptyVC.emptyAnnotationView.removeFromSuperview()
  551. self.leftSideEmptyVC.exportAnnotationBtn.isEnabled = true
  552. self.leftSideEmptyVC.deleteAnnotationBtn.isEnabled = true
  553. if (self.leftView.segmentedControl.selectedSegment == KMSelectedSegmentType.annotation.rawValue) {
  554. self.noteHeaderView.isHidden = false
  555. self.toolButtonBoxLayoutConstraint.constant = 64.0
  556. }
  557. }
  558. }
  559. // MARK: - Note
  560. extension KMLeftSideViewController {
  561. func note_refrshUIIfNeed() {
  562. if self.type.methodType != .Annotation {
  563. return
  564. }
  565. Task { @MainActor in
  566. self.noteOutlineView.reloadData()
  567. }
  568. }
  569. func note_reloadDataIfNeed() {
  570. if self.type.methodType != .Annotation {
  571. return
  572. }
  573. self.reloadAnnotation()
  574. }
  575. func note_reloadDataForAnnoIfNeed(anno: CPDFAnnotation) {
  576. if self.type.methodType != .Annotation {
  577. return
  578. }
  579. if anno is CPDFLineAnnotation || anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation || anno is CPDFInkAnnotation {
  580. // 形状注释 + Ink 需要显示框住的内容【刷新】
  581. for item in self.annotations {
  582. if let data = item.annotations?.first?.annotation, data.isEqual(to: anno) {
  583. self.noteOutlineView.reloadItem(item.annotations?.first)
  584. break
  585. }
  586. }
  587. }
  588. }
  589. func reloadAnnotation() {
  590. if self.listView != nil {
  591. let filterKey = self.pdfDocument()?.documentURL.path ?? ""
  592. let typeArr: [Any] = KMBotaTools.noteFilterAnnoTypes(key: filterKey)
  593. let colorArr: [Any] = KMBotaTools.noteFilterColors(key: filterKey)
  594. let authorArr: [Any] = KMBotaTools.noteFilterAuthors(key: filterKey)
  595. if typeArr.count == 0 && colorArr.count == 0 && authorArr.count == 0 {
  596. // self.filtrateButton.image = NSImage(named: "KMImageNameAnnotationsFiltrate")
  597. self.filterButtonLayer?.isHidden = true
  598. } else {
  599. // self.filtrateButton.image = NSImage(named: "icon_annotation_screening_select")self.filterButtonLayer?.isHidden = true
  600. self.filterButtonLayer?.isHidden = false
  601. }
  602. var dataArray: [KMBOTAAnnotationSection] = []
  603. var annotationArray: [CPDFAnnotation] = []
  604. var allAnnotation: [CPDFAnnotation] = []
  605. for i in 0 ..< self.pageCount() {
  606. var items: [KMBOTAAnnotationItem] = []
  607. let page = self.pdfDocument()?.page(at: UInt(i))
  608. var annos: [CPDFAnnotation] = []
  609. // 处理过滤
  610. if typeArr.count == 0 && colorArr.count == 0 && authorArr.count == 0 {
  611. let types = ["Highlight","Underline","Strikeout","Freehand","FreeText","Note","Square","Circle","Line","Stamp","Arrow","Image","Redact","Sign"]
  612. annos = KMOCToolClass.filterAnnotation(annotations: page?.annotations ?? [],types: types) as? [CPDFAnnotation] ?? []
  613. } else {
  614. var filterAnnos: [CPDFAnnotation] = page?.annotations ?? []
  615. if typeArr.count > 0 {
  616. filterAnnos = (KMOCToolClass.filterAnnotation(annotations: filterAnnos, types: typeArr) as? [CPDFAnnotation]) ?? []
  617. }
  618. if (colorArr.count > 0) {
  619. filterAnnos = (KMOCToolClass.filterAnnotation(annotations: filterAnnos,colors: colorArr) as? [CPDFAnnotation]) ?? []
  620. }
  621. if (authorArr.count > 0) {
  622. filterAnnos = (KMOCToolClass.filterAnnotation(annotations: filterAnnos,authors: authorArr) as? [CPDFAnnotation]) ?? []
  623. }
  624. annos = filterAnnos
  625. }
  626. //添加签名注释
  627. for annotation in page?.annotations ?? [] {
  628. if annotation.isKind(of: CPDFSignatureAnnotation.self) {
  629. annos.append(annotation)
  630. }
  631. }
  632. for annotation in annos {
  633. if annotation.annotationShouldDisplay() == false {
  634. annos.removeObject(annotation)
  635. }
  636. }
  637. //转换所有annotation类型
  638. let section = KMBOTAAnnotationSection()
  639. for anno in annos {
  640. let item = KMBOTAAnnotationItem()
  641. item.section = section
  642. item.annotation = anno
  643. item.index = Int(anno.page.pageIndex())
  644. items.append(item)
  645. allAnnotation.append(anno)
  646. }
  647. if items.count != 0 {
  648. section.annotations = items
  649. section.page = page
  650. section.isItemExpanded = true
  651. dataArray.append(section)
  652. }
  653. //添加所有annotation 用于筛选
  654. annotationArray += (page?.annotations ?? [])
  655. }
  656. // 处理排序
  657. if self.noteSortType == .page {
  658. var datas: [KMBOTAAnnotationSection] = []
  659. /// 排序(升序)
  660. if self.isAscendSort {
  661. allAnnotation.sort {
  662. let idx0 = $0.page?.pageIndex() ?? 0
  663. let idx1 = $1.page?.pageIndex() ?? 0
  664. return idx0 <= idx1
  665. }
  666. } else {
  667. allAnnotation.sort {
  668. let idx0 = $0.page?.pageIndex() ?? 0
  669. let idx1 = $1.page?.pageIndex() ?? 0
  670. return idx0 > idx1
  671. }
  672. }
  673. for anno in allAnnotation {
  674. let section = KMBOTAAnnotationSection()
  675. let item = KMBOTAAnnotationItem()
  676. item.section = section
  677. item.annotation = anno
  678. item.index = Int(anno.pageIndex())
  679. section.annotations = [item]
  680. section.page = anno.page
  681. section.isItemExpanded = true
  682. datas.append(section)
  683. }
  684. self.annotations = datas
  685. } else if self.noteSortType == .time {
  686. var datas: [KMBOTAAnnotationSection] = []
  687. /// 排序(升序)
  688. if self.isAscendSort {
  689. allAnnotation.sort {
  690. if $0.modificationDate() == nil {
  691. return false
  692. }
  693. if $1.modificationDate() == nil {
  694. return false
  695. }
  696. return $0.modificationDate() <= $1.modificationDate()
  697. }
  698. } else {
  699. allAnnotation.sort {
  700. if $0.modificationDate() == nil {
  701. return false
  702. }
  703. if $1.modificationDate() == nil {
  704. return false
  705. }
  706. return $0.modificationDate() > $1.modificationDate()
  707. }
  708. }
  709. for anno in allAnnotation {
  710. let section = KMBOTAAnnotationSection()
  711. let item = KMBOTAAnnotationItem()
  712. item.section = section
  713. item.annotation = anno
  714. item.index = Int(anno.pageIndex())
  715. section.annotations = [item]
  716. section.page = anno.page
  717. section.isItemExpanded = true
  718. datas.append(section)
  719. }
  720. self.annotations = datas
  721. }
  722. // 转换对象,用于数据显示
  723. self.allAnnotations = annotationArray
  724. // if self.annotations.count < 1 {
  725. // self.filtrateButton.isEnabled = false
  726. // } else {
  727. // self.filtrateButton.isEnabled = true
  728. // }
  729. }
  730. Task { @MainActor in
  731. self.noteOutlineView.reloadData()
  732. }
  733. }
  734. // 搜索 Action
  735. func updateNoteFilterPredicate() {
  736. var stringValue = self.noteSearchField.stringValue
  737. if self.caseInsensitiveNoteSearch { // 忽略大小写
  738. stringValue = stringValue.lowercased()
  739. }
  740. // 清空数据
  741. self.noteSearchArray.removeAll()
  742. if stringValue.isEmpty {
  743. for section in self.annotations {
  744. guard let note = section.annotations?.first?.annotation else {
  745. continue
  746. }
  747. self.noteSearchArray.append(note)
  748. }
  749. } else {
  750. for section in self.annotations {
  751. guard let note = section.annotations?.first?.annotation else {
  752. continue
  753. }
  754. var noteString = KMBOTAAnnotationTool.fetchContentLabelString(annotation: note)
  755. if let anno = note as? CPDFMarkupAnnotation {
  756. noteString = anno.markupContent()
  757. }
  758. if self.caseInsensitiveNoteSearch {
  759. noteString = noteString.lowercased()
  760. }
  761. if noteString.contains(stringValue) {
  762. self.noteSearchArray.append(note)
  763. }
  764. }
  765. }
  766. // 刷新 UI
  767. Task { @MainActor in
  768. self.noteOutlineView.reloadData()
  769. }
  770. }
  771. @objc func selectSelectedNote(_ sender: AnyObject?) {
  772. if self.hideNotes() == false {
  773. let selectedNotes = self.selectedNotes()
  774. if selectedNotes.count == 1 {
  775. let annotation = selectedNotes.last!
  776. self.listView?.go(to: annotation.bounds, on: annotation.page, animated: true)
  777. // [pdfView scrollAnnotationToVisible:annotation];
  778. // [pdfView setActiveAnnotation:annotation];
  779. self.listView?.updateActiveAnnotations([annotation])
  780. self.listView?.setNeedsDisplayAnnotationViewForVisiblePages()
  781. // }
  782. }
  783. // NSInteger column = [sender clickedColumn];
  784. // if (column != -1) {
  785. // NSString *colID = [[[sender tableColumns] objectAtIndex:column] identifier];
  786. //
  787. // if ([colID isEqualToString:@"color"]){
  788. // for (PDFAnnotation *annotation in self.pdfView.activeAnnotations) {
  789. // if (![annotation isKindOfClass:[PDFAnnotationChoiceWidget class]] &&
  790. // ![annotation isKindOfClass:[PDFAnnotationButtonWidget class]] &&
  791. // ![annotation isKindOfClass:[PDFAnnotationTextWidget class]]) {
  792. // [[NSColorPanel sharedColorPanel] orderFront:nil];
  793. // break;
  794. // }
  795. //
  796. // }
  797. // }
  798. // }
  799. }
  800. }
  801. func selectedNotes() -> [CPDFAnnotation] {
  802. var selectedNotes: [CPDFAnnotation] = []
  803. let rowIndexes = self.noteOutlineView.selectedRowIndexes
  804. for row in rowIndexes {
  805. let item = self.noteOutlineView.item(atRow: row)
  806. if item is KMBOTAAnnotationItem {
  807. if let anno = (item as! KMBOTAAnnotationItem).annotation {
  808. // if anno.type == nil {
  809. // item = [(SKNoteText *)item note];
  810. // }
  811. if selectedNotes.contains(anno) == false {
  812. selectedNotes.append(anno)
  813. }
  814. }
  815. }
  816. }
  817. return selectedNotes
  818. }
  819. func clearAnnotationFilterData() {
  820. if let _key = self.pdfDocument()?.documentURL?.path {
  821. let userDefaults = UserDefaults.standard
  822. let typeData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  823. userDefaults.set(typeData, forKey: NoteFilterVC.filterSelectTypeKey + _key)
  824. let colorData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  825. userDefaults.set(colorData, forKey: NoteFilterVC.filterSelectColorKey + _key)
  826. let authorData = try?NSKeyedArchiver.archivedData(withRootObject: [Any](), requiringSecureCoding: false)
  827. userDefaults.set(authorData, forKey: NoteFilterVC.filterSelectAuthorKey + _key)
  828. userDefaults.synchronize()
  829. }
  830. }
  831. func loadUnfoldDate(_ foldType: KMFoldType) {
  832. // 清空所有折叠数组
  833. self.allFoldNotes.removeAll()
  834. var mutableArray: [CPDFAnnotation] = []
  835. if self.noteSearchMode {
  836. for note in self.noteSearchArray {
  837. if note is CPDFMarkupAnnotation {
  838. mutableArray.append(note)
  839. }
  840. }
  841. } else {
  842. for section in self.annotations {
  843. for item in section.annotations ?? [] {
  844. if let note = item.annotation, note is CPDFMarkupAnnotation {
  845. mutableArray.append(note)
  846. }
  847. }
  848. }
  849. }
  850. // for note in self.notes {
  851. // if note is CPDFMarkupAnnotation {
  852. // mutableArray.append(note)
  853. // }
  854. // }
  855. self.canFoldNotes = mutableArray
  856. self.allFoldNotes = []
  857. }
  858. }