KMHomeViewController+Action.swift 63 KB

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