KMHomeViewController+Action.swift 56 KB

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