KMLeftSideViewController+Outline.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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. self.tocOutlineView.registerForDraggedTypes([.localDraggedTypes])
  42. self.tocOutlineView.target = self
  43. self.tocOutlineView.doubleAction = #selector(outlineContextMenuItemClicked_Rename)
  44. }
  45. func outline_initDefalutValue() {
  46. self.outlineView.wantsLayer = true
  47. self.outlineView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  48. self.outlineLabel.stringValue = KMLocalizedString("Outline", nil);
  49. self.outlineLabel.textColor = KMAppearance.Layout.h0Color()
  50. self.outlineAddButton.toolTip = KMLocalizedString("Add Item", nil)
  51. self.outlineSearchButton.toolTip = KMLocalizedString("Search", nil)
  52. self.outlineDoneButton.title = KMLocalizedString("Done", nil);
  53. self.outlineDoneButton.toolTip = KMLocalizedString("Done", nil);
  54. self.outlineDoneButton.setTitleColor(KMAppearance.Layout.w0Color())
  55. self.outlineDoneButton.wantsLayer = true
  56. self.outlineDoneButton.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  57. self.outlineDoneButton.layer?.cornerRadius = 4.0
  58. self.outlineSearchField.wantsLayer = true
  59. self.outlineSearchField.backgroundColor = KMAppearance.Layout.l_1Color()
  60. self.outlineSearchField.layer?.backgroundColor = KMAppearance.Layout.l_1Color().cgColor
  61. self.outlineSearchField.layer?.borderWidth = 1.0
  62. self.outlineSearchField.layer?.borderColor = KMAppearance.Interactive.a0Color().cgColor
  63. self.outlineDoneButton.isHidden = true
  64. self.outlineSearchField.isHidden = true
  65. (self.outlineSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Outline", nil)
  66. self.tocOutlineView.backgroundColor = KMAppearance.Layout.l0Color()
  67. self.tocOutlineView.autoresizesOutlineColumn = false
  68. self.tocOutlineView.allowsMultipleSelection = true
  69. self.tocOutlineView.allowsEmptySelection = true
  70. self.tocOutlineView.focusRingType = .none
  71. self.tocOutlineView.autoresizesSubviews = true
  72. }
  73. func updateOutlineSelection() {
  74. if self.outlineRoot() == nil || self.updatingOutlineSelection {
  75. return
  76. }
  77. self.updatingOutlineSelection = true
  78. let numRows = self.tocOutlineView.numberOfRows
  79. let currentPage = self.currentPage()
  80. var flagIdx = NSNotFound
  81. for i in 0 ..< numRows {
  82. guard let ol = self.tocOutlineView.item(atRow: i) as? CPDFOutline else {
  83. continue
  84. }
  85. guard let page = ol.km_page else {
  86. continue
  87. }
  88. if page.isEqual(to: currentPage) {
  89. flagIdx = i
  90. break
  91. }
  92. }
  93. if flagIdx != NSNotFound {
  94. self.tocOutlineView.km_safe_selectRowIndexes(.init(integer: flagIdx), byExtendingSelection: false)
  95. self.tocOutlineView.scrollRowToVisible(flagIdx)
  96. } else {
  97. self.tocOutlineView.deselectRow(self.tocOutlineView.selectedRow)
  98. }
  99. self.updatingOutlineSelection = false
  100. }
  101. func newAddOutlineEntryEditingMode(_ index: Int) {
  102. self.renamePDFOutline = self.tocOutlineView.item(atRow: self.tocOutlineView.selectedRow) as? CPDFOutline
  103. let row = self.tocOutlineView.selectedRow
  104. let viewS = self.tocOutlineView.view(atColumn: 0, row: row, makeIfNecessary: true)
  105. let targrtTextField = viewS?.subviews.first as? NSTextField
  106. self.renamePDFOutlineTextField = targrtTextField
  107. targrtTextField?.delegate = self
  108. targrtTextField?.isEditable = true
  109. targrtTextField?.becomeFirstResponder()
  110. }
  111. func selectedRowIndexes() -> IndexSet {
  112. var selectedIndexes = self.tocOutlineView.selectedRowIndexes
  113. let clickedRow = self.tocOutlineView.clickedRow
  114. if clickedRow != -1 && selectedIndexes.contains(clickedRow) == false {
  115. let indexes = IndexSet(integer: clickedRow)
  116. selectedIndexes = indexes
  117. }
  118. return selectedIndexes
  119. }
  120. func editOutlineUI(_ editVC: KMOutlineEditViewController) {
  121. guard let ol = editVC.outline else {
  122. return
  123. }
  124. if editVC.pageButton.state == .on {
  125. let numberString = editVC.outlineTargetPageIndexTextField.stringValue
  126. let idx = Int(numberString) ?? 1
  127. let newPage = editVC.pdfView?.document.page(at: UInt(idx-1))
  128. if let data = newPage?.pageIndex(), data != editVC.originalPageIndex {
  129. //新page不存在
  130. if (newPage == nil) {
  131. } else {
  132. let pageSize = newPage?.bounds(for: .cropBox).size ?? .zero
  133. if let dest = CPDFDestination(page: newPage, at: NSMakePoint(pageSize.width, pageSize.height)) {
  134. self.changePDFOutlineDestination(dest, PDFoutline: ol)
  135. }
  136. }
  137. }
  138. } else if editVC.urlButton.state == .on {
  139. var urlString = editVC.outlineURLTextField.stringValue
  140. let tLowerUrl = urlString.lowercased()
  141. if tLowerUrl.hasPrefix(kHTTPSPrefix) == false && tLowerUrl.hasPrefix(kFTPPrefix) == false && tLowerUrl.hasPrefix(kHTTPPrefix) == false && urlString.isEmpty == false {
  142. urlString = "\(kHTTPPrefix)\(urlString)"
  143. }
  144. if let act = CPDFURLAction(url: urlString) {
  145. if editVC.originalURLString != editVC.outlineURLTextField.stringValue {
  146. self.changePDFAction(act, PDFOutline: ol)
  147. }
  148. }
  149. } else if editVC.mailButton.state == .on {
  150. var mailString = editVC.mailAddressTextField.stringValue
  151. let tLowerStr = mailString.lowercased()
  152. if tLowerStr.hasPrefix(kEmailPrefix) == false {
  153. mailString = "\(kEmailPrefix)\(mailString)"
  154. }
  155. if var urlAction = CPDFURLAction(url: mailString) {
  156. if urlAction.url() == nil {
  157. urlAction = CPDFURLAction(url: kEmailPrefix)
  158. }
  159. if mailString != editVC.originalURLString {
  160. self.changePDFAction(urlAction, PDFOutline: ol)
  161. }
  162. }
  163. }
  164. if editVC.outlineNameTextView.string != editVC.originalLabel {
  165. self.renamePDFOutline(ol, label: editVC.outlineNameTextView.string)
  166. }
  167. }
  168. @objc func outlineContextMenuItemClicked_AddEntry(_ sender: AnyObject?) {
  169. let ris = self.selectedRowIndexes()
  170. if ris.isEmpty {
  171. var rootOL = self.outlineRoot()
  172. if rootOL == nil {
  173. rootOL = self.setNewOutlineRoot()
  174. }
  175. let ol = CPDFOutline()
  176. ol.label = String(format: "%@ %ld", KMLocalizedString("Page", nil), self.currentPageIndex()+1)
  177. ol.destination = self.currentDestination()
  178. self.addoutline(parent: rootOL, addOutline: ol, index: Int(rootOL?.numberOfChildren ?? 0), needExpand: false)
  179. return
  180. }
  181. if let row = ris.last {
  182. let item = self.tocOutlineView.item(atRow: row) as? CPDFOutline
  183. let ol = CPDFOutline()
  184. ol.label = String(format: "%@ %ld", KMLocalizedString("Page", nil), self.currentPageIndex()+1)
  185. ol.destination = self.currentDestination()
  186. let idx = Int(item?.index ?? 0) + 1
  187. self.addoutline(parent: item?.parent, addOutline: ol, index: idx, needExpand: false)
  188. self.tocOutlineView.scrollRowToVisible(idx)
  189. self.tocOutlineView.deselectRow(idx)
  190. }
  191. }
  192. @IBAction func outlineNormalSearchButtonAction(_ sender: NSButton) {
  193. self.outlineSearchField.isHidden = false
  194. self.outlineDoneButton.isHidden = false
  195. self.outlineLabel.isHidden = true
  196. self.outlineSearchButton.isHidden = true
  197. self.outlineMoreButton.isHidden = true
  198. self.outlineAddButton.isHidden = true
  199. self.outlineSearchField.becomeFirstResponder()
  200. }
  201. @IBAction func toc_expandAllComments(_ sender: AnyObject?) {
  202. if (self.tocType == .unfold) {
  203. return
  204. }
  205. self.tocType = .unfold
  206. self.tocOutlineView.reloadData()
  207. self.tocOutlineView.expandItem(nil, expandChildren: true)
  208. }
  209. @IBAction func toc_foldAllComments(_ sender: AnyObject?) {
  210. if (self.tocType == .fold) {
  211. return
  212. }
  213. self.tocType = .fold
  214. self.tocOutlineView.reloadData()
  215. self.tocOutlineView.collapseItem(nil, collapseChildren: true)
  216. }
  217. @objc func leftSideEmptyAnnotationClick_DeleteOutline(_ sender: AnyObject?) {
  218. let alert = NSAlert()
  219. alert.alertStyle = .critical
  220. alert.messageText = ""
  221. alert.informativeText = KMLocalizedString("This will permanently remove all outlines. Are you sure to continue?", nil)
  222. alert.addButton(withTitle: KMLocalizedString("Yes", nil))
  223. alert.addButton(withTitle: KMLocalizedString("No", nil))
  224. let response = alert.runModal()
  225. if response == .alertFirstButtonReturn {
  226. if let item = self.outlineRoot() {
  227. self.removeAllOutline(item)
  228. }
  229. }
  230. }
  231. func showSearchOutlineBlankState(_ toShowState: Bool) {
  232. if (toShowState) {
  233. let documentViewFrame = self.tocOutlineView.enclosingScrollView?.documentView?.frame ?? .zero
  234. let width = self.leftSideEmptyVC.outlineSearchView.bounds.size.width
  235. let height = self.leftSideEmptyVC.outlineSearchView.bounds.size.height
  236. self.leftSideEmptyVC.outlineSearchView.frame = NSMakeRect((documentViewFrame.size.width - width)/2.0, (documentViewFrame.size.height - height)/2.0, width, height)
  237. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.outlineSearchView)
  238. self.leftSideEmptyVC.outlineSearchView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  239. } else {
  240. self.leftSideEmptyVC.outlineSearchView.removeFromSuperview()
  241. }
  242. }
  243. func removeAllOutline(_ outline: CPDFOutline) {
  244. _ = self.setNewOutlineRoot()
  245. for i in 0 ..< self.pageCount() {
  246. self.pdfDocument()?.removeBookmark(forPageIndex: UInt(i))
  247. }
  248. self.layoutDocumentView()
  249. DispatchQueue.main.async {
  250. self.tocOutlineView.reloadData()
  251. }
  252. }
  253. func updateSelectRowHeight() {
  254. guard let ol = self.tocOutlineView.selectedItem() as? CPDFOutline else {
  255. return
  256. }
  257. let attriString = NSMutableAttributedString()
  258. let attri = [NSAttributedString.Key.foregroundColor : KMAppearance.Layout.h0Color()]
  259. attriString.append(.init(string: ol.label ?? "", attributes: attri))
  260. let row = self.tocOutlineView.selectedRow
  261. let column = self.tocOutlineView.tableColumn(withIdentifier: kLabelColumnId)
  262. let cell = column?.dataCell(forRow: row)
  263. (cell as? NSCell)?.objectValue = attriString
  264. let w = self.view.frame.size.width-86
  265. let num = self.getNum(ol)
  266. let gap = self.tocOutlineView.indentationPerLevel
  267. var rowH = ((cell as? NSCell)?.cellSize(forBounds: NSMakeRect(0, 0, w - (num > 0 ? 16 : 0) - gap * num.cgFloat, CGFloat.greatestFiniteMagnitude)).height) ?? 0
  268. rowH = fmax(rowH, self.tocOutlineView.rowHeight) + 25
  269. let view = self.tocOutlineView.view(atColumn: 0, row: row, makeIfNecessary: true)
  270. let frame = view?.frame ?? .zero
  271. view?.frame = NSMakeRect(frame.origin.x, frame.origin.y, frame.size.width, rowH)
  272. self.tocOutlineView.reloadData()
  273. }
  274. func getNum(_ ol: CPDFOutline?) -> Int {
  275. var num = 0
  276. var outline = ol?.parent
  277. // repeat {
  278. // outline = outline?.parent
  279. // if outline != nil {
  280. // num += 1
  281. // }
  282. // } while outline != nil
  283. while outline != nil {
  284. outline = outline?.parent
  285. if outline != nil {
  286. num += 1
  287. }
  288. }
  289. return num
  290. }
  291. func addOutlineAfter(_ ol: CPDFOutline) {
  292. if self.leftView.segmentedControl.selectedSegment == 2 {
  293. } else {
  294. self.leftView.segmentedControl.selectedSegment = 2
  295. }
  296. Task { @MainActor in
  297. self.tocOutlineView.reloadData()
  298. let idx = self.tocOutlineView.row(forItem: ol)
  299. self.updatingOutlineSelection = true
  300. self.tocOutlineView.km_selectItem(ol, byExtendingSelection: false)
  301. self.updatingOutlineSelection = false
  302. self.newAddOutlineEntryEditingMode(idx)
  303. }
  304. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  305. self.tocOutlineView.scrollRowToVisible(self.tocOutlineView.row(forItem: ol))
  306. }
  307. }
  308. func removeOutlineAfter(_ ol: CPDFOutline) {
  309. Task { @MainActor in
  310. self.tocOutlineView.reloadData()
  311. }
  312. }
  313. func demoteOutlineAfter(_ ol: CPDFOutline) {
  314. Task { @MainActor in
  315. self.tocOutlineView.reloadData()
  316. self.tocOutlineView.expandItem(ol.parent)
  317. self.tocOutlineView.km_selectItem(ol, byExtendingSelection: false)
  318. }
  319. }
  320. func promoteOutlineAfter(_ ol: CPDFOutline) {
  321. Task { @MainActor in
  322. self.tocOutlineView.reloadData()
  323. self.tocOutlineView.km_selectItem(ol, byExtendingSelection: false)
  324. }
  325. }
  326. func showOutlineEmptyView() {
  327. let view = self.tocOutlineView.enclosingScrollView?.documentView
  328. let viewFrame = view?.frame ?? .zero
  329. let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  330. self.leftSideEmptyVC.emptyOutlineView.frame = NSMakeRect((viewFrame.size.width-emptyVcSize.width)/2.0,(viewFrame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height)
  331. self.leftSideEmptyVC.emptyOutlineView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  332. self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyOutlineView)
  333. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = false
  334. }
  335. func hideOutlineEmptyView() {
  336. self.leftSideEmptyVC.emptyOutlineView.removeFromSuperview()
  337. self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = true
  338. }
  339. func fetchOutlines(for ol: CPDFOutline, searchString: String) -> [CPDFOutline] {
  340. var ols: [CPDFOutline] = []
  341. for i in 0 ..< ol.numberOfChildren {
  342. guard let child = ol.child(at: i) else {
  343. continue
  344. }
  345. if self.hasContainString(searchString, rootOutline: child) {
  346. ols.append(child)
  347. }
  348. }
  349. return ols
  350. }
  351. @objc func goToSelectedOutlineItem(_ sender: AnyObject?) {
  352. let cnt = self.tocOutlineView.selectedRowIndexes.count
  353. if cnt == 0 || cnt > 1 {
  354. return
  355. }
  356. guard let item = self.tocOutlineView.selectedItem() else {
  357. return
  358. }
  359. if let bk = item as? CPDFBookmark {
  360. self.listView?.go(toPageIndex: bk.pageIndex, animated: true)
  361. } else if let ol = item as? CPDFOutline {
  362. if let dest = ol.destination {
  363. self.listView?.go(to: dest)
  364. } else if let act = ol.action {
  365. if !self.isFirst {
  366. self.listView?.perform(act)
  367. }
  368. }
  369. }
  370. self.isFirst = false
  371. }
  372. public func refreshUIOfOutlineIfNeed() {
  373. if self.type.methodType != .Outline {
  374. return
  375. }
  376. Task { @MainActor in
  377. self.tocOutlineView.reloadData()
  378. }
  379. }
  380. }
  381. // MARK: - Undo & Redo
  382. extension KMLeftSideViewController {
  383. @objc dynamic func changePDFOutlineDestination(_ destination: CPDFDestination?, PDFoutline outline: CPDFOutline) {
  384. if let des = destination {
  385. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).changePDFOutlineDestination(outline.destination, PDFoutline: outline)
  386. let newDes = CPDFDestination(document: des.document, pageIndex: des.pageIndex, at: des.point, zoom: des.zoom)
  387. outline.destination = newDes
  388. self.tocOutlineView.reloadItem(outline)
  389. }
  390. }
  391. @objc dynamic func changePDFAction(_ action: CPDFAction?, PDFOutline outline: CPDFOutline) {
  392. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).changePDFAction(outline.action, PDFOutline: outline)
  393. outline.action = action
  394. }
  395. @objc dynamic func renamePDFOutline(_ outline: CPDFOutline, label: String) {
  396. if (self.isRenameNoteOutline) {
  397. if outline is CPDFAnnotation {
  398. // if([outline isKindOfClass:[PDFAnnotation class]]) {
  399. // PDFAnnotation *annotation = (PDFAnnotation *)outline;
  400. // annotation.string = label;
  401. // [rightSideController.noteOutlineView reloadData];
  402. // [rightSideController.noteOutlineView selectRowIndexes:[[[NSIndexSet alloc] initWithIndex:[rightSideController.noteOutlineView rowForItem:outline]] autorelease] byExtendingSelection:NO];
  403. }
  404. } else {
  405. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).renamePDFOutline(outline, label: outline.label)
  406. outline.label = label
  407. self.tocOutlineView.reloadData()
  408. self.tocOutlineView.km_selectItem(outline, byExtendingSelection: false)
  409. }
  410. }
  411. @objc dynamic func addoutline(parent parentOutline: CPDFOutline?, addOutline: CPDFOutline, index: Int, needExpand: Bool) {
  412. var tempO: CPDFOutline? = addOutline
  413. if addOutline.label != nil {
  414. parentOutline?.insertChild(addOutline, at: UInt(index))
  415. } else {
  416. let outline = parentOutline?.km_insertChild(label: String(format: "%@ %ld", KMLocalizedString("Page", nil), self.currentPageIndex()+1), dest: self.currentDestination(), at: index)
  417. tempO = outline
  418. }
  419. guard let outline = tempO else {
  420. return
  421. }
  422. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).removeOutline(parent: parentOutline, removeOutline: outline, index: index, needExpand: needExpand)
  423. self.view.window?.makeFirstResponder(nil)
  424. Task { @MainActor in
  425. self.tocOutlineView.reloadData()
  426. if (needExpand) {
  427. self.tocOutlineView.expandItem(parentOutline)
  428. }
  429. let idx = self.tocOutlineView.row(forItem: outline)
  430. self.tocOutlineView.selectRowIndexes(IndexSet(integer: idx), byExtendingSelection: false)
  431. self.newAddOutlineEntryEditingMode(index)
  432. }
  433. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  434. self.tocOutlineView.scrollRowToVisible(self.tocOutlineView.row(forItem: outline))
  435. }
  436. }
  437. @objc dynamic func removeOutline(parent parentOutline: CPDFOutline?, removeOutline: CPDFOutline, index: Int, needExpand: Bool) {
  438. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).addoutline(parent: parentOutline, addOutline: removeOutline, index: index, needExpand: true)
  439. removeOutline.removeFromParent()
  440. if (needExpand) {
  441. self.tocOutlineView.expandItem(parentOutline)
  442. }
  443. Task { @MainActor in
  444. self.tocOutlineView.reloadData()
  445. }
  446. }
  447. @objc dynamic func dragPDFOutline(_ outline: CPDFOutline?, toIndex index: Int, newParentOutline: CPDFOutline?) {
  448. guard let doc = self.view.window?.windowController?.document as? NSDocument else {
  449. NSSound.beep()
  450. return
  451. }
  452. if outline == nil {
  453. NSSound.beep()
  454. return
  455. }
  456. (doc.undoManager?.prepare(withInvocationTarget: self) as AnyObject).dragPDFOutline(outline, toIndex: Int(outline!.index), newParentOutline: outline?.parent)
  457. outline?.removeFromParent()
  458. newParentOutline?.insertChild(outline, at: UInt(index))
  459. self.tocOutlineView.reloadData()
  460. self.tocOutlineView.expandItem(newParentOutline)
  461. self.tocOutlineView.selectRowIndexes(IndexSet(integer: self.tocOutlineView.row(forItem: outline)), byExtendingSelection: false)
  462. }
  463. }
  464. // MARK: - Menu Actions
  465. extension KMLeftSideViewController {
  466. func outlineListMenu(_ menu: NSMenu) {
  467. _ = menu.addItem(withTitle: NSLocalizedString("Add Item", comment: ""), action: #selector(outlineContextMenuItemClicked_AddEntry), target: self, tag: KMOutlineViewMenuItemTag.addEntry.rawValue)
  468. _ = menu.addItem(withTitle: NSLocalizedString("Add Sub-Item", comment: ""), action: #selector(outlineContextMenuItemClicked_AddChildEntry), target: self, tag: KMOutlineViewMenuItemTag.addChild.rawValue)
  469. _ = menu.addItem(withTitle: NSLocalizedString("Add To A Higher Level", comment: ""), action: #selector(outlineContextMenuItemClicked_AddAuntEntry), target: self, tag: KMOutlineViewMenuItemTag.addAunt.rawValue)
  470. menu.addItem(.separator())
  471. _ = menu.addItem(withTitle: NSLocalizedString("Delete", comment: ""), action: #selector(outlineContextMenuItemClicked_RemoveEntry), target: self, tag: KMOutlineViewMenuItemTag.remove.rawValue)
  472. menu.addItem(.separator())
  473. _ = menu.addItem(withTitle: NSLocalizedString("Edit", comment: ""), action: #selector(outlineContextMenuItemClicked_Edit), target: self, tag: KMOutlineViewMenuItemTag.edit.rawValue)
  474. _ = menu.addItem(withTitle: NSLocalizedString("Change Destination", comment: ""), action: #selector(outlineContextMenuItemClicked_SetDestination), target: self, tag: KMOutlineViewMenuItemTag.setDestination.rawValue)
  475. _ = menu.addItem(withTitle: NSLocalizedString("Rename", comment: ""), action: #selector(outlineContextMenuItemClicked_Rename), target: self, tag: KMOutlineViewMenuItemTag.rename.rawValue)
  476. menu.addItem(.separator())
  477. _ = menu.addItem(withTitle: NSLocalizedString("Promote", comment: ""), action: #selector(outlineContextMenuItemClicked_Promote), target: self, tag: KMOutlineViewMenuItemTag.promote.rawValue)
  478. _ = menu.addItem(withTitle: NSLocalizedString("Demote", comment: ""), action: #selector(outlineContextMenuItemClicked_Demote), target: self, tag: KMOutlineViewMenuItemTag.demote.rawValue)
  479. }
  480. func outlineMoreMenu(_ view: NSButton) {
  481. let menu = NSMenu()
  482. let expandAllItem = menu.addItem(title: KMLocalizedString("Expand All", nil), action: #selector(toc_expandAllComments), target: self)
  483. expandAllItem?.representedObject = self.tocOutlineView
  484. let foldAllItem = menu.addItem(title: KMLocalizedString("Collapse All", nil), action: #selector(toc_foldAllComments), target: self)
  485. foldAllItem?.representedObject = self.tocOutlineView
  486. let rootOL = self.outlineRoot()
  487. let childNum = rootOL?.numberOfChildren ?? 0
  488. var num = 0
  489. for i in 0 ..< childNum {
  490. let ol = rootOL?.child(at: i)
  491. if self.tocOutlineView.isItemExpanded(ol) {
  492. num += 1
  493. }
  494. }
  495. self.tocType = .none
  496. if childNum > 0 {
  497. if num == 0 {
  498. self.tocType = .fold
  499. } else if num == childNum {
  500. self.tocType = .unfold
  501. }
  502. }
  503. expandAllItem?.state = self.tocType == .unfold ? .on : .off
  504. foldAllItem?.state = self.tocType == .fold ? .on : .off
  505. let removeEntryItem = menu.addItem(title: KMLocalizedString("Remove All Outlines", nil), action: #selector(leftSideEmptyAnnotationClick_DeleteOutline), target: self)
  506. removeEntryItem?.representedObject = self.tocOutlineView
  507. if let data = NSApp.currentEvent {
  508. NSMenu.popUpContextMenu(menu, with: data, for: view)
  509. }
  510. }
  511. func outlineListValidateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  512. if self.isLocked() {
  513. return false
  514. }
  515. let action = menuItem.action
  516. if (action == #selector(leftSideEmptyAnnotationClick_DeleteOutline)) {
  517. guard let rootOL = self.outlineRoot() else {
  518. return false
  519. }
  520. let childNum = rootOL.numberOfChildren
  521. if (self.isSearchOutlineMode) {
  522. let ols = self.fetchOutlines(for: rootOL, searchString: self.outlineSearchField.stringValue)
  523. return ols.count > 0
  524. } else {
  525. return childNum > 0
  526. }
  527. } else if action == #selector(toggleOutlineCaseInsensitiveSearch) {
  528. menuItem.state = self.outlineIgnoreCaseFlag ? .on : .off
  529. return true
  530. }
  531. if (self.isSearchOutlineMode) {
  532. if (action == #selector(outlineContextMenuItemClicked_AddEntry) ||
  533. action == #selector(outlineContextMenuItemClicked_AddChildEntry) ||
  534. action == #selector(outlineContextMenuItemClicked_AddAuntEntry) ||
  535. action == #selector(outlineContextMenuItemClicked_Edit) ||
  536. action == #selector(outlineContextMenuItemClicked_Rename)
  537. ) {
  538. return false
  539. }
  540. }
  541. if (self.tocOutlineView.selectedRowIndexes.count > 1) {
  542. if (menuItem.tag == KMOutlineViewMenuItemTag.remove.rawValue) {
  543. return true
  544. }
  545. return false
  546. } else if (self.tocOutlineView.selectedRowIndexes.count > 0) {
  547. if (action == #selector(outlineContextMenuItemClicked_AddChildEntry) ||
  548. action == #selector(outlineContextMenuItemClicked_SetDestination)) {
  549. return true
  550. }
  551. }
  552. if (self.tocOutlineView.clickedRow == -1) {
  553. if (action == #selector(outlineContextMenuItemClicked_AddEntry)) {
  554. return true
  555. } else {
  556. return false
  557. }
  558. } else {
  559. let clickedOutline = self.tocOutlineView.item(atRow: self.tocOutlineView.clickedRow) as? CPDFOutline
  560. if (action == #selector(outlineContextMenuItemClicked_Demote)) {
  561. if let data = clickedOutline {
  562. return self.pdfDocument()?.canDemote(outline: data) ?? false
  563. }
  564. return false
  565. }
  566. if (action == #selector(outlineContextMenuItemClicked_Promote)) {
  567. if let data = clickedOutline {
  568. return self.pdfDocument()?.canPromote(outline: data) ?? false
  569. } else {
  570. return false
  571. }
  572. }
  573. if (action == #selector(outlineContextMenuItemClicked_AddAuntEntry)) {
  574. let parentOutLine = clickedOutline?.parent
  575. let grandparentOutLine = parentOutLine?.parent
  576. if (grandparentOutLine != nil) {
  577. return true
  578. } else {
  579. return false
  580. }
  581. }
  582. }
  583. return true
  584. }
  585. //添加子节点
  586. @objc func outlineContextMenuItemClicked_AddChildEntry(_ sender: AnyObject?) {
  587. guard let row = self.selectedRowIndexes().last else {
  588. return
  589. }
  590. let item = self.tocOutlineView.item(atRow: row) as? CPDFOutline
  591. let ol = CPDFOutline()
  592. ol.label = String(format: "%@ %ld", KMLocalizedString("Page", nil), "\(self.currentPageIndex() + 1)")
  593. ol.destination = self.currentDestination()
  594. self.addoutline(parent: item, addOutline: ol, index: Int(item?.numberOfChildren ?? 0), needExpand: true)
  595. }
  596. //添加上一级节点
  597. @objc func outlineContextMenuItemClicked_AddAuntEntry(_ sender: AnyObject?) {
  598. guard let row = self.selectedRowIndexes().last else {
  599. return
  600. }
  601. let item = self.tocOutlineView.item(atRow: row) as? CPDFOutline
  602. let parentOL = item?.parent
  603. if parentOL?.parent != nil {
  604. let ol = CPDFOutline()
  605. ol.label = String(format: "%@ %ld", KMLocalizedString("Page", nil), "\(self.currentPageIndex() + 1)")
  606. ol.destination = self.currentDestination()
  607. self.addoutline(parent: parentOL?.parent, addOutline: ol, index: Int(parentOL?.index ?? 0) + 1, needExpand: false)
  608. }
  609. }
  610. //移除节点
  611. @objc func outlineContextMenuItemClicked_RemoveEntry(_ sender: AnyObject?) {
  612. for idx in self.selectedRowIndexes() {
  613. let item = self.tocOutlineView.item(atRow: idx)
  614. if let ol = item as? CPDFOutline {
  615. self.removeOutline(parent: ol.parent , removeOutline: ol, index: Int(ol.index), needExpand: false)
  616. }
  617. }
  618. }
  619. //重置目的
  620. @objc func outlineContextMenuItemClicked_SetDestination(_ sender: AnyObject?) {
  621. guard let ol = self.tocOutlineView.clickedItem() as? CPDFOutline else {
  622. return
  623. }
  624. Task {
  625. let res = 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)])
  626. if (res == .alertFirstButtonReturn) {
  627. self.changePDFOutlineDestination(self.currentDestination(), PDFoutline: ol)
  628. let idx = self.tocOutlineView.row(forItem: ol)
  629. self.tocOutlineView.km_safe_selectRowIndexes(.init(integer: idx), byExtendingSelection: false)
  630. }
  631. }
  632. }
  633. //弹出菜单
  634. @objc func outlineContextMenuItemClicked_Edit(_ sender: AnyObject?) {
  635. let ol: CPDFOutline? = self.tocOutlineView.km.clickedItem()
  636. guard let _ = ol?.km_page else {
  637. return
  638. }
  639. let popover = NSPopover()
  640. popover.delegate = self
  641. let vc = KMOutlineEditViewController(outline: ol, document: self.listView)
  642. if let cell = self.tocOutlineView.rowView(atRow: self.tocOutlineView.clickedRow, makeIfNecessary: true) {
  643. popover.contentViewController = vc
  644. popover.animates = true
  645. popover.behavior = .transient
  646. popover.show(relativeTo: cell.bounds, of: cell, preferredEdge: .minX)
  647. }
  648. }
  649. //重命名
  650. @objc func outlineContextMenuItemClicked_Rename(_ sender: AnyObject?) {
  651. if (self.tocOutlineView.clickedRow < 0) {
  652. return
  653. }
  654. self.renamePDFOutline = self.tocOutlineView.km.clickedItem()
  655. let cell = self.tocOutlineView.view(atColumn: 0, row: self.tocOutlineView.clickedRow, makeIfNecessary: true)
  656. let tf = cell?.subviews.first as? NSTextField
  657. self.renamePDFOutlineTextField = tf
  658. tf?.delegate = self
  659. tf?.isEditable = true
  660. tf?.becomeFirstResponder()
  661. }
  662. //降级节点
  663. @objc func outlineContextMenuItemClicked_Demote(_ sender: AnyObject?) {
  664. self.delegate?.controller?(controller: self, itemClick: sender, itemKey: .demote, params: nil)
  665. }
  666. //升级节点
  667. @objc func outlineContextMenuItemClicked_Promote(_ sender: AnyObject?) {
  668. self.delegate?.controller?(controller: self, itemClick: sender, itemKey: .promote, params: nil)
  669. }
  670. @objc func toggleOutlineCaseInsensitiveSearch(_ sender: NSMenuItem) {
  671. if (sender.state == .on) {
  672. self.outlineIgnoreCaseFlag = false
  673. } else {
  674. self.outlineIgnoreCaseFlag = true
  675. }
  676. if (self.outlineSearchField.stringValue.isEmpty == false) {
  677. self.tocOutlineView.reloadData()
  678. self.tocOutlineView.expandItem(nil, expandChildren: true)
  679. }
  680. }
  681. }
  682. // MARK: - KMTocOutlineViewDelegate
  683. extension KMLeftSideViewController: KMTocOutlineViewDelegate {
  684. func outlineView(_ anOutlineView: NSOutlineView, highlightLevelForRow row: Int) -> Int {
  685. if self.tocOutlineView.isEqual(to: anOutlineView) {
  686. let numRows = anOutlineView.numberOfRows
  687. if let outline = anOutlineView.item(atRow: row) as? CPDFOutline {
  688. let firstPage = outline.km_pageIndex
  689. var lastPage = self.pageCount()
  690. if row + 1 < numRows {
  691. lastPage = Int((anOutlineView.item(atRow: row + 1) as? CPDFOutline)?.km_pageIndex ?? UInt(NSNotFound))
  692. }
  693. // NSRange range = NSMakeRange(firstPage, MAX(1LU, lastPage - firstPage));
  694. // NSUInteger i, iMax = [lastViewedPages count];
  695. // for (i = 0; i < iMax; i++) {
  696. // if (NSLocationInRange((NSUInteger)[lastViewedPages pointerAtIndex:i], range))
  697. // return i;
  698. // }
  699. }
  700. }
  701. return NSNotFound
  702. }
  703. func outlineView(_ anOutlineView: NSOutlineView, imageContextForItem item: Any?) -> AnyObject? {
  704. if anOutlineView.isEqual(to: self.tocOutlineView) {
  705. if item == nil {
  706. return true as AnyObject
  707. }
  708. if item is CPDFOutline {
  709. return (item as! CPDFOutline).destination
  710. }
  711. }
  712. return nil
  713. }
  714. }
  715. extension KMLeftSideViewController: KMNoteOutlineViewDelegate {
  716. func outlineView(_ anOutlineView: NSOutlineView, canResizeRowByItem item: AnyObject?) -> Bool? {
  717. if anOutlineView.isEqual(to: self.noteOutlineView) {
  718. return true
  719. }
  720. return false
  721. }
  722. func outlineView(_ anOutlineView: NSOutlineView, setHeight newHeight: CGFloat, ofRowByItem item: AnyObject?) {
  723. // [rowHeights setFloat:newHeight forKey:item];
  724. }
  725. func outlineView(_ anOutlineView: NSOutlineView, didChangeHiddenOfTableColumn aTableColumn: NSTableColumn) {
  726. // if (mwcFlags.autoResizeNoteRows &&
  727. // [ov isEqual:rightSideController.noteOutlineView] &&
  728. // [[tableColumn identifier] isEqualToString:NOTE_COLUMNID]) {
  729. // [rowHeights removeAllFloats];
  730. // [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  731. // }
  732. }
  733. func outlineViewCommandKeyPressedDuringNavigation(_ anOutlineView: NSOutlineView) {
  734. // PDFAnnotation *annotation = [[self selectedNotes] lastObject];
  735. // if (annotation) {
  736. // [pdfView scrollAnnotationToVisible:annotation];
  737. // [pdfView setActiveAnnotation:annotation];
  738. // }
  739. }
  740. }