KMHomeViewController+Action.swift 97 KB

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