KMHomeViewController+Action.swift 95 KB

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