KMHomeViewController+Action.swift 62 KB

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