KMNThumbnailBaseViewController+Action.swift 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  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 KMMemberInfo.shared.isLogin == false {
  481. KMLoginWindowsController.shared.showWindow(nil)
  482. return
  483. }
  484. KMNThumbnailManager.manager.copyPages = []
  485. let indexpaths = collectionView.selectionIndexPaths
  486. for indexpath in indexpaths.sorted() {
  487. guard let page = showDocument?.page(at: UInt(indexpath.item))?.copy() as? CPDFPage else {
  488. continue
  489. }
  490. KMNThumbnailManager.manager.copyDocument.append(showDocument ?? CPDFDocument())
  491. KMNThumbnailManager.manager.copyPages.append(page)
  492. }
  493. }
  494. @objc public func pastMenuItemAciton(menuitemProperty:ComponentMenuitemProperty?) {
  495. if KMMemberInfo.shared.isLogin == false {
  496. KMLoginWindowsController.shared.showWindow(nil)
  497. return
  498. }
  499. var pastIndex = 1
  500. let point = menuitemProperty?.representedObject as? NSPoint
  501. let selectedIndexPaths = collectionView.selectionIndexPaths
  502. if(selectedIndexPaths.count > 0) {
  503. let maxmumIndexPath = selectedIndexPaths.max(by: { $0 < $1 })
  504. pastIndex = ((maxmumIndexPath?.item ?? 0) + 1)
  505. } else {
  506. if(point != nil) {
  507. let pointInCollectionView = collectionView.convert(point!, from: nil)
  508. let visibleItems = collectionView.visibleItems()
  509. let mouseX = pointInCollectionView.x
  510. let mouseY = pointInCollectionView.y
  511. // 获取当前行的所有 cell
  512. let currentRowItems = visibleItems.filter { item in
  513. if let indexPath = collectionView.indexPath(for: item),
  514. let cellAttributes = collectionView.layoutAttributesForItem(at: indexPath) {
  515. return cellAttributes.frame.minY <= mouseY && cellAttributes.frame.maxY >= mouseY
  516. }
  517. return false
  518. }
  519. if(mouseX < 24) { //点击区域在最左边
  520. // 找到最近右边的 cell
  521. let rightMostCell = currentRowItems.compactMap { collectionView.indexPath(for: $0) }
  522. .filter { indexPath in
  523. let cellRect = collectionView.layoutAttributesForItem(at: indexPath)?.frame
  524. return cellRect?.minX ?? 0 > mouseX // 只选择右侧的 cell
  525. }
  526. .sorted { ($0.item < $1.item) } // 按 item 的顺序排列
  527. .first // 选择第一个,即最右边的 cell
  528. pastIndex = (rightMostCell?.item ?? (Int(showDocument?.pageCount ?? 1)))
  529. } else {
  530. // 找到最近右边的 cell
  531. let leftMostCell = currentRowItems.compactMap { collectionView.indexPath(for: $0) }
  532. .filter { indexPath in
  533. let cellRect = collectionView.layoutAttributesForItem(at: indexPath)?.frame
  534. return cellRect?.maxX ?? 0 < mouseX // 只选择左侧的 cell
  535. }
  536. .sorted { $0.item > $1.item } // 按 item 的逆序排列,以选择最近的左侧 cell
  537. .first // 选择第一个,即最近的左边的 cell
  538. pastIndex = (leftMostCell?.item ?? (Int(showDocument?.pageCount ?? 1)) - 1) + 1
  539. }
  540. } else {
  541. pastIndex = Int(showDocument?.pageCount ?? 0)
  542. }
  543. }
  544. let copyPages = KMNThumbnailManager.manager.copyPages
  545. insertFormPages(insertPages: copyPages, pageDex: pastIndex)
  546. }
  547. @objc public func cutMenuItemAciton() {
  548. if KMMemberInfo.shared.isLogin == false {
  549. KMLoginWindowsController.shared.showWindow(nil)
  550. return
  551. }
  552. KMNThumbnailManager.manager.copyPages = []
  553. let indexpaths = collectionView.selectionIndexPaths
  554. for indexpath in indexpaths.sorted() {
  555. guard let page = showDocument?.page(at: UInt(indexpath.item))?.copy() as? CPDFPage else {
  556. continue
  557. }
  558. KMNThumbnailManager.manager.copyDocument.append(showDocument ?? CPDFDocument())
  559. KMNThumbnailManager.manager.copyPages.append(page)
  560. }
  561. if indexpaths.count < 1 {
  562. _ = 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))
  563. return
  564. } else if indexpaths.count == (showDocument?.pageCount ?? 0) {
  565. _ = 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))
  566. return
  567. }
  568. deletePages(indexpaths: indexpaths)
  569. }
  570. @objc public func deleteMenuItemAciton() {
  571. if KMMemberInfo.shared.isLogin == false {
  572. KMLoginWindowsController.shared.showWindow(nil)
  573. return
  574. }
  575. let indexpaths = collectionView.selectionIndexPaths
  576. if indexpaths.count < 1 {
  577. _ = 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))
  578. return
  579. } else if indexpaths.count == (showDocument?.pageCount ?? 0) {
  580. _ = 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))
  581. return
  582. }
  583. deletePages(indexpaths: indexpaths)
  584. }
  585. @objc func sharePageItemAction(menuItem:NSMenuItem) {
  586. if IAPProductsManager.default().isAvailableAllFunction() == false {
  587. let winC = KMPurchaseCompareWindowController.sharedInstance()
  588. winC?.showWindow(nil)
  589. return
  590. }
  591. let indexpaths = collectionView.selectionIndexPaths
  592. let doucument = showDocument
  593. let filename : String = doucument?.documentURL.lastPathComponent ?? ""
  594. let folderPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(filename)) ?? ""
  595. try? FileManager.default.removeItem(atPath: folderPath)
  596. let pdfdocument = CPDFDocument()
  597. let ret = pdfdocument?.importPages(KMNTools.indexpathsToIndexs(indexpaths: indexpaths), from: doucument, at: 0) ?? false
  598. let url = URL(fileURLWithPath: folderPath)
  599. if ret {
  600. let success = pdfdocument?.write(toFile: folderPath)
  601. let represent = menuItem.representedObject as? NSSharingService
  602. represent?.perform(withItems: [url])
  603. }
  604. }
  605. @objc public func displayPageSizeAction() {
  606. let indexpaths = collectionView.selectionIndexPaths
  607. isShowPageSize = !isShowPageSize
  608. collectionView.selectionIndexPaths = indexpaths
  609. }
  610. private func insertFilePath(filePath:String,pdfPassword:String?) {
  611. var selectedIndexPaths = collectionView.selectionIndexPaths
  612. if(selectedIndexPaths.count <= 0) {
  613. selectedIndexPaths = pdfviewSelectionIndexPaths
  614. }
  615. let insertPDF = KMNPDFInsertPDFWindowController(showDocument, filePath: filePath, password: pdfPassword, selectionIndexPaths: selectedIndexPaths)
  616. insertPDF.pdfCallback = { [weak self] fileAttribute, insertIdx in
  617. let doc = fileAttribute.pdfDocument
  618. var insertPages: [CPDFPage] = []
  619. for number in fileAttribute.fetchSelectPages() {
  620. if let page = doc?.page(at: UInt(number-1)) {
  621. insertPages.append(page)
  622. }
  623. }
  624. self?.thumbnailBaseViewDelegate?.insertPDFThumbnailViewControlle?(pageEditVC: self, pdfDocment: doc)
  625. self?.insertFormPages(insertPages: insertPages, pageDex: insertIdx)
  626. }
  627. insertPDF.fileCallback = { [weak self] filePath, insertIdx in
  628. self?.insertFromFilePath(fileNames: [filePath], formDex: 0, indexDex: UInt(insertIdx), selectIndexs: [], completionBlock: { newSelectIndexs in
  629. })
  630. }
  631. insertPDF.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  632. }
  633. // MARK: - public
  634. func updateThumnailItem(updateIndexPaths: Set<IndexPath>,isSelect:Bool) {
  635. for targetIndexPath in updateIndexPaths {
  636. let cellView = collectionView.item(at: targetIndexPath) as? KMNThumbnailCollectionViewItem
  637. if(cellView != nil) {
  638. cellView?.thumbnailMode.removeCacheImage()
  639. }
  640. }
  641. collectionView.reloadItems(at: updateIndexPaths)
  642. if(isSelect) {
  643. if updateIndexPaths.isEmpty { return }
  644. let firstIndexPath = updateIndexPaths.first
  645. collectionView.scrollToItems(at: [firstIndexPath ?? IndexPath(item: 0, section: 0)], scrollPosition: .top)
  646. collectionView.selectionIndexPaths = updateIndexPaths
  647. }
  648. }
  649. func updateAllThumnailItems() {
  650. KMNThumbnailManager.clearCacheFilePath(filePath: showDocument?.documentURL.path ?? "")
  651. collectionView.reloadData()
  652. }
  653. @objc public func insertFromPDFAction() {
  654. if KMMemberInfo.shared.isLogin == false {
  655. KMLoginWindowsController.shared.showWindow(nil)
  656. return
  657. }
  658. let openPanel = NSOpenPanel()
  659. openPanel.allowedFileTypes = supportDragFileTypes()
  660. openPanel.allowsMultipleSelection = false
  661. openPanel.beginSheetModal(for: NSWindow.currentWindow()) {[weak self] result in
  662. if result == NSApplication.ModalResponse.OK {
  663. let fileURL = openPanel.url
  664. if(fileURL?.pathExtension == "pdf") {
  665. let pdfDoc = CPDFDocument(url: fileURL)
  666. if let data = pdfDoc?.isLocked, data {
  667. DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
  668. NSWindowController.checkPassword(url: fileURL ?? NSURL.fileURL(withPath: ""), type: .owner) { result, pwd in
  669. if (pwd.isEmpty == false) {
  670. self?.insertFilePath(filePath: fileURL?.path ?? "", pdfPassword: pwd)
  671. }
  672. }
  673. }
  674. } else {
  675. self?.insertFilePath(filePath: fileURL?.path ?? "", pdfPassword: nil)
  676. }
  677. } else {
  678. self?.insertFilePath(filePath: fileURL?.path ?? "", pdfPassword: nil)
  679. }
  680. }
  681. }
  682. }
  683. @objc public func insertFromBlankAction() {
  684. if KMMemberInfo.shared.isLogin == false {
  685. KMLoginWindowsController.shared.showWindow(nil)
  686. return
  687. }
  688. var selectedIndexPaths = collectionView.selectionIndexPaths
  689. if(selectedIndexPaths.count <= 0) {
  690. selectedIndexPaths = pdfviewSelectionIndexPaths
  691. }
  692. let insertPDF = KMNPDFInsertBlankWindowController(self.showDocument, selectionIndexPaths: selectedIndexPaths)
  693. insertPDF.callback = { [weak self] pageSize, insertIdx in
  694. self?.insertBlankSize(pageSize: pageSize, pageDex: insertIdx)
  695. }
  696. insertPDF.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  697. }
  698. public func insertFromClipboardAction() {
  699. if KMMemberInfo.shared.isLogin == false {
  700. KMLoginWindowsController.shared.showWindow(nil)
  701. return
  702. }
  703. var selectedIndexPaths = collectionView.selectionIndexPaths
  704. if(selectedIndexPaths.count <= 0) {
  705. selectedIndexPaths = [IndexPath(item: Int(showDocument?.pageCount ?? 1) - 1, section: 0)]
  706. }
  707. var maxmumIndex = 1
  708. if(selectedIndexPaths.count > 0) {
  709. let maxmumIndexPath = selectedIndexPaths.max(by: { $0 < $1 })
  710. maxmumIndex = (maxmumIndexPath?.item ?? 0) + 1
  711. }
  712. var error: NSError?
  713. guard let document: CPDFDocument = KMNConvertTool.openDocumentWithImageFromPasteboard(NSPasteboard.general, error: &error) else {
  714. return
  715. }
  716. var insetPages:[CPDFPage] = []
  717. for i in 0 ..< document.pageCount {
  718. let page: CPDFPage = (document.page(at: i))
  719. insetPages.append(page)
  720. }
  721. if insetPages.count > 0 {
  722. insertFormPages(insertPages: insetPages, pageDex: maxmumIndex)
  723. }
  724. self.thumbnailBaseViewDelegate?.insertPDFThumbnailViewControlle?(pageEditVC: self, pdfDocment: document)
  725. let ips: Set<IndexPath> = [IndexPath(item: maxmumIndex, section: 0)]
  726. refreshDatas()
  727. collectionView.selectionIndexPaths = ips
  728. collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  729. }
  730. public func insertFromScannerAction() {
  731. if KMMemberInfo.shared.isLogin == false {
  732. KMLoginWindowsController.shared.showWindow(nil)
  733. return
  734. }
  735. let selectedIndexPaths = collectionView.selectionIndexPaths
  736. let maxmumIndexPath = selectedIndexPaths.max(by: { $0 < $1 })
  737. let vc = KMDeviceBrowserWindowController.shared
  738. vc.type = .scanner
  739. vc.importScannerFileCallback = { [weak self] (url: NSURL) -> Void in
  740. if let imag = NSImage(contentsOfFile: url.path! ) {
  741. let index = (maxmumIndexPath?.item ?? 0) + 1
  742. _ = self?.showDocument?.km_insertPage(imag.size, withImage: url.path! , at:UInt(index))
  743. self?.reloadDatas()
  744. let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
  745. self?.collectionView.selectionIndexPaths = ips
  746. self?.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
  747. vc.close()
  748. }
  749. }
  750. vc.showWindow(nil)
  751. vc.window?.center()
  752. }
  753. public func canUndo()->Bool {
  754. return true
  755. }
  756. public func undoPDFAction() {
  757. currentUndoManager?.undo()
  758. }
  759. public func canRodo()->Bool {
  760. return true
  761. }
  762. public func redoPDFAction() {
  763. currentUndoManager?.redo()
  764. }
  765. @objc public func extractPDFAction() {
  766. if KMMemberInfo.shared.isLogin == false {
  767. KMLoginWindowsController.shared.showWindow(nil)
  768. return
  769. }
  770. let selectedIndexPaths = collectionView.selectionIndexPaths
  771. if selectedIndexPaths.count < 1 {
  772. _ = 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))
  773. return
  774. }
  775. let extractPDF = KMNExtractPDFWindowController(self.showDocument, selectionIndexPaths: collectionView.selectionIndexPaths)
  776. extractPDF.callback = { [weak self] oneDocumentPerPage, isDeletePage in
  777. extractPDF.own_closeEndSheet()
  778. if let _ = self?.showDocument {
  779. self?.extractPages(indexpaths: selectedIndexPaths, oneDocumentPerPage: oneDocumentPerPage, callback: { [weak self] result, params in
  780. if (result == .failure || result == .cancel) {
  781. return
  782. }
  783. if (isDeletePage) {
  784. self?.deletePages(indexpaths: selectedIndexPaths)
  785. }
  786. })
  787. }
  788. }
  789. extractPDF.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  790. }
  791. @objc public func replacePDFAction() {
  792. if KMMemberInfo.shared.isLogin == false {
  793. KMLoginWindowsController.shared.showWindow(nil)
  794. return
  795. }
  796. let selectedIndexPaths = collectionView.selectionIndexPaths
  797. if selectedIndexPaths.count < 1 {
  798. _ = 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))
  799. return
  800. }
  801. self.km_open_file_multi { [unowned self] index, params in
  802. if (self.fetchProgressBlockParamsIsPasswordFile(params: params)) { // 加密文档进度回调
  803. return
  804. }
  805. let tFileUrl = self.fetchProgressBlockParamsForFileUrl(params: params)
  806. let pdfExtensions = KMNConvertTool.supportPDFFileType()
  807. if let exn = tFileUrl?.pathExtension, pdfExtensions.contains(exn) {
  808. if (tFileUrl!.path.isPDFValid() == false) {
  809. let alert = NSAlert()
  810. alert.alertStyle = .critical
  811. alert.messageText = KMLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.")
  812. alert.runModal()
  813. }
  814. }
  815. } completionBlock: { [unowned self] documents in
  816. self.replacePages(of: selectedIndexPaths, with: documents)
  817. }
  818. }
  819. public func splitPDFAction() {
  820. if KMMemberInfo.shared.isLogin == false {
  821. KMLoginWindowsController.shared.showWindow(nil)
  822. return
  823. }
  824. let selectedIndexPaths = collectionView.selectionIndexPaths
  825. if collectionView.selectionIndexPaths.count < 1 {
  826. _ = 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))
  827. return
  828. }
  829. let splitPDF = KMNSplitPDFWindowController(self.showDocument,selectionIndexPaths: selectedIndexPaths)
  830. splitPDF.own_beginSheetModal(for: self.view.window, completionHandler: nil)
  831. }
  832. public func reversePDFAction() {
  833. if KMMemberInfo.shared.isLogin == false {
  834. KMLoginWindowsController.shared.showWindow(nil)
  835. return
  836. }
  837. let selectedIndexPaths = collectionView.selectionIndexPaths
  838. if selectedIndexPaths.count < 2 {
  839. _ = 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))
  840. return
  841. }
  842. reversePages(indexs:KMNTools.indexpathsToIndexs(indexpaths: selectedIndexPaths))
  843. }
  844. @objc public func rotatePageLeftAction() {
  845. if KMMemberInfo.shared.isLogin == false {
  846. KMLoginWindowsController.shared.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. @objc public func rotatePageRightAction() {
  856. if KMMemberInfo.shared.isLogin == false {
  857. KMLoginWindowsController.shared.showWindow(nil)
  858. return
  859. }
  860. if collectionView.selectionIndexPaths.count < 1 {
  861. _ = 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))
  862. return
  863. }
  864. rotatePages(indexPaths: collectionView.selectionIndexPaths, rotateAngle: 90)
  865. }
  866. public func deletePageAction() {
  867. if KMMemberInfo.shared.isLogin == false {
  868. KMLoginWindowsController.shared.showWindow(nil)
  869. return
  870. }
  871. let selectedIndexPaths = collectionView.selectionIndexPaths
  872. if selectedIndexPaths.count < 1 {
  873. _ = 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))
  874. return
  875. } else if selectedIndexPaths.count == (showDocument?.pageCount ?? 0) {
  876. _ = 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))
  877. return
  878. }
  879. deletePages(indexpaths: selectedIndexPaths)
  880. }
  881. // MARK: - private
  882. private func fetchProgressBlockParamsIsPasswordFile(params: Any...) -> Bool {
  883. if (params.count <= 2) {
  884. return false
  885. }
  886. return true
  887. }
  888. private func fetchProgressBlockParamsForFileUrl(params: Any...) -> URL? {
  889. if (params.count < 2) {
  890. return nil
  891. }
  892. return params[1] as? URL
  893. }
  894. private func km_open_file_multi(type: KMPasswordInputWindowType = .owner, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  895. NSPanel.km_open_multi_success(self.view.window!) { panel in
  896. var array: [String] = []
  897. for fileType in KMConvertPDFManager.supportFileType() {
  898. array.append(fileType)
  899. }
  900. panel.allowedFileTypes = KMNConvertTool.pdfExtensions + array
  901. } completion: { urls in
  902. self.km_add_file_multi(fileUrls: urls, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  903. }
  904. }
  905. private func km_add_file_multi(fileUrls: [URL] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  906. var pdfUrls: [URL] = []
  907. var imageUrls: [URL] = []
  908. var officeUrls: [URL] = []
  909. for url in fileUrls {
  910. let type = url.pathExtension.lowercased()
  911. if (KMNConvertTool.isPDFType(type)) {
  912. pdfUrls.append(url)
  913. }
  914. if (KMNConvertTool.isImageType(type)) {
  915. imageUrls.append(url)
  916. }
  917. if (KMNConvertTool.isOfficeType(type)) {
  918. officeUrls.append(url)
  919. }
  920. }
  921. if (officeUrls.count == 0) {
  922. self.km_add_pdf_multi(fileUrls: pdfUrls, type: type, progressBlock: progressBlock) { documents in
  923. var index = documents.count
  924. var _documents: [CPDFDocument] = []
  925. for imageUrl in imageUrls {
  926. index += 1
  927. let document = CPDFDocument()
  928. let image = NSImage(contentsOfFile: imageUrl.path)
  929. let _ = document?.km_insertPage(image?.size ?? .zero, withImage: imageUrl.path, at: 0)
  930. _documents.append(document!)
  931. if let _callback = progressBlock { // 回调进度
  932. _callback(index, document as Any, imageUrl)
  933. }
  934. }
  935. completionBlock(documents + _documents)
  936. }
  937. return
  938. }
  939. self.km_add_office_multi(fileUrls: officeUrls) { [unowned self] fileUrlStrings in
  940. var officeDocuments: [CPDFDocument] = []
  941. var index = 0
  942. for fileUrlString in fileUrlStrings {
  943. index += 1
  944. let document = CPDFDocument(url: URL(fileURLWithPath: fileUrlString))
  945. officeDocuments.append(document!)
  946. if let _callback = progressBlock { // 回调进度
  947. _callback(index, document as Any, URL(fileURLWithPath: fileUrlString))
  948. }
  949. }
  950. self.km_add_pdf_multi(fileUrls: pdfUrls) { documents in
  951. var index = documents.count + officeDocuments.count
  952. var _documents: [CPDFDocument] = []
  953. for imageUrl in imageUrls {
  954. index += 1
  955. let document = CPDFDocument()
  956. let image = NSImage(contentsOfFile: imageUrl.path)
  957. let _ = document?.km_insertPage(image!.size, withImage: imageUrl.path, at: 0)
  958. _documents.append(document!)
  959. if let _callback = progressBlock { // 回调进度
  960. _callback(index, document as Any, imageUrl)
  961. }
  962. }
  963. completionBlock(officeDocuments + documents + _documents)
  964. }
  965. }
  966. }
  967. private func km_add_pdf_multi(fileUrls: [URL] ,type: KMPasswordInputWindowType = .open, progressBlock: ((_ index: Int, _ params: Any...)->Void)? = nil, completionBlock:@escaping ([CPDFDocument])->Void) {
  968. var results: [CPDFDocument] = []
  969. self.lockedFiles.removeAll()
  970. var index = 0
  971. for url in fileUrls {
  972. let document = CPDFDocument(url: url)
  973. if (document!.isLocked) {
  974. self.lockedFiles.append(url)
  975. continue
  976. }
  977. if let _document = document {
  978. results.append(_document)
  979. }
  980. index += 1
  981. if let _callback = progressBlock {
  982. _callback(index, ((document != nil) ? document : CPDFDocument()) as Any, url)
  983. }
  984. }
  985. if (self.lockedFiles.count == 0) {
  986. completionBlock(results)
  987. return
  988. }
  989. self._openPasswordWindow_loop(fileUrl: self.lockedFiles.first!, type: type) { params in
  990. index += 1
  991. if (params.count <= 2) { // 参数错误
  992. if let _callback = progressBlock { // 回调进度
  993. _callback(index)
  994. }
  995. return
  996. }
  997. let fileUrl = params[0] as! URL
  998. let result = params[1] as! KMPasswordInputWindowResult
  999. let password = params[2] as? String
  1000. if (result == .cancel) {
  1001. if let _callback = progressBlock { // 回调进度
  1002. _callback(index, CPDFDocument() as Any, fileUrl, result)
  1003. }
  1004. return
  1005. }
  1006. let document = CPDFDocument(url: fileUrl)
  1007. if let _password = password { // 将文档进行解密
  1008. document?.unlock(withPassword: _password)
  1009. }
  1010. if let _callback = progressBlock { // 回调进度
  1011. _callback(index, document as Any, fileUrl, result, password as Any)
  1012. }
  1013. // 将文档加入返回数据
  1014. if let _document = document {
  1015. results.append(_document)
  1016. }
  1017. } completionBlock: {
  1018. completionBlock(results)
  1019. }
  1020. }
  1021. private func km_add_office_multi(fileUrls: [URL], completionBlock:@escaping ([String])->Void) -> Void {
  1022. var fileUrlStrings: [String] = []
  1023. let dispatchGroup = Dispatch.DispatchGroup()
  1024. for (index, fileUrl) in fileUrls.enumerated() {
  1025. let filePath = fileUrl.path
  1026. let folderPath = "convertToPDF_\(index).pdf"
  1027. let savePath: String? = folderPath.kUrlToPDFFolderPath() as String
  1028. if (savePath == nil) {
  1029. continue
  1030. }
  1031. dispatchGroup.enter()
  1032. KMConvertPDFManager.convertFile(filePath, savePath: savePath!) { success, errorDic in
  1033. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  1034. dispatchGroup.leave()
  1035. if FileManager.default.fileExists(atPath: savePath!) {
  1036. try?FileManager.default.removeItem(atPath: savePath!)
  1037. }
  1038. let alert = NSAlert.init()
  1039. alert.alertStyle = .critical
  1040. var infoString = ""
  1041. if errorDic != nil {
  1042. for key in (errorDic! as Dictionary).keys {
  1043. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  1044. }
  1045. }
  1046. alert.informativeText = KMLocalizedString("Please install Microsoft Office to create PDFs from Office files")
  1047. alert.messageText = KMLocalizedString("Failed to Create PDF", comment: "")
  1048. alert.addButton(withTitle: KMLocalizedString("OK"))
  1049. alert.runModal()
  1050. return
  1051. }
  1052. if !savePath!.isPDFValid() {
  1053. dispatchGroup.leave()
  1054. let alert = NSAlert()
  1055. alert.alertStyle = .critical
  1056. alert.messageText = KMLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.")
  1057. alert.runModal()
  1058. return
  1059. }
  1060. fileUrlStrings.append(savePath!)
  1061. dispatchGroup.leave()
  1062. }
  1063. }
  1064. dispatchGroup.notify(queue: DispatchQueue.main) {
  1065. completionBlock(fileUrlStrings)
  1066. }
  1067. }
  1068. fileprivate func _openPasswordWindow_loop(fileUrl: URL, type: KMPasswordInputWindowType, progressBlock: ((_ params: Any...)->Void)?, completionBlock:@escaping ()->Void) {
  1069. KMPasswordInputWindow.openWindow(window: self.view.window!, type: type, url: fileUrl) { [weak self] result, password in
  1070. // 将结果返回
  1071. if let _callback = progressBlock {
  1072. _callback(fileUrl, result, password as Any)
  1073. }
  1074. // 进行下一个
  1075. self?.lockedFiles.removeFirst()
  1076. if let _fileUrl = self?.lockedFiles.first {
  1077. self?._openPasswordWindow_loop(fileUrl: _fileUrl, type: type, progressBlock: progressBlock, completionBlock: completionBlock)
  1078. } else {
  1079. completionBlock()
  1080. }
  1081. }
  1082. }
  1083. }