KMHomeViewController+Action.swift 98 KB

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