KMHomeViewController+Action.swift 94 KB

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