KMHomeViewController+Action.swift 99 KB

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