KMHomeViewController+Action.swift 63 KB

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