KMHomeViewController+Action.swift 98 KB

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