KMHomeViewController+Action.swift 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  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. func aiTranslation(withFilePath path: String) -> Void {
  565. if !KMLightMemberManager.manager.isLogin() {
  566. KMLoginWindowController.show(window: NSApp.mainWindow!)
  567. return
  568. }
  569. if !path.isPDFValid() {
  570. let alert = NSAlert()
  571. alert.alertStyle = .critical
  572. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  573. alert.runModal()
  574. } else {
  575. let infoDictionary = Bundle .main.infoDictionary!
  576. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  577. DispatchQueue.main.async {
  578. self.showProgressWindow()
  579. }
  580. KMRequestServerManager.manager.aiTranslationFileUpload(file: path, version: "1.0.1") { [unowned self] success, result in
  581. if success {
  582. let result: NSDictionary = result!.result
  583. let fileKey = result["fileKey"]
  584. let fileName = result["fileName"]
  585. let pageCount = result["pageCount"]
  586. if fileKey != nil {
  587. self.fileTranslateHandle(fileKey as! String)
  588. }
  589. } else {
  590. let result: String = result!.message
  591. DispatchQueue.main.async {
  592. self.hiddenProgressWindow()
  593. self.aiTranslationViewController.errorView.isHidden = false
  594. self.aiTranslationViewController.errorLabel.stringValue = result
  595. }
  596. }
  597. }
  598. }
  599. }
  600. func fileTranslateHandle(_ fileKey: String) -> Void {
  601. let infoDictionary = Bundle .main.infoDictionary!
  602. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  603. KMRequestServerManager.manager.aiTranslationFileTranslateHandle(fileKey: fileKey, from: self.aiTranslationViewController.fromStr, to: self.aiTranslationViewController.toStr, version: "1.0.1") { success, result in
  604. if success {
  605. let result: NSDictionary = result!.result
  606. let fileUrl: String = result["fileUrl"] as! String
  607. let downFileUrl: String = result["downFileUrl"] as! String
  608. let ossDownUrl: String = result["ossDownUrl"] as! String
  609. let fileName: String = result["fileName"] as! String
  610. let downFileName: String = result["downFileName"] as! String
  611. let from: String = result["from"] as! String
  612. let to: String = result["to"] as! String
  613. self.downloadFile(filePath: ossDownUrl, downFileName: downFileName)
  614. } else {
  615. let result: String = result!.message
  616. DispatchQueue.main.async {
  617. self.hiddenProgressWindow()
  618. self.aiTranslationViewController.errorView.isHidden = false
  619. self.aiTranslationViewController.errorLabel.stringValue = result
  620. }
  621. }
  622. }
  623. }
  624. func downloadFile(filePath: String, downFileName: String) -> Void {
  625. guard let fileURL = URL(string: filePath) else {
  626. let alert = NSAlert()
  627. alert.alertStyle = .critical
  628. alert.messageText = NSLocalizedString("Invalid file link", comment: "")
  629. alert.runModal()
  630. return
  631. }
  632. let destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent(downFileName)
  633. if FileManager.default.fileExists(atPath: destinationURL.path) {
  634. do {
  635. try FileManager.default.removeItem(at: destinationURL)
  636. print("删除旧文件成功")
  637. } catch {
  638. print("删除旧文件失败:\(error)")
  639. }
  640. }
  641. let sessionConfiguration = URLSessionConfiguration.default
  642. let session = URLSession(configuration: sessionConfiguration)
  643. let downloadTask = session.downloadTask(with: fileURL) { (tempLocalURL, response, error) in
  644. if let error = error {
  645. let alert = NSAlert()
  646. alert.alertStyle = .critical
  647. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Download failure", comment: ""))
  648. alert.runModal()
  649. return
  650. }
  651. guard let tempLocalURL = tempLocalURL else {
  652. let alert = NSAlert()
  653. alert.alertStyle = .critical
  654. alert.messageText = NSLocalizedString("The download file temporary path is invalid", comment: "")
  655. alert.runModal()
  656. return
  657. }
  658. DispatchQueue.main.async {
  659. self.hiddenProgressWindow()
  660. }
  661. do {
  662. try FileManager.default.moveItem(at: tempLocalURL, to: destinationURL)
  663. NSDocumentController.shared.openDocument(withContentsOf: destinationURL, display: true) { document, documentWasAlreadyOpen, error in
  664. if error != nil {
  665. NSApp.presentError(error!)
  666. } else {
  667. }
  668. }
  669. } catch {
  670. let alert = NSAlert()
  671. alert.alertStyle = .critical
  672. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("File saving failure", comment: ""))
  673. alert.runModal()
  674. }
  675. }
  676. downloadTask.resume()
  677. }
  678. override func otherMouseDown(with event: NSEvent) {
  679. if historyFileViewController.selectFiles.count > 0 {
  680. let eventPoint = event.locationInWindow as NSPoint
  681. let x = eventPoint.x - 270.0
  682. if x >= 0 {
  683. let point = NSPoint(x: x, y: eventPoint.y)
  684. if historyFileViewController.historyFileCollectionView.frame.contains(point) ||
  685. historyFileViewController.historyFileTableView.frame.contains(point) ||
  686. historyFileViewController.deleteBox.frame.contains(point) ||
  687. historyFileViewController.listBox.frame.contains(point) ||
  688. historyFileViewController.thumbnailBox.frame.contains(point) {
  689. } else {
  690. self.historyFileViewController.selectFiles.removeAll()
  691. self.historyFileViewController.selectFiles_shift.removeAll()
  692. if self.historyFileViewController.showMode == .Thumbnail {
  693. self.historyFileViewController.historyFileCollectionView.reloadData()
  694. } else {
  695. self.historyFileViewController.historyFileTableView.reloadData()
  696. }
  697. }
  698. } else {
  699. self.historyFileViewController.selectFiles.removeAll()
  700. self.historyFileViewController.selectFiles_shift.removeAll()
  701. if self.historyFileViewController.showMode == .Thumbnail {
  702. self.historyFileViewController.historyFileCollectionView.reloadData()
  703. } else {
  704. self.historyFileViewController.historyFileTableView.reloadData()
  705. }
  706. }
  707. }
  708. }
  709. internal func showConvertWindow(type: KMPDFConvertType) {
  710. Task { @MainActor in
  711. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  712. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  713. return
  714. }
  715. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  716. var windowController: KMConvertBaseWindowController?
  717. if (type == .word) { /// Word
  718. windowController = KMConvertWordWindowController()
  719. } else if (type == .excel) {
  720. windowController = KMConvertExcelWindowController()
  721. } else if (type == .ppt || type == .rtf || type == .html || type == .text) {
  722. windowController = KMConvertPPTsWindowController()
  723. if (type == .ppt) {
  724. windowController?.subType = 1
  725. } else if (type == .rtf) {
  726. windowController?.subType = 2
  727. } else if (type == .html) {
  728. windowController?.subType = 3
  729. } else if (type == .text) {
  730. windowController?.subType = 4
  731. }
  732. } else if (type == .csv) {
  733. windowController = KMConvertCSVWindowController()
  734. } else if (type == .image) {
  735. windowController = KMConvertImageWindowController()
  736. }
  737. let model = KMDocumentModel(url: url)
  738. if (password != nil) {
  739. let _ = model.unlock(password!)
  740. }
  741. windowController?.documentModel = model
  742. windowController?.itemClick = { [weak self] index in
  743. if (self?.currentWindowController == nil) {
  744. return
  745. }
  746. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  747. self?.currentWindowController = nil
  748. }
  749. self.view.window?.beginSheet((windowController?.window)!)
  750. self.currentWindowController = windowController
  751. }
  752. }
  753. }
  754. // MARK: PDF Tools
  755. // 插入
  756. func insertPageAction(_ pdfDocument: CPDFDocument, _ password: String, _ pages: [CPDFPage], _ indexPage: Int) -> Void {
  757. if indexPage >= 0 {
  758. let insertPages: [CPDFPage] = pages
  759. for i in 0...insertPages.count-1 {
  760. let page = pages[i]
  761. // FIXME: 待底层库修改,使用 insertPageObject 插入,插入位置变为文档最后,暂用 insertPage 代替
  762. pdfDocument.insertPageObject(page, at: UInt(indexPage + i))
  763. }
  764. self.savePDFDocument(pdfDocument, password: password)
  765. }
  766. }
  767. func extractPageAction(_ pdfDocument: CPDFDocument, _ pages: [CPDFPage], _ oneDocumentPerPage: Bool, _ isDeletePage: Bool) -> Void {
  768. if pages.count < 1 {
  769. let alert = NSAlert()
  770. alert.alertStyle = .critical
  771. alert.messageText = NSLocalizedString("Please select two or more pages first to organize.", comment: "")
  772. alert.runModal()
  773. return
  774. }
  775. if !oneDocumentPerPage {
  776. let fileName = pdfDocument.getFileNameAccordingSelctPages(pages)
  777. let outputSavePanel = NSSavePanel()
  778. outputSavePanel.allowedFileTypes = ["pdf"]
  779. outputSavePanel.nameFieldStringValue = fileName
  780. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  781. if result == .OK {
  782. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  783. let saveFilePath = outputSavePanel.url?.path
  784. DispatchQueue.global().async {
  785. var pdf = CPDFDocument.init()
  786. let success = (pdf!.extractAsOneDocument(withPages: pages, savePath: saveFilePath)) as Bool
  787. DispatchQueue.main.async {
  788. if success {
  789. let workspace = NSWorkspace.shared
  790. let url = URL(fileURLWithPath: saveFilePath!)
  791. workspace.activateFileViewerSelecting([url])
  792. if isDeletePage {
  793. for page in pages {
  794. let indexPage = pdfDocument.index(for: page)
  795. pdfDocument.removePage(at: indexPage)
  796. }
  797. }
  798. }
  799. }
  800. }
  801. }
  802. }
  803. }
  804. } else {
  805. let panel = NSOpenPanel()
  806. panel.canChooseFiles = false
  807. panel.canChooseDirectories = true
  808. panel.canCreateDirectories = true
  809. panel.allowsMultipleSelection = false
  810. panel.beginSheetModal(for: self.view.window!) { result in
  811. if result == .OK {
  812. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  813. let outputURL = panel.url
  814. DispatchQueue.global().async {
  815. let folderName = String(pdfDocument.documentURL!.lastPathComponent.split(separator: ".")[0]) + "_extract"
  816. var filePath = URL(fileURLWithPath: outputURL!.path).appendingPathComponent(folderName).path
  817. var i = 1
  818. let testFilePath = filePath
  819. while FileManager.default.fileExists(atPath: filePath) {
  820. filePath = testFilePath + "\(i)"
  821. i += 1
  822. }
  823. try? FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
  824. let successArray = pdfDocument.extractPerPageDocument(withPages: pages, folerPath: filePath)
  825. DispatchQueue.main.async {
  826. if successArray!.count > 0 {
  827. NSWorkspace.shared.activateFileViewerSelecting(successArray!)
  828. if !isDeletePage {
  829. for page in pages {
  830. let indexPage = pdfDocument.index(for: page)
  831. pdfDocument.removePage(at: indexPage)
  832. }
  833. }
  834. }
  835. }
  836. }
  837. }
  838. }
  839. }
  840. }
  841. }
  842. // MARK: 快捷工具 Action
  843. func fastToolDidSelectAllTools() {
  844. // 首页 快捷工具 Tools按钮
  845. refreshRightBoxUI(.PDFTools)
  846. }
  847. func fastTool_Batch() { // Batch
  848. // KMBatchWindowController.openFile(nil, .Batch)
  849. }
  850. func fastTool_OCR() { // OCR
  851. // KMOCRWindowController.openFiles(window: self.view.window!)
  852. }
  853. func fastTool_ConvertPDF() { // 转换PDF
  854. // KMBatchWindowController.openFile(nil, .ConvertPDF)
  855. }
  856. func fastTool_ImageToPDF() { // 图片转PDF
  857. print("选中 快捷工具 图片转PDF")
  858. KMImageToPDFWindowController.openFiles(window: NSApp.mainWindow!)
  859. }
  860. func fastTool_MergePDF() { // MergePDF
  861. Task { @MainActor in
  862. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  863. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  864. return
  865. }
  866. let panel = NSOpenPanel()
  867. panel.allowedFileTypes = ["pdf"]
  868. panel.allowsMultipleSelection = true
  869. panel.beginSheetModal(for: self.view.window!) { response in
  870. if (response == .cancel) {
  871. return
  872. }
  873. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  874. var filepaths: Array<String> = []
  875. for url in panel.urls {
  876. filepaths.append(url.path)
  877. }
  878. let windowController = KMPDFEditAppendWindow(filePaths: filepaths)
  879. self.currentWindowController = windowController
  880. windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, indexs in
  881. })
  882. }
  883. }
  884. }
  885. }
  886. func fastTool_Compression() { // 压缩
  887. Task { @MainActor in
  888. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  889. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  890. return
  891. }
  892. NSOpenPanel.km_secure_openPanel(window: self.view.window!) { url, result, passowrd in
  893. if (url == nil) {
  894. return
  895. }
  896. if (result != nil && result! == .cancel) {
  897. return
  898. }
  899. self.showCompressWindow(url!, passowrd)
  900. }
  901. }
  902. }
  903. func showCompressWindow(_ url: URL, _ password: String?) {
  904. Task { @MainActor in
  905. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  906. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  907. return
  908. }
  909. let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  910. self.currentWindowController = windowController
  911. windowController.documentURL = url
  912. windowController.password = password
  913. windowController.itemClick = { [weak self] (index: Int) -> () in
  914. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  915. self?.currentWindowController = nil
  916. }
  917. windowController.resultCallback = { [weak self] (result: Bool, openDocument: Bool, fileURL: URL, error: String) in
  918. if result {
  919. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  920. self?.currentWindowController = nil
  921. if openDocument {
  922. if !fileURL.path.isPDFValid() {
  923. let alert = NSAlert()
  924. alert.alertStyle = .critical
  925. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  926. alert.runModal()
  927. return
  928. }
  929. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in
  930. if error != nil {
  931. NSApp.presentError(error!)
  932. return
  933. }
  934. }
  935. } else {
  936. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  937. }
  938. } else {
  939. let alert = NSAlert()
  940. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  941. alert.runModal()
  942. }
  943. }
  944. await self.view.window?.beginSheet(windowController.window!)
  945. }
  946. }
  947. func fastTool_Security() { // 安全
  948. Task { @MainActor in
  949. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  950. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  951. return
  952. }
  953. NSOpenPanel.km_secure_openPanel(window: self.view.window!, needOwner: true) { url, result, passowrd in
  954. if (url == nil) {
  955. return
  956. }
  957. if (result != nil && result! == .cancel) {
  958. return
  959. }
  960. let windowController = KMSecureEncryptWindowController(windowNibName: "KMSecureEncryptWindowController")
  961. windowController.documentURL = url!
  962. windowController.myDocument = CPDFDocument(url: url!)
  963. if (passowrd != nil) {
  964. windowController.myDocument.unlock(withPassword: passowrd)
  965. }
  966. self.currentWindowController = windowController
  967. let newDocument: CPDFDocument = CPDFDocument(url: url!)
  968. windowController.itemClick = { [weak self] (index: Int) -> () in
  969. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  970. self?.currentWindowController = nil
  971. }
  972. windowController.resultCallback = { [weak self] (result: Bool) -> () in
  973. let windowController_secure: KMSecureEncryptWindowController = self?.currentWindowController as! KMSecureEncryptWindowController
  974. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  975. self!.currentWindowController = nil
  976. if (passowrd != nil) {
  977. newDocument.unlock(withPassword: passowrd)
  978. }
  979. newDocument.setPasswordOptions(windowController_secure.options)
  980. let result = KMPasswordInputWindow.saveDocument(newDocument)
  981. if result {
  982. NSWorkspace.shared.activateFileViewerSelecting([newDocument.documentURL])
  983. } else {
  984. let alert = NSAlert()
  985. alert.messageText = NSLocalizedString("Failure", comment: "")
  986. alert.runModal()
  987. }
  988. }
  989. self.view.window?.beginSheet(windowController.window!)
  990. }
  991. }
  992. }
  993. func fastTool_FileCompare() { // 文件对比
  994. print("选中 快捷工具 文件对比")
  995. }
  996. func fastTool_PDFToPPT() { // PDF转PPT
  997. Task { @MainActor in
  998. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  999. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1000. return
  1001. }
  1002. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1003. let windowController = KMConvertPPTsWindowController(windowNibName: "KMConvertBaseWindowController")
  1004. let model = KMDocumentModel(url: url)
  1005. windowController.subType = 1
  1006. if (password != nil) {
  1007. let _ = model.unlock(password!)
  1008. }
  1009. windowController.documentModel = model
  1010. windowController.itemClick = { [weak self] (index: Int) in
  1011. if (self?.currentWindowController == nil) {
  1012. return
  1013. }
  1014. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1015. self?.currentWindowController = nil
  1016. }
  1017. self.view.window?.beginSheet(windowController.window!)
  1018. self.currentWindowController = windowController
  1019. }
  1020. }
  1021. }
  1022. func fastTool_PDFToExcel() { // PDF转Excel
  1023. Task { @MainActor in
  1024. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1025. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1026. return
  1027. }
  1028. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1029. let windowController = KMConvertExcelWindowController(windowNibName: "KMConvertBaseWindowController")
  1030. let model = KMDocumentModel(url: url)
  1031. if (password != nil) {
  1032. let _ = model.unlock(password!)
  1033. }
  1034. windowController.documentModel = model
  1035. windowController.itemClick = { [weak self] (index: Int) in
  1036. if (self?.currentWindowController == nil) {
  1037. return
  1038. }
  1039. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1040. self?.currentWindowController = nil
  1041. }
  1042. self.view.window?.beginSheet(windowController.window!)
  1043. self.currentWindowController = windowController
  1044. }
  1045. }
  1046. }
  1047. func fastTool_PDFToWord() { // PDF转Word
  1048. Task { @MainActor in
  1049. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1050. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1051. return
  1052. }
  1053. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1054. let windowController = KMConvertWordWindowController(windowNibName: "KMConvertBaseWindowController")
  1055. let model = KMDocumentModel(url: url)
  1056. if (password != nil) {
  1057. let _ = model.unlock(password!)
  1058. }
  1059. windowController.documentModel = model
  1060. windowController.itemClick = { [weak self] (index: Int) in
  1061. if (self?.currentWindowController == nil) {
  1062. return
  1063. }
  1064. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1065. self?.currentWindowController = nil
  1066. }
  1067. self.view.window?.beginSheet(windowController.window!)
  1068. self.currentWindowController = windowController
  1069. }
  1070. }
  1071. }
  1072. func fastTool_PDFToImage() { // PDF转图片
  1073. Task { @MainActor in
  1074. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1075. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1076. return
  1077. }
  1078. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1079. let windowController = KMConvertImageWindowController(windowNibName: "KMConvertBaseWindowController")
  1080. let model = KMDocumentModel(url: url)
  1081. if (password != nil) {
  1082. let _ = model.unlock(password!)
  1083. }
  1084. windowController.documentModel = model
  1085. windowController.itemClick = { [weak self] (index: Int) in
  1086. if (self?.currentWindowController == nil) {
  1087. return
  1088. }
  1089. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1090. self?.currentWindowController = nil
  1091. }
  1092. self.view.window?.beginSheet(windowController.window!)
  1093. self.currentWindowController = windowController
  1094. }
  1095. }
  1096. }
  1097. func fastTool_Watermark() { // 水印
  1098. KMBatchWindowController.openFile(nil, .Watermark)
  1099. }
  1100. func fastTool_Background() { // 背景
  1101. KMBatchWindowController.openFile(nil, .Background)
  1102. }
  1103. func fastTool_HeaderAndFooter() { // 页眉页脚
  1104. KMBatchWindowController.openFile(nil, .HeaderAndFooter)
  1105. }
  1106. func fastTool_BatesCode() { // 贝茨码
  1107. KMBatchWindowController.openFile(nil, .BatesCode)
  1108. }
  1109. func fastTool_Print() { // 打印
  1110. KMPrintWindowController.openFiles(window: self.view.window!)
  1111. }
  1112. func fastTool_BatchRemove() { // 批量移除
  1113. KMBatchWindowController.openFile(nil, .BatchRemove)
  1114. }
  1115. func fastTool_Insert() { // 插入
  1116. let openPanel = NSOpenPanel()
  1117. openPanel.prompt = "插入"
  1118. openPanel.allowsMultipleSelection = false
  1119. openPanel.allowedFileTypes = ["pdf"]
  1120. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1121. if result == .OK {
  1122. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1123. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Insert)
  1124. insertWindowController.beginSheetModal(for: self.view.window!) { pdfDocument, password, pages, indexPage in
  1125. self.insertPageAction(pdfDocument, password, pages, indexPage)
  1126. }
  1127. }
  1128. }
  1129. }
  1130. }
  1131. func fastTool_BreakUp() { // 拆分
  1132. let openPanel = NSOpenPanel()
  1133. openPanel.prompt = "提取"
  1134. openPanel.allowsMultipleSelection = false
  1135. openPanel.allowedFileTypes = ["pdf"]
  1136. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1137. if result == .OK {
  1138. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1139. let document = CPDFDocument(url: openPanel.url)
  1140. let model = KMPageEditSplitSettingModel()
  1141. model.documentURL = openPanel.url
  1142. model.fileName = model.documentURL.lastPathComponent
  1143. model.pathExtension = model.fileName.components(separatedBy: ".").last
  1144. let windowController = KMPageEditSplitWindowController(model)
  1145. windowController.hasPreView = true
  1146. self.view.window?.beginSheet(windowController.window!)
  1147. self.currentWindowController = windowController
  1148. windowController.itemClick = { [weak self] index, value in
  1149. if (index == 1) { /// 取消
  1150. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1151. self?.currentWindowController = nil
  1152. return
  1153. }
  1154. /// 拆分
  1155. let windowController_split: KMPageEditSplitWindowController = self?.currentWindowController as! KMPageEditSplitWindowController
  1156. let outputModel: KMPageEditSplitSettingModel = windowController_split.model! as! KMPageEditSplitSettingModel
  1157. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1158. self?.currentWindowController = nil
  1159. let panel = NSOpenPanel()
  1160. panel.canChooseFiles = false
  1161. panel.canChooseDirectories = true
  1162. panel.canCreateDirectories = true
  1163. panel.beginSheetModal(for: (self?.view.window)!) { response in
  1164. KMPageEditTools.split(document!, outputModel, panel.url!.path, outputModel.outputFileNameDeletePathExtension) { result, outputDocuments, error in
  1165. if (result) {
  1166. }
  1167. }
  1168. }
  1169. }
  1170. }
  1171. }
  1172. }
  1173. }
  1174. func fastTool_Extract() { // 提取
  1175. let openPanel = NSOpenPanel()
  1176. openPanel.prompt = "提取"
  1177. openPanel.allowsMultipleSelection = false
  1178. openPanel.allowedFileTypes = ["pdf"]
  1179. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1180. if result == .OK {
  1181. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1182. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Extract)
  1183. insertWindowController.beginSheetExtractModal(for: self.view.window!) { pdfDocument, pages, oneDocumentPerPage, isDeletePage in
  1184. self.extractPageAction(pdfDocument, pages, oneDocumentPerPage, isDeletePage)
  1185. }
  1186. }
  1187. }
  1188. }
  1189. }
  1190. func fastTool_MarkCipher() { // 标记密文
  1191. let openPanel = NSOpenPanel()
  1192. openPanel.allowsMultipleSelection = false
  1193. openPanel.allowedFileTypes = ["pdf"]
  1194. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1195. if result == .cancel {
  1196. return
  1197. }
  1198. if !openPanel.url!.path.isPDFValid() {
  1199. let alert = NSAlert()
  1200. alert.alertStyle = .critical
  1201. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1202. alert.runModal()
  1203. return
  1204. }
  1205. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1206. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1207. if (error != nil) {
  1208. NSApp.presentError(error!)
  1209. return
  1210. }
  1211. let toolbar = (document as! KMMainDocument).mainViewController?.toolbarController
  1212. toolbar?.enterRedact()
  1213. }
  1214. }
  1215. }
  1216. }
  1217. func fastTool_AutomaticFormRecognition() { // 表单自动识别
  1218. let openPanel = NSOpenPanel()
  1219. openPanel.prompt = "表单自动识别"
  1220. openPanel.allowsMultipleSelection = false
  1221. openPanel.allowedFileTypes = ["pdf"]
  1222. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1223. if result == .OK {
  1224. }
  1225. }
  1226. }
  1227. func fastTool_PageEdit() { // 页面编辑
  1228. let openPanel = NSOpenPanel()
  1229. openPanel.allowsMultipleSelection = false
  1230. openPanel.allowedFileTypes = ["pdf"]
  1231. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1232. if result == .cancel {
  1233. return
  1234. }
  1235. if !openPanel.url!.path.isPDFValid() {
  1236. let alert = NSAlert()
  1237. alert.alertStyle = .critical
  1238. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1239. alert.runModal()
  1240. return
  1241. }
  1242. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1243. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1244. if (error != nil) {
  1245. NSApp.presentError(error!)
  1246. return
  1247. }
  1248. let mainView = (document as! KMMainDocument).mainViewController
  1249. mainView?.enterPageEdit()
  1250. }
  1251. }
  1252. }
  1253. }
  1254. // MARK: MenuItem Action & PopoverItem Action
  1255. func popoverItemAction(_ count: String) {
  1256. if count == NSLocalizedString("New Blank Page", comment: "") {
  1257. openBlankPage("")
  1258. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  1259. importFromWebPage("")
  1260. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  1261. importFromScanner("")
  1262. }
  1263. }
  1264. @IBAction func escButtonAction(_ sender: Any) {
  1265. self.historyFileViewController.selectFiles.removeAll()
  1266. if self.historyFileViewController.showMode == .Thumbnail {
  1267. self.historyFileViewController.historyFileCollectionView.reloadData()
  1268. } else {
  1269. self.historyFileViewController.historyFileTableView.reloadData()
  1270. }
  1271. }
  1272. @IBAction func importFromFile(_ sender: Any) {
  1273. self.openSupportPDFButtonAction()
  1274. }
  1275. @IBAction func openBlankPage(_ sender: Any) {
  1276. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  1277. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  1278. let pdfDocument = CPDFDocument()
  1279. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  1280. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  1281. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  1282. if error != nil {
  1283. NSApp.presentError(error!)
  1284. } else {
  1285. if document is KMMainDocument {
  1286. let newDocument = document
  1287. (newDocument as! KMMainDocument).isNewCreated = true
  1288. }
  1289. }
  1290. }
  1291. }
  1292. @IBAction func importFromWebPage(_ sender: Any) {
  1293. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  1294. self.urlToPDFWindowController!.beginSheetModal(for: NSApp.mainWindow!) { filePath in
  1295. if filePath != nil && FileManager.default.fileExists(atPath: filePath) {
  1296. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  1297. if error != nil {
  1298. NSApp.presentError(error!)
  1299. } else {
  1300. if document is KMMainDocument {
  1301. (document as! KMMainDocument).isNewCreated = true
  1302. }
  1303. }
  1304. }
  1305. }
  1306. }
  1307. }
  1308. @IBAction func importFromScanner(_ sender: Any) {
  1309. deviceBrowserWC = KMDeviceBrowserWindowController.init(windowNibName: "KMDeviceBrowserWindowController")
  1310. deviceBrowserWC!.type = .scanner
  1311. deviceBrowserWC!.importScannerFileCallback = { [unowned self](url: NSURL) -> Void in
  1312. openFile(withFilePath: url as URL)
  1313. }
  1314. deviceBrowserWC!.showWindow(NSApp.mainWindow)
  1315. }
  1316. @IBAction func menuItemClick_mergePDF(_ sender: Any) {
  1317. fastTool_MergePDF()
  1318. }
  1319. @IBAction func menuItemClick_Compress(_ sender: Any) {
  1320. fastTool_Compression()
  1321. }
  1322. @IBAction func menuItemClick_Convert(_ sender: Any) {
  1323. fastTool_ConvertPDF()
  1324. }
  1325. @IBAction func menuItemClick_SettingPassword(_ sender: Any) {
  1326. fastTool_Security()
  1327. }
  1328. @IBAction func menuItemClick_RemovePassword(_ sender: Any) {
  1329. fastTool_Security()
  1330. }
  1331. func fetchUniquePath(_ originalPath: String) -> String {
  1332. var path = originalPath
  1333. let dManager = FileManager.default
  1334. if !dManager.fileExists(atPath: path) {
  1335. if path.extension.count < 1 {
  1336. path = path.stringByAppendingPathExtension("pdf")
  1337. }
  1338. return path
  1339. } else {
  1340. let originalFullFileName = path.lastPathComponent
  1341. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  1342. let originalExtension = path.extension
  1343. let startIndex: Int = 0
  1344. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  1345. let fileLocatePath = originalPath.substring(to: endIndex)
  1346. var i = 1
  1347. while (1 != 0) {
  1348. var newName = String(format: "%@%ld", originalFileName, i)
  1349. newName = String(format: "%@%@", newName, originalExtension)
  1350. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  1351. if !dManager.fileExists(atPath: newPath) {
  1352. return newPath
  1353. } else {
  1354. i+=1
  1355. continue
  1356. }
  1357. }
  1358. }
  1359. }
  1360. // func kNewDocumentTempSavePath(_ fileName: String) -> String {
  1361. // let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  1362. //// let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1363. // let append2 = searchPath!.stringByAppendingPathComponent(String(format: "%@", fileName))
  1364. // return append2
  1365. // }
  1366. // MARK: Notification
  1367. @objc func homeFileRectChange(_ notification: Notification) -> Void {
  1368. let window = notification.object
  1369. self.historyFileViewController.reloadData()
  1370. }
  1371. }
  1372. // MARK: window Menu
  1373. extension KMHomeViewController {
  1374. @IBAction func menuItemAction_showForwardTagPage(_ sender: Any) {
  1375. (self.myDocument as! KMMainDocument).browser.selectPreviousTab()
  1376. }
  1377. @IBAction func menuItemAction_showNextTagPage(_ sender: Any) {
  1378. (self.myDocument as! KMMainDocument).browser.selectNextTab()
  1379. }
  1380. @IBAction func menuItemAction_newTagPageToNewWindow(_ sender: Any) {
  1381. let browser = (self.myDocument as! KMMainDocument).browser
  1382. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.openNewWindow(sender)
  1383. }
  1384. @IBAction func menuItemAction_mergeAllWindow(_ sender: Any) {
  1385. let browser = (self.myDocument as! KMMainDocument).browser
  1386. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.mergeAllWindow(sender)
  1387. }
  1388. @IBAction func menuItemAction_currentWindowName(_ sender: Any) {
  1389. }
  1390. }
  1391. // MARK: file Menu
  1392. extension KMHomeViewController {
  1393. @IBAction func menuItemAction_closeWindow(_ sender: Any) {
  1394. self.view.window?.close()
  1395. }
  1396. @IBAction func menuItemAction_closeAllWindows(_ sender: Any) {
  1397. for window in NSApp.windows {
  1398. window.close()
  1399. }
  1400. }
  1401. @IBAction func menuItemAction_ConvertToWord(_ sender: Any) {
  1402. self.fastTool_PDFToWord()
  1403. }
  1404. @IBAction func menuItemAction_ConvertToExcel(_ sender: Any) {
  1405. self.fastTool_PDFToExcel()
  1406. }
  1407. @IBAction func menuItemAction_ConvertToPPT(_ sender: Any) {
  1408. self.fastTool_PDFToPPT()
  1409. }
  1410. @IBAction func menuItemAction_ConvertToRTF(_ sender: Any) {
  1411. self.showConvertWindow(type: .rtf)
  1412. }
  1413. @IBAction func menuItemAction_ConvertToHTML(_ sender: Any) {
  1414. self.showConvertWindow(type: .html)
  1415. }
  1416. @IBAction func menuItemAction_ConvertToText(_ sender: Any) {
  1417. self.showConvertWindow(type: .text)
  1418. }
  1419. @IBAction func menuItemAction_ConvertToCSV(_ sender: Any) {
  1420. self.showConvertWindow(type: .csv)
  1421. }
  1422. @IBAction func menuItemAction_ConvertToImage(_ sender: Any) {
  1423. self.fastTool_PDFToImage()
  1424. }
  1425. }
  1426. // MARK: help Menu
  1427. extension KMHomeViewController {
  1428. // @IBAction func menuItemAction_search(_ sender: Any) {
  1429. //
  1430. // }
  1431. }