KMHomeViewController+Action.swift 100 KB

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