KMHomeViewController+Action.swift 98 KB

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