KMHomeViewController+Action.swift 97 KB

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