KMHomeViewController+Action.swift 99 KB

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