KMHomeViewController+Action.swift 96 KB

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