KMLeftSideViewController+Outline.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. //
  2. // KMLeftSideViewController+Outline.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/12/22.
  6. //
  7. import Foundation
  8. enum KMOutlineViewMenuItemTag: Int {
  9. case addEntry = 0
  10. case addChild
  11. case addAunt
  12. case remove
  13. case edit
  14. case setDestination
  15. case rename
  16. case promote
  17. case demote
  18. }
  19. extension KMLeftSideViewController {
  20. func outline_initSubViews() {
  21. self.outlineSearchField.delegate = self
  22. self.outlineAddButton.target = self
  23. self.outlineAddButton.action = #selector(outlineContextMenuItemClicked_AddEntry)
  24. self.outlineMoreButton.target = self
  25. self.outlineMoreButton.tag = 302
  26. self.outlineMoreButton.action = #selector(leftSideViewMoreButtonAction)
  27. self.outlineDoneButton.target = self
  28. self.outlineDoneButton.tag = 310
  29. self.outlineDoneButton.action = #selector(leftSideViewDoneButtonAction)
  30. let menuOutline = NSMenu()
  31. _ = menuOutline.addItem(title: KMLocalizedString("Ignore Case", "Menu item title"), action: #selector(toggleOutlineCaseInsensitiveSearch), target: self)
  32. (self.outlineSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menuOutline
  33. self.outlineSearchField.target = self
  34. self.tocOutlineView.menu = NSMenu()
  35. self.tocOutlineView.menu?.delegate = self
  36. self.tocOutlineView.delegate = self
  37. self.tocOutlineView.dataSource = self
  38. self.tocOutlineView.botaDelegate = self
  39. self.tocOutlineView.botaDataSource = self
  40. self.tocOutlineView.tocDelegate = self
  41. // kKMPDFViewOutlineDragDataType
  42. self.tocOutlineView.registerForDraggedTypes([.localDraggedTypes])
  43. self.tocOutlineView.target = self
  44. self.tocOutlineView.doubleAction = #selector(goToSelectedOutlineItem)
  45. }
  46. func outline_initDefalutValue() {
  47. self.outlineView.wantsLayer = true
  48. self.outlineView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  49. self.outlineLabel.stringValue = KMLocalizedString("Outline", nil);
  50. self.outlineLabel.textColor = KMAppearance.Layout.h0Color()
  51. self.outlineAddButton.toolTip = KMLocalizedString("Add Item", nil)
  52. self.outlineSearchButton.toolTip = KMLocalizedString("Search", nil)
  53. self.outlineDoneButton.title = KMLocalizedString("Done", nil);
  54. self.outlineDoneButton.toolTip = KMLocalizedString("Done", nil);
  55. self.outlineDoneButton.setTitleColor(KMAppearance.Layout.w0Color())
  56. self.outlineDoneButton.wantsLayer = true
  57. self.outlineDoneButton.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  58. self.outlineDoneButton.layer?.cornerRadius = 4.0
  59. self.outlineSearchField.wantsLayer = true
  60. self.outlineSearchField.backgroundColor = KMAppearance.Layout.l_1Color()
  61. self.outlineSearchField.layer?.backgroundColor = KMAppearance.Layout.l_1Color().cgColor
  62. self.outlineSearchField.layer?.borderWidth = 1.0
  63. self.outlineSearchField.layer?.borderColor = KMAppearance.Interactive.a0Color().cgColor
  64. self.outlineDoneButton.isHidden = true
  65. self.outlineSearchField.isHidden = true
  66. (self.outlineSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Outline", nil)
  67. self.tocOutlineView.backgroundColor = KMAppearance.Layout.l0Color()
  68. self.tocOutlineView.autoresizesOutlineColumn = false
  69. self.tocOutlineView.allowsMultipleSelection = true
  70. self.tocOutlineView.allowsEmptySelection = true
  71. }
  72. func updateOutlineSelection() {
  73. if self.listView.document.outlineRoot() == nil || self.updatingOutlineSelection {
  74. return
  75. }
  76. self.updatingOutlineSelection = true
  77. let numRows = self.tocOutlineView.numberOfRows
  78. var arr = NSMutableArray()
  79. for i in 0 ..< numRows {
  80. guard let tPDFOutline = self.tocOutlineView.item(atRow: i) as? CPDFOutline else {
  81. continue
  82. }
  83. let tPage = tPDFOutline.destination?.page()
  84. if (tPage == nil) {
  85. continue
  86. }
  87. let tDict = NSDictionary(object: tPage as Any, forKey: "\(i)" as NSCopying)
  88. arr.add(tDict)
  89. }
  90. let currentPage = self.listView.currentPage()
  91. var hasExistInOutlineView = false
  92. for dict in arr {
  93. guard let _dict = dict as? NSDictionary else {
  94. continue
  95. }
  96. let page = _dict.allValues.last as? CPDFPage
  97. // NSInteger index = [dict.allKeys.lastObject integerValue];
  98. let index = Int(_dict.allKeys.last as? String ?? "0") ?? 0
  99. if let data = page?.isEqual(to: currentPage), data {
  100. self.tocOutlineView.selectRowIndexes(IndexSet(integer: index), byExtendingSelection: false)
  101. self.tocOutlineView.scrollRowToVisible(index)
  102. hasExistInOutlineView = true
  103. break
  104. }
  105. }
  106. if (!hasExistInOutlineView) {
  107. self.tocOutlineView.deselectRow(self.tocOutlineView.selectedRow)
  108. }
  109. self.updatingOutlineSelection = false
  110. }
  111. func newAddOutlineEntryEditingMode(_ index: Int) {
  112. self.renamePDFOutline = self.tocOutlineView.item(atRow: self.tocOutlineView.selectedRow) as? CPDFOutline
  113. let row = self.tocOutlineView.selectedRow
  114. let viewS = self.tocOutlineView.view(atColumn: 0, row: row, makeIfNecessary: true)
  115. let targrtTextField = viewS?.subviews.first as? NSTextField
  116. self.renamePDFOutlineTextField = targrtTextField
  117. targrtTextField?.delegate = self
  118. targrtTextField?.isEditable = true
  119. targrtTextField?.becomeFirstResponder()
  120. }
  121. func loadUnfoldDate(_ foldType: KMFoldType) {
  122. // 清空所有折叠数组
  123. self.allFoldNotes.removeAll()
  124. var mutableArray: [CPDFAnnotation] = []
  125. if self.noteSearchMode {
  126. for note in self.noteSearchArray {
  127. if note is CPDFMarkupAnnotation {
  128. mutableArray.append(note)
  129. }
  130. }
  131. } else {
  132. for section in self.annotations {
  133. for item in section.annotations ?? [] {
  134. if let note = item.annotation, note is CPDFMarkupAnnotation {
  135. mutableArray.append(note)
  136. }
  137. }
  138. }
  139. }
  140. // for note in self.notes {
  141. // if note is CPDFMarkupAnnotation {
  142. // mutableArray.append(note)
  143. // }
  144. // }
  145. self.canFoldNotes = mutableArray
  146. self.allFoldNotes = []
  147. }
  148. func selectedRowIndexes() -> IndexSet {
  149. var selectedIndexes = self.tocOutlineView.selectedRowIndexes
  150. let clickedRow = self.tocOutlineView.clickedRow
  151. if clickedRow != -1 && selectedIndexes.contains(clickedRow) == false {
  152. var indexes = IndexSet(integer: clickedRow)
  153. selectedIndexes = indexes
  154. }
  155. return selectedIndexes
  156. }
  157. func editOutlineUI(_ editVC: KMOutlineEditViewController) {
  158. if editVC.pageButton.state == .on {
  159. let numberString = editVC.outlineTargetPageIndexTextField.stringValue
  160. let idx = Int(numberString) ?? 1
  161. let newPage = editVC.pdfView?.document.page(at: UInt(idx-1))
  162. let originalPage = editVC.originalDestination?.page()
  163. if let data = newPage?.pageIndex(), data != editVC.originalPageIndex {
  164. // if let data = newPage?.isEqual(to: originalPage), data {
  165. //新page不存在
  166. if (newPage == nil) {
  167. } else {
  168. if let outL = editVC.outline {
  169. let pageSize = newPage?.bounds(for: .cropBox).size ?? .zero
  170. if let destination = CPDFDestination(page: newPage, at: CGPointMake(pageSize.width, pageSize.height)) {
  171. self.changePDFOutlineDestination(destination, PDFoutline: outL)
  172. }
  173. }
  174. }
  175. }
  176. } else if editVC.urlButton.state == .on {
  177. var urlString = editVC.outlineURLTextField.stringValue
  178. let tLowerUrl = urlString.lowercased()
  179. if tLowerUrl.hasPrefix("https://") == false && tLowerUrl.hasPrefix("ftp://") == false && tLowerUrl.hasPrefix("http://") == false && urlString.isEmpty == false {
  180. urlString = "http://\(urlString)"
  181. }
  182. if let urlAction = CPDFURLAction(url: urlString), editVC.outline != nil {
  183. if editVC.originalURLString != editVC.outlineURLTextField.stringValue {
  184. self.changePDFAction(urlAction, PDFOutline: editVC.outline!)
  185. }
  186. }
  187. } else if editVC.mailButton.state == .on {
  188. var mailString = editVC.mailAddressTextField.stringValue
  189. let tLowerStr = mailString.lowercased()
  190. if tLowerStr.hasPrefix("mailto:") == false {
  191. mailString = "mailto:\(mailString)"
  192. }
  193. if var urlAction = CPDFURLAction(url: mailString) {
  194. if urlAction.url() == nil {
  195. urlAction = CPDFURLAction(url: "mailto:")
  196. }
  197. if mailString != editVC.originalURLString && editVC.outline != nil {
  198. self.changePDFAction(urlAction, PDFOutline: editVC.outline!)
  199. }
  200. }
  201. }
  202. if editVC.outlineNameTextView.string == editVC.originalLabel {
  203. return
  204. }
  205. if let outL = editVC.outline {
  206. self.renamePDFOutline(outL, label: editVC.outlineNameTextView.string)
  207. }
  208. }
  209. @objc func outlineContextMenuItemClicked_AddEntry(_ sender: AnyObject?) {
  210. let PDFOutlineArray = NSMutableArray()
  211. let rowSet = self.selectedRowIndexes()
  212. for idx in rowSet {
  213. PDFOutlineArray.add(self.tocOutlineView.item(atRow: idx))
  214. }
  215. if (PDFOutlineArray.count == 0) {
  216. var lastPDFLine = self.tocOutlineView.item(atRow: self.tocOutlineView.numberOfRows-1) as? CPDFOutline
  217. var rootPDFOutline: CPDFOutline?
  218. if (lastPDFLine != nil) {
  219. while (lastPDFLine!.parent != nil) {
  220. lastPDFLine = lastPDFLine?.parent
  221. }
  222. rootPDFOutline = lastPDFLine
  223. } else {
  224. rootPDFOutline = self.listView.document.outlineRoot()
  225. if ((rootPDFOutline == nil)) {
  226. // rootPDFOutline = CPDFOutline()
  227. // self.listView.document.setOutlineRoot(rootPDFOutline)
  228. rootPDFOutline = self.listView.document.setNewOutlineRoot()
  229. }
  230. }
  231. let addOutLine = CPDFOutline()
  232. addOutLine.label = String(format: "%@ %ld", KMLocalizedString("Page", nil), self.listView.currentPageIndex+1)
  233. addOutLine.destination = self.listView.currentDestination
  234. self.addoutline(parent: rootPDFOutline, addOutline: addOutLine, index: Int(rootPDFOutline?.numberOfChildren ?? 0), needExpand: false)
  235. } else {
  236. let currentPDFline = PDFOutlineArray.lastObject as? CPDFOutline
  237. let currentIndex = currentPDFline?.index ?? 0
  238. var parent: CPDFOutline?
  239. parent = currentPDFline?.parent
  240. let addOutLine = CPDFOutline()
  241. addOutLine.label = String(format: "%@ %ld", KMLocalizedString("Page", nil), self.listView.currentPageIndex+1)
  242. addOutLine.destination = self.listView.currentDestination
  243. self.addoutline(parent: parent, addOutline: addOutLine, index: Int(currentIndex) + 1, needExpand: false)
  244. self.tocOutlineView.scrollRowToVisible(Int(currentIndex) + 1)
  245. self.tocOutlineView.deselectRow(Int(currentIndex)+1)
  246. }
  247. }
  248. @IBAction func outlineNormalSearchButtonAction(_ sender: NSButton) {
  249. self.outlineSearchField.isHidden = false
  250. self.outlineDoneButton.isHidden = false
  251. self.outlineLabel.isHidden = true
  252. self.outlineSearchButton.isHidden = true
  253. self.outlineMoreButton.isHidden = true
  254. self.outlineAddButton.isHidden = true
  255. self.outlineSearchField.becomeFirstResponder()
  256. }
  257. @IBAction func toc_expandAllComments(_ sender: AnyObject?) {
  258. if (self.tocType == .unfold) {
  259. return
  260. }
  261. self.tocType = .unfold
  262. self.tocOutlineView.reloadData()
  263. self.tocOutlineView.expandItem(nil, expandChildren: true)
  264. }
  265. @IBAction func toc_foldAllComments(_ sender: AnyObject?) {
  266. if (self.tocType == .fold) {
  267. return
  268. }
  269. self.tocType = .fold
  270. self.tocOutlineView.reloadData()
  271. self.tocOutlineView.collapseItem(nil, collapseChildren: true)
  272. }
  273. @objc func leftSideEmptyAnnotationClick_DeleteOutline(_ sender: AnyObject?) {
  274. let alert = NSAlert()
  275. alert.alertStyle = .critical
  276. alert.messageText = ""
  277. alert.informativeText = KMLocalizedString("This will permanently remove all outlines. Are you sure to continue?", nil)
  278. alert.addButton(withTitle: KMLocalizedString("Yes", nil))
  279. alert.addButton(withTitle: KMLocalizedString("No", nil))
  280. let response = alert.runModal()
  281. if response == .alertFirstButtonReturn {
  282. if let item = self.listView.document.outlineRoot() {
  283. self.removeAllOutline(item)
  284. }
  285. }
  286. }
  287. func showSearchOutlineBlankState(_ toShowState: Bool) {
  288. if (toShowState) {
  289. self.leftSideEmptyVC.outlineSearchView.frame = CGRectMake((self.tocOutlineView.enclosingScrollView!.documentView!.frame.size.width - self.leftSideEmptyVC.outlineSearchView.bounds.size.width)/2.0, (self.tocOutlineView.enclosingScrollView!.documentView!.frame.size.height - self.leftSideEmptyVC.outlineSearchView.bounds.size.height)/2.0, self.leftSideEmptyVC.outlineSearchView.bounds.size.width, self.leftSideEmptyVC.outlineSearchView.bounds.size.height);
  290. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.outlineSearchView)
  291. self.leftSideEmptyVC.outlineSearchView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  292. } else {
  293. self.leftSideEmptyVC.outlineSearchView.removeFromSuperview()
  294. }
  295. }
  296. func removeAllOutline(_ outline: CPDFOutline) {
  297. self.listView.document.setNewOutlineRoot()
  298. for i in 0 ..< self.listView.document.pageCount {
  299. self.listView.document.removeBookmark(forPageIndex: i)
  300. }
  301. self.listView.layoutDocumentView()
  302. DispatchQueue.main.async {
  303. self.tocOutlineView.reloadData()
  304. }
  305. }
  306. func updateSelectRowHeight() {
  307. var rowHeight: CGFloat = 0
  308. let outline: CPDFOutline? = self.tocOutlineView.km.selectedItem()
  309. if outline == nil {
  310. return
  311. }
  312. var attributedString = NSMutableAttributedString()
  313. var dictAttr1 = [NSAttributedString.Key.font : KMAppearance.Layout.h0Color()]
  314. var attr1 = NSAttributedString(string: outline!.label, attributes: dictAttr1)
  315. attributedString.append(attr1)
  316. let row = self.tocOutlineView.selectedRow
  317. let viewS = self.tocOutlineView.view(atColumn: 0, row: row, makeIfNecessary: true)
  318. let tableColumn = self.tocOutlineView.tableColumn(withIdentifier: kLabelColumnId)
  319. // // id cell = [tableColumn dataCell];
  320. let cell = tableColumn?.dataCell(forRow: row)
  321. (cell as? NSCell)?.objectValue = attributedString
  322. // CGFloat w = leftSideController.view.frame.size.width - 86;//[tableColumn width] > 260 ? [tableColumn width] : 260;
  323. let w = self.view.frame.size.width-86
  324. let num = self.getNum(outline)
  325. let gap = self.tocOutlineView.indentationPerLevel
  326. rowHeight = ((cell as? NSCell)?.cellSize(forBounds: NSMakeRect(0, 0, w - (num > 0 ? 16 : 0) - gap * num.cgFloat, CGFLOAT_MAX)).height) ?? 0
  327. rowHeight = fmax(rowHeight, self.tocOutlineView.rowHeight) + 25
  328. // [rowHeights setFloat:rowHeight forKey:outline];
  329. var fram = viewS?.frame ?? .zero
  330. viewS?.frame = NSMakeRect(fram.origin.x, fram.origin.y, fram.size.width, rowHeight)
  331. self.tocOutlineView.reloadData()
  332. }
  333. func getNum(_ ol: CPDFOutline?) -> Int {
  334. var num = 0
  335. var outline = ol?.parent
  336. repeat {
  337. outline = outline?.parent
  338. if outline != nil {
  339. num += 1
  340. }
  341. } while outline != nil
  342. return num
  343. }
  344. }
  345. // MARK: - Undo & Redo
  346. extension KMLeftSideViewController {
  347. @objc dynamic func changePDFOutlineDestination(_ destination: CPDFDestination?, PDFoutline outline: CPDFOutline) {
  348. if let des = destination {
  349. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).changePDFOutlineDestination(outline.destination, PDFoutline: outline)
  350. let newDes = CPDFDestination(document: des.document, pageIndex: des.pageIndex, at: des.point, zoom: des.zoom)
  351. outline.destination = newDes
  352. self.tocOutlineView.reloadItem(outline)
  353. }
  354. }
  355. @objc dynamic func changePDFAction(_ action: CPDFAction, PDFOutline outline: CPDFOutline) {
  356. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).changePDFAction(outline.action, PDFOutline: outline)
  357. outline.action = action
  358. }
  359. @objc dynamic func renamePDFOutline(_ outline: CPDFOutline, label: String) {
  360. if (self.isRenameNoteOutline) {
  361. if outline is CPDFAnnotation {
  362. // if([outline isKindOfClass:[PDFAnnotation class]]) {
  363. // PDFAnnotation *annotation = (PDFAnnotation *)outline;
  364. // annotation.string = label;
  365. // [rightSideController.noteOutlineView reloadData];
  366. // [rightSideController.noteOutlineView selectRowIndexes:[[[NSIndexSet alloc] initWithIndex:[rightSideController.noteOutlineView rowForItem:outline]] autorelease] byExtendingSelection:NO];
  367. }
  368. } else {
  369. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).renamePDFOutline(outline, label: outline.label)
  370. outline.label = label
  371. self.tocOutlineView.reloadData()
  372. self.tocOutlineView.km_selectItem(outline, byExtendingSelection: false)
  373. }
  374. }
  375. @objc dynamic func demoteOutlineWithGrandParent(_ grandParentOutline: CPDFOutline, demoteOutline: CPDFOutline, index: Int) {
  376. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).promoteOutlineWithGrandParent(grandParentOutline, promoteOutline: demoteOutline, rowIndex: index)
  377. if grandParentOutline.isEqual(to: demoteOutline.parent) {
  378. let demoteIndex = demoteOutline.index
  379. let previousOutline = grandParentOutline.child(at: demoteIndex-1)
  380. demoteOutline.removeFromParent()
  381. previousOutline?.insertChild(demoteOutline, at: UInt(index))
  382. self.tocOutlineView.reloadData()
  383. self.tocOutlineView.expandItem(previousOutline)
  384. } else {
  385. demoteOutline.removeFromParent()
  386. grandParentOutline.insertChild(demoteOutline, at: grandParentOutline.numberOfChildren)
  387. self.tocOutlineView.reloadData()
  388. self.tocOutlineView.expandItem(grandParentOutline)
  389. }
  390. self.tocOutlineView.km_selectItem(demoteOutline, byExtendingSelection: false)
  391. }
  392. @objc dynamic func promoteOutlineWithGrandParent(_ grandParentOutline: CPDFOutline, promoteOutline: CPDFOutline, rowIndex: Int) {
  393. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).demoteOutlineWithGrandParent(grandParentOutline, demoteOutline: promoteOutline, index: rowIndex)
  394. let index = promoteOutline.parent?.index ?? 0
  395. if grandParentOutline.isEqual(to: promoteOutline.parent) {
  396. promoteOutline.removeFromParent()
  397. grandParentOutline.parent.insertChild(promoteOutline, at: index+1)
  398. } else {
  399. promoteOutline.removeFromParent()
  400. grandParentOutline.insertChild(promoteOutline, at: index+1)
  401. }
  402. self.tocOutlineView.reloadData()
  403. self.tocOutlineView.km_selectItem(promoteOutline, byExtendingSelection: false)
  404. }
  405. @objc dynamic func addoutline(parent parentOutline: CPDFOutline?, addOutline: CPDFOutline, index: Int, needExpand: Bool) {
  406. var tempO: CPDFOutline? = addOutline
  407. if addOutline.label != nil {
  408. parentOutline?.insertChild(addOutline, at: UInt(index))
  409. } else {
  410. let outline = parentOutline?.insertChild(at: UInt(index))
  411. outline?.label = String(format: "%@ %ld", KMLocalizedString("Page", nil), self.listView.currentPageIndex+1)
  412. outline?.destination = self.listView.currentDestination
  413. tempO = outline
  414. }
  415. guard let outline = tempO else {
  416. return
  417. }
  418. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).removeOutline(parent: parentOutline, removeOutline: outline, index: index, needExpand: needExpand)
  419. self.view.window?.makeFirstResponder(nil)
  420. Task { @MainActor in
  421. self.tocOutlineView.reloadData()
  422. if (needExpand) {
  423. self.tocOutlineView.expandItem(parentOutline)
  424. }
  425. let idx = self.tocOutlineView.row(forItem: outline)
  426. self.tocOutlineView.selectRowIndexes(IndexSet(integer: idx), byExtendingSelection: false)
  427. self.newAddOutlineEntryEditingMode(index)
  428. }
  429. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  430. self.tocOutlineView.scrollRowToVisible(self.tocOutlineView.row(forItem: outline))
  431. }
  432. }
  433. @objc dynamic func removeOutline(parent parentOutline: CPDFOutline?, removeOutline: CPDFOutline, index: Int, needExpand: Bool) {
  434. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).addoutline(parent: parentOutline, addOutline: removeOutline, index: index, needExpand: true)
  435. removeOutline.removeFromParent()
  436. if (needExpand) {
  437. self.tocOutlineView.expandItem(parentOutline)
  438. }
  439. Task { @MainActor in
  440. self.tocOutlineView.reloadData()
  441. }
  442. }
  443. @objc dynamic func dragPDFOutline(_ outline: CPDFOutline?, toIndex index: Int, newParentOutline: CPDFOutline?) {
  444. guard let doc = self.view.window?.windowController?.document as? NSDocument else {
  445. NSSound.beep()
  446. return
  447. }
  448. if outline == nil {
  449. NSSound.beep()
  450. return
  451. }
  452. (doc.undoManager?.prepare(withInvocationTarget: self) as AnyObject).dragPDFOutline(outline, toIndex: Int(outline!.index), newParentOutline: outline?.parent)
  453. outline?.removeFromParent()
  454. newParentOutline?.insertChild(outline, at: UInt(index))
  455. self.tocOutlineView.reloadData()
  456. self.tocOutlineView.expandItem(newParentOutline)
  457. self.tocOutlineView.selectRowIndexes(IndexSet(integer: self.tocOutlineView.row(forItem: outline)), byExtendingSelection: false)
  458. }
  459. }
  460. // MARK: - Menu Actions
  461. extension KMLeftSideViewController {
  462. //添加子节点
  463. @objc func outlineContextMenuItemClicked_AddChildEntry(_ sender: AnyObject?) {
  464. let PDFOutlineArray = NSMutableArray()
  465. let rowSet = self.selectedRowIndexes()
  466. for idx in rowSet {
  467. PDFOutlineArray.add(self.tocOutlineView.item(atRow: idx))
  468. }
  469. let currentPDFline = PDFOutlineArray.lastObject as? CPDFOutline
  470. let addOutLine = CPDFOutline()
  471. addOutLine.label = String(format: "%@ %ld", KMLocalizedString("Page", nil), "\(self.listView.currentPageIndex + 1)")
  472. addOutLine.destination = self.listView.currentDestination
  473. self.addoutline(parent: currentPDFline, addOutline: addOutLine, index: Int(currentPDFline?.numberOfChildren ?? 0), needExpand: true)
  474. }
  475. //添加上一级节点
  476. @objc func outlineContextMenuItemClicked_AddAuntEntry(_ sender: AnyObject?) {
  477. let PDFOutlineArray = NSMutableArray()
  478. let rowSet = self.selectedRowIndexes()
  479. for idx in rowSet {
  480. PDFOutlineArray.add(self.tocOutlineView.item(atRow: idx))
  481. }
  482. let clickedOutline = PDFOutlineArray.lastObject as? CPDFOutline
  483. let fatherOutLine = clickedOutline?.parent
  484. let grandfatherOutLine = fatherOutLine?.parent
  485. if (grandfatherOutLine != nil) {
  486. let addOutLine = CPDFOutline()
  487. addOutLine.label = String(format: "%@ %ld", KMLocalizedString("Page", nil), "\(self.listView.currentPageIndex + 1)")
  488. addOutLine.destination = self.listView.currentDestination
  489. self.addoutline(parent: grandfatherOutLine, addOutline: addOutLine, index: Int(fatherOutLine?.index ?? 0) + 1, needExpand: false)
  490. }
  491. }
  492. //移除节点
  493. @objc func outlineContextMenuItemClicked_RemoveEntry(_ sender: AnyObject?) {
  494. let set = self.selectedRowIndexes()
  495. var selectedPDFOutlineArr = NSMutableArray()
  496. for idx in set {
  497. selectedPDFOutlineArr.add(self.tocOutlineView.item(atRow: idx))
  498. }
  499. //整体移除多选
  500. for tOutline in selectedPDFOutlineArr {
  501. guard let outL = tOutline as? CPDFOutline else {
  502. continue
  503. }
  504. self.removeOutline(parent: outL.parent , removeOutline: outL, index: Int(outL.index), needExpand: false)
  505. }
  506. }
  507. //重置目的
  508. @objc func outlineContextMenuItemClicked_SetDestination(_ sender: AnyObject?) {
  509. guard let setPDFOutline = self.tocOutlineView.item(atRow: self.tocOutlineView.clickedRow) as? CPDFOutline else {
  510. return
  511. }
  512. Task {
  513. let modalRes = await KMAlertTool.runModel(style: .informational, message: KMLocalizedString("Are you sure you want to set the destination as the current location?", nil), buttons: [KMLocalizedString("Yes", nil), KMLocalizedString("No", nil)])
  514. if (modalRes == .alertFirstButtonReturn) {
  515. self.changePDFOutlineDestination(self.listView.currentDestination, PDFoutline: setPDFOutline)
  516. self.tocOutlineView.reloadData()
  517. let idx = self.tocOutlineView.row(forItem: setPDFOutline)
  518. self.tocOutlineView.selectRowIndexes(IndexSet(integer: idx), byExtendingSelection: false)
  519. }
  520. }
  521. }
  522. //弹出菜单
  523. @objc func outlineContextMenuItemClicked_Edit(_ sender: AnyObject?) {
  524. let popover = NSPopover()
  525. popover.delegate = self
  526. let targetOutline: CPDFOutline? = self.tocOutlineView.km.clickedItem()
  527. let outlineEditViewController = KMOutlineEditViewController(outline: targetOutline, document: self.listView)
  528. let cell = self.tocOutlineView.rowView(atRow: self.tocOutlineView.clickedRow, makeIfNecessary: true)
  529. popover.contentViewController = outlineEditViewController
  530. popover.animates = true
  531. popover.behavior = .transient
  532. popover.show(relativeTo: cell?.bounds ?? .zero, of: cell!, preferredEdge: .minX)
  533. }
  534. //重命名
  535. @objc func outlineContextMenuItemClicked_Rename(_ sender: AnyObject?) {
  536. if (self.tocOutlineView.clickedRow < 0) {
  537. return
  538. }
  539. self.renamePDFOutline = self.tocOutlineView.km.clickedItem()
  540. let viewS = self.tocOutlineView.view(atColumn: 0, row: self.tocOutlineView.clickedRow, makeIfNecessary: true)
  541. let targrtTextField = viewS?.subviews.first as? NSTextField
  542. self.renamePDFOutlineTextField = targrtTextField
  543. targrtTextField?.delegate = self
  544. targrtTextField?.isEditable = true
  545. targrtTextField?.becomeFirstResponder()
  546. }
  547. //降级节点
  548. @objc func outlineContextMenuItemClicked_Demote(_ sender: AnyObject?) {
  549. guard let currentOutline: CPDFOutline = self.tocOutlineView.km.clickedItem() else {
  550. return
  551. }
  552. let parentOutLine = currentOutline.parent
  553. let newParentOutLine = parentOutLine?.child(at: currentOutline.index-1)
  554. var newIndex = 0
  555. let newParentOutLineExpandState = self.tocOutlineView.isItemExpanded(newParentOutLine)
  556. if (newParentOutLineExpandState) {
  557. newIndex = self.tocOutlineView.clickedRow
  558. } else {
  559. newIndex = self.tocOutlineView.clickedRow + Int(newParentOutLine?.numberOfChildren ?? 0)
  560. }
  561. let currentIndex = currentOutline.index
  562. currentOutline.removeFromParent()
  563. self.demoteOutlineWithGrandParent(newParentOutLine!, demoteOutline: currentOutline, index: Int(currentIndex))
  564. }
  565. //升级节点
  566. @objc func outlineContextMenuItemClicked_Promote(_ sender: AnyObject?) {
  567. guard let currentOutline: CPDFOutline = self.tocOutlineView.km.clickedItem() else {
  568. return
  569. }
  570. let parentOutLine = currentOutline.parent
  571. if let grandParentOutLine = parentOutLine?.parent {
  572. self.promoteOutlineWithGrandParent(grandParentOutLine, promoteOutline: currentOutline, rowIndex:Int(currentOutline.index))
  573. }
  574. }
  575. @objc func toggleOutlineCaseInsensitiveSearch(_ sender: NSMenuItem) {
  576. if (sender.state == .on) {
  577. self.outlineIgnoreCaseFlag = false
  578. } else {
  579. self.outlineIgnoreCaseFlag = true
  580. }
  581. if (self.outlineSearchField.stringValue.isEmpty == false) {
  582. self.tocOutlineView.reloadData()
  583. self.tocOutlineView.expandItem(nil, expandChildren: true)
  584. }
  585. }
  586. }
  587. // MARK: - KMTocOutlineViewDelegate
  588. extension KMLeftSideViewController: KMTocOutlineViewDelegate {
  589. func outlineView(_ anOutlineView: NSOutlineView, highlightLevelForRow row: Int) -> Int {
  590. if self.tocOutlineView.isEqual(to: anOutlineView) {
  591. let numRows = anOutlineView.numberOfRows
  592. if let outline = anOutlineView.item(atRow: row) as? CPDFOutline {
  593. let firstPage = outline.km_pageIndex
  594. var lastPage = self.listView.document.pageCount
  595. if row + 1 < numRows {
  596. lastPage = (anOutlineView.item(atRow: row + 1) as? CPDFOutline)?.km_pageIndex ?? UInt(NSNotFound)
  597. }
  598. // NSRange range = NSMakeRange(firstPage, MAX(1LU, lastPage - firstPage));
  599. // NSUInteger i, iMax = [lastViewedPages count];
  600. // for (i = 0; i < iMax; i++) {
  601. // if (NSLocationInRange((NSUInteger)[lastViewedPages pointerAtIndex:i], range))
  602. // return i;
  603. // }
  604. }
  605. }
  606. return NSNotFound
  607. }
  608. func outlineView(_ anOutlineView: NSOutlineView, imageContextForItem item: Any?) -> AnyObject? {
  609. if anOutlineView.isEqual(to: self.tocOutlineView) {
  610. if item == nil {
  611. return true as AnyObject
  612. }
  613. if item is CPDFOutline {
  614. return (item as! CPDFOutline).destination
  615. }
  616. }
  617. return nil
  618. }
  619. }
  620. extension KMLeftSideViewController: KMNoteOutlineViewDelegate {
  621. func outlineView(_ anOutlineView: NSOutlineView, canResizeRowByItem item: AnyObject?) -> Bool? {
  622. if anOutlineView.isEqual(to: self.noteOutlineView) {
  623. return true
  624. }
  625. return false
  626. }
  627. func outlineView(_ anOutlineView: NSOutlineView, setHeight newHeight: CGFloat, ofRowByItem item: AnyObject?) {
  628. // [rowHeights setFloat:newHeight forKey:item];
  629. }
  630. func outlineView(_ anOutlineView: NSOutlineView, didChangeHiddenOfTableColumn aTableColumn: NSTableColumn) {
  631. // if (mwcFlags.autoResizeNoteRows &&
  632. // [ov isEqual:rightSideController.noteOutlineView] &&
  633. // [[tableColumn identifier] isEqualToString:NOTE_COLUMNID]) {
  634. // [rowHeights removeAllFloats];
  635. // [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  636. // }
  637. }
  638. func outlineViewCommandKeyPressedDuringNavigation(_ anOutlineView: NSOutlineView) {
  639. // PDFAnnotation *annotation = [[self selectedNotes] lastObject];
  640. // if (annotation) {
  641. // [pdfView scrollAnnotationToVisible:annotation];
  642. // [pdfView setActiveAnnotation:annotation];
  643. // }
  644. }
  645. }