KMHomeViewController+Action.swift 56 KB

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