KMNThumbnailBaseViewController+Action.swift 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  1. //
  2. // KMMainViewController+Action.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Foundation
  8. import KMComponentLibrary
  9. extension KMNThumbnailBaseViewController {
  10. private func insertImageFilePath(imagePath:String,pageDex:Int)->Bool{
  11. var isSuccessFul:Bool = false
  12. if (FileManager.default.fileExists(atPath: imagePath)) {
  13. if let image = NSImage(contentsOfFile: imagePath) {
  14. isSuccessFul = showDocument?.km_insertPage(image.size, withImage: imagePath, at: UInt(pageDex)) == true
  15. }
  16. }
  17. return isSuccessFul
  18. }
  19. private func undoDeleteIndexPaths(deleteIndexPath: Set<IndexPath>) {
  20. var changeIndex:IndexSet = []
  21. var deletePages:[CPDFPage] = []
  22. let pageIndexs = KMNTools.indexpathsToIndexs(indexpaths: deleteIndexPath)
  23. for i in pageIndexs {
  24. if let page = showDocument?.page(at: UInt(i)) {
  25. deletePages.append(page)
  26. changeIndex.insert(i)
  27. }
  28. }
  29. showDocument?.removePage(at: pageIndexs)
  30. refreshDatas()
  31. collectionView.reloadData()
  32. currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
  33. self?.undoInsertPages(insertPages: deletePages, indexs: pageIndexs)
  34. }
  35. thumbnailBaseViewDelegate?.thumbnailViewControlleHaveChange?(pageEditVC: self)
  36. }
  37. private func undoInsertPages(insertPages:[CPDFPage],indexs: IndexSet) {
  38. var indexpaths = Set<IndexPath>()
  39. var count: Int = 0
  40. for index in indexs {
  41. guard let pageCount = showDocument?.pageCount, index <= pageCount, count < insertPages.count, index != -1 else {
  42. KMPrint("index invalid. index: \(index)")
  43. break
  44. }
  45. showDocument?.insertPageObject(insertPages[count], at: UInt(index))
  46. indexpaths.insert(IndexPath(item: index, section: 0))
  47. count += 1
  48. }
  49. refreshDatas()
  50. collectionView.reloadData()
  51. collectionView.scrollToItems(at: indexpaths, scrollPosition: .centeredVertically)
  52. collectionView.selectionIndexPaths = indexpaths
  53. currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
  54. self?.deletePages(indexpaths: indexpaths)
  55. }
  56. thumbnailBaseViewDelegate?.thumbnailViewControlleHaveChange?(pageEditVC: self)
  57. }
  58. private func undoReplacePages(of targetIndexpaths: Set<IndexPath>, with documents: [CPDFDocument],insertIndexSet:IndexSet,orgPages:[CPDFPage],orgIndexs: IndexSet) {
  59. showDocument?.removePage(at: insertIndexSet)
  60. var indexpaths = Set<IndexPath>()
  61. var count: Int = 0
  62. for index in orgIndexs {
  63. guard let pageCount = showDocument?.pageCount, index <= pageCount, count < orgPages.count, index != -1 else {
  64. KMPrint("index invalid. index: \(index)")
  65. break
  66. }
  67. showDocument?.insertPageObject(orgPages[count], at: UInt(index))
  68. indexpaths.insert(IndexPath(item: index, section: 0))
  69. count += 1
  70. }
  71. refreshDatas()
  72. collectionView.reloadData()
  73. collectionView.scrollToItems(at: indexpaths, scrollPosition: .centeredVertically)
  74. collectionView.selectionIndexPaths = indexpaths
  75. currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
  76. self?.replacePages(of: targetIndexpaths, with: documents)
  77. }
  78. thumbnailBaseViewDelegate?.thumbnailViewControlleHaveChange?(pageEditVC: self)
  79. }
  80. private func undoMovePages(movePages:[CPDFPage],destinationDex:Int,orgPages:[CPDFPage],orgPageDexs:[Int]) {
  81. for (i, page) in orgPages.enumerated() {
  82. let dragIndex = page.pageIndex()
  83. let index:UInt = UInt(orgPageDexs[i])
  84. showDocument?.movePage(at: dragIndex, withPageAt: index)
  85. }
  86. var indexpaths = Set<IndexPath>()
  87. for (_, page) in movePages.enumerated() {
  88. let index = page.pageIndex()
  89. indexpaths.insert(IndexPath(item: Int(index), section: 0))
  90. }
  91. refreshDatas()
  92. collectionView.reloadData()
  93. collectionView.scrollToItems(at: indexpaths, scrollPosition: .centeredVertically)
  94. collectionView.selectionIndexPaths = indexpaths
  95. currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
  96. self?.movePages(dragPages: movePages, destinationDex: destinationDex)
  97. }
  98. thumbnailBaseViewDelegate?.thumbnailViewControlleHaveChange?(pageEditVC: self)
  99. }
  100. func insertFileComplete(newSelectIndexs: Set<IndexPath>){
  101. refreshDatas()
  102. collectionView.reloadData()
  103. collectionView.selectionIndexPaths = newSelectIndexs
  104. if newSelectIndexs.isEmpty { return }
  105. let firstIndexPath = newSelectIndexs.first
  106. collectionView.scrollToItems(at: [firstIndexPath ?? IndexPath(item: 0, section: 0)], scrollPosition: .top)
  107. currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
  108. self?.undoDeleteIndexPaths(deleteIndexPath: newSelectIndexs)
  109. }
  110. thumbnailBaseViewDelegate?.thumbnailViewControlleHaveChange?(pageEditVC: self)
  111. }
  112. public func insertFormPages(insertPages: [CPDFPage],pageDex:Int) {
  113. let pageIndexDex: Int = pageDex
  114. var indexpaths = Set<IndexPath>()
  115. let page = insertPages.first
  116. if page?.document == showDocument {
  117. for (i, page) in insertPages.enumerated() {
  118. let isSuccessFul:Bool = showDocument?.insertPageObject(page, at: UInt(pageIndexDex+i)) == true
  119. if(isSuccessFul == true) {
  120. indexpaths.insert(IndexPath(item: pageIndexDex+i, section: 0))
  121. }
  122. }
  123. } else {
  124. if let pasteDocument = page?.document {
  125. var indexs: IndexSet = IndexSet()
  126. for (i, page) in insertPages.enumerated() {
  127. indexs.insert(Int(pasteDocument.index(for: page)))
  128. indexpaths.insert(IndexPath(item: pageIndexDex+i, section: 0))
  129. }
  130. let isSuccessFul:Bool = showDocument?.importPages(indexs, from: pasteDocument, at: UInt(pageIndexDex)) == true
  131. if(isSuccessFul == false){
  132. return
  133. }
  134. }
  135. }
  136. refreshDatas()
  137. collectionView.reloadData()
  138. collectionView.scrollToItems(at: indexpaths, scrollPosition: .centeredVertically)
  139. collectionView.selectionIndexPaths = indexpaths
  140. currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
  141. self?.undoDeleteIndexPaths(deleteIndexPath: indexpaths)
  142. }
  143. thumbnailBaseViewDelegate?.thumbnailViewControlleHaveChange?(pageEditVC: self)
  144. }
  145. public func insertBlankSize(pageSize: CGSize,pageDex:Int) {
  146. var indexpaths = Set<IndexPath>()
  147. let isSuccessFul = showDocument?.insertBlankPage(pageSize: pageSize, at: pageDex)
  148. if(isSuccessFul == true) {
  149. indexpaths.insert(IndexPath(item: pageDex, section: 0))
  150. }
  151. refreshDatas()
  152. collectionView.reloadData()
  153. collectionView.scrollToItems(at: indexpaths, scrollPosition: .centeredVertically)
  154. collectionView.selectionIndexPaths = indexpaths
  155. currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
  156. self?.undoDeleteIndexPaths(deleteIndexPath: indexpaths)
  157. }
  158. thumbnailBaseViewDelegate?.thumbnailViewControlleHaveChange?(pageEditVC: self)
  159. }
  160. public func rotatePages(indexPaths: Set<IndexPath>, rotateAngle: Int) {
  161. var tIndexPaths: Set<IndexPath> = []
  162. tIndexPaths = indexPaths
  163. for targetIndexPath in indexPaths {
  164. if let page = showDocument?.page(at: UInt(targetIndexPath.item)) {
  165. var pageRotate = page.rotation + rotateAngle
  166. if(pageRotate == -90) {
  167. pageRotate = 270
  168. } else if (pageRotate == 450) {
  169. pageRotate = 90
  170. }
  171. page.rotation = pageRotate
  172. let cellView = collectionView.item(at: targetIndexPath) as? KMNThumbnailCollectionViewItem
  173. if(cellView != nil) {
  174. cellView?.thumbnailMode.removeCacheImage()
  175. }
  176. }
  177. }
  178. collectionView.reloadItems(at: tIndexPaths) // Ensure correct type conversion
  179. collectionView.selectionIndexPaths = tIndexPaths
  180. currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
  181. self?.rotatePages(indexPaths: tIndexPaths, rotateAngle: -rotateAngle)
  182. }
  183. thumbnailBaseViewDelegate?.thumbnailViewControlleHaveChange?(pageEditVC: self)
  184. }
  185. public func reversePages(indexs: IndexSet) {
  186. if let doc = showDocument {
  187. var theIdxs = indexs
  188. var res = false
  189. for _ in 0 ..< indexs.count {
  190. guard let first = theIdxs.first else {
  191. break
  192. }
  193. guard let last = theIdxs.last else {
  194. break
  195. }
  196. if first == last {
  197. break
  198. }
  199. res = doc.exchangePage(at: UInt(first), withPageAt: UInt(last))
  200. if res {
  201. theIdxs.remove(first)
  202. theIdxs.remove(last)
  203. }
  204. }
  205. if res {
  206. refreshDatas()
  207. let selected_indexpaths = KMNTools.indexsToIndexpaths(indexs: indexs)
  208. collectionView.reloadItems(at: selected_indexpaths)
  209. collectionView.selectionIndexPaths = selected_indexpaths
  210. currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
  211. self?.reversePages(indexs: indexs)
  212. }
  213. thumbnailBaseViewDelegate?.thumbnailViewControlleHaveChange?(pageEditVC: self)
  214. }
  215. }
  216. }
  217. public func replacePages(of targetIndexpaths: Set<IndexPath>, with documents: [CPDFDocument]) {
  218. if (targetIndexpaths.count == 0 || documents.count == 0) {
  219. KMPrint("replace invalid.")
  220. return
  221. }
  222. var index = targetIndexpaths.sorted().first!.item
  223. var deletePages:[CPDFPage] = []
  224. let indexSet = KMNTools.indexpathsToIndexs(indexpaths: targetIndexpaths)
  225. for i in indexSet {
  226. if let page = showDocument?.page(at: UInt(i)) {
  227. deletePages.append(page)
  228. }
  229. }
  230. showDocument?.removePage(at: indexSet)
  231. var tIndexPaths: Set<IndexPath> = []
  232. for document in documents {
  233. for i in 0 ..< document.pageCount {
  234. if let page = document.page(at: i) {
  235. showDocument?.insertPageObject(page, at: UInt(index))
  236. tIndexPaths.insert(IndexPath(item: index, section: 0))
  237. index += 1
  238. }
  239. }
  240. thumbnailBaseViewDelegate?.insertPDFThumbnailViewControlle?(pageEditVC: self, pdfDocment: document)
  241. }
  242. refreshDatas()
  243. collectionView.reloadData()
  244. collectionView.selectionIndexPaths = tIndexPaths
  245. currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
  246. self?.undoReplacePages(of: targetIndexpaths, with: documents, insertIndexSet: KMNTools.indexpathsToIndexs(indexpaths: tIndexPaths), orgPages: deletePages,orgIndexs: indexSet)
  247. }
  248. thumbnailBaseViewDelegate?.thumbnailViewControlleHaveChange?(pageEditVC: self)
  249. }
  250. public func deletePages(indexpaths:Set<IndexPath>) {
  251. var changeIndex:IndexSet = []
  252. var deletePages:[CPDFPage] = []
  253. let pageIndexs = KMNTools.indexpathsToIndexs(indexpaths: indexpaths)
  254. for i in pageIndexs {
  255. if let page = showDocument?.page(at: UInt(i)) {
  256. deletePages.append(page)
  257. changeIndex.insert(i)
  258. }
  259. }
  260. showDocument?.removePage(at: changeIndex)
  261. collectionView.selectionIndexPaths = []
  262. refreshDatas()
  263. collectionView.reloadData()
  264. currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
  265. self?.undoInsertPages(insertPages: deletePages, indexs: pageIndexs)
  266. }
  267. thumbnailBaseViewDelegate?.thumbnailViewControlleHaveChange?(pageEditVC: self)
  268. }
  269. public func movePages(dragPages:[CPDFPage],destinationDex:Int) {
  270. guard !dragPages.isEmpty else { return }
  271. var destinationIndex = destinationDex
  272. let maxDragPageIndex = dragPages.last?.pageIndex() ?? 0
  273. let minDragPageIndex = dragPages.first?.pageIndex() ?? 0
  274. let rangeStart = min(Int(minDragPageIndex), destinationIndex)
  275. let rangeEnd = max(Int(maxDragPageIndex), destinationIndex)
  276. var changePages:[CPDFPage] = []
  277. var changePageIndexs:[Int] = []
  278. for index in (rangeStart...rangeEnd) {
  279. if let changePage = showDocument?.page(at: UInt(index)) {
  280. changePages.append(changePage)
  281. changePageIndexs.append(index)
  282. }
  283. }
  284. for dragPage in dragPages {
  285. let dragIndex = dragPage.pageIndex()
  286. if destinationIndex > dragIndex {
  287. destinationIndex -= 1
  288. showDocument?.movePage(at: dragIndex, withPageAt: UInt(destinationIndex))
  289. } else {
  290. showDocument?.movePage(at: dragIndex, withPageAt: UInt(destinationIndex))
  291. }
  292. destinationIndex += 1
  293. }
  294. var selectIndexPaths: Set<IndexPath> = []
  295. for dragPage in dragPages {
  296. let dragIndex = dragPage.pageIndex()
  297. selectIndexPaths.insert(IndexPath(item: Int(dragIndex), section: 0))
  298. }
  299. refreshDatas()
  300. collectionView.reloadData()
  301. collectionView.selectionIndexPaths = selectIndexPaths
  302. if selectIndexPaths.isEmpty { return }
  303. let firstIndexPath = selectIndexPaths.first
  304. collectionView.scrollToItems(at: [firstIndexPath ?? IndexPath(item: 0, section: 0)], scrollPosition: .top)
  305. currentUndoManager?.registerUndo(withTarget: self) { [weak self] targetType in
  306. self?.undoMovePages(movePages: dragPages, destinationDex: destinationDex, orgPages: changePages, orgPageDexs: changePageIndexs)
  307. }
  308. thumbnailBaseViewDelegate?.thumbnailViewControlleHaveChange?(pageEditVC: self)
  309. }
  310. public func insertFromFilePath(fileNames:[String],formDex:Int,indexDex:UInt,selectIndexs:Set<IndexPath>,completionBlock:@escaping (Set<IndexPath>)->Void)-> Void {
  311. let path = fileNames[formDex]
  312. var insertDex = indexDex
  313. var tSelectIndex = selectIndexs
  314. let pathExtension = URL(fileURLWithPath: path).pathExtension.lowercased()
  315. if pathExtension == "pdf", let pdf = CPDFDocument(url: URL(fileURLWithPath: path)) {
  316. if pdf.isLocked {
  317. NSWindowController.checkPassword(url: pdf.documentURL, type: .owner) { success, resultPassword in
  318. if (resultPassword.isEmpty == false) {
  319. pdf.unlock(withPassword: resultPassword)
  320. for i in 0 ..< pdf.pageCount {
  321. let insertPage = pdf.page(at: i)
  322. self.showDocument?.insertPageObject(insertPage, at: insertDex)
  323. tSelectIndex.insert(IndexPath(item: Int(insertDex), section:0))
  324. insertDex += 1
  325. }
  326. var tFormDex = formDex
  327. tFormDex += 1
  328. self.thumbnailBaseViewDelegate?.insertPDFThumbnailViewControlle?(pageEditVC: self, pdfDocment: pdf)
  329. if(tFormDex < fileNames.count) {
  330. return self.insertFromFilePath(fileNames: fileNames, formDex: tFormDex, indexDex: indexDex, selectIndexs: tSelectIndex,completionBlock: completionBlock)
  331. } else {
  332. self.insertFileComplete(newSelectIndexs: tSelectIndex)
  333. return completionBlock(tSelectIndex)
  334. }
  335. }
  336. }
  337. } else {
  338. for i in 0 ..< pdf.pageCount {
  339. let insertPage = pdf.page(at: i)
  340. showDocument?.insertPageObject(insertPage ?? CPDFPage(), at: insertDex)
  341. tSelectIndex.insert(IndexPath(item: Int(insertDex), section:0))
  342. insertDex += 1
  343. }
  344. var tFormDex = formDex
  345. tFormDex += 1
  346. thumbnailBaseViewDelegate?.insertPDFThumbnailViewControlle?(pageEditVC: self, pdfDocment: pdf)
  347. if(tFormDex < fileNames.count) {
  348. return insertFromFilePath(fileNames: fileNames, formDex: tFormDex, indexDex: indexDex, selectIndexs: tSelectIndex,completionBlock: completionBlock)
  349. } else {
  350. insertFileComplete(newSelectIndexs: tSelectIndex)
  351. return completionBlock(tSelectIndex)
  352. }
  353. }
  354. } else if supportDragFileTypes().contains(pathExtension) {
  355. if KMConvertPDFManager.supportImages().contains(pathExtension) {
  356. let isSueccessFul = insertImageFilePath(imagePath: path, pageDex: Int(indexDex))
  357. if(isSueccessFul) {
  358. tSelectIndex.insert(IndexPath(item: Int(insertDex), section:0))
  359. insertDex += 1
  360. }
  361. var tFormDex = formDex
  362. tFormDex += 1
  363. if(tFormDex < fileNames.count) {
  364. return insertFromFilePath(fileNames: fileNames, formDex: tFormDex, indexDex: indexDex, selectIndexs: tSelectIndex,completionBlock: completionBlock)
  365. } else {
  366. insertFileComplete(newSelectIndexs: tSelectIndex)
  367. return completionBlock(tSelectIndex)
  368. }
  369. } else {
  370. KMNConvertTool.convertOffice(filePath: path) { convertPDFPath in
  371. if (convertPDFPath != nil) {
  372. let pathExtension = URL(fileURLWithPath: convertPDFPath!).pathExtension.lowercased()
  373. if pathExtension == "pdf", let pdf = CPDFDocument(url: URL(fileURLWithPath: convertPDFPath!)) {
  374. for i in 0 ..< pdf.pageCount {
  375. let insertPage = pdf.page(at: i)
  376. self.showDocument?.insertPageObject(insertPage, at: insertDex)
  377. tSelectIndex.insert(IndexPath(item: Int(insertDex), section:0))
  378. insertDex += 1
  379. }
  380. self.thumbnailBaseViewDelegate?.insertPDFThumbnailViewControlle?(pageEditVC: self, pdfDocment: pdf)
  381. var tFormDex = formDex
  382. tFormDex += 1
  383. if(tFormDex < fileNames.count) {
  384. return self.insertFromFilePath(fileNames: fileNames, formDex: tFormDex, indexDex: indexDex, selectIndexs: tSelectIndex,completionBlock: completionBlock)
  385. } else {
  386. self.insertFileComplete(newSelectIndexs: tSelectIndex)
  387. return completionBlock(tSelectIndex)
  388. }
  389. }
  390. }
  391. }
  392. }
  393. }
  394. }
  395. public func extractPages(indexpaths: Set<IndexPath>, oneDocumentPerPage: Bool, callback: @escaping KMResultBlock) {
  396. let pageIndexs = KMNTools.indexpathsToIndexs(indexpaths: indexpaths)
  397. let oneDocument = !oneDocumentPerPage
  398. let document = self.showDocument!
  399. /// 提取的页面
  400. var extractPages: Array<CPDFPage> = []
  401. for i in pageIndexs {
  402. guard let page = document.page(at: UInt(i)) else {
  403. continue
  404. }
  405. extractPages.append(page)
  406. }
  407. if (oneDocument) { /// 提取为一个文档
  408. var fileName = document.documentURL.deletingPathExtension().lastPathComponent
  409. fileName.append(" pages ")
  410. fileName.append(KMNTools.newParseSelectedIndexs(selectedIndex: pageIndexs.sorted()))
  411. fileName.append(".pdf")
  412. NSPanel.savePanel(self.view.window!, true) { panel in
  413. panel.nameFieldStringValue = fileName
  414. } completion: { response, url, isOpen in
  415. if (response != .OK) {
  416. callback(.cancel)
  417. return
  418. }
  419. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  420. DispatchQueue.global().async {
  421. var success = false
  422. let pdf = CPDFDocument.init()
  423. success = pdf!.extractAsOneDocument(withPages: extractPages, savePath: url!.path)
  424. DispatchQueue.main.async {
  425. if (success == false) {
  426. callback(.failure)
  427. return
  428. }
  429. if (isOpen == false) {
  430. NSWorkspace.shared.activateFileViewerSelecting([url!])
  431. } else {
  432. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url!, display: true) { _, _, _ in
  433. }
  434. }
  435. callback(.success, [url!])
  436. }
  437. }
  438. }
  439. }
  440. } else {
  441. let panel = NSOpenPanel()
  442. panel.canChooseFiles = false
  443. panel.canChooseDirectories = true
  444. panel.canCreateDirectories = true
  445. panel.allowsMultipleSelection = false
  446. panel.beginSheetModal(for: self.view.window!) { response in
  447. if response != .OK {
  448. callback(.cancel)
  449. return
  450. }
  451. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  452. let outputURL = panel.url
  453. DispatchQueue.global().async {
  454. let folderName = String((document.documentURL.lastPathComponent.split(separator: ".")[0])) + "_extract"
  455. var filePath = URL(fileURLWithPath: outputURL!.path).appendingPathComponent(folderName).path
  456. var i = 1
  457. let testFilePath = filePath
  458. while FileManager.default.fileExists(atPath: filePath) {
  459. filePath = testFilePath + "\(i)"
  460. i += 1
  461. }
  462. try? FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
  463. var successArray: [URL]?
  464. successArray = document.extractPerPageDocument(withPages: extractPages, folerPath: filePath)
  465. DispatchQueue.main.async {
  466. if successArray!.count == 0 {
  467. callback(.failure)
  468. return
  469. }
  470. NSWorkspace.shared.activateFileViewerSelecting(successArray!)
  471. callback(.success, successArray ?? NSURL())
  472. }
  473. }
  474. }
  475. }
  476. }
  477. }
  478. // MARK: - MenuItem
  479. @objc public func copyMenuItemAciton() {
  480. if IAPProductsManager.default().isAvailableAllFunction() == false {
  481. let winC = KMPurchaseCompareWindowController.sharedInstance()
  482. winC?.showWindow(nil)
  483. return
  484. }
  485. KMNThumbnailManager.manager.copyPages = []
  486. let indexpaths = collectionView.selectionIndexPaths
  487. for indexpath in indexpaths.sorted() {
  488. guard let page = showDocument?.page(at: UInt(indexpath.item))?.copy() as? CPDFPage else {
  489. continue
  490. }
  491. KMNThumbnailManager.manager.copyDocument.append(showDocument ?? CPDFDocument())
  492. KMNThumbnailManager.manager.copyPages.append(page)
  493. }
  494. }
  495. @objc public func pastMenuItemAciton(menuitemProperty:ComponentMenuitemProperty) {
  496. if IAPProductsManager.default().isAvailableAllFunction() == false {
  497. let winC = KMPurchaseCompareWindowController.sharedInstance()
  498. winC?.showWindow(nil)
  499. return
  500. }
  501. var pastIndex = 1
  502. let point = menuitemProperty.representedObject as? NSPoint
  503. let selectedIndexPaths = collectionView.selectionIndexPaths
  504. if(selectedIndexPaths.count > 0) {
  505. let maxmumIndexPath = selectedIndexPaths.max(by: { $0 < $1 })
  506. pastIndex = ((maxmumIndexPath?.item ?? 0) + 1)
  507. } else {
  508. if(point != nil) {
  509. let pointInCollectionView = collectionView.convert(point!, from: nil)
  510. let visibleItems = collectionView.visibleItems()
  511. let mouseX = pointInCollectionView.x
  512. let mouseY = pointInCollectionView.y
  513. // 获取当前行的所有 cell
  514. let currentRowItems = visibleItems.filter { item in
  515. if let indexPath = collectionView.indexPath(for: item),
  516. let cellAttributes = collectionView.layoutAttributesForItem(at: indexPath) {
  517. return cellAttributes.frame.minY <= mouseY && cellAttributes.frame.maxY >= mouseY
  518. }
  519. return false
  520. }
  521. if(mouseX < 24) { //点击区域在最左边
  522. // 找到最近右边的 cell
  523. let rightMostCell = currentRowItems.compactMap { collectionView.indexPath(for: $0) }
  524. .filter { indexPath in
  525. let cellRect = collectionView.layoutAttributesForItem(at: indexPath)?.frame
  526. return cellRect?.minX ?? 0 > mouseX // 只选择右侧的 cell
  527. }
  528. .sorted { ($0.item < $1.item) } // 按 item 的顺序排列
  529. .first // 选择第一个,即最右边的 cell
  530. pastIndex = (rightMostCell?.item ?? (Int(showDocument?.pageCount ?? 1)))
  531. } else {
  532. // 找到最近右边的 cell
  533. let leftMostCell = currentRowItems.compactMap { collectionView.indexPath(for: $0) }
  534. .filter { indexPath in
  535. let cellRect = collectionView.layoutAttributesForItem(at: indexPath)?.frame
  536. return cellRect?.maxX ?? 0 < mouseX // 只选择左侧的 cell
  537. }
  538. .sorted { $0.item > $1.item } // 按 item 的逆序排列,以选择最近的左侧 cell
  539. .first // 选择第一个,即最近的左边的 cell
  540. pastIndex = (leftMostCell?.item ?? (Int(showDocument?.pageCount ?? 1)) - 1) + 1
  541. }
  542. } else {
  543. pastIndex = Int(showDocument?.pageCount ?? 0)
  544. }
  545. }
  546. let copyPages = KMNThumbnailManager.manager.copyPages
  547. insertFormPages(insertPages: copyPages, pageDex: pastIndex)
  548. }
  549. @objc public func cutMenuItemAciton() {
  550. if IAPProductsManager.default().isAvailableAllFunction() == false {
  551. let winC = KMPurchaseCompareWindowController.sharedInstance()
  552. winC?.showWindow(nil)
  553. return
  554. }
  555. KMNThumbnailManager.manager.copyPages = []
  556. let indexpaths = collectionView.selectionIndexPaths
  557. for indexpath in indexpaths.sorted() {
  558. guard let page = showDocument?.page(at: UInt(indexpath.item))?.copy() as? CPDFPage else {
  559. continue
  560. }
  561. KMNThumbnailManager.manager.copyDocument.append(showDocument ?? CPDFDocument())
  562. KMNThumbnailManager.manager.copyPages.append(page)
  563. }
  564. deletePages(indexpaths: indexpaths)
  565. }
  566. @objc public func deleteMenuItemAciton() {
  567. if IAPProductsManager.default().isAvailableAllFunction() == false {
  568. let winC = KMPurchaseCompareWindowController.sharedInstance()
  569. winC?.showWindow(nil)
  570. return
  571. }
  572. let indexpaths = collectionView.selectionIndexPaths
  573. deletePages(indexpaths: indexpaths)
  574. }
  575. @objc func sharePageItemAction(menuItem:NSMenuItem) {
  576. if IAPProductsManager.default().isAvailableAllFunction() == false {
  577. let winC = KMPurchaseCompareWindowController.sharedInstance()
  578. winC?.showWindow(nil)
  579. return
  580. }
  581. let indexpaths = collectionView.selectionIndexPaths
  582. let doucument = showDocument
  583. let filename : String = doucument?.documentURL.lastPathComponent ?? ""
  584. let folderPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(filename)) ?? ""
  585. try? FileManager.default.removeItem(atPath: folderPath)
  586. let pdfdocument = CPDFDocument()
  587. let ret = pdfdocument?.importPages(KMNTools.indexpathsToIndexs(indexpaths: indexpaths), from: doucument, at: 0) ?? false
  588. let url = URL(fileURLWithPath: folderPath)
  589. if ret {
  590. let success = pdfdocument?.write(toFile: folderPath)
  591. let represent = menuItem.representedObject as? NSSharingService
  592. represent?.perform(withItems: [url])
  593. }
  594. }
  595. @objc public func displayPageSizeAction() {
  596. let indexpaths = collectionView.selectionIndexPaths
  597. isShowPageSize = !isShowPageSize
  598. collectionView.selectionIndexPaths = indexpaths
  599. }
  600. private func insertFilePath(filePath:String,pdfPassword:String?) {
  601. var selectedIndexPaths = collectionView.selectionIndexPaths
  602. if(selectedIndexPaths.count <= 0) {
  603. selectedIndexPaths = pdfviewSelectionIndexPaths
  604. }
  605. let insertPDF = KMNPDFInsertPDFWindowController(showDocument, filePath: filePath, password: pdfPassword, selectionIndexPaths: selectedIndexPaths)
  606. insertPDF.pdfCallback = { [weak self] fileAttribute, insertIdx in
  607. let doc = fileAttribute.pdfDocument
  608. var insertPages: [CPDFPage] = []
  609. for number in fileAttribute.fetchSelectPages() {
  610. if let page = doc?.page(at: UInt(number-1)) {
  611. insertPages.append(page)
  612. }
  613. }
  614. self?.thumbnailBaseViewDelegate?.insertPDFThumbnailViewControlle?(pageEditVC: self, pdfDocment: doc)
  615. self?.insertFormPages(insertPages: insertPages, pageDex: insertIdx)
  616. }
  617. insertPDF.fileCallback = { [weak self] filePath, insertIdx in
  618. self?.insertFromFilePath(fileNames: [filePath], formDex: 0, indexDex: UInt(insertIdx), selectIndexs: [], completionBlock: { newSelectIndexs in
  619. })
  620. }
  621. insertPDF.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  622. }
  623. // MARK: - public
  624. func updateThumnailItem(updateIndexPaths: Set<IndexPath>,isSelect:Bool) {
  625. for targetIndexPath in updateIndexPaths {
  626. let cellView = collectionView.item(at: targetIndexPath) as? KMNThumbnailCollectionViewItem
  627. if(cellView != nil) {
  628. cellView?.thumbnailMode.removeCacheImage()
  629. }
  630. }
  631. collectionView.reloadItems(at: updateIndexPaths)
  632. if(isSelect) {
  633. if updateIndexPaths.isEmpty { return }
  634. let firstIndexPath = updateIndexPaths.first
  635. collectionView.scrollToItems(at: [firstIndexPath ?? IndexPath(item: 0, section: 0)], scrollPosition: .top)
  636. collectionView.selectionIndexPaths = updateIndexPaths
  637. }
  638. }
  639. func updateAllThumnailItems() {
  640. KMNThumbnailManager.clearCacheFilePath(filePath: showDocument?.documentURL.path ?? "")
  641. collectionView.reloadData()
  642. }
  643. @objc public func insertFromPDFAction() {
  644. if IAPProductsManager.default().isAvailableAllFunction() == false {
  645. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  646. return
  647. }
  648. let openPanel = NSOpenPanel()
  649. openPanel.allowedFileTypes = supportDragFileTypes()
  650. openPanel.allowsMultipleSelection = false
  651. openPanel.beginSheetModal(for: NSWindow.currentWindow()) {[weak self] result in
  652. if result == NSApplication.ModalResponse.OK {
  653. let fileURL = openPanel.url
  654. if(fileURL?.pathExtension == "pdf") {
  655. let pdfDoc = CPDFDocument(url: fileURL)
  656. if let data = pdfDoc?.isLocked, data {
  657. DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
  658. NSWindowController.checkPassword(url: fileURL ?? NSURL.fileURL(withPath: ""), type: .owner) { result, pwd in
  659. if (pwd.isEmpty == false) {
  660. self?.insertFilePath(filePath: fileURL?.path ?? "", pdfPassword: pwd)
  661. }
  662. }
  663. }
  664. } else {
  665. self?.insertFilePath(filePath: fileURL?.path ?? "", pdfPassword: nil)
  666. }
  667. } else {
  668. self?.insertFilePath(filePath: fileURL?.path ?? "", pdfPassword: nil)
  669. }
  670. }
  671. }
  672. }
  673. @objc public func insertFromBlankAction() {
  674. if IAPProductsManager.default().isAvailableAllFunction() == false {
  675. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  676. return
  677. }
  678. var selectedIndexPaths = collectionView.selectionIndexPaths
  679. if(selectedIndexPaths.count <= 0) {
  680. selectedIndexPaths = pdfviewSelectionIndexPaths
  681. }
  682. let insertPDF = KMNPDFInsertBlankWindowController(self.showDocument, selectionIndexPaths: selectedIndexPaths)
  683. insertPDF.callback = { [weak self] pageSize, insertIdx in
  684. self?.insertBlankSize(pageSize: pageSize, pageDex: insertIdx)
  685. }
  686. insertPDF.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  687. }
  688. public func insertFromClipboardAction() {
  689. if IAPProductsManager.default().isAvailableAllFunction() == false {
  690. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  691. return
  692. }
  693. var selectedIndexPaths = collectionView.selectionIndexPaths
  694. if(selectedIndexPaths.count <= 0) {
  695. selectedIndexPaths = pdfviewSelectionIndexPaths
  696. }
  697. var maxmumIndex = 1
  698. if(selectedIndexPaths.count > 0) {
  699. let maxmumIndexPath = selectedIndexPaths.max(by: { $0 < $1 })
  700. maxmumIndex = (maxmumIndexPath?.item ?? 0) + 1
  701. }
  702. var error: NSError?
  703. guard let document: CPDFDocument = KMNConvertTool.openDocumentWithImageFromPasteboard(NSPasteboard.general, error: &error) else {
  704. return
  705. }
  706. var insetPages:[CPDFPage] = []
  707. for i in 0 ..< document.pageCount {
  708. let page: CPDFPage = (document.page(at: i))
  709. insetPages.append(page)
  710. }
  711. if insetPages.count > 0 {
  712. insertFormPages(insertPages: insetPages, pageDex: maxmumIndex)
  713. }
  714. self.thumbnailBaseViewDelegate?.insertPDFThumbnailViewControlle?(pageEditVC: self, pdfDocment: document)
  715. let ips: Set<IndexPath> = [IndexPath(item: maxmumIndex, section: 0)]
  716. refreshDatas()
  717. collectionView.selectionIndexPaths = ips
  718. collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  719. }
  720. public func insertFromScannerAction() {
  721. if IAPProductsManager.default().isAvailableAllFunction() == false {
  722. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  723. return
  724. }
  725. let selectedIndexPaths = collectionView.selectionIndexPaths
  726. let maxmumIndexPath = selectedIndexPaths.max(by: { $0 < $1 })
  727. let vc = KMDeviceBrowserWindowController.shared
  728. vc.type = .scanner
  729. vc.importScannerFileCallback = { [weak self] (url: NSURL) -> Void in
  730. if let imag = NSImage(contentsOfFile: url.path! ) {
  731. let index = (maxmumIndexPath?.item ?? 0) + 1
  732. _ = self?.showDocument?.km_insertPage(imag.size, withImage: url.path! , at:UInt(index))
  733. self?.refreshDatas()
  734. let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
  735. self?.collectionView.selectionIndexPaths = ips
  736. self?.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  737. }
  738. }
  739. vc.showWindow(nil)
  740. vc.window?.center()
  741. }
  742. public func canUndo()->Bool {
  743. return true
  744. }
  745. public func undoPDFAction() {
  746. currentUndoManager?.undo()
  747. }
  748. public func canRodo()->Bool {
  749. return true
  750. }
  751. public func redoPDFAction() {
  752. currentUndoManager?.redo()
  753. }
  754. @objc public func extractPDFAction() {
  755. if IAPProductsManager.default().isAvailableAllFunction() == false {
  756. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  757. return
  758. }
  759. let selectedIndexPaths = collectionView.selectionIndexPaths
  760. if selectedIndexPaths.count < 1 {
  761. _ = 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))
  762. return
  763. }
  764. let extractPDF = KMNExtractPDFWindowController(self.showDocument, selectionIndexPaths: collectionView.selectionIndexPaths)
  765. extractPDF.callback = { [weak self] oneDocumentPerPage, isDeletePage in
  766. extractPDF.own_closeEndSheet()
  767. if let _ = self?.showDocument {
  768. self?.extractPages(indexpaths: selectedIndexPaths, oneDocumentPerPage: oneDocumentPerPage, callback: { [weak self] result, params in
  769. if (result == .failure || result == .cancel) {
  770. return
  771. }
  772. if (isDeletePage) {
  773. self?.deletePages(indexpaths: selectedIndexPaths)
  774. }
  775. })
  776. }
  777. }
  778. extractPDF.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  779. }
  780. @objc public func replacePDFAction() {
  781. if IAPProductsManager.default().isAvailableAllFunction() == false {
  782. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  783. return
  784. }
  785. let selectedIndexPaths = collectionView.selectionIndexPaths
  786. if selectedIndexPaths.count < 1 {
  787. _ = 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))
  788. return
  789. }
  790. self.km_open_file_multi { [unowned self] index, params in
  791. if (self.fetchProgressBlockParamsIsPasswordFile(params: params)) { // 加密文档进度回调
  792. return
  793. }
  794. let tFileUrl = self.fetchProgressBlockParamsForFileUrl(params: params)
  795. let pdfExtensions = KMNConvertTool.supportPDFFileType()
  796. if let exn = tFileUrl?.pathExtension, pdfExtensions.contains(exn) {
  797. if (tFileUrl!.path.isPDFValid() == false) {
  798. let alert = NSAlert()
  799. alert.alertStyle = .critical
  800. alert.messageText = KMLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.")
  801. alert.runModal()
  802. }
  803. }
  804. } completionBlock: { [unowned self] documents in
  805. self.replacePages(of: selectedIndexPaths, with: documents)
  806. }
  807. }
  808. public func splitPDFAction() {
  809. if IAPProductsManager.default().isAvailableAllFunction() == false {
  810. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  811. return
  812. }
  813. let selectedIndexPaths = collectionView.selectionIndexPaths
  814. if collectionView.selectionIndexPaths.count < 1 {
  815. _ = 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))
  816. return
  817. }
  818. let splitPDF = KMNSplitPDFWindowController(self.showDocument,selectionIndexPaths: selectedIndexPaths)
  819. splitPDF.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  820. }
  821. public func reversePDFAction() {
  822. if IAPProductsManager.default().isAvailableAllFunction() == false {
  823. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  824. return
  825. }
  826. let selectedIndexPaths = collectionView.selectionIndexPaths
  827. if selectedIndexPaths.count < 2 {
  828. _ = 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))
  829. return
  830. }
  831. reversePages(indexs:KMNTools.indexpathsToIndexs(indexpaths: selectedIndexPaths))
  832. }
  833. @objc public func rotatePageLeftAction() {
  834. if IAPProductsManager.default().isAvailableAllFunction() == false {
  835. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  836. return
  837. }
  838. if collectionView.selectionIndexPaths.count < 1 {
  839. _ = 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))
  840. return
  841. }
  842. rotatePages(indexPaths: collectionView.selectionIndexPaths, rotateAngle: -90)
  843. }
  844. @objc public func rotatePageRightAction() {
  845. if IAPProductsManager.default().isAvailableAllFunction() == false {
  846. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  847. return
  848. }
  849. if collectionView.selectionIndexPaths.count < 1 {
  850. _ = 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))
  851. return
  852. }
  853. rotatePages(indexPaths: collectionView.selectionIndexPaths, rotateAngle: 90)
  854. }
  855. public func deletePageAction() {
  856. if IAPProductsManager.default().isAvailableAllFunction() == false {
  857. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  858. return
  859. }
  860. let selectedIndexPaths = collectionView.selectionIndexPaths
  861. if selectedIndexPaths.count < 1 {
  862. _ = 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))
  863. return
  864. } else if selectedIndexPaths.count == (showDocument?.pageCount ?? 0) {
  865. _ = 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))
  866. return
  867. }
  868. deletePages(indexpaths: selectedIndexPaths)
  869. }
  870. // MARK: - private
  871. private func fetchProgressBlockParamsIsPasswordFile(params: Any...) -> Bool {
  872. if (params.count <= 2) {
  873. return false
  874. }
  875. return true
  876. }
  877. private func fetchProgressBlockParamsForFileUrl(params: Any...) -> URL? {
  878. if (params.count < 2) {
  879. return nil
  880. }
  881. return params[1] as? URL
  882. }
  883. private func km_open_file_multi(type: KMPasswordInputWindowType = .owner, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  884. NSPanel.km_open_multi_success(self.view.window!) { panel in
  885. var array: [String] = []
  886. for fileType in KMConvertPDFManager.supportFileType() {
  887. array.append(fileType)
  888. }
  889. panel.allowedFileTypes = KMNConvertTool.pdfExtensions + array
  890. } completion: { urls in
  891. self.km_add_file_multi(fileUrls: urls, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  892. }
  893. }
  894. private func km_add_file_multi(fileUrls: [URL] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  895. var pdfUrls: [URL] = []
  896. var imageUrls: [URL] = []
  897. var officeUrls: [URL] = []
  898. for url in fileUrls {
  899. let type = url.pathExtension.lowercased()
  900. if (KMNConvertTool.isPDFType(type)) {
  901. pdfUrls.append(url)
  902. }
  903. if (KMNConvertTool.isImageType(type)) {
  904. imageUrls.append(url)
  905. }
  906. if (KMNConvertTool.isOfficeType(type)) {
  907. officeUrls.append(url)
  908. }
  909. }
  910. if (officeUrls.count == 0) {
  911. self.km_add_pdf_multi(fileUrls: pdfUrls, type: type, progressBlock: progressBlock) { documents in
  912. var index = documents.count
  913. var _documents: [CPDFDocument] = []
  914. for imageUrl in imageUrls {
  915. index += 1
  916. let document = CPDFDocument()
  917. let image = NSImage(contentsOfFile: imageUrl.path)
  918. let _ = document?.km_insertPage(image?.size ?? .zero, withImage: imageUrl.path, at: 0)
  919. _documents.append(document!)
  920. if let _callback = progressBlock { // 回调进度
  921. _callback(index, document as Any, imageUrl)
  922. }
  923. }
  924. completionBlock(documents + _documents)
  925. }
  926. return
  927. }
  928. self.km_add_office_multi(fileUrls: officeUrls) { [unowned self] fileUrlStrings in
  929. var officeDocuments: [CPDFDocument] = []
  930. var index = 0
  931. for fileUrlString in fileUrlStrings {
  932. index += 1
  933. let document = CPDFDocument(url: URL(fileURLWithPath: fileUrlString))
  934. officeDocuments.append(document!)
  935. if let _callback = progressBlock { // 回调进度
  936. _callback(index, document as Any, URL(fileURLWithPath: fileUrlString))
  937. }
  938. }
  939. self.km_add_pdf_multi(fileUrls: pdfUrls) { documents in
  940. var index = documents.count + officeDocuments.count
  941. var _documents: [CPDFDocument] = []
  942. for imageUrl in imageUrls {
  943. index += 1
  944. let document = CPDFDocument()
  945. let image = NSImage(contentsOfFile: imageUrl.path)
  946. let _ = document?.km_insertPage(image!.size, withImage: imageUrl.path, at: 0)
  947. _documents.append(document!)
  948. if let _callback = progressBlock { // 回调进度
  949. _callback(index, document as Any, imageUrl)
  950. }
  951. }
  952. completionBlock(officeDocuments + documents + _documents)
  953. }
  954. }
  955. }
  956. private func km_add_pdf_multi(fileUrls: [URL] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  957. var results: [CPDFDocument] = []
  958. self.lockedFiles.removeAll()
  959. var index = 0
  960. for url in fileUrls {
  961. let document = CPDFDocument(url: url)
  962. if (document!.isLocked) {
  963. self.lockedFiles.append(url)
  964. continue
  965. }
  966. if let _document = document {
  967. results.append(_document)
  968. }
  969. index += 1
  970. if let _callback = progressBlock {
  971. _callback(index, ((document != nil) ? document : CPDFDocument()) as Any, url)
  972. }
  973. }
  974. if (self.lockedFiles.count == 0) {
  975. completionBlock(results)
  976. return
  977. }
  978. self._openPasswordWindow_loop(fileUrl: self.lockedFiles.first!, type: type) { params in
  979. index += 1
  980. if (params.count <= 2) { // 参数错误
  981. if let _callback = progressBlock { // 回调进度
  982. _callback(index)
  983. }
  984. return
  985. }
  986. let fileUrl = params[0] as! URL
  987. let result = params[1] as! KMPasswordInputWindowResult
  988. let password = params[2] as? String
  989. if (result == .cancel) {
  990. if let _callback = progressBlock { // 回调进度
  991. _callback(index, CPDFDocument() as Any, fileUrl, result)
  992. }
  993. return
  994. }
  995. let document = CPDFDocument(url: fileUrl)
  996. if let _password = password { // 将文档进行解密
  997. document?.unlock(withPassword: _password)
  998. }
  999. if let _callback = progressBlock { // 回调进度
  1000. _callback(index, document as Any, fileUrl, result, password as Any)
  1001. }
  1002. // 将文档加入返回数据
  1003. if let _document = document {
  1004. results.append(_document)
  1005. }
  1006. } completionBlock: {
  1007. completionBlock(results)
  1008. }
  1009. }
  1010. private func km_add_office_multi(fileUrls: [URL], completionBlock:@escaping ([String])->Void) -> Void {
  1011. var fileUrlStrings: [String] = []
  1012. let dispatchGroup = Dispatch.DispatchGroup()
  1013. for (index, fileUrl) in fileUrls.enumerated() {
  1014. let filePath = fileUrl.path
  1015. let folderPath = "convertToPDF_\(index).pdf"
  1016. let savePath: String? = folderPath.kUrlToPDFFolderPath() as String
  1017. if (savePath == nil) {
  1018. continue
  1019. }
  1020. dispatchGroup.enter()
  1021. KMConvertPDFManager.convertFile(filePath, savePath: savePath!) { success, errorDic in
  1022. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  1023. dispatchGroup.leave()
  1024. if FileManager.default.fileExists(atPath: savePath!) {
  1025. try?FileManager.default.removeItem(atPath: savePath!)
  1026. }
  1027. let alert = NSAlert.init()
  1028. alert.alertStyle = .critical
  1029. var infoString = ""
  1030. if errorDic != nil {
  1031. for key in (errorDic! as Dictionary).keys {
  1032. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  1033. }
  1034. }
  1035. alert.informativeText = KMLocalizedString("Please install Microsoft Office to create PDFs from Office files")
  1036. alert.messageText = KMLocalizedString("Failed to Create PDF", comment: "")
  1037. alert.addButton(withTitle: KMLocalizedString("OK"))
  1038. alert.runModal()
  1039. return
  1040. }
  1041. if !savePath!.isPDFValid() {
  1042. dispatchGroup.leave()
  1043. let alert = NSAlert()
  1044. alert.alertStyle = .critical
  1045. alert.messageText = KMLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.")
  1046. alert.runModal()
  1047. return
  1048. }
  1049. fileUrlStrings.append(savePath!)
  1050. dispatchGroup.leave()
  1051. }
  1052. }
  1053. dispatchGroup.notify(queue: DispatchQueue.main) {
  1054. completionBlock(fileUrlStrings)
  1055. }
  1056. }
  1057. fileprivate func _openPasswordWindow_loop(fileUrl: URL, type: KMPasswordInputWindowType, progressBlock: ((_ params: Any...)->Void)?, completionBlock:@escaping ()->Void) {
  1058. KMPasswordInputWindow.openWindow(window: self.view.window!, type: type, url: fileUrl) { [weak self] result, password in
  1059. // 将结果返回
  1060. if let _callback = progressBlock {
  1061. _callback(fileUrl, result, password as Any)
  1062. }
  1063. // 进行下一个
  1064. self?.lockedFiles.removeFirst()
  1065. if let _fileUrl = self?.lockedFiles.first {
  1066. self?._openPasswordWindow_loop(fileUrl: _fileUrl, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  1067. } else {
  1068. completionBlock()
  1069. }
  1070. }
  1071. }
  1072. }