KMHomeViewController+Action.swift 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662
  1. //
  2. // KMHomeViewController+Action.swift
  3. // PDF Master
  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. createPDFButtonAction()
  58. break
  59. case .Home:
  60. homeButtonAction()
  61. break
  62. case .PDFTools:
  63. pdfToolsButtonAction()
  64. break
  65. case .FavoriteDocuments:
  66. favoriteDocumentsButtonAction()
  67. break
  68. case .CloudDocuments:
  69. cloudDocumentsButtonAction()
  70. break
  71. default:
  72. print("error: 错误的传入枚举")
  73. break
  74. }
  75. }
  76. func fastToolItemAction(_ type: DataNavigationViewButtonActionType) {
  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. }
  151. }
  152. func openPDFButtonAction() {
  153. NSPanel.km_open_pdf_multi_success(self.view.window!, panel: nil) { urls in
  154. for url in urls {
  155. if !url.path.isPDFValid() {
  156. let alert = NSAlert()
  157. alert.alertStyle = .critical
  158. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  159. alert.runModal()
  160. } else {
  161. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  162. if error != nil {
  163. NSApp.presentError(error!)
  164. } else {
  165. }
  166. }
  167. }
  168. }
  169. }
  170. }
  171. func openSupportPDFButtonAction() {
  172. let openPanel = NSOpenPanel()
  173. openPanel.allowedFileTypes = ["pdf", "PDF", "jpg", "cur", "bmp", "jpeg", "gif", "png", "tiff", "tif", "ico", "icns", "tga", "psd", "eps", "hdr", "jp2", "jpc", "pict", "sgi", "heic", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pptx"]
  174. openPanel.allowsMultipleSelection = true
  175. var window = self.view.window
  176. if (window == nil) {
  177. window = NSApp.mainWindow
  178. }
  179. openPanel.beginSheetModal(for: window!) { [self] result in
  180. if result == .OK {
  181. var imageUrl: [URL] = []
  182. for url in openPanel.urls {
  183. let type = url.pathExtension.lowercased()
  184. if (type == "pdf" || type == "PDF") {
  185. if !url.path.isPDFValid() {
  186. let alert = NSAlert()
  187. alert.alertStyle = .critical
  188. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  189. alert.runModal()
  190. } else {
  191. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  192. if error != nil {
  193. NSApp.presentError(error!)
  194. return
  195. }
  196. }
  197. }
  198. } else if (type == "jpg") ||
  199. (type == "cur") ||
  200. (type == "bmp") ||
  201. (type == "jpeg") ||
  202. (type == "gif") ||
  203. (type == "png") ||
  204. (type == "tiff") ||
  205. (type == "tif") ||
  206. (type == "ico") ||
  207. (type == "icns") ||
  208. (type == "tga") ||
  209. (type == "psd") ||
  210. (type == "eps") ||
  211. (type == "hdr") ||
  212. (type == "jp2") ||
  213. (type == "jpc") ||
  214. (type == "pict") ||
  215. (type == "sgi") ||
  216. (type == "heic") {
  217. openImageFile(url: url)
  218. } else if (type == "doc") ||
  219. (type == "docx") ||
  220. (type == "xls") ||
  221. (type == "xlsx") ||
  222. (type == "ppt") ||
  223. (type == "pptx") ||
  224. (type == "pptx") {
  225. self.openOfficeFile(url: url)
  226. }
  227. }
  228. }
  229. }
  230. }
  231. func createPDFButtonAction() {
  232. let popViewDataArr = [NSLocalizedString("New Blank Page", comment: ""),
  233. // NSLocalizedString("New From Web Page", comment: ""),
  234. NSLocalizedString("Import From Scanner", comment: "")]
  235. createPopoverAction(popViewDataArr)
  236. }
  237. func homeButtonAction() {
  238. refreshRightBoxUI(.Home)
  239. }
  240. func pdfToolsButtonAction() {
  241. refreshRightBoxUI(.PDFTools)
  242. }
  243. func favoriteDocumentsButtonAction() {
  244. print("Favorite Documents")
  245. }
  246. func cloudDocumentsButtonAction() {
  247. refreshRightBoxUI(.CloudDocuments)
  248. }
  249. // 产品推广
  250. func productPromotionFoldOrUnfold(_ sender: NSButton) {
  251. var arr1: [NSString] = []
  252. var arr2: [NSString] = []
  253. if sender.isEqual(to: pdfSeriesButtonVC.button) {
  254. if self.pdfProSeriesBoxHeightConstraint.constant == 0 {
  255. arr1 = self.productPromotionPDFProSeries as! [NSString]
  256. }
  257. if self.othersBoxHeightConstraint.constant > 0 {
  258. arr2 = self.productPromotionOthers as! [NSString]
  259. }
  260. }
  261. if sender.isEqual(to: self.pdfOthersButtonVC.button) {
  262. if self.pdfProSeriesBoxHeightConstraint.constant > 0 {
  263. arr1 = self.productPromotionPDFProSeries as! [NSString]
  264. }
  265. if self.othersBoxHeightConstraint.constant == 0 {
  266. arr2 = self.productPromotionOthers as! [NSString]
  267. }
  268. }
  269. self.productPromotionShow(arr1 as NSArray, withOthers: arr2 as NSArray, isInitialize: false)
  270. refreshProductActiveSpacing()
  271. }
  272. func productPromotionClickAction(_ name: NSString) {
  273. var httpString: NSString = ""
  274. if name.isEqual(to: "Windows") {
  275. httpString = "https://www.pdfreaderpro.com/windows?utm_source=MacApp&utm_campaign=PDFProMac&utm_medium=pdfmac_promo"
  276. } else if name.isEqual(to: "iPhone / iPad") {
  277. #if VERSION_FREE
  278. #if VERSION_DMG
  279. httpString = "https://www.pdfreaderpro.com/product?utm_source=MacAppDmg&utm_campaign=ProductLinkLeftNav&utm_medium=PdfProduct"
  280. #else
  281. httpString = "https://www.pdfreaderpro.com/product?utm_source=MacAppLite&utm_campaign=ProductLinkLeftNav&utm_medium=PdfProduct"
  282. #endif
  283. #else
  284. httpString = "https://www.pdfreaderpro.com/product?utm_source=MacApp&utm_campaign=ProductLinkLeftNav&utm_medium=PdfProduct"
  285. #endif
  286. } else if name.isEqual(to: "Android") {
  287. httpString = "https://www.pdfreaderpro.com/pdfreaderpro-android?utm_source=MacAppDmg&utm_campaign=AndroidLink&utm_medium=PdfAndroid"
  288. } else if name.isEqual(to: "ComPDFKit") {
  289. httpString = "https://www.compdf.com?utm_source=macapp&utm_medium=pdfmac&utm_campaign=compdfkit-promp"
  290. } else if name.isEqual(to: "ComVideoKit") {
  291. httpString = "https://www.filmagepro.com/video-sdk?utm_source=macapp&utm_medium=pdfmac&utm_campaign=comvideosdk-promo"
  292. } else if name.isEqual(to: "SignFlow") {
  293. httpString = "https://apps.apple.com/app/apple-store/id1584624017?pt=118745145&ct=pdfmac-promo&mt=8"
  294. } else if name.isEqual(to: "FiImage Editor") {
  295. httpString = "https://apps.apple.com/app/apple-store/id1475051178?pt=118745145&ct=pdfmac-promo&mt=8"
  296. } else if name.isEqual(to: "FiImage Screen") {
  297. httpString = "https://apps.apple.com/app/apple-store/id1475049179?pt=118745145&ct=pdfmac-promo&mt=8"
  298. } else if name.isEqual(to: "Free PDF Templates") {
  299. httpString = "https://www.pdfreaderpro.com/templates?utm_source=MacApp&utm_campaign=PDFProMac&utm_medium=pdfmac_promo"
  300. }
  301. self.workSpaceOpenUrl(httpString)
  302. }
  303. func historyFile(deleteDocuments indexPaths: [URL]) {
  304. if UserDefaults.standard.bool(forKey: "kHistoryDeleteNOReminderKey") {
  305. historyFileDeleteAction(indexPaths)
  306. } else {
  307. let historyFileDeleteVC: KMHistoryFileDeleteWindowController = KMHistoryFileDeleteWindowController.init(windowNibName: NSNib.Name("KMHistoryFileDeleteWindowController"))
  308. historyFileDeleteVC.indexPaths = indexPaths
  309. self.currentWindowController = historyFileDeleteVC
  310. historyFileDeleteVC.deleteCallback = { [weak self](indexPaths: [URL], windowController: KMHistoryFileDeleteWindowController) -> Void in
  311. if self != nil {
  312. self?.currentWindowController = nil
  313. self!.historyFileDeleteAction(indexPaths)
  314. }
  315. }
  316. self.view.window?.beginSheet(historyFileDeleteVC.window!)
  317. }
  318. }
  319. func historyFileDeleteAction(_ indexPaths: [URL]) -> Void {
  320. // NSDocumentController.shared.clearRecentDocuments(nil)
  321. let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
  322. NSDocumentController.shared.clearRecentDocuments(nil)
  323. DispatchQueue.main.asyncAfter(deadline: .now()) { [self] in
  324. for (_, url) in urls.enumerated() {
  325. if !indexPaths.contains(url) {
  326. NSDocumentController.shared.noteNewRecentDocumentURL(url)
  327. }
  328. }
  329. }
  330. historyFileViewController.reloadData()
  331. }
  332. func openHistoryFilePath(url: URL) -> Void {
  333. if !url.path.isPDFValid() {
  334. let alert = NSAlert()
  335. alert.alertStyle = .critical
  336. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  337. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  338. self.historyFileViewController.reloadData()
  339. }
  340. return
  341. }
  342. if url.pathExtension.lowercased() == "pdf" {
  343. let pdfDoc = CPDFDocument.init(url: url)
  344. if pdfDoc != nil {
  345. let document = NSDocumentController.shared.document(for: url)
  346. var alreadyOpen = false
  347. for openDocument in NSDocumentController.shared.documents {
  348. if document == openDocument {
  349. alreadyOpen = true
  350. }
  351. }
  352. if !alreadyOpen {
  353. KMMainDocument().tryToUnlockDocument(pdfDoc!)
  354. var selectDocument: KMMainDocument? = nil
  355. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  356. selectDocument = (document as! KMMainDocument)
  357. }
  358. if selectDocument != nil {
  359. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  360. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  361. if (selectDocument?.browser.window.isVisible)! as Bool {
  362. selectDocument?.browser.window.orderFront(nil)
  363. } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  364. selectDocument?.browser.window.orderFront(nil)
  365. }
  366. } else {
  367. if !url.path.isPDFValid() {
  368. let alert = NSAlert()
  369. alert.alertStyle = .critical
  370. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  371. alert.runModal()
  372. } else {
  373. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  374. if error != nil {
  375. NSApp.presentError(error!)
  376. return
  377. }
  378. }
  379. }
  380. }
  381. } else {
  382. var selectDocument: KMMainDocument? = nil
  383. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  384. selectDocument = (document as! KMMainDocument)
  385. }
  386. if selectDocument != nil {
  387. if selectDocument?.browser != nil {
  388. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  389. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  390. if (selectDocument?.browser.window.isVisible)! as Bool {
  391. selectDocument?.browser.window.orderFront(nil)
  392. } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  393. selectDocument?.browser.window.orderFront(nil)
  394. }
  395. }
  396. } else {
  397. if !url.path.isPDFValid() {
  398. let alert = NSAlert()
  399. alert.alertStyle = .critical
  400. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  401. alert.runModal()
  402. } else {
  403. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  404. if error != nil {
  405. NSApp.presentError(error!)
  406. return
  407. }
  408. }
  409. }
  410. }
  411. }
  412. } else {
  413. let alert = NSAlert()
  414. alert.alertStyle = .critical
  415. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  416. alert.beginSheetModal(for: view.window!) { [unowned self] result in
  417. self.historyFileViewController.reloadData()
  418. }
  419. }
  420. } else {
  421. NSWorkspace.shared.open(url)
  422. }
  423. }
  424. func openFile(withFilePath path: URL) -> Void {
  425. let type = path.pathExtension.lowercased()
  426. if (type == "pdf") {
  427. if !path.path.isPDFValid() {
  428. let alert = NSAlert()
  429. alert.alertStyle = .critical
  430. alert.messageText = NSLocalizedString("This file format is not supported, please drag in PDF, picture, Office format files", comment: "")
  431. alert.runModal()
  432. return
  433. }
  434. NSDocumentController.shared.openDocument(withContentsOf: path, display: true) { document, documentWasAlreadyOpen, error in
  435. if error != nil {
  436. NSApp.presentError(error!)
  437. return
  438. }
  439. }
  440. } else if (type == "jpg") ||
  441. (type == "cur") ||
  442. (type == "bmp") ||
  443. (type == "jpeg") ||
  444. (type == "gif") ||
  445. (type == "png") ||
  446. (type == "tiff") ||
  447. (type == "tif") ||
  448. (type == "ico") ||
  449. (type == "icns") ||
  450. (type == "tga") ||
  451. (type == "psd") ||
  452. (type == "eps") ||
  453. (type == "hdr") ||
  454. (type == "jp2") ||
  455. (type == "jpc") ||
  456. (type == "pict") ||
  457. (type == "sgi") ||
  458. (type == "heic") {
  459. openImageFile(url: path)
  460. } else if (type == "doc") ||
  461. (type == "docx") ||
  462. (type == "xls") ||
  463. (type == "xlsx") ||
  464. (type == "ppt") ||
  465. (type == "pptx") ||
  466. (type == "pptx") {
  467. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  468. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  469. openOfficeFile(url: path)
  470. }
  471. }
  472. func openImageFile(url: URL) -> Void {
  473. var filePath = url.path
  474. let fileName: NSString = url.lastPathComponent as NSString
  475. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath()).deletingLastPathComponent
  476. let imageName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension
  477. let path = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".pdf")
  478. if (!FileManager.default.fileExists(atPath: path.deletingLastPathComponent as String)) {
  479. try?FileManager.default.createDirectory(atPath: path.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  480. }
  481. if (!FileManager.default.fileExists(atPath: path as String)) {
  482. FileManager.default.createFile(atPath: path as String, contents: nil)
  483. }
  484. let document = CPDFDocument.init()
  485. var success = false
  486. if NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "png" ||
  487. NSString(string: NSString(string: filePath).lastPathComponent).pathExtension == "PNG" {
  488. let jpgPath = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".jpg")
  489. if (!FileManager.default.fileExists(atPath: jpgPath as String)) {
  490. FileManager.default.createFile(atPath: jpgPath as String, contents: nil)
  491. }
  492. // 加载 PNG 图像
  493. guard let pngImage = NSImage(contentsOfFile: filePath) else {
  494. print("Failed to load PNG image")
  495. return
  496. }
  497. // 创建 NSBitmapImageRep 对象,并将 PNG 图像绘制到其中
  498. let bitmap = NSBitmapImageRep(data: pngImage.tiffRepresentation!)
  499. let rect = NSRect(origin: .zero, size: bitmap!.size)
  500. bitmap?.draw(in: rect)
  501. // 将 PNG 图像数据转换为 JPG 图像数据
  502. guard let jpgData = bitmap?.representation(using: .jpeg, properties: [:]) else {
  503. print("Failed to convert PNG to JPG")
  504. return
  505. }
  506. // 保存 JPG 图像数据到文件
  507. let fileURL = URL(fileURLWithPath: jpgPath)
  508. do {
  509. try jpgData.write(to: fileURL)
  510. filePath = fileURL.path
  511. print("JPG image saved successfully")
  512. } catch {
  513. print("Failed to save JPG image: \(error.localizedDescription)")
  514. }
  515. }
  516. //FIXME: 无法插入图片
  517. let image = NSImage(contentsOfFile: filePath)
  518. let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount)
  519. if insertPageSuccess != nil {
  520. //信号量控制异步
  521. let semaphore = DispatchSemaphore(value: 0)
  522. DispatchQueue.global().async {
  523. success = ((document?.write(toFile: path)) != nil)
  524. semaphore.signal()
  525. }
  526. semaphore.wait()
  527. } else {
  528. }
  529. if success {
  530. if !path.isPDFValid() {
  531. let alert = NSAlert()
  532. alert.alertStyle = .critical
  533. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  534. alert.runModal()
  535. return
  536. }
  537. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { document, documentWasAlreadyOpen, error in
  538. if error != nil {
  539. NSApp.presentError(error!)
  540. return
  541. }
  542. }
  543. }
  544. }
  545. func openOfficeFile(url: URL) -> Void {
  546. let filePath = url.path
  547. let folderPath = "convertToPDF.pdf"
  548. let savePath = folderPath.kUrlToPDFFolderPath()
  549. if (!FileManager.default.fileExists(atPath: savePath!.deletingLastPathComponent as String)) {
  550. try?FileManager.default.createDirectory(atPath: savePath!.deletingLastPathComponent as String, withIntermediateDirectories: true, attributes: nil)
  551. }
  552. if (!FileManager.default.fileExists(atPath: savePath! as String)) {
  553. FileManager.default.createFile(atPath: savePath! as String, contents: nil)
  554. }
  555. if savePath == nil {
  556. return
  557. }
  558. KMConvertPDFManagerOC.convertFile(filePath, savePath: savePath!) { success, errorDic in
  559. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  560. if FileManager.default.fileExists(atPath: savePath!) {
  561. try?FileManager.default.removeItem(atPath: savePath!)
  562. }
  563. let alert = NSAlert.init()
  564. alert.alertStyle = .critical
  565. var infoString = ""
  566. if errorDic != nil {
  567. for key in (errorDic! as Dictionary).keys {
  568. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  569. }
  570. }
  571. alert.informativeText = NSLocalizedString("Please install Microsoft Office to create PDFs from Office files", comment: "")
  572. alert.messageText = NSLocalizedString("Failed to Create PDF", comment: "")
  573. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  574. alert.runModal()
  575. return
  576. }
  577. if !savePath!.isPDFValid() {
  578. let alert = NSAlert()
  579. alert.alertStyle = .critical
  580. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  581. alert.runModal()
  582. return
  583. }
  584. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath!), display: true) { document, documentWasAlreadyOpen, error in
  585. if error != nil {
  586. NSApp.presentError(error!)
  587. return
  588. }
  589. }
  590. }
  591. }
  592. func aiTranslation(withFilePath path: String) -> Void {
  593. if !KMLightMemberManager.manager.isLogin() {
  594. KMLoginWindowController.show(window: NSApp.mainWindow!)
  595. return
  596. }
  597. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: path)
  598. if self.isFileGreaterThan10MB(atPath: path) {
  599. self.aiTranslationViewController.errorView.isHidden = false
  600. self.aiTranslationViewController.errorLabel.stringValue = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  601. } else if isExceedsLimit {
  602. self.aiTranslationViewController.errorView.isHidden = false
  603. self.aiTranslationViewController.errorLabel.stringValue = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  604. } else {
  605. let url = URL(fileURLWithPath: path)
  606. if (url.pathExtension == "pdf") || url.pathExtension == "PDF" {
  607. if !path.isPDFValid() {
  608. let alert = NSAlert()
  609. alert.alertStyle = .critical
  610. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  611. alert.runModal()
  612. return
  613. }
  614. }
  615. let infoDictionary = Bundle .main.infoDictionary!
  616. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  617. DispatchQueue.main.async {
  618. self.showProgressWindow()
  619. }
  620. KMRequestServerManager.manager.aiTranslationFileUpload(file: path, version: "1.0.1") { [unowned self] success, result in
  621. if success {
  622. let result: NSDictionary = result!.result
  623. let fileKey = result["fileKey"]
  624. let fileName = result["fileName"]
  625. let pageCount = result["pageCount"]
  626. if fileKey != nil {
  627. self.fileTranslateHandle(fileKey as! String)
  628. }
  629. } else {
  630. let result: String = result!.message
  631. DispatchQueue.main.async {
  632. self.hiddenProgressWindow()
  633. self.aiTranslationViewController.errorView.isHidden = false
  634. self.aiTranslationViewController.errorLabel.stringValue = result
  635. }
  636. }
  637. }
  638. }
  639. }
  640. func fileTranslateHandle(_ fileKey: String) -> Void {
  641. let infoDictionary = Bundle .main.infoDictionary!
  642. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  643. KMRequestServerManager.manager.aiTranslationFileTranslateHandle(fileKey: fileKey, from: self.aiTranslationViewController.fromStr, to: self.aiTranslationViewController.toStr, version: "1.0.1") { success, result in
  644. if success {
  645. let result: NSDictionary = result!.result
  646. let fileUrl: String = result["fileUrl"] as! String
  647. let downFileUrl: String = result["downFileUrl"] as! String
  648. let ossDownUrl: String = result["ossDownUrl"] as! String
  649. let fileName: String = result["fileName"] as! String
  650. let downFileName: String = result["downFileName"] as! String
  651. let from: String = result["from"] as! String
  652. let to: String = result["to"] as! String
  653. self.downloadFile(filePath: ossDownUrl, downFileName: downFileName)
  654. } else {
  655. let result: String = result!.message
  656. DispatchQueue.main.async {
  657. self.hiddenProgressWindow()
  658. self.aiTranslationViewController.errorView.isHidden = false
  659. self.aiTranslationViewController.errorLabel.stringValue = result
  660. }
  661. }
  662. }
  663. }
  664. func downloadFile(filePath: String, downFileName: String) -> Void {
  665. guard let fileURL = URL(string: filePath) else {
  666. let alert = NSAlert()
  667. alert.alertStyle = .critical
  668. alert.messageText = NSLocalizedString("Invalid file link", comment: "")
  669. alert.runModal()
  670. return
  671. }
  672. let destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent(downFileName)
  673. if FileManager.default.fileExists(atPath: destinationURL.path) {
  674. do {
  675. try FileManager.default.removeItem(at: destinationURL)
  676. print("删除旧文件成功")
  677. } catch {
  678. print("删除旧文件失败:\(error)")
  679. }
  680. }
  681. let sessionConfiguration = URLSessionConfiguration.default
  682. let session = URLSession(configuration: sessionConfiguration)
  683. let downloadTask = session.downloadTask(with: fileURL) { (tempLocalURL, response, error) in
  684. if let error = error {
  685. let alert = NSAlert()
  686. alert.alertStyle = .critical
  687. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Download failed", comment: ""))
  688. alert.runModal()
  689. return
  690. }
  691. guard let tempLocalURL = tempLocalURL else {
  692. let alert = NSAlert()
  693. alert.alertStyle = .critical
  694. alert.messageText = NSLocalizedString("Invalid temporary directory", comment: "")
  695. alert.runModal()
  696. return
  697. }
  698. DispatchQueue.main.async {
  699. self.hiddenProgressWindow()
  700. }
  701. do {
  702. try FileManager.default.moveItem(at: tempLocalURL, to: destinationURL)
  703. NSDocumentController.shared.openDocument(withContentsOf: destinationURL, display: true) { document, documentWasAlreadyOpen, error in
  704. if error != nil {
  705. NSApp.presentError(error!)
  706. } else {
  707. }
  708. }
  709. } catch {
  710. let alert = NSAlert()
  711. alert.alertStyle = .critical
  712. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Failed to save file", comment: ""))
  713. alert.runModal()
  714. }
  715. }
  716. downloadTask.resume()
  717. }
  718. override func otherMouseDown(with event: NSEvent) {
  719. if historyFileViewController.selectFiles.count > 0 {
  720. let eventPoint = event.locationInWindow as NSPoint
  721. let x = eventPoint.x - 270.0
  722. if x >= 0 {
  723. let point = NSPoint(x: x, y: eventPoint.y)
  724. if historyFileViewController.historyFileCollectionView.frame.contains(point) ||
  725. historyFileViewController.historyFileTableView.frame.contains(point) ||
  726. historyFileViewController.deleteBox.frame.contains(point) ||
  727. historyFileViewController.listBox.frame.contains(point) ||
  728. historyFileViewController.thumbnailBox.frame.contains(point) {
  729. } else {
  730. self.historyFileViewController.selectFiles.removeAll()
  731. self.historyFileViewController.selectFiles_shift.removeAll()
  732. if self.historyFileViewController.showMode == .Thumbnail {
  733. self.historyFileViewController.historyFileCollectionView.reloadData()
  734. } else {
  735. self.historyFileViewController.historyFileTableView.reloadData()
  736. }
  737. }
  738. } else {
  739. self.historyFileViewController.selectFiles.removeAll()
  740. self.historyFileViewController.selectFiles_shift.removeAll()
  741. if self.historyFileViewController.showMode == .Thumbnail {
  742. self.historyFileViewController.historyFileCollectionView.reloadData()
  743. } else {
  744. self.historyFileViewController.historyFileTableView.reloadData()
  745. }
  746. }
  747. }
  748. }
  749. internal func showConvertWindow(type: KMPDFConvertType) {
  750. Task { @MainActor in
  751. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  752. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  753. return
  754. }
  755. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  756. var windowController: KMConvertBaseWindowController?
  757. if (type == .word) { /// Word
  758. windowController = KMConvertWordWindowController()
  759. } else if (type == .excel) {
  760. windowController = KMConvertExcelWindowController()
  761. } else if (type == .ppt || type == .rtf || type == .html || type == .text) {
  762. windowController = KMConvertPPTsWindowController()
  763. if (type == .ppt) {
  764. windowController?.subType = 1
  765. } else if (type == .rtf) {
  766. windowController?.subType = 2
  767. } else if (type == .html) {
  768. windowController?.subType = 3
  769. } else if (type == .text) {
  770. windowController?.subType = 4
  771. }
  772. } else if (type == .csv) {
  773. windowController = KMConvertCSVWindowController()
  774. } else if (type == .image) {
  775. windowController = KMConvertImageWindowController()
  776. }
  777. let model = KMDocumentModel(url: url)
  778. if (password != nil) {
  779. let _ = model.unlock(password!)
  780. }
  781. windowController?.documentModel = model
  782. windowController?.itemClick = { [weak self] index in
  783. if (self?.currentWindowController == nil) {
  784. return
  785. }
  786. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  787. self?.currentWindowController = nil
  788. }
  789. self.view.window?.beginSheet((windowController?.window)!)
  790. self.currentWindowController = windowController
  791. }
  792. }
  793. }
  794. // MARK: PDF Tools
  795. // 插入
  796. func insertPageAction(_ pdfDocument: CPDFDocument, _ password: String, _ pages: [CPDFPage], _ indexPage: Int) -> Void {
  797. if indexPage >= 0 {
  798. let insertPages: [CPDFPage] = pages
  799. for i in 0...insertPages.count-1 {
  800. let page = pages[i]
  801. // FIXME: 待底层库修改,使用 insertPageObject 插入,插入位置变为文档最后,暂用 insertPage 代替
  802. pdfDocument.insertPageObject(page, at: UInt(indexPage + i))
  803. }
  804. self.savePDFDocument(pdfDocument, password: password)
  805. }
  806. }
  807. func extractPageAction(_ pdfDocument: CPDFDocument, _ pages: [CPDFPage], _ oneDocumentPerPage: Bool, _ isDeletePage: Bool) -> Void {
  808. if pages.count < 1 {
  809. let alert = NSAlert()
  810. alert.alertStyle = .critical
  811. alert.messageText = NSLocalizedString("Please select two or more pages first to organize.", comment: "")
  812. alert.runModal()
  813. return
  814. }
  815. if !oneDocumentPerPage {
  816. let fileName = pdfDocument.getFileNameAccordingSelctPages(pages)
  817. let outputSavePanel = NSSavePanel()
  818. outputSavePanel.allowedFileTypes = ["pdf"]
  819. outputSavePanel.nameFieldStringValue = fileName
  820. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  821. if result == .OK {
  822. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  823. let saveFilePath = outputSavePanel.url?.path
  824. DispatchQueue.global().async {
  825. var pdf = CPDFDocument.init()
  826. let success = (pdf!.extractAsOneDocument(withPages: pages, savePath: saveFilePath)) as Bool
  827. DispatchQueue.main.async {
  828. if success {
  829. let workspace = NSWorkspace.shared
  830. let url = URL(fileURLWithPath: saveFilePath!)
  831. workspace.activateFileViewerSelecting([url])
  832. if isDeletePage {
  833. for page in pages {
  834. let indexPage = pdfDocument.index(for: page)
  835. pdfDocument.removePage(at: indexPage)
  836. }
  837. }
  838. }
  839. }
  840. }
  841. }
  842. }
  843. }
  844. } else {
  845. let panel = NSOpenPanel()
  846. panel.canChooseFiles = false
  847. panel.canChooseDirectories = true
  848. panel.canCreateDirectories = true
  849. panel.allowsMultipleSelection = false
  850. panel.beginSheetModal(for: self.view.window!) { result in
  851. if result == .OK {
  852. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  853. let outputURL = panel.url
  854. DispatchQueue.global().async {
  855. let folderName = String(pdfDocument.documentURL!.lastPathComponent.split(separator: ".")[0]) + "_extract"
  856. var filePath = URL(fileURLWithPath: outputURL!.path).appendingPathComponent(folderName).path
  857. var i = 1
  858. let testFilePath = filePath
  859. while FileManager.default.fileExists(atPath: filePath) {
  860. filePath = testFilePath + "\(i)"
  861. i += 1
  862. }
  863. try? FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
  864. let successArray = pdfDocument.extractPerPageDocument(withPages: pages, folerPath: filePath)
  865. DispatchQueue.main.async {
  866. if successArray!.count > 0 {
  867. NSWorkspace.shared.activateFileViewerSelecting(successArray!)
  868. if !isDeletePage {
  869. for page in pages {
  870. let indexPage = pdfDocument.index(for: page)
  871. pdfDocument.removePage(at: indexPage)
  872. }
  873. }
  874. }
  875. }
  876. }
  877. }
  878. }
  879. }
  880. }
  881. }
  882. // MARK: 快捷工具 Action
  883. func fastToolDidSelectAllTools() {
  884. // 首页 快捷工具 Tools按钮
  885. refreshRightBoxUI(.PDFTools)
  886. }
  887. func fastTool_Batch() { // Batch
  888. // KMBatchWindowController.openFile(nil, .Batch)
  889. }
  890. func fastTool_OCR() { // OCR
  891. // KMOCRWindowController.openFiles(window: self.view.window!)
  892. }
  893. func fastTool_ConvertPDF() { // 转换PDF
  894. // KMBatchWindowController.openFile(nil, .ConvertPDF)
  895. }
  896. func fastTool_ImageToPDF() { // 图片转PDF
  897. KMImageToPDFWindowController.openFiles(window: NSApp.mainWindow!)
  898. }
  899. func fastTool_MergePDF() { // MergePDF
  900. Task { @MainActor in
  901. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  902. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  903. return
  904. }
  905. NSPanel.km_open_pdf_multi_success(self.view.window!, panel: nil) { urls in
  906. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  907. var filepaths: Array<String> = []
  908. for url in urls {
  909. filepaths.append(url.path)
  910. }
  911. let windowController = KMPDFEditAppendWindow(filePaths: filepaths)
  912. self.currentWindowController = windowController
  913. windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, indexs in
  914. })
  915. }
  916. }
  917. }
  918. }
  919. func fastTool_Compression() { // 压缩
  920. Task { @MainActor in
  921. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  922. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  923. return
  924. }
  925. NSOpenPanel.km_secure_openPanel(window: self.view.window!) { url, result, passowrd in
  926. if (url == nil) {
  927. return
  928. }
  929. if (result != nil && result! == .cancel) {
  930. return
  931. }
  932. self.showCompressWindow(url!, passowrd)
  933. }
  934. }
  935. }
  936. func showCompressWindow(_ url: URL, _ password: String?) {
  937. Task { @MainActor in
  938. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  939. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  940. return
  941. }
  942. let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  943. self.currentWindowController = windowController
  944. windowController.documentURL = url
  945. windowController.password = password
  946. windowController.itemClick = { [weak self] (index: Int) -> () in
  947. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  948. self?.currentWindowController = nil
  949. }
  950. windowController.resultCallback = { [weak self] (result: Bool, openDocument: Bool, fileURL: URL, error: String) in
  951. if result {
  952. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  953. self?.currentWindowController = nil
  954. if openDocument {
  955. if !fileURL.path.isPDFValid() {
  956. let alert = NSAlert()
  957. alert.alertStyle = .critical
  958. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  959. alert.runModal()
  960. return
  961. }
  962. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in
  963. if error != nil {
  964. NSApp.presentError(error!)
  965. return
  966. }
  967. }
  968. } else {
  969. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  970. }
  971. } else {
  972. let alert = NSAlert()
  973. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  974. alert.runModal()
  975. }
  976. }
  977. await self.view.window?.beginSheet(windowController.window!)
  978. }
  979. }
  980. func fastTool_Security() { // 安全
  981. Task { @MainActor in
  982. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  983. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  984. return
  985. }
  986. NSOpenPanel.km_secure_openPanel(window: self.view.window!, needOwner: true) { url, result, passowrd in
  987. if (url == nil) {
  988. return
  989. }
  990. if (result != nil && result! == .cancel) {
  991. return
  992. }
  993. let windowController = KMSecureEncryptWindowController(windowNibName: "KMSecureEncryptWindowController")
  994. windowController.documentURL = url!
  995. windowController.myDocument = CPDFDocument(url: url!)
  996. if (passowrd != nil) {
  997. windowController.myDocument.unlock(withPassword: passowrd)
  998. }
  999. self.currentWindowController = windowController
  1000. let newDocument: CPDFDocument = CPDFDocument(url: url!)
  1001. windowController.itemClick = { [weak self] (index: Int) -> () in
  1002. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  1003. self?.currentWindowController = nil
  1004. }
  1005. windowController.resultCallback = { [weak self] (result: Bool) -> () in
  1006. let windowController_secure: KMSecureEncryptWindowController = self?.currentWindowController as! KMSecureEncryptWindowController
  1007. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  1008. self!.currentWindowController = nil
  1009. if (passowrd != nil) {
  1010. newDocument.unlock(withPassword: passowrd)
  1011. }
  1012. newDocument.setPasswordOptions(windowController_secure.options)
  1013. let result = KMPasswordInputWindow.saveDocument(newDocument)
  1014. if result {
  1015. NSWorkspace.shared.activateFileViewerSelecting([newDocument.documentURL])
  1016. } else {
  1017. let alert = NSAlert()
  1018. alert.messageText = NSLocalizedString("Failure", comment: "")
  1019. alert.runModal()
  1020. }
  1021. }
  1022. self.view.window?.beginSheet(windowController.window!)
  1023. }
  1024. }
  1025. }
  1026. func fastTool_FileCompare() { // 文件对比
  1027. print("选中 快捷工具 文件对比")
  1028. }
  1029. func fastTool_PDFToPPT() { // PDF转PPT
  1030. Task { @MainActor in
  1031. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1032. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1033. return
  1034. }
  1035. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1036. let windowController = KMConvertPPTsWindowController(windowNibName: "KMConvertBaseWindowController")
  1037. let model = KMDocumentModel(url: url)
  1038. windowController.subType = 1
  1039. if (password != nil) {
  1040. let _ = model.unlock(password!)
  1041. }
  1042. windowController.documentModel = model
  1043. windowController.itemClick = { [weak self] (index: Int) in
  1044. if (self?.currentWindowController == nil) {
  1045. return
  1046. }
  1047. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1048. self?.currentWindowController = nil
  1049. }
  1050. self.view.window?.beginSheet(windowController.window!)
  1051. self.currentWindowController = windowController
  1052. }
  1053. }
  1054. }
  1055. func fastTool_PDFToExcel() { // PDF转Excel
  1056. Task { @MainActor in
  1057. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1058. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1059. return
  1060. }
  1061. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1062. let windowController = KMConvertExcelWindowController(windowNibName: "KMConvertBaseWindowController")
  1063. let model = KMDocumentModel(url: url)
  1064. if (password != nil) {
  1065. let _ = model.unlock(password!)
  1066. }
  1067. windowController.documentModel = model
  1068. windowController.itemClick = { [weak self] (index: Int) in
  1069. if (self?.currentWindowController == nil) {
  1070. return
  1071. }
  1072. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1073. self?.currentWindowController = nil
  1074. }
  1075. self.view.window?.beginSheet(windowController.window!)
  1076. self.currentWindowController = windowController
  1077. }
  1078. }
  1079. }
  1080. func fastTool_PDFToWord() { // PDF转Word
  1081. Task { @MainActor in
  1082. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1083. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1084. return
  1085. }
  1086. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1087. if (url.path.isPDFValid() == false) {
  1088. let alert = NSAlert()
  1089. alert.alertStyle = .critical
  1090. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1091. alert.runModal()
  1092. return
  1093. }
  1094. let windowController = KMConvertWordWindowController(windowNibName: "KMConvertBaseWindowController")
  1095. let model = KMDocumentModel(url: url)
  1096. if (password != nil) {
  1097. let _ = model.unlock(password!)
  1098. }
  1099. windowController.documentModel = model
  1100. windowController.itemClick = { [weak self] (index: Int) in
  1101. if (self?.currentWindowController == nil) {
  1102. return
  1103. }
  1104. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1105. self?.currentWindowController = nil
  1106. }
  1107. self.view.window?.beginSheet(windowController.window!)
  1108. self.currentWindowController = windowController
  1109. }
  1110. }
  1111. }
  1112. func fastTool_PDFToImage() { // PDF转图片
  1113. Task { @MainActor in
  1114. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1115. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1116. return
  1117. }
  1118. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1119. let windowController = KMConvertImageWindowController(windowNibName: "KMConvertBaseWindowController")
  1120. let model = KMDocumentModel(url: url)
  1121. if (password != nil) {
  1122. let _ = model.unlock(password!)
  1123. }
  1124. windowController.documentModel = model
  1125. windowController.itemClick = { [weak self] (index: Int) in
  1126. if (self?.currentWindowController == nil) {
  1127. return
  1128. }
  1129. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1130. self?.currentWindowController = nil
  1131. }
  1132. self.view.window?.beginSheet(windowController.window!)
  1133. self.currentWindowController = windowController
  1134. }
  1135. }
  1136. }
  1137. func fastTool_Watermark() { // 水印
  1138. KMBatchWindowController.openFile(nil, .Watermark)
  1139. }
  1140. func fastTool_Background() { // 背景
  1141. KMBatchWindowController.openFile(nil, .Background)
  1142. }
  1143. func fastTool_HeaderAndFooter() { // 页眉页脚
  1144. KMBatchWindowController.openFile(nil, .HeaderAndFooter)
  1145. }
  1146. func fastTool_BatesCode() { // 贝茨码
  1147. KMBatchWindowController.openFile(nil, .BatesCode)
  1148. }
  1149. func fastTool_Print() { // 打印
  1150. KMPrintWindowController.openFiles(window: self.view.window!)
  1151. }
  1152. func fastTool_BatchRemove() { // 批量移除
  1153. KMBatchWindowController.openFile(nil, .BatchRemove)
  1154. }
  1155. func fastTool_Insert() { // 插入
  1156. let openPanel = NSOpenPanel()
  1157. openPanel.prompt = "插入"
  1158. openPanel.allowsMultipleSelection = false
  1159. openPanel.allowedFileTypes = ["pdf"]
  1160. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1161. if result == .OK {
  1162. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1163. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Insert)
  1164. insertWindowController.beginSheetModal(for: self.view.window!) { pdfDocument, password, pages, indexPage in
  1165. self.insertPageAction(pdfDocument, password, pages, indexPage)
  1166. }
  1167. }
  1168. }
  1169. }
  1170. }
  1171. func fastTool_BreakUp() { // 拆分
  1172. let openPanel = NSOpenPanel()
  1173. openPanel.prompt = "提取"
  1174. openPanel.allowsMultipleSelection = false
  1175. openPanel.allowedFileTypes = ["pdf"]
  1176. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1177. if result == .OK {
  1178. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1179. let document = CPDFDocument(url: openPanel.url)
  1180. let model = KMPageEditSplitSettingModel()
  1181. model.documentURL = openPanel.url
  1182. model.fileName = model.documentURL.lastPathComponent
  1183. model.pathExtension = model.fileName.components(separatedBy: ".").last
  1184. let windowController = KMPageEditSplitWindowController(model)
  1185. windowController.hasPreView = true
  1186. self.view.window?.beginSheet(windowController.window!)
  1187. self.currentWindowController = windowController
  1188. windowController.itemClick = { [weak self] index, value in
  1189. if (index == 1) { /// 取消
  1190. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1191. self?.currentWindowController = nil
  1192. return
  1193. }
  1194. /// 拆分
  1195. let windowController_split: KMPageEditSplitWindowController = self?.currentWindowController as! KMPageEditSplitWindowController
  1196. let outputModel: KMPageEditSplitSettingModel = windowController_split.model! as! KMPageEditSplitSettingModel
  1197. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1198. self?.currentWindowController = nil
  1199. let panel = NSOpenPanel()
  1200. panel.canChooseFiles = false
  1201. panel.canChooseDirectories = true
  1202. panel.canCreateDirectories = true
  1203. panel.beginSheetModal(for: (self?.view.window)!) { response in
  1204. KMPageEditTools.split(document!, outputModel, panel.url!.path, outputModel.outputFileNameDeletePathExtension) { result, outputDocuments, error in
  1205. if (result) {
  1206. }
  1207. }
  1208. }
  1209. }
  1210. }
  1211. }
  1212. }
  1213. }
  1214. func fastTool_Extract() { // 提取
  1215. let openPanel = NSOpenPanel()
  1216. openPanel.prompt = "提取"
  1217. openPanel.allowsMultipleSelection = false
  1218. openPanel.allowedFileTypes = ["pdf"]
  1219. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1220. if result == .OK {
  1221. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1222. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Extract)
  1223. insertWindowController.beginSheetExtractModal(for: self.view.window!) { pdfDocument, pages, oneDocumentPerPage, isDeletePage in
  1224. self.extractPageAction(pdfDocument, pages, oneDocumentPerPage, isDeletePage)
  1225. }
  1226. }
  1227. }
  1228. }
  1229. }
  1230. func fastTool_MarkCipher() { // 标记密文
  1231. let openPanel = NSOpenPanel()
  1232. openPanel.allowsMultipleSelection = false
  1233. openPanel.allowedFileTypes = ["pdf"]
  1234. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1235. if result == .cancel {
  1236. return
  1237. }
  1238. if !openPanel.url!.path.isPDFValid() {
  1239. let alert = NSAlert()
  1240. alert.alertStyle = .critical
  1241. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1242. alert.runModal()
  1243. return
  1244. }
  1245. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1246. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1247. if (error != nil) {
  1248. NSApp.presentError(error!)
  1249. return
  1250. }
  1251. let toolbar = (document as! KMMainDocument).mainViewController?.toolbarController
  1252. toolbar?.enterRedact()
  1253. }
  1254. }
  1255. }
  1256. }
  1257. func fastTool_AutomaticFormRecognition() { // 表单自动识别
  1258. let openPanel = NSOpenPanel()
  1259. openPanel.prompt = "表单自动识别"
  1260. openPanel.allowsMultipleSelection = false
  1261. openPanel.allowedFileTypes = ["pdf"]
  1262. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1263. if result == .OK {
  1264. }
  1265. }
  1266. }
  1267. func fastTool_PageEdit() { // 页面编辑
  1268. let openPanel = NSOpenPanel()
  1269. openPanel.allowsMultipleSelection = false
  1270. openPanel.allowedFileTypes = ["pdf"]
  1271. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1272. if result == .cancel {
  1273. return
  1274. }
  1275. if !openPanel.url!.path.isPDFValid() {
  1276. let alert = NSAlert()
  1277. alert.alertStyle = .critical
  1278. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1279. alert.runModal()
  1280. return
  1281. }
  1282. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1283. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1284. if (error != nil) {
  1285. NSApp.presentError(error!)
  1286. return
  1287. }
  1288. let mainView = (document as! KMMainDocument).mainViewController
  1289. mainView?.enterPageEdit()
  1290. }
  1291. }
  1292. }
  1293. }
  1294. // MARK: MenuItem Action & PopoverItem Action
  1295. func popoverItemAction(_ count: String) {
  1296. if count == NSLocalizedString("New Blank Page", comment: "") {
  1297. openBlankPage("")
  1298. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  1299. importFromWebPage("")
  1300. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  1301. importFromScanner("")
  1302. }
  1303. }
  1304. @IBAction func escButtonAction(_ sender: Any) {
  1305. self.historyFileViewController.selectFiles.removeAll()
  1306. if self.historyFileViewController.showMode == .Thumbnail {
  1307. self.historyFileViewController.historyFileCollectionView.reloadData()
  1308. } else {
  1309. self.historyFileViewController.historyFileTableView.reloadData()
  1310. }
  1311. }
  1312. @IBAction func importFromFile(_ sender: Any) {
  1313. self.openSupportPDFButtonAction()
  1314. }
  1315. @IBAction func openBlankPage(_ sender: Any) {
  1316. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  1317. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  1318. let pdfDocument = CPDFDocument()
  1319. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  1320. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  1321. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  1322. if error != nil {
  1323. NSApp.presentError(error!)
  1324. } else {
  1325. if document is KMMainDocument {
  1326. let newDocument = document
  1327. (newDocument as! KMMainDocument).isNewCreated = true
  1328. }
  1329. }
  1330. }
  1331. }
  1332. @IBAction func importFromWebPage(_ sender: Any) {
  1333. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  1334. self.urlToPDFWindowController!.beginSheetModal(for: NSApp.mainWindow!) { filePath in
  1335. if filePath != nil && FileManager.default.fileExists(atPath: filePath) {
  1336. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  1337. if error != nil {
  1338. NSApp.presentError(error!)
  1339. } else {
  1340. if document is KMMainDocument {
  1341. (document as! KMMainDocument).isNewCreated = true
  1342. }
  1343. }
  1344. }
  1345. }
  1346. }
  1347. }
  1348. @IBAction func importFromScanner(_ sender: Any) {
  1349. deviceBrowserWC = KMDeviceBrowserWindowController.shared
  1350. deviceBrowserWC?.type = .scanner
  1351. deviceBrowserWC?.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  1352. self?.openFile(withFilePath: url as URL)
  1353. }
  1354. deviceBrowserWC?.showWindow(NSApp.mainWindow)
  1355. }
  1356. @IBAction func menuItemClick_mergePDF(_ sender: Any) {
  1357. fastTool_MergePDF()
  1358. }
  1359. @IBAction func menuItemClick_Compress(_ sender: Any) {
  1360. fastTool_Compression()
  1361. }
  1362. @IBAction func menuItemClick_Convert(_ sender: Any) {
  1363. fastTool_ConvertPDF()
  1364. }
  1365. @IBAction func menuItemClick_SettingPassword(_ sender: Any) {
  1366. fastTool_Security()
  1367. }
  1368. @IBAction func menuItemClick_RemovePassword(_ sender: Any) {
  1369. fastTool_Security()
  1370. }
  1371. func fetchUniquePath(_ originalPath: String) -> String {
  1372. var path = originalPath
  1373. let dManager = FileManager.default
  1374. if !dManager.fileExists(atPath: path) {
  1375. if path.extension.count < 1 {
  1376. path = path.stringByAppendingPathExtension("pdf")
  1377. }
  1378. return path
  1379. } else {
  1380. let originalFullFileName = path.lastPathComponent
  1381. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  1382. let originalExtension = path.extension
  1383. let startIndex: Int = 0
  1384. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  1385. let fileLocatePath = originalPath.substring(to: endIndex)
  1386. var i = 1
  1387. while (1 != 0) {
  1388. var newName = String(format: "%@%ld", originalFileName, i)
  1389. newName = String(format: "%@%@", newName, originalExtension)
  1390. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  1391. if !dManager.fileExists(atPath: newPath) {
  1392. return newPath
  1393. } else {
  1394. i+=1
  1395. continue
  1396. }
  1397. }
  1398. }
  1399. }
  1400. // func kNewDocumentTempSavePath(_ fileName: String) -> String {
  1401. // let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  1402. //// let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1403. // let append2 = searchPath!.stringByAppendingPathComponent(String(format: "%@", fileName))
  1404. // return append2
  1405. // }
  1406. // MARK: Notification
  1407. @objc func homeFileRectChange(_ notification: Notification) -> Void {
  1408. let window = notification.object
  1409. self.historyFileViewController.reloadData()
  1410. }
  1411. }
  1412. // MARK: window Menu
  1413. extension KMHomeViewController {
  1414. @IBAction func menuItemAction_showForwardTagPage(_ sender: Any) {
  1415. (self.myDocument as! KMMainDocument).browser.selectPreviousTab()
  1416. }
  1417. @IBAction func menuItemAction_showNextTagPage(_ sender: Any) {
  1418. (self.myDocument as! KMMainDocument).browser.selectNextTab()
  1419. }
  1420. @IBAction func menuItemAction_newTagPageToNewWindow(_ sender: Any) {
  1421. let browser = (self.myDocument as! KMMainDocument).browser
  1422. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.openNewWindow(sender)
  1423. }
  1424. @IBAction func menuItemAction_mergeAllWindow(_ sender: Any) {
  1425. ((self.myDocument as? KMMainDocument)?.browser.windowController as? KMBrowserWindowController)?.mergeAllWindow(sender)
  1426. }
  1427. @IBAction func menuItemAction_currentWindowName(_ sender: Any) {
  1428. }
  1429. }
  1430. // MARK: file Menu
  1431. extension KMHomeViewController {
  1432. @IBAction func menuItemAction_closeWindow(_ sender: Any) {
  1433. self.view.window?.close()
  1434. }
  1435. @IBAction func menuItemAction_closeAllWindows(_ sender: Any) {
  1436. for window in NSApp.windows {
  1437. window.close()
  1438. }
  1439. }
  1440. @IBAction func menuItemAction_ConvertToWord(_ sender: Any) {
  1441. self.fastTool_PDFToWord()
  1442. }
  1443. @IBAction func menuItemAction_ConvertToExcel(_ sender: Any) {
  1444. self.fastTool_PDFToExcel()
  1445. }
  1446. @IBAction func menuItemAction_ConvertToPPT(_ sender: Any) {
  1447. self.fastTool_PDFToPPT()
  1448. }
  1449. @IBAction func menuItemAction_ConvertToRTF(_ sender: Any) {
  1450. self.showConvertWindow(type: .rtf)
  1451. }
  1452. @IBAction func menuItemAction_ConvertToHTML(_ sender: Any) {
  1453. self.showConvertWindow(type: .html)
  1454. }
  1455. @IBAction func menuItemAction_ConvertToText(_ sender: Any) {
  1456. self.showConvertWindow(type: .text)
  1457. }
  1458. @IBAction func menuItemAction_ConvertToCSV(_ sender: Any) {
  1459. self.showConvertWindow(type: .csv)
  1460. }
  1461. @IBAction func menuItemAction_ConvertToImage(_ sender: Any) {
  1462. self.fastTool_PDFToImage()
  1463. }
  1464. }
  1465. // MARK: help Menu
  1466. extension KMHomeViewController {
  1467. // @IBAction func menuItemAction_search(_ sender: Any) {
  1468. //
  1469. // }
  1470. }