KMHomeViewController+Action.swift 99 KB

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