KMHomeViewController+Action.swift 98 KB

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