// // KMPDFEditViewController.swift // PDF Reader Pro // // Created by tangchao on 2023/1/6. // typealias KMPDFEditViewControllerSelectionDidChange = (_ selectedIndexs: Set) -> () typealias KMIndexChooseBlock = (_ index: Int) -> Void class KMPDFEditViewController: KMPDFThumbViewBaseController { static let kNoPagesSelectedTipMessage = "No pages selected. Please select one or more pages first to organize." @IBOutlet weak var topBarBox: NSBox! @IBOutlet weak var contentBox: NSBox! @IBOutlet weak var thumbnailSizeView: NSView! @IBOutlet weak var zoomInButton: NSButton! @IBOutlet weak var zoomOutButton: NSButton! @IBOutlet weak var lineBoxView: NSView! 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 [[.insert ,.extract], [.leftRotate, .rightRotate, .copy, .paste, .reverse], [.delete], [.share]] } } private var pdfDocument: CPDFDocument? var listView: CPDFView? var pageIsUpdate: Bool = true var selectedPages: [Int] = [] private let defaultItemSize = NSMakeSize(215, 250) var itemSize: NSSize = NSMakeSize(215, 250) // index=1 双击退出;index=2 打印 var itemClick: KMCommonClickBlock? private var _isEdited = false var isEdited: Bool { return self._isEdited } var documentEditedCallback: KMCommonBlock? var selectionDidChange: KMPDFEditViewControllerSelectionDidChange? internal var viewFirstAppear = true private var _listViewCurrentIndex: Int = 0 var listViewCurrentIndex: Int { get { return self._listViewCurrentIndex } } private var fileAttri_: KMFileAttribute? private var popOver_: NSPopover? deinit { } required init?(coder: NSCoder) { super.init(coder: coder) } init(_ document: CPDFDocument) { super.init(nibName: "KMPDFEditViewController", bundle: nil) self.pdfDocument = document self.kmUndoManager = UndoManager() self.fileAttri_ = KMFileAttribute() self.fileAttri_?.password = document.password ?? "" self.fileAttri_?.filePath = document.documentURL.path } override func viewDidAppear() { super.viewDidAppear() let isLocked = self.pdfDocument?.isLocked ?? false let first = self.viewFirstAppear if (isLocked == false && self.viewFirstAppear) { self.viewFirstAppear = false if let doc = self.pdfDocument { self.thumbnailView.document = doc } self.thumbnailView.reloadData() } if let view = self.listView { // 存储阅读视图的当前页面索引 self._listViewCurrentIndex = view.currentPageIndex } var item: Int = 0 if (self.selectedPages.isEmpty) { let index = self.listView?.currentPageIndex ?? 0 self.selectPages(indexs: IndexSet(integer: index)) self.toolBar.setPageRangeString("\(index+1)") item = index } else { var indexs: IndexSet = [] for pageIndex in self.selectedPages { let pageCnt = self.listView?.document?.pageCount ?? 0 if (pageIndex < 0 || pageIndex >= pageCnt) { continue } indexs.insert(pageIndex) } self.selectPages(indexs: indexs) self.toolBar.setPageRangeString(KMPageRangeTools.newParseSelectedIndexs(selectedIndex: indexs.sorted())) item = indexs.sorted().last ?? 0 } if first { let cnt = self.thumbnailView.document?.pageCount ?? 0 if cnt > 0 { var ips = Set() ips.insert(IndexPath(item: item, section: 0)) self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .bottom) } } self.view.window?.makeFirstResponder(self) self._showPDFEditDetails() } override func viewDidLoad() { super.viewDidLoad() self._isEdited = false // 显示拖放移动动效 // self.thumbnailView.dragMoveEffectAnimated = true // self.thumbnailView.collectionView.backgroundColor(NSColor.km_init(hex: "#CED0D4")) self.thumbnailView.collectionView.wantsLayer = true // self.thumbnailView.collectionView.layer?.backgroundColor = KMAppearance.PDFViewBackgroundColor().cgColor if KMAppearance.isDarkMode() { self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#5F5F60").cgColor } else { self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#DADBDE").cgColor } self.thumbnailSizeView.wantsLayer = true self.thumbnailSizeView.layer?.backgroundColor = KMAppearance.Layout.b80Color().cgColor self.lineBoxView.wantsLayer = true self.lineBoxView.layer?.backgroundColor = KMAppearance.Layout.h2Color().cgColor var allowedFileTypes: [String] = [] // if let _types = KMConvertPDFManager.supportFileType() { allowedFileTypes = KMTools.pdfExtensions + KMConvertPDFManager.supportFileType() // } 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() self.trackEvent(type: .insert, index: index) } else if (index == KMPageEditType.insert_blank_page) { self.insertBlankPageAction() self.trackEvent(type: .insert, index: index) } else if (index == KMPageEditType.insert_custom_page) { self.item_insertCustomPage(sender: nil) self.trackEvent(type: .insert, index: index) } else if (index == KMPageEditType.insert_fromImage) { self.item_insertFromImage(sender: nil) self.trackEvent(type: .insert, index: index) } else if (index == KMPageEditType.insert_fromClipboard) { self.item_insertFromClipboard(sender: nil) self.trackEvent(type: .insert, index: index) } else if (index == KMPageEditType.insert_fromScanner) { self.item_insertFromScanner(sender: nil) self.trackEvent(type: .insert, index: index) } else if (index == KMPageEditType.extract_selected_pages) { self.extractSelectPageItemAction() } else if (index == KMPageEditType.split_selected_pages) { self.splitMenuAction() } 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) { } else if (type == .insert) { self.trackEvent(type: .insert) } else if (type == .copy) { self.copyAction() } else if (type == .paste) { self.pasteAction() } } toolBar.pageRangeitemClick = { [weak self] type in self?.km_comboBoxSelectionDidChange(type) } toolBar.pageRangeValueDidChange = { [weak self] value, _ in if let data = self?.toolBar.pageRangeView { self?.km_controlTextDidEndEditing(data) } } let view = self.thumbnailView self.contentBox.contentView?.addSubview(view) view.frame = self.contentBox.contentView?.bounds ?? .zero view.autoresizingMask = [.width, .height] self.pageEditThumbnailView.delegate = self self.pageEditThumbnailView.selectionDidChange = { [weak self] selectedIndexs in guard let self = self else { return } self.selectionDidChange?(selectedIndexs) self.view.window?.makeFirstResponder(self) let enabled = (selectedIndexs.count > 0) for i in 0 ..< self.toolBar.toolBar.items.count { let item = self.toolBar.toolBar.items[i] if item.itemIdentifier == KMToolbarPageEditLeftRotateItemIdentifier || item.itemIdentifier == KMToolbarPageEditRightRotateItemIdentifier { item.unEnabled = !enabled } } 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 self.listView != nil { // 存储阅读视图的当前页面索引 if indexs.count != 0 { self._listViewCurrentIndex = indexs.last! } } } } override func interfaceThemeDidChanged(_ appearance: NSAppearance.Name) { super.interfaceThemeDidChanged(appearance) self.thumbnailView.collectionView.wantsLayer = true if KMAppearance.isDarkMode() { self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#5F5F60").cgColor } else { self.thumbnailView.collectionView.layer?.backgroundColor = NSColor.km_init(hex: "#DADBDE").cgColor } Task { @MainActor in let ips = self.thumbnailView.selectionIndexPaths self.thumbnailView.collectionView.reloadData() self.thumbnailView.selectionIndexPaths = ips } } override func keyDown(with event: NSEvent) { // super.keyDown(with: event) let cmd = event.modifierFlags.contains(.command) let shift = event.modifierFlags.contains(.shift) let code = event.keyCode let isLeft = code == 123 let isUp = code == 126 let isRight = code == 124 let isDown = code == 125 if cmd { if code == 0 { // cmd + a self.km_comboBoxSelectionDidChange(.all) return } // let ips = self.thumbnailView.selectionIndexPaths // let indexs = self.indexpathsToIndexs(indexpaths: ips) //// let idx = indexs.last ?? 0 // var selectedIndexs = indexs // let numberItems = self.thumbnailView.collectionView.numberOfItems(inSection: 0) // let firstIdx = 0 // let lastIdx = max(numberItems-1, 0) // if isLeft { // + // if self.isEmptySelection() { // selectedIndexs.insert(lastIdx) // } else { // if let idx = selectedIndexs.first, idx > 0 { // selectedIndexs.insert(idx-1) // } // } // } else if isRight { // - // if self.isEmptySelection() { // selectedIndexs.insert(firstIdx) // } else { // if let idx = selectedIndexs.last, idx < lastIdx { // selectedIndexs.insert(idx+1) // } // } // } else { // var numberPerLine = 0 // let itemW = self.thumbnailView.itemSize.width // if itemW > 0 { // numberPerLine = Int(NSWidth(self.thumbnailView.collectionView.frame) / itemW) // } // if isUp { // if self.isEmptySelection() { // selectedIndexs.insert(lastIdx) // } else { // if let idx = selectedIndexs.first, idx > 0 { // selectedIndexs.insert(max(idx-numberPerLine, 0)) // } // } // } else if isDown { // if self.isEmptySelection() { // selectedIndexs.insert(firstIdx) // } else { // if let idx = selectedIndexs.last, idx < lastIdx { // selectedIndexs.insert(min(idx+numberPerLine, lastIdx)) // } // } // } // } // // if selectedIndexs.isEmpty == false { // let ips = self.indexsToIndexpaths(indexs: selectedIndexs) // self.thumbnailView.selectionIndexPaths = ips // self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically) // } } else if shift { } else { let ips = self.thumbnailView.selectionIndexPaths let indexs = self.indexpathsToIndexs(indexpaths: ips) let idx = indexs.last ?? 0 var selectedIndexs = IndexSet() let numberItems = self.thumbnailView.collectionView.numberOfItems(inSection: 0) let firstIdx = 0 let lastIdx = max(numberItems-1, 0) if isLeft { if self.isEmptySelection() { selectedIndexs.insert(lastIdx) } else { if idx > 0 { selectedIndexs.insert(idx-1) } } } else if isRight { if self.isEmptySelection() { selectedIndexs.insert(firstIdx) } else { if idx < lastIdx { selectedIndexs.insert(idx+1) } } } else { var numberPerLine = 0 let itemW = self.thumbnailView.itemSize.width if itemW > 0 { numberPerLine = Int(NSWidth(self.thumbnailView.collectionView.frame) / itemW) } if isUp { if self.isEmptySelection() { selectedIndexs.insert(lastIdx) } else { selectedIndexs.insert(max(idx-numberPerLine, 0)) } } else if isDown { if self.isEmptySelection() { selectedIndexs.insert(firstIdx) } else { selectedIndexs.insert(min(idx+numberPerLine, lastIdx)) } } } if selectedIndexs.isEmpty == false { let ips = self.indexsToIndexpaths(indexs: selectedIndexs) self.thumbnailView.selectionIndexPaths = ips self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically) } } } // 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) { self._isEdited = true // 提醒外面文档已编辑 guard let callback = self.documentEditedCallback else { return } callback(type) } private func _progressHUD(message: String, style: KMCustomAlertStyle = .blue) { _ = CustomAlertView.alertView(message: message, fromView: self.thumbnailView, withStyle: style) } private func _showPDFEditDetails() { var insertItem: KMToolbarItemView? for item in self.toolBar.toolBar.items { if item.itemIdentifier == KMToolbarPageEditInsetItemIdentifier { insertItem = item break } } if insertItem?.window == nil { return } let showConvertDetails = KMPageEditPopViewController.showPageEditDetails() if (showConvertDetails) { let item = insertItem let popViewController = KMPageEditPopViewController() self.popOver_ = NSPopover() self.popOver_?.contentViewController = popViewController self.popOver_?.animates = false self.popOver_?.setBackgroundColor(KMAppearance.Interactive.a0Color()) self.popOver_?.behavior = .transient // self.popOver.appearance = NSPopoverAppearanceMinimal; // self.popOver_?.appearance = .minimal self.popOver_?.contentSize = popViewController.view.frame.size self.popOver_?.show(relativeTo: item?.bounds ?? .zero, of: item!, preferredEdge: .maxY) } } // 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 KMMemberInfo.shared.isMemberAllFunction == false { KMMemberInfo.shared.advancedFunctionUsage() return } let pageCnt = self.pdfDocument?.pageCount ?? 0 if (self.thumbnailView.selectionIndexPaths.count == pageCnt) { self._progressHUD(message: NSLocalizedString("Can not delete all pages.", comment: "")) return } super.cutAction() } override func copyAction() { self.trackEvent_copy() super.copyAction() } override func deleteAction() { if KMMemberInfo.shared.isMemberAllFunction == false { let winC = KMProductCompareWC.shared if self.kEventTag == 1 { winC.kEventName = "Onbrd_EditPage_BuyNow" } else { winC.kEventName = "Reading_Delete_BuyNow" } KMMemberInfo.shared.advancedFunctionUsage() return } if self.isEmptySelection() { self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage)) return } let msg = String(format: NSLocalizedString("Are you sure to delete page %@ ?", comment: ""), KMTools.parseIndexSet(indexSet: self.indexpathsToIndexs(indexpaths: self.thumbnailView.selectionIndexPaths))) Task { let res = await KMAlertTool.runModel(message: msg, buttons: [NSLocalizedString("Delete", comment: ""), NSLocalizedString("Cancel", comment: "")]) if res != .alertFirstButtonReturn { return } self.trackEvent(type: .delete) super.deleteAction() self.toolBar.unSelectItem(for: KMToolbarPageEditDeleteItemIdentifier) } } override func deleteIndexPaths(indexpaths: Set) { guard let pageCount = self.thumbnailView.document?.pageCount else { KMPrint("pageCount invalid.") return } if (indexpaths.count == pageCount) { self._progressHUD(message: NSLocalizedString("Can not delete all pages.", comment: "")) return } self.dealPdfDocumentDidEditCallback(type: .delete) super.deleteIndexPaths(indexpaths: indexpaths) } override func leftRotateAction() { if KMMemberInfo.shared.isMemberAllFunction == false { KMMemberInfo.shared.advancedFunctionUsage() return } self.trackEvent(type: .leftRotate) super.leftRotateAction() } override func leftRotateIndexpaths(indexpaths: Set) { if (!self.indexpathsIsValid(indexpaths: indexpaths) || !self.canRotate()) { return } super.leftRotateIndexpaths(indexpaths: indexpaths) self.dealPdfDocumentDidEditCallback(type: .leftRotate) } override func rightRotateAction() { if KMMemberInfo.shared.isMemberAllFunction == false { let winC = KMProductCompareWC.shared if self.kEventTag == 1 { winC.kEventName = "Onbrd_EditPage_BuyNow" } else { winC.kEventName = "Reading_Rotate_BuyNow" } KMMemberInfo.shared.advancedFunctionUsage() return } if self.isEmptySelection() { self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage)) return } self.trackEvent(type: .rightRotate) super.rightRotateAction() } 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 KMMemberInfo.shared.isMemberAllFunction == false { KMMemberInfo.shared.advancedFunctionUsage() return } if (self.canPaste()) { super.pasteAction() self.dealPdfDocumentDidEditCallback(type: .paste) } else { if KMThumbnailManager.manager.copyPages.count <= 0 { self._progressHUD(message: KMLocalizedString("No copied page selected. Please select and copy a page first.")) } } } @objc func pasteActonForEmpty(_ sender: NSMenuItem) { guard let indexpaths = sender.representedObject as? IndexPath else { NSSound.beep() return } let idx = max(0, indexpaths.item-1) // self.pastePage(at: indexpaths.item) self.pastePage(at: idx) dealPdfDocumentDidEditCallback(type: .copy) } override func pastePage(at index: Int) { if KMMemberInfo.shared.isMemberAllFunction == false { KMMemberInfo.shared.advancedFunctionUsage() return } super.pastePage(at: index) } override func extractAction() { if KMMemberInfo.shared.isMemberAllFunction == false { let winC = KMProductCompareWC.shared if self.kEventTag == 1 { winC.kEventName = "Onbrd_EditPage_BuyNow" } else { winC.kEventName = "Reading_Extract_BuyNow" } KMMemberInfo.shared.advancedFunctionUsage() return } if self.isEmptySelection() { self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage)) return } self.trackEvent(type: .extract) super.extractAction() DispatchQueue.main.async { self.toolBar.unSelectItem(for: KMToolbarPageEditExtractItemIdentifier) } } override func replaceAction() { if KMMemberInfo.shared.isMemberAllFunction == false { let winC = KMProductCompareWC.shared if self.kEventTag == 1 { winC.kEventName = "Onbrd_EditPage_BuyNow" } else { winC.kEventName = "Reading_Replace_BuyNow" } KMMemberInfo.shared.advancedFunctionUsage() return } if self.isEmptySelection() { self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage)) return } self.trackEvent(type: .replace) super.replaceAction() DispatchQueue.main.async { self.toolBar.unSelectItem(for: KMToolbarPageEditReplaceItemIdentifier) } } override func replacePages(of targetIndexpaths: Set, with documents: [CPDFDocument]) { self.model.insertedDocumentSet.formUnion(documents) super.replacePages(of: targetIndexpaths, with: documents) } // 插入规则:选中后面插入[多选插入第后个后面];没有选中,插入阅读页当前页; override func getInsertIndex() -> Int { let ips = self.thumbnailView.selectionIndexPaths.sorted() if ips.isEmpty { return self.listView?.currentPageIndex ?? 0 } return ips.last?.item ?? 0 } override func splitAction() { if KMMemberInfo.shared.isMemberAllFunction == false { let winC = KMProductCompareWC.shared if self.kEventTag == 1 { winC.kEventName = "Onbrd_EditPage_BuyNow" } else { winC.kEventName = "Reading_Split_BuyNow" } KMMemberInfo.shared.advancedFunctionUsage() return } if self.isEmptySelection() { self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage)) return } guard let doc = self.pdfDocument else { NSSound.beep() return } let windowC = SplitWindowController(document: doc) windowC.fileAttribute?.pagesType = .custom let ips = self.indexpathsToIndexs(indexpaths: self.thumbnailView.selectionIndexPaths).sorted() let string = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: ips) windowC.fileAttribute?.pagesString = string self.km_beginSheet(windowC: windowC) } func splitMethod(windowC: KMPageEditSplitWindowController, model: KMPageEditSplitSettingModel, limit: Bool = false) { if KMMemberInfo.shared.isMemberAllFunction == false { KMMemberInfo.shared.advancedFunctionUsage() return } if self.isEmptySelection() { self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage)) return } self._splitMethod(windowC: windowC, model: model, limit: limit) } func splitMenuAction() { if KMMemberInfo.shared.isMemberAllFunction == false { let winC = KMProductCompareWC.shared if self.kEventTag == 1 { winC.kEventName = "Onbrd_EditPage_BuyNow" } else { winC.kEventName = "Reading_Split_BuyNow" } KMMemberInfo.shared.advancedFunctionUsage() return } let pdf = self.thumbnailView.document let pages = self.thumbnailView.selectionIndexPaths if (pages.isEmpty == false) { if self.fileAttri_ == nil { self.fileAttri_ = KMFileAttribute() self.fileAttri_?.password = self.thumbnailView.document?.password ?? "" self.fileAttri_?.filePath = self.thumbnailView.document?.documentURL.path ?? "" } let fileAttribute = self.fileAttri_ fileAttribute?.bAllPage = false fileAttribute?.pagesType = .custom fileAttribute?.pdfDocument = pdf fileAttribute?.pagesString = KMPageRangeTools.newParseSelectedIndexs(selectedIndex: self.indexpathsToIndexs(indexpaths: pages).sorted()) fileAttribute?.pageCnt = Int(self.thumbnailView.document?.pageCount ?? 0) let pages = fileAttribute?.fetchSelectPages() ?? [] if pages.isEmpty { KMAlertTool.runModelForMainThread(message: KMLocalizedString("Invalid page range or the page number is out of range. Please try again.", nil)) } else { let panel = NSOpenPanel() panel.canChooseFiles = false panel.canChooseDirectories = true panel.canCreateDirectories = true panel.beginSheetModal(for: self.view.window!) { result in if (result == .OK) { let outputURL = panel.urls.first! var tFolderPath = outputURL.path var index = 0 var folderName = self.pdfDocument?.documentURL.deletingPathExtension().lastPathComponent if folderName == nil { folderName = KMLocalizedString("Untitled", nil) } var folderPath = "\(tFolderPath)/\(folderName ?? "")" //创建目录 while (FileManager.default.fileExists(atPath: folderPath)) { index += 1 folderPath = "\(tFolderPath)/\(folderName ?? "")_\(index)" // folderPath = [tFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%ld",folderName,index]]; } tFolderPath = folderPath let result = try?FileManager.default.createDirectory(atPath: tFolderPath, withIntermediateDirectories: true) if (result == nil) { // if (![[NSFileManager defaultManager] createDirectoryAtPath:tFolderPath withIntermediateDirectories:YES attributes:nil error:nil]) { KMAlertTool.runModelForMainThread(message: KMLocalizedString("Failed to split!", nil)) return } let vc = KMProgressWindowController() NSApp.beginSheet(vc.window!, modalFor: self.view.window!, modalDelegate: nil, didEnd: nil, contextInfo: nil) DispatchQueue.global().async { // NSArray * successArray = [self.pdfDocument splitByFileWithPages:fileAttribute folerPath:tFolderPath fileName:folderName]; let successArray = self.pdfDocument?.splitByFileWithPages(fileAttribute!, folerPath: tFolderPath, fileName: folderName ?? "") ?? [] DispatchQueue.main.async { if successArray.count > 0 { let filePath = successArray.first ?? "" let workSpace = NSWorkspace.shared workSpace.activateFileViewerSelecting([URL(fileURLWithPath: filePath)]) } else { KMAlertTool.runModelForMainThread(message: KMLocalizedString("Failed to split!", nil)) } NSApp.endSheet(vc.window!) vc.close() } } } } } } else{ self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage)) } } override func reverseAction() { if KMMemberInfo.shared.isMemberAllFunction == false { let winC = KMProductCompareWC.shared winC.kEventName = "Reading_Reverse_BuyNow" KMMemberInfo.shared.advancedFunctionUsage() return } let cnt = self.thumbnailView.selectionIndexPaths.count if cnt < 2 { self._progressHUD(message: KMLocalizedString("No page selected. Please select at least two pages to organize.")) return } self.trackEvent(type: .reverse) 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.isEmptySelection() == false) { 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.count <= 0) { return } DispatchQueue.main.async { self.showProgressWindow(message: NSLocalizedString("Spliting...", comment: "")) self.progressC?.maxValue = Double(file_indexs.count) let _document = 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) 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) { if let doc = self.thumbnailView.document { KMThumbnailCache.shared.clearCache() // KMPageEditTools.reverse(doc, 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) // } // } var theIdxs = indexs var res = false for i in 0 ..< indexs.count { guard let first = theIdxs.first else { break } guard let last = theIdxs.last else { break } if first == last { break } res = self.pdfDocument?.exchangePage(at: UInt(first), withPageAt: UInt(last)) ?? false if res { theIdxs.remove(first) theIdxs.remove(last) } } if res { 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.pdfDocument?.page(at: UInt(index)))?.copy() as? CPDFPage if (newPage == nil) { continue } newPages.insert(newPage!, at: 0) self.pdfDocument?.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.pdfDocument?.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) } KMThumbnailCache.shared.clearCache() // 刷新UI self.refreshUI() if (reversed == false) { self.selectPages(indexs: selectIndexs) } } @objc private func new_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.pdfDocument?.page(at: UInt(index)))?.copy() as? CPDFPage if (newPage == nil) { continue } newPages.insert(newPage!, at: 0) // self.pdfDocument?.removePage(at: UInt(index)) if (index < toIndex) { /// 删除了插入位置前面的页面,需要改变 toIndex toIndexOffset += 1 } if (currentPage == nil) && (originalIndex == index) { currentPage = newPage } } var after = false if (indexs.last! < toIndex && dp == .on) { // 往后拖拽 toIndexOffset -= 1 after = true } let insertIndex = max(0, toIndex-toIndexOffset) var selectIndexs: IndexSet = [] for (index, page) in newPages.enumerated() { // self.pdfDocument?.insertPageObject(page, at: UInt(insertIndex+index)) selectIndexs.insert(insertIndex+index) if (currentPage?.pageIndex() == page.pageIndex()) { // self._listViewCurrentIndex = insertIndex+index } // self.pdfDocument?.movePage(at: UInt(index), withPageAt: UInt(insertIndex+index)) } var theToIndex = toIndex if indexs.count == 1 { theToIndex = insertIndex } if after { var offset = 0 for index in indexs { self.pdfDocument?.movePage(at: UInt(index-offset), withPageAt: UInt(theToIndex)) offset += 1 } } else { var offset = 0 for index in indexs.reversed() { self.pdfDocument?.movePage(at: UInt(index+offset), withPageAt: UInt(theToIndex)) offset += 1 } } // 新增 undo self.kmUndoManager?.registerUndo(withTarget: self) { target in target.clearSelectPages() target.new_dragPages_reversed(indexs, toIndex, newPages, dp: dp) } KMThumbnailCache.shared.clearCache() // 刷新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.pdfDocument?.removePage(at: UInt(index)) } // 再插入到对应的位置 for (index,value) in indexs.enumerated() { var page: CPDFPage? if (index < pages.count) { page = pages[index] } if (page != nil) { self.pdfDocument?.insertPageObject(page!, at: UInt(value)) } } // 新增 undo self.kmUndoManager?.registerUndo(withTarget: self) { target in target.dragPages(indexs, toIndex, dp: dp, reversed: true) } // 刷新UI self.refreshUI() } @objc private func new_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 } } var after = false if (indexs.last! < toIndex && dp == .on) { // 往后拖拽 toIndexOffset -= 1 after = true } 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.pdfDocument?.removePage(at: UInt(index)) } // 再插入到对应的位置 for (index,value) in indexs.enumerated() { var page: CPDFPage? if (index < pages.count) { page = pages[index] } if (page != nil) { // self.pdfDocument?.insertPageObject(page!, at: UInt(value)) } } if after { // var offset = 0 for (index,value) in indexs.enumerated() { let idx = datas[index] self.pdfDocument?.movePage(at: UInt(idx), withPageAt: UInt(value)) // offset += 1 } // for index in datas.reversed() { // self.pdfDocument?.movePage(at: UInt(index+offset), withPageAt: UInt(toIndex)) // offset += 1 // } } else { // var offset = 0 for (index,value) in indexs.reversed().enumerated() { let idx = datas.reversed()[index] self.pdfDocument?.movePage(at: UInt(idx), withPageAt: UInt(value)) } // for index in indexs { // self.pdfDocument?.movePage(at: UInt(index-offset), withPageAt: UInt(toIndex)) // offset += 1 // } } // 新增 undo self.kmUndoManager?.registerUndo(withTarget: self) { target in target.new_dragPages(indexs, toIndex, dp: dp, reversed: true) } KMThumbnailCache.shared.clearCache() // 刷新UI self.refreshUI() } // MARK: topBar 事件 @objc func zoomOutButtonAction(sender: NSButton?) { if (self.itemSize.width > self.defaultItemSize.width) { return } 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*2, height: self.defaultItemSize.height*2) } // self.toolBar.zoomInButton?.isEnabled = true // if (self.itemSize.width > self.defaultItemSize.width) { // sender?.isEnabled = false // } KMThumbnailCache.shared.clearCache() self.pageEditThumbnailView.zoomOut() if pageEditThumbnailView.canZoomIn() { zoomOutButton.isEnabled = true } else { zoomOutButton.isEnabled = false } if pageEditThumbnailView.canZoomOut() { zoomInButton.isEnabled = true } else { zoomInButton.isEnabled = false } } @objc func zoomInButtonAction(sender: NSButton?) { if (self.itemSize.width < self.defaultItemSize.width) { return } 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 // } KMThumbnailCache.shared.clearCache() self.pageEditThumbnailView.zoomIn() if pageEditThumbnailView.canZoomIn() { zoomOutButton.isEnabled = true } else { zoomOutButton.isEnabled = false } if pageEditThumbnailView.canZoomOut() { zoomInButton.isEnabled = true } else { zoomInButton.isEnabled = false } } // MARK: menu 菜单事件 override func menuNeedsUpdate(_ menu: NSMenu) { // let row = self.thumbnailView.collectionView.selectionIndexes // let point = self.thumbnailView.collectionView.convert(NSEvent.mouseLocation, to: nil) let point = self.view.window?.currentEvent?.locationInView(self.thumbnailView.collectionView) ?? .zero let indexpaths = self.thumbnailView.collectionView.indexPathForItem(at: point) menu.removeAllItems() if indexpaths == nil || indexpaths!.isEmpty { // 空白处点击 if KMThumbnailManager.manager.copyPages.isEmpty { // 不能粘贴 // if self.canPaste() { return } let item_ = menu.addItem(withTitle: NSLocalizedString("Paste", comment: ""), action: #selector(pasteActonForEmpty), target: self) // item_?.keyEquivalent = KMKeyEquivalent.paste let repObj = self.thumbnailView.collectionView.km_indexPathForItem(at: point, nearest: true) item_?.representedObject = repObj return } super.menuNeedsUpdate(menu) } @objc func item_insertCustomPage(sender: NSMenuItem?) { if KMMemberInfo.shared.isMemberAllFunction == false { let winC = KMProductCompareWC.shared if self.kEventTag == 1 { winC.kEventName = "Onbrd_EditPage_BuyNow" } else { winC.kEventName = "Reading_InsertBlankPage_BuyNow" } KMMemberInfo.shared.advancedFunctionUsage() return } guard let doc = self.pdfDocument else { NSSound.beep() return } let windowC = KMPDFEditInsertBlankPageWindow(document: doc) windowC.currentPage = self.getSelecteIndex() + 1 windowC.insertLocation = 3 windowC.callback = { [weak self] pdfDoc, _, pages, insertI in if pages != nil { // mm 单位的大小 guard let _winC = self?.kmCurrentWindowC as? KMPDFEditInsertBlankPageWindow else { self?.km_endSheet() return } var pageSize = _winC.pageSize let direction = windowC.pageRotation == 0 ? 0 : 1 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 } } /// 插入位置 let document = CPDFDocument() document?.insertPage(pageSize, at: 0) if let page: CPDFPage = (document?.page(at: 0)) { self?.insertPages(pages: [page], at: IndexSet(integer: insertI)) } let ips: Set = [IndexPath(item: insertI, section: 0)] self?.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically) } self?.km_endSheet() } self.km_beginSheet(windowC: windowC) } @objc func item_insertFromImage(sender: NSMenuItem?) { if KMMemberInfo.shared.isMemberAllFunction == false { let winC = KMProductCompareWC.shared if self.kEventTag == 1 { winC.kEventName = "Onbrd_EditPage_BuyNow" } else { winC.kEventName = "Reading_InsertImage_BuyNow" } KMMemberInfo.shared.advancedFunctionUsage() return } let openPanel = NSOpenPanel() openPanel.allowedFileTypes = KMImageToPDFMethod.supportedImageTypes() openPanel.allowsMultipleSelection = true openPanel.message = KMLocalizedString("Select images to create a new document. To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.", nil) openPanel.canChooseDirectories = false openPanel.allowsMultipleSelection = false openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in if result == NSApplication.ModalResponse.OK { if let fileURL = openPanel.urls.first { // self.choosePositionWindow {[weak self] index in // /// 插入位置 if NSDocument.isDamage(url: fileURL, needAlertIfDamage: true) { // 损坏图片 return } if let imag = NSImage(contentsOfFile: fileURL.path ) { let index = self.getInsertIndex() + 1 let document = CPDFDocument() _ = document?.km_insertPage(imag.size, withImage: fileURL.path , at: 0) if let page: CPDFPage = (document?.page(at: 0)) { self.insertPages(pages: [page], at: IndexSet(integer: index)) } let ips: Set = [IndexPath(item: index, section: 0)] self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically) } // } } } } } func choosePositionWindow(completion: @escaping KMIndexChooseBlock) -> Void { // guard let doc = self.pdfDocument else { // NSSound.beep() // return // } // let windowC = KMFileInsertPositionWindowController(document: doc) // windowC.currentPage = self.getSelecteIndex() + 1 // windowC.insertLocation = 3 // windowC.callback = { [weak self] pdfDoc, _, insertI in // if insertI >= 0 { // if (completion != nil) { // completion(insertI); // } // } // self?.km_endSheet() // } // self.km_beginSheet(windowC: windowC) } @objc func item_insertFromClipboard(sender: NSMenuItem?) { if KMMemberInfo.shared.isMemberAllFunction == false { let winC = KMProductCompareWC.shared if self.kEventTag == 1 { winC.kEventName = "Onbrd_EditPage_BuyNow" } else { winC.kEventName = "Reading_InsertClipboard_BuyNow" } KMMemberInfo.shared.advancedFunctionUsage() return } /// 插入位置 var error: NSError? guard let document: CPDFDocument = self.openDocumentWithImageFromPasteboard(NSPasteboard.general, error: &error) else { return } let index = self.getInsertIndex() + 1 if let page: CPDFPage = (document.page(at: 0)) { self.insertPages(pages: [page], at: IndexSet(integer: index)) } let ips: Set = [IndexPath(item: index, section: 0)] self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically) } @objc func item_insertFromScanner(sender: NSMenuItem?) { if KMMemberInfo.shared.isMemberAllFunction == false { let winC = KMProductCompareWC.shared if self.kEventTag == 1 { winC.kEventName = "Onbrd_EditPage_BuyNow" } else { winC.kEventName = "Reading_InsertSacnner_BuyNow" } KMMemberInfo.shared.advancedFunctionUsage() return } let vc = KMDeviceBrowserWindowController.shared vc.type = .scanner vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in /// 插入位置 if let imag = NSImage(contentsOfFile: url.path! ) { let index = (self?.getInsertIndex())! + 1 let document = CPDFDocument() _ = document?.km_insertPage(imag.size, withImage: url.path! , at: 0) if let page: CPDFPage = (document?.page(at: 0)) { self?.insertPages(pages: [page], at: IndexSet(integer: index)) } let ips: Set = [IndexPath(item: index, section: 0)] self?.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically) } vc.close() } vc.showWindow(NSApp.mainWindow) } func openDocumentWithImageFromPasteboard(_ pboard: NSPasteboard, error outError: AutoreleasingUnsafeMutablePointer?) -> CPDFDocument? { var document: CPDFDocument? = nil var data: Data? = nil if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.pdf.rawValue]) { data = pboard.data(forType: NSPasteboard.PasteboardType.pdf) } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.postScript.rawValue]) { data = pboard.data(forType: NSPasteboard.PasteboardType.postScript) } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.tiff.rawValue]) { data = convertTIFFDataToPDF(pboard.data(forType: NSPasteboard.PasteboardType.tiff) ?? Data()) } else { let images = pboard.readObjects(forClasses: [NSImage.self], options: [:]) let strings = pboard.readObjects(forClasses: [NSAttributedString.self], options: [:]) if images?.count ?? 0 > 0 { data = convertTIFFDataToPDF((images![0] as AnyObject).tiffRepresentation!) } else if strings?.count ?? 0 > 0 { data = KMOCTool.convertStringsToPDF(withString: strings ?? [""]) // convertStringsToPDF(strings!) } } if let data = data { document = CPDFDocument(data: data) } else if let outError = outError { outError.pointee = NSError(domain: "SKDocumentErrorDomain", code: 3, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Unable to load data from clipboard", comment: "Error description")]) } return document } func convertTIFFDataToPDF(_ tiffData: Data) -> Data? { guard let imsrc = CGImageSourceCreateWithData(tiffData as CFData, [kCGImageSourceTypeIdentifierHint: kUTTypeTIFF] as CFDictionary), CGImageSourceGetCount(imsrc) > 0, let cgImage = CGImageSourceCreateImageAtIndex(imsrc, 0, nil) else { return nil } let pdfData = NSMutableData(capacity: tiffData.count) let consumer = CGDataConsumer(data: pdfData! as CFMutableData)! var rect = CGRect(x: 0, y: 0, width: CGFloat(cgImage.width), height: CGFloat(cgImage.height)) let ctxt = CGContext(consumer: consumer, mediaBox: &rect, nil) ctxt!.beginPDFPage(nil) ctxt!.draw(cgImage, in: rect) ctxt!.endPDFPage() ctxt!.closePDF() return pdfData as? Data } func extractSelectPageItemAction() { if KMMemberInfo.shared.isMemberAllFunction == false { let winC = KMProductCompareWC.shared if self.kEventTag == 1 { winC.kEventName = "Onbrd_EditPage_BuyNow" } else { winC.kEventName = "Reading_Extract_BuyNow" } KMMemberInfo.shared.advancedFunctionUsage() return } let indexs = self.thumbnailView.selectionIndexPaths if indexs.isEmpty { self._progressHUD(message: KMLocalizedString(Self.kNoPagesSelectedTipMessage)) return } self.extractPages(indexpaths: indexs, oneDocumentPerPage: false) { result, params in } } // MARK: toolBar 菜单事件 @objc func reverseMenuAction(sender: AnyObject?) { let selectedIndexs = self.thumbnailView.selectionIndexPaths if (selectedIndexs.count < 2 ) { let alertView = CustomAlertView.alertView(message: NSLocalizedString("Please select at least two pages for editing first", comment: ""), fromView: self.thumbnailView, withStyle: .blue) alertView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor alertView?.layer?.cornerRadius = 4 return } self.reversePages(indexs: self.indexpathsToIndexs(indexpaths: selectedIndexs)) self.dealPdfDocumentDidEditCallback(type: .reverse) } override func addMenuItem(menu: NSMenu, item: KMPDFThumbViewMenu.Item) -> NSMenuItem? { var item_: NSMenuItem? if (item.sel == KMPDFThumbViewMenu.insertSelector) { item_ = menu.addItem(withTitle: NSLocalizedString("Blank Page", comment: ""), action: #selector(insertPageItemAction), target: self) } 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_ } // MARK: - Zoom Methods @IBAction func buttonClicked_Bigger(_ sender: AnyObject?) { // if (self.thumbnailView.thumbnailSize.width == 100.) { // self.thumbnailView.thumbnailSize = CGSizeMake(200, 200); // } else if (self.thumbnailView.thumbnailSize.width == 200.) { // self.thumbnailView.thumbnailSize = CGSizeMake(400, 400); // } self.zoomOutButtonAction(sender: sender as? NSButton) } @IBAction func buttonClicked_Smaller(_ sender: AnyObject?) { // if (self.thumbnailView.thumbnailSize.width == 400.) { // self.thumbnailView.thumbnailSize = CGSizeMake(200, 200); // } else if (self.thumbnailView.thumbnailSize.width == 200.) { // self.thumbnailView.thumbnailSize = CGSizeMake(100, 100); // } self.zoomInButtonAction(sender: sender as? NSButton) } override func mouseMoved(with event: NSEvent) { super.mouseMoved(with: event) self.view.window?.mouseMoved(with: event) } } 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) { guard let item = menu.parent else { NSSound.beep() return } 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) ?? false let url = URL(fileURLWithPath: folderPath) if ret { let success = pdfdocument?.write(to:url) ?? false // if success { // let workspace = NSWorkspace.shared // workspace.activateFileViewerSelecting([url]) // } } let represent = 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()) } override func menuItemAction_extract(_ sender: Any?) { self.extractSelectPageItemAction() } } extension KMPDFEditViewController { override func menuItemAction_print(_ sender: Any?) { if let item = sender as? NSMenuItem { self.printItemAction(menu: item) } } override func menuItemAction_showPageSize(_ sender: Any?) { if let item = sender as? NSMenuItem { self.showPageSizeItemAction(menu: item) } } override func menuItemAction_share(_ sender: Any?) { if let item = sender as? NSMenuItem { self.sharePageItemAction(menu: item) } } } // MARK: - KMSelectPopButtonDelegate extension KMPDFEditViewController { func km_comboBoxSelectionDidChange(_ obj: KMPageRange) { self.pageIsUpdate = false var indexpaths: Set = [] let type: KMPageRange? = obj let pageCnt = self.pdfDocument?.pageCount ?? 0 for i in 0 ..< pageCnt { 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)) } } if (type == .custom) { let windowC = KMPDFEditPageRangeWindowController() windowC.pdfDocument = self.pdfDocument windowC.pageSelectCallBack = { [weak self] pagesArray in var indexpaths = Set() for page in pagesArray { indexpaths.insert(IndexPath(item: page-1, section: 0)) } self?.km_endSheet() self?.selectPages(indexpaths: indexpaths) self?.thumbnailView.collectionView.scrollToItems(at: indexpaths, scrollPosition: .bottom) } self.km_beginSheet(windowC: windowC) } 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) ?? 0)) 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, canDragItemsAt indexPaths: Set, with event: NSEvent) -> Bool { return KMMemberInfo.shared.isMemberAllFunction } 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: { [weak self] documents in var insertIndex: Int = indexpath.item var pages: Array = [] var indexs = IndexSet() self?.model.insertedDocumentSet.formUnion(documents) for document in documents { for i in 0 ..< document.pageCount { if 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.new_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: 6, left: 40, bottom: 0, right: 40) } 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.km.dequeueReusableCell(for: indexpath) cellView.isShowPageSize = self.thumbnailView.isShowPageSize if let data = self.pdfDocument?.page(at: UInt(indexpath.item)) { cellView.setPage(page: data) } let bks = self.listView?.document.bookmarks() var hasBookmark = false for bk in bks ?? [] { if indexpath.item == bk.pageIndex { hasBookmark = true break } } cellView.bkIcon.isHidden = !hasBookmark cellView.doubleClickAction = { [weak 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 = { [weak 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)) let ips: Set = [IndexPath(item: index, section: 0)] self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically) 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, index: Int = 0) -> Void { if (type == .insert) { if index == 0 { 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 index == KMPageEditType.insert_blank_page || index == KMPageEditType.insert_custom_page { self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertBlankPage"], platform: .AppCenter) } else if index == KMPageEditType.insert_files { self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertPDF"], platform: .AppCenter) } else if index == KMPageEditType.insert_fromImage { self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertImage"], platform: .AppCenter) } else if index == KMPageEditType.insert_fromClipboard { self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertClipboard"], platform: .AppCenter) } else if index == KMPageEditType.insert_fromScanner { self.trackEvent(eventName: "SubTbr_PageEdit", params: ["SubTbr_Btn" : "Btn_SubTbr_PageEdit_InsertScanner"], platform: .AppCenter) } } 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) } }