KMHomeViewController+Action.swift 98 KB

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