123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230 |
- //
- // KMMainViewController+Action.swift
- // PDF Reader Pro
- //
- // Created by wanjun on 2022/12/15.
- //
- import Foundation
- import KMComponentLibrary
- extension KMNThumbnailBaseViewController {
-
- private func insertImageFilePath(imagePath:String,pageDex:Int)->Bool{
- var isSuccessFul:Bool = false
- if (FileManager.default.fileExists(atPath: imagePath)) {
- if let image = NSImage(contentsOfFile: imagePath) {
- isSuccessFul = showDocument?.km_insertPage(image.size, withImage: imagePath, at: UInt(pageDex)) == true
- }
- }
- return isSuccessFul
- }
-
- private func undoDeleteIndexPaths(deleteIndexPath: Set<IndexPath>) {
- var changeIndex:IndexSet = []
- var deletePages:[CPDFPage] = []
-
- let pageIndexs = KMNTools.indexpathsToIndexs(indexpaths: deleteIndexPath)
- for i in pageIndexs {
- if let page = showDocument?.page(at: UInt(i)) {
- deletePages.append(page)
- changeIndex.insert(i)
- }
- }
-
- showDocument?.removePage(at: pageIndexs)
- refreshDatas()
- collectionView.reloadData()
-
- currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
- self?.undoInsertPages(insertPages: deletePages, indexs: pageIndexs)
- }
- }
-
- private func undoInsertPages(insertPages:[CPDFPage],indexs: IndexSet) {
- var indexpaths = Set<IndexPath>()
- var count: Int = 0
- for index in indexs {
- guard let pageCount = showDocument?.pageCount, index <= pageCount, count < insertPages.count, index != -1 else {
- KMPrint("index invalid. index: \(index)")
- break
- }
-
- showDocument?.insertPageObject(insertPages[count], at: UInt(index))
- indexpaths.insert(IndexPath(item: index, section: 0))
- count += 1
- }
-
- refreshDatas()
- collectionView.reloadData()
- collectionView.scrollToItems(at: indexpaths, scrollPosition: .centeredVertically)
- collectionView.selectionIndexPaths = indexpaths
-
- currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
- self?.deletePages(indexpaths: indexpaths)
- }
- }
-
- private func undoReplacePages(of targetIndexpaths: Set<IndexPath>, with documents: [CPDFDocument],insertIndexSet:IndexSet,orgPages:[CPDFPage],orgIndexs: IndexSet) {
-
- showDocument?.removePage(at: insertIndexSet)
-
- var indexpaths = Set<IndexPath>()
- var count: Int = 0
- for index in orgIndexs {
- guard let pageCount = showDocument?.pageCount, index <= pageCount, count < orgPages.count, index != -1 else {
- KMPrint("index invalid. index: \(index)")
- break
- }
-
- showDocument?.insertPageObject(orgPages[count], at: UInt(index))
- indexpaths.insert(IndexPath(item: index, section: 0))
- count += 1
- }
-
- refreshDatas()
- collectionView.reloadData()
- collectionView.scrollToItems(at: indexpaths, scrollPosition: .centeredVertically)
- collectionView.selectionIndexPaths = indexpaths
-
- currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
- self?.replacePages(of: targetIndexpaths, with: documents)
- }
- }
-
- private func undoMovePages(movePages:[CPDFPage],destinationDex:Int,orgPages:[CPDFPage],orgPageDexs:[Int]) {
-
- for (i, page) in orgPages.enumerated() {
- let dragIndex = page.pageIndex()
- let index:UInt = UInt(orgPageDexs[i])
- showDocument?.movePage(at: dragIndex, withPageAt: index)
- }
-
- var indexpaths = Set<IndexPath>()
- for (_, page) in movePages.enumerated() {
- let index = page.pageIndex()
- indexpaths.insert(IndexPath(item: Int(index), section: 0))
- }
- refreshDatas()
- collectionView.reloadData()
- collectionView.scrollToItems(at: indexpaths, scrollPosition: .centeredVertically)
- collectionView.selectionIndexPaths = indexpaths
-
- currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
- self?.movePages(dragPages: movePages, destinationDex: destinationDex)
- }
- }
-
- func insertFileComplete(newSelectIndexs: Set<IndexPath>){
- refreshDatas()
- collectionView.reloadData()
-
- collectionView.selectionIndexPaths = newSelectIndexs
-
- if newSelectIndexs.isEmpty { return }
-
- let firstIndexPath = newSelectIndexs.first
- collectionView.scrollToItems(at: [firstIndexPath ?? IndexPath(item: 0, section: 0)], scrollPosition: .top)
-
- currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
- self?.undoDeleteIndexPaths(deleteIndexPath: newSelectIndexs)
- }
- }
-
- public func insertFormPages(insertPages: [CPDFPage],pageDex:Int) {
- let pageIndexDex: Int = pageDex
- var indexpaths = Set<IndexPath>()
-
- let page = insertPages.first
- if page?.document == showDocument {
- for (i, page) in insertPages.enumerated() {
- let isSuccessFul:Bool = showDocument?.insertPageObject(page, at: UInt(pageIndexDex+i)) == true
- if(isSuccessFul == true) {
- indexpaths.insert(IndexPath(item: pageIndexDex+i, section: 0))
- }
- }
- } else {
- if let pasteDocument = page?.document {
- var indexs: IndexSet = IndexSet()
- for (i, page) in insertPages.enumerated() {
- indexs.insert(Int(pasteDocument.index(for: page)))
- indexpaths.insert(IndexPath(item: pageIndexDex+i, section: 0))
- }
-
- let isSuccessFul:Bool = showDocument?.importPages(indexs, from: pasteDocument, at: UInt(pageIndexDex)) == true
- if(isSuccessFul == false){
- return
- }
- }
- }
-
- refreshDatas()
- collectionView.reloadData()
- collectionView.scrollToItems(at: indexpaths, scrollPosition: .centeredVertically)
- collectionView.selectionIndexPaths = indexpaths
-
- currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
- self?.undoDeleteIndexPaths(deleteIndexPath: indexpaths)
- }
- }
-
- public func insertBlankSize(pageSize: CGSize,pageDex:Int) {
- var indexpaths = Set<IndexPath>()
- let isSuccessFul = showDocument?.insertBlankPage(pageSize: pageSize, at: pageDex)
- if(isSuccessFul == true) {
- indexpaths.insert(IndexPath(item: pageDex, section: 0))
- }
-
- refreshDatas()
- collectionView.reloadData()
- collectionView.scrollToItems(at: indexpaths, scrollPosition: .centeredVertically)
- collectionView.selectionIndexPaths = indexpaths
-
- currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
- self?.undoDeleteIndexPaths(deleteIndexPath: indexpaths)
- }
- }
-
- public func rotatePages(indexPaths: Set<IndexPath>, rotateAngle: Int) {
- var tIndexPaths: Set<IndexPath> = []
- tIndexPaths = indexPaths
- for targetIndexPath in indexPaths {
- if let page = showDocument?.page(at: UInt(targetIndexPath.item)) {
- var pageRotate = page.rotation + rotateAngle
- if(pageRotate == -90) {
- pageRotate = 270
- } else if (pageRotate == 450) {
- pageRotate = 90
-
- }
- page.rotation = pageRotate
-
- let cellView = collectionView.item(at: targetIndexPath) as? KMNThumbnailCollectionViewItem
- if(cellView != nil) {
- cellView?.thumbnailMode.removeCacheImage()
- }
- }
- }
-
- collectionView.reloadItems(at: tIndexPaths) // Ensure correct type conversion
- collectionView.selectionIndexPaths = tIndexPaths
-
- currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
- self?.rotatePages(indexPaths: tIndexPaths, rotateAngle: -rotateAngle)
- }
- }
-
- public func reversePages(indexs: IndexSet) {
- if let doc = showDocument {
- var theIdxs = indexs
- var res = false
- for _ in 0 ..< indexs.count {
- guard let first = theIdxs.first else {
- break
- }
- guard let last = theIdxs.last else {
- break
- }
- if first == last {
- break
- }
- res = doc.exchangePage(at: UInt(first), withPageAt: UInt(last))
- if res {
- theIdxs.remove(first)
- theIdxs.remove(last)
-
- }
- }
- if res {
- refreshDatas()
- let selected_indexpaths = KMNTools.indexsToIndexpaths(indexs: indexs)
-
- collectionView.reloadItems(at: selected_indexpaths)
-
- collectionView.selectionIndexPaths = selected_indexpaths
-
- currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
- self?.reversePages(indexs: indexs)
- }
- }
- }
- }
-
- public func replacePages(of targetIndexpaths: Set<IndexPath>, with documents: [CPDFDocument]) {
- if (targetIndexpaths.count == 0 || documents.count == 0) {
- KMPrint("replace invalid.")
- return
- }
- var index = targetIndexpaths.sorted().first!.item
-
- var deletePages:[CPDFPage] = []
-
- let indexSet = KMNTools.indexpathsToIndexs(indexpaths: targetIndexpaths)
- for i in indexSet {
- if let page = showDocument?.page(at: UInt(i)) {
- deletePages.append(page)
- }
- }
- showDocument?.removePage(at: indexSet)
-
- var tIndexPaths: Set<IndexPath> = []
- for document in documents {
- for i in 0 ..< document.pageCount {
- if let page = document.page(at: i) {
- showDocument?.insertPageObject(page, at: UInt(index))
- tIndexPaths.insert(IndexPath(item: index, section: 0))
- index += 1
- }
- }
- thumbnailBaseViewDelegate?.insertPDFThumbnailViewControlle?(pageEditVC: self, pdfDocment: document)
- }
-
- refreshDatas()
- collectionView.reloadData()
- collectionView.selectionIndexPaths = tIndexPaths
-
- currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
- self?.undoReplacePages(of: targetIndexpaths, with: documents, insertIndexSet: KMNTools.indexpathsToIndexs(indexpaths: tIndexPaths), orgPages: deletePages,orgIndexs: indexSet)
- }
- }
-
- public func deletePages(indexpaths:Set<IndexPath>) {
- var changeIndex:IndexSet = []
- var deletePages:[CPDFPage] = []
-
- let pageIndexs = KMNTools.indexpathsToIndexs(indexpaths: indexpaths)
- for i in pageIndexs {
- if let page = showDocument?.page(at: UInt(i)) {
- deletePages.append(page)
- changeIndex.insert(i)
- }
- }
- showDocument?.removePage(at: changeIndex)
- collectionView.selectionIndexPaths = []
- refreshDatas()
- collectionView.reloadData()
- currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
- self?.undoInsertPages(insertPages: deletePages, indexs: pageIndexs)
- }
- }
-
- public func movePages(dragPages:[CPDFPage],destinationDex:Int) {
- guard !dragPages.isEmpty else { return }
-
- var destinationIndex = destinationDex
- let maxDragPageIndex = dragPages.last?.pageIndex() ?? 0
- let minDragPageIndex = dragPages.first?.pageIndex() ?? 0
-
- let rangeStart = min(Int(minDragPageIndex), destinationIndex)
- let rangeEnd = max(Int(maxDragPageIndex), destinationIndex)
-
- var changePages:[CPDFPage] = []
- var changePageIndexs:[Int] = []
- for index in (rangeStart...rangeEnd) {
- if let changePage = showDocument?.page(at: UInt(index)) {
- changePages.append(changePage)
- changePageIndexs.append(index)
- }
- }
- for dragPage in dragPages {
- let dragIndex = dragPage.pageIndex()
- if destinationIndex > dragIndex {
- destinationIndex -= 1
- showDocument?.movePage(at: dragIndex, withPageAt: UInt(destinationIndex))
- } else {
- showDocument?.movePage(at: dragIndex, withPageAt: UInt(destinationIndex))
- }
- destinationIndex += 1
- }
-
- var selectIndexPaths: Set<IndexPath> = []
-
- for dragPage in dragPages {
- let dragIndex = dragPage.pageIndex()
- selectIndexPaths.insert(IndexPath(item: Int(dragIndex), section: 0))
- }
-
- refreshDatas()
- collectionView.reloadData()
- collectionView.selectionIndexPaths = selectIndexPaths
- if selectIndexPaths.isEmpty { return }
- let firstIndexPath = selectIndexPaths.first
- collectionView.scrollToItems(at: [firstIndexPath ?? IndexPath(item: 0, section: 0)], scrollPosition: .top)
-
- currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
- self?.undoMovePages(movePages: dragPages, destinationDex: destinationDex, orgPages: changePages, orgPageDexs: changePageIndexs)
- }
- }
-
- public func insertFromFilePath(fileNames:[String],formDex:Int,indexDex:UInt,selectIndexs:Set<IndexPath>,completionBlock:@escaping (Set<IndexPath>)->Void)-> Void {
- let path = fileNames[formDex]
- var insertDex = indexDex
- var tSelectIndex = selectIndexs
-
- let pathExtension = URL(fileURLWithPath: path).pathExtension.lowercased()
- if pathExtension == "pdf", let pdf = CPDFDocument(url: URL(fileURLWithPath: path)) {
- if pdf.isLocked {
- self.view.window?.windowController?.showCheckPassword(url: pdf.documentURL, type: .owner) { success, resultPassword in
- if (resultPassword.isEmpty == false) {
- pdf.unlock(withPassword: resultPassword)
-
- for i in 0 ..< pdf.pageCount {
- let insertPage = pdf.page(at: i)
- self.showDocument?.insertPageObject(insertPage, at: insertDex)
- tSelectIndex.insert(IndexPath(item: Int(insertDex), section:0))
- insertDex += 1
- }
-
- var tFormDex = formDex
- tFormDex += 1
- self.thumbnailBaseViewDelegate?.insertPDFThumbnailViewControlle?(pageEditVC: self, pdfDocment: pdf)
- if(tFormDex < fileNames.count) {
- return self.insertFromFilePath(fileNames: fileNames, formDex: tFormDex, indexDex: indexDex, selectIndexs: tSelectIndex,completionBlock: completionBlock)
- } else {
- self.insertFileComplete(newSelectIndexs: tSelectIndex)
- return completionBlock(tSelectIndex)
- }
- }
- }
- } else {
- for i in 0 ..< pdf.pageCount {
- let insertPage = pdf.page(at: i)
- showDocument?.insertPageObject(insertPage ?? CPDFPage(), at: insertDex)
- tSelectIndex.insert(IndexPath(item: Int(insertDex), section:0))
- insertDex += 1
- }
- var tFormDex = formDex
- tFormDex += 1
- thumbnailBaseViewDelegate?.insertPDFThumbnailViewControlle?(pageEditVC: self, pdfDocment: pdf)
- if(tFormDex < fileNames.count) {
- return insertFromFilePath(fileNames: fileNames, formDex: tFormDex, indexDex: indexDex, selectIndexs: tSelectIndex,completionBlock: completionBlock)
- } else {
- insertFileComplete(newSelectIndexs: tSelectIndex)
- return completionBlock(tSelectIndex)
- }
-
- }
- } else if supportDragFileTypes().contains(pathExtension) {
- if KMConvertPDFManager.supportImages().contains(pathExtension) {
- let isSueccessFul = insertImageFilePath(imagePath: path, pageDex: Int(indexDex))
- if(isSueccessFul) {
- tSelectIndex.insert(IndexPath(item: Int(insertDex), section:0))
- insertDex += 1
- }
-
- var tFormDex = formDex
- tFormDex += 1
- if(tFormDex < fileNames.count) {
- return insertFromFilePath(fileNames: fileNames, formDex: tFormDex, indexDex: indexDex, selectIndexs: tSelectIndex,completionBlock: completionBlock)
- } else {
- insertFileComplete(newSelectIndexs: tSelectIndex)
- return completionBlock(tSelectIndex)
- }
-
- } else {
- KMNConvertTool.convertOffice(filePath: path) { convertPDFPath in
- if (convertPDFPath != nil) {
- let pathExtension = URL(fileURLWithPath: convertPDFPath!).pathExtension.lowercased()
- if pathExtension == "pdf", let pdf = CPDFDocument(url: URL(fileURLWithPath: convertPDFPath!)) {
- for i in 0 ..< pdf.pageCount {
- let insertPage = pdf.page(at: i)
- self.showDocument?.insertPageObject(insertPage, at: insertDex)
- tSelectIndex.insert(IndexPath(item: Int(insertDex), section:0))
- insertDex += 1
- }
- self.thumbnailBaseViewDelegate?.insertPDFThumbnailViewControlle?(pageEditVC: self, pdfDocment: pdf)
-
- var tFormDex = formDex
- tFormDex += 1
- if(tFormDex < fileNames.count) {
- return self.insertFromFilePath(fileNames: fileNames, formDex: tFormDex, indexDex: indexDex, selectIndexs: tSelectIndex,completionBlock: completionBlock)
- } else {
- self.insertFileComplete(newSelectIndexs: tSelectIndex)
- return completionBlock(tSelectIndex)
- }
-
- }
- }
- }
- }
- }
- }
-
- public func extractPages(indexpaths: Set<IndexPath>, oneDocumentPerPage: Bool, callback: @escaping KMResultBlock) {
- let pageIndexs = KMNTools.indexpathsToIndexs(indexpaths: indexpaths)
- let oneDocument = !oneDocumentPerPage
- let document = self.showDocument!
- /// 提取的页面
- var extractPages: Array<CPDFPage> = []
- for i in pageIndexs {
- extractPages.append(document.page(at: UInt(i)))
- }
-
- if (oneDocument) { /// 提取为一个文档
- var fileName = document.documentURL.deletingPathExtension().lastPathComponent
- fileName.append(" pages ")
- fileName.append(KMNTools.newParseSelectedIndexs(selectedIndex: pageIndexs.sorted()))
- fileName.append(".pdf")
- NSPanel.savePanel(self.view.window!, true) { panel in
- panel.nameFieldStringValue = fileName
- } completion: { response, url, isOpen in
- if (response != .OK) {
- callback(.cancel)
- return
- }
-
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
- DispatchQueue.global().async {
- var success = false
- let pdf = CPDFDocument.init()
- success = pdf!.extractAsOneDocument(withPages: extractPages, savePath: url!.path)
- DispatchQueue.main.async {
- if (success == false) {
- callback(.failure)
- return
- }
-
- if (isOpen == false) {
- NSWorkspace.shared.activateFileViewerSelecting([url!])
- } else {
- NSDocumentController.shared.km_safe_openDocument(withContentsOf: url!, display: true) { _, _, _ in
- }
- }
- callback(.success, [url!])
- }
- }
- }
- }
- } else {
- let panel = NSOpenPanel()
- panel.canChooseFiles = false
- panel.canChooseDirectories = true
- panel.canCreateDirectories = true
- panel.allowsMultipleSelection = false
- panel.beginSheetModal(for: self.view.window!) { response in
- if response != .OK {
- callback(.cancel)
- return
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
- let outputURL = panel.url
- DispatchQueue.global().async {
- let folderName = String((document.documentURL.lastPathComponent.split(separator: ".")[0])) + "_extract"
-
- var filePath = URL(fileURLWithPath: outputURL!.path).appendingPathComponent(folderName).path
- var i = 1
- let testFilePath = filePath
- while FileManager.default.fileExists(atPath: filePath) {
- filePath = testFilePath + "\(i)"
- i += 1
- }
-
- try? FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
-
- var successArray: [URL]?
- successArray = document.extractPerPageDocument(withPages: extractPages, folerPath: filePath)
-
- DispatchQueue.main.async {
- if successArray!.count == 0 {
- callback(.failure)
- return
- }
- NSWorkspace.shared.activateFileViewerSelecting(successArray!)
- callback(.success, successArray ?? NSURL())
- }
- }
- }
- }
- }
- }
-
- // MARK: - MenuItem
- @objc public func copyMenuItemAciton() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- winC?.showWindow(nil)
- return
- }
- KMNThumbnailManager.manager.copyPages = []
-
- let indexpaths = collectionView.selectionIndexPaths
- for indexpath in indexpaths.sorted() {
- guard let page = showDocument?.page(at: UInt(indexpath.item)).copy() as? CPDFPage else {
- continue
- }
-
- KMNThumbnailManager.manager.copyDocument.append(showDocument ?? CPDFDocument())
- KMNThumbnailManager.manager.copyPages.append(page)
- }
- }
-
- @objc public func pastMenuItemAciton(menuitemProperty:ComponentMenuitemProperty) {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- winC?.showWindow(nil)
- return
- }
-
- var pastIndex = 1
- let point = menuitemProperty.representedObject as? NSPoint
-
- if(point != nil) {
- let pointInCollectionView = collectionView.convert(point!, from: nil)
-
- let visibleItems = collectionView.visibleItems()
- let mouseX = pointInCollectionView.x
- let mouseY = pointInCollectionView.y
-
- // 获取当前行的所有 cell
- let currentRowItems = visibleItems.filter { item in
- if let indexPath = collectionView.indexPath(for: item),
- let cellAttributes = collectionView.layoutAttributesForItem(at: indexPath) {
- return cellAttributes.frame.minY <= mouseY && cellAttributes.frame.maxY >= mouseY
- }
- return false
- }
- if(mouseX < 24) { //点击区域在最左边
- // 找到最近右边的 cell
- let rightMostCell = currentRowItems.compactMap { collectionView.indexPath(for: $0) }
- .filter { indexPath in
- let cellRect = collectionView.layoutAttributesForItem(at: indexPath)?.frame
- return cellRect?.minX ?? 0 > mouseX // 只选择右侧的 cell
- }
- .sorted { ($0.item < $1.item) } // 按 item 的顺序排列
- .first // 选择第一个,即最右边的 cell
- pastIndex = (rightMostCell?.item ?? (Int(showDocument?.pageCount ?? 1)))
- } else {
- // 找到最近右边的 cell
- let leftMostCell = currentRowItems.compactMap { collectionView.indexPath(for: $0) }
- .filter { indexPath in
- let cellRect = collectionView.layoutAttributesForItem(at: indexPath)?.frame
- return cellRect?.maxX ?? 0 < mouseX // 只选择左侧的 cell
- }
- .sorted { $0.item > $1.item } // 按 item 的逆序排列,以选择最近的左侧 cell
- .first // 选择第一个,即最近的左边的 cell
-
- pastIndex = (leftMostCell?.item ?? (Int(showDocument?.pageCount ?? 1)) - 1) + 1
- }
- } else {
- let selectedIndexPaths = collectionView.selectionIndexPaths
- if(selectedIndexPaths.count > 0) {
- let maxmumIndexPath = selectedIndexPaths.max(by: { $0 < $1 })
- pastIndex = ((maxmumIndexPath?.item ?? 0) + 1)
- } else {
- pastIndex = Int(showDocument?.pageCount ?? 0)
- }
- }
- let copyPages = KMNThumbnailManager.manager.copyPages
-
- insertFormPages(insertPages: copyPages, pageDex: pastIndex)
- }
-
- @objc public func cutMenuItemAciton() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- winC?.showWindow(nil)
- return
- }
-
- let indexpaths = collectionView.selectionIndexPaths
- for indexpath in indexpaths.sorted() {
- guard let page = showDocument?.page(at: UInt(indexpath.item)).copy() as? CPDFPage else {
- continue
- }
-
- KMNThumbnailManager.manager.copyDocument.append(showDocument ?? CPDFDocument())
- KMNThumbnailManager.manager.copyPages.append(page)
- }
-
- deletePages(indexpaths: indexpaths)
- }
-
- @objc public func deleteMenuItemAciton() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- winC?.showWindow(nil)
- return
- }
- let indexpaths = collectionView.selectionIndexPaths
- deletePages(indexpaths: indexpaths)
- }
-
- @objc func sharePageItemAction(menuItem:NSMenuItem) {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- let winC = KMPurchaseCompareWindowController.sharedInstance()
- winC?.showWindow(nil)
- return
- }
- let indexpaths = collectionView.selectionIndexPaths
-
- let doucument = showDocument
- 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(KMNTools.indexpathsToIndexs(indexpaths: indexpaths), from: doucument, at: 0) ?? false
- let url = URL(fileURLWithPath: folderPath)
- if ret {
- let success = pdfdocument?.write(toFile: folderPath)
- let represent = menuItem.representedObject as? NSSharingService
- represent?.perform(withItems: [url])
- }
- }
-
- @objc public func displayPageSizeAction() {
- let indexpaths = collectionView.selectionIndexPaths
- isShowPageSize = !isShowPageSize
- collectionView.selectionIndexPaths = indexpaths
- }
-
- private func insertFilePath(filePath:String,pdfPassword:String?) {
- let selectedIndexPaths = collectionView.selectionIndexPaths
-
- let insertPDF = KMNPDFInsertPDFWindowController(showDocument, filePath: filePath, password: pdfPassword, selectionIndexPaths: selectedIndexPaths)
- insertPDF.pdfCallback = { [weak self] fileAttribute, insertIdx in
- let doc = fileAttribute.pdfDocument
-
- var insertPages: [CPDFPage] = []
-
- for number in fileAttribute.fetchSelectPages() {
- if let page = doc?.page(at: UInt(number-1)) {
- insertPages.append(page)
- }
- }
- self?.thumbnailBaseViewDelegate?.insertPDFThumbnailViewControlle?(pageEditVC: self, pdfDocment: doc)
-
- self?.insertFormPages(insertPages: insertPages, pageDex: insertIdx)
- }
- insertPDF.fileCallback = { [weak self] filePath, insertIdx in
- self?.insertFromFilePath(fileNames: [filePath], formDex: 0, indexDex: UInt(insertIdx), selectIndexs: [], completionBlock: { newSelectIndexs in
- })
- }
-
- insertPDF.own_beginSheetModal(for: self.view.window, completionHandler: nil)
- }
-
- // MARK: - public
- func updateThumnailItem(updateIndexPaths: Set<IndexPath>,isSelect:Bool) {
-
- for targetIndexPath in updateIndexPaths {
- let cellView = collectionView.item(at: targetIndexPath) as? KMNThumbnailCollectionViewItem
- if(cellView != nil) {
- cellView?.thumbnailMode.removeCacheImage()
- }
- }
-
- collectionView.reloadItems(at: updateIndexPaths)
- if(isSelect) {
- if updateIndexPaths.isEmpty { return }
- let firstIndexPath = updateIndexPaths.first
- collectionView.scrollToItems(at: [firstIndexPath ?? IndexPath(item: 0, section: 0)], scrollPosition: .top)
-
- collectionView.selectionIndexPaths = updateIndexPaths
- }
- }
-
- func updateAllThumnailItems() {
- KMNThumbnailManager.clearCacheFilePath(filePath: showDocument?.documentURL.path ?? "")
-
- collectionView.reloadData()
- }
-
- @objc public func insertFromPDFAction() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
- return
- }
-
- let openPanel = NSOpenPanel()
- openPanel.allowedFileTypes = supportDragFileTypes()
- openPanel.allowsMultipleSelection = false
- openPanel.beginSheetModal(for: NSWindow.currentWindow()) {[weak self] result in
- if result == NSApplication.ModalResponse.OK {
- let fileURL = openPanel.url
- if(fileURL?.pathExtension == "pdf") {
- let pdfDoc = CPDFDocument(url: fileURL)
- if let data = pdfDoc?.isLocked, data {
- DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
- self?.view.window?.windowController?.showCheckPassword(url: fileURL ?? NSURL.fileURL(withPath: ""), type: .owner) { result, pwd in
- if (pwd.isEmpty == false) {
- self?.insertFilePath(filePath: fileURL?.path ?? "", pdfPassword: pwd)
- }
- }
- }
- } else {
- self?.insertFilePath(filePath: fileURL?.path ?? "", pdfPassword: nil)
- }
- } else {
- self?.insertFilePath(filePath: fileURL?.path ?? "", pdfPassword: nil)
- }
- }
- }
- }
-
- @objc public func insertFromBlankAction() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
- return
- }
-
- let selectedIndexPaths = collectionView.selectionIndexPaths
-
- let insertPDF = KMNPDFInsertBlankWindowController(self.showDocument, selectionIndexPaths: selectedIndexPaths)
- insertPDF.callback = { [weak self] pageSize, insertIdx in
- self?.insertBlankSize(pageSize: pageSize, pageDex: insertIdx)
- }
- insertPDF.own_beginSheetModal(for: self.view.window, completionHandler: nil)
- }
-
- public func insertFromClipboardAction() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
- return
- }
- let selectedIndexPaths = collectionView.selectionIndexPaths
- var maxmumIndex = 1
- if(selectedIndexPaths.count > 0) {
- let maxmumIndexPath = selectedIndexPaths.max(by: { $0 < $1 })
- maxmumIndex = (maxmumIndexPath?.item ?? 0) + 1
- }
-
- var error: NSError?
- guard let document: CPDFDocument = KMNConvertTool.openDocumentWithImageFromPasteboard(NSPasteboard.general, error: &error) else {
- return
- }
- if let page: CPDFPage = (document.page(at: 0)) {
- insertFormPages(insertPages: [page], pageDex: maxmumIndex)
- }
-
- self.thumbnailBaseViewDelegate?.insertPDFThumbnailViewControlle?(pageEditVC: self, pdfDocment: document)
- let ips: Set<IndexPath> = [IndexPath(item: maxmumIndex, section: 0)]
-
- refreshDatas()
- collectionView.selectionIndexPaths = ips
- collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
- }
-
- public func insertFromScannerAction() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
- return
- }
-
- let selectedIndexPaths = collectionView.selectionIndexPaths
- let maxmumIndexPath = selectedIndexPaths.max(by: { $0 < $1 })
-
- let vc = KMDeviceBrowserWindowController.shared
- vc.type = .scanner
- vc.importScannerFileCallback = { [weak self] (url: NSURL) -> Void in
- if let imag = NSImage(contentsOfFile: url.path! ) {
- let index = (maxmumIndexPath?.item ?? 0) + 1
- _ = self?.showDocument?.km_insertPage(imag.size, withImage: url.path! , at:UInt(index))
-
- self?.refreshDatas()
-
- let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
-
- self?.collectionView.selectionIndexPaths = ips
- self?.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
- }
- }
- vc.showWindow(nil)
- vc.window?.center()
- }
-
-
- public func canUndo()->Bool {
- return true
- }
-
- public func undoPDFAction() {
- currentUndoManager?.undo()
- }
-
- public func canRodo()->Bool {
- return true
- }
-
- public func redoPDFAction() {
- currentUndoManager?.redo()
- }
-
- @objc public func extractPDFAction() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
- return
- }
-
- let selectedIndexPaths = collectionView.selectionIndexPaths
-
- if selectedIndexPaths.count < 1 {
- _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Please select one or more pages first to organize."), type: .info, fromView: self.view, point:CGPointMake(self.view.frame.origin.x + self.view.frame.size.width/2, self.view.bounds.size.height - 30))
- return
- }
-
- let extractPDF = KMNExtractPDFWindowController(self.showDocument, selectionIndexPaths: collectionView.selectionIndexPaths)
- extractPDF.callback = { [weak self] oneDocumentPerPage, isDeletePage in
- extractPDF.own_closeEndSheet()
- if let _ = self?.showDocument {
- self?.extractPages(indexpaths: selectedIndexPaths, oneDocumentPerPage: oneDocumentPerPage, callback: { [weak self] result, params in
- if (result == .failure || result == .cancel) {
- return
- }
- if (isDeletePage) {
- self?.deletePages(indexpaths: selectedIndexPaths)
- }
- })
- }
- }
- extractPDF.own_beginSheetModal(for: self.view.window, completionHandler: nil)
- }
-
- @objc public func replacePDFAction() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
- return
- }
-
- let selectedIndexPaths = collectionView.selectionIndexPaths
-
- if selectedIndexPaths.count < 1 {
- _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Please select one or more pages first to organize."), type: .info, fromView: self.view, point:CGPointMake(self.view.frame.origin.x + self.view.frame.size.width/2, self.view.bounds.size.height - 30))
- return
- }
-
- self.km_open_file_multi { [unowned self] index, params in
- if (self.fetchProgressBlockParamsIsPasswordFile(params: params)) { // 加密文档进度回调
- return
- }
-
- let tFileUrl = self.fetchProgressBlockParamsForFileUrl(params: params)
- let pdfExtensions = KMNConvertTool.supportPDFFileType()
- if let exn = tFileUrl?.pathExtension, pdfExtensions.contains(exn) {
- if (tFileUrl!.path.isPDFValid() == false) {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = KMLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.")
- alert.runModal()
- }
- }
- } completionBlock: { [unowned self] documents in
- self.replacePages(of: selectedIndexPaths, with: documents)
- }
- }
-
- public func splitPDFAction() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
- return
- }
-
- let selectedIndexPaths = collectionView.selectionIndexPaths
-
- if collectionView.selectionIndexPaths.count < 1 {
- _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Please select one or more pages first to organize."), type: .info, fromView: self.view, point:CGPointMake(self.view.bounds.origin.x + self.view.bounds.size.width/2, self.view.bounds.size.height - 30))
- return
- }
-
- let splitPDF = KMNSplitPDFWindowController(self.showDocument,selectionIndexPaths: selectedIndexPaths)
- splitPDF.own_beginSheetModal(for: self.view.window, completionHandler: nil)
- }
-
- public func reversePDFAction() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
- return
- }
- let selectedIndexPaths = collectionView.selectionIndexPaths
-
- if selectedIndexPaths.count < 2 {
- _ = KMNCustomAlertView.alertView(message: KMLocalizedString("No page selected. Please select at least two pages to organize."), type: .info, fromView: self.view, point:CGPointMake(self.view.frame.origin.x + self.view.frame.size.width/2, self.view.bounds.size.height - 30))
- return
- }
- reversePages(indexs:KMNTools.indexpathsToIndexs(indexpaths: selectedIndexPaths))
- }
-
- @objc public func rotatePageLeftAction() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
- return
- }
-
- if collectionView.selectionIndexPaths.count < 1 {
- _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Please select one or more pages first to organize."), type: .info, fromView: self.view, point:CGPointMake(self.view.frame.origin.x + self.view.frame.size.width/2, self.view.bounds.size.height - 30))
- return
- }
- rotatePages(indexPaths: collectionView.selectionIndexPaths, rotateAngle: -90)
- }
-
- @objc public func rotatePageRightAction() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
- return
- }
-
- if collectionView.selectionIndexPaths.count < 1 {
- _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Please select one or more pages first to organize."), type: .info, fromView: self.view, point:CGPointMake(self.view.frame.origin.x + self.view.frame.size.width/2, self.view.bounds.size.height - 30))
- return
- }
- rotatePages(indexPaths: collectionView.selectionIndexPaths, rotateAngle: 90)
- }
-
- public func deletePageAction() {
- if IAPProductsManager.default().isAvailableAllFunction() == false {
- KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
- return
- }
-
- let selectedIndexPaths = collectionView.selectionIndexPaths
-
- if selectedIndexPaths.count < 1 {
- _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Please select one or more pages first to organize."), type: .info, fromView: self.view, point:CGPointMake(self.view.frame.origin.x + self.view.frame.size.width/2, self.view.bounds.size.height - 30))
- return
- } else if selectedIndexPaths.count == (showDocument?.pageCount ?? 0) {
- _ = KMNCustomAlertView.alertView(message: KMLocalizedString("Can not delete all pages."), type: .info, fromView: self.view, point:CGPointMake(self.view.frame.origin.x + self.view.frame.size.width/2, self.view.bounds.size.height - 30))
- return
-
- }
-
- deletePages(indexpaths: selectedIndexPaths)
- }
-
- // MARK: - private
- private func fetchProgressBlockParamsIsPasswordFile(params: Any...) -> Bool {
- if (params.count <= 2) {
- return false
- }
- return true
- }
-
- private func fetchProgressBlockParamsForFileUrl(params: Any...) -> URL? {
- if (params.count < 2) {
- return nil
- }
- return params[1] as? URL
- }
-
- private func km_open_file_multi(type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
- NSPanel.km_open_multi_success(self.view.window!) { panel in
- var array: [String] = []
- for fileType in KMConvertPDFManager.supportFileType() {
- array.append(fileType)
- }
- panel.allowedFileTypes = KMNConvertTool.pdfExtensions + array
- } completion: { urls in
- self.km_add_file_multi(fileUrls: urls, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
- }
- }
-
- private func km_add_file_multi(fileUrls: [URL] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
- var pdfUrls: [URL] = []
- var imageUrls: [URL] = []
- var officeUrls: [URL] = []
- for url in fileUrls {
- let type = url.pathExtension.lowercased()
- if (KMNConvertTool.isPDFType(type)) {
- pdfUrls.append(url)
- }
- if (KMNConvertTool.isImageType(type)) {
- imageUrls.append(url)
- }
- if (KMNConvertTool.isOfficeType(type)) {
- officeUrls.append(url)
- }
- }
-
- if (officeUrls.count == 0) {
- self.km_add_pdf_multi(fileUrls: pdfUrls, type: type, progressBlock: progressBlock) { documents in
- var index = documents.count
- var _documents: [CPDFDocument] = []
- for imageUrl in imageUrls {
- index += 1
- let document = CPDFDocument()
- let image = NSImage(contentsOfFile: imageUrl.path)
- let _ = document?.km_insertPage(image?.size ?? .zero, withImage: imageUrl.path, at: 0)
- _documents.append(document!)
-
- if let _callback = progressBlock { // 回调进度
- _callback(index, document as Any, imageUrl)
- }
- }
-
- completionBlock(documents + _documents)
- }
- return
- }
-
- self.km_add_office_multi(fileUrls: officeUrls) { [unowned self] fileUrlStrings in
- var officeDocuments: [CPDFDocument] = []
- var index = 0
- for fileUrlString in fileUrlStrings {
- index += 1
- let document = CPDFDocument(url: URL(fileURLWithPath: fileUrlString))
- officeDocuments.append(document!)
-
- if let _callback = progressBlock { // 回调进度
- _callback(index, document as Any, URL(fileURLWithPath: fileUrlString))
- }
- }
-
- self.km_add_pdf_multi(fileUrls: pdfUrls) { documents in
- var index = documents.count + officeDocuments.count
- var _documents: [CPDFDocument] = []
- for imageUrl in imageUrls {
- index += 1
- let document = CPDFDocument()
- let image = NSImage(contentsOfFile: imageUrl.path)
- let _ = document?.km_insertPage(image!.size, withImage: imageUrl.path, at: 0)
- _documents.append(document!)
-
- if let _callback = progressBlock { // 回调进度
- _callback(index, document as Any, imageUrl)
- }
- }
-
- completionBlock(officeDocuments + documents + _documents)
- }
- }
- }
-
- private func km_add_pdf_multi(fileUrls: [URL] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
- var results: [CPDFDocument] = []
-
- self.lockedFiles.removeAll()
- var index = 0
- for url in fileUrls {
- let document = CPDFDocument(url: url)
- if (document!.isLocked) {
- self.lockedFiles.append(url)
- continue
- }
-
- if let _document = document {
- results.append(_document)
- }
-
- index += 1
- if let _callback = progressBlock {
- _callback(index, ((document != nil) ? document : CPDFDocument()) as Any, url)
- }
- }
-
- if (self.lockedFiles.count == 0) {
- completionBlock(results)
- return
- }
-
- self._openPasswordWindow_loop(fileUrl: self.lockedFiles.first!, type: type) { params in
- index += 1
- if (params.count <= 2) { // 参数错误
- if let _callback = progressBlock { // 回调进度
- _callback(index)
- }
- return
- }
-
- let fileUrl = params[0] as! URL
- let result = params[1] as! KMPasswordInputWindowResult
- let password = params[2] as? String
- if (result == .cancel) {
- if let _callback = progressBlock { // 回调进度
- _callback(index, CPDFDocument() as Any, fileUrl, result)
- }
- return
- }
-
- let document = CPDFDocument(url: fileUrl)
- if let _password = password { // 将文档进行解密
- document?.unlock(withPassword: _password)
- }
- if let _callback = progressBlock { // 回调进度
- _callback(index, document as Any, fileUrl, result, password as Any)
- }
- // 将文档加入返回数据
- if let _document = document {
- results.append(_document)
- }
- } completionBlock: {
- completionBlock(results)
- }
- }
-
- private func km_add_office_multi(fileUrls: [URL], completionBlock:@escaping ([String])->Void) -> Void {
- var fileUrlStrings: [String] = []
-
- let dispatchGroup = Dispatch.DispatchGroup()
- for (index, fileUrl) in fileUrls.enumerated() {
- let filePath = fileUrl.path
- let folderPath = "convertToPDF_\(index).pdf"
- let savePath: String? = folderPath.kUrlToPDFFolderPath() as String
- if (savePath == nil) {
- continue
- }
-
- dispatchGroup.enter()
- KMConvertPDFManager.convertFile(filePath, savePath: savePath!) { success, errorDic in
- if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
- dispatchGroup.leave()
-
- if FileManager.default.fileExists(atPath: savePath!) {
- try?FileManager.default.removeItem(atPath: savePath!)
- }
- let alert = NSAlert.init()
- alert.alertStyle = .critical
- var infoString = ""
- if errorDic != nil {
- for key in (errorDic! as Dictionary).keys {
- infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
- }
- }
- alert.informativeText = KMLocalizedString("Please install Microsoft Office to create PDFs from Office files")
- alert.messageText = KMLocalizedString("Failed to Create PDF", comment: "")
- alert.addButton(withTitle: KMLocalizedString("OK"))
- alert.runModal()
- return
- }
-
- if !savePath!.isPDFValid() {
- dispatchGroup.leave()
-
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = KMLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.")
- alert.runModal()
- return
- }
-
- fileUrlStrings.append(savePath!)
- dispatchGroup.leave()
- }
- }
-
- dispatchGroup.notify(queue: DispatchQueue.main) {
- completionBlock(fileUrlStrings)
- }
- }
-
- fileprivate func _openPasswordWindow_loop(fileUrl: URL, type: KMPasswordInputWindowType, progressBlock: ((_ params: Any...)->Void)?, completionBlock:@escaping ()->Void) {
- KMPasswordInputWindow.openWindow(window: self.view.window!, type: type, url: fileUrl) { [weak self] result, password in
- // 将结果返回
- if let _callback = progressBlock {
- _callback(fileUrl, result, password as Any)
- }
-
- // 进行下一个
- self?.lockedFiles.removeFirst()
- if let _fileUrl = self?.lockedFiles.first {
- self?._openPasswordWindow_loop(fileUrl: _fileUrl, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
- } else {
- completionBlock()
- }
- }
- }
- }
|