KMNOutlineController.swift 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  1. //
  2. // KMNOutlineController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by User-Tangchao on 2024/11/12.
  6. //
  7. import Cocoa
  8. import KMComponentLibrary
  9. class KMNOutlineController: KMNBaseViewController {
  10. @IBOutlet weak var outlineView: NSView!
  11. @IBOutlet weak var outlineMoreButton: NSButton!
  12. @IBOutlet weak var outlineAddButton: NSButton!
  13. @IBOutlet weak var outlineSearchButton: NSButton!
  14. @IBOutlet weak var outlineLabel: NSTextField!
  15. @IBOutlet weak var outlineSearchField: KMLeftSideViewSearchField!
  16. @IBOutlet weak var outlineDoneButton: NSButton!
  17. @IBOutlet var tocOutlineView: KMTocOutlineView!
  18. var handdler = KMNOutlineHanddler()
  19. var isSearchOutlineMode = false
  20. convenience init() {
  21. self.init(nibName: "KMNOutlineController", bundle: nil)
  22. }
  23. override func viewDidLoad() {
  24. super.viewDidLoad()
  25. // Do view setup here.
  26. if let data = tocOutlineView.enclosingScrollView {
  27. view.addSubview(data)
  28. data.frame = view.bounds
  29. data.autoresizingMask = [.width, .height]
  30. }
  31. initSubViews()
  32. initDefalutValue()
  33. }
  34. override func updateUILanguage() {
  35. super.updateUILanguage()
  36. }
  37. override func updateUIThemeColor() {
  38. super.updateUIThemeColor()
  39. KMMainThreadExecute {
  40. self.view.wantsLayer = true
  41. let color = ComponentLibrary.shared.getComponentColorFromKey("colorBg/layout-middle")
  42. self.view.layer?.backgroundColor = color.cgColor
  43. }
  44. }
  45. func initSubViews() {
  46. // self.outlineSearchField.delegate = self
  47. // self.outlineAddButton.target = self
  48. // self.outlineAddButton.action = #selector(outlineContextMenuItemClicked_AddEntry)
  49. //
  50. // self.outlineMoreButton.target = self
  51. // self.outlineMoreButton.tag = 302
  52. // self.outlineMoreButton.action = #selector(leftSideViewMoreButtonAction)
  53. //
  54. // self.outlineDoneButton.target = self
  55. // self.outlineDoneButton.tag = 310
  56. // self.outlineDoneButton.action = #selector(leftSideViewDoneButtonAction)
  57. //
  58. // let menuOutline = NSMenu()
  59. // _ = menuOutline.addItem(title: KMLocalizedString("Ignore Case"), action: #selector(toggleOutlineCaseInsensitiveSearch), target: self)
  60. // (self.outlineSearchField.cell as? NSSearchFieldCell)?.searchMenuTemplate = menuOutline
  61. // self.outlineSearchField.target = self
  62. // self.tocOutlineView.menu = NSMenu()
  63. // self.tocOutlineView.menu?.delegate = self
  64. self.tocOutlineView.delegate = self
  65. self.tocOutlineView.dataSource = self
  66. self.tocOutlineView.botaDelegate = self
  67. self.tocOutlineView.botaDataSource = self
  68. self.tocOutlineView.tocDelegate = self
  69. self.tocOutlineView.registerForDraggedTypes([.localDraggedTypes])
  70. self.tocOutlineView.target = self
  71. self.tocOutlineView.doubleAction = #selector(outlineContextMenuItemClicked_Rename)
  72. }
  73. func initDefalutValue() {
  74. // self.outlineView.wantsLayer = true
  75. // self.outlineView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  76. //
  77. // self.outlineLabel.stringValue = KMLocalizedString("Outline");
  78. // self.outlineLabel.textColor = KMAppearance.Layout.h0Color()
  79. // self.outlineAddButton.toolTip = KMLocalizedString("Add Item")
  80. //
  81. // self.outlineSearchButton.toolTip = KMLocalizedString("Search")
  82. //
  83. // self.outlineDoneButton.title = KMLocalizedString("Done");
  84. // self.outlineDoneButton.toolTip = KMLocalizedString("Done");
  85. // self.outlineDoneButton.setTitleColor(KMAppearance.Layout.w0Color())
  86. // self.outlineDoneButton.wantsLayer = true
  87. // self.outlineDoneButton.layer?.backgroundColor = KMAppearance.Interactive.a0Color().cgColor
  88. // self.outlineDoneButton.layer?.cornerRadius = 4.0
  89. //
  90. // self.outlineSearchField.wantsLayer = true
  91. // self.outlineSearchField.backgroundColor = KMAppearance.Layout.l_1Color()
  92. // self.outlineSearchField.layer?.backgroundColor = KMAppearance.Layout.l_1Color().cgColor
  93. // self.outlineSearchField.layer?.borderWidth = 1.0
  94. // self.outlineSearchField.layer?.borderColor = KMAppearance.Interactive.a0Color().cgColor
  95. //
  96. // self.outlineDoneButton.isHidden = true
  97. // self.outlineSearchField.isHidden = true
  98. //
  99. // (self.outlineSearchField.cell as? NSSearchFieldCell)?.placeholderString = KMLocalizedString("Search Outline")
  100. // self.tocOutlineView.backgroundColor = KMAppearance.Layout.l0Color()
  101. tocOutlineView.backgroundColor = .orange
  102. tocOutlineView.enclosingScrollView?.drawsBackground = false
  103. tocOutlineView.enclosingScrollView?.backgroundColor = .blue
  104. tocOutlineView.enclosingScrollView?.wantsLayer = true
  105. tocOutlineView.enclosingScrollView?.layer?.backgroundColor = NSColor.red.cgColor
  106. self.tocOutlineView.autoresizesOutlineColumn = false
  107. self.tocOutlineView.allowsMultipleSelection = true
  108. self.tocOutlineView.allowsEmptySelection = true
  109. self.tocOutlineView.focusRingType = .none
  110. self.tocOutlineView.autoresizesSubviews = true
  111. }
  112. func updateOutlineSelection() {
  113. // if self.outlineRoot() == nil || self.updatingOutlineSelection {
  114. // return
  115. // }
  116. // self.updatingOutlineSelection = true
  117. // let numRows = self.tocOutlineView.numberOfRows
  118. // let currentPage = self.currentPage()
  119. // var flagIdx = NSNotFound
  120. // for i in 0 ..< numRows {
  121. // guard let ol = self.tocOutlineView.item(atRow: i) as? CPDFOutline else {
  122. // continue
  123. // }
  124. // guard let page = ol.km_page else {
  125. // continue
  126. // }
  127. // if page.isEqual(to: currentPage) {
  128. // flagIdx = i
  129. // break
  130. // }
  131. // }
  132. //
  133. // if flagIdx != NSNotFound {
  134. // self.tocOutlineView.km_safe_selectRowIndexes(.init(integer: flagIdx), byExtendingSelection: false)
  135. // self.tocOutlineView.scrollRowToVisible(flagIdx)
  136. // } else {
  137. // self.tocOutlineView.deselectRow(self.tocOutlineView.selectedRow)
  138. // }
  139. // self.updatingOutlineSelection = false
  140. }
  141. func newAddOutlineEntryEditingMode(_ index: Int) {
  142. // self.renamePDFOutline = self.tocOutlineView.item(atRow: self.tocOutlineView.selectedRow) as? CPDFOutline
  143. // let row = self.tocOutlineView.selectedRow
  144. // let viewS = self.tocOutlineView.view(atColumn: 0, row: row, makeIfNecessary: true)
  145. // let targrtTextField = viewS?.subviews.first as? NSTextField
  146. // self.renamePDFOutlineTextField = targrtTextField
  147. // targrtTextField?.delegate = self
  148. // targrtTextField?.isEditable = true
  149. // targrtTextField?.becomeFirstResponder()
  150. }
  151. func selectedRowIndexes() -> IndexSet {
  152. var selectedIndexes = self.tocOutlineView.selectedRowIndexes
  153. let clickedRow = self.tocOutlineView.clickedRow
  154. if clickedRow != -1 && selectedIndexes.contains(clickedRow) == false {
  155. let indexes = IndexSet(integer: clickedRow)
  156. selectedIndexes = indexes
  157. }
  158. return selectedIndexes
  159. }
  160. func editOutlineUI(_ editVC: KMOutlineEditViewController) {
  161. guard let ol = editVC.outline else {
  162. return
  163. }
  164. if editVC.pageButton.state == .on {
  165. let numberString = editVC.outlineTargetPageIndexTextField.stringValue
  166. let idx = Int(numberString) ?? 1
  167. let newPage = editVC.pdfView?.document.page(at: UInt(idx-1))
  168. if let data = newPage?.pageIndex(), data != editVC.originalPageIndex {
  169. //新page不存在
  170. if (newPage == nil) {
  171. } else {
  172. let pageSize = newPage?.bounds(for: .cropBox).size ?? .zero
  173. if let dest = CPDFDestination(page: newPage, at: NSMakePoint(pageSize.width, pageSize.height)) {
  174. self.changePDFOutlineDestination(dest, PDFoutline: ol)
  175. }
  176. }
  177. }
  178. } else if editVC.urlButton.state == .on {
  179. var urlString = editVC.outlineURLTextField.stringValue
  180. let tLowerUrl = urlString.lowercased()
  181. if tLowerUrl.hasPrefix(kHTTPSPrefix) == false && tLowerUrl.hasPrefix(kFTPPrefix) == false && tLowerUrl.hasPrefix(kHTTPPrefix) == false && urlString.isEmpty == false {
  182. urlString = "\(kHTTPPrefix)\(urlString)"
  183. }
  184. if let act = CPDFURLAction(url: urlString) {
  185. if editVC.originalURLString != editVC.outlineURLTextField.stringValue {
  186. self.changePDFAction(act, PDFOutline: ol)
  187. }
  188. }
  189. } else if editVC.mailButton.state == .on {
  190. var mailString = editVC.mailAddressTextField.stringValue
  191. let tLowerStr = mailString.lowercased()
  192. if tLowerStr.hasPrefix(kEmailPrefix) == false {
  193. mailString = "\(kEmailPrefix)\(mailString)"
  194. }
  195. if var urlAction = CPDFURLAction(url: mailString) {
  196. if urlAction.url() == nil {
  197. urlAction = CPDFURLAction(url: kEmailPrefix)
  198. }
  199. if mailString != editVC.originalURLString {
  200. self.changePDFAction(urlAction, PDFOutline: ol)
  201. }
  202. }
  203. }
  204. if editVC.outlineNameTextView.string != editVC.originalLabel {
  205. self.renamePDFOutline(ol, label: editVC.outlineNameTextView.string)
  206. }
  207. }
  208. @objc func outlineContextMenuItemClicked_AddEntry(_ sender: AnyObject?) {
  209. // let ris = self.selectedRowIndexes()
  210. // if ris.isEmpty {
  211. // var rootOL = self.outlineRoot()
  212. // if rootOL == nil {
  213. // rootOL = self.setNewOutlineRoot()
  214. // }
  215. //
  216. // let ol = CPDFOutline()
  217. // ol.label = String(format: "%@ %ld", KMLocalizedString("Page"), self.currentPageIndex()+1)
  218. // ol.destination = self.currentDestination()
  219. // self.addoutline(parent: rootOL, addOutline: ol, index: Int(rootOL?.numberOfChildren ?? 0), needExpand: false)
  220. // return
  221. // }
  222. //
  223. // if let row = ris.last {
  224. // let item = self.tocOutlineView.item(atRow: row) as? CPDFOutline
  225. // let ol = CPDFOutline()
  226. // ol.label = String(format: "%@ %ld", KMLocalizedString("Page"), self.currentPageIndex()+1)
  227. // ol.destination = self.currentDestination()
  228. // let idx = Int(item?.index ?? 0) + 1
  229. // self.addoutline(parent: item?.parent, addOutline: ol, index: idx, needExpand: false)
  230. // self.tocOutlineView.scrollRowToVisible(idx)
  231. // self.tocOutlineView.deselectRow(idx)
  232. // }
  233. }
  234. @IBAction func outlineNormalSearchButtonAction(_ sender: NSButton) {
  235. self.outlineSearchField.isHidden = false
  236. self.outlineDoneButton.isHidden = false
  237. self.outlineLabel.isHidden = true
  238. self.outlineSearchButton.isHidden = true
  239. self.outlineMoreButton.isHidden = true
  240. self.outlineAddButton.isHidden = true
  241. self.outlineSearchField.becomeFirstResponder()
  242. }
  243. @IBAction func toc_expandAllComments(_ sender: AnyObject?) {
  244. // if (self.tocType == .unfold) {
  245. // return
  246. // }
  247. // self.tocType = .unfold
  248. // self.tocOutlineView.expandItem(nil, expandChildren: true)
  249. }
  250. @IBAction func toc_foldAllComments(_ sender: AnyObject?) {
  251. // if (self.tocType == .fold) {
  252. // return
  253. // }
  254. // self.tocType = .fold
  255. // self.tocOutlineView.collapseItem(nil, collapseChildren: true)
  256. }
  257. @objc func leftSideEmptyAnnotationClick_DeleteOutline(_ sender: AnyObject?) {
  258. let alert = NSAlert()
  259. alert.alertStyle = .critical
  260. alert.messageText = ""
  261. alert.informativeText = KMLocalizedString("This will permanently remove all outlines. Are you sure to continue?")
  262. alert.addButton(withTitle: KMLocalizedString("Yes"))
  263. alert.addButton(withTitle: KMLocalizedString("No"))
  264. let response = alert.runModal()
  265. if response == .alertFirstButtonReturn {
  266. // if let item = self.outlineRoot() {
  267. // self.removeAllOutline(item)
  268. // }
  269. }
  270. }
  271. func showSearchOutlineBlankState(_ toShowState: Bool) {
  272. // if (toShowState) {
  273. // let documentViewFrame = self.tocOutlineView.enclosingScrollView?.documentView?.frame ?? .zero
  274. // let width = self.leftSideEmptyVC.outlineSearchView.bounds.size.width
  275. // let height = self.leftSideEmptyVC.outlineSearchView.bounds.size.height
  276. // self.leftSideEmptyVC.outlineSearchView.frame = NSMakeRect((documentViewFrame.size.width - width)/2.0, (documentViewFrame.size.height - height)/2.0, width, height)
  277. // self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.outlineSearchView)
  278. // self.leftSideEmptyVC.outlineSearchView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  279. // } else {
  280. // self.leftSideEmptyVC.outlineSearchView.removeFromSuperview()
  281. // }
  282. }
  283. func removeAllOutline(_ outline: CPDFOutline) {
  284. // _ = self.setNewOutlineRoot()
  285. //
  286. // for i in 0 ..< self.pageCount() {
  287. // self.pdfDocument()?.removeBookmark(forPageIndex: UInt(i))
  288. // }
  289. // self.layoutDocumentView()
  290. // DispatchQueue.main.async {
  291. // }
  292. }
  293. func updateSelectRowHeight() {
  294. guard let ol = self.tocOutlineView.selectedItem() as? CPDFOutline else {
  295. return
  296. }
  297. let attriString = NSMutableAttributedString()
  298. let attri = [NSAttributedString.Key.foregroundColor : KMAppearance.Layout.h0Color()]
  299. attriString.append(.init(string: ol.label ?? "", attributes: attri))
  300. let row = self.tocOutlineView.selectedRow
  301. let column = self.tocOutlineView.tableColumn(withIdentifier: kLabelColumnId)
  302. let cell = column?.dataCell(forRow: row)
  303. (cell as? NSCell)?.objectValue = attriString
  304. let w = self.view.frame.size.width-86
  305. let num = self.getNum(ol)
  306. let gap = self.tocOutlineView.indentationPerLevel
  307. var rowH = ((cell as? NSCell)?.cellSize(forBounds: NSMakeRect(0, 0, w - (num > 0 ? 16 : 0) - gap * num.cgFloat, CGFloat.greatestFiniteMagnitude)).height) ?? 0
  308. rowH = fmax(rowH, self.tocOutlineView.rowHeight) + 25
  309. let view = self.tocOutlineView.view(atColumn: 0, row: row, makeIfNecessary: true)
  310. let frame = view?.frame ?? .zero
  311. view?.frame = NSMakeRect(frame.origin.x, frame.origin.y, frame.size.width, rowH)
  312. }
  313. func getNum(_ ol: CPDFOutline?) -> Int {
  314. var num = 0
  315. var outline = ol?.parent
  316. repeat {
  317. outline = outline?.parent
  318. if outline != nil {
  319. num += 1
  320. }
  321. } while outline != nil
  322. return num
  323. }
  324. func addOutlineAfter(_ ol: CPDFOutline) {
  325. // if self.leftView.segmentedControl.selectedSegment == 2 {
  326. //
  327. // } else {
  328. // self.leftView.segmentedControl.selectedSegment = 2
  329. // }
  330. //
  331. // Task { @MainActor in
  332. //
  333. // let idx = self.tocOutlineView.row(forItem: ol)
  334. // self.updatingOutlineSelection = true
  335. // self.tocOutlineView.km_selectItem(ol, byExtendingSelection: false)
  336. // self.updatingOutlineSelection = false
  337. // self.newAddOutlineEntryEditingMode(idx)
  338. // }
  339. //
  340. // DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  341. // self.tocOutlineView.scrollRowToVisible(self.tocOutlineView.row(forItem: ol))
  342. // }
  343. }
  344. func removeOutlineAfter(_ ol: CPDFOutline) {
  345. Task { @MainActor in
  346. }
  347. }
  348. func demoteOutlineAfter(_ ol: CPDFOutline) {
  349. Task { @MainActor in
  350. self.tocOutlineView.expandItem(ol.parent)
  351. self.tocOutlineView.km_selectItem(ol, byExtendingSelection: false)
  352. }
  353. }
  354. func promoteOutlineAfter(_ ol: CPDFOutline) {
  355. Task { @MainActor in
  356. self.tocOutlineView.km_selectItem(ol, byExtendingSelection: false)
  357. }
  358. }
  359. func showOutlineEmptyView() {
  360. // let view = self.tocOutlineView.enclosingScrollView?.documentView
  361. // let viewFrame = view?.frame ?? .zero
  362. // let emptyVcSize = self.leftSideEmptyVC.emptyOutlineView.frame.size
  363. // self.leftSideEmptyVC.emptyOutlineView.frame = NSMakeRect((viewFrame.size.width-emptyVcSize.width)/2.0,(viewFrame.size.height-emptyVcSize.height)/2.0, emptyVcSize.width, emptyVcSize.height)
  364. // self.leftSideEmptyVC.emptyOutlineView.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin]
  365. // self.tocOutlineView.enclosingScrollView?.documentView?.addSubview(self.leftSideEmptyVC.emptyOutlineView)
  366. // self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = false
  367. }
  368. func hideOutlineEmptyView() {
  369. // self.leftSideEmptyVC.emptyOutlineView.removeFromSuperview()
  370. // self.leftSideEmptyVC.deleteOutlineBtn.isEnabled = true
  371. }
  372. func fetchOutlines(for ol: CPDFOutline, searchString: String) -> [CPDFOutline] {
  373. var ols: [CPDFOutline] = []
  374. for i in 0 ..< ol.numberOfChildren {
  375. guard let child = ol.child(at: i) else {
  376. continue
  377. }
  378. // if self.hasContainString(searchString, rootOutline: child) {
  379. // ols.append(child)
  380. // }
  381. }
  382. return ols
  383. }
  384. @objc func goToSelectedOutlineItem(_ sender: AnyObject?) {
  385. // let cnt = self.tocOutlineView.selectedRowIndexes.count
  386. // if cnt == 0 || cnt > 1 {
  387. // return
  388. // }
  389. // guard let item = self.tocOutlineView.selectedItem() else {
  390. // return
  391. // }
  392. // if let bk = item as? CPDFBookmark {
  393. // self.listView?.go(toPageIndex: bk.pageIndex, animated: true)
  394. // } else if let ol = item as? CPDFOutline {
  395. // if let dest = ol.destination {
  396. // self.listView?.go(to: dest)
  397. // } else if let act = ol.action {
  398. // if !self.isFirst {
  399. // self.listView?.perform(act)
  400. // }
  401. // }
  402. // }
  403. // self.isFirst = false
  404. }
  405. public func refreshUIOfOutlineIfNeed() {
  406. // if self.type.methodType != .Outline {
  407. // return
  408. // }
  409. // Task { @MainActor in
  410. //
  411. // }
  412. }
  413. }
  414. // MARK: - Undo & Redo
  415. extension KMNOutlineController {
  416. @objc dynamic func changePDFOutlineDestination(_ destination: CPDFDestination?, PDFoutline outline: CPDFOutline) {
  417. // if let des = destination {
  418. // (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).changePDFOutlineDestination(outline.destination, PDFoutline: outline)
  419. // let newDes = CPDFDestination(document: des.document, pageIndex: des.pageIndex, at: des.point, zoom: des.zoom)
  420. // outline.destination = newDes
  421. //
  422. // self.tocOutlineView.reloadItem(outline)
  423. // }
  424. }
  425. @objc dynamic func changePDFAction(_ action: CPDFAction?, PDFOutline outline: CPDFOutline) {
  426. // (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).changePDFAction(outline.action, PDFOutline: outline)
  427. // outline.action = action
  428. }
  429. @objc dynamic func renamePDFOutline(_ outline: CPDFOutline, label: String) {
  430. // if (self.isRenameNoteOutline) {
  431. // if outline is CPDFAnnotation {
  432. //// if([outline isKindOfClass:[PDFAnnotation class]]) {
  433. //// PDFAnnotation *annotation = (PDFAnnotation *)outline;
  434. //// annotation.string = label;
  435. //// [rightSideController.noteOutlineView reloadData];
  436. //// [rightSideController.noteOutlineView selectRowIndexes:[[[NSIndexSet alloc] initWithIndex:[rightSideController.noteOutlineView rowForItem:outline]] autorelease] byExtendingSelection:NO];
  437. // }
  438. // } else {
  439. // (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).renamePDFOutline(outline, label: outline.label)
  440. // outline.label = label
  441. //
  442. // self.tocOutlineView.km_selectItem(outline, byExtendingSelection: false)
  443. // }
  444. }
  445. @objc dynamic func addoutline(parent parentOutline: CPDFOutline?, addOutline: CPDFOutline, index: Int, needExpand: Bool) {
  446. // var tempO: CPDFOutline? = addOutline
  447. // if addOutline.label != nil {
  448. // parentOutline?.insertChild(addOutline, at: UInt(index))
  449. // } else {
  450. // let outline = parentOutline?.km_insertChild(label: String(format: "%@ %ld", KMLocalizedString("Page"), self.currentPageIndex()+1), dest: self.currentDestination(), at: index)
  451. // tempO = outline
  452. // }
  453. //
  454. // guard let outline = tempO else {
  455. // return
  456. // }
  457. //
  458. // (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).removeOutline(parent: parentOutline, removeOutline: outline, index: index, needExpand: needExpand)
  459. // self.view.window?.makeFirstResponder(nil)
  460. //
  461. // Task { @MainActor in
  462. //
  463. //
  464. // if (needExpand) {
  465. // self.tocOutlineView.expandItem(parentOutline)
  466. // }
  467. // let idx = self.tocOutlineView.row(forItem: outline)
  468. // self.tocOutlineView.selectRowIndexes(IndexSet(integer: idx), byExtendingSelection: false)
  469. //
  470. // self.newAddOutlineEntryEditingMode(index)
  471. // }
  472. //
  473. // DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  474. // self.tocOutlineView.scrollRowToVisible(self.tocOutlineView.row(forItem: outline))
  475. // }
  476. }
  477. @objc dynamic func removeOutline(parent parentOutline: CPDFOutline?, removeOutline: CPDFOutline, index: Int, needExpand: Bool) {
  478. // (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).addoutline(parent: parentOutline, addOutline: removeOutline, index: index, needExpand: true)
  479. // removeOutline.removeFromParent()
  480. // if (needExpand) {
  481. // self.tocOutlineView.expandItem(parentOutline)
  482. // }
  483. // Task { @MainActor in
  484. //
  485. // }
  486. }
  487. @objc dynamic func dragPDFOutline(_ outline: CPDFOutline?, toIndex index: Int, newParentOutline: CPDFOutline?) {
  488. // guard let doc = self.view.window?.windowController?.document as? NSDocument else {
  489. // NSSound.beep()
  490. // return
  491. // }
  492. // if outline == nil {
  493. // NSSound.beep()
  494. // return
  495. // }
  496. // (doc.undoManager?.prepare(withInvocationTarget: self) as AnyObject).dragPDFOutline(outline, toIndex: Int(outline!.index), newParentOutline: outline?.parent)
  497. // outline?.removeFromParent()
  498. // newParentOutline?.insertChild(outline, at: UInt(index))
  499. //
  500. // self.tocOutlineView.expandItem(newParentOutline)
  501. // self.tocOutlineView.selectRowIndexes(IndexSet(integer: self.tocOutlineView.row(forItem: outline)), byExtendingSelection: false)
  502. }
  503. }
  504. // MARK: - Menu Actions
  505. extension KMNOutlineController {
  506. func outlineListMenu(_ menu: NSMenu) {
  507. _ = menu.addItem(withTitle: NSLocalizedString("Add Item", comment: ""), action: #selector(outlineContextMenuItemClicked_AddEntry), target: self, tag: KMOutlineViewMenuItemTag.addEntry.rawValue)
  508. _ = menu.addItem(withTitle: NSLocalizedString("Add Sub-Item", comment: ""), action: #selector(outlineContextMenuItemClicked_AddChildEntry), target: self, tag: KMOutlineViewMenuItemTag.addChild.rawValue)
  509. _ = menu.addItem(withTitle: NSLocalizedString("Add To A Higher Level", comment: ""), action: #selector(outlineContextMenuItemClicked_AddAuntEntry), target: self, tag: KMOutlineViewMenuItemTag.addAunt.rawValue)
  510. menu.addItem(.separator())
  511. _ = menu.addItem(withTitle: NSLocalizedString("Delete", comment: ""), action: #selector(outlineContextMenuItemClicked_RemoveEntry), target: self, tag: KMOutlineViewMenuItemTag.remove.rawValue)
  512. menu.addItem(.separator())
  513. _ = menu.addItem(withTitle: NSLocalizedString("Edit", comment: ""), action: #selector(outlineContextMenuItemClicked_Edit), target: self, tag: KMOutlineViewMenuItemTag.edit.rawValue)
  514. _ = menu.addItem(withTitle: NSLocalizedString("Change Destination", comment: ""), action: #selector(outlineContextMenuItemClicked_SetDestination), target: self, tag: KMOutlineViewMenuItemTag.setDestination.rawValue)
  515. _ = menu.addItem(withTitle: NSLocalizedString("Rename", comment: ""), action: #selector(outlineContextMenuItemClicked_Rename), target: self, tag: KMOutlineViewMenuItemTag.rename.rawValue)
  516. menu.addItem(.separator())
  517. _ = menu.addItem(withTitle: NSLocalizedString("Promote", comment: ""), action: #selector(outlineContextMenuItemClicked_Promote), target: self, tag: KMOutlineViewMenuItemTag.promote.rawValue)
  518. _ = menu.addItem(withTitle: NSLocalizedString("Demote", comment: ""), action: #selector(outlineContextMenuItemClicked_Demote), target: self, tag: KMOutlineViewMenuItemTag.demote.rawValue)
  519. }
  520. func outlineMoreMenu(_ view: NSButton) {
  521. // let menu = NSMenu()
  522. // let expandAllItem = menu.addItem(title: KMLocalizedString("Expand All"), action: #selector(toc_expandAllComments), target: self)
  523. // expandAllItem?.representedObject = self.tocOutlineView
  524. //
  525. // let foldAllItem = menu.addItem(title: KMLocalizedString("Collapse All"), action: #selector(toc_foldAllComments), target: self)
  526. // foldAllItem?.representedObject = self.tocOutlineView
  527. // let rootOL = self.outlineRoot()
  528. // let childNum = rootOL?.numberOfChildren ?? 0
  529. //
  530. // var num = 0
  531. // for i in 0 ..< childNum {
  532. // let ol = rootOL?.child(at: i)
  533. // if self.tocOutlineView.isItemExpanded(ol) {
  534. // num += 1
  535. // }
  536. // }
  537. //
  538. // self.tocType = .none
  539. // if childNum > 0 {
  540. // if num == 0 {
  541. // self.tocType = .fold
  542. // } else if num == childNum {
  543. // self.tocType = .unfold
  544. // }
  545. // }
  546. //
  547. // expandAllItem?.state = self.tocType == .unfold ? .on : .off
  548. // foldAllItem?.state = self.tocType == .fold ? .on : .off
  549. //
  550. // let removeEntryItem = menu.addItem(title: KMLocalizedString("Remove All Outlines"), action: #selector(leftSideEmptyAnnotationClick_DeleteOutline), target: self)
  551. // removeEntryItem?.representedObject = self.tocOutlineView
  552. // if let data = NSApp.currentEvent {
  553. // NSMenu.popUpContextMenu(menu, with: data, for: view)
  554. // }
  555. }
  556. func outlineListValidateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  557. // if self.isLocked() {
  558. // return false
  559. // }
  560. let action = menuItem.action
  561. // if (action == #selector(leftSideEmptyAnnotationClick_DeleteOutline)) {
  562. // guard let rootOL = self.outlineRoot() else {
  563. // return false
  564. // }
  565. // let childNum = rootOL.numberOfChildren
  566. // if (self.isSearchOutlineMode) {
  567. // let ols = self.fetchOutlines(for: rootOL, searchString: self.outlineSearchField.stringValue)
  568. // return ols.count > 0
  569. // } else {
  570. // return childNum > 0
  571. // }
  572. // } else if action == #selector(toggleOutlineCaseInsensitiveSearch) {
  573. // menuItem.state = self.outlineIgnoreCaseFlag ? .on : .off
  574. // return true
  575. // }
  576. //
  577. // if (self.isSearchOutlineMode) {
  578. // if (action == #selector(outlineContextMenuItemClicked_AddEntry) ||
  579. // action == #selector(outlineContextMenuItemClicked_AddChildEntry) ||
  580. // action == #selector(outlineContextMenuItemClicked_AddAuntEntry) ||
  581. // action == #selector(outlineContextMenuItemClicked_Edit) ||
  582. // action == #selector(outlineContextMenuItemClicked_Rename)
  583. // ) {
  584. // return false
  585. // }
  586. // }
  587. if (self.tocOutlineView.selectedRowIndexes.count > 1) {
  588. if (menuItem.tag == KMOutlineViewMenuItemTag.remove.rawValue) {
  589. return true
  590. }
  591. return false
  592. } else if (self.tocOutlineView.selectedRowIndexes.count > 0) {
  593. if (action == #selector(outlineContextMenuItemClicked_AddChildEntry) ||
  594. action == #selector(outlineContextMenuItemClicked_SetDestination)) {
  595. return true
  596. }
  597. }
  598. if (self.tocOutlineView.clickedRow == -1) {
  599. if (action == #selector(outlineContextMenuItemClicked_AddEntry)) {
  600. return true
  601. } else {
  602. return false
  603. }
  604. } else {
  605. let clickedOutline = self.tocOutlineView.item(atRow: self.tocOutlineView.clickedRow) as? CPDFOutline
  606. if (action == #selector(outlineContextMenuItemClicked_Demote)) {
  607. if let data = clickedOutline {
  608. // return self.pdfDocument()?.canDemote(outline: data) ?? false
  609. }
  610. return false
  611. }
  612. if (action == #selector(outlineContextMenuItemClicked_Promote)) {
  613. if let data = clickedOutline {
  614. // return self.pdfDocument()?.canPromote(outline: data) ?? false
  615. } else {
  616. return false
  617. }
  618. }
  619. if (action == #selector(outlineContextMenuItemClicked_AddAuntEntry)) {
  620. let parentOutLine = clickedOutline?.parent
  621. let grandparentOutLine = parentOutLine?.parent
  622. if (grandparentOutLine != nil) {
  623. return true
  624. } else {
  625. return false
  626. }
  627. }
  628. }
  629. return true
  630. }
  631. //添加子节点
  632. @objc func outlineContextMenuItemClicked_AddChildEntry(_ sender: AnyObject?) {
  633. guard let row = self.selectedRowIndexes().last else {
  634. return
  635. }
  636. let item = self.tocOutlineView.item(atRow: row) as? CPDFOutline
  637. let ol = CPDFOutline()
  638. // ol.label = String(format: "%@ %ld", KMLocalizedString("Page"), "\(self.currentPageIndex() + 1)")
  639. // ol.destination = self.currentDestination()
  640. self.addoutline(parent: item, addOutline: ol, index: Int(item?.numberOfChildren ?? 0), needExpand: true)
  641. }
  642. //添加上一级节点
  643. @objc func outlineContextMenuItemClicked_AddAuntEntry(_ sender: AnyObject?) {
  644. guard let row = self.selectedRowIndexes().last else {
  645. return
  646. }
  647. let item = self.tocOutlineView.item(atRow: row) as? CPDFOutline
  648. let parentOL = item?.parent
  649. if parentOL?.parent != nil {
  650. let ol = CPDFOutline()
  651. // ol.label = String(format: "%@ %ld", KMLocalizedString("Page"), "\(self.currentPageIndex() + 1)")
  652. // ol.destination = self.currentDestination()
  653. self.addoutline(parent: parentOL?.parent, addOutline: ol, index: Int(parentOL?.index ?? 0) + 1, needExpand: false)
  654. }
  655. }
  656. //移除节点
  657. @objc func outlineContextMenuItemClicked_RemoveEntry(_ sender: AnyObject?) {
  658. for idx in self.selectedRowIndexes() {
  659. let item = self.tocOutlineView.item(atRow: idx)
  660. if let ol = item as? CPDFOutline {
  661. self.removeOutline(parent: ol.parent , removeOutline: ol, index: Int(ol.index), needExpand: false)
  662. }
  663. }
  664. }
  665. //重置目的
  666. @objc func outlineContextMenuItemClicked_SetDestination(_ sender: AnyObject?) {
  667. guard let ol = self.tocOutlineView.clickedItem() as? CPDFOutline else {
  668. return
  669. }
  670. Task {
  671. let res = await KMAlertTool.runModel(style: .informational, message: KMLocalizedString("Are you sure you want to set the destination as the current location?"), buttons: [KMLocalizedString("Yes"), KMLocalizedString("No")])
  672. if (res == .alertFirstButtonReturn) {
  673. // self.changePDFOutlineDestination(self.currentDestination(), PDFoutline: ol)
  674. let idx = self.tocOutlineView.row(forItem: ol)
  675. self.tocOutlineView.km_safe_selectRowIndexes(.init(integer: idx), byExtendingSelection: false)
  676. }
  677. }
  678. }
  679. //弹出菜单
  680. @objc func outlineContextMenuItemClicked_Edit(_ sender: AnyObject?) {
  681. let ol: CPDFOutline? = self.tocOutlineView.km.clickedItem()
  682. guard let _ = ol?.km_page else {
  683. return
  684. }
  685. let popover = NSPopover()
  686. // popover.delegate = self
  687. // let vc = KMOutlineEditViewController(outline: ol, document: self.listView)
  688. if let cell = self.tocOutlineView.rowView(atRow: self.tocOutlineView.clickedRow, makeIfNecessary: true) {
  689. // popover.contentViewController = vc
  690. popover.animates = true
  691. popover.behavior = .transient
  692. popover.show(relativeTo: cell.bounds, of: cell, preferredEdge: .minX)
  693. }
  694. }
  695. //重命名
  696. @objc func outlineContextMenuItemClicked_Rename(_ sender: AnyObject?) {
  697. if (self.tocOutlineView.clickedRow < 0) {
  698. return
  699. }
  700. // self.renamePDFOutline = self.tocOutlineView.km.clickedItem()
  701. // let cell = self.tocOutlineView.view(atColumn: 0, row: self.tocOutlineView.clickedRow, makeIfNecessary: true)
  702. // let tf = cell?.subviews.first as? NSTextField
  703. // self.renamePDFOutlineTextField = tf
  704. // tf?.delegate = self
  705. // tf?.isEditable = true
  706. // tf?.becomeFirstResponder()
  707. }
  708. //降级节点
  709. @objc func outlineContextMenuItemClicked_Demote(_ sender: AnyObject?) {
  710. // self.delegate?.controller?(controller: self, itemClick: sender, itemKey: .demote, params: nil)
  711. }
  712. //升级节点
  713. @objc func outlineContextMenuItemClicked_Promote(_ sender: AnyObject?) {
  714. // self.delegate?.controller?(controller: self, itemClick: sender, itemKey: .promote, params: nil)
  715. }
  716. @objc func toggleOutlineCaseInsensitiveSearch(_ sender: NSMenuItem) {
  717. // if (sender.state == .on) {
  718. // self.outlineIgnoreCaseFlag = false
  719. // } else {
  720. // self.outlineIgnoreCaseFlag = true
  721. // }
  722. // if (self.outlineSearchField.stringValue.isEmpty == false) {
  723. //
  724. // self.tocOutlineView.expandItem(nil, expandChildren: true)
  725. // }
  726. }
  727. }
  728. // MARK: - KMTocOutlineViewDelegate
  729. extension KMNOutlineController: KMTocOutlineViewDelegate {
  730. func outlineView(_ anOutlineView: NSOutlineView, highlightLevelForRow row: Int) -> Int {
  731. // if self.tocOutlineView.isEqual(to: anOutlineView) {
  732. // let numRows = anOutlineView.numberOfRows
  733. // if let outline = anOutlineView.item(atRow: row) as? CPDFOutline {
  734. // let firstPage = outline.km_pageIndex
  735. // var lastPage = self.pageCount()
  736. // if row + 1 < numRows {
  737. // lastPage = Int((anOutlineView.item(atRow: row + 1) as? CPDFOutline)?.km_pageIndex ?? UInt(NSNotFound))
  738. // }
  739. // // NSRange range = NSMakeRange(firstPage, MAX(1LU, lastPage - firstPage));
  740. // // NSUInteger i, iMax = [lastViewedPages count];
  741. // // for (i = 0; i < iMax; i++) {
  742. // // if (NSLocationInRange((NSUInteger)[lastViewedPages pointerAtIndex:i], range))
  743. // // return i;
  744. // // }
  745. // }
  746. // }
  747. return NSNotFound
  748. }
  749. func outlineView(_ anOutlineView: NSOutlineView, imageContextForItem item: Any?) -> AnyObject? {
  750. if anOutlineView.isEqual(to: self.tocOutlineView) {
  751. if item == nil {
  752. return true as AnyObject
  753. }
  754. if item is CPDFOutline {
  755. return (item as! CPDFOutline).destination
  756. }
  757. }
  758. return nil
  759. }
  760. }
  761. extension KMNOutlineController: KMNoteOutlineViewDelegate {
  762. func outlineView(_ anOutlineView: NSOutlineView, canResizeRowByItem item: AnyObject?) -> Bool? {
  763. // if anOutlineView.isEqual(to: self.noteOutlineView) {
  764. // return true
  765. // }
  766. return false
  767. }
  768. func outlineView(_ anOutlineView: NSOutlineView, setHeight newHeight: CGFloat, ofRowByItem item: AnyObject?) {
  769. // [rowHeights setFloat:newHeight forKey:item];
  770. }
  771. func outlineView(_ anOutlineView: NSOutlineView, didChangeHiddenOfTableColumn aTableColumn: NSTableColumn) {
  772. // if (mwcFlags.autoResizeNoteRows &&
  773. // [ov isEqual:rightSideController.noteOutlineView] &&
  774. // [[tableColumn identifier] isEqualToString:NOTE_COLUMNID]) {
  775. // [rowHeights removeAllFloats];
  776. // [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  777. // }
  778. }
  779. func outlineViewCommandKeyPressedDuringNavigation(_ anOutlineView: NSOutlineView) {
  780. // PDFAnnotation *annotation = [[self selectedNotes] lastObject];
  781. // if (annotation) {
  782. // [pdfView scrollAnnotationToVisible:annotation];
  783. // [pdfView setActiveAnnotation:annotation];
  784. // }
  785. }
  786. }
  787. // MARK: - NSOutlineViewDelegate, NSOutlineViewDataSource
  788. extension KMNOutlineController: NSOutlineViewDelegate, NSOutlineViewDataSource {
  789. func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
  790. if outlineView.isEqual(to: self.tocOutlineView) {
  791. if self.handdler.isLocked() {
  792. return 0
  793. }
  794. if item == nil { // 第一层
  795. guard let rootOL = self.handdler.outlineRoot() else {
  796. self.showOutlineEmptyView()
  797. return 0
  798. }
  799. // 搜索按钮
  800. self.outlineSearchButton.isEnabled = rootOL.numberOfChildren > 0
  801. if self.isSearchOutlineMode { // 是否为搜索模块
  802. // if self.hasContainString(self.outlineSearchField.stringValue, rootOutline: rootOL) == false {
  803. // self.showSearchOutlineBlankState(true)
  804. // return 0
  805. // }
  806. self.showSearchOutlineBlankState(false)
  807. let ols = self.fetchOutlines(for: rootOL, searchString: self.outlineSearchField.stringValue)
  808. return ols.count
  809. }
  810. if rootOL.numberOfChildren == 0 { // 没有数据
  811. self.showOutlineEmptyView()
  812. return 0
  813. }
  814. // 有数据
  815. self.hideOutlineEmptyView()
  816. return Int(rootOL.numberOfChildren)
  817. } else { // 第二层 +
  818. guard let ol = item as? CPDFOutline, ol.numberOfChildren > 0 else {
  819. return 0
  820. }
  821. if self.isSearchOutlineMode == false {
  822. return Int(ol.numberOfChildren)
  823. }
  824. // 搜索模式
  825. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  826. return ols.count
  827. }
  828. }
  829. return 0
  830. }
  831. func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
  832. if outlineView.isEqual(to: self.tocOutlineView) {
  833. if self.handdler.isLocked() {
  834. return ""
  835. }
  836. if item == nil {
  837. if self.isSearchOutlineMode {
  838. guard let rootOL = self.handdler.outlineRoot(), rootOL.numberOfChildren > 0 else {
  839. return ""
  840. }
  841. let ols = self.fetchOutlines(for: rootOL, searchString: self.outlineSearchField.stringValue)
  842. return ols.safe_element(for: index) as Any
  843. }
  844. let rootOL = self.handdler.outlineRoot()
  845. return rootOL?.child(at: UInt(index)) as Any
  846. } else {
  847. if let ol = item as? CPDFOutline {
  848. if self.isSearchOutlineMode == false {
  849. return ol.child(at: UInt(index)) as Any
  850. }
  851. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  852. return ols.safe_element(for: index) as Any
  853. }
  854. }
  855. }
  856. return item as Any
  857. }
  858. func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
  859. if outlineView.isEqual(to: self.tocOutlineView) {
  860. let cell = outlineView.makeView(withIdentifier: KMTocTableCellView.km_identifier, owner: self) as! KMTocTableCellView
  861. let columnId = tableColumn?.identifier.rawValue
  862. var title = ""
  863. var pageLabel = ""
  864. if let ol = item as? CPDFOutline {
  865. title = ol.label ?? ""
  866. if ol.actionType == .page {
  867. pageLabel = "\((ol.destination?.pageIndex ?? 0) + 1)"
  868. }
  869. }
  870. cell.pageLabel.stringValue = pageLabel
  871. if columnId == kLabelColumnId.rawValue {
  872. if self.isSearchOutlineMode {
  873. let attriString = NSMutableAttributedString(string: title)
  874. var searchString = self.outlineSearchField.stringValue
  875. var roughString = title
  876. // if self.outlineIgnoreCaseFlag {
  877. // roughString = roughString.lowercased()
  878. // searchString = searchString.lowercased()
  879. // }
  880. //
  881. let ranges = roughString.ranges(of: searchString)
  882. for range in ranges.nsRnage {
  883. attriString.addAttribute(.font, value: NSFont.boldSystemFont(ofSize: 13), range: range)
  884. }
  885. cell.tocLabel.attributedStringValue = attriString
  886. } else {
  887. cell.tocLabel.stringValue = title
  888. }
  889. }
  890. cell.tocLabel.textColor = KMAppearance.titleColor()
  891. return cell
  892. }
  893. return nil
  894. }
  895. func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
  896. if outlineView.isEqual(self.tocOutlineView) {
  897. if let ol = item as? CPDFOutline {
  898. let string: NSString = ol.label as NSString
  899. let ps = NSMutableParagraphStyle()
  900. ps.lineHeightMultiple = 1.32
  901. ps.alignment = .left
  902. let attris = [NSAttributedString.Key.paragraphStyle : ps,
  903. NSAttributedString.Key.font : NSFont.SFProTextRegularFont(14.0)]
  904. let size = string.boundingRect(with: NSMakeSize(outlineView.frame.size.width - 30, 200), options: NSString.DrawingOptions(rawValue: 3), attributes: attris)
  905. return max(40, size.height + 16)
  906. }
  907. return 40
  908. }
  909. return outlineView.rowHeight
  910. }
  911. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
  912. if outlineView.isEqual(self.tocOutlineView) {
  913. guard let ol = item as? CPDFOutline else {
  914. return false
  915. }
  916. if self.isSearchOutlineMode == false {
  917. return ol.numberOfChildren > 0
  918. }
  919. let ols = self.fetchOutlines(for: ol, searchString: self.outlineSearchField.stringValue)
  920. return ols.count > 0
  921. }
  922. return false
  923. }
  924. func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
  925. if outlineView.isEqual(self.tocOutlineView) {
  926. let itemView = KMBotaTableRowView()
  927. itemView.backgroundColor = .purple
  928. return itemView
  929. }
  930. return nil
  931. }
  932. func outlineViewSelectionDidChange(_ notification: Notification) {
  933. if self.tocOutlineView.isEqual(to: notification.object) {
  934. // if self.dragIn {
  935. // return
  936. // }
  937. // if self.updatingOutlineSelection == false {
  938. // self.updatingOutlineSelection = true
  939. // self.goToSelectedOutlineItem(nil)
  940. // self.updatingOutlineSelection = false
  941. // }
  942. }
  943. }
  944. func outlineViewItemDidExpand(_ notification: Notification) {
  945. // if self.tocOutlineView.isEqual(to: notification.object) {
  946. // self.updateOutlineSelection()
  947. // }
  948. }
  949. func outlineViewItemDidCollapse(_ notification: Notification) {
  950. // if self.tocOutlineView.isEqual(to: notification.object) {
  951. // self.updateOutlineSelection()
  952. // }
  953. }
  954. func outlineView(_ outlineView: NSOutlineView, validateDrop info: NSDraggingInfo, proposedItem item: Any?, proposedChildIndex index: Int) -> NSDragOperation {
  955. var dragOp = NSDragOperation(rawValue: 0)
  956. if outlineView.isEqual(to: self.tocOutlineView) {
  957. if (index == -1) {
  958. dragOp = NSDragOperation(rawValue: 0)
  959. } else {
  960. dragOp = .move
  961. }
  962. }
  963. return dragOp
  964. }
  965. func outlineView(_ outlineView: NSOutlineView, writeItems items: [Any], to pasteboard: NSPasteboard) -> Bool {
  966. if outlineView.isEqual(to: self.tocOutlineView) {
  967. if (self.tocOutlineView.selectedRowIndexes.count > 1) {
  968. return false
  969. }
  970. let tIndex = IndexSet(integer: self.tocOutlineView.clickedRow)
  971. self.tocOutlineView.deselectRow(tIndex.first ?? 0)
  972. // self._dragPDFOutline = items.first as? CPDFOutline
  973. let set = IndexSet(integer: 0)
  974. let zNSIndexSetData = NSKeyedArchiver.archivedData(withRootObject: set)
  975. // [pasteboard declareTypes:[NSArray arrayWithObject:kKMPDFViewOutlineDragDataType] owner:self];
  976. pasteboard.declareTypes([.localDraggedTypes], owner: self)
  977. pasteboard.setData(zNSIndexSetData, forType: .localDraggedTypes)
  978. return true
  979. }
  980. return false
  981. }
  982. func outlineView(_ outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: Any?, childIndex index: Int) -> Bool {
  983. if outlineView.isEqual(to: self.tocOutlineView) {
  984. if (index < 0) {
  985. return false
  986. }
  987. let outline = item as? CPDFOutline
  988. // guard let dragPDFOL = self._dragPDFOutline else {
  989. // return false
  990. // }
  991. //root,drag item to root
  992. // if ((outline?.parent == nil)) {
  993. // //fetch root
  994. // var root = dragPDFOL
  995. // while (root.parent != nil) {
  996. // root = root.parent
  997. // }
  998. // if dragPDFOL.parent.isEqual(to: root) {
  999. // if dragPDFOL.index > index {
  1000. // self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: root)
  1001. // } else {
  1002. //// if let bks = self.bookmarks(), bks.count > 0 {
  1003. //// if let data = item as? String, data == Self.kOutlineRootBookmarkItem {
  1004. ////
  1005. //// } else {
  1006. //// if index > 1 {
  1007. //// self.dragPDFOutline(self._dragPDFOutline, toIndex: index-2, newParentOutline: root)
  1008. //// }
  1009. //// }
  1010. //// } else {
  1011. // self.dragPDFOutline(self._dragPDFOutline, toIndex: index-1, newParentOutline: root)
  1012. //// }
  1013. // }
  1014. // } else {
  1015. // self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: root)
  1016. // }
  1017. // } else {
  1018. // //在同一个层级内移动
  1019. // if dragPDFOL.parent.isEqual(to: item) {
  1020. // if (dragPDFOL.index > 0) {
  1021. // if dragPDFOL.index > index {
  1022. // self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: outline)
  1023. // }else{
  1024. // self.dragPDFOutline(self._dragPDFOutline, toIndex: index-1, newParentOutline: outline)
  1025. // }
  1026. // } else {
  1027. // return false
  1028. // }
  1029. // } else {
  1030. // var tOutlline: CPDFOutline? = outline
  1031. // var isContains = false
  1032. // while (tOutlline != nil) {
  1033. // if tOutlline!.isEqual(to: self._dragPDFOutline) {
  1034. // isContains = true
  1035. // break
  1036. // }
  1037. // tOutlline = tOutlline?.parent
  1038. // }
  1039. // if (!isContains) {
  1040. // self.dragPDFOutline(self._dragPDFOutline, toIndex: index, newParentOutline: outline)
  1041. // }
  1042. // }
  1043. // }
  1044. return true
  1045. }
  1046. return false
  1047. }
  1048. func outlineView(_ outlineView: NSOutlineView, willDisplayOutlineCell cell: Any, for tableColumn: NSTableColumn?, item: Any) {
  1049. if outlineView.isEqual(to: self.tocOutlineView) {
  1050. if outlineView.selectionHighlightStyle == .regular && outlineView.isRowSelected(outlineView.row(forItem: item)) {
  1051. (cell as? NSCell)?.backgroundStyle = .lowered
  1052. }
  1053. }
  1054. }
  1055. func outlineView(_ outlineView: NSOutlineView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forItems draggedItems: [Any]) {
  1056. // self.dragIn = true
  1057. }
  1058. func outlineView(_ outlineView: NSOutlineView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
  1059. // self.dragIn = false
  1060. }
  1061. /*
  1062. #pragma mark NSOutlineView delegate protocol
  1063. - (void)outlineView:(NSOutlineView *)ov didClickTableColumn:(NSTableColumn *)tableColumn {
  1064. if ([ov isEqual:rightSideController.noteOutlineView]) {
  1065. NSTableColumn *oldTableColumn = [ov highlightedTableColumn];
  1066. NSTableColumn *newTableColumn = ([NSEvent modifierFlags] & NSEventModifierFlagCommand) ? nil : tableColumn;
  1067. NSMutableArray *sortDescriptors = nil;
  1068. BOOL ascending = YES;
  1069. if ([oldTableColumn isEqual:newTableColumn]) {
  1070. sortDescriptors = [[[rightSideController.noteArrayController sortDescriptors] mutableCopy] autorelease];
  1071. [sortDescriptors replaceObjectAtIndex:0 withObject:[[sortDescriptors firstObject] reversedSortDescriptor]];
  1072. ascending = [[sortDescriptors firstObject] ascending];
  1073. } else {
  1074. NSString *tcID = [newTableColumn identifier];
  1075. NSSortDescriptor *pageIndexSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationPageIndexKey ascending:ascending] autorelease];
  1076. NSSortDescriptor *boundsSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:SKPDFAnnotationBoundsOrderKey ascending:ascending selector:@selector(compare:)] autorelease];
  1077. sortDescriptors = [NSMutableArray arrayWithObjects:pageIndexSortDescriptor, boundsSortDescriptor, nil];
  1078. if ([tcID isEqualToString:TYPE_COLUMNID]) {
  1079. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationTypeKey ascending:YES selector:@selector(noteTypeCompare:)] autorelease] atIndex:0];
  1080. } else if ([tcID isEqualToString:COLOR_COLUMNID]) {
  1081. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationColorKey ascending:YES selector:@selector(colorCompare:)] autorelease] atIndex:0];
  1082. } else if ([tcID isEqualToString:NOTE_COLUMNID]) {
  1083. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationStringKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  1084. } else if ([tcID isEqualToString:AUTHOR_COLUMNID]) {
  1085. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationUserNameKey ascending:YES selector:@selector(localizedCaseInsensitiveNumericCompare:)] autorelease] atIndex:0];
  1086. } else if ([tcID isEqualToString:DATE_COLUMNID]) {
  1087. [sortDescriptors insertObject:[[[NSSortDescriptor alloc] initWithKey:SKNPDFAnnotationModificationDateKey ascending:YES] autorelease] atIndex:0];
  1088. }
  1089. if (oldTableColumn)
  1090. [ov setIndicatorImage:nil inTableColumn:oldTableColumn];
  1091. [ov setHighlightedTableColumn:newTableColumn];
  1092. }
  1093. [rightSideController.noteArrayController setSortDescriptors:sortDescriptors];
  1094. if (newTableColumn)
  1095. [ov setIndicatorImage:[NSImage imageNamed:ascending ? @"NSAscendingSortIndicator" : @"NSDescendingSortIndicator"]
  1096. inTableColumn:newTableColumn];
  1097. [ov reloadData];
  1098. }
  1099. }
  1100. - (void)outlineViewColumnDidResize:(NSNotification *)notification{
  1101. if (mwcFlags.autoResizeNoteRows &&
  1102. [[notification object] isEqual:rightSideController.noteOutlineView] &&
  1103. [[[[notification userInfo] objectForKey:@"NSTableColumn"] identifier] isEqualToString:NOTE_COLUMNID] &&
  1104. [(SKScrollView *)[[notification object] enclosingScrollView] isResizingSubviews] == NO) {
  1105. [rowHeights removeAllFloats];
  1106. [rightSideController.noteOutlineView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [rightSideController.noteOutlineView numberOfRows])]];
  1107. }
  1108. }
  1109. - (void)sizeOutlineViewToContents:(NSOutlineView*) outlineView;
  1110. {
  1111. NSInteger rowCount = [outlineView numberOfRows];
  1112. for (NSInteger i = 0; i < rowCount; i++){
  1113. CGFloat rowHeight = 0;
  1114. PDFOutline *outline = [leftSideController.tocOutlineView itemAtRow:i];
  1115. if (!outline){
  1116. continue;
  1117. }
  1118. NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc]init] autorelease];
  1119. NSDictionary *dictAttr1 = @{NSForegroundColorAttributeName:[KMAppearance KMColor_Layout_H0]};
  1120. NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:outline.label attributes:dictAttr1];
  1121. [attributedString appendAttributedString:attr1];
  1122. // NSTableCellView *viewS = [leftSideController.tocOutlineView viewAtColumn:0 row:i makeIfNecessary:YES];
  1123. NSTableColumn *tableColumn = [leftSideController.tocOutlineView tableColumnWithIdentifier:LABEL_COLUMNID];
  1124. // id cell = [tableColumn dataCell];
  1125. id cell = [tableColumn dataCellForRow:i];
  1126. [cell setObjectValue:attributedString];
  1127. CGFloat w = leftSideController.view.frame.size.width - 86;//[tableColumn width] > 260 ? [tableColumn width] : 260;
  1128. NSInteger num = [self getNum:outline];
  1129. CGFloat gap = [leftSideController.tocOutlineView indentationPerLevel];
  1130. rowHeight = [cell cellSizeForBounds:NSMakeRect(0.0, 0.0, w - (num > 0?16:0) - gap*num, CGFLOAT_MAX)].height;
  1131. rowHeight = fmax(rowHeight, [leftSideController.tocOutlineView rowHeight]) + 25;
  1132. [rowHeights setFloat:rowHeight forKey:outline];
  1133. if (@available(macOS 10.13, *)) {
  1134. } else {
  1135. rowHeight = 40.0;
  1136. }
  1137. // CGRect fram = viewS.frame;
  1138. // viewS.frame = CGRectMake(fram.origin.x, fram.origin.y, fram.size.width, rowHeight);
  1139. }
  1140. [leftSideController.tocOutlineView reloadData];
  1141. }
  1142. */
  1143. func noteItems(_ items: NSArray) -> NSArray {
  1144. let noteItems = NSMutableArray()
  1145. for item in items {
  1146. guard let anno = (item as? KMBotaAnnotationModel)?.anno else {
  1147. continue
  1148. }
  1149. if anno.type == nil {
  1150. // item = [(SKNoteText *)item note];
  1151. }
  1152. if noteItems.contains(anno) == false {
  1153. noteItems.add(anno)
  1154. }
  1155. }
  1156. return noteItems
  1157. }
  1158. }
  1159. // MARK: - KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource
  1160. extension KMNOutlineController: KMCustomOutlineViewDelegate, KMCustomOutlineViewDataSource {
  1161. func outlineView(_ anOutlineView: NSOutlineView, canDeleteItems items: [Any]) -> Bool {
  1162. if anOutlineView.isEqual(to: self.tocOutlineView) {
  1163. return items.count > 0
  1164. }
  1165. return false
  1166. }
  1167. func outlineView(_ anOutlineView: NSOutlineView, deleteItems items: [Any]) {
  1168. if anOutlineView.isEqual(to: self.tocOutlineView) {
  1169. self.outlineContextMenuItemClicked_RemoveEntry(nil)
  1170. }
  1171. }
  1172. func outlineView(_ anOutlineView: NSOutlineView, canCopyItems items: [Any]) -> Bool {
  1173. return false
  1174. }
  1175. func outlineView(_ anOutlineView: NSOutlineView, typeSelectHelperSelectionStrings aTypeSelectHelper: SKTypeSelectHelper) -> NSArray {
  1176. if self.tocOutlineView.isEqual(to: anOutlineView) {
  1177. let count = self.tocOutlineView.numberOfRows
  1178. let array = NSMutableArray(capacity: count)
  1179. for i in 0 ..< count {
  1180. // [array addObject:[[(PDFOutline *)[leftSideController.tocOutlineView itemAtRow:i] label] lossyStringUsingEncoding:NSASCIIStringEncoding]];
  1181. let item = self.tocOutlineView.item(atRow: i) as? CPDFOutline
  1182. array.add(item?.label ?? "")
  1183. }
  1184. return array
  1185. }
  1186. return NSArray()
  1187. }
  1188. }