KMHomeViewController+Action.swift 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609
  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. if (menuItem.action == #selector(menuItemAction_mergeAllWindow)) {
  27. if let _browserWindowC = ((self.myDocument as? KMMainDocument)?.browser.windowController as? KMBrowserWindowController) {
  28. return _browserWindowC.canMergeAllWindow()
  29. }
  30. }
  31. return true
  32. }
  33. }
  34. extension KMHomeViewController {
  35. // MARK: Action
  36. @objc func homeToolAction(_ sender: NSButton) -> Void {
  37. if sender == homeButtonVC.button {
  38. homeToolAction(homeToolState: KMHomeToolState.Home)
  39. } else if sender == pdfToolsButtonVC.button {
  40. homeToolAction(homeToolState: KMHomeToolState.PDFTools)
  41. } else if sender == cloudDocumentsButtonVC.button {
  42. homeToolAction(homeToolState: KMHomeToolState.CloudDocuments)
  43. } else if sender == openPDFButtonVC.button {
  44. homeToolAction(homeToolState: KMHomeToolState.OpenPDF)
  45. } else if sender == createPDFButtonVC.button {
  46. openSupportPDFButtonAction()
  47. } else if sender == createPDFImage.button {
  48. homeToolAction(homeToolState: KMHomeToolState.CreatePDF)
  49. }
  50. }
  51. func homeToolAction(homeToolState: KMHomeToolState) {
  52. switch homeToolState {
  53. case .OpenPDF:
  54. openPDFButtonAction()
  55. break
  56. case .CreatePDF:
  57. createPDFButtonAction()
  58. break
  59. case .Home:
  60. homeButtonAction()
  61. break
  62. case .PDFTools:
  63. pdfToolsButtonAction()
  64. break
  65. case .FavoriteDocuments:
  66. favoriteDocumentsButtonAction()
  67. break
  68. case .CloudDocuments:
  69. cloudDocumentsButtonAction()
  70. break
  71. default:
  72. print("error: 错误的传入枚举")
  73. break
  74. }
  75. }
  76. func fastToolItemAction(_ type: DataNavigationViewButtonActionType) {
  77. switch type {
  78. case .Batch:
  79. fastTool_Batch()
  80. break
  81. case .OCR:
  82. fastTool_OCR()
  83. break
  84. case .ConvertPDF:
  85. fastTool_ConvertPDF()
  86. break
  87. case .ImageToPDF:
  88. fastTool_ImageToPDF()
  89. break
  90. case .MergePDF:
  91. fastTool_MergePDF()
  92. break
  93. case .Compression:
  94. fastTool_Compression()
  95. break
  96. case .Security:
  97. fastTool_Security()
  98. break
  99. case .FileCompare:
  100. fastTool_FileCompare()
  101. break
  102. case .PDFToPPT:
  103. fastTool_PDFToPPT()
  104. break
  105. case .PDFToExcel:
  106. fastTool_PDFToExcel()
  107. break
  108. case .PDFToWord:
  109. fastTool_PDFToWord()
  110. break
  111. case .PDFToImage:
  112. fastTool_PDFToImage()
  113. break
  114. case .Watermark:
  115. fastTool_Watermark()
  116. break
  117. case .Background:
  118. fastTool_Background()
  119. break
  120. case .HeaderAndFooter:
  121. fastTool_HeaderAndFooter()
  122. break
  123. case .BatesCode:
  124. fastTool_BatesCode()
  125. break
  126. case .Print:
  127. fastTool_Print()
  128. break
  129. case .BatchRemove:
  130. fastTool_BatchRemove()
  131. break
  132. case .Insert:
  133. fastTool_Insert()
  134. break
  135. case .BreakUp:
  136. fastTool_BreakUp()
  137. break
  138. case .Extract:
  139. fastTool_Extract()
  140. break
  141. case .MarkCipher:
  142. fastTool_MarkCipher()
  143. break
  144. case .AutomaticFormRecognition:
  145. fastTool_AutomaticFormRecognition()
  146. break
  147. case .PageEdit:
  148. fastTool_PageEdit()
  149. break
  150. }
  151. }
  152. func openPDFButtonAction() {
  153. NSPanel.km_open_pdf_multi_success(self.view.window!, panel: nil) { urls in
  154. for url in urls {
  155. if !url.path.isPDFValid() {
  156. let alert = NSAlert()
  157. alert.alertStyle = .critical
  158. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  159. alert.runModal()
  160. } else {
  161. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  162. if error != nil {
  163. NSApp.presentError(error!)
  164. } else {
  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.beginSheetModal(for: view.window!) { [unowned self] result in
  338. self.historyFileViewController.reloadData()
  339. }
  340. return
  341. }
  342. if url.pathExtension.lowercased() == "pdf" {
  343. let pdfDoc = CPDFDocument.init(url: url)
  344. if pdfDoc != nil {
  345. let document = NSDocumentController.shared.document(for: url)
  346. var alreadyOpen = false
  347. for openDocument in NSDocumentController.shared.documents {
  348. if document == openDocument {
  349. alreadyOpen = true
  350. }
  351. }
  352. if !alreadyOpen {
  353. KMMainDocument().tryToUnlockDocument(pdfDoc!)
  354. var selectDocument: KMMainDocument? = nil
  355. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  356. selectDocument = (document as! KMMainDocument)
  357. }
  358. if selectDocument != nil {
  359. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  360. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  361. if (selectDocument?.browser.window.isVisible)! as Bool {
  362. selectDocument?.browser.window.orderFront(nil)
  363. } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  364. selectDocument?.browser.window.orderFront(nil)
  365. }
  366. } else {
  367. if !url.path.isPDFValid() {
  368. let alert = NSAlert()
  369. alert.alertStyle = .critical
  370. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  371. alert.runModal()
  372. } else {
  373. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  374. if error != nil {
  375. NSApp.presentError(error!)
  376. return
  377. }
  378. }
  379. }
  380. }
  381. } else {
  382. var selectDocument: KMMainDocument? = nil
  383. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  384. selectDocument = (document as! KMMainDocument)
  385. }
  386. if selectDocument != nil {
  387. if selectDocument?.browser != 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. }
  396. } else {
  397. if !url.path.isPDFValid() {
  398. let alert = NSAlert()
  399. alert.alertStyle = .critical
  400. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  401. alert.runModal()
  402. } else {
  403. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  404. if error != nil {
  405. NSApp.presentError(error!)
  406. return
  407. }
  408. }
  409. }
  410. }
  411. }
  412. } else {
  413. let alert = NSAlert()
  414. alert.alertStyle = .critical
  415. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  416. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  417. self.historyFileViewController.reloadData()
  418. }
  419. }
  420. } else {
  421. NSWorkspace.shared.open(url)
  422. }
  423. }
  424. func openFile(withFilePath path: URL) -> Void {
  425. let type = path.pathExtension.lowercased()
  426. if (type == "pdf") {
  427. if !path.path.isPDFValid() {
  428. let alert = NSAlert()
  429. alert.alertStyle = .critical
  430. alert.messageText = NSLocalizedString("This file format is not supported, please drag in PDF, picture, Office format files", comment: "")
  431. alert.runModal()
  432. return
  433. }
  434. NSDocumentController.shared.openDocument(withContentsOf: path, display: true) { document, documentWasAlreadyOpen, error in
  435. if error != nil {
  436. NSApp.presentError(error!)
  437. return
  438. }
  439. }
  440. } else if (type == "jpg") ||
  441. (type == "cur") ||
  442. (type == "bmp") ||
  443. (type == "jpeg") ||
  444. (type == "gif") ||
  445. (type == "png") ||
  446. (type == "tiff") ||
  447. (type == "tif") ||
  448. (type == "ico") ||
  449. (type == "icns") ||
  450. (type == "tga") ||
  451. (type == "psd") ||
  452. (type == "eps") ||
  453. (type == "hdr") ||
  454. (type == "jp2") ||
  455. (type == "jpc") ||
  456. (type == "pict") ||
  457. (type == "sgi") ||
  458. (type == "heic") {
  459. openImageFile(url: path)
  460. } else if (type == "doc") ||
  461. (type == "docx") ||
  462. (type == "xls") ||
  463. (type == "xlsx") ||
  464. (type == "ppt") ||
  465. (type == "pptx") ||
  466. (type == "pptx") {
  467. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  468. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  469. openOfficeFile(url: path)
  470. }
  471. }
  472. func openImageFile(url: URL) -> Void {
  473. let filePath = url.path
  474. let fileName: NSString = url.lastPathComponent as NSString
  475. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath()).deletingLastPathComponent
  476. let imageName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension
  477. let path = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".pdf")
  478. let document = CPDFDocument.init()
  479. var success = false
  480. //FIXME: 无法插入图片
  481. let image = NSImage(contentsOfFile: filePath)
  482. let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount)
  483. if insertPageSuccess != nil {
  484. //信号量控制异步
  485. let semaphore = DispatchSemaphore(value: 0)
  486. DispatchQueue.global().async {
  487. success = ((document?.write(toFile: path)) != nil)
  488. semaphore.signal()
  489. }
  490. semaphore.wait()
  491. } else {
  492. }
  493. if success {
  494. if !path.isPDFValid() {
  495. let alert = NSAlert()
  496. alert.alertStyle = .critical
  497. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  498. alert.runModal()
  499. return
  500. }
  501. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { document, documentWasAlreadyOpen, error in
  502. if error != nil {
  503. NSApp.presentError(error!)
  504. return
  505. }
  506. }
  507. }
  508. }
  509. func openOfficeFile(url: URL) -> Void {
  510. let filePath = url.path
  511. let folderPath = "convertToPDF.pdf"
  512. let savePath = folderPath.kUrlToPDFFolderPath()
  513. if savePath == nil {
  514. return
  515. }
  516. KMConvertPDFManagerOC.convertFile(filePath, savePath: savePath!) { success, errorDic in
  517. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  518. if FileManager.default.fileExists(atPath: savePath!) {
  519. try?FileManager.default.removeItem(atPath: savePath!)
  520. }
  521. let alert = NSAlert.init()
  522. alert.alertStyle = .critical
  523. var infoString = ""
  524. if errorDic != nil {
  525. for key in (errorDic! as Dictionary).keys {
  526. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  527. }
  528. }
  529. alert.informativeText = NSLocalizedString("Please install Microsoft Office to create PDFs from Office files", comment: "")
  530. alert.messageText = NSLocalizedString("Failed to Create PDF", comment: "")
  531. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  532. alert.runModal()
  533. return
  534. }
  535. if !savePath!.isPDFValid() {
  536. let alert = NSAlert()
  537. alert.alertStyle = .critical
  538. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  539. alert.runModal()
  540. return
  541. }
  542. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath!), display: true) { document, documentWasAlreadyOpen, error in
  543. if error != nil {
  544. NSApp.presentError(error!)
  545. return
  546. }
  547. }
  548. }
  549. }
  550. func aiTranslation(withFilePath path: String) -> Void {
  551. if !KMLightMemberManager.manager.isLogin() {
  552. KMLoginWindowController.show(window: NSApp.mainWindow!)
  553. return
  554. }
  555. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: path)
  556. if self.isFileGreaterThan10MB(atPath: path) {
  557. self.aiTranslationViewController.errorView.isHidden = false
  558. self.aiTranslationViewController.errorLabel.stringValue = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  559. } else if isExceedsLimit {
  560. self.aiTranslationViewController.errorView.isHidden = false
  561. self.aiTranslationViewController.errorLabel.stringValue = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  562. } else {
  563. let url = URL(fileURLWithPath: path)
  564. if (url.pathExtension == "pdf") || url.pathExtension == "PDF" {
  565. if !path.isPDFValid() {
  566. let alert = NSAlert()
  567. alert.alertStyle = .critical
  568. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  569. alert.runModal()
  570. return
  571. }
  572. }
  573. let infoDictionary = Bundle .main.infoDictionary!
  574. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  575. DispatchQueue.main.async {
  576. self.showProgressWindow()
  577. }
  578. KMRequestServerManager.manager.aiTranslationFileUpload(file: path, version: "1.0.1") { [unowned self] success, result in
  579. if success {
  580. let result: NSDictionary = result!.result
  581. let fileKey = result["fileKey"]
  582. let fileName = result["fileName"]
  583. let pageCount = result["pageCount"]
  584. if fileKey != nil {
  585. self.fileTranslateHandle(fileKey as! String)
  586. }
  587. } else {
  588. let result: String = result!.message
  589. DispatchQueue.main.async {
  590. self.hiddenProgressWindow()
  591. self.aiTranslationViewController.errorView.isHidden = false
  592. self.aiTranslationViewController.errorLabel.stringValue = result
  593. }
  594. }
  595. }
  596. }
  597. }
  598. func fileTranslateHandle(_ fileKey: String) -> Void {
  599. let infoDictionary = Bundle .main.infoDictionary!
  600. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  601. KMRequestServerManager.manager.aiTranslationFileTranslateHandle(fileKey: fileKey, from: self.aiTranslationViewController.fromStr, to: self.aiTranslationViewController.toStr, version: "1.0.1") { success, result in
  602. if success {
  603. let result: NSDictionary = result!.result
  604. let fileUrl: String = result["fileUrl"] as! String
  605. let downFileUrl: String = result["downFileUrl"] as! String
  606. let ossDownUrl: String = result["ossDownUrl"] as! String
  607. let fileName: String = result["fileName"] as! String
  608. let downFileName: String = result["downFileName"] as! String
  609. let from: String = result["from"] as! String
  610. let to: String = result["to"] as! String
  611. self.downloadFile(filePath: ossDownUrl, downFileName: downFileName)
  612. } else {
  613. let result: String = result!.message
  614. DispatchQueue.main.async {
  615. self.hiddenProgressWindow()
  616. self.aiTranslationViewController.errorView.isHidden = false
  617. self.aiTranslationViewController.errorLabel.stringValue = result
  618. }
  619. }
  620. }
  621. }
  622. func downloadFile(filePath: String, downFileName: String) -> Void {
  623. guard let fileURL = URL(string: filePath) else {
  624. let alert = NSAlert()
  625. alert.alertStyle = .critical
  626. alert.messageText = NSLocalizedString("Invalid file link", comment: "")
  627. alert.runModal()
  628. return
  629. }
  630. let destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent(downFileName)
  631. if FileManager.default.fileExists(atPath: destinationURL.path) {
  632. do {
  633. try FileManager.default.removeItem(at: destinationURL)
  634. print("删除旧文件成功")
  635. } catch {
  636. print("删除旧文件失败:\(error)")
  637. }
  638. }
  639. let sessionConfiguration = URLSessionConfiguration.default
  640. let session = URLSession(configuration: sessionConfiguration)
  641. let downloadTask = session.downloadTask(with: fileURL) { (tempLocalURL, response, error) in
  642. if let error = error {
  643. let alert = NSAlert()
  644. alert.alertStyle = .critical
  645. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Download failed", comment: ""))
  646. alert.runModal()
  647. return
  648. }
  649. guard let tempLocalURL = tempLocalURL else {
  650. let alert = NSAlert()
  651. alert.alertStyle = .critical
  652. alert.messageText = NSLocalizedString("Invalid temporary directory", comment: "")
  653. alert.runModal()
  654. return
  655. }
  656. DispatchQueue.main.async {
  657. self.hiddenProgressWindow()
  658. }
  659. do {
  660. try FileManager.default.moveItem(at: tempLocalURL, to: destinationURL)
  661. NSDocumentController.shared.openDocument(withContentsOf: destinationURL, display: true) { document, documentWasAlreadyOpen, error in
  662. if error != nil {
  663. NSApp.presentError(error!)
  664. } else {
  665. }
  666. }
  667. } catch {
  668. let alert = NSAlert()
  669. alert.alertStyle = .critical
  670. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Failed to save file", comment: ""))
  671. alert.runModal()
  672. }
  673. }
  674. downloadTask.resume()
  675. }
  676. override func otherMouseDown(with event: NSEvent) {
  677. if historyFileViewController.selectFiles.count > 0 {
  678. let eventPoint = event.locationInWindow as NSPoint
  679. let x = eventPoint.x - 270.0
  680. if x >= 0 {
  681. let point = NSPoint(x: x, y: eventPoint.y)
  682. if historyFileViewController.historyFileCollectionView.frame.contains(point) ||
  683. historyFileViewController.historyFileTableView.frame.contains(point) ||
  684. historyFileViewController.deleteBox.frame.contains(point) ||
  685. historyFileViewController.listBox.frame.contains(point) ||
  686. historyFileViewController.thumbnailBox.frame.contains(point) {
  687. } else {
  688. self.historyFileViewController.selectFiles.removeAll()
  689. self.historyFileViewController.selectFiles_shift.removeAll()
  690. if self.historyFileViewController.showMode == .Thumbnail {
  691. self.historyFileViewController.historyFileCollectionView.reloadData()
  692. } else {
  693. self.historyFileViewController.historyFileTableView.reloadData()
  694. }
  695. }
  696. } else {
  697. self.historyFileViewController.selectFiles.removeAll()
  698. self.historyFileViewController.selectFiles_shift.removeAll()
  699. if self.historyFileViewController.showMode == .Thumbnail {
  700. self.historyFileViewController.historyFileCollectionView.reloadData()
  701. } else {
  702. self.historyFileViewController.historyFileTableView.reloadData()
  703. }
  704. }
  705. }
  706. }
  707. internal func showConvertWindow(type: KMPDFConvertType) {
  708. Task { @MainActor in
  709. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  710. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  711. return
  712. }
  713. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  714. var windowController: KMConvertBaseWindowController?
  715. if (type == .word) { /// Word
  716. windowController = KMConvertWordWindowController()
  717. } else if (type == .excel) {
  718. windowController = KMConvertExcelWindowController()
  719. } else if (type == .ppt || type == .rtf || type == .html || type == .text) {
  720. windowController = KMConvertPPTsWindowController()
  721. if (type == .ppt) {
  722. windowController?.subType = 1
  723. } else if (type == .rtf) {
  724. windowController?.subType = 2
  725. } else if (type == .html) {
  726. windowController?.subType = 3
  727. } else if (type == .text) {
  728. windowController?.subType = 4
  729. }
  730. } else if (type == .csv) {
  731. windowController = KMConvertCSVWindowController()
  732. } else if (type == .image) {
  733. windowController = KMConvertImageWindowController()
  734. }
  735. let model = KMDocumentModel(url: url)
  736. if (password != nil) {
  737. let _ = model.unlock(password!)
  738. }
  739. windowController?.documentModel = model
  740. windowController?.itemClick = { [weak self] index in
  741. if (self?.currentWindowController == nil) {
  742. return
  743. }
  744. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  745. self?.currentWindowController = nil
  746. }
  747. self.view.window?.beginSheet((windowController?.window)!)
  748. self.currentWindowController = windowController
  749. }
  750. }
  751. }
  752. // MARK: PDF Tools
  753. // 插入
  754. func insertPageAction(_ pdfDocument: CPDFDocument, _ password: String, _ pages: [CPDFPage], _ indexPage: Int) -> Void {
  755. if indexPage >= 0 {
  756. let insertPages: [CPDFPage] = pages
  757. for i in 0...insertPages.count-1 {
  758. let page = pages[i]
  759. // FIXME: 待底层库修改,使用 insertPageObject 插入,插入位置变为文档最后,暂用 insertPage 代替
  760. pdfDocument.insertPageObject(page, at: UInt(indexPage + i))
  761. }
  762. self.savePDFDocument(pdfDocument, password: password)
  763. }
  764. }
  765. func extractPageAction(_ pdfDocument: CPDFDocument, _ pages: [CPDFPage], _ oneDocumentPerPage: Bool, _ isDeletePage: Bool) -> Void {
  766. if pages.count < 1 {
  767. let alert = NSAlert()
  768. alert.alertStyle = .critical
  769. alert.messageText = NSLocalizedString("Please select two or more pages first to organize.", comment: "")
  770. alert.runModal()
  771. return
  772. }
  773. if !oneDocumentPerPage {
  774. let fileName = pdfDocument.getFileNameAccordingSelctPages(pages)
  775. let outputSavePanel = NSSavePanel()
  776. outputSavePanel.allowedFileTypes = ["pdf"]
  777. outputSavePanel.nameFieldStringValue = fileName
  778. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  779. if result == .OK {
  780. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  781. let saveFilePath = outputSavePanel.url?.path
  782. DispatchQueue.global().async {
  783. var pdf = CPDFDocument.init()
  784. let success = (pdf!.extractAsOneDocument(withPages: pages, savePath: saveFilePath)) as Bool
  785. DispatchQueue.main.async {
  786. if success {
  787. let workspace = NSWorkspace.shared
  788. let url = URL(fileURLWithPath: saveFilePath!)
  789. workspace.activateFileViewerSelecting([url])
  790. if isDeletePage {
  791. for page in pages {
  792. let indexPage = pdfDocument.index(for: page)
  793. pdfDocument.removePage(at: indexPage)
  794. }
  795. }
  796. }
  797. }
  798. }
  799. }
  800. }
  801. }
  802. } else {
  803. let panel = NSOpenPanel()
  804. panel.canChooseFiles = false
  805. panel.canChooseDirectories = true
  806. panel.canCreateDirectories = true
  807. panel.allowsMultipleSelection = false
  808. panel.beginSheetModal(for: self.view.window!) { result in
  809. if result == .OK {
  810. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  811. let outputURL = panel.url
  812. DispatchQueue.global().async {
  813. let folderName = String(pdfDocument.documentURL!.lastPathComponent.split(separator: ".")[0]) + "_extract"
  814. var filePath = URL(fileURLWithPath: outputURL!.path).appendingPathComponent(folderName).path
  815. var i = 1
  816. let testFilePath = filePath
  817. while FileManager.default.fileExists(atPath: filePath) {
  818. filePath = testFilePath + "\(i)"
  819. i += 1
  820. }
  821. try? FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
  822. let successArray = pdfDocument.extractPerPageDocument(withPages: pages, folerPath: filePath)
  823. DispatchQueue.main.async {
  824. if successArray!.count > 0 {
  825. NSWorkspace.shared.activateFileViewerSelecting(successArray!)
  826. if !isDeletePage {
  827. for page in pages {
  828. let indexPage = pdfDocument.index(for: page)
  829. pdfDocument.removePage(at: indexPage)
  830. }
  831. }
  832. }
  833. }
  834. }
  835. }
  836. }
  837. }
  838. }
  839. }
  840. // MARK: 快捷工具 Action
  841. func fastToolDidSelectAllTools() {
  842. // 首页 快捷工具 Tools按钮
  843. refreshRightBoxUI(.PDFTools)
  844. }
  845. func fastTool_Batch() { // Batch
  846. // KMBatchWindowController.openFile(nil, .Batch)
  847. }
  848. func fastTool_OCR() { // OCR
  849. // KMOCRWindowController.openFiles(window: self.view.window!)
  850. }
  851. func fastTool_ConvertPDF() { // 转换PDF
  852. // KMBatchWindowController.openFile(nil, .ConvertPDF)
  853. }
  854. func fastTool_ImageToPDF() { // 图片转PDF
  855. KMImageToPDFWindowController.openFiles(window: NSApp.mainWindow!)
  856. }
  857. func fastTool_MergePDF() { // MergePDF
  858. Task { @MainActor in
  859. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  860. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  861. return
  862. }
  863. NSPanel.km_open_pdf_multi_success(self.view.window!, panel: nil) { urls in
  864. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  865. var filepaths: Array<String> = []
  866. for url in urls {
  867. filepaths.append(url.path)
  868. }
  869. let windowController = KMPDFEditAppendWindow(filePaths: filepaths)
  870. self.currentWindowController = windowController
  871. windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, indexs in
  872. })
  873. }
  874. }
  875. }
  876. }
  877. func fastTool_Compression() { // 压缩
  878. Task { @MainActor in
  879. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  880. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  881. return
  882. }
  883. NSOpenPanel.km_secure_openPanel(window: self.view.window!) { url, result, passowrd in
  884. if (url == nil) {
  885. return
  886. }
  887. if (result != nil && result! == .cancel) {
  888. return
  889. }
  890. self.showCompressWindow(url!, passowrd)
  891. }
  892. }
  893. }
  894. func showCompressWindow(_ url: URL, _ password: String?) {
  895. Task { @MainActor in
  896. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  897. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  898. return
  899. }
  900. let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  901. self.currentWindowController = windowController
  902. windowController.documentURL = url
  903. windowController.password = password
  904. windowController.itemClick = { [weak self] (index: Int) -> () in
  905. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  906. self?.currentWindowController = nil
  907. }
  908. windowController.resultCallback = { [weak self] (result: Bool, openDocument: Bool, fileURL: URL, error: String) in
  909. if result {
  910. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  911. self?.currentWindowController = nil
  912. if openDocument {
  913. if !fileURL.path.isPDFValid() {
  914. let alert = NSAlert()
  915. alert.alertStyle = .critical
  916. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  917. alert.runModal()
  918. return
  919. }
  920. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in
  921. if error != nil {
  922. NSApp.presentError(error!)
  923. return
  924. }
  925. }
  926. } else {
  927. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  928. }
  929. } else {
  930. let alert = NSAlert()
  931. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  932. alert.runModal()
  933. }
  934. }
  935. await self.view.window?.beginSheet(windowController.window!)
  936. }
  937. }
  938. func fastTool_Security() { // 安全
  939. Task { @MainActor in
  940. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  941. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  942. return
  943. }
  944. NSOpenPanel.km_secure_openPanel(window: self.view.window!, needOwner: true) { url, result, passowrd in
  945. if (url == nil) {
  946. return
  947. }
  948. if (result != nil && result! == .cancel) {
  949. return
  950. }
  951. let windowController = KMSecureEncryptWindowController(windowNibName: "KMSecureEncryptWindowController")
  952. windowController.documentURL = url!
  953. windowController.myDocument = CPDFDocument(url: url!)
  954. if (passowrd != nil) {
  955. windowController.myDocument.unlock(withPassword: passowrd)
  956. }
  957. self.currentWindowController = windowController
  958. let newDocument: CPDFDocument = CPDFDocument(url: url!)
  959. windowController.itemClick = { [weak self] (index: Int) -> () in
  960. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  961. self?.currentWindowController = nil
  962. }
  963. windowController.resultCallback = { [weak self] (result: Bool) -> () in
  964. let windowController_secure: KMSecureEncryptWindowController = self?.currentWindowController as! KMSecureEncryptWindowController
  965. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  966. self!.currentWindowController = nil
  967. if (passowrd != nil) {
  968. newDocument.unlock(withPassword: passowrd)
  969. }
  970. newDocument.setPasswordOptions(windowController_secure.options)
  971. let result = KMPasswordInputWindow.saveDocument(newDocument)
  972. if result {
  973. NSWorkspace.shared.activateFileViewerSelecting([newDocument.documentURL])
  974. } else {
  975. let alert = NSAlert()
  976. alert.messageText = NSLocalizedString("Failure", comment: "")
  977. alert.runModal()
  978. }
  979. }
  980. self.view.window?.beginSheet(windowController.window!)
  981. }
  982. }
  983. }
  984. func fastTool_FileCompare() { // 文件对比
  985. print("选中 快捷工具 文件对比")
  986. }
  987. func fastTool_PDFToPPT() { // PDF转PPT
  988. Task { @MainActor in
  989. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  990. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  991. return
  992. }
  993. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  994. let windowController = KMConvertPPTsWindowController(windowNibName: "KMConvertBaseWindowController")
  995. let model = KMDocumentModel(url: url)
  996. windowController.subType = 1
  997. if (password != nil) {
  998. let _ = model.unlock(password!)
  999. }
  1000. windowController.documentModel = model
  1001. windowController.itemClick = { [weak self] (index: Int) in
  1002. if (self?.currentWindowController == nil) {
  1003. return
  1004. }
  1005. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1006. self?.currentWindowController = nil
  1007. }
  1008. self.view.window?.beginSheet(windowController.window!)
  1009. self.currentWindowController = windowController
  1010. }
  1011. }
  1012. }
  1013. func fastTool_PDFToExcel() { // PDF转Excel
  1014. Task { @MainActor in
  1015. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1016. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1017. return
  1018. }
  1019. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1020. let windowController = KMConvertExcelWindowController(windowNibName: "KMConvertBaseWindowController")
  1021. let model = KMDocumentModel(url: url)
  1022. if (password != nil) {
  1023. let _ = model.unlock(password!)
  1024. }
  1025. windowController.documentModel = model
  1026. windowController.itemClick = { [weak self] (index: Int) in
  1027. if (self?.currentWindowController == nil) {
  1028. return
  1029. }
  1030. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1031. self?.currentWindowController = nil
  1032. }
  1033. self.view.window?.beginSheet(windowController.window!)
  1034. self.currentWindowController = windowController
  1035. }
  1036. }
  1037. }
  1038. func fastTool_PDFToWord() { // PDF转Word
  1039. Task { @MainActor in
  1040. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1041. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1042. return
  1043. }
  1044. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1045. if (url.path.isPDFValid() == false) {
  1046. let alert = NSAlert()
  1047. alert.alertStyle = .critical
  1048. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1049. alert.runModal()
  1050. return
  1051. }
  1052. let windowController = KMConvertWordWindowController(windowNibName: "KMConvertBaseWindowController")
  1053. let model = KMDocumentModel(url: url)
  1054. if (password != nil) {
  1055. let _ = model.unlock(password!)
  1056. }
  1057. windowController.documentModel = model
  1058. windowController.itemClick = { [weak self] (index: Int) in
  1059. if (self?.currentWindowController == nil) {
  1060. return
  1061. }
  1062. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1063. self?.currentWindowController = nil
  1064. }
  1065. self.view.window?.beginSheet(windowController.window!)
  1066. self.currentWindowController = windowController
  1067. }
  1068. }
  1069. }
  1070. func fastTool_PDFToImage() { // PDF转图片
  1071. Task { @MainActor in
  1072. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1073. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1074. return
  1075. }
  1076. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1077. let windowController = KMConvertImageWindowController(windowNibName: "KMConvertBaseWindowController")
  1078. let model = KMDocumentModel(url: url)
  1079. if (password != nil) {
  1080. let _ = model.unlock(password!)
  1081. }
  1082. windowController.documentModel = model
  1083. windowController.itemClick = { [weak self] (index: Int) in
  1084. if (self?.currentWindowController == nil) {
  1085. return
  1086. }
  1087. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1088. self?.currentWindowController = nil
  1089. }
  1090. self.view.window?.beginSheet(windowController.window!)
  1091. self.currentWindowController = windowController
  1092. }
  1093. }
  1094. }
  1095. func fastTool_Watermark() { // 水印
  1096. KMBatchWindowController.openFile(nil, .Watermark)
  1097. }
  1098. func fastTool_Background() { // 背景
  1099. KMBatchWindowController.openFile(nil, .Background)
  1100. }
  1101. func fastTool_HeaderAndFooter() { // 页眉页脚
  1102. KMBatchWindowController.openFile(nil, .HeaderAndFooter)
  1103. }
  1104. func fastTool_BatesCode() { // 贝茨码
  1105. KMBatchWindowController.openFile(nil, .BatesCode)
  1106. }
  1107. func fastTool_Print() { // 打印
  1108. KMPrintWindowController.openFiles(window: self.view.window!)
  1109. }
  1110. func fastTool_BatchRemove() { // 批量移除
  1111. KMBatchWindowController.openFile(nil, .BatchRemove)
  1112. }
  1113. func fastTool_Insert() { // 插入
  1114. let openPanel = NSOpenPanel()
  1115. openPanel.prompt = "插入"
  1116. openPanel.allowsMultipleSelection = false
  1117. openPanel.allowedFileTypes = ["pdf"]
  1118. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1119. if result == .OK {
  1120. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1121. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Insert)
  1122. insertWindowController.beginSheetModal(for: self.view.window!) { pdfDocument, password, pages, indexPage in
  1123. self.insertPageAction(pdfDocument, password, pages, indexPage)
  1124. }
  1125. }
  1126. }
  1127. }
  1128. }
  1129. func fastTool_BreakUp() { // 拆分
  1130. let openPanel = NSOpenPanel()
  1131. openPanel.prompt = "提取"
  1132. openPanel.allowsMultipleSelection = false
  1133. openPanel.allowedFileTypes = ["pdf"]
  1134. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1135. if result == .OK {
  1136. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1137. let document = CPDFDocument(url: openPanel.url)
  1138. let model = KMPageEditSplitSettingModel()
  1139. model.documentURL = openPanel.url
  1140. model.fileName = model.documentURL.lastPathComponent
  1141. model.pathExtension = model.fileName.components(separatedBy: ".").last
  1142. let windowController = KMPageEditSplitWindowController(model)
  1143. windowController.hasPreView = true
  1144. self.view.window?.beginSheet(windowController.window!)
  1145. self.currentWindowController = windowController
  1146. windowController.itemClick = { [weak self] index, value in
  1147. if (index == 1) { /// 取消
  1148. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1149. self?.currentWindowController = nil
  1150. return
  1151. }
  1152. /// 拆分
  1153. let windowController_split: KMPageEditSplitWindowController = self?.currentWindowController as! KMPageEditSplitWindowController
  1154. let outputModel: KMPageEditSplitSettingModel = windowController_split.model! as! KMPageEditSplitSettingModel
  1155. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1156. self?.currentWindowController = nil
  1157. let panel = NSOpenPanel()
  1158. panel.canChooseFiles = false
  1159. panel.canChooseDirectories = true
  1160. panel.canCreateDirectories = true
  1161. panel.beginSheetModal(for: (self?.view.window)!) { response in
  1162. KMPageEditTools.split(document!, outputModel, panel.url!.path, outputModel.outputFileNameDeletePathExtension) { result, outputDocuments, error in
  1163. if (result) {
  1164. }
  1165. }
  1166. }
  1167. }
  1168. }
  1169. }
  1170. }
  1171. }
  1172. func fastTool_Extract() { // 提取
  1173. let openPanel = NSOpenPanel()
  1174. openPanel.prompt = "提取"
  1175. openPanel.allowsMultipleSelection = false
  1176. openPanel.allowedFileTypes = ["pdf"]
  1177. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1178. if result == .OK {
  1179. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1180. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Extract)
  1181. insertWindowController.beginSheetExtractModal(for: self.view.window!) { pdfDocument, pages, oneDocumentPerPage, isDeletePage in
  1182. self.extractPageAction(pdfDocument, pages, oneDocumentPerPage, isDeletePage)
  1183. }
  1184. }
  1185. }
  1186. }
  1187. }
  1188. func fastTool_MarkCipher() { // 标记密文
  1189. let openPanel = NSOpenPanel()
  1190. openPanel.allowsMultipleSelection = false
  1191. openPanel.allowedFileTypes = ["pdf"]
  1192. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1193. if result == .cancel {
  1194. return
  1195. }
  1196. if !openPanel.url!.path.isPDFValid() {
  1197. let alert = NSAlert()
  1198. alert.alertStyle = .critical
  1199. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1200. alert.runModal()
  1201. return
  1202. }
  1203. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1204. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1205. if (error != nil) {
  1206. NSApp.presentError(error!)
  1207. return
  1208. }
  1209. let toolbar = (document as! KMMainDocument).mainViewController?.toolbarController
  1210. toolbar?.enterRedact()
  1211. }
  1212. }
  1213. }
  1214. }
  1215. func fastTool_AutomaticFormRecognition() { // 表单自动识别
  1216. let openPanel = NSOpenPanel()
  1217. openPanel.prompt = "表单自动识别"
  1218. openPanel.allowsMultipleSelection = false
  1219. openPanel.allowedFileTypes = ["pdf"]
  1220. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1221. if result == .OK {
  1222. }
  1223. }
  1224. }
  1225. func fastTool_PageEdit() { // 页面编辑
  1226. let openPanel = NSOpenPanel()
  1227. openPanel.allowsMultipleSelection = false
  1228. openPanel.allowedFileTypes = ["pdf"]
  1229. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1230. if result == .cancel {
  1231. return
  1232. }
  1233. if !openPanel.url!.path.isPDFValid() {
  1234. let alert = NSAlert()
  1235. alert.alertStyle = .critical
  1236. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1237. alert.runModal()
  1238. return
  1239. }
  1240. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1241. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1242. if (error != nil) {
  1243. NSApp.presentError(error!)
  1244. return
  1245. }
  1246. let mainView = (document as! KMMainDocument).mainViewController
  1247. mainView?.enterPageEdit()
  1248. }
  1249. }
  1250. }
  1251. }
  1252. // MARK: MenuItem Action & PopoverItem Action
  1253. func popoverItemAction(_ count: String) {
  1254. if count == NSLocalizedString("New Blank Page", comment: "") {
  1255. openBlankPage("")
  1256. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  1257. importFromWebPage("")
  1258. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  1259. importFromScanner("")
  1260. }
  1261. }
  1262. @IBAction func escButtonAction(_ sender: Any) {
  1263. self.historyFileViewController.selectFiles.removeAll()
  1264. if self.historyFileViewController.showMode == .Thumbnail {
  1265. self.historyFileViewController.historyFileCollectionView.reloadData()
  1266. } else {
  1267. self.historyFileViewController.historyFileTableView.reloadData()
  1268. }
  1269. }
  1270. @IBAction func importFromFile(_ sender: Any) {
  1271. self.openSupportPDFButtonAction()
  1272. }
  1273. @IBAction func openBlankPage(_ sender: Any) {
  1274. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  1275. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  1276. let pdfDocument = CPDFDocument()
  1277. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  1278. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  1279. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  1280. if error != nil {
  1281. NSApp.presentError(error!)
  1282. } else {
  1283. if document is KMMainDocument {
  1284. let newDocument = document
  1285. (newDocument as! KMMainDocument).isNewCreated = true
  1286. }
  1287. }
  1288. }
  1289. }
  1290. @IBAction func importFromWebPage(_ sender: Any) {
  1291. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  1292. self.urlToPDFWindowController!.beginSheetModal(for: NSApp.mainWindow!) { filePath in
  1293. if filePath != nil && FileManager.default.fileExists(atPath: filePath) {
  1294. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  1295. if error != nil {
  1296. NSApp.presentError(error!)
  1297. } else {
  1298. if document is KMMainDocument {
  1299. (document as! KMMainDocument).isNewCreated = true
  1300. }
  1301. }
  1302. }
  1303. }
  1304. }
  1305. }
  1306. @IBAction func importFromScanner(_ sender: Any) {
  1307. deviceBrowserWC = KMDeviceBrowserWindowController.shared
  1308. deviceBrowserWC?.type = .scanner
  1309. deviceBrowserWC?.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  1310. self?.openFile(withFilePath: url as URL)
  1311. }
  1312. deviceBrowserWC?.showWindow(NSApp.mainWindow)
  1313. }
  1314. @IBAction func menuItemClick_mergePDF(_ sender: Any) {
  1315. fastTool_MergePDF()
  1316. }
  1317. @IBAction func menuItemClick_Compress(_ sender: Any) {
  1318. fastTool_Compression()
  1319. }
  1320. @IBAction func menuItemClick_Convert(_ sender: Any) {
  1321. fastTool_ConvertPDF()
  1322. }
  1323. @IBAction func menuItemClick_SettingPassword(_ sender: Any) {
  1324. fastTool_Security()
  1325. }
  1326. @IBAction func menuItemClick_RemovePassword(_ sender: Any) {
  1327. fastTool_Security()
  1328. }
  1329. func fetchUniquePath(_ originalPath: String) -> String {
  1330. var path = originalPath
  1331. let dManager = FileManager.default
  1332. if !dManager.fileExists(atPath: path) {
  1333. if path.extension.count < 1 {
  1334. path = path.stringByAppendingPathExtension("pdf")
  1335. }
  1336. return path
  1337. } else {
  1338. let originalFullFileName = path.lastPathComponent
  1339. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  1340. let originalExtension = path.extension
  1341. let startIndex: Int = 0
  1342. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  1343. let fileLocatePath = originalPath.substring(to: endIndex)
  1344. var i = 1
  1345. while (1 != 0) {
  1346. var newName = String(format: "%@%ld", originalFileName, i)
  1347. newName = String(format: "%@%@", newName, originalExtension)
  1348. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  1349. if !dManager.fileExists(atPath: newPath) {
  1350. return newPath
  1351. } else {
  1352. i+=1
  1353. continue
  1354. }
  1355. }
  1356. }
  1357. }
  1358. // func kNewDocumentTempSavePath(_ fileName: String) -> String {
  1359. // let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  1360. //// let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1361. // let append2 = searchPath!.stringByAppendingPathComponent(String(format: "%@", fileName))
  1362. // return append2
  1363. // }
  1364. // MARK: Notification
  1365. @objc func homeFileRectChange(_ notification: Notification) -> Void {
  1366. let window = notification.object
  1367. self.historyFileViewController.reloadData()
  1368. }
  1369. }
  1370. // MARK: window Menu
  1371. extension KMHomeViewController {
  1372. @IBAction func menuItemAction_showForwardTagPage(_ sender: Any) {
  1373. (self.myDocument as! KMMainDocument).browser.selectPreviousTab()
  1374. }
  1375. @IBAction func menuItemAction_showNextTagPage(_ sender: Any) {
  1376. (self.myDocument as! KMMainDocument).browser.selectNextTab()
  1377. }
  1378. @IBAction func menuItemAction_newTagPageToNewWindow(_ sender: Any) {
  1379. let browser = (self.myDocument as! KMMainDocument).browser
  1380. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.openNewWindow(sender)
  1381. }
  1382. @IBAction func menuItemAction_mergeAllWindow(_ sender: Any) {
  1383. ((self.myDocument as? KMMainDocument)?.browser.windowController as? KMBrowserWindowController)?.mergeAllWindow(sender)
  1384. }
  1385. @IBAction func menuItemAction_currentWindowName(_ sender: Any) {
  1386. }
  1387. }
  1388. // MARK: file Menu
  1389. extension KMHomeViewController {
  1390. @IBAction func menuItemAction_closeWindow(_ sender: Any) {
  1391. self.view.window?.close()
  1392. }
  1393. @IBAction func menuItemAction_closeAllWindows(_ sender: Any) {
  1394. for window in NSApp.windows {
  1395. window.close()
  1396. }
  1397. }
  1398. @IBAction func menuItemAction_ConvertToWord(_ sender: Any) {
  1399. self.fastTool_PDFToWord()
  1400. }
  1401. @IBAction func menuItemAction_ConvertToExcel(_ sender: Any) {
  1402. self.fastTool_PDFToExcel()
  1403. }
  1404. @IBAction func menuItemAction_ConvertToPPT(_ sender: Any) {
  1405. self.fastTool_PDFToPPT()
  1406. }
  1407. @IBAction func menuItemAction_ConvertToRTF(_ sender: Any) {
  1408. self.showConvertWindow(type: .rtf)
  1409. }
  1410. @IBAction func menuItemAction_ConvertToHTML(_ sender: Any) {
  1411. self.showConvertWindow(type: .html)
  1412. }
  1413. @IBAction func menuItemAction_ConvertToText(_ sender: Any) {
  1414. self.showConvertWindow(type: .text)
  1415. }
  1416. @IBAction func menuItemAction_ConvertToCSV(_ sender: Any) {
  1417. self.showConvertWindow(type: .csv)
  1418. }
  1419. @IBAction func menuItemAction_ConvertToImage(_ sender: Any) {
  1420. self.fastTool_PDFToImage()
  1421. }
  1422. }
  1423. // MARK: help Menu
  1424. extension KMHomeViewController {
  1425. // @IBAction func menuItemAction_search(_ sender: Any) {
  1426. //
  1427. // }
  1428. }