KMHomeViewController+Action.swift 98 KB

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