// // KMPDFEditViewController.swift // PDF Master // // Created by tangchao on 2023/1/6. // typealias KMPDFEditViewControllerSelectionDidChange = (_ selectedIndexs: Set) -> () class KMPDFEditViewController: KMPDFThumbViewBaseController { @IBOutlet weak var topBarBox: NSBox! @IBOutlet weak var contentBox: NSBox! var toolBar = KMPDFEditToolbar(frame: NSZeroRect) override var thumbnailView: KMPDFThumbnailView { get { if (super.thumbnailView is KMPageEditThumbnailView) { return super.thumbnailView } super.thumbnailView = KMPageEditThumbnailView() return super.thumbnailView } set { super.thumbnailView = newValue } } var pageEditThumbnailView: KMPageEditThumbnailView { get { return self.thumbnailView as! KMPageEditThumbnailView } } override var menuItems: [[KMPDFThumbViewMenu.Item]] { get { return [[.copy, .cut, .paste, .delete], [.insert, .extract, .replace, .split, .reverse], [.rightRotate, .leftRotate], [.showPageSize], [.print]] } } private var pdfDocument: CPDFDocument? var listView: CPDFView? var pageIsUpdate: Bool = true var selectedPages: [Int] = [] private let defaultItemSize = NSMakeSize(218 + 12 * 2, 292 + 24) var itemSize: NSSize = NSMakeSize(218 + 12 * 2, 292 + 24) // index=1 双击退出;index=2 打印 var itemClick: KMCommonClickBlock? var documentEditedCallback: KMCommonBlock? var selectionDidChange: KMPDFEditViewControllerSelectionDidChange? internal var viewFirstAppear = true private var _listViewCurrentIndex: Int = 0 var listViewCurrentIndex: Int { get { return self._listViewCurrentIndex } } override var canPayFunction: Bool { didSet { self.thumbnailView.limit = !self.canPayFunction } } required init?(coder: NSCoder) { super.init(coder: coder) } init(_ document: CPDFDocument) { super.init(nibName: "KMPDFEditViewController", bundle: nil) self.pdfDocument = document self.kmUndoManager = UndoManager() } override func viewDidAppear() { super.viewDidAppear() if (self.pdfDocument?.isLocked == false && self.viewFirstAppear) { self.viewFirstAppear = false self.thumbnailView.document = self.pdfDocument! self.thumbnailView.reloadData() } if let view = self.listView { // 存储阅读视图的当前页面索引 self._listViewCurrentIndex = view.currentPageIndex } if (self.selectedPages.isEmpty) { var index: Int = 0 if (self.listView != nil) { index = self.listView!.currentPageIndex } self.selectPages(indexs: IndexSet(integer: index)) self.toolBar.setPageRangeString("\(index+1)") } else { var indexs: IndexSet = [] for pageIndex in self.selectedPages { if (pageIndex < 0 || pageIndex >= (self.listView?.document.pageCount)!) { continue } indexs.insert(pageIndex) } self.selectPages(indexs: indexs) self.toolBar.setPageRangeString(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs.sorted())) } self.view.window?.makeFirstResponder(self) } override func viewDidLoad() { super.viewDidLoad() // 显示拖放移动动效 // self.thumbnailView.dragMoveEffectAnimated = true self.thumbnailView.collectionView.backgroundColor(NSColor.km_init(hex: "#CED0D4")) var allowedFileTypes: [String] = [] if let _types = KMConvertPDFManagerOC.supportFileType() as? [String] { allowedFileTypes = KMTools.pdfExtensions + _types } else { allowedFileTypes = KMTools.pdfExtensions + KMTools.imageExtensions } self.thumbnailView.kmAllowedFileTypes = allowedFileTypes let toolBar = self.toolBar self.topBarBox.contentView = toolBar self.topBarBox.fillColor = NSColor.km_init(hex: "#F7F8FA") toolBar.itemClick = { [unowned self] item, index in guard let type = KMPageEditType(rawValue: index) else { if (index == KMPageEditType.insert_files) { self.insertFileAction() } else if (index == KMPageEditType.insert_blank_page) { self.insertBlankPageAction() } else if (index == KMPageEditType.insert_custom_page) { self.item_insertCustomPage(sender: nil) } return } if (type == .leftRotate) { self.leftRotateAction() } else if (type == .rightRotate) { self.rightRotateAction() } else if (type == .zoomOut) { self.zoomOutButtonAction(sender: item?.zoomOutButton) } else if (type == .zoomIn) { self.zoomInButtonAction(sender: item?.zoomInButton) } else if (type == .extract) { self.extractAction() } else if (type == .replace) { self.replaceAction() } else if (type == .split) { self.splitAction() } else if (type == .reverse) { self.reverseAction() } else if (type == .delete) { self.deleteAction() } else if (type == .pageRange) { self.km_comboBoxSelectionDidChange((item?.pageRangeView)!) } else if (type == .insert) { self.trackEvent(type: .insert) } } toolBar.pageRangeValueDidChange = { [unowned self] value, _ in self.km_controlTextDidEndEditing(self.toolBar.pageRangeView!) } let view = self.thumbnailView self.contentBox.contentView?.addSubview(view) view.frame = self.contentBox.contentView!.bounds view.autoresizingMask = [.width, .height] self.pageEditThumbnailView.delegate = self self.pageEditThumbnailView.selectionDidChange = { [unowned self] selectedIndexs in self.selectionDidChange?(selectedIndexs) self.view.window?.makeFirstResponder(self) let enabled = (selectedIndexs.count > 0) for i in 0 ..< self.toolBar.toolBar.items.count { let item: KMToolBoxItem = self.toolBar.toolBar.items[i] if (item.itemIdentifier == KMToolbarPageEditExtractItemIdentifier || item.itemIdentifier == KMToolbarPageEditLeftRotateItemIdentifier || item.itemIdentifier == KMToolbarPageEditRightRotateItemIdentifier || item.itemIdentifier == KMToolbarPageEditReplaceItemIdentifier) { item.unEnabled = !enabled } else if (item.itemIdentifier == KMToolbarPageEditReverseItemIdentifier) { item.unEnabled = !(selectedIndexs.count > 1) } else if (item.itemIdentifier == KMToolbarPageEditDeleteItemIdentifier) { item.unEnabled = !self.canDelete() } } if (self.pageIsUpdate == false) { self.pageIsUpdate = true return } var indexs: Array = [] for indexPath in selectedIndexs { indexs.append(indexPath.item) } indexs.sort(){$0 < $1} self.toolBar.setPageRangeString(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs)) if let view = self.listView { // 存储阅读视图的当前页面索引 if indexs.count != 0 { self._listViewCurrentIndex = indexs.last! } } } } // MARK: Private Methods private func getSelecteIndex() -> Int { let index = self.getPasteIndex() if (index != NSNotFound) { return index } return 0 } private func getSelectedPage() -> CPDFPage { return (self.pdfDocument!.page(at: UInt(getSelecteIndex())))! } private func selectPages(indexs: IndexSet) { var indexpaths: Set = [] for index in indexs { indexpaths.insert(IndexPath(item: index, section: 0)) } self.selectPages(indexpaths: indexpaths) } private func km_becomeFirstResponder() { DispatchQueue.main.async { self.view.window?.makeFirstResponder(self) } } fileprivate func dealPdfDocumentDidEditCallback(type: KMPageEditType = .none) { // 提醒外面文档已编辑 guard let callback = self.documentEditedCallback else { return } callback(type) } // MARK: - 清空选择 private func clearSelectPages() { self.selectPages(indexs: IndexSet()) } override func refreshUI(indexpaths: Set = [], keepSelected: Bool = false) { super.refreshUI(indexpaths: indexpaths, keepSelected: keepSelected) self.listView?.layoutDocumentView() } override func cutAction() { if (self.thumbnailView.selectionIndexPaths.count == (self.listView?.document.pageCount)!) { let _ = CustomAlertView(message: NSLocalizedString("Unable to delete all pages", comment: ""), from: self.thumbnailView, with: .blue) return } super.cutAction() } override func copyAction() { self.trackEvent_copy() super.copyAction() } override func deleteAction() { self.trackEvent(type: .delete) super.deleteAction() self.toolBar.unSelectItem(for: KMToolbarPageEditDeleteItemIdentifier) } override func deleteIndexPaths(indexpaths: Set) { guard let pageCount = self.listView?.document.pageCount else { KMPrint("pageCount invalid.") return } if (indexpaths.count == pageCount) { let _ = CustomAlertView(message: NSLocalizedString("Unable to delete all pages", comment: ""), from: self.thumbnailView, with: .blue) return } self.dealPdfDocumentDidEditCallback(type: .delete) super.deleteIndexPaths(indexpaths: indexpaths) } override func leftRotateAction() { self.trackEvent(type: .leftRotate) super.leftRotateAction() // self.toolBar.unSelectItem(for: KMToolbarPageEditLeftRotateItemIdentifier) } override func leftRotateIndexpaths(indexpaths: Set) { if (!self.indexpathsIsValid(indexpaths: indexpaths) || !self.canRotate()) { return } super.leftRotateIndexpaths(indexpaths: indexpaths) self.dealPdfDocumentDidEditCallback(type: .leftRotate) } override func rightRotateAction() { self.trackEvent(type: .rightRotate) super.rightRotateAction() // self.toolBar.unSelectItem(for: KMToolbarPageEditRightRotateItemIdentifier) } override func rightRotateIndexpaths(indexpaths: Set) { if (!self.indexpathsIsValid(indexpaths: indexpaths) || !self.canRotate()) { return } super.rightRotateIndexpaths(indexpaths: indexpaths) self.dealPdfDocumentDidEditCallback(type: .rightRotate) } override func insertPages(pages: Array, at indexs: IndexSet) { super.insertPages(pages: pages, at: indexs) if (!indexs.isEmpty) { self.selectPages(indexs: indexs) self.dealPdfDocumentDidEditCallback(type: .insert) } } override func pasteAction() { if (self.canPaste()) { super.pasteAction() self.dealPdfDocumentDidEditCallback(type: .paste) } } override func extractAction() { self.trackEvent(type: .extract) super.extractAction() DispatchQueue.main.async { self.toolBar.unSelectItem(for: KMToolbarPageEditExtractItemIdentifier) } } override func replaceAction() { self.trackEvent(type: .replace) super.replaceAction() DispatchQueue.main.async { self.toolBar.unSelectItem(for: KMToolbarPageEditReplaceItemIdentifier) } } override func getInsertIndex() -> Int { var index = 0 if let pageCount = self.thumbnailView.document?.pageCount, pageCount > 0 { // 默认为最后一页 index = Int(pageCount-1) } // 在当前选中item之后插入 // 多选时,则取最后一页 for indexpath in self.thumbnailView.selectionIndexPaths.sorted() { index = indexpath.item } return index } override func splitAction() { self.trackEvent(type: .split) Task { @MainActor in self.toolBar.unSelectItem(for: KMToolbarPageEditSplitItemIdentifier) self.showSplitWindow { [unowned self] splitWindowC, model in if (!self.canPayFunction) { _ = KMSubscribeWaterMarkWindowController.show(window: splitWindowC.window!, type: .split) { isSubscribeSuccess, isWaterMarkExport, isClose in if (isClose) { return } if (isSubscribeSuccess) { self.km_endSheet() self._splitMethod(windowC: splitWindowC, model: model) return } if (isWaterMarkExport) { self.km_endSheet() self._splitMethod(windowC: splitWindowC, model: model, limit: true) return } } return } /// 拆分 self._splitMethod(windowC: splitWindowC, model: model) } } } func splitMethod(windowC: KMPageEditSplitWindowController, model: KMPageEditSplitSettingModel, limit: Bool = false) { self._splitMethod(windowC: windowC, model: model, limit: limit) } override func reverseAction() { self.trackEvent(type: .reverse) // Task { @MainActor in self.toolBar.unSelectItem(for: KMToolbarPageEditReverseItemIdentifier) self.reverseMenuAction(sender: nil) // } } func showSplitWindow(callback: @escaping (KMPageEditSplitWindowController, KMPageEditSplitSettingModel)->Void) { let model = KMPageEditSplitSettingModel() model.documentURL = self.listView?.document.documentURL if let pagecnt = self.thumbnailView.document?.pageCount { model.pageCount = Int(pagecnt) } model.fileName = model.documentURL.lastPathComponent model.pathExtension = model.fileName.components(separatedBy: ".").last if (self.thumbnailView.selectionIndexPaths.count > 0) { model.type = 2 model.pageRangeType = 2 var selectedIndexs: Array = [] for indexpath in self.thumbnailView.selectionIndexPaths { selectedIndexs.append(indexpath.item) } model.pageRangeString = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: selectedIndexs) } else { model.type = 0 } let windowController = KMPageEditSplitWindowController(model) self.km_beginSheet(windowC: windowController) windowController.itemClick = { [weak self] index, value in if (index == 1) { /// 取消 self?.km_endSheet() return } guard let _windowC = self?.kmCurrentWindowC as? KMPageEditSplitWindowController else { self?.km_endSheet() return } callback(_windowC, model) } } private func _splitMethod(windowC: KMPageEditSplitWindowController, model: KMPageEditSplitSettingModel, limit: Bool = false) { let outputModel = windowC.model! as! KMPageEditSplitSettingModel DispatchQueue.main.async { let panel = NSOpenPanel() panel.canChooseFiles = false panel.canChooseDirectories = true panel.canCreateDirectories = true panel.beginSheetModal(for: NSWindow.currentWindow()) { response in if (response == .cancel) { return } let file_indexs = outputModel.getSplitIndexSets if (file_indexs == nil || file_indexs!.count <= 0) { return } DispatchQueue.main.async { self.showProgressWindow(message: NSLocalizedString("Spliting...", comment: "")) self.progressC?.maxValue = Double(file_indexs!.count) let _document: CPDFDocument = (self.listView?.document)! let filePath = "\(panel.url!.path)/\(_document.documentURL.deletingPathExtension().lastPathComponent)" let uniqueFilePath = KMTools.getUniqueFilePath(filePath: filePath) // Swift.debugPrint(uniqueFilePath) if (!FileManager.default.fileExists(atPath: uniqueFilePath)) { try?FileManager.default.createDirectory(atPath: uniqueFilePath, withIntermediateDirectories: true) } var filepaths: [String] = [] for i in 0 ..< file_indexs!.count { let indexs = file_indexs![i] if (indexs.isEmpty) { continue } let filepath = String(format: "%@/%@.pdf", uniqueFilePath, model.getNewOutputFileName(index: i+1)) filepaths.append(filepath) let newDocument = CPDFDocument() newDocument?.importPages(indexs, from: _document, at: 0) self.progressC?.increment(by: 1.0) if (limit) { let _ = KMTools.saveWatermarkDocument(document: newDocument!, to: URL(fileURLWithPath: filepath)) } else { newDocument?.write(to: URL(fileURLWithPath: filepath)) } } self.hiddenProgressWindow() self.km_endSheet() if let _urlString = filepaths.first?.deletingLastPathComponent { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: _urlString)]) } } } } } // MARK: Undo / Redo @objc private func reversePages(indexs: IndexSet) { KMPageEditTools.reverse((self.listView?.document)!, indexs ) { result, error in if (result) { self.refreshUI(indexpaths: self.indexsToIndexpaths(indexs: indexs), keepSelected: true) self.kmUndoManager?.registerUndo(withTarget: self, selector: #selector(self.reversePages), object: indexs) } } } @objc private func dragPages(_ indexs: IndexSet, _ toIndex: Int, dp: NSCollectionView.DropOperation, reversed: Bool = false) { if (indexs.count <= 0) { return } self.listViewCurrentPageUpdateForDrag(indexs: indexs, toIndex: toIndex) // 插入位置偏移量 var toIndexOffset: Int = 0 // 需要移动的页面index数组 var newPages: [CPDFPage] = [] var currentPage: CPDFPage? var originalIndex = self.listViewCurrentIndex // 从后面往前删除 for index in indexs.reversed() { let newPage = (self.listView?.document.page(at: UInt(index)))?.copy() as? CPDFPage if (newPage == nil) { continue } newPages.insert(newPage!, at: 0) self.listView?.document.removePage(at: UInt(index)) if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex toIndexOffset += 1 } if (currentPage == nil) && (originalIndex == index) { currentPage = newPage } } if (indexs.last! < toIndex && dp == .on) { // 往后拖拽 toIndexOffset -= 1 } let insertIndex = max(0, toIndex-toIndexOffset) var selectIndexs: IndexSet = [] for (index, page) in newPages.enumerated() { self.listView?.document.insertPageObject(page, at: UInt(insertIndex+index)) selectIndexs.insert(insertIndex+index) if (currentPage?.pageIndex() == page.pageIndex()) { // self._listViewCurrentIndex = insertIndex+index } } // 新增 undo self.kmUndoManager?.registerUndo(withTarget: self) { target in target.clearSelectPages() target.dragPages_reversed(indexs, toIndex, newPages, dp: dp) } // 刷新UI self.refreshUI() if (reversed == false) { self.selectPages(indexs: selectIndexs) } } @objc private func dragPages_reversed(_ indexs: IndexSet, _ toIndex: Int, _ pages: [CPDFPage], dp: NSCollectionView.DropOperation) { if (indexs.count <= 0) { return } // 插入位置偏移量 var toIndexOffset: Int = 0 for index in indexs { if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex toIndexOffset += 1 } } if (indexs.last! < toIndex && dp == .on) { // 往后拖拽 toIndexOffset -= 1 } let insertIndex = max(0, toIndex-toIndexOffset) // 需要移动的页面index数组 var datas: [Int] = [] for index in insertIndex ..< (insertIndex + indexs.count) { datas.append(index) } // 从后面开始删除 for index in datas.reversed() { self.listView?.document.removePage(at: UInt(index)) } // 再插入到对应的位置 for (index,value) in indexs.enumerated() { var page: CPDFPage? if (index < pages.count) { page = pages[index] } if (page != nil) { self.listView?.document.insertPageObject(page!, at: UInt(value)) } } // 新增 undo self.kmUndoManager?.registerUndo(withTarget: self) { target in target.dragPages(indexs, toIndex, dp: dp, reversed: true) } // 刷新UI self.refreshUI() } // MARK: topBar 事件 @objc func zoomOutButtonAction(sender: NSButton?) { if (self.itemSize.width > self.defaultItemSize.width) { return } if let _document = self.thumbnailView.document { for i in 0 ..< _document.pageCount { let page = _document.page(at: i) page?.pageEditImage = nil } } if (self.itemSize.width < self.defaultItemSize.width) { self.itemSize = self.defaultItemSize } else if (self.itemSize.width == self.defaultItemSize.width) { self.itemSize = NSSize(width: self.defaultItemSize.width*1.5, height: self.defaultItemSize.height*1.5) } self.toolBar.zoomInButton?.isEnabled = true if (self.itemSize.width > self.defaultItemSize.width) { sender?.isEnabled = false } self.pageEditThumbnailView.zoomOut() } @objc func zoomInButtonAction(sender: NSButton?) { if (self.itemSize.width < self.defaultItemSize.width) { return } if let _document = self.thumbnailView.document { for i in 0 ..< _document.pageCount { let page = _document.page(at: i) page?.pageEditImage = nil } } if (self.itemSize.width > self.defaultItemSize.width) { self.itemSize = self.defaultItemSize } else if (self.itemSize.width == self.defaultItemSize.width) { self.itemSize = NSSize(width: self.defaultItemSize.width*0.5, height: self.defaultItemSize.height*0.5) } self.toolBar.zoomOutButton?.isEnabled = true if (self.itemSize.width < self.defaultItemSize.width) { sender?.isEnabled = false } self.pageEditThumbnailView.zoomIn() } // MARK: menu 菜单事件 @objc func item_insertCustomPage(sender: NSMenuItem?) { Task { @MainActor in let windowController = KMPageEditInsertCustomPageWindowController() if (self.thumbnailView.selectionIndexPaths.count > 0) { let page = self.getSelectedPage() let width = page.bounds.size.width * 210 / 595 let height = page.bounds.size.height * 297 / 842 windowController.selectedPageSize = NSSize(width: width, height: height) // windowController.selectedPageSize = self.getSelectedPage().bounds.size } self.km_beginSheet(windowC: windowController) windowController.itemClick = { [weak self] index in if (index == 1) { /// 取消 self?.km_endSheet() return } /// 插入 guard let windowC = self?.kmCurrentWindowC as? KMPageEditInsertCustomPageWindowController else { self?.km_endSheet() return } guard let _insertIndex = self?.getInsertIndex() else { self?.km_endSheet() return } /// 样式 // let type = windowC.typeIndex // mm 单位的大小 let pageSize = windowC.pageSize let direction = windowC.direction var _pageSize = KMPageEditTools.sizeUnitToBoundSize(unit: .mm, pageSize: pageSize) if (direction == 0) { // 纵向 if (_pageSize.width > _pageSize.height) { // 需要交换 let tmp = _pageSize.width _pageSize.width = _pageSize.height _pageSize.height = tmp } else { // no things. } } else { // 横向 if (_pageSize.width > _pageSize.height) { // no things. } else { // 需要交换 let tmp = _pageSize.width _pageSize.width = _pageSize.height _pageSize.height = tmp } } /// 插入位置 // if (type == 1) { /// 空白页 let document = CPDFDocument() document?.insertPage(_pageSize, at: 0) if let page: CPDFPage = (document?.page(at: 0)) { self?.insertPages(pages: [page], at: IndexSet(integer: _insertIndex+1)) } // } else { // let document = CPDFDocument() // var imageName = "plaid" // if (type == 2) { // imageName = "horizontal_line" // } else if (type == 3) { // imageName = "five_line_score" // } // let imagePath = Bundle.main.pathForImageResource(imageName) // document?.insertPage(pageSize, withImage: imagePath, at: 0) // let page: CPDFPage = (document?.page(at: 0))! // if (direction == 0) { /// 纵向 // page.rotation = 90 // } // // self?.insertPagesForDescSort(pages: [page], indexs: IndexSet(integer: _insertIndex+1)) // } self?.km_endSheet() } } } // MARK: toolBar 菜单事件 @objc func reverseMenuAction(sender: AnyObject?) { let selectedIndexs = self.thumbnailView.selectionIndexPaths if (selectedIndexs.count < 2 ) { let alertView = CustomAlertView(message: NSLocalizedString("Please select at least two pages for editing first", comment: ""), from: self.thumbnailView, with: .blue) alertView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor alertView?.layer?.cornerRadius = 4 return } var indexs: IndexSet = [] for indexpath in selectedIndexs { indexs.insert(indexpath.item) } self.reversePages(indexs: indexs) self.dealPdfDocumentDidEditCallback(type: .reverse) } override func addMenuItem(menu: NSMenu, item: KMPDFThumbViewMenu.Item) -> NSMenuItem? { var item_: NSMenuItem? if (item.sel == KMPDFThumbViewMenu.insertSelector) { if (self.thumbnailView.selectionIndexPaths.count == 1) { item_ = menu.addItem(withTitle: NSLocalizedString("Insert", comment: ""), action: nil, target: self) let subMenu = NSMenu() subMenu.addItem(withTitle: NSLocalizedString("Insert a Blank Page", comment: ""), action: #selector(insertPageItemAction), target: self, tag:0) subMenu.addItem(withTitle: NSLocalizedString("Insert Custom Page", comment: ""), action: #selector(insertPageItemAction), target: self, tag:1) subMenu.addItem(withTitle: NSLocalizedString("Insert File", comment: ""), action: #selector(insertPageItemAction), target: self, tag:2) item_?.submenu = subMenu } } else if (item.sel == KMPDFThumbViewMenu.splitSelector) { if (self.thumbnailView.selectionIndexPaths.count > 1) { item_ = menu.addItem(withTitle: NSLocalizedString("Split", comment: ""), action: KMPDFThumbViewMenu.splitSelector, target: self) } } else if (item.sel == KMPDFThumbViewMenu.reverseSelector) { if (self.thumbnailView.selectionIndexPaths.count > 1) { item_ = menu.addItem(withTitle: NSLocalizedString("Reverse", comment: ""), action: KMPDFThumbViewMenu.reverseSelector, target: self) } } else { return super.addMenuItem(menu: menu, item: item) } return item_ } } extension KMPDFEditViewController { //MARK: menu Action @objc func insertPageItemAction(menu:NSMenuItem) { if (menu.tag == 0) { self.insertBlankPageAction() } else if (menu.tag == 1) { self.item_insertCustomPage(sender: nil) } else if (menu.tag == 2) { self.insertFileAction() } } @objc func sharePageItemAction(menu:NSMenuItem) { let item = menu.parent! let index = (item.representedObject as! IndexSet).first ?? -1 if Int(index) >= 0 { let doucument = self.pdfDocument! let page = doucument.page(at: UInt(index)) let filename : String = doucument.documentURL.lastPathComponent let folderPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(filename))! try? FileManager.default.removeItem(atPath: folderPath) let pdfdocument = CPDFDocument() let ret = pdfdocument!.importPages((item.representedObject as! IndexSet), from: self.thumbnailView.document, at: 0) let url = URL(fileURLWithPath: folderPath) if ret { let success = pdfdocument!.write(to:url) if success { let workspace = NSWorkspace.shared workspace.activateFileViewerSelecting([url]) } } let represent : NSSharingService = menu.representedObject as! NSSharingService represent.perform(withItems: [url]) } } @objc func showPageSizeItemAction(menu: NSMenuItem) { self.thumbnailView.isShowPageSize = !self.thumbnailView.isShowPageSize self.refreshUIForKeepSelecteds() } @objc func printItemAction(menu:NSMenuItem) { var datas: [Int] = [] for indexpath in self.thumbnailView.selectionIndexPaths { datas.append(indexpath.item) } guard let callback = self.itemClick else { return } callback(2, datas.sorted()) } } extension KMPDFEditViewController { override func menuItemAction_print(_ sender: Any?) { self.printItemAction(menu: sender as! NSMenuItem) } override func menuItemAction_showPageSize(_ sender: Any?) { self.showPageSizeItemAction(menu: sender as! NSMenuItem) } } // MARK: - KMSelectPopButtonDelegate extension KMPDFEditViewController { func km_comboBoxSelectionDidChange(_ obj: KMDesignSelect) { self.pageIsUpdate = false let index: Int = obj.indexOfSelectedItem var indexpaths: Set = [] var type: KMPageRange? if (index <= 0) { /// 全部页面 type = .all } else if (index == 1) { /// 奇数页 type = .odd } else if (index == 2) { /// 偶数页 type = .even } else if (index == 3) { /// 横向页 type = .horizontal } else if (index == 4) { /// 纵向页 type = .vertical } else { /// 自定义 type = .custom } for i in 0 ..< (self.pdfDocument?.pageCount)! { if (type == .all) { indexpaths.insert(IndexPath(item: Int(i), section: 0)) } else if (type == .odd) { if (i % 2 == 1) { continue } indexpaths.insert(IndexPath(item: Int(i), section: 0)) } else if (type == .even) { if (i % 2 == 0) { continue } indexpaths.insert(IndexPath(item: Int(i), section: 0)) } else if (type == .horizontal) { let page = self.pdfDocument?.page(at: i) guard let isVertical = page?.isVertical(), !isVertical else { continue } indexpaths.insert(IndexPath(item: Int(i), section: 0)) } else if (type == .vertical) { let page = self.pdfDocument?.page(at: i) guard let isHorizontal = page?.isHorizontal(), !isHorizontal else { continue } indexpaths.insert(IndexPath(item: Int(i), section: 0)) } } obj.editable = type == .custom if (type == .custom) { self.clearSelectPages() DispatchQueue.main.async { self.toolBar.pageRangeView?.stringValue = "" self.view.window?.makeFirstResponder(self.toolBar.pageRangeView?.textField) } } else { self.pageEditThumbnailView.selectPages(at: indexpaths) } } func km_controlTextDidEndEditing(_ obj: KMDesignSelect) { self.view.window?.makeFirstResponder(self) for index in 0 ..< obj.numberOfItems { if (obj.items[index] == obj.stringValue) { return } } let pages = KMPageRangeTools.findSelectPage(pageRangeString: self.toolBar.pageRangeView!.stringValue, pageCount: Int((self.listView?.document.pageCount)!)) if (pages.isEmpty) { let alert = NSAlert() alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "") alert.runModal() self.toolBar.setPageRangeString("") DispatchQueue.main.async { self.view.window?.makeFirstResponder(self.toolBar.pageRangeView?.textField) } return } var indexpaths: Set = [] for page in pages { if (page >= 1) { indexpaths.insert(IndexPath(item: page-1, section: 0)) } } self.pageIsUpdate = false self.pageEditThumbnailView.selectPages(at: indexpaths) } } // MARK: - // MARK: KMThumbnailViewDelegate extension KMPDFEditViewController: KMThumbnailViewDelegate { func thumbnailView(thumbanView: KMThumbnailView, shouldAcceptDrop draggingInfo: NSDraggingInfo, indexPath: IndexPath, dropOperation: NSCollectionView.DropOperation) -> Bool { return true } func thumbnailView(thumbanView: KMThumbnailView, didDragAddFiles files: [URL], indexpath: IndexPath) { self.km_add_file_multi(fileUrls: files) { index, params in if (self.fetchProgressBlockParamsIsPasswordFile(params: params)) { // 加密文档进度回调 return } let _fileUrl = self.fetchProgressBlockParamsForFileUrl(params: params) if let exn = _fileUrl?.pathExtension, KMTools.isPDFType(exn) { if (_fileUrl!.path.isPDFValid() == false) { let alert = NSAlert() alert.alertStyle = .critical alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "") alert.runModal() } } } completionBlock: { [unowned self] documents in var insertIndex: Int = indexpath.item var pages: Array = [] var indexs = IndexSet() for document in documents { for i in 0 ..< document.pageCount { let page = document.page(at: i) pages.append(page!) indexs.insert(insertIndex) insertIndex += 1 } } self.insertPages(pages: pages, at: indexs) } } func thumbnailView(thumbanView: KMThumbnailView, didDrag dragedIndexPaths: [IndexPath], indexpath: IndexPath, dragInfo: [KMThumbnailViewDragInfoKey.RawValue : Any]) { let toIndex = max(0, indexpath.item) var indexs = IndexSet() for indexpath in dragedIndexPaths { indexs.insert(indexpath.item) } var dp = NSCollectionView.DropOperation.on if let _dp = dragInfo[KMThumbnailViewDragInfoKey.dropOperation.rawValue] as? NSCollectionView.DropOperation { dp = _dp } self.dragPages(indexs, toIndex, dp: dp) if (dragedIndexPaths.count > 0) { self.dealPdfDocumentDidEditCallback() } } func thumbnailView(thumbanView: KMThumbnailView, shouldPasteboardWriterForItemAt indexPath: IndexPath) -> Bool { if (!self.canPayFunction) { return false } return true } func thumbnailView(thumbanView: KMThumbnailView, insetForSectionAt section: Int) -> NSEdgeInsets { return NSEdgeInsets(top: 16, left: 16, bottom: 0, right: 32) } func thumbnailView(thumbanView: KMThumbnailView, sizeForItemAt indexpath: IndexPath) -> NSSize { self.thumbnailView.thumbnailSzie = CGSize(width: 120, height: 155) if (!self.thumbnailView.isShowPageSize) { return NSMakeSize(self.itemSize.width, self.itemSize.height+26) } return self.itemSize } func thumbnailView(thumbanView: KMThumbnailView, numberOfItemsInSection section: Int) -> Int { if let count = self.pdfDocument?.pageCount { return Int(count) } return 0 } func thumbnailView(thumbanView: KMThumbnailView, itemForRepresentedObjectAt indexpath: IndexPath) -> NSCollectionViewItem { let cellView: KMPageEditThumbnailItem = thumbanView.collectionView.makeItem(withIdentifier: KMPageEditThumbnailItem.km_identifier, for: indexpath) as! KMPageEditThumbnailItem cellView.isShowPageSize = self.thumbnailView.isShowPageSize cellView.setPage(page: (self.pdfDocument?.page(at: UInt(indexpath.item)))!) cellView.doubleClickAction = { [unowned self] _ in guard let callback = self.itemClick else { return } callback(1, indexpath.item) } cellView.mouseDownAction = { [unowned self] _ in let selectionIndexPaths = self.thumbnailView.selectionIndexPaths if (selectionIndexPaths.count == 1 && selectionIndexPaths.first?.item == indexpath.item) { return } self.selectPages(indexs: IndexSet.init(integer: indexpath.item)) } cellView.rightMouseDownAction = { [unowned self] _ in self.selectPages(indexs: IndexSet.init(integer: indexpath.item)) } return cellView } } // MARK: - 系统菜单栏 extension KMPDFEditViewController { override func undo(_ sender: Any?) { super.undo(sender) self.km_becomeFirstResponder() } override func redo(_ sender: Any?) { super.redo(sender) self.km_becomeFirstResponder() } } // MARK: - KMExtensions extension KMPDFEditViewController { override func deleteAfter(indexpaths: Set) { self.clearSelectPages() self.km_becomeFirstResponder() } override func copyAfter(indexpaths: Set) { self.km_becomeFirstResponder() } override func pasteAfter(at index: Int) { self.km_becomeFirstResponder() } override func cutAfter(indexpaths: Set) { self.clearSelectPages() self.km_becomeFirstResponder() } override func leftRotateAfter(indexpaths: Set) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.thumbnailView.document) self.km_becomeFirstResponder() } override func rightRotateAfter(indexpaths: Set) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "KMPDFViewRotatePage"), object: self.thumbnailView.document) self.km_becomeFirstResponder() } override func replaceAfter(of targetIndexs: IndexSet, with pages: [CPDFPage], at index: Int) { var indexpaths = Set() var insertIndex = index for _ in pages { indexpaths.insert(IndexPath(item: insertIndex, section: 0)) insertIndex += 1 } self.thumbnailView.selectionIndexPaths = indexpaths self.dealPdfDocumentDidEditCallback(type: .replace) } override func insertBlankPageAfter(size: NSSize, at index: Int) { self.selectPages(indexs: IndexSet(integer: index)) self.dealPdfDocumentDidEditCallback(type: .insert) } func listViewCurrentPageUpdateForDrag(indexs: IndexSet, toIndex: Int) { if (indexs.isEmpty) { return } // listView 当前页面 被拖拽 if (indexs.contains(self._listViewCurrentIndex)) { // let idx = indexs.firstIndex(of: self._listViewCurrentIndex) var idx: Int = 0 for index in indexs { if (index == self._listViewCurrentIndex) { break } idx += 1 } // 插入位置偏移量 var toIndexOffset: Int = 0 // 从后面往前删除 for index in indexs.reversed() { let newPage = (self.listView?.document.page(at: UInt(index)))?.copy() as? CPDFPage if (newPage == nil) { continue } if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex toIndexOffset += 1 } } if (indexs.last! < toIndex) { // 往后拖拽 toIndexOffset -= 1 } let insertIndex = max(0, toIndex-toIndexOffset) self._listViewCurrentIndex = insertIndex+idx } else { var forwardCnt = 0 var nextCnt = 0 for index in indexs { if (index > self._listViewCurrentIndex) { nextCnt += 1 } else { forwardCnt += 1 } } if (self._listViewCurrentIndex > toIndex) { // 插入到目标前面, 前面不管,只管后面的格式 self._listViewCurrentIndex += nextCnt } else if (self._listViewCurrentIndex < toIndex) { // 插入到目标后面, 后面不管,只管前面的格式 self._listViewCurrentIndex = max(0, self._listViewCurrentIndex - forwardCnt) } else { // 插入到目标位置 [跟插入到目标后面一样] self._listViewCurrentIndex = max(0, self._listViewCurrentIndex - forwardCnt) } } } } // MARK: - Analytics (埋点) extension KMPDFEditViewController { func trackEvent(type: KMPageEditType) -> Void { if (type == .insert) { KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Insert", parameters: [ KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit, KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all) } else if (type == .extract) { KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Extract", parameters: [ KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit, KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all) } else if (type == .leftRotate || type == .rightRotate) { KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Rotate", parameters: [ KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit, KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all) } else if (type == .replace) { KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Replace", parameters: [ KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit, KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all) } else if (type == .split) { KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Split", parameters: [ KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit, KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all) } else if (type == .reverse) { KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Reverse", parameters: [ KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit, KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all) } else if (type == .delete) { KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Delete", parameters: [ KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit, KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all) } } func trackEvent_copy() -> Void { KMAnalytics.trackEvent(eventName: "Btn_SubTbr_Copy", parameters: [ KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.subTbr_PageEdit, KMAnalytics.Parameter.labelKey : KMAnalytics.Label.subTbr_Btn], platform: .AppCenter, appTarget: .all) } }