KMHomeViewController+Action.swift 69 KB

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