KMThumbnailViewController.swift 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. //
  2. // KMThumbnailViewController.swift
  3. // PDF Master
  4. //
  5. // Created by lxy on 2022/10/10.
  6. //
  7. @objc protocol KMThumbnailViewControllerDelegate {
  8. @objc optional func gotoPageEdit(thumbnailViewController:KMThumbnailViewController, pages: [Int])
  9. @objc optional func pageDidSelect(controller: KMThumbnailViewController, pages: [Int])
  10. @objc optional func controller(controller: KMThumbnailViewController, itemClick item: Any?, itemKey: KMItemKey, params: Any?)
  11. }
  12. class KMThumbnailViewController: KMBaseViewController {
  13. open weak var delegate: KMThumbnailViewControllerDelegate?
  14. @IBOutlet weak var headerView: NSView!
  15. @IBOutlet weak var titleLabel: NSTextField!
  16. @IBOutlet weak var thumbnailView: KMPDFThumbnailView!
  17. @IBOutlet var doublePageBtn: NSButton!
  18. @IBOutlet weak var lineView: NSView!
  19. var doublePageMode : Bool! = false
  20. var isLocalEvent: Bool = false //是否为本视图事件
  21. var listView : CPDFListView!
  22. //注释状态
  23. var annotationShowState: KMAnnotationViewShowType = .none {
  24. didSet {
  25. if self.thumbnailView != nil {
  26. self.thumbnailView.annotationShowState = self.annotationShowState
  27. }
  28. }
  29. }
  30. override var canPayFunction: Bool {
  31. didSet {
  32. self.thumbnailView.limit = !self.canPayFunction
  33. }
  34. }
  35. deinit {
  36. NotificationCenter.default.removeObserver(self)
  37. Swift.debugPrint("KMThumbnailViewController 释放")
  38. }
  39. override func viewWillAppear() {
  40. super.viewWillAppear()
  41. self.thumbnailView.reloadData()
  42. self.thumbnailView.collectionView.selectionIndexes = IndexSet(integer: IndexSet.Element(self.listView.currentPageIndex))
  43. self.thumbnailView.collectionView.mouseDownCancelSelected = false
  44. }
  45. override func viewDidLoad() {
  46. super.viewDidLoad()
  47. self.view.wantsLayer = true
  48. self.view.layer?.backgroundColor = NSColor.clear.cgColor
  49. self.lineView.backgroundColor(NSColor.km_init(hex: "#EDEEF0"))
  50. self.headerView.wantsLayer = true
  51. self.headerView.layer?.backgroundColor = NSColor.km_init(hex: "#F7F8FA").cgColor
  52. self.titleLabel.stringValue = NSLocalizedString("Thumbnails", comment: "")
  53. self.titleLabel.font = NSFont.SFProTextSemiboldFont(14.0)
  54. self.titleLabel.textColor = NSColor.km_init(hex: "#252629")
  55. if self.listView.document != nil {
  56. self.thumbnailView.document = self.listView.document
  57. }
  58. // self.doublePageBtn.isHidden = true
  59. self.thumbnailView.delegate = self
  60. self.thumbnailView.collectionView.isSelectable = true
  61. self.thumbnailView.collectionView.allowsMultipleSelection = true
  62. self.thumbnailView.isShowPageSize = true
  63. self.thumbnailView.isNeedMarkerLine = true
  64. // self.thumbnailView.collectionView.allowsEmptySelection = false
  65. var allowedFileTypes: [String] = []
  66. if let _types = KMConvertPDFManagerOC.supportFileType() as? [String] {
  67. allowedFileTypes = KMTools.pdfExtensions + _types
  68. } else {
  69. allowedFileTypes = KMTools.pdfExtensions + KMTools.imageExtensions
  70. }
  71. self.thumbnailView.kmAllowedFileTypes = allowedFileTypes
  72. self.doublePageBtn.toolTip = NSLocalizedString("Single/Double column display", comment: "")
  73. self.pdfCurrentPageChange()
  74. self.initNotification()
  75. }
  76. func initNotification() {
  77. NotificationCenter.default.addObserver(self, selector: #selector(PDFViewEditingAreaDidChangedNotification), name: NSNotification.Name.init(rawValue: "kPDFViewEditingAreaDidChanged"), object: nil)
  78. NotificationCenter.default.addObserver(self, selector: #selector(KMPDFViewPageCountChangedNotification), name: NSNotification.Name.init(rawValue: "KMPDFViewRotatePage"), object: nil)
  79. NotificationCenter.default.addObserver(self, selector: #selector(KMPDFViewCurrentPageDidChangedNotification), name: NSNotification.Name.init(rawValue: "KMPDFViewCurrentPageDidChanged"), object: nil)
  80. NotificationCenter.default.addObserver(self, selector: #selector(KMPDFViewPageCountChangedNotification), name: NSNotification.Name.init(rawValue: "CPDFDocumentPageCountChangedNotification"), object: nil)
  81. NotificationCenter.default.addObserver(self, selector: #selector(AnnotationDidChangeNoti), name: NSNotification.Name.init(rawValue: "CPDFPageDidAddAnnotationNotification"), object: nil)
  82. NotificationCenter.default.addObserver(self, selector: #selector(AnnotationDidChangeNoti), name: NSNotification.Name.init(rawValue: "CPDFPageDidRemoveAnnotationNotification"), object: nil)
  83. }
  84. func removeNotification() {
  85. NotificationCenter.default.removeObserver(self)
  86. }
  87. //MARK: Public Method
  88. func reloadData () {
  89. if self.doublePageMode {
  90. self.thumbnailView.thumbnailSzie = CGSize(width: 86, height: 101)
  91. self.doublePageBtn.image = NSImage(named: "KMImageNameThumbnailPage")
  92. // self.thumbnailView.isNeedMarkerLine = false
  93. self.thumbnailView.hasDragLineView = false
  94. } else {
  95. self.thumbnailView.thumbnailSzie = CGSize(width: 156, height: 180)
  96. self.doublePageBtn.image = NSImage(named: "KMImageNameThumbnailDoublePage")
  97. // self.thumbnailView.isNeedMarkerLine = false
  98. }
  99. self.thumbnailView.reloadData()
  100. // self.km_resignFirstResponder()
  101. }
  102. func reloadDataAtIndexs (indexs: IndexSet) {
  103. var selectPages: [Int] = []
  104. for index in indexs {
  105. selectPages.append(index+1)
  106. }
  107. DispatchQueue.main.async {
  108. var data = Set<IndexPath>()
  109. for index in selectPages {
  110. data.insert(IndexPath(item: index-1, section: 0))
  111. }
  112. self.thumbnailView.collectionView.reloadItems(at: data)
  113. // self.km_resignFirstResponder()
  114. }
  115. }
  116. //MARK: Private Method
  117. @IBAction func doublePageAction(_ sender: Any) {
  118. self.doublePageMode = !self.doublePageMode
  119. self.reloadData()
  120. }
  121. private func dragPagesForDescSort(_ indexs: IndexSet, _ toIndex: Int) {
  122. if (indexs.count <= 0) {
  123. return
  124. }
  125. /// 数据降序排序
  126. let indexArray = indexs.sorted { index1, index2 in
  127. return index1 > index2
  128. }
  129. var newIndexs: IndexSet = []
  130. for index in indexArray {
  131. newIndexs.insert(index)
  132. }
  133. self.dragPages(newIndexs, toIndex)
  134. }
  135. @objc private func dragPages(_ indexs: IndexSet, _ toIndex: Int) {
  136. if (indexs.count <= 0) {
  137. return
  138. }
  139. //获取原有page的下标 和 开始添加的下标
  140. var indexTemp: Int = toIndex
  141. var pageItems: [KMThumbnailPageItem] = []
  142. for index in indexs {
  143. let newPage: CPDFPage = self.listView?.document.page(at: UInt(index)).copy() as! CPDFPage
  144. let pageItem = KMThumbnailPageItem(page: newPage, index: index, oldIndex: index)
  145. pageItems.append(pageItem)
  146. if (toIndex > index) { /// 删除了插入位置前面的页面,需要改变 toIndex
  147. indexTemp -= 1
  148. }
  149. }
  150. //建立模型
  151. var tPageItems: [KMThumbnailPageItem] = []
  152. for index in 0...pageItems.count - 1 {
  153. let pageItem: KMThumbnailPageItem = pageItems[index]
  154. let tItem = KMThumbnailPageItem(page: pageItem.page, index: indexTemp + index, oldIndex: pageItem.index)
  155. tPageItems.append(tItem)
  156. }
  157. //进行移动
  158. self.dragPageItems(pageItems: tPageItems)
  159. }
  160. private func km_resignFirstResponder() {
  161. NSApp.mainWindow?.makeFirstResponder(self)
  162. }
  163. //MARK: Noti
  164. @objc func KMPDFViewCurrentPageDidChangedNotification(notification: NSNotification) {
  165. if notification.object is CPDFDocument {
  166. let pdfdocument : CPDFDocument = notification.object as! CPDFDocument
  167. if pdfdocument.isEqual(self.listView.document) {
  168. if !isLocalEvent {
  169. // DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { [unowned self] in
  170. self.pdfCurrentPageChange()
  171. self.delegate?.pageDidSelect?(controller: self, pages: [self.listView.currentPageIndex])
  172. // }
  173. }
  174. isLocalEvent = false
  175. }
  176. }
  177. }
  178. @objc func KMPDFViewPageCountChangedNotification(notification: NSNotification) {
  179. if notification.object is CPDFDocument {
  180. let pdfdocument : CPDFDocument = notification.object as! CPDFDocument
  181. if pdfdocument.isEqual(self.listView.document) {
  182. if !isLocalEvent {
  183. // DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { [unowned self] in
  184. self.reloadData()
  185. // }
  186. }
  187. isLocalEvent = false
  188. }
  189. }
  190. }
  191. @objc func AnnotationDidChangeNoti(notification: NSNotification) {
  192. if notification.object is CPDFAnnotation {
  193. let pdfAnnotation : CPDFAnnotation = notification.object as! CPDFAnnotation
  194. if (pdfAnnotation.page != nil) {
  195. var indexs: IndexSet = IndexSet()
  196. indexs.insert(IndexSet.Element(pdfAnnotation.page.pageIndex()))
  197. self.reloadDataAtIndexs(indexs: indexs)
  198. }
  199. }
  200. }
  201. @objc func PDFViewEditingAreaDidChangedNotification(notification: NSNotification) {
  202. if notification.object is CPDFDocument {
  203. let pdfdocument : CPDFDocument = notification.object as! CPDFDocument
  204. if pdfdocument.isEqual(self.listView.document) {
  205. var indexs: IndexSet = IndexSet()
  206. indexs.insert(IndexSet.Element(self.listView.currentPageIndex))
  207. self.reloadDataAtIndexs(indexs: indexs)
  208. }
  209. }
  210. }
  211. func pdfCurrentPageChange () {
  212. if self.listView.document.pageCount == 0 {
  213. return
  214. }
  215. let insertIndex: Int = self.listView.currentPageIndex;
  216. var indexs: IndexSet = IndexSet()
  217. indexs.insert(insertIndex)
  218. self.selectPages(indexs: indexs)
  219. // self.thumbnailView.collectionView.scrollToItems(at: self.thumbnailView.collectionView.selectionIndexPaths, scrollPosition: NSCollectionView.ScrollPosition.centeredVertically)
  220. }
  221. //MARK: menu Action
  222. @IBAction func insertPageItemAction(menu:NSMenuItem) {
  223. if menu.tag == 0 {
  224. self.item_insertFile(sender: menu)
  225. } else if menu.tag == 1 {
  226. self.item_insertBankPage(sender: menu)
  227. } else if menu.tag == 2 {
  228. self.item_insertPage(sender: menu)
  229. }
  230. }
  231. @objc private func item_insertFile(sender: NSMenuItem?) {
  232. let panel = NSOpenPanel()
  233. panel.allowedFileTypes = ["pdf"]
  234. panel.beginSheetModal(for: self.view.window!) { [weak self] response in
  235. if (response == .cancel) {
  236. return
  237. }
  238. /// 处理page
  239. var insertIndex: Int = self!.thumbnailView.collectionView.selectionIndexes.last!
  240. let doucument = CPDFDocument(url: panel.url)
  241. if ((doucument?.isLocked)!) {
  242. KMPasswordInputWindow.openWindow(window: self!.view.window!, url: panel.url!) { [weak self] result, password in
  243. if (result == .cancel) {
  244. return
  245. }
  246. doucument?.unlock(withPassword: password)
  247. var newInsertIndex: Int = insertIndex + 1
  248. var pages: [CPDFPage] = []
  249. var indexs: IndexSet = IndexSet()
  250. for i in 0 ..< doucument!.pageCount {
  251. let page = doucument?.page(at: i)
  252. pages.append(page!)
  253. indexs.insert(newInsertIndex)
  254. newInsertIndex += 1
  255. }
  256. self?.insertPagesForDescSort(pages: pages, indexs: indexs)
  257. }
  258. } else {
  259. var newInsertIndex: Int = insertIndex + 1
  260. var pages: [CPDFPage] = []
  261. var indexs: IndexSet = IndexSet()
  262. for i in 0 ..< doucument!.pageCount {
  263. let page = doucument?.page(at: i)
  264. pages.append(page!)
  265. indexs.insert(newInsertIndex)
  266. newInsertIndex += 1
  267. }
  268. self?.insertPagesForDescSort(pages: pages, indexs: indexs)
  269. }
  270. }
  271. }
  272. @objc private func item_insertBankPage(sender: NSMenuItem?) {
  273. let insertIndex: Int = self.thumbnailView.collectionView.selectionIndexes.last!
  274. let page = self.listView?.document.page(at: UInt(insertIndex))
  275. let document = CPDFDocument()
  276. document?.insertPage((page?.bounds.size)!, at: 0)
  277. let newPage: CPDFPage = (document?.page(at: 0))!
  278. self.insertPagesForDescSort(pages: [newPage], indexs: IndexSet(integer: insertIndex+1))
  279. }
  280. @objc private func item_insertPage(sender: NSMenuItem?) {
  281. let windowController = KMPageEditInsertCustomPageWindowController(windowNibName: "KMPageEditInsertCustomPageWindowController")
  282. let insertIndex: Int = self.thumbnailView.collectionView.selectionIndexes.last!
  283. let page = self.listView?.document.page(at: UInt(insertIndex))
  284. if (self.thumbnailView.collectionView.selectionIndexes.count > 0) {
  285. windowController.selectedPageSize = page!.bounds.size
  286. }
  287. self.view.window?.beginSheet(windowController.window!, completionHandler: { response in})
  288. windowController.itemClick = {
  289. [weak self] (index: Int) in
  290. if (index == 1) { /// 取消
  291. self?.view.window?.endSheet((windowController.window)!)
  292. return
  293. }
  294. /// 插入
  295. /// 样式
  296. let windowController_Insert: KMPageEditInsertCustomPageWindowController = windowController
  297. let type = windowController_Insert.typeIndex
  298. /// 页面大小
  299. let pageSize = windowController_Insert.pageSize
  300. /// 方向
  301. let direction = windowController_Insert.direction
  302. /// 插入位置
  303. let insertIndex: Int = insertIndex
  304. if (type == 1) { /// 空白页
  305. let document = CPDFDocument()
  306. document?.insertPage(pageSize, at: 0)
  307. let page: CPDFPage = (document?.page(at: 0))!
  308. if (direction == 0) { /// 纵向
  309. page.rotation = 90
  310. }
  311. self?.insertPagesForDescSort(pages: [page], indexs: IndexSet(integer: insertIndex+1))
  312. } else {
  313. let document = CPDFDocument()
  314. var imageName = "plaid"
  315. if (type == 2) {
  316. imageName = "horizontal_line"
  317. } else if (type == 3) {
  318. imageName = "five_line_score"
  319. }
  320. let imagePath = Bundle.main.pathForImageResource(imageName)
  321. document?.insertPage(pageSize, withImage: imagePath, at: 0)
  322. let page: CPDFPage = (document?.page(at: 0))!
  323. if (direction == 0) { /// 纵向
  324. page.rotation = 90
  325. }
  326. self?.insertPagesForDescSort(pages: [page], indexs: IndexSet(integer: insertIndex+1))
  327. }
  328. self?.view.window?.endSheet((windowController.window)!)
  329. }
  330. }
  331. @objc private func insertPagesForDescSort(pages: Array<CPDFPage>, indexs: IndexSet) {
  332. self.insertPages(pages: pages, indexs: indexs)
  333. /// 选中插入的页面
  334. self.selectPages(indexs: indexs)
  335. }
  336. func selectPages(indexs: IndexSet, needScroll: Bool = true) {
  337. var selectPages: [Int] = []
  338. for index in indexs {
  339. selectPages.append(index+1)
  340. }
  341. DispatchQueue.main.async {
  342. var data = Set<IndexPath>()
  343. for index in selectPages {
  344. data.insert(IndexPath(item: index-1, section: 0))
  345. }
  346. if self.thumbnailView != nil {
  347. self.thumbnailView.collectionView.deselectAll(nil)
  348. if needScroll {
  349. self.thumbnailView.collectionView.selectItems(at: data, scrollPosition: .centeredVertically)
  350. } else {
  351. self.thumbnailView.collectionView.selectItems(at: data, scrollPosition: NSCollectionView.ScrollPosition())
  352. }
  353. }
  354. }
  355. }
  356. /// MARK: indexs 需要降序排序后
  357. @objc private func insertPages(pages: Array<CPDFPage>, indexs: IndexSet) {
  358. var count: Int = 0
  359. for index in indexs {
  360. if (count >= pages.count) {
  361. break
  362. }
  363. // let newPage = pages[count].copy() as? CPDFPage
  364. let newPage = pages[count]
  365. // if (newPage == nil) {
  366. // continue
  367. // }
  368. self.listView?.document.insertPageObject(newPage, at: UInt(index))
  369. count += 1
  370. }
  371. // self.listView.undoManager?.registerUndo(withTarget: self, selector: #selector(deletePages), object: indexs)
  372. // 设置文档已编辑
  373. DispatchQueue.main.asyncAfter(deadline: .now() + 0.7, execute: {
  374. self.setDocumentEditedState(window: self.view.window)
  375. })
  376. (self.listView.undoManager?.prepare(withInvocationTarget: self) as AnyObject).deletePages(indexs: indexs)
  377. self.listView?.layoutDocumentView()
  378. self.thumbnailView.reloadData()
  379. }
  380. /// MARK: indexs 需要降序排序后
  381. /// dynamic 动态派发
  382. @objc private dynamic func deletePages(indexs: IndexSet) {
  383. let newIndexs = indexs.sorted()
  384. var array: Array<CPDFPage> = []
  385. for i in indexs {
  386. array.append((self.listView?.document.page(at: UInt(i)))!)
  387. }
  388. self.listView?.document.removePage(at: indexs)
  389. self.listView.undoManager?.registerUndo(withTarget: self) { target in
  390. target.insertPages(pages: array, indexs: indexs)
  391. }
  392. self.listView?.layoutDocumentView()
  393. self.thumbnailView.reloadData()
  394. }
  395. @IBAction func rotatePageItemAction(menu:NSMenuItem) {
  396. Task { @MainActor in
  397. #if VERSION_DMG
  398. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  399. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  400. return
  401. }
  402. #endif
  403. let indexs = self.thumbnailView.collectionView.selectionIndexes
  404. let indexPaths = self.thumbnailView.collectionView.selectionIndexPaths
  405. if indexs.count >= 0 {
  406. var pageItems: [KMThumbnailPageItem] = []
  407. let newDocument = self.thumbnailView.document
  408. for index in indexs {
  409. let page : CPDFPage = (newDocument?.page(at: UInt(index)))!
  410. var rotation = page.rotation
  411. if rotation == 0 {
  412. rotation = 90
  413. } else if rotation == 90 {
  414. rotation = 180
  415. } else if rotation == 180 {
  416. rotation = 270
  417. } else if rotation == 270 {
  418. rotation = 0
  419. }
  420. let pageItem = KMThumbnailPageItem(page: page, rotate: rotation, oldRotate: page.rotation)
  421. pageItems.append(pageItem)
  422. }
  423. self.rotatePageItems(pageItems: pageItems, indexPaths: indexPaths)
  424. // 事件外面传递
  425. self.delegate?.controller?(controller: self, itemClick: menu, itemKey: .rightRotate, params: nil)
  426. }
  427. }
  428. }
  429. @IBAction func leftRotatePageItemAction(menu:NSMenuItem) {
  430. Task { @MainActor in
  431. #if VERSION_DMG
  432. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  433. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  434. return
  435. }
  436. #endif
  437. let indexs = self.thumbnailView.collectionView.selectionIndexes
  438. let indexPaths = self.thumbnailView.collectionView.selectionIndexPaths
  439. if indexs.count >= 0 {
  440. var pageItems: [KMThumbnailPageItem] = []
  441. let newDocument = self.thumbnailView.document
  442. for index in indexs {
  443. let page : CPDFPage = (newDocument?.page(at: UInt(index)))!
  444. var rotation = page.rotation
  445. if rotation == 0 {
  446. rotation = 270
  447. } else if rotation == 90 {
  448. rotation = 0
  449. } else if rotation == 180 {
  450. rotation = 90
  451. } else if rotation == 270 {
  452. rotation = 180
  453. }
  454. let pageItem = KMThumbnailPageItem(page: page, rotate: rotation, oldRotate: page.rotation)
  455. pageItems.append(pageItem)
  456. }
  457. self.rotatePageItems(pageItems: pageItems, indexPaths: indexPaths)
  458. // 事件外面传递
  459. self.delegate?.controller?(controller: self, itemClick: menu, itemKey: .leftRotate, params: nil)
  460. }
  461. }
  462. }
  463. @IBAction func extractPageItemAction(menu:NSMenuItem) {
  464. let index = (self.thumbnailView.collectionView.selectionIndexes).first ?? -1
  465. if Int(index) >= 0 {
  466. let newDocument = self.thumbnailView.document
  467. var page : CPDFPage = (newDocument?.page(at: UInt(index)))!
  468. let filename : String = (newDocument?.documentURL.lastPathComponent)!
  469. let pageIndex = newDocument!.index(for: page) + 1
  470. var newfileName : String = "\(NSString(string: filename).deletingPathExtension) page \(pageIndex)"
  471. newfileName = "\(newfileName)\(filename.extension)"
  472. let panel = NSSavePanel()
  473. panel.nameFieldStringValue = newfileName
  474. panel.canCreateDirectories = true
  475. panel.allowedFileTypes = ["pdf"]
  476. panel.isExtensionHidden = true
  477. panel.beginSheetModal(for: self.view.window!) { result in
  478. if result == .OK {
  479. let pdfdocument = CPDFDocument()
  480. let ret = pdfdocument!.importPages((self.thumbnailView.collectionView.selectionIndexes), from: self.thumbnailView.document, at: 0)
  481. if ret {
  482. let success = pdfdocument!.write(to:panel.url)
  483. if success {
  484. let workspace = NSWorkspace.shared
  485. workspace.activateFileViewerSelecting([panel.url!])
  486. }
  487. }
  488. }
  489. }
  490. }
  491. }
  492. @IBAction func pageEditItemAction(menu:NSMenuItem) {
  493. var indexs: [Int] = []
  494. for index in self.thumbnailView.collectionView.selectionIndexes {
  495. indexs.append(index)
  496. }
  497. self.delegate?.gotoPageEdit?(thumbnailViewController: self, pages: indexs)
  498. }
  499. @IBAction func deletePageItemAction(menu:NSMenuItem) {
  500. Task { @MainActor in
  501. #if VERSION_DMG
  502. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  503. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  504. return
  505. }
  506. #endif
  507. let indexs = self.thumbnailView.collectionView.selectionIndexes
  508. if indexs.count > 0 {
  509. self.deletePageItemWithIndexs(indexs: indexs)
  510. // 事件外面传递
  511. self.delegate?.controller?(controller: self, itemClick: menu, itemKey: .delete, params: nil)
  512. }
  513. }
  514. }
  515. @objc func showPageSizeItemAction(menu: NSMenuItem) {
  516. self.thumbnailView.isShowPageSize = !self.thumbnailView.isShowPageSize
  517. let indexpaths = self.thumbnailView.selectionIndexPaths
  518. self.reloadData()
  519. self.thumbnailView.selectionIndexPaths = indexpaths
  520. }
  521. @IBAction func sharePageItemAction(menu:NSMenuItem) {
  522. let item = menu.parent!
  523. let index = (self.thumbnailView.collectionView.selectionIndexes).first ?? -1
  524. if Int(index) >= 0 {
  525. let doucument = self.thumbnailView.document
  526. let page = doucument?.page(at: UInt(index))
  527. let filename : String = (doucument?.documentURL.lastPathComponent)!
  528. let folderPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(filename))!
  529. try? FileManager.default.removeItem(atPath: folderPath)
  530. let pdfdocument = CPDFDocument()
  531. let ret = pdfdocument!.importPages((self.thumbnailView.collectionView.selectionIndexes), from: self.thumbnailView.document, at: 0)
  532. let url = URL(fileURLWithPath: folderPath)
  533. if ret {
  534. let success = pdfdocument!.write(to:url)
  535. if success {
  536. let workspace = NSWorkspace.shared
  537. workspace.activateFileViewerSelecting([url])
  538. }
  539. }
  540. let represent : NSSharingService = menu.representedObject as! NSSharingService
  541. represent.perform(withItems: [url])
  542. }
  543. }
  544. @IBAction func copyItemAction(menu:NSMenuItem) {
  545. Task { @MainActor in
  546. #if VERSION_DMG
  547. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  548. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  549. return
  550. }
  551. #endif
  552. KMThumbnailManager.manager.copyPages.removeAll()
  553. let indexs = self.thumbnailView.collectionView.selectionIndexes
  554. //文件存储用于跨文件page处理
  555. _ = KMThumbnailManager.manager.copyPages(document: self.thumbnailView.document!, indexs: indexs)
  556. //本地page记录用于本文件page移动处理
  557. if indexs.count >= 0 {
  558. for i in indexs {
  559. let page = self.thumbnailView.document?.page(at: UInt(i)).copy() as? CPDFPage
  560. KMThumbnailManager.manager.copyPages.append(page ?? CPDFPage())
  561. }
  562. }
  563. }
  564. }
  565. @IBAction func cutItemAction(menu:NSMenuItem) {
  566. Task { @MainActor in
  567. #if VERSION_DMG
  568. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  569. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  570. return
  571. }
  572. #endif
  573. KMThumbnailManager.manager.copyPages.removeAll()
  574. let indexs = self.thumbnailView.collectionView.selectionIndexes
  575. _ = KMThumbnailManager.manager.copyPages(document: self.thumbnailView.document!, indexs: indexs)
  576. if indexs.count >= 0 {
  577. for i in indexs {
  578. let page = self.thumbnailView.document?.page(at: UInt(i)).copy() as? CPDFPage
  579. KMThumbnailManager.manager.copyPages.append(page ?? CPDFPage())
  580. }
  581. self.deletePageItemWithIndexs(indexs: indexs)
  582. // 事件传递到外面
  583. self.delegate?.controller?(controller: self, itemClick: menu, itemKey: .cut, params: nil)
  584. }
  585. }
  586. }
  587. @IBAction func pastePageItemAction(menu:NSMenuItem) {
  588. Task { @MainActor in
  589. #if VERSION_DMG
  590. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  591. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  592. return
  593. }
  594. #endif
  595. let copyPages = KMThumbnailManager.manager.copyPages
  596. let page = copyPages.first
  597. if page?.document == self.thumbnailView.document {
  598. var index = (self.thumbnailView.collectionView.selectionIndexes).last ?? -1
  599. if Int(index) >= 0 && copyPages.count > 0 {
  600. var pageItems: [KMThumbnailPageItem] = []
  601. for page in copyPages {
  602. index = index + 1
  603. let pageItem = KMThumbnailPageItem(page: page, index: index, oldIndex: index)
  604. pageItems.append(pageItem)
  605. }
  606. self.addPageItems(pageItems: pageItems)
  607. self.selectPages(indexs: IndexSet(integer: index))
  608. self.listView.go(toPageIndex: index, animated: true)
  609. // 事件传递到外面
  610. self.delegate?.controller?(controller: self, itemClick: menu, itemKey: .paste, params: nil)
  611. }
  612. } else {
  613. let index = ((self.thumbnailView.collectionView.selectionIndexes).last ?? self.thumbnailView.collectionView.numberOfItems(inSection: 0) - 1) + 1
  614. debugPrint("不是同一个document")
  615. let url = URL(fileURLWithPath: KMThumbnailManager.manager.tempCopyFilePath)
  616. self.thumbnailView(thumbanView: self.thumbnailView, didDragAddFiles: [url], indexpath: NSIndexPath(forItem: index, inSection: 0) as IndexPath)
  617. }
  618. }
  619. }
  620. @IBAction func printItemAction(menu:NSMenuItem) {
  621. var indexs:[Int] = []
  622. for index in self.thumbnailView.collectionView.selectionIndexes {
  623. indexs.append(index)
  624. }
  625. if indexs.count > 0 {
  626. self.delegate?.controller?(controller: self, itemClick: menu, itemKey: .print, params: indexs)
  627. }
  628. }
  629. }
  630. protocol KMThumbnailViewControllerAction {}
  631. extension KMThumbnailViewController: KMThumbnailViewControllerAction {
  632. @IBAction func cut(_ sender: Any) {
  633. self.cutItemAction(menu: NSMenuItem())
  634. }
  635. @IBAction func copy(_ sender: Any) {
  636. self.copyItemAction(menu: NSMenuItem())
  637. }
  638. @IBAction func paste(_ sender: Any) {
  639. self.pastePageItemAction(menu: NSMenuItem())
  640. }
  641. @IBAction func delete(_ sender: Any) {
  642. self.deletePageItemAction(menu: NSMenuItem())
  643. }
  644. @IBAction func escButtonAction(_ sender: NSButton) {
  645. self.cancelSelect()
  646. }
  647. func cancelSelect() {
  648. self.selectPages(indexs: [])
  649. // self.km_resignFirstResponder()
  650. }
  651. }
  652. // MARK: - KMThumbnailViewDelegate
  653. extension KMThumbnailViewController : KMThumbnailViewDelegate {
  654. func thumbnailView(thumbanView: KMThumbnailView, didSelectItemAt indexpath: IndexPath, object: AnyObject?) {
  655. guard let event = object as? NSEvent else {
  656. return
  657. }
  658. self.km_resignFirstResponder()
  659. //是本地触发事件
  660. self.isLocalEvent = true
  661. if thumbanView.collectionView.selectionIndexes.count == 1 || (!event.modifierFlags.contains(NSEvent.ModifierFlags.command) &&
  662. !event.modifierFlags.contains(NSEvent.ModifierFlags.shift)) {
  663. let page : CPDFPage = self.listView.document.page(at: UInt(indexpath.item))
  664. self.listView.go(toPageIndex: Int(page.pageIndex()), animated: true)
  665. self.thumbnailView.collectionView.deselectAll(nil)
  666. self.thumbnailView.collectionView.selectionIndexes = IndexSet(integer: IndexSet.Element(indexpath.item))
  667. }
  668. var indexs: [Int] = []
  669. for index in self.thumbnailView.collectionView.selectionIndexes {
  670. indexs.append(index)
  671. }
  672. self.delegate?.pageDidSelect?(controller: self, pages: indexs)
  673. }
  674. func thumbnailView(thumbanView: KMThumbnailView, rightMouseDidClick indexpath: IndexPath, item: NSCollectionViewItem?, object: AnyObject?) {
  675. guard let event = object as? NSEvent else {
  676. return
  677. }
  678. self.addRightMenuItem(view: item as! KMPDFThumbnailItem, event: event)
  679. }
  680. func thumbnailView(thumbanView: KMThumbnailView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, dragOperation operation: NSDragOperation) {
  681. self.isLocalEvent = false
  682. }
  683. func thumbnailView(thumbanView: KMThumbnailView, sizeForItemAt indexpath: IndexPath) -> NSSize {
  684. if self.doublePageMode {
  685. return NSMakeSize(86, 147)
  686. } else {
  687. return NSMakeSize(156, 226)
  688. }
  689. }
  690. func thumbnailView(thumbanView: KMThumbnailView, shouldAcceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionView.DropOperation) -> Bool {
  691. #if VERSION_DMG
  692. if (!self.canUseAdvanced) {
  693. let _ = KMComparativeTableViewController.show(window: self.view.window!, .thumb)
  694. return false
  695. }
  696. #endif
  697. return true
  698. }
  699. func thumbnailView(thumbanView: KMThumbnailView, shouldPasteboardWriterForItemAt indexPath: IndexPath) -> Bool {
  700. #if VERSION_DMG
  701. if (!self.canUseAdvanced) {
  702. DispatchQueue.main.async {
  703. let _ = KMComparativeTableViewController.show(window: self.view.window!, .thumb)
  704. }
  705. return false
  706. }
  707. #endif
  708. if (!self.canPayFunction) {
  709. return false
  710. }
  711. return true
  712. }
  713. func thumbnailView(thumbanView: KMThumbnailView, didDrag dragedIndexPaths: [IndexPath], indexpath: IndexPath, dragInfo: [KMThumbnailViewDragInfoKey.RawValue : Any]) {
  714. let toIndex = max(0, indexpath.item)
  715. var indexs = IndexSet()
  716. for indexpath in dragedIndexPaths {
  717. indexs.insert(indexpath.item)
  718. }
  719. self.dragPagesForDescSort(indexs, toIndex)
  720. self.delegate?.pageDidSelect?(controller: self, pages: [self.listView.currentPageIndex])
  721. }
  722. func thumbnailView(thumbanView: KMThumbnailView, insetForSectionAt section: Int) -> NSEdgeInsets {
  723. if self.doublePageMode {
  724. return NSEdgeInsets(top: 8, left: 16, bottom: 8, right: 16)
  725. } else {
  726. return NSEdgeInsets(top: 8, left: 24, bottom: 8, right: 24)
  727. }
  728. }
  729. func thumbnailView(thumbanView: KMThumbnailView, didDragAddFiles files: [URL], indexpath: IndexPath) {
  730. self.km_add_file_multi(fileUrls: files) { [unowned self] index, params in
  731. if (self.fetchProgressBlockParamsIsPasswordFile(params: params)) { // 加密文档进度回调
  732. return
  733. }
  734. var _fileUrl = self.fetchProgressBlockParamsForFileUrl(params: params)
  735. if let exn = _fileUrl?.pathExtension, KMTools.isPDFType(exn) {
  736. if (_fileUrl!.path.isPDFValid() == false) {
  737. let alert = NSAlert()
  738. alert.alertStyle = .critical
  739. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  740. alert.runModal()
  741. }
  742. }
  743. } completionBlock: { [unowned self] documents in
  744. debugPrint(indexpath)
  745. var insertIndex: Int = indexpath.item
  746. var pages: Array<CPDFPage> = []
  747. var indexs = IndexSet()
  748. for document in documents {
  749. for i in 0 ..< document.pageCount {
  750. let page = document.page(at: i)
  751. pages.append(page!)
  752. indexs.insert(insertIndex)
  753. insertIndex += 1
  754. }
  755. }
  756. self.insertPagesForDescSort(pages: pages, indexs: indexs)
  757. }
  758. }
  759. }
  760. //MARK: NSMenuDelegate
  761. extension KMThumbnailViewController {
  762. override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  763. let action = menuItem.action
  764. if action == #selector(insertPageItemAction) ||
  765. action == #selector(insertPageItemAction) ||
  766. action == #selector(deletePageItemAction) ||
  767. action == #selector(rotatePageItemAction) ||
  768. action == #selector(leftRotatePageItemAction) ||
  769. action == #selector(copyItemAction) ||
  770. action == #selector(cutItemAction) ||
  771. action == #selector(printItemAction) ||
  772. action == #selector(sharePageItemAction) ||
  773. action == #selector(extractPageItemAction) {
  774. if self.thumbnailView.collectionView.selectionIndexes.count > 0 {
  775. return true
  776. } else {
  777. return false
  778. }
  779. }
  780. if action == #selector(pastePageItemAction) {
  781. if KMThumbnailManager.manager.copyPages.count != 0 {
  782. return true
  783. } else {
  784. return false
  785. }
  786. }
  787. if (action == #selector(undo)) {
  788. return self.listView.undoManager?.canUndo ?? false
  789. }
  790. if (action == #selector(redo)) {
  791. return self.listView.undoManager?.canRedo ?? false
  792. }
  793. return true
  794. }
  795. func addRightMenuItem(view: KMPDFThumbnailItem, event: NSEvent) {
  796. let index = view.page.pageIndex()
  797. if !self.thumbnailView.collectionView.selectionIndexes.contains(IndexSet.Element(index)) {
  798. var indexs: IndexSet = IndexSet()
  799. indexs.insert(IndexSet.Element(index))
  800. self.selectPages(indexs: indexs, needScroll: false)
  801. //
  802. // //PDFView跳转
  803. self.isLocalEvent = true
  804. self.listView.go(toPageIndex: Int(view.page.pageIndex()), animated: true)
  805. }
  806. DispatchQueue.main.async { [unowned self] in
  807. let menu = NSMenu()
  808. var item = NSMenuItem()
  809. // item = menu.addItem(withTitle: NSLocalizedString("Insert", comment: ""), action: nil, target: self)
  810. // item.representedObject = row
  811. //
  812. // var subMenu = NSMenu()
  813. // var subitem = NSMenuItem()
  814. // subitem = subMenu.addItem(withTitle: NSLocalizedString("Insert File", comment: ""), action: #selector(insertPageItemAction), target: self, tag:0)
  815. // subitem.representedObject = row
  816. // subitem = subMenu.addItem(withTitle: NSLocalizedString("Insert blank page", comment: ""), action: #selector(insertPageItemAction), target: self, tag:1)
  817. // subitem.representedObject = row
  818. // subitem = subMenu.addItem(withTitle: NSLocalizedString("Insert page", comment: ""), action: #selector(insertPageItemAction), target: self, tag:2)
  819. // subitem.representedObject = row
  820. // item.submenu = subMenu
  821. // item = menu.addItem(withTitle: NSLocalizedString("Extract", comment: ""), action: #selector(extractPageItemAction), target: self)
  822. item = menu.addItem(withTitle: NSLocalizedString("Copy", comment: ""), action: #selector(copyItemAction), target: self)
  823. item.keyEquivalent = "c"
  824. item = menu.addItem(withTitle: NSLocalizedString("Cut", comment: ""), action: #selector(cutItemAction), target: self)
  825. item.keyEquivalent = "x"
  826. item = menu.addItem(withTitle: NSLocalizedString("Paste", comment: ""), action: #selector(pastePageItemAction), target: self)
  827. item.keyEquivalent = "v"
  828. item = menu.addItem(withTitle: NSLocalizedString("Delete Page", comment: ""), action: #selector(deletePageItemAction), target: self)
  829. item.keyEquivalent = String(Unicode.Scalar(NSBackspaceCharacter)!)
  830. item.keyEquivalentModifierMask = []
  831. menu.addItem(NSMenuItem.separator())
  832. item = menu.addItem(withTitle: NSLocalizedString("Page Edit", comment: ""), action: #selector(pageEditItemAction), target: self)
  833. menu.addItem(NSMenuItem.separator())
  834. item = menu.addItem(withTitle: NSLocalizedString("Rotate Clockwise", comment: ""), action: #selector(rotatePageItemAction), target: self)
  835. item = menu.addItem(withTitle: NSLocalizedString("Rotate Counterclockwise", comment: ""), action: #selector(leftRotatePageItemAction), target: self)
  836. menu.addItem(NSMenuItem.separator())
  837. if (!self.thumbnailView.isShowPageSize) {
  838. item = menu.addItem(withTitle: NSLocalizedString("Hide Page Size", comment: ""), action: #selector(showPageSizeItemAction), target: self)
  839. } else {
  840. item = menu.addItem(withTitle: NSLocalizedString("Display Page Size", comment: ""), action: #selector(showPageSizeItemAction), target: self)
  841. }
  842. menu.addItem(NSMenuItem.separator())
  843. item = menu.addItem(withTitle: NSLocalizedString("Print", comment: ""), action: #selector(printItemAction), target: self)
  844. let point = view.contentBox?.convert(event.locationInWindow, from: nil)
  845. menu.popUp(positioning: nil, at: point!, in: view.contentBox)
  846. // item = menu.addItem(withTitle: NSLocalizedString("Share", comment: ""), action: nil, target: self)
  847. // item.representedObject = row
  848. // item.submenu = NSSharingServicePicker.menu(forSharingItems: [self.listView.document.documentURL ?? ""], subjectContext: "", withTarget: self, selector: #selector(sharePageItemAction), serviceDelegate: nil)
  849. }
  850. }
  851. }
  852. //MARK: undoRedo
  853. extension KMThumbnailViewController {
  854. func rotatePageItems(pageItems: [KMThumbnailPageItem], indexPaths: Set<IndexPath>) {
  855. let tempPageItems = pageItems
  856. for pageItem in tempPageItems {
  857. pageItem.page.rotation = pageItem.rotate
  858. }
  859. self.listView.layoutDocumentView()
  860. self.thumbnailView.reloadData()
  861. self.thumbnailView.collectionView.selectItems(at: indexPaths, scrollPosition: .centeredVertically)
  862. self.listView.undoManager?.registerUndo(withTarget: self) { [unowned self] targetType in
  863. self.isLocalEvent = true
  864. //替换下标顺序
  865. var tempPageItems: [KMThumbnailPageItem] = []
  866. for pageItem in pageItems {
  867. let item = KMThumbnailPageItem(page: pageItem.page, rotate: pageItem.oldRotate, oldRotate: pageItem.rotate)
  868. tempPageItems.append(item)
  869. }
  870. self.rotatePageItems(pageItems: tempPageItems, indexPaths: indexPaths)
  871. }
  872. }
  873. func deletePageItemWithIndexs(indexs: IndexSet) {
  874. if (indexs.count == (self.listView?.document.pageCount)!) {
  875. let _ = CustomAlertView(message: NSLocalizedString("Unable to delete all pages", comment: ""), from: self.thumbnailView, with: .blue)
  876. return
  877. }
  878. var pageItems: [KMThumbnailPageItem] = []
  879. for index in indexs {
  880. let page = self.listView.document.page(at: UInt(index))?.copy() as? CPDFPage
  881. if (page == nil) {
  882. continue
  883. }
  884. let pageItem = KMThumbnailPageItem(page: page!, index: index, oldIndex: index, bookMark: self.listView.document.bookmark(forPageIndex: UInt(index)))
  885. pageItems.append(pageItem)
  886. }
  887. self.deletePageItems(pageItems: pageItems)
  888. }
  889. func deletePageItems(pageItems: [KMThumbnailPageItem]) {
  890. //移除现有
  891. var tempPageItems = pageItems
  892. tempPageItems.sort(){$0.oldIndex > $1.oldIndex}
  893. for pageItem in tempPageItems {
  894. self.listView?.document.removePage(at: UInt(pageItem.oldIndex))
  895. }
  896. self.listView.layoutDocumentView()
  897. self.thumbnailView.reloadData()
  898. self.pdfCurrentPageChange()
  899. self.listView.undoManager?.registerUndo(withTarget: self) { [unowned self] targetType in
  900. self.isLocalEvent = true
  901. self.addPageItems(pageItems: tempPageItems)
  902. }
  903. }
  904. func addPageItems(pageItems: [KMThumbnailPageItem]) {
  905. var tempPageItems = pageItems
  906. tempPageItems.sort(){$0.oldIndex < $1.oldIndex}
  907. for pageItem in tempPageItems {
  908. let newPage = pageItem.page
  909. self.listView?.document.insertPageObject(newPage, at: UInt(pageItem.oldIndex))
  910. }
  911. for pageItem in tempPageItems {
  912. if pageItem.bookMark != nil && pageItem.oldIndex < self.listView.document.pageCount {
  913. self.listView?.document.addBookmark(pageItem.bookMark!.label, forPageIndex: UInt(pageItem.oldIndex))
  914. }
  915. }
  916. self.listView.layoutDocumentView()
  917. self.thumbnailView.reloadData()
  918. self.pdfCurrentPageChange()
  919. self.listView.undoManager?.registerUndo(withTarget: self) { [unowned self] targetType in
  920. self.isLocalEvent = true
  921. self.deletePageItems(pageItems: tempPageItems)
  922. }
  923. }
  924. func dragPageItems(pageItems: [KMThumbnailPageItem]) {
  925. var tempPageItems = pageItems
  926. //按照原下标顺序
  927. tempPageItems.sort(){$0.oldIndex > $1.oldIndex}
  928. //移除现有
  929. for pageItem in tempPageItems {
  930. self.listView?.document.removePage(at: UInt(pageItem.oldIndex))
  931. }
  932. //在原位置添加
  933. tempPageItems.sort(){$0.index < $1.index}
  934. for pageItem in tempPageItems {
  935. let newPage = pageItem.page
  936. self.listView?.document.insertPageObject(newPage, at: UInt(pageItem.index))
  937. }
  938. if pageItems.count > 0 {
  939. self.isLocalEvent = true
  940. self.selectPages(indexs: IndexSet(integer: pageItems.first!.index))
  941. self.listView.go(toPageIndex: pageItems.first!.index, animated: true)
  942. }
  943. // 刷新UI
  944. self.listView?.layoutDocumentView()
  945. self.thumbnailView.reloadData()
  946. self.listView.undoManager?.registerUndo(withTarget: self) { [unowned self] targetType in
  947. //替换下标顺序
  948. var tempPageItems: [KMThumbnailPageItem] = []
  949. for pageItem in pageItems {
  950. let item = KMThumbnailPageItem(page: pageItem.page, index: pageItem.oldIndex, oldIndex: pageItem.index)
  951. tempPageItems.append(item)
  952. }
  953. self.dragPageItems(pageItems: tempPageItems)
  954. }
  955. }
  956. @IBAction func undo(_ sender: Any) {
  957. if (self.listView.undoManager?.canUndo ?? false) {
  958. self.listView.undoManager?.undo()
  959. }
  960. }
  961. @IBAction func redo(_ sender: Any) {
  962. if (self.listView.undoManager?.canRedo ?? false) {
  963. self.listView.undoManager?.redo()
  964. }
  965. }
  966. }
  967. struct KMThumbnailPageItem {
  968. var page: CPDFPage
  969. var index: Int = 0
  970. var oldIndex: Int = 0
  971. var rotate: Int = 0
  972. var oldRotate: Int = 0
  973. var bookMark: CPDFBookmark?
  974. }