KMHomeViewController+Action.swift 97 KB

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