KMHomeViewController+Action.swift 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  1. //
  2. // KMHomeViewController+Action.swift
  3. // PDF Office
  4. //
  5. // Created by wanjun on 2022/10/13.
  6. //
  7. import Foundation
  8. extension KMHomeViewController: NSMenuItemValidation {
  9. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  10. if (menuItem.action == #selector(menuItemAction_currentWindowName)) {
  11. menuItem.title = NSLocalizedString("Home", comment: "")
  12. return true
  13. }
  14. return true
  15. }
  16. }
  17. extension KMHomeViewController {
  18. // MARK: Action
  19. @objc func homeToolAction(_ sender: NSButton) -> Void {
  20. if sender == homeButtonVC.button {
  21. homeToolAction(homeToolState: KMHomeToolState.Home)
  22. } else if sender == pdfToolsButtonVC.button {
  23. homeToolAction(homeToolState: KMHomeToolState.PDFTools)
  24. } else if sender == cloudDocumentsButtonVC.button {
  25. homeToolAction(homeToolState: KMHomeToolState.CloudDocuments)
  26. } else if sender == openPDFButtonVC.button {
  27. homeToolAction(homeToolState: KMHomeToolState.OpenPDF)
  28. } else if sender == createPDFButtonVC.button {
  29. openSupportPDFButtonAction()
  30. } else if sender == createPDFImage.button {
  31. homeToolAction(homeToolState: KMHomeToolState.CreatePDF)
  32. }
  33. }
  34. func homeToolAction(homeToolState: KMHomeToolState) {
  35. switch homeToolState {
  36. case .OpenPDF:
  37. openPDFButtonAction()
  38. break
  39. case .CreatePDF:
  40. createPDFButtonAction()
  41. break
  42. case .Home:
  43. homeButtonAction()
  44. break
  45. case .PDFTools:
  46. pdfToolsButtonAction()
  47. break
  48. case .FavoriteDocuments:
  49. favoriteDocumentsButtonAction()
  50. break
  51. case .CloudDocuments:
  52. cloudDocumentsButtonAction()
  53. break
  54. default:
  55. print("error: 错误的传入枚举")
  56. break
  57. }
  58. }
  59. func fastToolItemAction(_ type: DataNavigationViewButtonActionType) {
  60. switch type {
  61. case .Batch:
  62. fastTool_Batch()
  63. break
  64. case .OCR:
  65. fastTool_OCR()
  66. break
  67. case .ConvertPDF:
  68. fastTool_ConvertPDF()
  69. break
  70. case .ImageToPDF:
  71. fastTool_ImageToPDF()
  72. break
  73. case .MergePDF:
  74. fastTool_MergePDF()
  75. break
  76. case .Compression:
  77. fastTool_Compression()
  78. break
  79. case .Security:
  80. fastTool_Security()
  81. break
  82. case .FileCompare:
  83. fastTool_FileCompare()
  84. break
  85. case .PDFToPPT:
  86. fastTool_PDFToPPT()
  87. break
  88. case .PDFToExcel:
  89. fastTool_PDFToExcel()
  90. break
  91. case .PDFToWord:
  92. fastTool_PDFToWord()
  93. break
  94. case .PDFToImage:
  95. fastTool_PDFToImage()
  96. break
  97. case .Watermark:
  98. fastTool_Watermark()
  99. break
  100. case .Background:
  101. fastTool_Background()
  102. break
  103. case .HeaderAndFooter:
  104. fastTool_HeaderAndFooter()
  105. break
  106. case .BatesCode:
  107. fastTool_BatesCode()
  108. break
  109. case .Print:
  110. fastTool_Print()
  111. break
  112. case .BatchRemove:
  113. fastTool_BatchRemove()
  114. break
  115. case .Insert:
  116. fastTool_Insert()
  117. break
  118. case .BreakUp:
  119. fastTool_BreakUp()
  120. break
  121. case .Extract:
  122. fastTool_Extract()
  123. break
  124. case .MarkCipher:
  125. fastTool_MarkCipher()
  126. break
  127. case .AutomaticFormRecognition:
  128. fastTool_AutomaticFormRecognition()
  129. break
  130. case .PageEdit:
  131. fastTool_PageEdit()
  132. break
  133. }
  134. }
  135. func openPDFButtonAction() {
  136. let openPanel = NSOpenPanel()
  137. openPanel.allowedFileTypes = ["pdf", "PDF"]
  138. openPanel.allowsMultipleSelection = true
  139. openPanel.beginSheetModal(for: self.view.window!) { result in
  140. if result == .OK {
  141. for url in openPanel.urls {
  142. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  143. if error != nil {
  144. NSApp.presentError(error!)
  145. } else {
  146. }
  147. }
  148. }
  149. }
  150. }
  151. }
  152. func openSupportPDFButtonAction() {
  153. let openPanel = NSOpenPanel()
  154. openPanel.allowedFileTypes = ["pdf", "PDF", "jpg", "cur", "bmp", "jpeg", "gif", "png", "tiff", "tif", "ico", "icns", "tga", "psd", "eps", "hdr", "jp2", "jpc", "pict", "sgi", "heic", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pptx"]
  155. openPanel.allowsMultipleSelection = true
  156. openPanel.beginSheetModal(for: self.view.window!) { [self] result in
  157. if result == .OK {
  158. var imageUrl: [URL] = []
  159. for url in openPanel.urls {
  160. let type = url.pathExtension.lowercased()
  161. if (type == "pdf" || type == "PDF") {
  162. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  163. }
  164. } else if (type == "jpg") ||
  165. (type == "cur") ||
  166. (type == "bmp") ||
  167. (type == "jpeg") ||
  168. (type == "gif") ||
  169. (type == "png") ||
  170. (type == "tiff") ||
  171. (type == "tif") ||
  172. (type == "ico") ||
  173. (type == "icns") ||
  174. (type == "tga") ||
  175. (type == "psd") ||
  176. (type == "eps") ||
  177. (type == "hdr") ||
  178. (type == "jp2") ||
  179. (type == "jpc") ||
  180. (type == "pict") ||
  181. (type == "sgi") ||
  182. (type == "heic") {
  183. openImageFile(url: url)
  184. } else if (type == "doc") ||
  185. (type == "docx") ||
  186. (type == "xls") ||
  187. (type == "xlsx") ||
  188. (type == "ppt") ||
  189. (type == "pptx") ||
  190. (type == "pptx") {
  191. self.openOfficeFile(url: url)
  192. }
  193. }
  194. }
  195. }
  196. }
  197. func createPDFButtonAction() {
  198. let popViewDataArr = [NSLocalizedString("New Blank Page", comment: ""),
  199. // NSLocalizedString("New From Web Page", comment: ""),
  200. NSLocalizedString("Import From Scanner", comment: "")]
  201. createPopoverAction(popViewDataArr)
  202. }
  203. func homeButtonAction() {
  204. refreshRightBoxUI(.Home)
  205. }
  206. func pdfToolsButtonAction() {
  207. refreshRightBoxUI(.PDFTools)
  208. }
  209. func favoriteDocumentsButtonAction() {
  210. print("Favorite Documents")
  211. }
  212. func cloudDocumentsButtonAction() {
  213. refreshRightBoxUI(.CloudDocuments)
  214. }
  215. // 产品推广
  216. func productPromotionFoldOrUnfold(_ sender: NSButton) {
  217. var arr1: [NSString] = []
  218. var arr2: [NSString] = []
  219. if sender.isEqual(to: pdfSeriesButtonVC.button) {
  220. if self.pdfProSeriesBoxHeightConstraint.constant == 0 {
  221. arr1 = self.productPromotionPDFProSeries as! [NSString]
  222. }
  223. if self.othersBoxHeightConstraint.constant > 0 {
  224. arr2 = self.productPromotionOthers as! [NSString]
  225. }
  226. }
  227. if sender.isEqual(to: self.pdfOthersButtonVC.button) {
  228. if self.pdfProSeriesBoxHeightConstraint.constant > 0 {
  229. arr1 = self.productPromotionPDFProSeries as! [NSString]
  230. }
  231. if self.othersBoxHeightConstraint.constant == 0 {
  232. arr2 = self.productPromotionOthers as! [NSString]
  233. }
  234. }
  235. self.productPromotionShow(arr1 as NSArray, withOthers: arr2 as NSArray, isInitialize: false)
  236. refreshProductActiveSpacing()
  237. }
  238. func productPromotionClickAction(_ name: NSString) {
  239. var httpString: NSString = ""
  240. if name.isEqual(to: "Windows") {
  241. httpString = "https://www.pdfreaderpro.com/windows?utm_source=MacApp&utm_campaign=PDFProMac&utm_medium=pdfmac_promo"
  242. } else if name.isEqual(to: "iPhone / iPad") {
  243. #if VERSION_FREE
  244. #if VERSION_DMG
  245. httpString = "https://www.pdfreaderpro.com/product?utm_source=MacAppDmg&utm_campaign=ProductLinkLeftNav&utm_medium=PdfProduct"
  246. #else
  247. httpString = "https://www.pdfreaderpro.com/product?utm_source=MacAppLite&utm_campaign=ProductLinkLeftNav&utm_medium=PdfProduct"
  248. #endif
  249. #else
  250. httpString = "https://www.pdfreaderpro.com/product?utm_source=MacApp&utm_campaign=ProductLinkLeftNav&utm_medium=PdfProduct"
  251. #endif
  252. } else if name.isEqual(to: "Android") {
  253. httpString = "https://www.pdfreaderpro.com/pdfreaderpro-android?utm_source=MacAppDmg&utm_campaign=AndroidLink&utm_medium=PdfAndroid"
  254. } else if name.isEqual(to: "ComPDFKit") {
  255. httpString = "https://www.compdf.com?utm_source=macapp&utm_medium=pdfmac&utm_campaign=compdfkit-promp"
  256. } else if name.isEqual(to: "ComVideoKit") {
  257. httpString = "https://www.filmagepro.com/video-sdk?utm_source=macapp&utm_medium=pdfmac&utm_campaign=comvideosdk-promo"
  258. } else if name.isEqual(to: "SignFlow") {
  259. httpString = "https://apps.apple.com/app/apple-store/id1584624017?pt=118745145&ct=pdfmac-promo&mt=8"
  260. } else if name.isEqual(to: "FiImage Editor") {
  261. httpString = "https://apps.apple.com/app/apple-store/id1475051178?pt=118745145&ct=pdfmac-promo&mt=8"
  262. } else if name.isEqual(to: "FiImage Screen") {
  263. httpString = "https://apps.apple.com/app/apple-store/id1475049179?pt=118745145&ct=pdfmac-promo&mt=8"
  264. } else if name.isEqual(to: "Free PDF Templates") {
  265. httpString = "https://www.pdfreaderpro.com/templates?utm_source=MacApp&utm_campaign=PDFProMac&utm_medium=pdfmac_promo"
  266. }
  267. self.workSpaceOpenUrl(httpString)
  268. }
  269. func historyFile(deleteDocuments indexPaths: [URL]) {
  270. if UserDefaults.standard.bool(forKey: "kHistoryDeleteNOReminderKey") {
  271. historyFileDeleteAction(indexPaths)
  272. } else {
  273. let historyFileDeleteVC: KMHistoryFileDeleteWindowController = KMHistoryFileDeleteWindowController.init(windowNibName: NSNib.Name("KMHistoryFileDeleteWindowController"))
  274. historyFileDeleteVC.indexPaths = indexPaths
  275. historyFileDeleteVC.deleteCallback = { [self](indexPaths: [URL], windowController: KMHistoryFileDeleteWindowController) -> Void in
  276. historyFileDeleteAction(indexPaths)
  277. }
  278. self.view.window?.beginSheet(historyFileDeleteVC.window!)
  279. }
  280. }
  281. func historyFileDeleteAction(_ indexPaths: [URL]) -> Void {
  282. NSDocumentController.shared.clearRecentDocuments(nil)
  283. historyFileViewController.reloadData()
  284. }
  285. func openHistoryFilePath(url: URL) -> Void {
  286. if url.pathExtension.lowercased() == "pdf" {
  287. let pdfDoc = CPDFDocument.init(url: url)
  288. if pdfDoc != nil {
  289. if ((pdfDoc?.isLocked)! == true) {
  290. KMPasswordInputWindow.openWindow(window: self.view.window!, url: url) { result, password in
  291. if result == .cancel { /// 关闭
  292. return
  293. }
  294. /// 解密成功
  295. let document = NSDocumentController.shared.document(for: url)
  296. var selectDocument: KMMainDocument? = nil
  297. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  298. selectDocument = (document as! KMMainDocument)
  299. }
  300. if selectDocument != nil {
  301. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  302. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  303. if (selectDocument?.browser.window.isVisible)! as Bool {
  304. selectDocument?.browser.window.orderFront(nil)
  305. } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  306. selectDocument?.browser.window.orderFront(nil)
  307. }
  308. } else {
  309. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  310. if error != nil {
  311. NSApp.presentError(error!)
  312. return
  313. }
  314. (document as! KMMainDocument).mainViewController.listView.document.unlock(withPassword: password)
  315. }
  316. }
  317. }
  318. return
  319. }
  320. let document = NSDocumentController.shared.document(for: url)
  321. var selectDocument: KMMainDocument? = nil
  322. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  323. selectDocument = (document as! KMMainDocument)
  324. }
  325. if selectDocument != nil {
  326. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  327. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  328. if (selectDocument?.browser.window.isVisible)! as Bool {
  329. selectDocument?.browser.window.orderFront(nil)
  330. } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  331. selectDocument?.browser.window.orderFront(nil)
  332. }
  333. } else {
  334. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  335. if error != nil {
  336. NSApp.presentError(error!)
  337. return
  338. }
  339. }
  340. }
  341. } else {
  342. let alert = NSAlert()
  343. alert.alertStyle = .critical
  344. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  345. alert.runModal()
  346. }
  347. } else {
  348. NSWorkspace.shared.open(url)
  349. }
  350. }
  351. func openFile(withFilePath path: URL) -> Void {
  352. let type = path.pathExtension.lowercased()
  353. if (type == "pdf") {
  354. NSDocumentController.shared.openDocument(withContentsOf: path, display: true) { document, documentWasAlreadyOpen, error in
  355. }
  356. } else if (type == "jpg") ||
  357. (type == "cur") ||
  358. (type == "bmp") ||
  359. (type == "jpeg") ||
  360. (type == "gif") ||
  361. (type == "png") ||
  362. (type == "tiff") ||
  363. (type == "tif") ||
  364. (type == "ico") ||
  365. (type == "icns") ||
  366. (type == "tga") ||
  367. (type == "psd") ||
  368. (type == "eps") ||
  369. (type == "hdr") ||
  370. (type == "jp2") ||
  371. (type == "jpc") ||
  372. (type == "pict") ||
  373. (type == "sgi") ||
  374. (type == "heic") {
  375. openImageFile(url: path)
  376. } else if (type == "doc") ||
  377. (type == "docx") ||
  378. (type == "xls") ||
  379. (type == "xlsx") ||
  380. (type == "ppt") ||
  381. (type == "pptx") ||
  382. (type == "pptx") {
  383. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  384. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  385. openOfficeFile(url: path)
  386. }
  387. }
  388. func openImageFile(url: URL) -> Void {
  389. let filePath = url.path
  390. let fileName: NSString = url.lastPathComponent as NSString
  391. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath()).deletingLastPathComponent
  392. let imageName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension
  393. let path = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".pdf")
  394. let document = CPDFDocument.init()
  395. var success = false
  396. //FIXME: 无法插入图片
  397. let image = NSImage(contentsOfFile: filePath)
  398. let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount)
  399. if insertPageSuccess != nil {
  400. //信号量控制异步
  401. let semaphore = DispatchSemaphore(value: 0)
  402. DispatchQueue.global().async {
  403. success = ((document?.write(toFile: path)) != nil)
  404. semaphore.signal()
  405. }
  406. semaphore.wait()
  407. } else {
  408. }
  409. if success {
  410. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { document, documentWasAlreadyOpen, error in
  411. }
  412. }
  413. }
  414. func openOfficeFile(url: URL) -> Void {
  415. let filePath = url.path
  416. let folderPath = "convertToPDF.pdf"
  417. let savePath = folderPath.kUrlToPDFFolderPath()
  418. if savePath == nil {
  419. return
  420. }
  421. KMConvertPDFManagerOC.convertFile(filePath, savePath: savePath!) { success, errorDic in
  422. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  423. if FileManager.default.fileExists(atPath: savePath!) {
  424. try?FileManager.default.removeItem(atPath: savePath!)
  425. }
  426. let alert = NSAlert.init()
  427. alert.alertStyle = .critical
  428. var infoString = ""
  429. if errorDic != nil {
  430. for key in (errorDic! as Dictionary).keys {
  431. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  432. }
  433. }
  434. alert.informativeText = infoString
  435. alert.messageText = NSLocalizedString("Conversion Failed", comment: "")
  436. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  437. alert.runModal()
  438. return
  439. }
  440. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath!), display: true) { document, documentWasAlreadyOpen, error in
  441. }
  442. }
  443. }
  444. override func keyDown(with event: NSEvent) -> Void {
  445. if event.keyCode == 53 { // esc
  446. self.historyFileViewController.selectFiles.removeAll()
  447. if self.historyFileViewController.showMode == .Thumbnail {
  448. self.historyFileViewController.historyFileCollectionView.reloadData()
  449. } else {
  450. self.historyFileViewController.historyFileTableView.reloadData()
  451. }
  452. }
  453. }
  454. override func otherMouseDown(with event: NSEvent) {
  455. if historyFileViewController.selectFiles.count > 0 {
  456. let eventPoint = event.locationInWindow as NSPoint
  457. let x = eventPoint.x - 270.0
  458. if x >= 0 {
  459. let point = NSPoint(x: x, y: eventPoint.y)
  460. if historyFileViewController.historyFileCollectionView.frame.contains(point) ||
  461. historyFileViewController.historyFileTableView.frame.contains(point) {
  462. } else {
  463. self.historyFileViewController.selectFiles.removeAll()
  464. if self.historyFileViewController.showMode == .Thumbnail {
  465. self.historyFileViewController.historyFileCollectionView.reloadData()
  466. } else {
  467. self.historyFileViewController.historyFileTableView.reloadData()
  468. }
  469. }
  470. } else {
  471. self.historyFileViewController.selectFiles.removeAll()
  472. if self.historyFileViewController.showMode == .Thumbnail {
  473. self.historyFileViewController.historyFileCollectionView.reloadData()
  474. } else {
  475. self.historyFileViewController.historyFileTableView.reloadData()
  476. }
  477. }
  478. }
  479. }
  480. // MARK: PDF Tools
  481. // 插入
  482. func insertPageAction(_ pdfDocument: CPDFDocument, _ password: String, _ pages: [CPDFPage], _ indexPage: Int) -> Void {
  483. if indexPage >= 0 {
  484. let insertPages: [CPDFPage] = pages
  485. for i in 0...insertPages.count-1 {
  486. let page = pages[i]
  487. // FIXME: 待底层库修改,使用 insertPageObject 插入,插入位置变为文档最后,暂用 insertPage 代替
  488. pdfDocument.insertPageObject(page, at: UInt(indexPage + i))
  489. }
  490. self.savePDFDocument(pdfDocument, password: password)
  491. }
  492. }
  493. func extractPageAction(_ pdfDocument: CPDFDocument, _ pages: [CPDFPage], _ oneDocumentPerPage: Bool, _ isDeletePage: Bool) -> Void {
  494. if pages.count < 1 {
  495. let alert = NSAlert()
  496. alert.alertStyle = .critical
  497. alert.messageText = NSLocalizedString("Please select two or more pages first to organize.", comment: "")
  498. alert.runModal()
  499. return
  500. }
  501. if !oneDocumentPerPage {
  502. let fileName = pdfDocument.getFileNameAccordingSelctPages(pages)
  503. let outputSavePanel = NSSavePanel()
  504. outputSavePanel.allowedFileTypes = ["pdf"]
  505. outputSavePanel.nameFieldStringValue = fileName
  506. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  507. if result == .OK {
  508. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  509. let saveFilePath = outputSavePanel.url?.path
  510. DispatchQueue.global().async {
  511. var pdf = CPDFDocument.init()
  512. let success = (pdf!.extractAsOneDocument(withPages: pages, savePath: saveFilePath)) as Bool
  513. DispatchQueue.main.async {
  514. if success {
  515. let workspace = NSWorkspace.shared
  516. let url = URL(fileURLWithPath: saveFilePath!)
  517. workspace.activateFileViewerSelecting([url])
  518. if isDeletePage {
  519. for page in pages {
  520. let indexPage = pdfDocument.index(for: page)
  521. pdfDocument.removePage(at: indexPage)
  522. }
  523. }
  524. }
  525. }
  526. }
  527. }
  528. }
  529. }
  530. } else {
  531. let panel = NSOpenPanel()
  532. panel.canChooseFiles = false
  533. panel.canChooseDirectories = true
  534. panel.canCreateDirectories = true
  535. panel.allowsMultipleSelection = false
  536. panel.beginSheetModal(for: self.view.window!) { result in
  537. if result == .OK {
  538. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  539. let outputURL = panel.url
  540. DispatchQueue.global().async {
  541. let folderName = String(pdfDocument.documentURL!.lastPathComponent.split(separator: ".")[0]) + "_extract"
  542. var filePath = URL(fileURLWithPath: outputURL!.path).appendingPathComponent(folderName).path
  543. var i = 1
  544. let testFilePath = filePath
  545. while FileManager.default.fileExists(atPath: filePath) {
  546. filePath = testFilePath + "\(i)"
  547. i += 1
  548. }
  549. try? FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
  550. let successArray = pdfDocument.extractPerPageDocument(withPages: pages, folerPath: filePath)
  551. DispatchQueue.main.async {
  552. if successArray!.count > 0 {
  553. NSWorkspace.shared.activateFileViewerSelecting(successArray!)
  554. if !isDeletePage {
  555. for page in pages {
  556. let indexPage = pdfDocument.index(for: page)
  557. pdfDocument.removePage(at: indexPage)
  558. }
  559. }
  560. }
  561. }
  562. }
  563. }
  564. }
  565. }
  566. }
  567. }
  568. // MARK: 快捷工具 Action
  569. func fastToolDidSelectAllTools() {
  570. // 首页 快捷工具 Tools按钮
  571. refreshRightBoxUI(.PDFTools)
  572. }
  573. func fastTool_Batch() { // Batch
  574. // KMBatchWindowController.openFile(nil, .Batch)
  575. }
  576. func fastTool_OCR() { // OCR
  577. // KMOCRWindowController.openFiles(window: self.view.window!)
  578. }
  579. func fastTool_ConvertPDF() { // 转换PDF
  580. // KMBatchWindowController.openFile(nil, .ConvertPDF)
  581. }
  582. func fastTool_ImageToPDF() { // 图片转PDF
  583. print("选中 快捷工具 图片转PDF")
  584. KMImageToPDFWindowController.openFiles(window: NSApp.mainWindow!)
  585. }
  586. func fastTool_MergePDF() { // MergePDF
  587. let panel = NSOpenPanel()
  588. panel.allowedFileTypes = ["pdf"]
  589. panel.allowsMultipleSelection = true
  590. panel.beginSheetModal(for: self.view.window!) { response in
  591. if (response == .cancel) {
  592. return
  593. }
  594. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  595. var filepaths: Array<String> = []
  596. for url in panel.urls {
  597. filepaths.append(url.path)
  598. }
  599. let windowController = KMPDFEditAppendWindow(filePaths: filepaths)
  600. self.currentWindowController = windowController
  601. windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, indexs in
  602. })
  603. }
  604. }
  605. }
  606. func fastTool_Compression() { // 压缩
  607. NSOpenPanel.km_secure_openPanel(window: self.view.window!) { url, result, passowrd in
  608. if (url == nil) {
  609. return
  610. }
  611. if (result != nil && result! == .cancel) {
  612. return
  613. }
  614. self.showCompressWindow(url!, passowrd)
  615. }
  616. }
  617. func showCompressWindow(_ url: URL, _ password: String?) {
  618. let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  619. self.view.window?.beginSheet(windowController.window!)
  620. self.currentWindowController = windowController
  621. windowController.documentURL = url
  622. windowController.password = password
  623. windowController.itemClick = { [weak self] (index: Int) -> () in
  624. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  625. self?.currentWindowController = nil
  626. }
  627. windowController.resultCallback = { [weak self] (result: Bool, openDocument: Bool, fileURL: URL, error: String) in
  628. if result {
  629. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  630. self?.currentWindowController = nil
  631. if openDocument {
  632. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in }
  633. } else {
  634. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  635. }
  636. } else {
  637. let alert = NSAlert()
  638. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  639. alert.runModal()
  640. }
  641. }
  642. }
  643. func fastTool_Security() { // 安全
  644. NSOpenPanel.km_secure_openPanel(window: self.view.window!, needOwner: true) { url, result, passowrd in
  645. if (url == nil) {
  646. return
  647. }
  648. if (result != nil && result! == .cancel) {
  649. return
  650. }
  651. let windowController = KMSecureEncryptWindowController(windowNibName: "KMSecureEncryptWindowController")
  652. windowController.documentURL = url!
  653. windowController.myDocument = CPDFDocument(url: url!)
  654. if (passowrd != nil) {
  655. windowController.myDocument.unlock(withPassword: passowrd)
  656. }
  657. self.currentWindowController = windowController
  658. let newDocument: CPDFDocument = CPDFDocument(url: url!)
  659. windowController.itemClick = { [weak self] (index: Int) -> () in
  660. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  661. self?.currentWindowController = nil
  662. }
  663. windowController.resultCallback = { [weak self] (result: Bool) -> () in
  664. let windowController_secure: KMSecureEncryptWindowController = self?.currentWindowController as! KMSecureEncryptWindowController
  665. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  666. self!.currentWindowController = nil
  667. if (passowrd != nil) {
  668. newDocument.unlock(withPassword: passowrd)
  669. }
  670. newDocument.setPasswordOptions(windowController_secure.options)
  671. let result = KMPasswordInputWindow.saveDocument(newDocument)
  672. if result {
  673. NSWorkspace.shared.activateFileViewerSelecting([newDocument.documentURL])
  674. } else {
  675. let alert = NSAlert()
  676. alert.messageText = NSLocalizedString("Failure", comment: "")
  677. alert.runModal()
  678. }
  679. }
  680. self.view.window?.beginSheet(windowController.window!)
  681. }
  682. }
  683. func fastTool_FileCompare() { // 文件对比
  684. print("选中 快捷工具 文件对比")
  685. }
  686. func fastTool_PDFToPPT() { // PDF转PPT
  687. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  688. let windowController = KMConvertPPTsWindowController(windowNibName: "KMConvertBaseWindowController")
  689. let model = KMDocumentModel()
  690. windowController.subType = 1
  691. model.documentURL = url
  692. if (password != nil) {
  693. model.password = password!
  694. }
  695. windowController.documentModel = model
  696. windowController.itemClick = { [weak self] (index: Int) in
  697. if (self!.currentWindowController == nil) {
  698. return
  699. }
  700. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  701. self?.currentWindowController = nil
  702. }
  703. self.view.window?.beginSheet(windowController.window!)
  704. self.currentWindowController = windowController
  705. }
  706. }
  707. func fastTool_PDFToExcel() { // PDF转Excel
  708. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  709. let windowController = KMConvertExcelWindowController(windowNibName: "KMConvertBaseWindowController")
  710. let model = KMDocumentModel()
  711. model.documentURL = url
  712. if (password != nil) {
  713. model.password = password!
  714. }
  715. windowController.documentModel = model
  716. windowController.itemClick = { [weak self] (index: Int) in
  717. if (self!.currentWindowController == nil) {
  718. return
  719. }
  720. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  721. self?.currentWindowController = nil
  722. }
  723. self.view.window?.beginSheet(windowController.window!)
  724. self.currentWindowController = windowController
  725. }
  726. }
  727. func fastTool_PDFToWord() { // PDF转Word
  728. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  729. let windowController = KMConvertWordWindowController(windowNibName: "KMConvertBaseWindowController")
  730. let model = KMDocumentModel()
  731. model.documentURL = url
  732. if (password != nil) {
  733. model.password = password!
  734. }
  735. windowController.documentModel = model
  736. windowController.itemClick = { [weak self] (index: Int) in
  737. if (self!.currentWindowController == nil) {
  738. return
  739. }
  740. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  741. self?.currentWindowController = nil
  742. }
  743. self.view.window?.beginSheet(windowController.window!)
  744. self.currentWindowController = windowController
  745. }
  746. }
  747. func fastTool_PDFToImage() { // PDF转图片
  748. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  749. let windowController = KMConvertImageWindowController(windowNibName: "KMConvertBaseWindowController")
  750. let model = KMDocumentModel()
  751. model.documentURL = url
  752. if (password != nil) {
  753. model.password = password!
  754. }
  755. windowController.documentModel = model
  756. windowController.itemClick = { [weak self] (index: Int) in
  757. if (self!.currentWindowController == nil) {
  758. return
  759. }
  760. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  761. self?.currentWindowController = nil
  762. }
  763. self.view.window?.beginSheet(windowController.window!)
  764. self.currentWindowController = windowController
  765. }
  766. }
  767. func fastTool_Watermark() { // 水印
  768. KMBatchWindowController.openFile(nil, .Watermark)
  769. }
  770. func fastTool_Background() { // 背景
  771. KMBatchWindowController.openFile(nil, .Background)
  772. }
  773. func fastTool_HeaderAndFooter() { // 页眉页脚
  774. KMBatchWindowController.openFile(nil, .HeaderAndFooter)
  775. }
  776. func fastTool_BatesCode() { // 贝茨码
  777. KMBatchWindowController.openFile(nil, .BatesCode)
  778. }
  779. func fastTool_Print() { // 打印
  780. KMPrintWindowController.openFiles(window: self.view.window!)
  781. }
  782. func fastTool_BatchRemove() { // 批量移除
  783. KMBatchWindowController.openFile(nil, .BatchRemove)
  784. }
  785. func fastTool_Insert() { // 插入
  786. let openPanel = NSOpenPanel()
  787. openPanel.prompt = "插入"
  788. openPanel.allowsMultipleSelection = false
  789. openPanel.allowedFileTypes = ["pdf"]
  790. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  791. if result == .OK {
  792. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  793. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Insert)
  794. insertWindowController.beginSheetModal(for: self.view.window!) { pdfDocument, password, pages, indexPage in
  795. self.insertPageAction(pdfDocument, password, pages, indexPage)
  796. }
  797. }
  798. }
  799. }
  800. }
  801. func fastTool_BreakUp() { // 拆分
  802. let openPanel = NSOpenPanel()
  803. openPanel.prompt = "提取"
  804. openPanel.allowsMultipleSelection = false
  805. openPanel.allowedFileTypes = ["pdf"]
  806. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  807. if result == .OK {
  808. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  809. let document = CPDFDocument(url: openPanel.url)
  810. let model = KMPageEditSplitSettingModel()
  811. model.documentURL = openPanel.url
  812. model.fileName = model.documentURL.lastPathComponent
  813. model.pathExtension = model.fileName.components(separatedBy: ".").last
  814. let windowController = KMPageEditSplitWindowController(model)
  815. windowController.hasPreView = true
  816. self.view.window?.beginSheet(windowController.window!)
  817. self.currentWindowController = windowController
  818. windowController.itemClick = { [weak self] index, value in
  819. if (index == 1) { /// 取消
  820. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  821. self?.currentWindowController = nil
  822. return
  823. }
  824. /// 拆分
  825. let windowController_split: KMPageEditSplitWindowController = self?.currentWindowController as! KMPageEditSplitWindowController
  826. let outputModel: KMPageEditSplitSettingModel = windowController_split.model! as! KMPageEditSplitSettingModel
  827. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  828. self?.currentWindowController = nil
  829. let panel = NSOpenPanel()
  830. panel.canChooseFiles = false
  831. panel.canChooseDirectories = true
  832. panel.canCreateDirectories = true
  833. panel.beginSheetModal(for: (self?.view.window)!) { response in
  834. KMPageEditTools.split(document!, outputModel, panel.url!.path, outputModel.outputFileNameDeletePathExtension) { result, outputDocuments, error in
  835. if (result) {
  836. }
  837. }
  838. }
  839. }
  840. }
  841. }
  842. }
  843. }
  844. func fastTool_Extract() { // 提取
  845. let openPanel = NSOpenPanel()
  846. openPanel.prompt = "提取"
  847. openPanel.allowsMultipleSelection = false
  848. openPanel.allowedFileTypes = ["pdf"]
  849. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  850. if result == .OK {
  851. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  852. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Extract)
  853. insertWindowController.beginSheetExtractModal(for: self.view.window!) { pdfDocument, pages, oneDocumentPerPage, isDeletePage in
  854. self.extractPageAction(pdfDocument, pages, oneDocumentPerPage, isDeletePage)
  855. }
  856. }
  857. }
  858. }
  859. }
  860. func fastTool_MarkCipher() { // 标记密文
  861. let openPanel = NSOpenPanel()
  862. openPanel.allowsMultipleSelection = false
  863. openPanel.allowedFileTypes = ["pdf"]
  864. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  865. if result == .cancel {
  866. return
  867. }
  868. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  869. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  870. if (error != nil) {
  871. NSApp.presentError(error!)
  872. return
  873. }
  874. let toolbar = (document as! KMMainDocument).mainViewController.toolbarController
  875. toolbar?.enterRedact()
  876. }
  877. }
  878. }
  879. }
  880. func fastTool_AutomaticFormRecognition() { // 表单自动识别
  881. let openPanel = NSOpenPanel()
  882. openPanel.prompt = "表单自动识别"
  883. openPanel.allowsMultipleSelection = false
  884. openPanel.allowedFileTypes = ["pdf"]
  885. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  886. if result == .OK {
  887. }
  888. }
  889. }
  890. func fastTool_PageEdit() { // 页面编辑
  891. let openPanel = NSOpenPanel()
  892. openPanel.allowsMultipleSelection = false
  893. openPanel.allowedFileTypes = ["pdf"]
  894. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  895. if result == .cancel {
  896. return
  897. }
  898. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  899. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  900. if (error != nil) {
  901. NSApp.presentError(error!)
  902. return
  903. }
  904. let mainView = (document as! KMMainDocument).mainViewController
  905. mainView.enterPageEdit()
  906. }
  907. }
  908. }
  909. }
  910. // MARK: MenuItem Action & PopoverItem Action
  911. func popoverItemAction(_ count: String) {
  912. if count == NSLocalizedString("New Blank Page", comment: "") {
  913. openBlankPage("")
  914. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  915. importFromWebPage("")
  916. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  917. importFromScanner("")
  918. }
  919. }
  920. @IBAction func importFromFile(_ sender: Any) {
  921. }
  922. @IBAction func openBlankPage(_ sender: Any) {
  923. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  924. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  925. let pdfDocument = CPDFDocument()
  926. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  927. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  928. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  929. if document is KMMainDocument {
  930. let newDocument = document
  931. (newDocument as! KMMainDocument).isNewCreated = true
  932. }
  933. }
  934. }
  935. @IBAction func importFromWebPage(_ sender: Any) {
  936. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  937. self.urlToPDFWindowController!.beginSheetModal(for: NSApp.mainWindow!) { filePath in
  938. if filePath != nil && FileManager.default.fileExists(atPath: filePath) {
  939. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  940. if document is KMMainDocument {
  941. (document as! KMMainDocument).isNewCreated = true
  942. }
  943. }
  944. }
  945. }
  946. }
  947. @IBAction func importFromScanner(_ sender: Any) {
  948. let vc = KMDeviceBrowserWindowController.init(windowNibName: "KMDeviceBrowserWindowController")
  949. vc.type = .scanner
  950. vc.importCameraFileCallback = {(url: NSURL) -> () in
  951. NSDocumentController.shared.openDocument(withContentsOf: url as URL, display: false) { document, documentWasAlreadyOpen, error in
  952. if document is KMMainDocument {
  953. (document as! KMMainDocument).isNewCreated = true
  954. }
  955. }
  956. }
  957. vc.showWindow(NSApp.mainWindow)
  958. }
  959. @IBAction func menuItemClick_mergePDF(_ sender: Any) {
  960. fastTool_MergePDF()
  961. }
  962. @IBAction func menuItemClick_Compress(_ sender: Any) {
  963. fastTool_Compression()
  964. }
  965. @IBAction func menuItemClick_Convert(_ sender: Any) {
  966. fastTool_ConvertPDF()
  967. }
  968. @IBAction func menuItemClick_SettingPassword(_ sender: Any) {
  969. fastTool_Security()
  970. }
  971. @IBAction func menuItemClick_RemovePassword(_ sender: Any) {
  972. fastTool_Security()
  973. }
  974. func fetchUniquePath(_ originalPath: String) -> String {
  975. var path = originalPath
  976. let dManager = FileManager.default
  977. if !dManager.fileExists(atPath: path) {
  978. if path.extension.count < 1 {
  979. path = path.stringByAppendingPathExtension("pdf")
  980. }
  981. return path
  982. } else {
  983. let originalFullFileName = path.lastPathComponent
  984. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  985. let originalExtension = path.extension
  986. let startIndex: Int = 0
  987. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  988. let fileLocatePath = originalPath.substring(to: endIndex)
  989. var i = 1
  990. while (1 != 0) {
  991. var newName = String(format: "%@%ld", originalFileName, i)
  992. newName = String(format: "%@%@", newName, originalExtension)
  993. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  994. if !dManager.fileExists(atPath: newPath) {
  995. return newPath
  996. } else {
  997. i+=1
  998. continue
  999. }
  1000. }
  1001. }
  1002. }
  1003. // func kNewDocumentTempSavePath(_ fileName: String) -> String {
  1004. // let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  1005. //// let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1006. // let append2 = searchPath!.stringByAppendingPathComponent(String(format: "%@", fileName))
  1007. // return append2
  1008. // }
  1009. // MARK: Notification
  1010. @objc func homeFileRectChange(_ notification: Notification) -> Void {
  1011. let window = notification.object
  1012. self.historyFileViewController.reloadData()
  1013. }
  1014. }
  1015. // MARK: window Menu
  1016. extension KMHomeViewController {
  1017. @IBAction func menuItemAction_moveToOtherDisplay(_ sender: Any) {
  1018. }
  1019. @IBAction func menuItemAction_showForwardTagPage(_ sender: Any) {
  1020. }
  1021. @IBAction func menuItemAction_showNextTagPage(_ sender: Any) {
  1022. }
  1023. @IBAction func menuItemAction_newTagPageToNewWindow(_ sender: Any) {
  1024. }
  1025. @IBAction func menuItemAction_mergeAllWindow(_ sender: Any) {
  1026. }
  1027. @IBAction func menuItemAction_bringAllToFront(_ sender: Any) {
  1028. }
  1029. @IBAction func menuItemAction_currentWindowName(_ sender: Any) {
  1030. }
  1031. }
  1032. // MARK: file Menu
  1033. extension KMHomeViewController {
  1034. @IBAction func menuItemAction_closeWindow(_ sender: Any) {
  1035. self.view.window?.close()
  1036. }
  1037. @IBAction func menuItemAction_ConvertToWord(_ sender: Any) {
  1038. self.fastTool_PDFToWord()
  1039. }
  1040. @IBAction func menuItemAction_ConvertToExcel(_ sender: Any) {
  1041. self.fastTool_PDFToExcel()
  1042. }
  1043. @IBAction func menuItemAction_ConvertToPPT(_ sender: Any) {
  1044. self.fastTool_PDFToPPT()
  1045. }
  1046. @IBAction func menuItemAction_ConvertToImage(_ sender: Any) {
  1047. self.fastTool_PDFToImage()
  1048. }
  1049. }
  1050. // MARK: help Menu
  1051. extension KMHomeViewController {
  1052. @IBAction func menuItemAction_search(_ sender: Any) {
  1053. }
  1054. }