KMHomeViewController+Action.swift 93 KB

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