KMHomeViewController+Action.swift 98 KB

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