KMAnnotationViewController.swift 35 KB

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