KMAnnotationViewController.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. //
  2. // KMAnnotationViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lxy on 2022/10/10.
  6. //
  7. import Cocoa
  8. enum KMAnnotationViewShowType: Int {
  9. case none
  10. case hidden
  11. }
  12. class KMAnnotationViewController: KMSideViewController {
  13. @IBOutlet weak var topView: NSView!
  14. @IBOutlet weak var filtrateButton: NSButton!
  15. @IBOutlet weak var moreButton: NSButton!
  16. @IBOutlet weak var markupTitleLabel: NSTextField!
  17. @IBOutlet weak var emptyView: NSView!
  18. @IBOutlet weak var bigTipLabel: NSTextField!
  19. @IBOutlet weak var tipLabel: NSTextField!
  20. @IBOutlet weak var annotationOutlineView: KMAnnotationOutlineView!
  21. var annotations: [KMBOTAAnnotationSection] = [] {
  22. didSet {
  23. self.annotationOutlineView.inputData = annotations
  24. self.updateExtempViewState()
  25. }
  26. }
  27. var screenAnnotations: [KMBOTAAnnotationSection] = [] {
  28. didSet {
  29. self.annotations = screenAnnotations
  30. }
  31. }
  32. //注释状态
  33. var annotationShowState: KMAnnotationViewShowType = .none {
  34. didSet {
  35. self.reloadData()
  36. }
  37. }
  38. var allAnnotations: [CPDFAnnotation] = []
  39. //localEvent
  40. var localEvent: Bool = false
  41. deinit {
  42. KMPrint("KMAnnotationViewController")
  43. self.removeNotification()
  44. }
  45. //MARK: View
  46. override func viewDidLoad() {
  47. super.viewDidLoad()
  48. self.setup()
  49. self.updateUI()
  50. self.updateLanguage()
  51. self.addNotification()
  52. self.reloadData()
  53. }
  54. func setup() {
  55. self.view.wantsLayer = true
  56. self.view.layer?.backgroundColor = NSColor.km_init(hex: "#F7F8FA").cgColor
  57. self.emptyView.backgroundColor(NSColor.km_init(hex: "#F7F8FA"))
  58. self.topView.wantsLayer = true
  59. self.topView.layer?.backgroundColor = NSColor.clear.cgColor
  60. self.annotationOutlineView.outlineView.doubleAction = #selector(tableViewDoubleAction)
  61. self.annotationOutlineView.delegate = self
  62. }
  63. func updateUI() {
  64. self.markupTitleLabel.font = NSFont.SFProTextSemiboldFont(14.0)
  65. self.markupTitleLabel.textColor = NSColor.km_init(hex: "#252629")
  66. self.bigTipLabel.font = NSFont.SFProTextRegularFont(14.0)
  67. self.bigTipLabel.textColor = NSColor.km_init(hex: "#616469")
  68. if self.annotationShowState == .none {
  69. } else {
  70. self.bigTipLabel.font = NSFont.SFProTextRegularFont(12.0)
  71. self.bigTipLabel.textColor = NSColor.km_init(hex: "#94989C")
  72. }
  73. }
  74. func updateLanguage() {
  75. self.markupTitleLabel.stringValue = NSLocalizedString("Annotation", comment: "")
  76. self.filtrateButton.toolTip = NSLocalizedString("Sort", comment: "")
  77. self.moreButton.toolTip = NSLocalizedString("More", comment: "")
  78. if self.annotationShowState == .none {
  79. self.bigTipLabel.stringValue = NSLocalizedString("No Annotations", comment: "")
  80. let title = NSLocalizedString("All annotations will be displayed here.", comment: "")
  81. let paragraphStyle = NSMutableParagraphStyle()
  82. paragraphStyle.lineHeightMultiple = 1.32
  83. paragraphStyle.alignment = .center
  84. self.tipLabel.attributedStringValue = NSMutableAttributedString(string: title, attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle, .foregroundColor : NSColor.km_init(hex: "#94989C"), NSAttributedString.Key.font: NSFont.SFProTextRegularFont(12)])
  85. } else {
  86. self.bigTipLabel.stringValue = NSLocalizedString("The Annotations are hidden", comment: "")
  87. self.tipLabel.stringValue = ""
  88. }
  89. }
  90. func addNotification() {
  91. NotificationCenter.default.addObserver(self, selector: #selector(documentPageCountChangedNotification), name: NSNotification.Name.init(rawValue: "CPDFDocumentPageCountChangedNotification"), object: nil)
  92. NotificationCenter.default.addObserver(self, selector: #selector(CPDFListViewActiveAnnotationsChangeNotification), name: NSNotification.Name.init(rawValue: "CPDFListViewActiveAnnotationsChangeNotification"), object: nil)
  93. NotificationCenter.default.addObserver(self, selector: #selector(CPDFListViewAnnotationsAttributeHasChangeNotification), name: NSNotification.Name.init(rawValue: "CPDFListViewAnnotationsAttributeHasChangeNotification"), object: nil)
  94. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataAfter), name: NSNotification.Name.init(rawValue: "CPDFPageDidAddAnnotationNotification"), object: nil)
  95. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataAfter), name: NSNotification.Name.init(rawValue: "CPDFPageDidRemoveAnnotationNotification"), object: nil)
  96. }
  97. func removeNotification() {
  98. NotificationCenter.default.removeObserver(self)
  99. }
  100. public func clear() {
  101. self.annotations.removeAll()
  102. self.annotationOutlineView.reloadData()
  103. }
  104. }
  105. //MARK: Data
  106. extension KMAnnotationViewController {
  107. @objc public func reloadData() {
  108. // self.reloadAnnotation()
  109. // self.annotationSort(sortArray: [])
  110. }
  111. func reloadAnnotation() {
  112. if self.listView != nil {
  113. var dataArray: [KMBOTAAnnotationSection] = []
  114. var annotationArray: [CPDFAnnotation] = []
  115. for i in 0 ..< self.pageCount() {
  116. var annotationItemArray: [KMBOTAAnnotationItem] = []
  117. let page = self.pdfDocument()?.page(at: UInt(i))
  118. let types = ["Highlight","Underline","Strikeout","Freehand","FreeText","Note","Square","Circle","Line","Stamp","Arrow","Image","Redact","Sign"]
  119. var pageAnnotations: [CPDFAnnotation] = KMOCToolClass.filterAnnotation(annotations: page!.annotations,types: types) as! [CPDFAnnotation]
  120. //添加签名注释
  121. for annotation in page!.annotations {
  122. if annotation.isKind(of: CPDFSignatureAnnotation.self) {
  123. pageAnnotations.append(annotation)
  124. }
  125. }
  126. for annotation in pageAnnotations {
  127. if annotation.annotationShouldDisplay() == false {
  128. pageAnnotations.removeObject(annotation)
  129. }
  130. }
  131. //转换所有annotation类型
  132. let section = KMBOTAAnnotationSection()
  133. for annotation in pageAnnotations {
  134. let item = KMBOTAAnnotationItem()
  135. item.section = section
  136. item.annotation = annotation
  137. item.index = Int(annotation.page.pageIndex())
  138. annotationItemArray.append(item)
  139. }
  140. if annotationItemArray.count != 0 {
  141. section.annotations = annotationItemArray
  142. section.page = page
  143. section.isItemExpanded = true
  144. dataArray.append(section)
  145. }
  146. //添加所有annotation 用于筛选
  147. annotationArray += pageAnnotations
  148. }
  149. //转换对象,用于数据显示
  150. self.annotations = dataArray
  151. self.allAnnotations = annotationArray
  152. if self.annotations.count < 1 {
  153. self.filtrateButton.isEnabled = false
  154. } else {
  155. self.filtrateButton.isEnabled = true
  156. }
  157. }
  158. }
  159. func annotationSort(sortArray:[[Any]]) {
  160. if self.listView != nil {
  161. var typeArr: [Any] = []
  162. var colorArr: [Any] = []
  163. var authorArr: [Any] = []
  164. let sud = UserDefaults.standard
  165. let typeData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Type" + (self.pdfDocument()?.documentURL.path ?? "")) as? Data
  166. if typeData != nil {
  167. typeArr = NSKeyedUnarchiver.unarchiveObject(with: typeData!) as! [Any]
  168. }
  169. let colorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Color" + (self.pdfDocument()?.documentURL.path ?? "")) as? Data
  170. if colorData != nil {
  171. colorArr = NSKeyedUnarchiver.unarchiveObject(with: colorData!) as! [Any]
  172. }
  173. let authorData = sud.object(forKey: "KMNoteOutlineFilterSelectArray_Author" + (self.pdfDocument()?.documentURL.path ?? "")) as? Data
  174. if authorData != nil {
  175. authorArr = NSKeyedUnarchiver.unarchiveObject(with: authorData!) as! [Any]
  176. }
  177. if typeArr.count == 0 && colorArr.count == 0 && authorArr.count == 0 {
  178. self.filtrateButton.image = NSImage(named: "KMImageNameAnnotationsFiltrate")
  179. self.reloadAnnotation()
  180. } else {
  181. self.filtrateButton.image = NSImage(named: "icon_annotation_screening_select")
  182. var dataArray: [KMBOTAAnnotationSection] = []
  183. for i in 0 ..< self.pageCount() {
  184. var annotationItemArray: [KMBOTAAnnotationItem] = []
  185. let page = self.listView?.document?.page(at: UInt(i))
  186. if page!.annotations.count > 0 {
  187. var filterAnnotations: [CPDFAnnotation] = page!.annotations
  188. if typeArr.count > 0 {
  189. filterAnnotations = (KMOCToolClass.filterAnnotation(annotations: filterAnnotations, types: typeArr) as! [CPDFAnnotation])
  190. }
  191. if (colorArr.count > 0) {
  192. filterAnnotations = (KMOCToolClass.filterAnnotation(annotations: filterAnnotations,colors: colorArr) as! [CPDFAnnotation])
  193. }
  194. if (authorArr.count > 0) {
  195. filterAnnotations = (KMOCToolClass.filterAnnotation(annotations: filterAnnotations,authors: authorArr) as! [CPDFAnnotation])
  196. }
  197. let section = KMBOTAAnnotationSection()
  198. for annotation in filterAnnotations {
  199. let item = KMBOTAAnnotationItem()
  200. item.section = section
  201. item.annotation = annotation
  202. item.index = Int(page!.pageIndex())
  203. annotationItemArray.append(item)
  204. }
  205. if annotationItemArray.count != 0 {
  206. section.annotations = annotationItemArray
  207. section.page = page
  208. section.isItemExpanded = true
  209. dataArray.append(section)
  210. }
  211. }
  212. }
  213. self.annotations = dataArray
  214. }
  215. }
  216. }
  217. }
  218. //MARK: reloadData
  219. extension KMAnnotationViewController {
  220. func updateExtempViewState() {
  221. if self.emptyView != nil {
  222. var hidden = false
  223. if self.annotationOutlineView.outlineView.numberOfRows != 0 {
  224. hidden = true
  225. }
  226. self.emptyView.isHidden = hidden
  227. self.annotationOutlineView.isHidden = !hidden
  228. //刷新
  229. self.updateUI()
  230. self.updateLanguage()
  231. }
  232. }
  233. }
  234. //MARK: Notification
  235. extension KMAnnotationViewController {
  236. @objc public func reloadDataAfter() {
  237. if !localEvent {
  238. let rect = self.annotationOutlineView.outlineView.visibleRect
  239. self.reloadData()
  240. self.annotationOutlineView.outlineView.scrollToVisible(rect)
  241. }
  242. // localEvent = false
  243. }
  244. @objc func documentPageCountChangedNotification(notification: NSNotification) {
  245. if notification.object is CPDFDocument {
  246. let pdfdocument : CPDFDocument = notification.object as! CPDFDocument
  247. if pdfdocument.isEqual(self.listView?.document) {
  248. if !localEvent {
  249. self.reloadData()
  250. }
  251. // localEvent = false
  252. }
  253. }
  254. }
  255. @objc func CPDFListViewActiveAnnotationsChangeNotification(notification: NSNotification) {
  256. if notification.object is CPDFListView {
  257. let listView : CPDFListView = notification.object as! CPDFListView
  258. if listView.isEqual(self.listView) {
  259. if self.listView?.activeAnnotations.count == 0 {
  260. self.escButtonAction(Any.self)
  261. } else {
  262. if !localEvent {
  263. let tempAnnotations : [CPDFAnnotation] = self.listView?.activeAnnotations as! [CPDFAnnotation]
  264. var indexset = IndexSet()
  265. for annotation in tempAnnotations {
  266. if self.annotations.count > 0 {
  267. for section in self.annotations {
  268. for item in section.annotations! {
  269. if item.annotation == annotation {
  270. let index = self.annotationOutlineView.outlineView.row(forItem: item)
  271. indexset.insert(index)
  272. }
  273. }
  274. }
  275. }
  276. }
  277. if indexset.count != 0 && indexset.first != -1 {
  278. self.annotationOutlineView.outlineView.selectRowIndexes(indexset, byExtendingSelection: false)
  279. self.annotationOutlineView.didSelectItem(view: nil, event: NSEvent(), isNeedDelegate: false)
  280. }
  281. }
  282. // localEvent = false
  283. }
  284. }
  285. }
  286. }
  287. @objc func CPDFListViewAnnotationsAttributeHasChangeNotification(notification: NSNotification) {
  288. if notification.object != nil {
  289. let dic = notification.object as? NSDictionary
  290. if dic?["keyPath"] as! String != CPDFAnnotationBoundsKey &&
  291. dic?["keyPath"] as! String != CPDFAnnotationStartPointKey &&
  292. dic?["keyPath"] as! String != CPDFAnnotationEndPointKey{
  293. if dic?["object"] is CPDFAnnotation {
  294. let annotation : CPDFAnnotation = dic?["object"] as? CPDFAnnotation ?? CPDFAnnotation()
  295. for section in self.annotations {
  296. for (_, item) in section.annotations!.enumerated() {
  297. if item.annotation == annotation {
  298. let row = self.annotationOutlineView.outlineView.row(forItem: item)
  299. let indexSet = IndexSet.init(integer: row)
  300. self.annotationOutlineView.outlineView.noteHeightOfRows(withIndexesChanged: indexSet)
  301. self.annotationOutlineView.outlineView.reloadItem(item)
  302. break
  303. }
  304. }
  305. }
  306. }
  307. }
  308. }
  309. }
  310. }
  311. //MARK: Action
  312. extension KMAnnotationViewController {
  313. @IBAction func tableViewDoubleAction(_ sender: Any) {
  314. if self.annotationOutlineView.selectItems.count > 1 {
  315. return
  316. }
  317. let selectedRow = self.annotationOutlineView.outlineView.selectedRow
  318. if selectedRow >= 0 {
  319. let annotationItem = self.annotationOutlineView.outlineView.item(atRow: selectedRow)
  320. if (annotationItem is KMBOTAAnnotationItem) {
  321. let annotation = (annotationItem as! KMBOTAAnnotationItem).annotation
  322. self.listView?.go(to: annotation!.bounds, on: annotation!.page, animated: true)
  323. }
  324. }
  325. }
  326. @IBAction func moreButtonAction(_ sender: NSButton) {
  327. self.addMoreMenu(sender: sender)
  328. }
  329. @IBAction func filtrateButtonAction(_ sender: NSButton) {
  330. let menu = NSMenu()
  331. let annotationScreenView = KMAnnotationScreenCollectionView(frame: CGRect(x: 0, y: 0, width: 304, height: 296))
  332. annotationScreenView.path = self.listView?.document.documentURL.path ?? ""
  333. annotationScreenView.annotations = self.allAnnotations
  334. annotationScreenView.applyAction = { [weak self] (view, typeArray, colorArray, authArray) in
  335. menu.cancelTracking()
  336. self?.annotationSort(sortArray: [typeArray, colorArray, authArray])
  337. }
  338. annotationScreenView.cancelAction = { [weak self] view in
  339. menu.cancelTracking()
  340. }
  341. let item = menu.addItem(withTitle: "", action: nil, keyEquivalent: "")
  342. item.target = self
  343. // item.representedObject = filterVC
  344. item.view = annotationScreenView
  345. menu.popUp(positioning: nil, at: CGPoint(x: -130, y: 30), in: sender)
  346. }
  347. @IBAction func deleteButtonAction(_ sender: Any) {
  348. let alert = NSAlert()
  349. alert.alertStyle = .critical
  350. alert.messageText = NSLocalizedString("This will permanently remove all annotations. Are you sure to continue?", comment: "")
  351. alert.informativeText = NSLocalizedString("You cannot undo this operation.", comment: "")
  352. alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
  353. alert.addButton(withTitle: NSLocalizedString("No", comment: ""))
  354. alert.beginSheetModal(for: self.view.window!, completionHandler: { result in
  355. if result == .OK {
  356. for i in 0 ..< self.pageCount() {
  357. let page = self.listView?.document?.page(at: UInt(i))
  358. page?.removeAllAnnotations()
  359. }
  360. // let undoManager : UndoManager = self.mainWindowController.document?.undoManager ?? UndoManager()
  361. // undoManager.setActionName("")
  362. self.listView?.updateActiveAnnotations([CPDFAnnotation()])
  363. self.listView?.setNeedsDisplayForVisiblePages()
  364. self.reloadData()
  365. }
  366. })
  367. }
  368. //
  369. @IBAction func flattenButtonAction(_ sender: NSMenuItem) {
  370. let selects = sender.representedObject as! NSIndexSet
  371. var indexs : [Int] = []
  372. for index in selects {
  373. indexs.append(index)
  374. }
  375. if selects.count == 1 {
  376. let index = selects.firstIndex
  377. let annotationItem: KMBOTAAnnotationItem = self.annotationOutlineView.outlineView.item(atRow: index) as! KMBOTAAnnotationItem
  378. if annotationItem.annotation != nil {
  379. if annotationItem.annotation!.contents?.lengthOfBytes(using: String.Encoding(rawValue: String.Encoding.utf16.rawValue)) ?? 0 > 0 {
  380. var content: String = annotationItem.annotation!.contents!
  381. let item: CPDFMarkupAnnotation = annotationItem.annotation! as? CPDFMarkupAnnotation ?? CPDFMarkupAnnotation()
  382. if item.markupText() != nil {
  383. KMPrint(item.markupText() as Any)
  384. content = content + "\n" + (item.markupText() ?? "")
  385. }
  386. let pasteBoard = NSPasteboard.general
  387. pasteBoard.clearContents()
  388. pasteBoard.setString(content, forType: .string)
  389. }
  390. }
  391. }
  392. }
  393. //
  394. @IBAction func exportItemAction(_ sender: Any) {
  395. let panel = NSSavePanel()
  396. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).xfdf"
  397. panel.isExtensionHidden = true
  398. let response = panel.runModal()
  399. if response == .OK {
  400. let url = panel.url
  401. let result = self.listView?.document.exportAnnotation(toXFDFPath: url!.path) ?? false
  402. if result {
  403. // NSWorkspace.shared.openFile(url!.path.deletingLastPathComponent)
  404. // NSWorkspace.shared.open(url!)
  405. let filePath = url!.path // 要打开的文件路径
  406. let fileURL = URL(fileURLWithPath: filePath)
  407. let fileDirectoryURL = fileURL.deletingLastPathComponent() // 获取文件所在的文件夹路径
  408. NSWorkspace.shared.activateFileViewerSelecting([fileDirectoryURL])
  409. }
  410. }
  411. }
  412. //
  413. @IBAction func importItemAction(_ sender: Any) {
  414. let panel = NSOpenPanel()
  415. panel.allowsMultipleSelection = false
  416. panel.allowedFileTypes = ["xfdf"]
  417. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  418. if response == .OK {
  419. let openPath = panel.url?.path
  420. let result = self.listView?.document.importAnnotation(fromXFDFPath: openPath!) ?? false
  421. if result {
  422. self.listView?.setNeedsDisplayAnnotationViewForVisiblePages()
  423. self.reloadData()
  424. }
  425. }
  426. }
  427. }
  428. //
  429. @IBAction func deleteItemAction(_ sender: NSMenuItem) {
  430. let selects = sender.representedObject as! NSIndexSet
  431. var indexs : [KMBOTAAnnotationItem] = []
  432. for index in selects {
  433. if self.annotationOutlineView.outlineView.item(atRow: index) is KMBOTAAnnotationItem {
  434. let annotationItem: KMBOTAAnnotationItem = self.annotationOutlineView.outlineView.item(atRow: index) as! KMBOTAAnnotationItem
  435. annotationItem.index = index
  436. indexs.append(annotationItem)
  437. }
  438. }
  439. indexs.sort(){$0.index! > $1.index!}
  440. self.deleteAnnotations(annotationItems: indexs)
  441. }
  442. //
  443. @IBAction func deleteAllAnonationAction(_ sender: NSMenuItem) {
  444. let alter = NSAlert()
  445. alter.alertStyle = NSAlert.Style.informational
  446. alter.messageText = NSLocalizedString("This will permanently remove all annotations. Are you sure to continue?", comment: "")
  447. alter.addButton(withTitle: NSLocalizedString("Yes", comment:""))
  448. alter.addButton(withTitle: NSLocalizedString("No", comment:""))
  449. let modlres = alter.runModal()
  450. if modlres == NSApplication.ModalResponse.alertFirstButtonReturn {
  451. // for i in 0 ..< self.listView.document.pageCount {
  452. // let page = self.listView.document.page(at: i)
  453. // for annotation in page!.annotations {
  454. // page?.removeAnnotation(annotation)
  455. //
  456. // }
  457. // }
  458. // self.listView.setNeedsDisplayForVisiblePages()
  459. // self.reloadData()
  460. var indexs : [KMBOTAAnnotationItem] = []
  461. for section in self.annotations {
  462. indexs.append(contentsOf: section.annotations!)
  463. }
  464. indexs.sort(){$0.index! > $1.index!}
  465. self.deleteAnnotations(annotationItems: indexs)
  466. }
  467. }
  468. //
  469. @IBAction func escButtonAction(_ sender: Any) {
  470. self.cancelSelect()
  471. }
  472. //
  473. func cancelSelect() {
  474. self.annotationOutlineView.cancelSelect()
  475. }
  476. //
  477. func selectItem(index: Int) {
  478. self.annotationOutlineView.outlineView.selectRowIndexes(IndexSet(integer: index), byExtendingSelection: false)
  479. self.annotationOutlineView.didSelectItem(view: nil, event: NSEvent(), isNeedDelegate: false)
  480. }
  481. func updateListViewData(annotationItems: [KMBOTAAnnotationItem]) {
  482. if annotationItems.count > 0 {
  483. if annotationItems.count == 1 {
  484. let annotationItem = annotationItems.first!
  485. if annotationItem.annotation != nil {
  486. self.listView?.go(to: annotationItem.annotation!.bounds, on: annotationItem.annotation!.page, animated: true)
  487. }
  488. }
  489. var annotations: [CPDFAnnotation] = []
  490. for item in annotationItems {
  491. if item.annotation != nil {
  492. annotations.append(item.annotation!)
  493. }
  494. }
  495. self.listView?.updateActiveAnnotations(annotations)
  496. self.listView?.setNeedsDisplayAnnotationViewForVisiblePages()
  497. }
  498. }
  499. }
  500. extension KMAnnotationViewController: KMAnnotationOutlineViewDelegate {
  501. func annotationOutlineView(_ outlineView: KMAnnotationOutlineView, rightMouseDownDidSelectView: NSView, evnet: NSEvent) {
  502. self.addRightMenuItem(view: rightMouseDownDidSelectView, event: evnet)
  503. }
  504. func annotationOutlineView(_ outlineView: KMAnnotationOutlineView, didReloadData: KMBOTAOutlineItem) {
  505. }
  506. func annotationOutlineView(_ outlineView: KMAnnotationOutlineView, didSelectItem: [KMBOTAAnnotationItem]) {
  507. self.localEvent = true
  508. self.updateListViewData(annotationItems: didSelectItem)
  509. self.localEvent = false
  510. }
  511. }
  512. //MARK: Menu
  513. extension KMAnnotationViewController : NSMenuDelegate, NSMenuItemValidation {
  514. @objc private func expandAllComments(sender:NSMenuItem) {
  515. self.annotationOutlineView.expandAllComments(item: sender)
  516. }
  517. @objc private func collapseAllComments(sender:NSMenuItem) {
  518. self.annotationOutlineView.collapseAllComments(item: sender)
  519. }
  520. // @objc private func expandAllComments(sender:NSMenuItem) {
  521. // if sender.tag == 0 {
  522. // self.annotationOutlineView.expandAllComments(item: sender)
  523. // } else if sender.tag == 1 {
  524. // self.annotationOutlineView.collapseAllComments(item: sender)
  525. // } else if sender.tag == 2 {
  526. // let alter = NSAlert()
  527. // alter.alertStyle = NSAlert.Style.informational
  528. // alter.messageText = NSLocalizedString("This will permanently remove all outlines. Are you sure to continue?", comment: "")
  529. // alter.addButton(withTitle: NSLocalizedString("Yes", comment:""))
  530. // alter.addButton(withTitle: NSLocalizedString("No", comment:""))
  531. // let modlres = alter.runModal()
  532. // if modlres == NSApplication.ModalResponse.alertFirstButtonReturn {
  533. // self.deleteAllAnonationAction(sender)
  534. // }
  535. // }
  536. // }
  537. func addRightMenuItem(view: NSView, event: NSEvent) {
  538. let menu = NSMenu()
  539. menu.delegate = self
  540. let selectedRowIndexes = self.annotationOutlineView.outlineView.selectedRowIndexes
  541. var menuItem = NSMenuItem()
  542. if selectedRowIndexes.count == 1 {
  543. let item: KMBOTAAnnotationItem = self.annotationOutlineView.outlineView.item(atRow: selectedRowIndexes.first!) as! KMBOTAAnnotationItem
  544. if item.annotation != nil {
  545. if item.annotation!.contents != nil {
  546. if item.annotation!.contents.count > 0 {
  547. menuItem = menu.addItem(withTitle: NSLocalizedString("Copy Text", comment: ""), action: #selector(flattenButtonAction), target: self)!
  548. menuItem.representedObject = selectedRowIndexes
  549. menu.addItem(NSMenuItem.separator())
  550. }
  551. }
  552. }
  553. }
  554. menuItem = menu.addItem(withTitle: NSLocalizedString("Export Annotation", comment: ""), action: #selector(exportItemAction), target: self)!
  555. if self.annotationOutlineView.selectItems.count == 1 {
  556. menuItem = menu.addItem(withTitle: NSLocalizedString("Import Annotation", comment: ""), action: #selector(importItemAction), target: self)!
  557. }
  558. menu.addItem(NSMenuItem.separator())
  559. menuItem = menu.addItem(withTitle: NSLocalizedString("Delete", comment: ""), action: #selector(deleteItemAction), target: self)!
  560. menuItem.representedObject = selectedRowIndexes
  561. menu.addItem(NSMenuItem.separator())
  562. let point = view.convert(event.locationInWindow, from: nil)
  563. menu.popUp(positioning: nil, at: point, in: view)
  564. }
  565. func addMoreMenu(sender: NSView) {
  566. let moreMenu = NSMenu()
  567. _ = moreMenu.addItem(withTitle: NSLocalizedString("Expand All", comment: ""), action: #selector(expandAllComments), target: self, tag: 0)
  568. _ = moreMenu.addItem(withTitle: NSLocalizedString("Collapse All", comment: ""), action: #selector(collapseAllComments), target: self, tag: 1)
  569. // let soreItem = moreMenu.addItem(withTitle: NSLocalizedString("Sort", comment: ""), action: nil, target: self)
  570. // let soreMenu = NSMenu()
  571. // soreMenu.addItem(withTitle: NSLocalizedString("Page", comment: ""), action: #selector(expandAllComments), target: self, tag: 0)
  572. // soreMenu.addItem(withTitle: NSLocalizedString("Chronologically - ascending", comment: ""), action: #selector(expandAllComments), target: self, tag: 1)
  573. // soreMenu.addItem(withTitle: NSLocalizedString("Chronologically - reverse", comment: ""), action: #selector(expandAllComments), target: self, tag: 0)
  574. // soreItem?.submenu = soreMenu
  575. _ = moreMenu.addItem(withTitle: NSLocalizedString("Import Annotations", comment: ""), action: #selector(importItemAction), target: self)
  576. _ = moreMenu.addItem(withTitle: NSLocalizedString("Export Annotations to XFDF", comment: ""), action: #selector(exportItemAction), target: self)
  577. _ = moreMenu.addItem(withTitle: NSLocalizedString("Remove All Annotations", comment: ""), action: #selector(deleteAllAnonationAction), target: self)
  578. let rect = sender.convert(sender.bounds, to: self.view)
  579. moreMenu.popUp(positioning: nil, at: NSPoint(x: rect.origin.x, y: rect.origin.y-10), in: self.view)
  580. }
  581. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  582. let action = menuItem.action
  583. if (action == #selector(undo)) {
  584. return self.listView?.undoManager?.canUndo ?? false
  585. }
  586. if (action == #selector(redo)) {
  587. return self.listView?.undoManager?.canRedo ?? false
  588. }
  589. if (action == #selector(flattenButtonAction)) {
  590. if self.annotationOutlineView.selectItems.count != 1 {
  591. return false
  592. }
  593. }
  594. if (action == #selector(deleteAllAnonationAction)) {
  595. if self.annotations.count == 0 {
  596. return false
  597. }
  598. }
  599. if action == #selector(exportItemAction) {
  600. if self.annotations.count == 0 {
  601. return false
  602. }
  603. }
  604. if action == #selector(exportItemAction) {
  605. if self.annotations.count == 0 {
  606. return false
  607. }
  608. }
  609. if (action == #selector(expandAllComments)) {
  610. var canExpand = false
  611. for row in 0..<self.annotationOutlineView.outlineView.numberOfRows {
  612. // 检查当前项目是否可以展开
  613. let item = self.annotationOutlineView.outlineView.item(atRow: row)
  614. if self.annotationOutlineView.outlineView.isExpandable(item) {
  615. if !self.annotationOutlineView.outlineView.isItemExpanded(item) {
  616. canExpand = true
  617. break
  618. }
  619. }
  620. }
  621. return canExpand
  622. }
  623. if (action == #selector(collapseAllComments)) {
  624. var canCollapse = false
  625. for row in 0..<self.annotationOutlineView.outlineView.numberOfRows {
  626. let item = self.annotationOutlineView.outlineView.item(atRow: row)
  627. if self.annotationOutlineView.outlineView.isExpandable(item) {
  628. if self.annotationOutlineView.outlineView.isItemExpanded(item) {
  629. canCollapse = true
  630. break
  631. }
  632. }
  633. }
  634. return canCollapse
  635. }
  636. return true
  637. }
  638. }
  639. //MARK: undo Redo
  640. extension KMAnnotationViewController {
  641. func deleteAnnotations(annotationItems: [KMBOTAAnnotationItem]) {
  642. self.removeNotification()
  643. self.localEvent = true
  644. var removeAnnotations: [Any] = []
  645. var tempAnnotations: [KMBOTAAnnotationItem] = []
  646. for annotationItem in annotationItems {
  647. let annotation = annotationItem.annotation
  648. annotationItem.index = annotationItem.section?.annotations?.firstIndex(of: annotationItem)
  649. let page = annotation?.page
  650. if ((page?.annotations.contains(annotation!)) != nil) {
  651. page?.removeAnnotation(annotation)
  652. annotationItem.section?.annotations?.removeObject(annotationItem)
  653. } else {
  654. KMPrint("不存在")
  655. }
  656. if let data = self.listView?.activeAnnotations.contains(annotation!), data {
  657. removeAnnotations.append(annotation!)
  658. }
  659. if annotation != nil {
  660. tempAnnotations.append(annotationItem)
  661. }
  662. }
  663. if removeAnnotations.count != 0 {
  664. self.listView?.activeAnnotations.remove(removeAnnotations)
  665. }
  666. self.listView?.setNeedsDisplayForVisiblePages()
  667. self.annotationOutlineView.reloadData(expandItemType: .none)
  668. self.updateExtempViewState()
  669. self.listView?.undoManager?.registerUndo(withTarget: self) { [weak self] targetType in
  670. self?.addAnnotations(annotationItems: tempAnnotations)
  671. }
  672. self.addNotification()
  673. self.localEvent = false
  674. }
  675. func addAnnotations(annotationItems: [KMBOTAAnnotationItem]) {
  676. self.removeNotification()
  677. self.localEvent = true
  678. var tempAnnotationItems: [KMBOTAAnnotationItem] = annotationItems
  679. tempAnnotationItems.sort(){$0.index ?? 0 < $1.index ?? 0}
  680. for annotationItem in tempAnnotationItems {
  681. if !annotationItem.annotation!.page.annotations.contains(annotationItem.annotation!) {
  682. annotationItem.annotation?.page.addAnnotation(annotationItem.annotation!)
  683. annotationItem.section?.annotations?.insert(annotationItem, at: annotationItem.index ?? 0)
  684. }
  685. }
  686. self.listView?.setNeedsDisplayForVisiblePages()
  687. self.annotationOutlineView.reloadData(expandItemType: .none)
  688. if tempAnnotationItems.count != 0 {
  689. let row = self.annotationOutlineView.outlineView.row(forItem: tempAnnotationItems.last)
  690. self.annotationOutlineView.outlineView.scrollRowToVisible(row)
  691. }
  692. self.updateExtempViewState()
  693. let tempAnnotations: [KMBOTAAnnotationItem] = tempAnnotationItems
  694. self.listView?.undoManager?.registerUndo(withTarget: self) { [weak self] targetType in
  695. self?.deleteAnnotations(annotationItems: tempAnnotations)
  696. }
  697. self.addNotification()
  698. self.localEvent = false
  699. }
  700. @IBAction func undo(_ sender: Any) {
  701. if (self.listView?.undoManager?.canUndo ?? false) {
  702. self.listView?.undoManager?.undo()
  703. }
  704. }
  705. @IBAction func redo(_ sender: Any) {
  706. if (self.listView?.undoManager?.canRedo ?? false) {
  707. self.listView?.undoManager?.redo()
  708. }
  709. }
  710. }