KMHomeViewController+Action.swift 56 KB

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