KMHomeViewController+Action.swift 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976
  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. fastTool_FileCompare()
  152. break
  153. case .equity:
  154. break
  155. case .PrintMultipage:
  156. break
  157. case .PrintPoster:
  158. break
  159. case .PrintBooklet:
  160. break
  161. }
  162. }
  163. func openPDFButtonAction() {
  164. NSPanel.km_open_pdf_multi_success(self.view.window!, panel: nil) { urls in
  165. for url in urls {
  166. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url, display: true) { _, _, _ in
  167. }
  168. }
  169. }
  170. }
  171. func openSupportPDFButtonAction() {
  172. var window = self.view.window
  173. if (window == nil) {
  174. window = NSApp.mainWindow
  175. }
  176. NSOpenPanel.km_open_multi(window!) { panel in
  177. // if let data = KMConvertPDFManager.supportFileType() as? [String], !data.isEmpty {
  178. panel.allowedFileTypes = KMTools.pdfExtensions + KMConvertPDFManager.supportFileType()
  179. // } else {
  180. // panel.allowedFileTypes = KMTools.pdfExtensions + KMTools.imageExtensions
  181. // }
  182. } completion: { [weak self] result , urls in
  183. if result == .OK {
  184. var imageUrl: [URL] = []
  185. for url in urls! {
  186. let type = url.pathExtension.lowercased()
  187. if (type == "pdf" || type == "PDF") {
  188. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url, display: true) { _, _, _ in
  189. }
  190. } else if (type == "jpg") ||
  191. (type == "cur") ||
  192. (type == "bmp") ||
  193. (type == "jpeg") ||
  194. (type == "gif") ||
  195. (type == "png") ||
  196. (type == "tiff") ||
  197. (type == "tif") ||
  198. (type == "ico") ||
  199. (type == "icns") ||
  200. (type == "tga") ||
  201. (type == "psd") ||
  202. (type == "eps") ||
  203. (type == "hdr") ||
  204. (type == "jp2") ||
  205. (type == "jpc") ||
  206. (type == "pict") ||
  207. (type == "sgi") ||
  208. (type == "heic") {
  209. self?.openImageFile(url: url)
  210. } else if (type == "doc") ||
  211. (type == "docx") ||
  212. (type == "xls") ||
  213. (type == "xlsx") ||
  214. (type == "ppt") ||
  215. (type == "pptx") ||
  216. (type == "pptx") {
  217. self?.openOfficeFile(url: url)
  218. }
  219. }
  220. }
  221. }
  222. }
  223. func homeButtonAction() {
  224. refreshRightBoxUI(.Home)
  225. }
  226. func pdfToolsButtonAction() {
  227. refreshRightBoxUI(.PDFTools)
  228. }
  229. func favoriteDocumentsButtonAction() {
  230. KMPrint("Favorite Documents")
  231. }
  232. func cloudDocumentsButtonAction() {
  233. refreshRightBoxUI(.CloudDocuments)
  234. }
  235. func productPromotionClickAction(_ name: NSString) {
  236. var httpString: NSString = ""
  237. if name.isEqual(to: "Windows") {
  238. httpString = "https://www.pdfreaderpro.com/windows?utm_source=MacApp&utm_campaign=PDFProMac&utm_medium=pdfmac_promo"
  239. } else if name.isEqual(to: "iPhone / iPad") {
  240. #if VERSION_FREE
  241. #if VERSION_DMG
  242. httpString = "https://www.pdfreaderpro.com/product?utm_source=MacAppDmg&utm_campaign=ProductLinkLeftNav&utm_medium=PdfProduct"
  243. #else
  244. httpString = "https://www.pdfreaderpro.com/product?utm_source=MacAppLite&utm_campaign=ProductLinkLeftNav&utm_medium=PdfProduct"
  245. #endif
  246. #else
  247. httpString = "https://www.pdfreaderpro.com/product?utm_source=MacApp&utm_campaign=ProductLinkLeftNav&utm_medium=PdfProduct"
  248. #endif
  249. } else if name.isEqual(to: "Android") {
  250. httpString = "https://www.pdfreaderpro.com/pdfreaderpro-android?utm_source=MacAppDmg&utm_campaign=AndroidLink&utm_medium=PdfAndroid"
  251. } else if name.isEqual(to: "ComPDFKit") {
  252. httpString = "https://www.compdf.com?utm_source=macapp&utm_medium=pdfmac&utm_campaign=compdfkit-promp"
  253. } else if name.isEqual(to: "ComVideoKit") {
  254. httpString = "https://www.filmagepro.com/video-sdk?utm_source=macapp&utm_medium=pdfmac&utm_campaign=comvideosdk-promo"
  255. } else if name.isEqual(to: "SignFlow") {
  256. httpString = "https://apps.apple.com/app/apple-store/id1584624017?pt=118745145&ct=pdfmac-promo&mt=8"
  257. } else if name.isEqual(to: "FiImage Editor") {
  258. httpString = "https://apps.apple.com/app/apple-store/id1475051178?pt=118745145&ct=pdfmac-promo&mt=8"
  259. } else if name.isEqual(to: "FiImage Screen") {
  260. httpString = "https://apps.apple.com/app/apple-store/id1475049179?pt=118745145&ct=pdfmac-promo&mt=8"
  261. } else if name.isEqual(to: "Free PDF Templates") {
  262. httpString = "https://www.pdfreaderpro.com/templates?utm_source=MacApp&utm_campaign=PDFProMac&utm_medium=pdfmac_promo"
  263. }
  264. self.workSpaceOpenUrl(httpString)
  265. }
  266. func historyFile(deleteDocuments indexPaths: [URL]) {
  267. if UserDefaults.standard.bool(forKey: "kHistoryDeleteNOReminderKey") {
  268. historyFileDeleteAction(indexPaths)
  269. } else {
  270. let historyFileDeleteVC: KMHistoryFileDeleteWindowController = KMHistoryFileDeleteWindowController.init(windowNibName: NSNib.Name("KMHistoryFileDeleteWindowController"))
  271. historyFileDeleteVC.indexPaths = indexPaths
  272. self.currentWindowController = historyFileDeleteVC
  273. historyFileDeleteVC.deleteCallback = { [weak self](indexPaths: [URL], windowController: KMHistoryFileDeleteWindowController) -> Void in
  274. if self != nil {
  275. self?.currentWindowController = nil
  276. self!.historyFileDeleteAction(indexPaths)
  277. }
  278. }
  279. self.view.window?.beginSheet(historyFileDeleteVC.window!)
  280. }
  281. }
  282. func historyFileDeleteAction(_ indexPaths: [URL]) -> Void {
  283. let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
  284. NSDocumentController.shared.clearRecentDocuments(nil)
  285. DispatchQueue.main.asyncAfter(deadline: .now()) { [self] in
  286. for (_, url) in urls.enumerated() {
  287. if !indexPaths.contains(url) {
  288. NSDocumentController.shared.noteNewRecentDocumentURL(url)
  289. }
  290. }
  291. self.homeContentView.historyListView.reloadData()
  292. }
  293. }
  294. func openHistoryFilePath(url: URL) -> Void {
  295. if !url.path.isPDFValid() {
  296. let alert = NSAlert()
  297. alert.alertStyle = .critical
  298. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  299. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  300. self.homeContentView.historyListView.reloadData()
  301. // self.historyFileViewController.reloadData()
  302. }
  303. return
  304. }
  305. if url.pathExtension.lowercased() == "pdf" {
  306. let pdfDoc = CPDFDocument.init(url: url)
  307. if pdfDoc != nil {
  308. let document = NSDocumentController.shared.document(for: url)
  309. var alreadyOpen = false
  310. for openDocument in NSDocumentController.shared.documents {
  311. if document == openDocument {
  312. alreadyOpen = true
  313. }
  314. }
  315. if !alreadyOpen {
  316. KMMainDocument().tryToUnlockDocument(pdfDoc!)
  317. var selectDocument: KMMainDocument? = nil
  318. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  319. selectDocument = (document as! KMMainDocument)
  320. }
  321. if selectDocument != nil {
  322. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  323. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  324. if (selectDocument?.browser.window.isVisible)! as Bool {
  325. selectDocument?.browser.window.orderFront(nil)
  326. } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  327. selectDocument?.browser.window.orderFront(nil)
  328. }
  329. } else {
  330. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url, display: true) { _, _, _ in
  331. }
  332. }
  333. } else {
  334. var selectDocument: KMMainDocument? = nil
  335. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  336. selectDocument = (document as! KMMainDocument)
  337. }
  338. if selectDocument != nil {
  339. if selectDocument?.browser != nil {
  340. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  341. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  342. if (selectDocument?.browser.window.isVisible)! as Bool {
  343. selectDocument?.browser.window.orderFront(nil)
  344. } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  345. selectDocument?.browser.window.orderFront(nil)
  346. }
  347. }
  348. } else {
  349. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url, display: true) { _, _, _ in
  350. }
  351. }
  352. }
  353. } else {
  354. let alert = NSAlert()
  355. alert.alertStyle = .critical
  356. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  357. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  358. self.homeContentView.historyListView.reloadData()
  359. // self.historyFileViewController.reloadData()
  360. }
  361. }
  362. } else {
  363. NSWorkspace.shared.open(url)
  364. }
  365. }
  366. func openFile(withFilePath path: URL) -> Void {
  367. let type = path.pathExtension.lowercased()
  368. if (type == "pdf") {
  369. if !path.path.isPDFValid() {
  370. let alert = NSAlert()
  371. alert.alertStyle = .critical
  372. alert.messageText = NSLocalizedString("This file format is not supported, please drag in PDF, picture, Office format files", comment: "")
  373. alert.runModal()
  374. return
  375. }
  376. NSDocumentController.shared.openDocument(withContentsOf: path, display: true) { document, documentWasAlreadyOpen, error in
  377. if error != nil {
  378. NSApp.presentError(error!)
  379. return
  380. }
  381. }
  382. } else if (type == "jpg") ||
  383. (type == "cur") ||
  384. (type == "bmp") ||
  385. (type == "jpeg") ||
  386. (type == "gif") ||
  387. (type == "png") ||
  388. (type == "tiff") ||
  389. (type == "tif") ||
  390. (type == "ico") ||
  391. (type == "icns") ||
  392. (type == "tga") ||
  393. (type == "psd") ||
  394. (type == "eps") ||
  395. (type == "hdr") ||
  396. (type == "jp2") ||
  397. (type == "jpc") ||
  398. (type == "pict") ||
  399. (type == "sgi") ||
  400. (type == "heic") {
  401. openImageFile(url: path)
  402. } else if (type == "doc") ||
  403. (type == "docx") ||
  404. (type == "xls") ||
  405. (type == "xlsx") ||
  406. (type == "ppt") ||
  407. (type == "pptx") ||
  408. (type == "pptx") {
  409. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  410. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
  411. openOfficeFile(url: path)
  412. }
  413. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  414. self.homeContentView.historyListView.reloadData()
  415. }
  416. }
  417. func openImageFile(url: URL) -> Void {
  418. var filePath = url.path
  419. let fileName: NSString = url.lastPathComponent as NSString
  420. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String).deletingLastPathComponent
  421. let imageName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension
  422. let path = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".pdf")
  423. if (!FileManager.default.fileExists(atPath: path.deletingLastPathComponent as String)) {
  424. try?FileManager.default.createDirectory(atPath: path.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  425. }
  426. if (!FileManager.default.fileExists(atPath: path as String)) {
  427. FileManager.default.createFile(atPath: path as String, contents: nil)
  428. }
  429. let document = CPDFDocument.init()
  430. var success = false
  431. if NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "png" ||
  432. NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "PNG" {
  433. let jpgPath = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".jpg")
  434. if (!FileManager.default.fileExists(atPath: jpgPath as String)) {
  435. FileManager.default.createFile(atPath: jpgPath as String, contents: nil)
  436. }
  437. // 加载 PNG 图像
  438. guard let pngImage = NSImage(contentsOfFile: filePath) else {
  439. KMPrint("Failed to load PNG image")
  440. return
  441. }
  442. // 创建 NSBitmapImageRep 对象,并将 PNG 图像绘制到其中
  443. let bitmap = NSBitmapImageRep(data: pngImage.tiffRepresentation!)
  444. let rect = NSRect(origin: .zero, size: bitmap!.size)
  445. bitmap?.draw(in: rect)
  446. // 将 PNG 图像数据转换为 JPG 图像数据
  447. guard let jpgData = bitmap?.representation(using: .jpeg, properties: [:]) else {
  448. KMPrint("Failed to convert PNG to JPG")
  449. return
  450. }
  451. // 保存 JPG 图像数据到文件
  452. let fileURL = URL(fileURLWithPath: jpgPath)
  453. do {
  454. try jpgData.write(to: fileURL)
  455. filePath = fileURL.path
  456. KMPrint("JPG image saved successfully")
  457. } catch {
  458. KMPrint("Failed to save JPG image: \(error.localizedDescription)")
  459. }
  460. }
  461. //FIXME: 无法插入图片
  462. let image = NSImage(contentsOfFile: filePath)
  463. let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount)
  464. if insertPageSuccess != nil {
  465. //信号量控制异步
  466. let semaphore = DispatchSemaphore(value: 0)
  467. DispatchQueue.global().async {
  468. success = ((document?.write(toFile: path)) != nil)
  469. semaphore.signal()
  470. }
  471. semaphore.wait()
  472. } else {
  473. }
  474. if success {
  475. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { _, _, _ in
  476. }
  477. }
  478. }
  479. func openOfficeFile(url: URL) -> Void {
  480. let filePath = url.path
  481. let folderPath = "convertToPDF.pdf"
  482. let savePath: String? = folderPath.kUrlToPDFFolderPath() as String
  483. if (!FileManager.default.fileExists(atPath: savePath!.deletingLastPathComponent as String)) {
  484. try?FileManager.default.createDirectory(atPath: savePath!.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  485. }
  486. if (!FileManager.default.fileExists(atPath: savePath! as String)) {
  487. FileManager.default.createFile(atPath: savePath! as String, contents: nil)
  488. }
  489. if savePath == nil {
  490. return
  491. }
  492. KMConvertPDFManager.convertFile(filePath, savePath: savePath!) { success, errorDic in
  493. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  494. if FileManager.default.fileExists(atPath: savePath!) {
  495. try?FileManager.default.removeItem(atPath: savePath!)
  496. }
  497. let alert = NSAlert.init()
  498. alert.alertStyle = .critical
  499. var infoString = ""
  500. if errorDic != nil {
  501. for key in (errorDic! as Dictionary).keys {
  502. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  503. }
  504. }
  505. alert.informativeText = NSLocalizedString("Please install Microsoft Office to create PDFs from Office files", comment: "")
  506. alert.messageText = NSLocalizedString("Failed to Create PDF", comment: "")
  507. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  508. alert.runModal()
  509. return
  510. }
  511. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: savePath!), display: true) { _, _, _ in
  512. }
  513. }
  514. }
  515. func aiTranslation(withFilePath path: String) -> Void {
  516. if !KMLightMemberManager.manager.isLogin() {
  517. KMLoginWindowController.show(window: NSApp.mainWindow!)
  518. return
  519. }
  520. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: path)
  521. if self.isFileGreaterThan10MB(atPath: path) {
  522. self.aiTranslationViewController.errorView.isHidden = false
  523. self.aiTranslationViewController.errorLabel.stringValue = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  524. } else if isExceedsLimit {
  525. self.aiTranslationViewController.errorView.isHidden = false
  526. self.aiTranslationViewController.errorLabel.stringValue = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  527. } else {
  528. let url = URL(fileURLWithPath: path)
  529. if (url.pathExtension == "pdf") || url.pathExtension == "PDF" {
  530. if !path.isPDFValid() {
  531. let alert = NSAlert()
  532. alert.alertStyle = .critical
  533. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  534. alert.runModal()
  535. return
  536. }
  537. }
  538. let infoDictionary = Bundle .main.infoDictionary!
  539. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  540. DispatchQueue.main.async {
  541. self.showProgressWindow()
  542. self.progressController?.maxValue = Double(100)
  543. }
  544. timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerTick), userInfo: nil, repeats: true)
  545. KMRequestServerManager.manager.aiTranslationFileUpload(file: path, version: majorVersion as! String) { [unowned self] success, result in
  546. if success {
  547. let result: NSDictionary = result!.result
  548. let fileKey = result["fileKey"]
  549. let fileName = result["fileName"]
  550. let pageCount = result["pageCount"]
  551. if fileKey != nil {
  552. self.fileTranslateHandle(fileKey as! String)
  553. }
  554. } else {
  555. let result: String = result!.message
  556. DispatchQueue.main.async {
  557. self.hiddenProgressWindow()
  558. self.aiTranslationViewController.errorView.isHidden = false
  559. self.aiTranslationViewController.errorLabel.stringValue = result
  560. }
  561. }
  562. }
  563. }
  564. }
  565. func fileTranslateHandle(_ fileKey: String) -> Void {
  566. let infoDictionary = Bundle .main.infoDictionary!
  567. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  568. let languageArr = UserDefaults.standard.array(forKey: "KMAITranslationLanguageArrayKey1") as? [String] ?? [NSLocalizedString("Automatic", comment: ""), NSLocalizedString("English", comment: "")]
  569. let language1 = self.aiTranslationViewController.languageAbbreviation(languageArr[0])
  570. let language2 = self.aiTranslationViewController.languageAbbreviation(languageArr[1])
  571. KMRequestServerManager.manager.aiTranslationFileTranslateHandle(fileKey: fileKey, from: language1, to: language2, version: majorVersion as! String) { success, result in
  572. if success {
  573. let result: NSDictionary = result!.result
  574. let fileUrl: String = result["fileUrl"] as! String
  575. let downFileUrl: String = result["downFileUrl"] as! String
  576. let ossDownUrl: String = result["ossDownUrl"] as! String
  577. let fileName: String = result["fileName"] as! String
  578. let downFileName: String = result["downFileName"] as! String
  579. let from: String = result["from"] as! String
  580. let to: String = result["to"] as! String
  581. self.downloadFile(filePath: ossDownUrl, downFileName: downFileName)
  582. } else {
  583. let result: String = result!.message
  584. DispatchQueue.main.async {
  585. self.hiddenProgressWindow()
  586. self.aiTranslationViewController.errorView.isHidden = false
  587. self.aiTranslationViewController.errorLabel.stringValue = result
  588. }
  589. }
  590. }
  591. }
  592. func downloadFile(filePath: String, downFileName: String) -> Void {
  593. guard let fileURL = URL(string: filePath) else {
  594. let alert = NSAlert()
  595. alert.alertStyle = .critical
  596. alert.messageText = NSLocalizedString("Invalid file link", comment: "")
  597. alert.runModal()
  598. return
  599. }
  600. let destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent(downFileName)
  601. if FileManager.default.fileExists(atPath: destinationURL.path) {
  602. do {
  603. try FileManager.default.removeItem(at: destinationURL)
  604. KMPrint("删除旧文件成功")
  605. } catch {
  606. KMPrint("删除旧文件失败:\(error)")
  607. }
  608. }
  609. let sessionConfiguration = URLSessionConfiguration.default
  610. let session = URLSession(configuration: sessionConfiguration)
  611. let downloadTask = session.downloadTask(with: fileURL) { (tempLocalURL, response, error) in
  612. if let error = error {
  613. let alert = NSAlert()
  614. alert.alertStyle = .critical
  615. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Download failed", comment: ""))
  616. alert.runModal()
  617. return
  618. }
  619. guard let tempLocalURL = tempLocalURL else {
  620. let alert = NSAlert()
  621. alert.alertStyle = .critical
  622. alert.messageText = NSLocalizedString("Invalid temporary directory", comment: "")
  623. alert.runModal()
  624. return
  625. }
  626. DispatchQueue.main.async {
  627. self.hiddenProgressWindow()
  628. }
  629. do {
  630. try FileManager.default.moveItem(at: tempLocalURL, to: destinationURL)
  631. NSDocumentController.shared.openDocument(withContentsOf: destinationURL, display: true) { document, documentWasAlreadyOpen, error in
  632. if error != nil {
  633. NSApp.presentError(error!)
  634. } else {
  635. }
  636. }
  637. } catch {
  638. let alert = NSAlert()
  639. alert.alertStyle = .critical
  640. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Failed to save file", comment: ""))
  641. alert.runModal()
  642. }
  643. }
  644. downloadTask.resume()
  645. }
  646. override func otherMouseDown(with event: NSEvent) {
  647. if historyFileViewController.selectFiles.count > 0 {
  648. let eventPoint = event.locationInWindow as NSPoint
  649. let x = eventPoint.x - 270.0
  650. if x >= 0 {
  651. let point = NSPoint(x: x, y: eventPoint.y)
  652. let historyPoint = historyFileViewController.historyFileCollectionView.convert(eventPoint, from: nil)
  653. var indexPath: IndexPath? = nil
  654. if historyFileViewController.showMode == .List {
  655. let rowIndex = historyFileViewController.historyFileTableView.row(at: historyPoint)
  656. // 查找列索引
  657. let columnIndex = historyFileViewController.historyFileTableView.column(at: point)
  658. // 使用行和列索引创建 indexPath
  659. if rowIndex != -1 {
  660. indexPath = IndexPath(item: columnIndex, section: rowIndex)
  661. }
  662. } else {
  663. indexPath = historyFileViewController.historyFileCollectionView.indexPathForItem(at: historyPoint)
  664. }
  665. if (historyFileViewController.historyFileCollectionView.frame.contains(point) ||
  666. historyFileViewController.historyFileTableView.frame.contains(point) ||
  667. historyFileViewController.deleteBox.frame.contains(point) ||
  668. historyFileViewController.listBox.frame.contains(point) ||
  669. historyFileViewController.thumbnailBox.frame.contains(point)) && indexPath != nil {
  670. } else {
  671. self.historyFileViewController.selectFiles.removeAll()
  672. self.historyFileViewController.selectFiles_shift.removeAll()
  673. if self.historyFileViewController.showMode == .Thumbnail {
  674. self.historyFileViewController.historyFileCollectionView.reloadData()
  675. } else {
  676. self.historyFileViewController.historyFileTableView.reloadData()
  677. }
  678. }
  679. } else {
  680. self.historyFileViewController.selectFiles.removeAll()
  681. self.historyFileViewController.selectFiles_shift.removeAll()
  682. if self.historyFileViewController.showMode == .Thumbnail {
  683. self.historyFileViewController.historyFileCollectionView.reloadData()
  684. } else {
  685. self.historyFileViewController.historyFileTableView.reloadData()
  686. }
  687. }
  688. }
  689. }
  690. // MARK: PDF Tools
  691. // 插入
  692. func insertPageAction(_ pdfDocument: CPDFDocument, _ password: String, _ pages: [CPDFPage], _ indexPage: Int) -> Void {
  693. if indexPage >= 0 {
  694. let insertPages: [CPDFPage] = pages
  695. for i in 0...insertPages.count-1 {
  696. let page = pages[i]
  697. // FIXME: 待底层库修改,使用 insertPageObject 插入,插入位置变为文档最后,暂用 insertPage 代替
  698. pdfDocument.insertPageObject(page, at: UInt(indexPage + i))
  699. }
  700. self.savePDFDocument(pdfDocument, password: password)
  701. }
  702. }
  703. func extractPageAction(_ pdfDocument: CPDFDocument, _ pages: [CPDFPage], _ oneDocumentPerPage: Bool, _ isDeletePage: Bool) -> Void {
  704. if pages.count < 1 {
  705. let alert = NSAlert()
  706. alert.alertStyle = .critical
  707. alert.messageText = NSLocalizedString("Please select two or more pages first to organize.", comment: "")
  708. alert.runModal()
  709. return
  710. }
  711. if !oneDocumentPerPage {
  712. let fileName = pdfDocument.getFileNameAccordingSelctPages(pages)
  713. let outputSavePanel = NSSavePanel()
  714. outputSavePanel.allowedFileTypes = ["pdf"]
  715. outputSavePanel.nameFieldStringValue = fileName
  716. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  717. if result == .OK {
  718. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  719. let saveFilePath = outputSavePanel.url?.path
  720. DispatchQueue.global().async {
  721. var pdf = CPDFDocument.init()
  722. let success = (pdf!.extractAsOneDocument(withPages: pages, savePath: saveFilePath)) as Bool
  723. DispatchQueue.main.async {
  724. if success {
  725. let workspace = NSWorkspace.shared
  726. let url = URL(fileURLWithPath: saveFilePath!)
  727. workspace.activateFileViewerSelecting([url])
  728. if isDeletePage {
  729. for page in pages {
  730. let indexPage = pdfDocument.index(for: page)
  731. pdfDocument.removePage(at: indexPage)
  732. }
  733. }
  734. }
  735. }
  736. }
  737. }
  738. }
  739. }
  740. } else {
  741. let panel = NSOpenPanel()
  742. panel.canChooseFiles = false
  743. panel.canChooseDirectories = true
  744. panel.canCreateDirectories = true
  745. panel.allowsMultipleSelection = false
  746. panel.beginSheetModal(for: self.view.window!) { result in
  747. if result == .OK {
  748. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  749. let outputURL = panel.url
  750. DispatchQueue.global().async {
  751. let folderName = String(pdfDocument.documentURL!.lastPathComponent.split(separator: ".")[0]) + "_extract"
  752. var filePath = URL(fileURLWithPath: outputURL!.path).appendingPathComponent(folderName).path
  753. var i = 1
  754. let testFilePath = filePath
  755. while FileManager.default.fileExists(atPath: filePath) {
  756. filePath = testFilePath + "\(i)"
  757. i += 1
  758. }
  759. try? FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
  760. let successArray = pdfDocument.extractPerPageDocument(withPages: pages, folerPath: filePath)
  761. DispatchQueue.main.async {
  762. if successArray!.count > 0 {
  763. NSWorkspace.shared.activateFileViewerSelecting(successArray!)
  764. if !isDeletePage {
  765. for page in pages {
  766. let indexPage = pdfDocument.index(for: page)
  767. pdfDocument.removePage(at: indexPage)
  768. }
  769. }
  770. }
  771. }
  772. }
  773. }
  774. }
  775. }
  776. }
  777. }
  778. // MARK: 快捷工具 Action
  779. func fastToolDidSelectAllTools() {
  780. // 首页 快捷工具 Tools按钮
  781. refreshRightBoxUI(.PDFTools)
  782. }
  783. func fastTool_Batch() { // Batch
  784. // KMBatchWindowController.openFile(nil, .Batch)
  785. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  786. batchWindowController.window?.makeKeyAndOrderFront("")
  787. }
  788. func fastTool_OCR() { // OCR
  789. // KMOCRWindowController.openFiles(window: self.view.window!)
  790. let openPanel = NSOpenPanel()
  791. var arr = KMImageToPDFMethod.supportedImageTypes()
  792. arr.append("pdf")
  793. openPanel.allowedFileTypes = arr
  794. //MARK: 允许多选还是单选,如果是付费用户允许多选
  795. openPanel.allowsMultipleSelection = false
  796. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  797. if result == NSApplication.ModalResponse.OK {
  798. quickOcr(urls: openPanel.urls)
  799. }
  800. }
  801. }
  802. func quickOcr(urls: Array<URL>) {
  803. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  804. var document: CPDFDocument?
  805. for fileURL in urls {
  806. if fileURL.lastPathComponent.pathExtension == "pdf"{
  807. document = CPDFDocument(url: fileURL)
  808. }else{
  809. document = CPDFDocument()
  810. let image = NSImage(contentsOfFile: fileURL.path)
  811. _ = document?.km_insertPage(image!.size, withImage: fileURL.path, at: 0)
  812. }
  813. break
  814. }
  815. if document == nil{
  816. let alert = NSAlert()
  817. alert.alertStyle = .critical
  818. alert.messageText = KMLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", nil)
  819. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  820. if response == .alertFirstButtonReturn {
  821. // Handle cancel action
  822. }
  823. }
  824. return
  825. }
  826. let com = KMOCRPDFWindowController(cpdfDocument: document!, pwd: document!.password)
  827. self.km_beginSheet(windowC: com)
  828. }
  829. }
  830. func fastTool_ConvertPDF() { // 转换PDF
  831. // KMBatchWindowController.openFile(nil, .ConvertPDF)
  832. let openPanel = NSOpenPanel()
  833. var arr = KMImageToPDFMethod.supportedImageTypes()
  834. arr.append("pdf")
  835. openPanel.allowedFileTypes = ["pdf","PDF"]
  836. //MARK: 允许多选还是单选,如果是付费用户允许多选
  837. openPanel.allowsMultipleSelection = false
  838. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  839. if result == NSApplication.ModalResponse.OK {
  840. quickConvertPdf(urls: openPanel.urls, type: .WordAdvance)
  841. }
  842. }
  843. }
  844. func quickConvertPdf(urls: Array<URL>, type: KMConvertWithPDFType) {
  845. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  846. var arr: Array<KMBatchOperateFile> = Array()
  847. for fileURL in urls {
  848. let img = NSImage(contentsOfFile: fileURL.path)
  849. if self.isDamageImage(image: img, path: fileURL.path) {
  850. let alert = NSAlert()
  851. alert.alertStyle = .critical
  852. alert.messageText = String(format: KMLocalizedString("The file \"%@\" could not be opened.", nil), fileURL.path.lastPathComponent)
  853. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  854. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  855. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  856. if response == .alertFirstButtonReturn {
  857. // Handle cancel action
  858. }
  859. }
  860. continue
  861. }
  862. let file = KMBatchOperateFile(filePath: fileURL.path, type: .Convert)
  863. arr.append(file)
  864. }
  865. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  866. if #available(macOS 10.13, *) {
  867. baseWindowController.window?.makeKeyAndOrderFront(nil)
  868. } else {
  869. baseWindowController.showWindow(nil)
  870. }
  871. if arr.count > 0 {
  872. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: .Convert, files: arr)
  873. }
  874. baseWindowController.switchToConvertType(convertType: type)
  875. }
  876. }
  877. func fastTool_ImageToPDF() { // 图片转PDF
  878. // KMImageToPDFWindowController.openFiles(window: NSApp.mainWindow!)
  879. let openPanel = NSOpenPanel()
  880. openPanel.allowedFileTypes = KMImageToPDFMethod.supportedImageTypes()
  881. //MARK: 允许多选还是单选,如果是付费用户允许多选
  882. openPanel.allowsMultipleSelection = true
  883. 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)
  884. // openPanel.canChooseFiles = false
  885. // openPanel.canChooseDirectories = true
  886. // openPanel.canCreateDirectories = true
  887. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  888. if result == NSApplication.ModalResponse.OK {
  889. openImageToPdfWindow(urls: openPanel.urls)
  890. }
  891. }
  892. }
  893. func openImageToPdfWindow(urls: Array<URL>) {
  894. var arr: Array<KMBatchOperateFile> = Array()
  895. for fileURL in urls {
  896. let img = NSImage(contentsOfFile: fileURL.path)
  897. if self.isDamageImage(image: img, path: fileURL.path) {
  898. let alert = NSAlert()
  899. alert.alertStyle = .critical
  900. alert.messageText = String(format: KMLocalizedString("The file \"%@\" could not be opened.", nil), fileURL.path.lastPathComponent)
  901. alert.informativeText = NSLocalizedString("It may be damaged or use a file format that PDF Reader Pro doesn’t recognize.", comment: "")
  902. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  903. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  904. if response == .alertFirstButtonReturn {
  905. // Handle cancel action
  906. }
  907. }
  908. continue
  909. }
  910. let file = KMBatchOperateFile(filePath: fileURL.path, type: .CreatePDF)
  911. arr.append(file)
  912. }
  913. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  914. if #available(macOS 10.13, *) {
  915. baseWindowController.window?.makeKeyAndOrderFront(nil)
  916. } else {
  917. baseWindowController.showWindow(nil)
  918. }
  919. if arr.count > 0 {
  920. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: .CreatePDF, files: arr)
  921. }
  922. }
  923. func isDamageImage(image: NSImage?, path: String) -> Bool {
  924. if (image == nil) {
  925. return true
  926. }
  927. let addImageAnnotation = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).last!.appendingPathComponent(Bundle.main.bundleIdentifier!).appendingPathComponent("addImageAnnotation")
  928. // let addImageAnnotation = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("addImageAnnotation")
  929. if !FileManager.default.fileExists(atPath: addImageAnnotation.path) {
  930. try? FileManager.default.createDirectory(atPath: addImageAnnotation.path, withIntermediateDirectories: false, attributes: nil)
  931. }
  932. guard let data = image!.tiffRepresentation else { return false }
  933. guard let imageRep = NSBitmapImageRep(data: data) else { return false }
  934. imageRep.size = image!.size
  935. var imageData: Data?
  936. if path.lowercased() == "png" {
  937. imageData = imageRep.representation(using: .png, properties: [:])
  938. } else {
  939. imageData = imageRep.representation(using: .jpeg, properties: [:])
  940. }
  941. let rPath: URL = addImageAnnotation.appendingPathComponent(tagString()).appendingPathExtension("png")
  942. if let data = imageData {
  943. try?data.write(to: rPath)
  944. return false
  945. } else {
  946. return true
  947. }
  948. }
  949. func tagString() -> String {
  950. let dateFormatter = DateFormatter()
  951. dateFormatter.dateFormat = "yyMMddHHmmss"
  952. let currentDate = Date()
  953. let formattedDate = dateFormatter.string(from: currentDate)
  954. let randomNum = Int(arc4random_uniform(10000))
  955. let str = String(format: "%@%04d", dateFormatter.string(from: Date()),randomNum)
  956. return str//"(formattedDate)(String(format: "%04d", randomNum))"
  957. }
  958. func fastTool_MergePDF() { // MergePDF
  959. Task { @MainActor in
  960. // #if VERSION_DMG
  961. // if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  962. // let _ = KMComparativeTableViewController.show(window: self.view.window!, .merge)
  963. // return
  964. // }
  965. // #endif
  966. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  967. // let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, isContinue: true, type: .merge) { isSubscribeSuccess, isWaterMarkExport, isClose in
  968. // if (isClose) {
  969. // return
  970. // }
  971. // self.km_open_pdf_merge()
  972. // }
  973. // return
  974. // }
  975. self.km_open_pdf_merge()
  976. }
  977. }
  978. func km_open_pdf_merge() {
  979. DispatchQueue.main.async {
  980. let windowController = KMMergeWindowController(windowNibName: "KMMergeWindowController")
  981. self.currentWindowController = windowController
  982. windowController.cancelAction = { [unowned self] controller in
  983. self.view.window?.endSheet((self.currentWindowController!.window)!)
  984. self.currentWindowController = nil
  985. }
  986. self.view.window?.beginSheet(windowController.window!)
  987. }
  988. }
  989. func fastTool_Compression() { // 压缩
  990. let openPanel = NSOpenPanel()
  991. openPanel.allowedFileTypes = ["pdf","PDF"]
  992. //MARK: 允许多选还是单选,如果是付费用户允许多选
  993. openPanel.allowsMultipleSelection = false
  994. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  995. if result == NSApplication.ModalResponse.OK {
  996. quickCompressPdf(urls: openPanel.urls)
  997. }
  998. }
  999. }
  1000. func quickCompressPdf(urls: Array<URL>) {
  1001. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  1002. var arr: Array<KMBatchOperateFile> = Array()
  1003. for fileURL in urls {
  1004. let file = KMBatchOperateFile(filePath: fileURL.path, type: .Compress)
  1005. arr.append(file)
  1006. }
  1007. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  1008. if #available(macOS 10.13, *) {
  1009. baseWindowController.window?.makeKeyAndOrderFront(nil)
  1010. } else {
  1011. baseWindowController.showWindow(nil)
  1012. }
  1013. if arr.count > 0 {
  1014. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: .Compress, files: arr)
  1015. }
  1016. }
  1017. }
  1018. func km_secure_openPanel_compress() {
  1019. DispatchQueue.main.async {
  1020. NSOpenPanel.km_secure_openPanel(window: self.view.window!) { url, result, passowrd in
  1021. if (url == nil) {
  1022. return
  1023. }
  1024. if (result != nil && result! == .cancel) {
  1025. return
  1026. }
  1027. self.showCompressWindow(url!, passowrd)
  1028. }
  1029. }
  1030. }
  1031. func showCompressWindow(_ url: URL, _ password: String?) {
  1032. // Task { @MainActor in
  1033. // let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  1034. // windowController.documentURL = url
  1035. // windowController.password = password
  1036. //
  1037. // windowController.itemClick = { [weak self] _ in
  1038. // self?.km_endSheet()
  1039. // }
  1040. //
  1041. // windowController.resultCallback = { [weak self] result, openDocument, fileURL, _ in
  1042. // if result {
  1043. // self?.km_endSheet()
  1044. // if openDocument {
  1045. // NSDocumentController.shared.km_safe_openDocument(withContentsOf: fileURL, display: true) { _, _, _ in
  1046. //
  1047. // }
  1048. // } else {
  1049. // NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  1050. // }
  1051. // } else {
  1052. // let alert = NSAlert()
  1053. // alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  1054. // alert.runModal()
  1055. // }
  1056. // }
  1057. // self.km_beginSheet(windowC: windowController)
  1058. // }
  1059. }
  1060. func fastTool_Security() { // 安全
  1061. let openPanel = NSOpenPanel()
  1062. openPanel.allowedFileTypes = ["pdf","PDF"]
  1063. //MARK: 允许多选还是单选,如果是付费用户允许多选
  1064. openPanel.allowsMultipleSelection = true
  1065. openPanel.message = KMLocalizedString("To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.", nil)
  1066. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1067. if result == NSApplication.ModalResponse.OK {
  1068. quickPassword(urls: openPanel.urls)
  1069. }
  1070. }
  1071. }
  1072. func quickPassword(urls: Array<URL>) {
  1073. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  1074. var arr: Array<KMBatchOperateFile> = Array()
  1075. for fileURL in urls {
  1076. let file = KMBatchOperateFile(filePath: fileURL.path, type: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddPassword : .RemovePassword)
  1077. arr.append(file)
  1078. }
  1079. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  1080. if #available(macOS 10.13, *) {
  1081. baseWindowController.window?.makeKeyAndOrderFront(nil)
  1082. } else {
  1083. baseWindowController.showWindow(nil)
  1084. }
  1085. if arr.count > 0 {
  1086. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddPassword : .RemovePassword, files: arr)
  1087. }
  1088. }
  1089. }
  1090. func fastTool_FileCompare() { // 文件对比
  1091. let openPanel = NSOpenPanel()
  1092. openPanel.allowsMultipleSelection = false
  1093. openPanel.allowedFileTypes = ["pdf"]
  1094. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1095. if result == .cancel {
  1096. return
  1097. }
  1098. if !openPanel.url!.path.isPDFValid() {
  1099. let alert = NSAlert()
  1100. alert.alertStyle = .critical
  1101. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1102. alert.runModal()
  1103. return
  1104. }
  1105. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1106. let controller = KMCompareWindowController(windowNibName: "KMCompareWindowController")
  1107. self.currentWindowController = controller
  1108. controller.filePath = openPanel.url!.path
  1109. controller.cancelAction = { [unowned self] contr in
  1110. self.view.window?.endSheet((controller.window)!)
  1111. // self.currentWindowController = nil
  1112. }
  1113. controller.contentComplete = { [unowned self] controller, pdfCompareContent, result, oldDocument, document in
  1114. DispatchQueue.main.async {
  1115. self.view.window?.endSheet((controller.window)!)
  1116. // self.currentWindowController = nil
  1117. self.openContentCompareVC(with: pdfCompareContent, results: result, oldDocument: oldDocument, document: document)
  1118. }
  1119. }
  1120. controller.coveringComplete = { [unowned self] controller, document in
  1121. self.view.window?.endSheet((controller.window)!)
  1122. // self.currentWindowController = nil
  1123. self.openCoveringCompareVC(with: document)
  1124. }
  1125. // if index == 1 {
  1126. controller.fileType = .content
  1127. // } else {
  1128. // controller.fileType = .coverting
  1129. // }
  1130. NSWindow.currentWindow().beginSheet(controller.window!)
  1131. }
  1132. }
  1133. }
  1134. func fastTool_PDFToPPT() {
  1135. // self.showConvertWindow(type: .ppt)
  1136. let openPanel = NSOpenPanel()
  1137. openPanel.allowedFileTypes = ["pdf","PDF"]
  1138. //MARK: 允许多选还是单选,如果是付费用户允许多选
  1139. openPanel.allowsMultipleSelection = false
  1140. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1141. if result == NSApplication.ModalResponse.OK {
  1142. quickConvertPdf(urls: openPanel.urls, type: .PowerPoint)
  1143. }
  1144. }
  1145. }
  1146. func fastTool_PDFToExcel() {
  1147. // self.showConvertWindow(type: .excel)
  1148. let openPanel = NSOpenPanel()
  1149. openPanel.allowedFileTypes = ["pdf","PDF"]
  1150. //MARK: 允许多选还是单选,如果是付费用户允许多选
  1151. openPanel.allowsMultipleSelection = false
  1152. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1153. if result == NSApplication.ModalResponse.OK {
  1154. quickConvertPdf(urls: openPanel.urls, type: .Excel)
  1155. }
  1156. }
  1157. }
  1158. func fastTool_PDFToWord() { // PDF转Word
  1159. // self.showConvertWindow(type: .word)
  1160. fastTool_ConvertPDF()
  1161. }
  1162. func fastTool_PDFToImage() { // PDF转图片
  1163. self.showConvertWindow(type: .image)
  1164. }
  1165. func fastTool_Watermark() { // 水印
  1166. // KMBatchWindowController.openFile(nil, .Watermark)
  1167. let openPanel = NSOpenPanel()
  1168. openPanel.allowedFileTypes = ["pdf","PDF"]
  1169. //MARK: 允许多选还是单选,如果是付费用户允许多选
  1170. openPanel.allowsMultipleSelection = false
  1171. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1172. if result == NSApplication.ModalResponse.OK {
  1173. quickWaterMark(urls: openPanel.urls)
  1174. }
  1175. }
  1176. }
  1177. func quickWaterMark(urls: Array<URL>) {
  1178. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  1179. var arr: Array<KMBatchOperateFile> = Array()
  1180. for fileURL in urls {
  1181. let pdf = CPDFDocument(url: fileURL)
  1182. if !pdf!.allowsPrinting || !pdf!.allowsCopying {
  1183. let alert = NSAlert()
  1184. alert.alertStyle = .critical
  1185. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1186. alert.runModal()
  1187. return
  1188. }
  1189. let file = KMBatchOperateFile(filePath: fileURL.path, type: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddWatermark : .RemoveWatermark)
  1190. arr.append(file)
  1191. }
  1192. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  1193. if #available(macOS 10.13, *) {
  1194. baseWindowController.window?.makeKeyAndOrderFront(nil)
  1195. } else {
  1196. baseWindowController.showWindow(nil)
  1197. }
  1198. if arr.count > 0 {
  1199. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddWatermark : .RemoveWatermark, files: arr)
  1200. }
  1201. }
  1202. }
  1203. func fastTool_Background() { // 背景
  1204. // KMBatchWindowController.openFile(nil, .Background)
  1205. let openPanel = NSOpenPanel()
  1206. openPanel.allowedFileTypes = ["pdf","PDF"]
  1207. //MARK: 允许多选还是单选,如果是付费用户允许多选
  1208. openPanel.allowsMultipleSelection = false
  1209. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1210. if result == NSApplication.ModalResponse.OK {
  1211. quickBackgroudMark(urls: openPanel.urls)
  1212. }
  1213. }
  1214. }
  1215. func quickBackgroudMark(urls: Array<URL>) {
  1216. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  1217. var arr: Array<KMBatchOperateFile> = Array()
  1218. for fileURL in urls {
  1219. let pdf = CPDFDocument(url: fileURL)
  1220. if !pdf!.allowsPrinting || !pdf!.allowsCopying {
  1221. let alert = NSAlert()
  1222. alert.alertStyle = .critical
  1223. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1224. alert.runModal()
  1225. return
  1226. }
  1227. let file = KMBatchOperateFile(filePath: fileURL.path, type: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddBackground : .RemoveBackground)
  1228. arr.append(file)
  1229. }
  1230. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  1231. if #available(macOS 10.13, *) {
  1232. baseWindowController.window?.makeKeyAndOrderFront(nil)
  1233. } else {
  1234. baseWindowController.showWindow(nil)
  1235. }
  1236. if arr.count > 0 {
  1237. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddBackground : .RemoveBackground, files: arr)
  1238. }
  1239. }
  1240. }
  1241. func fastTool_HeaderAndFooter() { // 页眉页脚
  1242. // KMBatchWindowController.openFile(nil, .HeaderAndFooter)
  1243. let openPanel = NSOpenPanel()
  1244. openPanel.allowedFileTypes = ["pdf","PDF"]
  1245. //MARK: 允许多选还是单选,如果是付费用户允许多选
  1246. openPanel.allowsMultipleSelection = false
  1247. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1248. if result == NSApplication.ModalResponse.OK {
  1249. quickHeaderAndFooterMark(urls: openPanel.urls)
  1250. }
  1251. }
  1252. }
  1253. func quickHeaderAndFooterMark(urls: Array<URL>) {
  1254. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  1255. var arr: Array<KMBatchOperateFile> = Array()
  1256. for fileURL in urls {
  1257. let pdf = CPDFDocument(url: fileURL)
  1258. if !pdf!.allowsPrinting || !pdf!.allowsCopying {
  1259. let alert = NSAlert()
  1260. alert.alertStyle = .critical
  1261. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1262. alert.runModal()
  1263. return
  1264. }
  1265. let file = KMBatchOperateFile(filePath: fileURL.path, type: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddHeaderFooter : .RemoveHeaderFooter)
  1266. arr.append(file)
  1267. }
  1268. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  1269. if #available(macOS 10.13, *) {
  1270. baseWindowController.window?.makeKeyAndOrderFront(nil)
  1271. } else {
  1272. baseWindowController.showWindow(nil)
  1273. }
  1274. if arr.count > 0 {
  1275. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddHeaderFooter : .RemoveHeaderFooter, files: arr)
  1276. }
  1277. }
  1278. }
  1279. func fastTool_BatesCode() { // 贝茨码
  1280. // KMBatchWindowController.openFile(nil, .BatesCode)
  1281. let openPanel = NSOpenPanel()
  1282. openPanel.allowedFileTypes = ["pdf","PDF"]
  1283. //MARK: 允许多选还是单选,如果是付费用户允许多选
  1284. openPanel.allowsMultipleSelection = false
  1285. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
  1286. if result == NSApplication.ModalResponse.OK {
  1287. quickBatesNumberMark(urls: openPanel.urls)
  1288. }
  1289. }
  1290. }
  1291. func quickBatesNumberMark(urls: Array<URL>) {
  1292. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  1293. var arr: Array<KMBatchOperateFile> = Array()
  1294. for fileURL in urls {
  1295. let pdf = CPDFDocument(url: fileURL)
  1296. if !pdf!.allowsPrinting || !pdf!.allowsCopying {
  1297. let alert = NSAlert()
  1298. alert.alertStyle = .critical
  1299. alert.messageText = NSLocalizedString("This is a secured document. Editing is not permitted.", comment: "")
  1300. alert.runModal()
  1301. return
  1302. }
  1303. let file = KMBatchOperateFile(filePath: fileURL.path, type: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddBates : .RemoveBates)
  1304. arr.append(file)
  1305. }
  1306. let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  1307. if #available(macOS 10.13, *) {
  1308. baseWindowController.window?.makeKeyAndOrderFront(nil)
  1309. } else {
  1310. baseWindowController.showWindow(nil)
  1311. }
  1312. if arr.count > 0 {
  1313. baseWindowController.checkNeedPasswordSwitchToOperateType(operateType: KMBatchQuickActionManager.defaultManager.actionType == .add ? .AddBates : .RemoveBates, files: arr)
  1314. }
  1315. }
  1316. }
  1317. func fastTool_Print() { // 打印
  1318. KMPrintWindowController.openFiles(window: self.view.window!)
  1319. }
  1320. func fastTool_BatchRemove() { // 批量移除
  1321. // KMBatchWindowController.openFile(nil, .BatchRemove)
  1322. }
  1323. func fastTool_Insert() { // 插入
  1324. let openPanel = NSOpenPanel()
  1325. openPanel.prompt = NSLocalizedString("Insert", comment: "")
  1326. openPanel.allowsMultipleSelection = false
  1327. openPanel.allowedFileTypes = ["pdf"]
  1328. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1329. if result == .OK {
  1330. // DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1331. // let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Insert)
  1332. // insertWindowController.beginSheetModal(for: self.view.window!) { pdfDocument, password, pages, indexPage in
  1333. // self.insertPageAction(pdfDocument, password, pages, indexPage)
  1334. // }
  1335. // }
  1336. // }
  1337. let windowC = KMPDFInsertWindowController(fileURL: openPanel.url!)
  1338. // [com beginSheetModalForWindow:[NSApp mainWindow] completionHandler:^(PDFDocument *pdfDocument, NSString *password, NSMutableArray<PDFPage *> *pages, NSInteger indexPage) {
  1339. // if (pdfDocument && indexPage >= 0) {
  1340. // [pdfDocument insertWithInsertPages:pages insertPageIndex:indexPage];
  1341. // [self savePDFDocument:pdfDocument password:password];
  1342. // }
  1343. // }];
  1344. windowC.callback = { [unowned self] idx, params in
  1345. if params.count >= 4 {
  1346. if let doc = params.first as? CPDFDocument {
  1347. // doc.insertWithInsertPages((params[2] as? [CPDFPage]) ?? [], insertPageIndex: params[3] as! Int)
  1348. self.savePDFDocument(doc, password: params[1] as? String ?? "")
  1349. }
  1350. }
  1351. self.km_endSheet()
  1352. }
  1353. self.km_beginSheet(windowC: windowC)
  1354. }
  1355. }
  1356. }
  1357. // func savePDFDocument(_ pdf: CPDFDocument, password: String?) {
  1358. //// KMProgressWindowController * vc = [[KMProgressWindowController alloc] init];
  1359. //// [NSApp beginSheet:[vc window] modalForWindow:[NSApp mainWindow] modalDelegate:nil didEndSelector:nil contextInfo:NULL];
  1360. //
  1361. // DispatchQueue.global().async {
  1362. // var isSuccessfully = false
  1363. // if (pdf.isEncrypted) {
  1364. // isSuccessfully = pdf.write(to: pdf.documentURL, withOptions: [.userPasswordOption : password ?? "", .ownerPasswordOption : password ?? ""])
  1365. // } else {
  1366. // isSuccessfully = pdf.write(to: pdf.documentURL)
  1367. // }
  1368. // if (!isSuccessfully) {
  1369. //// isSuccessfully = [pdf.dataRepresentation writeToURL:pdf.documentURL atomically:YES];
  1370. // try?pdf.dataRepresentation().write(to: pdf.documentURL)
  1371. // }
  1372. //
  1373. // Task { @MainActor in
  1374. //// [NSApp endSheet:vc.window];
  1375. //// [vc close];
  1376. //
  1377. // if (isSuccessfully) {
  1378. //// BOOL autoOpen = [[NSUserDefaults standardUserDefaults] boolForKey:KMAutoOpenDocumentKey];
  1379. //// if (autoOpen) {
  1380. //// [[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:pdf.documentURL display:YES completionHandler:^(NSDocument * _Nullable document, BOOL documentWasAlreadyOpen, NSError * _Nullable error) {
  1381. ////
  1382. //// }];
  1383. //// } else {
  1384. // let workspace = NSWorkspace.shared
  1385. // let url = URL(fileURLWithPath: pdf.documentURL.path)
  1386. // workspace.activateFileViewerSelecting([url])
  1387. //// }
  1388. // } else {
  1389. // _ = await KMAlertTool.runModel(message: KMLocalizedString("Failed to insert page(s)!", nil))
  1390. // }
  1391. // }
  1392. // }
  1393. // }
  1394. func fastTool_BreakUp() { // 拆分
  1395. // [[FMTrackEventManager manager] trackEvent:@"Onbrd" withProperties:@{@"HP_Tools":@"Split"}];
  1396. //
  1397. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  1398. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  1399. // return;
  1400. // }
  1401. // self.isDragEntered = YES;
  1402. let openPanel = NSOpenPanel()
  1403. openPanel.allowedFileTypes = ["pdf"]
  1404. openPanel.allowsMultipleSelection = false
  1405. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1406. // self.isDragEntered = NO;
  1407. if result == .OK {
  1408. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1409. let com = SplitWindowController(fileURL: openPanel.url!)
  1410. self.km_beginSheet(windowC: com)
  1411. }
  1412. }
  1413. }
  1414. }
  1415. func fastTool_Extract() { // 提取
  1416. let openPanel = NSOpenPanel()
  1417. openPanel.prompt = "提取"
  1418. openPanel.allowsMultipleSelection = false
  1419. openPanel.allowedFileTypes = ["pdf"]
  1420. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1421. if result == .OK {
  1422. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1423. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Extract)
  1424. insertWindowController.beginSheetExtractModal(for: self.view.window!) { pdfDocument, pages, oneDocumentPerPage, isDeletePage in
  1425. self.extractPageAction(pdfDocument, pages, oneDocumentPerPage, isDeletePage)
  1426. }
  1427. }
  1428. }
  1429. }
  1430. }
  1431. func fastTool_MarkCipher() { // 标记密文
  1432. let openPanel = NSOpenPanel()
  1433. openPanel.allowsMultipleSelection = false
  1434. openPanel.allowedFileTypes = ["pdf"]
  1435. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1436. if result == .cancel {
  1437. return
  1438. }
  1439. if !openPanel.url!.path.isPDFValid() {
  1440. let alert = NSAlert()
  1441. alert.alertStyle = .critical
  1442. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1443. alert.runModal()
  1444. return
  1445. }
  1446. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1447. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1448. if (error != nil) {
  1449. NSApp.presentError(error!)
  1450. return
  1451. }
  1452. let toolbar = (document as! KMMainDocument).mainViewController?.toolbarController
  1453. toolbar?.enterRedact()
  1454. }
  1455. }
  1456. }
  1457. }
  1458. func fastTool_AutomaticFormRecognition() { // 表单自动识别
  1459. let openPanel = NSOpenPanel()
  1460. openPanel.prompt = "表单自动识别"
  1461. openPanel.allowsMultipleSelection = false
  1462. openPanel.allowedFileTypes = ["pdf"]
  1463. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1464. if result == .OK {
  1465. }
  1466. }
  1467. }
  1468. func fastTool_PageEdit() { // 页面编辑
  1469. let openPanel = NSOpenPanel()
  1470. openPanel.allowsMultipleSelection = false
  1471. openPanel.allowedFileTypes = ["pdf"]
  1472. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1473. if result == .cancel {
  1474. return
  1475. }
  1476. if !openPanel.url!.path.isPDFValid() {
  1477. let alert = NSAlert()
  1478. alert.alertStyle = .critical
  1479. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1480. alert.runModal()
  1481. return
  1482. }
  1483. if let pdf = CPDFDocument(url: openPanel.url!) {
  1484. if pdf.allowsCopying == false || pdf.allowsPrinting == false {
  1485. Task {
  1486. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  1487. }
  1488. return
  1489. }
  1490. }
  1491. let windowC = KMPDFEditWindowController(filepath: openPanel.url!.path, password: nil)
  1492. windowC.startModal(nil)
  1493. }
  1494. }
  1495. @IBAction func escButtonAction(_ sender: Any) {
  1496. // self.historyFileViewController.selectFiles.removeAll()
  1497. // if self.historyFileViewController.showMode == .Thumbnail {
  1498. // self.historyFileViewController.historyFileCollectionView.reloadData()
  1499. // } else {
  1500. // self.historyFileViewController.historyFileTableView.reloadData()
  1501. // }
  1502. }
  1503. @IBAction func importFromFile(_ sender: Any) {
  1504. self.openSupportPDFButtonAction()
  1505. }
  1506. @IBAction func menuItemClick_mergePDF(_ sender: Any) {
  1507. fastTool_MergePDF()
  1508. }
  1509. @IBAction func menuItemClick_Compress(_ sender: Any) {
  1510. fastTool_Compression()
  1511. }
  1512. @IBAction func menuItemClick_Convert(_ sender: Any) {
  1513. fastTool_ConvertPDF()
  1514. }
  1515. @IBAction func menuItemClick_SettingPassword(_ sender: Any) {
  1516. KMBatchQuickActionManager.defaultManager.actionType = .add
  1517. fastTool_Security()
  1518. }
  1519. @IBAction func menuItemClick_RemovePassword(_ sender: Any) {
  1520. KMBatchQuickActionManager.defaultManager.actionType = .add
  1521. fastTool_Security()
  1522. }
  1523. func fetchUniquePath(_ originalPath: String) -> String {
  1524. var path = originalPath
  1525. let dManager = FileManager.default
  1526. if !dManager.fileExists(atPath: path) {
  1527. if path.extension.count < 1 {
  1528. path = path.stringByAppendingPathExtension("pdf")
  1529. }
  1530. return path
  1531. } else {
  1532. let originalFullFileName = path.lastPathComponent
  1533. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  1534. let originalExtension = path.extension
  1535. let startIndex: Int = 0
  1536. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  1537. let fileLocatePath = originalPath.substring(to: endIndex)
  1538. var i = 1
  1539. while (1 != 0) {
  1540. var newName = String(format: "%@%ld", originalFileName, i)
  1541. newName = String(format: "%@%@", newName, originalExtension)
  1542. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  1543. if !dManager.fileExists(atPath: newPath) {
  1544. return newPath
  1545. } else {
  1546. i+=1
  1547. continue
  1548. }
  1549. }
  1550. }
  1551. }
  1552. // func kNewDocumentTempSavePath(_ fileName: String) -> String {
  1553. // let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  1554. //// let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1555. // let append2 = searchPath!.stringByAppendingPathComponent(String(format: "%@", fileName))
  1556. // return append2
  1557. // }
  1558. // MARK: Notification
  1559. @objc func homeFileRectChange(_ notification: Notification) -> Void {
  1560. let window = notification.object
  1561. self.historyFileViewController.reloadData()
  1562. }
  1563. }
  1564. // MARK: window Menu
  1565. extension KMHomeViewController {
  1566. @IBAction func menuItemAction_showForwardTagPage(_ sender: Any) {
  1567. (self.myDocument as! KMMainDocument).browser.selectPreviousTab()
  1568. }
  1569. @IBAction func menuItemAction_showNextTagPage(_ sender: Any) {
  1570. (self.myDocument as! KMMainDocument).browser.selectNextTab()
  1571. }
  1572. @IBAction func menuItemAction_newTagPageToNewWindow(_ sender: Any) {
  1573. let browser = (self.myDocument as! KMMainDocument).browser
  1574. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.openNewWindow(sender)
  1575. }
  1576. @IBAction func menuItemAction_mergeAllWindow(_ sender: Any) {
  1577. ((self.myDocument as? KMMainDocument)?.browser.windowController as? KMBrowserWindowController)?.mergeAllWindow(sender)
  1578. }
  1579. @IBAction func menuItemAction_currentWindowName(_ sender: Any) {
  1580. }
  1581. }
  1582. // MARK: file Menu
  1583. extension KMHomeViewController {
  1584. @IBAction func menuItemAction_closeWindow(_ sender: Any) {
  1585. self.view.window?.close()
  1586. }
  1587. @IBAction func menuItemAction_closeAllWindows(_ sender: Any) {
  1588. for window in NSApp.windows {
  1589. window.close()
  1590. }
  1591. }
  1592. @IBAction func menuItemAction_ConvertToWord(_ sender: Any) {
  1593. self.fastTool_PDFToWord()
  1594. }
  1595. @IBAction func menuItemAction_ConvertToExcel(_ sender: Any) {
  1596. self.fastTool_PDFToExcel()
  1597. }
  1598. @IBAction func menuItemAction_ConvertToPPT(_ sender: Any) {
  1599. self.fastTool_PDFToPPT()
  1600. }
  1601. @IBAction func menuItemAction_ConvertToRTF(_ sender: Any) {
  1602. self.showConvertWindow(type: .rtf)
  1603. }
  1604. @IBAction func menuItemAction_ConvertToHTML(_ sender: Any) {
  1605. self.showConvertWindow(type: .html)
  1606. }
  1607. @IBAction func menuItemAction_ConvertToText(_ sender: Any) {
  1608. self.showConvertWindow(type: .text)
  1609. }
  1610. @IBAction func menuItemAction_ConvertToCSV(_ sender: Any) {
  1611. self.showConvertWindow(type: .csv)
  1612. }
  1613. @IBAction func menuItemAction_ConvertToImage(_ sender: Any) {
  1614. self.fastTool_PDFToImage()
  1615. }
  1616. }
  1617. // MARK: help Menu
  1618. extension KMHomeViewController {
  1619. // @IBAction func menuItemAction_search(_ sender: Any) {
  1620. //
  1621. // }
  1622. }
  1623. // MARK: - Analytics (埋点)
  1624. extension KMHomeViewController {
  1625. func trackEvent_ai(eventName: String) -> Void {
  1626. KMAnalytics.trackEvent(eventName: eventName, parameters: [
  1627. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.home,
  1628. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.ai_Btn], platform: .AppCenter, appTarget: .all)
  1629. }
  1630. func trackEvent_create(eventName: String) -> Void {
  1631. KMAnalytics.trackEvent(eventName: eventName, parameters: [
  1632. KMAnalytics.Parameter.categoryKey : KMAnalytics.Category.home,
  1633. KMAnalytics.Parameter.labelKey : KMAnalytics.Label.create_Btn], platform: .AppCenter, appTarget: .all)
  1634. }
  1635. }
  1636. extension KMHomeViewController {
  1637. //文件对比
  1638. func openContentCompareVC(with pdfCompareContent: CPDFCompareContent?, results: [CPDFCompareResults], oldDocument: CPDFDocument, document: CPDFDocument) {
  1639. let compareContentController = KMCompareContentWindowController(document: document, oldDocument: oldDocument, results: results)
  1640. self.currentController = compareContentController
  1641. // let compareContentView = KMCompareContentView()
  1642. // compareContentView.oldDocument = oldDocument
  1643. // compareContentView.document = document
  1644. // compareContentView.compareResults = results
  1645. compareContentController.saveHandle = { [unowned self] view in
  1646. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) { [unowned self] in
  1647. let saveController = KMCompareSaveWindow(windowNibName: "KMCompareSaveWindow")
  1648. self.currentWindowController = saveController
  1649. saveController.cancelHandle = { [unowned self] controller in
  1650. NSWindow.currentWindow().endSheet(controller.window!)
  1651. self.currentWindowController = nil
  1652. }
  1653. saveController.saveHandle = { [unowned self] controller, saveType in
  1654. let folderPath = controller.fileSaveFolderPath
  1655. if folderPath != nil {
  1656. if !FileManager.default.fileExists(atPath: folderPath) {
  1657. try? FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: true, attributes: nil)
  1658. }
  1659. var savePath: String
  1660. switch saveType {
  1661. case 0:
  1662. let filePath = oldDocument.documentURL.path
  1663. let fileName = filePath.deletingPathExtension.lastPathComponent
  1664. savePath = "\(folderPath)/\(fileName.deletingPathExtension)_compare\(filePath.extension)"
  1665. savePath = self.getValidFilePath(savePath)
  1666. oldDocument.write(to: URL(fileURLWithPath: savePath))
  1667. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  1668. case 1:
  1669. let filePath = document.documentURL.path
  1670. let fileName = filePath.deletingPathExtension.lastPathComponent
  1671. savePath = "\(folderPath)/\(fileName)_compare\(filePath.extension)"
  1672. savePath = self.getValidFilePath(savePath)
  1673. document.write(to: URL(fileURLWithPath: savePath))
  1674. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  1675. case 2:
  1676. let filePath = oldDocument.documentURL.path
  1677. let fileName = filePath.deletingPathExtension.lastPathComponent
  1678. savePath = "\(folderPath)/MergedCompareFile\(filePath.extension)"
  1679. savePath = self.getValidFilePath(savePath)
  1680. pdfCompareContent!.saveAsComparisonDocument(withFilePath: savePath)
  1681. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: savePath)])
  1682. default:
  1683. break
  1684. }
  1685. }
  1686. NSWindow.currentWindow().endSheet(controller.window!)
  1687. self.currentWindowController = nil
  1688. }
  1689. NSWindow.currentWindow().beginSheet(saveController.window!)
  1690. }
  1691. }
  1692. compareContentController.closeHandle = { [unowned self] controller in
  1693. self.view.window!.endSheet(controller.window!)
  1694. self.currentController = nil
  1695. // view.removeFromSuperview()
  1696. }
  1697. NSWindow.currentWindow().beginSheet(compareContentController.window!)
  1698. // self.PDFContendView.addSubview(compareContentView)
  1699. // compareContentView.frame = self.PDFContendView.bounds
  1700. // compareContentView.autoresizingMask = [.width,.height]
  1701. }
  1702. func getValidFilePath(_ oldPath: String) -> String {
  1703. let fileManager = FileManager.default
  1704. do {
  1705. let fileAttributes = try fileManager.attributesOfItem(atPath: oldPath)
  1706. guard let fileType = fileAttributes[FileAttributeKey.type] as? String else {
  1707. return oldPath
  1708. }
  1709. var i = 1
  1710. var newPath = oldPath
  1711. while fileManager.fileExists(atPath: newPath) {
  1712. if fileType == FileAttributeType.typeDirectory.rawValue {
  1713. newPath = oldPath + "(\(i))"
  1714. } else {
  1715. let fileExtension = (oldPath as NSString).pathExtension
  1716. newPath = ((oldPath as NSString).deletingPathExtension as NSString).appendingFormat("(\(i)).\(fileExtension)" as NSString) as String
  1717. }
  1718. i += 1
  1719. }
  1720. return newPath
  1721. } catch {
  1722. print("Error getting file attributes: \(error)")
  1723. return oldPath
  1724. }
  1725. }
  1726. func openCoveringCompareVC(with pdfDocument: CPDFDocument) {
  1727. let controller = KMCompareCoveringWindowController(document: pdfDocument)
  1728. self.currentWindowController = controller
  1729. // let coveringView = KMCompareCoveringView()
  1730. // coveringView.pdfDocument = pdfDocument
  1731. controller.closeHandle = { [unowned self] controller in
  1732. // view.removeFromSuperview()
  1733. self.view.window!.endSheet(controller.window!)
  1734. self.currentController = nil
  1735. }
  1736. controller.saveHandle = { [unowned self] controller in
  1737. let savePanel = NSSavePanel()
  1738. savePanel.nameFieldStringValue = "untitled"
  1739. savePanel.allowedFileTypes = ["pdf"]
  1740. savePanel.beginSheetModal(for: NSWindow.currentWindow()) { result in
  1741. if result == .OK {
  1742. pdfDocument.write(to: savePanel.url!)
  1743. NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
  1744. }
  1745. }
  1746. }
  1747. // self.view.window!.endSheet(controller.window!)
  1748. NSWindow.currentWindow().beginSheet(controller.window!)
  1749. // self.PDFContendView.addSubview(coveringView)
  1750. // coveringView.frame = self.PDFContendView.bounds
  1751. // coveringView.autoresizingMask = [.width,.height]
  1752. }
  1753. }