KMHomeViewController+Action.swift 99 KB

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