KMHomeViewController+Action.swift 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361
  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. }
  780. func fastTool_OCR() { // OCR
  781. // KMOCRWindowController.openFiles(window: self.view.window!)
  782. }
  783. func fastTool_ConvertPDF() { // 转换PDF
  784. // KMBatchWindowController.openFile(nil, .ConvertPDF)
  785. }
  786. func fastTool_ImageToPDF() { // 图片转PDF
  787. // KMImageToPDFWindowController.openFiles(window: NSApp.mainWindow!)
  788. }
  789. func fastTool_MergePDF() { // MergePDF
  790. Task { @MainActor in
  791. // #if VERSION_DMG
  792. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  793. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .merge)
  794. // return
  795. // }
  796. // #endif
  797. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  798. // let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true, type: .merge) { isSubscribeSuccess, isWaterMarkExport, isClose in
  799. // if (isClose) {
  800. // return
  801. // }
  802. // self.km_open_pdf_merge()
  803. // }
  804. // return
  805. // }
  806. self.km_open_pdf_merge()
  807. }
  808. }
  809. func km_open_pdf_merge() {
  810. DispatchQueue.main.async {
  811. NSPanel.km_open_pdf_multi_success(self.view.window!, panel: nil) { urls in
  812. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  813. var filepaths: Array<String> = []
  814. for url in urls {
  815. filepaths.append(url.path)
  816. }
  817. let windowController = KMPDFEditAppendWindow(filePaths: filepaths)
  818. self.currentWindowController = windowController
  819. windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, indexs in
  820. })
  821. }
  822. }
  823. }
  824. }
  825. func fastTool_Compression() { // 压缩
  826. Task { @MainActor in
  827. // #if VERSION_DMG
  828. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  829. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .merge)
  830. // return
  831. // }
  832. // #endif
  833. self.km_secure_openPanel_compress()
  834. }
  835. }
  836. func km_secure_openPanel_compress() {
  837. DispatchQueue.main.async {
  838. NSOpenPanel.km_secure_openPanel(window: self.view.window!) { url, result, passowrd in
  839. if (url == nil) {
  840. return
  841. }
  842. if (result != nil && result! == .cancel) {
  843. return
  844. }
  845. self.showCompressWindow(url!, passowrd)
  846. }
  847. }
  848. }
  849. func showCompressWindow(_ url: URL, _ password: String?) {
  850. Task { @MainActor in
  851. let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  852. windowController.documentURL = url
  853. windowController.password = password
  854. windowController.itemClick = { [weak self] _ in
  855. self?.km_endSheet()
  856. }
  857. windowController.resultCallback = { [weak self] result, openDocument, fileURL, _ in
  858. if result {
  859. self?.km_endSheet()
  860. if openDocument {
  861. NSDocumentController.shared.km_safe_openDocument(withContentsOf: fileURL, display: true) { _, _, _ in
  862. }
  863. } else {
  864. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  865. }
  866. } else {
  867. let alert = NSAlert()
  868. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  869. alert.runModal()
  870. }
  871. }
  872. self.km_beginSheet(windowC: windowController)
  873. }
  874. }
  875. func fastTool_Security() { // 安全
  876. self.showSecurityWindow()
  877. }
  878. func fastTool_FileCompare() { // 文件对比
  879. KMPrint("选中 快捷工具 文件对比")
  880. }
  881. func fastTool_PDFToPPT() {
  882. self.showConvertWindow(type: .ppt)
  883. }
  884. func fastTool_PDFToExcel() {
  885. self.showConvertWindow(type: .excel)
  886. }
  887. func fastTool_PDFToWord() { // PDF转Word
  888. self.showConvertWindow(type: .word)
  889. }
  890. func fastTool_PDFToImage() { // PDF转图片
  891. self.showConvertWindow(type: .image)
  892. }
  893. func fastTool_Watermark() { // 水印
  894. // KMBatchWindowController.openFile(nil, .Watermark)
  895. }
  896. func fastTool_Background() { // 背景
  897. // KMBatchWindowController.openFile(nil, .Background)
  898. }
  899. func fastTool_HeaderAndFooter() { // 页眉页脚
  900. // KMBatchWindowController.openFile(nil, .HeaderAndFooter)
  901. }
  902. func fastTool_BatesCode() { // 贝茨码
  903. // KMBatchWindowController.openFile(nil, .BatesCode)
  904. }
  905. func fastTool_Print() { // 打印
  906. KMPrintWindowController.openFiles(window: self.view.window!)
  907. }
  908. func fastTool_BatchRemove() { // 批量移除
  909. // KMBatchWindowController.openFile(nil, .BatchRemove)
  910. }
  911. func fastTool_Insert() { // 插入
  912. let openPanel = NSOpenPanel()
  913. openPanel.prompt = "插入"
  914. openPanel.allowsMultipleSelection = false
  915. openPanel.allowedFileTypes = ["pdf"]
  916. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  917. if result == .OK {
  918. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  919. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Insert)
  920. insertWindowController.beginSheetModal(for: self.view.window!) { pdfDocument, password, pages, indexPage in
  921. self.insertPageAction(pdfDocument, password, pages, indexPage)
  922. }
  923. }
  924. }
  925. }
  926. }
  927. func fastTool_BreakUp() { // 拆分
  928. let openPanel = NSOpenPanel()
  929. openPanel.prompt = "提取"
  930. openPanel.allowsMultipleSelection = false
  931. openPanel.allowedFileTypes = ["pdf"]
  932. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  933. if result == .OK {
  934. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  935. let document = CPDFDocument(url: openPanel.url)
  936. let model = KMPageEditSplitSettingModel()
  937. model.documentURL = openPanel.url
  938. model.fileName = model.documentURL.lastPathComponent
  939. model.pathExtension = model.fileName.components(separatedBy: ".").last
  940. let windowController = KMPageEditSplitWindowController(model)
  941. windowController.hasPreView = true
  942. self.view.window?.beginSheet(windowController.window!)
  943. self.currentWindowController = windowController
  944. windowController.itemClick = { [weak self] index, value in
  945. if (index == 1) { /// 取消
  946. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  947. self?.currentWindowController = nil
  948. return
  949. }
  950. /// 拆分
  951. let windowController_split: KMPageEditSplitWindowController = self?.currentWindowController as! KMPageEditSplitWindowController
  952. let outputModel: KMPageEditSplitSettingModel = windowController_split.model! as! KMPageEditSplitSettingModel
  953. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  954. self?.currentWindowController = nil
  955. let panel = NSOpenPanel()
  956. panel.canChooseFiles = false
  957. panel.canChooseDirectories = true
  958. panel.canCreateDirectories = true
  959. panel.beginSheetModal(for: (self?.view.window)!) { response in
  960. KMPageEditTools.split(document!, outputModel, panel.url!.path, outputModel.outputFileNameDeletePathExtension) { result, outputDocuments, error in
  961. if (result) {
  962. }
  963. }
  964. }
  965. }
  966. }
  967. }
  968. }
  969. }
  970. func fastTool_Extract() { // 提取
  971. let openPanel = NSOpenPanel()
  972. openPanel.prompt = "提取"
  973. openPanel.allowsMultipleSelection = false
  974. openPanel.allowedFileTypes = ["pdf"]
  975. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  976. if result == .OK {
  977. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  978. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Extract)
  979. insertWindowController.beginSheetExtractModal(for: self.view.window!) { pdfDocument, pages, oneDocumentPerPage, isDeletePage in
  980. self.extractPageAction(pdfDocument, pages, oneDocumentPerPage, isDeletePage)
  981. }
  982. }
  983. }
  984. }
  985. }
  986. func fastTool_MarkCipher() { // 标记密文
  987. let openPanel = NSOpenPanel()
  988. openPanel.allowsMultipleSelection = false
  989. openPanel.allowedFileTypes = ["pdf"]
  990. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  991. if result == .cancel {
  992. return
  993. }
  994. if !openPanel.url!.path.isPDFValid() {
  995. let alert = NSAlert()
  996. alert.alertStyle = .critical
  997. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  998. alert.runModal()
  999. return
  1000. }
  1001. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1002. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1003. if (error != nil) {
  1004. NSApp.presentError(error!)
  1005. return
  1006. }
  1007. let toolbar = (document as! KMMainDocument).mainViewController?.toolbarController
  1008. toolbar?.enterRedact()
  1009. }
  1010. }
  1011. }
  1012. }
  1013. func fastTool_AutomaticFormRecognition() { // 表单自动识别
  1014. let openPanel = NSOpenPanel()
  1015. openPanel.prompt = "表单自动识别"
  1016. openPanel.allowsMultipleSelection = false
  1017. openPanel.allowedFileTypes = ["pdf"]
  1018. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1019. if result == .OK {
  1020. }
  1021. }
  1022. }
  1023. func fastTool_PageEdit() { // 页面编辑
  1024. let openPanel = NSOpenPanel()
  1025. openPanel.allowsMultipleSelection = false
  1026. openPanel.allowedFileTypes = ["pdf"]
  1027. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1028. if result == .cancel {
  1029. return
  1030. }
  1031. if !openPanel.url!.path.isPDFValid() {
  1032. let alert = NSAlert()
  1033. alert.alertStyle = .critical
  1034. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1035. alert.runModal()
  1036. return
  1037. }
  1038. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1039. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1040. if (error != nil) {
  1041. NSApp.presentError(error!)
  1042. return
  1043. }
  1044. let mainView = (document as! KMMainDocument).mainViewController
  1045. mainView?.enterPageEdit()
  1046. }
  1047. }
  1048. }
  1049. }
  1050. @IBAction func escButtonAction(_ sender: Any) {
  1051. // self.historyFileViewController.selectFiles.removeAll()
  1052. // if self.historyFileViewController.showMode == .Thumbnail {
  1053. // self.historyFileViewController.historyFileCollectionView.reloadData()
  1054. // } else {
  1055. // self.historyFileViewController.historyFileTableView.reloadData()
  1056. // }
  1057. }
  1058. @IBAction func importFromFile(_ sender: Any) {
  1059. self.openSupportPDFButtonAction()
  1060. }
  1061. @IBAction func menuItemClick_mergePDF(_ sender: Any) {
  1062. fastTool_MergePDF()
  1063. }
  1064. @IBAction func menuItemClick_Compress(_ sender: Any) {
  1065. fastTool_Compression()
  1066. }
  1067. @IBAction func menuItemClick_Convert(_ sender: Any) {
  1068. fastTool_ConvertPDF()
  1069. }
  1070. @IBAction func menuItemClick_SettingPassword(_ sender: Any) {
  1071. fastTool_Security()
  1072. }
  1073. @IBAction func menuItemClick_RemovePassword(_ sender: Any) {
  1074. fastTool_Security()
  1075. }
  1076. func fetchUniquePath(_ originalPath: String) -> String {
  1077. var path = originalPath
  1078. let dManager = FileManager.default
  1079. if !dManager.fileExists(atPath: path) {
  1080. if path.extension.count < 1 {
  1081. path = path.stringByAppendingPathExtension("pdf")
  1082. }
  1083. return path
  1084. } else {
  1085. let originalFullFileName = path.lastPathComponent
  1086. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  1087. let originalExtension = path.extension
  1088. let startIndex: Int = 0
  1089. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  1090. let fileLocatePath = originalPath.substring(to: endIndex)
  1091. var i = 1
  1092. while (1 != 0) {
  1093. var newName = String(format: "%@%ld", originalFileName, i)
  1094. newName = String(format: "%@%@", newName, originalExtension)
  1095. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  1096. if !dManager.fileExists(atPath: newPath) {
  1097. return newPath
  1098. } else {
  1099. i+=1
  1100. continue
  1101. }
  1102. }
  1103. }
  1104. }
  1105. // func kNewDocumentTempSavePath(_ fileName: String) -> String {
  1106. // let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  1107. //// let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1108. // let append2 = searchPath!.stringByAppendingPathComponent(String(format: "%@", fileName))
  1109. // return append2
  1110. // }
  1111. // MARK: Notification
  1112. @objc func homeFileRectChange(_ notification: Notification) -> Void {
  1113. let window = notification.object
  1114. self.historyFileViewController.reloadData()
  1115. }
  1116. }
  1117. // MARK: window Menu
  1118. extension KMHomeViewController {
  1119. @IBAction func menuItemAction_showForwardTagPage(_ sender: Any) {
  1120. (self.myDocument as! KMMainDocument).browser.selectPreviousTab()
  1121. }
  1122. @IBAction func menuItemAction_showNextTagPage(_ sender: Any) {
  1123. (self.myDocument as! KMMainDocument).browser.selectNextTab()
  1124. }
  1125. @IBAction func menuItemAction_newTagPageToNewWindow(_ sender: Any) {
  1126. let browser = (self.myDocument as! KMMainDocument).browser
  1127. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.openNewWindow(sender)
  1128. }
  1129. @IBAction func menuItemAction_mergeAllWindow(_ sender: Any) {
  1130. ((self.myDocument as? KMMainDocument)?.browser.windowController as? KMBrowserWindowController)?.mergeAllWindow(sender)
  1131. }
  1132. @IBAction func menuItemAction_currentWindowName(_ sender: Any) {
  1133. }
  1134. }
  1135. // MARK: file Menu
  1136. extension KMHomeViewController {
  1137. @IBAction func menuItemAction_closeWindow(_ sender: Any) {
  1138. self.view.window?.close()
  1139. }
  1140. @IBAction func menuItemAction_closeAllWindows(_ sender: Any) {
  1141. for window in NSApp.windows {
  1142. window.close()
  1143. }
  1144. }
  1145. @IBAction func menuItemAction_ConvertToWord(_ sender: Any) {
  1146. self.fastTool_PDFToWord()
  1147. }
  1148. @IBAction func menuItemAction_ConvertToExcel(_ sender: Any) {
  1149. self.fastTool_PDFToExcel()
  1150. }
  1151. @IBAction func menuItemAction_ConvertToPPT(_ sender: Any) {
  1152. self.fastTool_PDFToPPT()
  1153. }
  1154. @IBAction func menuItemAction_ConvertToRTF(_ sender: Any) {
  1155. self.showConvertWindow(type: .rtf)
  1156. }
  1157. @IBAction func menuItemAction_ConvertToHTML(_ sender: Any) {
  1158. self.showConvertWindow(type: .html)
  1159. }
  1160. @IBAction func menuItemAction_ConvertToText(_ sender: Any) {
  1161. self.showConvertWindow(type: .text)
  1162. }
  1163. @IBAction func menuItemAction_ConvertToCSV(_ sender: Any) {
  1164. self.showConvertWindow(type: .csv)
  1165. }
  1166. @IBAction func menuItemAction_ConvertToImage(_ sender: Any) {
  1167. self.fastTool_PDFToImage()
  1168. }
  1169. }
  1170. // MARK: help Menu
  1171. extension KMHomeViewController {
  1172. // @IBAction func menuItemAction_search(_ sender: Any) {
  1173. //
  1174. // }
  1175. }
  1176. // MARK: - Analytics (埋点)
  1177. extension KMHomeViewController {
  1178. func trackEvent_ai(eventName: String) -> Void {
  1179. KMAnalytics.trackEvent(eventName: eventName, parameters: [
  1180. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.home,
  1181. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.ai_Btn], platform: .AppCenter, appTarget: .all)
  1182. }
  1183. func trackEvent_create(eventName: String) -> Void {
  1184. KMAnalytics.trackEvent(eventName: eventName, parameters: [
  1185. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.home,
  1186. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.create_Btn], platform: .AppCenter, appTarget: .all)
  1187. }
  1188. }