KMHomeViewController+Action.swift 59 KB

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