KMNThumbnailBaseViewController+Action.swift 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  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. reloadDatas() // 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?.reloadDatas()
  734. let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
  735. self?.collectionView.selectionIndexPaths = ips
  736. self?.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  737. vc.close()
  738. }
  739. }
  740. vc.showWindow(nil)
  741. vc.window?.center()
  742. }
  743. public func canUndo()->Bool {
  744. return true
  745. }
  746. public func undoPDFAction() {
  747. currentUndoManager?.undo()
  748. }
  749. public func canRodo()->Bool {
  750. return true
  751. }
  752. public func redoPDFAction() {
  753. currentUndoManager?.redo()
  754. }
  755. @objc public func extractPDFAction() {
  756. if IAPProductsManager.default().isAvailableAllFunction() == false {
  757. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  758. return
  759. }
  760. let selectedIndexPaths = collectionView.selectionIndexPaths
  761. if selectedIndexPaths.count < 1 {
  762. _ = 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))
  763. return
  764. }
  765. let extractPDF = KMNExtractPDFWindowController(self.showDocument, selectionIndexPaths: collectionView.selectionIndexPaths)
  766. extractPDF.callback = { [weak self] oneDocumentPerPage, isDeletePage in
  767. extractPDF.own_closeEndSheet()
  768. if let _ = self?.showDocument {
  769. self?.extractPages(indexpaths: selectedIndexPaths, oneDocumentPerPage: oneDocumentPerPage, callback: { [weak self] result, params in
  770. if (result == .failure || result == .cancel) {
  771. return
  772. }
  773. if (isDeletePage) {
  774. self?.deletePages(indexpaths: selectedIndexPaths)
  775. }
  776. })
  777. }
  778. }
  779. extractPDF.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  780. }
  781. @objc public func replacePDFAction() {
  782. if IAPProductsManager.default().isAvailableAllFunction() == false {
  783. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  784. return
  785. }
  786. let selectedIndexPaths = collectionView.selectionIndexPaths
  787. if selectedIndexPaths.count < 1 {
  788. _ = 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))
  789. return
  790. }
  791. self.km_open_file_multi { [unowned self] index, params in
  792. if (self.fetchProgressBlockParamsIsPasswordFile(params: params)) { // 加密文档进度回调
  793. return
  794. }
  795. let tFileUrl = self.fetchProgressBlockParamsForFileUrl(params: params)
  796. let pdfExtensions = KMNConvertTool.supportPDFFileType()
  797. if let exn = tFileUrl?.pathExtension, pdfExtensions.contains(exn) {
  798. if (tFileUrl!.path.isPDFValid() == false) {
  799. let alert = NSAlert()
  800. alert.alertStyle = .critical
  801. alert.messageText = KMLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.")
  802. alert.runModal()
  803. }
  804. }
  805. } completionBlock: { [unowned self] documents in
  806. self.replacePages(of: selectedIndexPaths, with: documents)
  807. }
  808. }
  809. public func splitPDFAction() {
  810. if IAPProductsManager.default().isAvailableAllFunction() == false {
  811. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  812. return
  813. }
  814. let selectedIndexPaths = collectionView.selectionIndexPaths
  815. if collectionView.selectionIndexPaths.count < 1 {
  816. _ = 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))
  817. return
  818. }
  819. let splitPDF = KMNSplitPDFWindowController(self.showDocument,selectionIndexPaths: selectedIndexPaths)
  820. splitPDF.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  821. }
  822. public func reversePDFAction() {
  823. if IAPProductsManager.default().isAvailableAllFunction() == false {
  824. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  825. return
  826. }
  827. let selectedIndexPaths = collectionView.selectionIndexPaths
  828. if selectedIndexPaths.count < 2 {
  829. _ = 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))
  830. return
  831. }
  832. reversePages(indexs:KMNTools.indexpathsToIndexs(indexpaths: selectedIndexPaths))
  833. }
  834. @objc public func rotatePageLeftAction() {
  835. if IAPProductsManager.default().isAvailableAllFunction() == false {
  836. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  837. return
  838. }
  839. if collectionView.selectionIndexPaths.count < 1 {
  840. _ = 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))
  841. return
  842. }
  843. rotatePages(indexPaths: collectionView.selectionIndexPaths, rotateAngle: -90)
  844. }
  845. @objc public func rotatePageRightAction() {
  846. if IAPProductsManager.default().isAvailableAllFunction() == false {
  847. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  848. return
  849. }
  850. if collectionView.selectionIndexPaths.count < 1 {
  851. _ = 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))
  852. return
  853. }
  854. rotatePages(indexPaths: collectionView.selectionIndexPaths, rotateAngle: 90)
  855. }
  856. public func deletePageAction() {
  857. if IAPProductsManager.default().isAvailableAllFunction() == false {
  858. KMPurchaseCompareWindowController.sharedInstance()?.showWindow(nil)
  859. return
  860. }
  861. let selectedIndexPaths = collectionView.selectionIndexPaths
  862. if selectedIndexPaths.count < 1 {
  863. _ = 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))
  864. return
  865. } else if selectedIndexPaths.count == (showDocument?.pageCount ?? 0) {
  866. _ = 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))
  867. return
  868. }
  869. deletePages(indexpaths: selectedIndexPaths)
  870. }
  871. // MARK: - private
  872. private func fetchProgressBlockParamsIsPasswordFile(params: Any...) -> Bool {
  873. if (params.count <= 2) {
  874. return false
  875. }
  876. return true
  877. }
  878. private func fetchProgressBlockParamsForFileUrl(params: Any...) -> URL? {
  879. if (params.count < 2) {
  880. return nil
  881. }
  882. return params[1] as? URL
  883. }
  884. private func km_open_file_multi(type: KMPasswordInputWindowType = .owner, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  885. NSPanel.km_open_multi_success(self.view.window!) { panel in
  886. var array: [String] = []
  887. for fileType in KMConvertPDFManager.supportFileType() {
  888. array.append(fileType)
  889. }
  890. panel.allowedFileTypes = KMNConvertTool.pdfExtensions + array
  891. } completion: { urls in
  892. self.km_add_file_multi(fileUrls: urls, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  893. }
  894. }
  895. private func km_add_file_multi(fileUrls: [URL] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  896. var pdfUrls: [URL] = []
  897. var imageUrls: [URL] = []
  898. var officeUrls: [URL] = []
  899. for url in fileUrls {
  900. let type = url.pathExtension.lowercased()
  901. if (KMNConvertTool.isPDFType(type)) {
  902. pdfUrls.append(url)
  903. }
  904. if (KMNConvertTool.isImageType(type)) {
  905. imageUrls.append(url)
  906. }
  907. if (KMNConvertTool.isOfficeType(type)) {
  908. officeUrls.append(url)
  909. }
  910. }
  911. if (officeUrls.count == 0) {
  912. self.km_add_pdf_multi(fileUrls: pdfUrls, type: type, progressBlock: progressBlock) { documents in
  913. var index = documents.count
  914. var _documents: [CPDFDocument] = []
  915. for imageUrl in imageUrls {
  916. index += 1
  917. let document = CPDFDocument()
  918. let image = NSImage(contentsOfFile: imageUrl.path)
  919. let _ = document?.km_insertPage(image?.size ?? .zero, withImage: imageUrl.path, at: 0)
  920. _documents.append(document!)
  921. if let _callback = progressBlock { // 回调进度
  922. _callback(index, document as Any, imageUrl)
  923. }
  924. }
  925. completionBlock(documents + _documents)
  926. }
  927. return
  928. }
  929. self.km_add_office_multi(fileUrls: officeUrls) { [unowned self] fileUrlStrings in
  930. var officeDocuments: [CPDFDocument] = []
  931. var index = 0
  932. for fileUrlString in fileUrlStrings {
  933. index += 1
  934. let document = CPDFDocument(url: URL(fileURLWithPath: fileUrlString))
  935. officeDocuments.append(document!)
  936. if let _callback = progressBlock { // 回调进度
  937. _callback(index, document as Any, URL(fileURLWithPath: fileUrlString))
  938. }
  939. }
  940. self.km_add_pdf_multi(fileUrls: pdfUrls) { documents in
  941. var index = documents.count + officeDocuments.count
  942. var _documents: [CPDFDocument] = []
  943. for imageUrl in imageUrls {
  944. index += 1
  945. let document = CPDFDocument()
  946. let image = NSImage(contentsOfFile: imageUrl.path)
  947. let _ = document?.km_insertPage(image!.size, withImage: imageUrl.path, at: 0)
  948. _documents.append(document!)
  949. if let _callback = progressBlock { // 回调进度
  950. _callback(index, document as Any, imageUrl)
  951. }
  952. }
  953. completionBlock(officeDocuments + documents + _documents)
  954. }
  955. }
  956. }
  957. private func km_add_pdf_multi(fileUrls: [URL] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  958. var results: [CPDFDocument] = []
  959. self.lockedFiles.removeAll()
  960. var index = 0
  961. for url in fileUrls {
  962. let document = CPDFDocument(url: url)
  963. if (document!.isLocked) {
  964. self.lockedFiles.append(url)
  965. continue
  966. }
  967. if let _document = document {
  968. results.append(_document)
  969. }
  970. index += 1
  971. if let _callback = progressBlock {
  972. _callback(index, ((document != nil) ? document : CPDFDocument()) as Any, url)
  973. }
  974. }
  975. if (self.lockedFiles.count == 0) {
  976. completionBlock(results)
  977. return
  978. }
  979. self._openPasswordWindow_loop(fileUrl: self.lockedFiles.first!, type: type) { params in
  980. index += 1
  981. if (params.count <= 2) { // 参数错误
  982. if let _callback = progressBlock { // 回调进度
  983. _callback(index)
  984. }
  985. return
  986. }
  987. let fileUrl = params[0] as! URL
  988. let result = params[1] as! KMPasswordInputWindowResult
  989. let password = params[2] as? String
  990. if (result == .cancel) {
  991. if let _callback = progressBlock { // 回调进度
  992. _callback(index, CPDFDocument() as Any, fileUrl, result)
  993. }
  994. return
  995. }
  996. let document = CPDFDocument(url: fileUrl)
  997. if let _password = password { // 将文档进行解密
  998. document?.unlock(withPassword: _password)
  999. }
  1000. if let _callback = progressBlock { // 回调进度
  1001. _callback(index, document as Any, fileUrl, result, password as Any)
  1002. }
  1003. // 将文档加入返回数据
  1004. if let _document = document {
  1005. results.append(_document)
  1006. }
  1007. } completionBlock: {
  1008. completionBlock(results)
  1009. }
  1010. }
  1011. private func km_add_office_multi(fileUrls: [URL], completionBlock:@escaping ([String])->Void) -> Void {
  1012. var fileUrlStrings: [String] = []
  1013. let dispatchGroup = Dispatch.DispatchGroup()
  1014. for (index, fileUrl) in fileUrls.enumerated() {
  1015. let filePath = fileUrl.path
  1016. let folderPath = "convertToPDF_\(index).pdf"
  1017. let savePath: String? = folderPath.kUrlToPDFFolderPath() as String
  1018. if (savePath == nil) {
  1019. continue
  1020. }
  1021. dispatchGroup.enter()
  1022. KMConvertPDFManager.convertFile(filePath, savePath: savePath!) { success, errorDic in
  1023. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  1024. dispatchGroup.leave()
  1025. if FileManager.default.fileExists(atPath: savePath!) {
  1026. try?FileManager.default.removeItem(atPath: savePath!)
  1027. }
  1028. let alert = NSAlert.init()
  1029. alert.alertStyle = .critical
  1030. var infoString = ""
  1031. if errorDic != nil {
  1032. for key in (errorDic! as Dictionary).keys {
  1033. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  1034. }
  1035. }
  1036. alert.informativeText = KMLocalizedString("Please install Microsoft Office to create PDFs from Office files")
  1037. alert.messageText = KMLocalizedString("Failed to Create PDF", comment: "")
  1038. alert.addButton(withTitle: KMLocalizedString("OK"))
  1039. alert.runModal()
  1040. return
  1041. }
  1042. if !savePath!.isPDFValid() {
  1043. dispatchGroup.leave()
  1044. let alert = NSAlert()
  1045. alert.alertStyle = .critical
  1046. alert.messageText = KMLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.")
  1047. alert.runModal()
  1048. return
  1049. }
  1050. fileUrlStrings.append(savePath!)
  1051. dispatchGroup.leave()
  1052. }
  1053. }
  1054. dispatchGroup.notify(queue: DispatchQueue.main) {
  1055. completionBlock(fileUrlStrings)
  1056. }
  1057. }
  1058. fileprivate func _openPasswordWindow_loop(fileUrl: URL, type: KMPasswordInputWindowType, progressBlock: ((_ params: Any...)->Void)?, completionBlock:@escaping ()->Void) {
  1059. KMPasswordInputWindow.openWindow(window: self.view.window!, type: type, url: fileUrl) { [weak self] result, password in
  1060. // 将结果返回
  1061. if let _callback = progressBlock {
  1062. _callback(fileUrl, result, password as Any)
  1063. }
  1064. // 进行下一个
  1065. self?.lockedFiles.removeFirst()
  1066. if let _fileUrl = self?.lockedFiles.first {
  1067. self?._openPasswordWindow_loop(fileUrl: _fileUrl, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  1068. } else {
  1069. completionBlock()
  1070. }
  1071. }
  1072. }
  1073. }