KMHomeViewController+Action.swift 98 KB

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