KMHomeViewController+Action.swift 92 KB

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