KMThumbnailViewController.swift 40 KB

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