KMThumbnailViewController.swift 45 KB

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