KMLeftSideViewController+Thumbnail.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. //
  2. // KMLeftSideViewController+Thumbnail.swift
  3. // PDF Master
  4. //
  5. // Created by tangchao on 2024/1/12.
  6. //
  7. import Foundation
  8. extension KMLeftSideViewController.Key {
  9. static let thumbSizeScaling = "KMThumbnailSizeScalingKey"
  10. static let thumbDisplayPageSizeKey = "kKMThumbnailDisplayPageSizeKey"
  11. }
  12. // MARK: - Actions
  13. extension KMLeftSideViewController {
  14. public func refreshUIOfThumbnailIfNeed(preference: Bool = false) {
  15. if self.type.methodType != .Thumbnail {
  16. return
  17. }
  18. if preference {
  19. self.reloadThumbnailSize()
  20. }
  21. Task { @MainActor in
  22. self.thumbnailTableView.reloadData()
  23. }
  24. }
  25. public func reloadThumbnailDataIfNeed() {
  26. if self.type.methodType != .Thumbnail {
  27. return
  28. }
  29. self.resetThumbnails()
  30. }
  31. public func reloadThumbnailSize() {
  32. let defaultSize = roundf(KMPreference.shared.thumbPageSize)
  33. var thumbnailSize = Self.kTinySize
  34. if defaultSize < Self.kTinySize + Self.kFudgeSize {
  35. } else {
  36. if defaultSize < Self.kSmallSize + Self.kFudgeSize {
  37. thumbnailSize = Self.kSmallSize
  38. } else {
  39. if defaultSize < Self.kLargeSize + Self.kFudgeSize {
  40. thumbnailSize = Self.kLargeSize
  41. } else {
  42. thumbnailSize = Self.kHugeSize
  43. }
  44. }
  45. }
  46. if (abs(thumbnailSize - Float(self.thumbnailCacheSize)) > Self.kFudgeSize) {
  47. self.thumbnailCacheSize = thumbnailSize.cgFloat
  48. }
  49. Task { @MainActor in
  50. self.thumbnailTableView.reloadData()
  51. }
  52. }
  53. // 显示缩略图模块
  54. func showThumbnail() {
  55. if self.leftView.segmentedControl.selectedSegment == 0 {
  56. } else {
  57. self.leftView.segmentedControl.selectedSegment = 0
  58. }
  59. }
  60. func updateThumbnail(at index: Int) {
  61. if index < self.thumbnails.count {
  62. self.thumbnails[index].dirty = true
  63. /*
  64. 原问题:CrashKit - SKMainWindowController updateThumbnailAtPageIndex:] ([__NSArrayM objectAtIndex:]: index 9223372036854775807 beyond bounds [0 .. 17])
  65. 注释原因:缩略图高亮为自定义后,刷新会将高亮刷新到0行
  66. */
  67. // [leftSideController.thumbnailTableView reloadData];
  68. // BOOL visible = NO;
  69. // PDFPage *page = [[pdfView document] pageAtIndex:anIndex];
  70. // if([self.pdfView.visiblePages containsObject:page]) {
  71. // visible = YES;
  72. // }
  73. // NSInteger curIndex = [pdfView.document indexForPage:pdfView.currentPage];
  74. // if (need && curIndex != anIndex && !visible) {
  75. // [pdfView goToPage:[[pdfView document] pageAtIndex:anIndex]];
  76. // }
  77. }
  78. }
  79. func allThumbnailsNeedUpdate() {
  80. for thumb in self.thumbnails {
  81. thumb.dirty = true
  82. }
  83. self.reloadThumbnailSize()
  84. }
  85. func thumb_selectRowIndexsIfNeed(_ indexs: IndexSet) {
  86. let isReadMode = self.mainViewController?.isReadMode ?? false
  87. if self.type.methodType != .Thumbnail && isReadMode == false {
  88. return
  89. }
  90. if indexs.isEmpty {
  91. return
  92. }
  93. Task { @MainActor in
  94. self.thumbnailTableView.selectRowIndexes(indexs, byExtendingSelection: false)
  95. self.thumbnailTableView.scrollRowToVisible(indexs.first ?? 0)
  96. }
  97. }
  98. func thumb_initSubViews() {
  99. self.thumbnailZoomInButton.target = self
  100. self.thumbnailZoomInButton.action = #selector(thumbnailSizeScaling)
  101. self.thumbnailZoomInButton.tag = 1
  102. self.thumbnailZoomOutButton.target = self
  103. self.thumbnailZoomOutButton.action = #selector(thumbnailSizeScaling)
  104. self.thumbnailZoomOutButton.tag = 0
  105. self.thumbnailTableView.delegate = self
  106. self.thumbnailTableView.dataSource = self
  107. self.thumbnailTableView.thumbDelegate = self
  108. self.thumbnailTableView.botaDelegate = self
  109. self.thumbnailTableView.menu?.delegate = self
  110. self.thumbnailTableView.registerForDraggedTypes([.localDraggedTypes, .fileURL,.string,.pdf])
  111. self.thumbnailTableView.registerForDraggedTypes(NSFilePromiseReceiver.readableDraggedTypes.map { NSPasteboard.PasteboardType($0) })
  112. self.thumbnailTableView.setDraggingSourceOperationMask(.every, forLocal: false)
  113. }
  114. func thumb_initDefalutValue() {
  115. self.isDisplayPageSize = KMDataManager.ud_bool(forKey: Self.Key.thumbDisplayPageSizeKey)
  116. self.thumbnailView.wantsLayer = true
  117. self.thumbnailView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
  118. self.thumbnailTitleLabel.stringValue = KMLocalizedString("Thumbnails", nil)
  119. self.thumbnailTitleLabel.textColor = KMAppearance.Layout.h0Color()
  120. self.thumbnailZoomInButton.toolTip = KMLocalizedString("Zoom In", nil)
  121. self.thumbnailZoomOutButton.toolTip = KMLocalizedString("Zoom Out", nil)
  122. self.thumbnailTableView.backgroundColor = KMAppearance.Layout.l0Color()
  123. self.thumbnailTableView.allowsMultipleSelection = true
  124. self.thumbnailTableView.selectionHighlightStyle = .none
  125. }
  126. func thumb_fetchSelectedRows() -> [Int]? {
  127. return self.thumbnailTableView.selectedRowIndexes.sorted()
  128. }
  129. func updateThumbnailSelection() {
  130. let pageIndex = self.currentPageIndex()
  131. self.updatingThumbnailSelection = true
  132. self.thumbnailTableView.km_safe_selectRowIndexes(IndexSet(integer: pageIndex), byExtendingSelection: false)
  133. self.thumbnailTableView.scrollRowToVisible(pageIndex)
  134. self.updatingThumbnailSelection = false
  135. }
  136. }
  137. // MARK: - Others
  138. extension KMLeftSideViewController {}
  139. // MARK: - KMThumbnailTableViewDelegate
  140. extension KMLeftSideViewController: KMThumbnailTableViewDelegate {
  141. func tableView(_ tableView: NSTableView, highlightLevelForRow row: Int) -> UInt {
  142. if tableView.isEqual(to: self.thumbnailTableView) {
  143. // NSUInteger i, iMax = [lastViewedPages count];
  144. // for (i = 0; i < iMax; i++) {
  145. // if (row == (NSInteger)[lastViewedPages pointerAtIndex:i])
  146. // return i;
  147. // }
  148. }
  149. return UInt.max
  150. }
  151. func tableView(_ tableView: NSTableView, commandSelectRow rowIndex: Int) -> Bool {
  152. if tableView.isEqual(to: self.thumbnailTableView) {
  153. // NSRect rect = [[[pdfView document] pageAtIndex:row] boundsForBox:kPDFDisplayBoxCropBox];
  154. //
  155. // rect.origin.y = NSMidY(rect) - 0.5 * SNAPSHOT_HEIGHT;
  156. // rect.size.height = SNAPSHOT_HEIGHT;
  157. // [self showSnapshotAtPageNumber:row forRect:rect scaleFactor:[pdfView scaleFactor] autoFits:NO];
  158. let thumbailTabCell = tableView.view(atColumn: 0, row: rowIndex, makeIfNecessary: true) as? KMThumbnailTableviewCell
  159. thumbailTabCell?.isSelectCell = true
  160. var rowIndexSet = IndexSet()
  161. for i in self.thumbnailTableView.selectedRowIndexes {
  162. rowIndexSet.insert(i)
  163. }
  164. rowIndexSet.insert(rowIndex)
  165. self.thumbnailTableView.selectRowIndexes(rowIndexSet, byExtendingSelection: true)
  166. return true
  167. }
  168. return false
  169. }
  170. func tableView(_ tableView: NSTableView, shiftSelectRow rowIndex: Int) -> Bool {
  171. if tableView.isEqual(to: self.thumbnailTableView) {
  172. if (self.thumbnailTableView.selectedRowIndexes.count == 0) {
  173. let thumbailTabCell = tableView.view(atColumn: 0, row: rowIndex, makeIfNecessary: true) as? KMThumbnailTableviewCell
  174. thumbailTabCell?.isSelectCell = true
  175. var rowIndexSet = IndexSet()
  176. self.thumbnailTableView.selectRowIndexes(rowIndexSet, byExtendingSelection: true)
  177. return true
  178. } else if (self.thumbnailTableView.selectedRowIndexes.count == 1 && self.thumbnailTableView.selectedRowIndexes.first == rowIndex) {
  179. return false
  180. } else {
  181. var fristIndex = self.thumbnailTableView.selectedRowIndexes.first ?? Int.min
  182. var lastIndex = self.thumbnailTableView.selectedRowIndexes.last ?? Int.max
  183. for idx in self.thumbnailTableView.selectedRowIndexes {
  184. if(idx < fristIndex) {
  185. fristIndex = idx
  186. }
  187. if(idx > lastIndex) {
  188. lastIndex = idx
  189. }
  190. }
  191. if(rowIndex < fristIndex) {
  192. fristIndex = rowIndex
  193. } else if (rowIndex > lastIndex) {
  194. lastIndex = rowIndex
  195. }
  196. var rowIndexSet = IndexSet()
  197. for i in fristIndex ... lastIndex {
  198. rowIndexSet.insert(i)
  199. }
  200. self.thumbnailTableView.selectRowIndexes(rowIndexSet, byExtendingSelection: true)
  201. self.thumbnailTableView.ks_reloadData()
  202. return true
  203. }
  204. }
  205. return false
  206. }
  207. }
  208. // MARK: - Undo & Redo
  209. extension KMLeftSideViewController {
  210. @objc dynamic func tableView(_ tv: NSTableView, rotateRowsWithIndexes rowIndexes: NSIndexSet) {
  211. if tv.isEqual(to: self.thumbnailTableView) {
  212. for idx in rowIndexes {
  213. if (idx != NSNotFound) {
  214. let page = self.pdfDocument()?.page(at: UInt(idx))
  215. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).rotatePage(page, pageAt: idx)
  216. page?.rightRotate()
  217. self.layoutDocumentView()
  218. self.resetThumbnails()
  219. // NSInteger pageIndex = MIN(idx, [[pdfView document] pageCount]-1);
  220. // [pdfView goToPage:[[pdfView document] pageAtIndex:pageIndex]];
  221. }
  222. self.thumbnailTableView.selectRowIndexes(rowIndexes as IndexSet, byExtendingSelection: true)
  223. }
  224. }
  225. }
  226. @objc dynamic func rotatePage(_ page: CPDFPage?, pageAt index: Int) {
  227. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, rotateRowsWithIndexes: NSIndexSet(index: index))
  228. page?.leftRotate()
  229. self.layoutDocumentView()
  230. self.resetThumbnails()
  231. }
  232. @objc dynamic func insertPage(_ page: CPDFPage, pageAt index: Int) {
  233. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).tableView(self.thumbnailTableView, deleteRowsWithIndexes: IndexSet(integer: index))
  234. self.pdfDocument()?.insertPageObject(page, at: UInt(index))
  235. self.layoutDocumentView()
  236. self.resetThumbnails(ks: false)
  237. let pageIndex = min(index, self.pageCount()-1)
  238. Task { @MainActor in
  239. self.listView?.go(toPageIndex: pageIndex, animated: false)
  240. }
  241. }
  242. @objc dynamic func insertPages(_ selectedIndexSet: IndexSet, pageAt index: Int) {
  243. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).deletePages(selectedIndexSet, pageAt: index)
  244. self.layoutDocumentView()
  245. self.resetThumbnails(ks: false)
  246. Task { @MainActor in
  247. if let pageIndex = selectedIndexSet.first {
  248. self.listView?.go(toPageIndex: pageIndex, animated: false)
  249. }
  250. }
  251. }
  252. @objc dynamic func deletePages(_ selectedIndexSet: IndexSet, pageAt index: Int) {
  253. (self.listView?.undoManager?.prepare(withInvocationTarget: self) as AnyObject).insertPages(selectedIndexSet, pageAt: index)
  254. for idx in selectedIndexSet {
  255. if idx < self.pageCount() {
  256. self.pdfDocument()?.removePage(at: UInt(idx))
  257. }
  258. }
  259. self.layoutDocumentView()
  260. self.resetThumbnails()
  261. let pageIndex = min(index, self.pageCount()-1)
  262. self.listView?.go(toPageIndex: pageIndex, animated: false)
  263. }
  264. }
  265. // MARK: - Menu Actions
  266. extension KMLeftSideViewController {
  267. @objc func cutPage(_ sender: AnyObject?) {
  268. if IAPProductsManager.default().isAvailableAllFunction() == false {
  269. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  270. return
  271. }
  272. self.tableView(self.thumbnailTableView, cutRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  273. }
  274. @objc func copyPage(_ sender: AnyObject?) {
  275. self.tableView(self.thumbnailTableView, copyRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  276. }
  277. @objc func pastePage(_ sender: AnyObject?) {
  278. self.tableView(self.thumbnailTableView, pasteFromPasteboard: nil)
  279. }
  280. @objc func deletePage(_ sender: AnyObject?) {
  281. if IAPProductsManager.default().isAvailableAllFunction() == false {
  282. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  283. return
  284. }
  285. self.tableView(self.thumbnailTableView, deleteRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  286. }
  287. @objc func rotatePageMenuAction(_ sender: AnyObject?) {
  288. if IAPProductsManager.default().isAvailableAllFunction() == false {
  289. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  290. return
  291. }
  292. self.tableView(self.thumbnailTableView, rotateRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes as NSIndexSet)
  293. }
  294. @objc func quickInsert(_ sender: AnyObject?) {
  295. if IAPProductsManager.default().isAvailableAllFunction() == false {
  296. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  297. return
  298. }
  299. let idx = self.thumbnailTableView.selectedRowIndexes.first ?? NSNotFound
  300. if idx == NSNotFound || idx >= self.pageCount() {
  301. return
  302. }
  303. let result = self.listView?.insertPage(KMNormalBlankSize, at: idx+1) ?? false
  304. if result == false {
  305. return
  306. }
  307. var selectedIndexSet = IndexSet()
  308. selectedIndexSet.insert(idx+1)
  309. self.insertPages(selectedIndexSet, pageAt: idx)
  310. }
  311. @objc func insert(_ sender: AnyObject?) {
  312. if IAPProductsManager.default().isAvailableAllFunction() == false {
  313. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  314. return
  315. }
  316. guard let document = self.pdfDocument() else {
  317. return
  318. }
  319. let idx = self.thumbnailTableView.selectedRowIndexes.first ?? NSNotFound
  320. if idx == NSNotFound || idx >= document.pageCount {
  321. return
  322. }
  323. if document.allowsCopying == false || document.allowsPrinting == false {
  324. Task {
  325. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  326. }
  327. return
  328. }
  329. let winC = KMPDFEditInsertBlankPageWindow(document: document)
  330. winC.insertLocation = 3
  331. winC.currentPage = idx + 1
  332. winC.callback = { [weak self] pdfDoc, _, pages, insertI in
  333. guard let myWinC = self?.kmCurrentWindowC as? KMPDFEditInsertBlankPageWindow else {
  334. self?.km_quick_endSheet()
  335. return
  336. }
  337. if let _ = pages {
  338. var pageSize = myWinC.pageSize
  339. let direction = myWinC.pageRotation == 0 ? 0 : 1
  340. if (direction == 0) { // 纵向
  341. if (pageSize.width > pageSize.height) { // 需要交换
  342. let tmp = pageSize.width
  343. pageSize.width = pageSize.height
  344. pageSize.height = tmp
  345. } else {
  346. // no things.
  347. }
  348. } else { // 横向
  349. if (pageSize.width > pageSize.height) {
  350. // no things.
  351. } else { // 需要交换
  352. let tmp = pageSize.width
  353. pageSize.width = pageSize.height
  354. pageSize.height = tmp
  355. }
  356. }
  357. /// 插入位置
  358. let document = CPDFDocument()
  359. document?.insertPage(pageSize, at: 0)
  360. if let page = document?.page(at: 0) {
  361. self?.insertPage(page, pageAt: insertI)
  362. }
  363. }
  364. self?.km_quick_endSheet()
  365. }
  366. self.km_beginSheet(windowC: winC)
  367. }
  368. @objc func insertPDF(_ sender: AnyObject?) {
  369. if IAPProductsManager.default().isAvailableAllFunction() == false {
  370. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  371. return
  372. }
  373. guard let document = self.pdfDocument() else {
  374. return
  375. }
  376. let idx = self.thumbnailTableView.selectedRowIndexes.first ?? NSNotFound
  377. if idx == NSNotFound || idx >= document.pageCount {
  378. return
  379. }
  380. if document.allowsCopying == false || document.allowsPrinting == false {
  381. Task {
  382. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  383. }
  384. return
  385. }
  386. let panel = NSOpenPanel()
  387. panel.allowedFileTypes = ["pdf"]
  388. panel.beginSheetModal(for: self.view.window!) { response in
  389. if response == .cancel {
  390. return
  391. }
  392. for fileURL in panel.urls {
  393. let pdfDoc = CPDFDocument(url: fileURL)
  394. if let data = pdfDoc?.isLocked, data {
  395. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  396. KMBaseWindowController.checkPassword(url: fileURL, type: .owner) { [unowned self] success, resultPassword in
  397. self.km_quick_endSheet()
  398. if (resultPassword.isEmpty == false) {
  399. let insertVC = KMPDFEditInsertPageWindow(document: document, path: fileURL, password: resultPassword)
  400. insertVC.insertLocation = 3
  401. insertVC.currentPage = idx + 1
  402. self.km_beginSheet(windowC: insertVC)
  403. insertVC.callback = { [weak self] pdfDoc, pwd, pages, insertIdx in
  404. var indexs = IndexSet()
  405. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertPageWindow, _winC.insertDocument != nil else {
  406. self?.km_quick_endSheet()
  407. return
  408. }
  409. let doc = _winC.insertDocument!
  410. let fileAttribute = _winC.fileAttribute
  411. var insertIndex = insertIdx
  412. var insertPages: [CPDFPage] = []
  413. for number in fileAttribute.fetchSelectPages() {
  414. if let page = doc.page(at: UInt(number-1)) {
  415. insertPages.append(page)
  416. indexs.insert(insertIndex)
  417. insertIndex += 1
  418. }
  419. }
  420. for (i, page) in insertPages.enumerated() {
  421. self?.pdfDocument()?.insertPageObject(page, at: UInt(insertIdx + i))
  422. }
  423. self?.insertPages(indexs, pageAt: insertIdx)
  424. self?.km_quick_endSheet()
  425. }
  426. }
  427. }
  428. }
  429. } else {
  430. let insertVC = KMPDFEditInsertPageWindow(document: document, path: fileURL)
  431. insertVC.insertLocation = 3
  432. insertVC.currentPage = idx + 1
  433. self.km_beginSheet(windowC: insertVC)
  434. insertVC.callback = { [weak self] pdfDoc, pwd, pages, insertIdx in
  435. var indexs = IndexSet()
  436. guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertPageWindow, _winC.insertDocument != nil else {
  437. self?.km_quick_endSheet()
  438. return
  439. }
  440. let doc = _winC.insertDocument!
  441. let fileAttribute = _winC.fileAttribute
  442. var insertIndex = insertIdx
  443. var insertPages: [CPDFPage] = []
  444. for number in fileAttribute.fetchSelectPages() {
  445. if let page = doc.page(at: UInt(number-1)) {
  446. insertPages.append(page)
  447. indexs.insert(insertIndex)
  448. insertIndex += 1
  449. }
  450. }
  451. for (i, page) in insertPages.enumerated() {
  452. self?.pdfDocument()?.insertPageObject(page, at: UInt(insertIdx + i))
  453. }
  454. self?.insertPages(indexs, pageAt: insertIdx)
  455. self?.km_quick_endSheet()
  456. }
  457. }
  458. }
  459. }
  460. }
  461. @objc func extractPage(_ sender: AnyObject?) {
  462. if IAPProductsManager.default().isAvailableAllFunction() == false {
  463. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  464. return
  465. }
  466. self.tableView(self.thumbnailTableView, extractRowsWithIndexes: self.thumbnailTableView.selectedRowIndexes)
  467. }
  468. @objc func pageEdit(_ sender: AnyObject?) {
  469. self.delegate?.controller?(controller: self, itemClick: nil, itemKey: .pageEdit, params: nil)
  470. }
  471. @objc func displayPageSize(_ sender: AnyObject?) {
  472. if IAPProductsManager.default().isAvailableAllFunction() == false {
  473. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  474. return
  475. }
  476. self.isDisplayPageSize = !self.isDisplayPageSize
  477. KMDataManager.ud_set(self.isDisplayPageSize, forKey: Self.Key.thumbDisplayPageSizeKey)
  478. Task { @MainActor in
  479. self.thumbnailTableView.ks_reloadData()
  480. }
  481. }
  482. @objc func sharePage(_ sender: AnyObject?) {
  483. if IAPProductsManager.default().isAvailableAllFunction() == false {
  484. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  485. return
  486. }
  487. guard let document = self.pdfDocument() else {
  488. return
  489. }
  490. var pages = NSMutableArray()
  491. for idx in self.thumbnailTableView.selectedRowIndexes {
  492. if (idx < document.pageCount) {
  493. if let page = self.pdfDocument()?.page(at: UInt(idx)) {
  494. pages.add(page)
  495. }
  496. }
  497. }
  498. let pdf = CPDFDocument()
  499. for page in pages {
  500. if let _page = page as? CPDFPage {
  501. pdf?.insertPageObject(_page, at: pdf?.pageCount ?? 0)
  502. }
  503. }
  504. var fileName = ""
  505. var documentFileName = document.documentURL?.deletingPathExtension().lastPathComponent ?? ""
  506. var tName = self.fileNameWithSelectedPages(self.thumbnailTableView.selectedRowIndexes)
  507. if (tName.count > 50) {
  508. tName = tName.substring(to: 50)
  509. }
  510. if (pages.count > 1) {
  511. fileName = String(format: "%@ pages %@", documentFileName, tName)
  512. } else {
  513. fileName = String(format: "%@ page %@", documentFileName, tName)
  514. }
  515. let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
  516. var cachesDir = paths.first ?? ""
  517. cachesDir = "\(cachesDir)/\(fileName).pdf"
  518. var array = NSMutableArray()
  519. let url = URL(fileURLWithPath: cachesDir)
  520. array.add(url)
  521. let vc = KMProgressWindowController()
  522. guard let win = vc.window else {
  523. NSSound.beep()
  524. return
  525. }
  526. self.view.window?.beginSheet(win, completionHandler: { [unowned self] returnCode in
  527. NSApp.endSheet(self.view.window!, returnCode: returnCode.rawValue)
  528. })
  529. DispatchQueue.global().async {
  530. let sucess = pdf?.write(toFile: cachesDir) ?? false
  531. if (sucess) {
  532. DispatchQueue.main.async {
  533. let represent = (sender as? NSMenuItem)?.representedObject as? NSSharingService
  534. represent?.perform(withItems: [url])
  535. NSApp.endSheet(win)
  536. vc.close()
  537. }
  538. } else {
  539. NSApp.endSheet(win)
  540. vc.close()
  541. }
  542. }
  543. }
  544. }