KMHomeViewController+Action.swift 100 KB

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