KMHomeViewController+Action.swift 56 KB

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