KMHomeViewController+Action.swift 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  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. return true
  27. }
  28. }
  29. extension KMHomeViewController {
  30. // MARK: Action
  31. @objc func homeToolAction(_ sender: NSButton) -> Void {
  32. if sender == homeButtonVC.button {
  33. homeToolAction(homeToolState: KMHomeToolState.Home)
  34. } else if sender == pdfToolsButtonVC.button {
  35. homeToolAction(homeToolState: KMHomeToolState.PDFTools)
  36. } else if sender == cloudDocumentsButtonVC.button {
  37. homeToolAction(homeToolState: KMHomeToolState.CloudDocuments)
  38. } else if sender == openPDFButtonVC.button {
  39. homeToolAction(homeToolState: KMHomeToolState.OpenPDF)
  40. } else if sender == createPDFButtonVC.button {
  41. openSupportPDFButtonAction()
  42. } else if sender == createPDFImage.button {
  43. homeToolAction(homeToolState: KMHomeToolState.CreatePDF)
  44. }
  45. }
  46. func homeToolAction(homeToolState: KMHomeToolState) {
  47. switch homeToolState {
  48. case .OpenPDF:
  49. openPDFButtonAction()
  50. break
  51. case .CreatePDF:
  52. createPDFButtonAction()
  53. break
  54. case .Home:
  55. homeButtonAction()
  56. break
  57. case .PDFTools:
  58. pdfToolsButtonAction()
  59. break
  60. case .FavoriteDocuments:
  61. favoriteDocumentsButtonAction()
  62. break
  63. case .CloudDocuments:
  64. cloudDocumentsButtonAction()
  65. break
  66. default:
  67. print("error: 错误的传入枚举")
  68. break
  69. }
  70. }
  71. func fastToolItemAction(_ type: DataNavigationViewButtonActionType) {
  72. switch type {
  73. case .Batch:
  74. fastTool_Batch()
  75. break
  76. case .OCR:
  77. fastTool_OCR()
  78. break
  79. case .ConvertPDF:
  80. fastTool_ConvertPDF()
  81. break
  82. case .ImageToPDF:
  83. fastTool_ImageToPDF()
  84. break
  85. case .MergePDF:
  86. fastTool_MergePDF()
  87. break
  88. case .Compression:
  89. fastTool_Compression()
  90. break
  91. case .Security:
  92. fastTool_Security()
  93. break
  94. case .FileCompare:
  95. fastTool_FileCompare()
  96. break
  97. case .PDFToPPT:
  98. fastTool_PDFToPPT()
  99. break
  100. case .PDFToExcel:
  101. fastTool_PDFToExcel()
  102. break
  103. case .PDFToWord:
  104. fastTool_PDFToWord()
  105. break
  106. case .PDFToImage:
  107. fastTool_PDFToImage()
  108. break
  109. case .Watermark:
  110. fastTool_Watermark()
  111. break
  112. case .Background:
  113. fastTool_Background()
  114. break
  115. case .HeaderAndFooter:
  116. fastTool_HeaderAndFooter()
  117. break
  118. case .BatesCode:
  119. fastTool_BatesCode()
  120. break
  121. case .Print:
  122. fastTool_Print()
  123. break
  124. case .BatchRemove:
  125. fastTool_BatchRemove()
  126. break
  127. case .Insert:
  128. fastTool_Insert()
  129. break
  130. case .BreakUp:
  131. fastTool_BreakUp()
  132. break
  133. case .Extract:
  134. fastTool_Extract()
  135. break
  136. case .MarkCipher:
  137. fastTool_MarkCipher()
  138. break
  139. case .AutomaticFormRecognition:
  140. fastTool_AutomaticFormRecognition()
  141. break
  142. case .PageEdit:
  143. fastTool_PageEdit()
  144. break
  145. }
  146. }
  147. func openPDFButtonAction() {
  148. let openPanel = NSOpenPanel()
  149. openPanel.allowedFileTypes = ["pdf", "PDF"]
  150. openPanel.allowsMultipleSelection = true
  151. openPanel.beginSheetModal(for: self.view.window!) { result in
  152. if result == .OK {
  153. for url in openPanel.urls {
  154. if !url.path.isPDFValid() {
  155. let alert = NSAlert()
  156. alert.alertStyle = .critical
  157. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  158. alert.runModal()
  159. } else {
  160. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  161. if error != nil {
  162. NSApp.presentError(error!)
  163. } else {
  164. }
  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.runModal()
  338. return
  339. }
  340. if url.pathExtension.lowercased() == "pdf" {
  341. let pdfDoc = CPDFDocument.init(url: url)
  342. if pdfDoc != nil {
  343. let document = NSDocumentController.shared.document(for: url)
  344. var alreadyOpen = false
  345. for openDocument in NSDocumentController.shared.documents {
  346. if document == openDocument {
  347. alreadyOpen = true
  348. }
  349. }
  350. if !alreadyOpen {
  351. KMMainDocument().tryToUnlockDocument(pdfDoc!)
  352. if ((pdfDoc?.isLocked)! == true) {
  353. KMPasswordInputWindow.openWindow(window: self.view.window!, url: url) { result, password in
  354. if result == .cancel { /// 关闭
  355. return
  356. }
  357. /// 解密成功
  358. var selectDocument: KMMainDocument? = nil
  359. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  360. selectDocument = (document as! KMMainDocument)
  361. }
  362. if selectDocument != nil {
  363. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  364. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  365. if (selectDocument?.browser.window.isVisible)! as Bool {
  366. selectDocument?.browser.window.orderFront(nil)
  367. } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  368. selectDocument?.browser.window.orderFront(nil)
  369. }
  370. } else {
  371. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  372. if error != nil {
  373. NSApp.presentError(error!)
  374. return
  375. }
  376. // (document as! KMMainDocument).mainViewController.listView.document.unlock(withPassword: password)
  377. (document as! KMMainDocument).mainViewController?.password = password
  378. }
  379. }
  380. }
  381. return
  382. } else {
  383. var selectDocument: KMMainDocument? = nil
  384. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  385. selectDocument = (document as! KMMainDocument)
  386. }
  387. if selectDocument != 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. } else {
  396. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  397. if error != nil {
  398. NSApp.presentError(error!)
  399. return
  400. }
  401. }
  402. }
  403. }
  404. } else {
  405. var selectDocument: KMMainDocument? = nil
  406. if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  407. selectDocument = (document as! KMMainDocument)
  408. }
  409. if selectDocument != nil {
  410. if selectDocument?.browser != nil {
  411. let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  412. selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  413. if (selectDocument?.browser.window.isVisible)! as Bool {
  414. selectDocument?.browser.window.orderFront(nil)
  415. } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  416. selectDocument?.browser.window.orderFront(nil)
  417. }
  418. }
  419. } else {
  420. NSDocumentController.shared.openDocument(withContentsOf: url, display: true) { document, documentWasAlreadyOpen, error in
  421. if error != nil {
  422. NSApp.presentError(error!)
  423. return
  424. }
  425. }
  426. }
  427. }
  428. } else {
  429. let alert = NSAlert()
  430. alert.alertStyle = .critical
  431. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  432. alert.runModal()
  433. }
  434. } else {
  435. NSWorkspace.shared.open(url)
  436. }
  437. }
  438. func openFile(withFilePath path: URL) -> Void {
  439. let type = path.pathExtension.lowercased()
  440. if (type == "pdf") {
  441. if !path.path.isPDFValid() {
  442. let alert = NSAlert()
  443. alert.alertStyle = .critical
  444. alert.messageText = NSLocalizedString("This file format is not supported, please drag in PDF, picture, Office format files", comment: "")
  445. alert.runModal()
  446. return
  447. }
  448. NSDocumentController.shared.openDocument(withContentsOf: path, display: true) { document, documentWasAlreadyOpen, error in
  449. if error != nil {
  450. NSApp.presentError(error!)
  451. return
  452. }
  453. }
  454. } else if (type == "jpg") ||
  455. (type == "cur") ||
  456. (type == "bmp") ||
  457. (type == "jpeg") ||
  458. (type == "gif") ||
  459. (type == "png") ||
  460. (type == "tiff") ||
  461. (type == "tif") ||
  462. (type == "ico") ||
  463. (type == "icns") ||
  464. (type == "tga") ||
  465. (type == "psd") ||
  466. (type == "eps") ||
  467. (type == "hdr") ||
  468. (type == "jp2") ||
  469. (type == "jpc") ||
  470. (type == "pict") ||
  471. (type == "sgi") ||
  472. (type == "heic") {
  473. openImageFile(url: path)
  474. } else if (type == "doc") ||
  475. (type == "docx") ||
  476. (type == "xls") ||
  477. (type == "xlsx") ||
  478. (type == "ppt") ||
  479. (type == "pptx") ||
  480. (type == "pptx") {
  481. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  482. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  483. openOfficeFile(url: path)
  484. }
  485. }
  486. func openImageFile(url: URL) -> Void {
  487. let filePath = url.path
  488. let fileName: NSString = url.lastPathComponent as NSString
  489. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath()).deletingLastPathComponent
  490. let imageName = NSString(string: NSString(string: filePath).lastPathComponent).deletingPathExtension
  491. let path = self.fetchDifferentFilePath(filePath: savePath + "/" + imageName + ".pdf")
  492. let document = CPDFDocument.init()
  493. var success = false
  494. //FIXME: 无法插入图片
  495. let image = NSImage(contentsOfFile: filePath)
  496. let insertPageSuccess = document?.insertPage(image!.size, withImage: filePath, at: document!.pageCount)
  497. if insertPageSuccess != nil {
  498. //信号量控制异步
  499. let semaphore = DispatchSemaphore(value: 0)
  500. DispatchQueue.global().async {
  501. success = ((document?.write(toFile: path)) != nil)
  502. semaphore.signal()
  503. }
  504. semaphore.wait()
  505. } else {
  506. }
  507. if success {
  508. if !path.isPDFValid() {
  509. let alert = NSAlert()
  510. alert.alertStyle = .critical
  511. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  512. alert.runModal()
  513. return
  514. }
  515. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { document, documentWasAlreadyOpen, error in
  516. if error != nil {
  517. NSApp.presentError(error!)
  518. return
  519. }
  520. }
  521. }
  522. }
  523. func openOfficeFile(url: URL) -> Void {
  524. let filePath = url.path
  525. let folderPath = "convertToPDF.pdf"
  526. let savePath = folderPath.kUrlToPDFFolderPath()
  527. if savePath == nil {
  528. return
  529. }
  530. KMConvertPDFManagerOC.convertFile(filePath, savePath: savePath!) { success, errorDic in
  531. if errorDic != nil || !success || !FileManager.default.fileExists(atPath: savePath!) {
  532. if FileManager.default.fileExists(atPath: savePath!) {
  533. try?FileManager.default.removeItem(atPath: savePath!)
  534. }
  535. let alert = NSAlert.init()
  536. alert.alertStyle = .critical
  537. var infoString = ""
  538. if errorDic != nil {
  539. for key in (errorDic! as Dictionary).keys {
  540. infoString = infoString.appendingFormat("%@\n", errorDic![key] as! CVarArg)
  541. }
  542. }
  543. alert.informativeText = NSLocalizedString("Please install Microsoft Office to create PDFs from Office files", comment: "")
  544. alert.messageText = NSLocalizedString("Failed to Create PDF", comment: "")
  545. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  546. alert.runModal()
  547. return
  548. }
  549. if !savePath!.isPDFValid() {
  550. let alert = NSAlert()
  551. alert.alertStyle = .critical
  552. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  553. alert.runModal()
  554. return
  555. }
  556. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath!), display: true) { document, documentWasAlreadyOpen, error in
  557. if error != nil {
  558. NSApp.presentError(error!)
  559. return
  560. }
  561. }
  562. }
  563. }
  564. func aiTranslation(withFilePath path: String) -> Void {
  565. if !KMLightMemberManager.manager.isLogin() {
  566. KMLoginWindowController.show(window: NSApp.mainWindow!)
  567. return
  568. }
  569. if self.isFileGreaterThan10MB(atPath: path) {
  570. self.aiTranslationViewController.errorView.isHidden = false
  571. self.aiTranslationViewController.errorLabel.stringValue = NSLocalizedString("The uploaded file cannot exceed 10MB", comment: "")
  572. } else {
  573. let url = URL(fileURLWithPath: path)
  574. if (url.pathExtension == "pdf") || url.pathExtension == "PDF" {
  575. if !path.isPDFValid() {
  576. let alert = NSAlert()
  577. alert.alertStyle = .critical
  578. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  579. alert.runModal()
  580. return
  581. }
  582. }
  583. let infoDictionary = Bundle .main.infoDictionary!
  584. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  585. DispatchQueue.main.async {
  586. self.showProgressWindow()
  587. }
  588. KMRequestServerManager.manager.aiTranslationFileUpload(file: path, version: "1.0.1") { [unowned self] success, result in
  589. if success {
  590. let result: NSDictionary = result!.result
  591. let fileKey = result["fileKey"]
  592. let fileName = result["fileName"]
  593. let pageCount = result["pageCount"]
  594. if fileKey != nil {
  595. self.fileTranslateHandle(fileKey as! String)
  596. }
  597. } else {
  598. let result: String = result!.message
  599. DispatchQueue.main.async {
  600. self.hiddenProgressWindow()
  601. self.aiTranslationViewController.errorView.isHidden = false
  602. self.aiTranslationViewController.errorLabel.stringValue = result
  603. }
  604. }
  605. }
  606. }
  607. }
  608. func fileTranslateHandle(_ fileKey: String) -> Void {
  609. let infoDictionary = Bundle .main.infoDictionary!
  610. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  611. KMRequestServerManager.manager.aiTranslationFileTranslateHandle(fileKey: fileKey, from: self.aiTranslationViewController.fromStr, to: self.aiTranslationViewController.toStr, version: "1.0.1") { success, result in
  612. if success {
  613. let result: NSDictionary = result!.result
  614. let fileUrl: String = result["fileUrl"] as! String
  615. let downFileUrl: String = result["downFileUrl"] as! String
  616. let ossDownUrl: String = result["ossDownUrl"] as! String
  617. let fileName: String = result["fileName"] as! String
  618. let downFileName: String = result["downFileName"] as! String
  619. let from: String = result["from"] as! String
  620. let to: String = result["to"] as! String
  621. self.downloadFile(filePath: ossDownUrl, downFileName: downFileName)
  622. } else {
  623. let result: String = result!.message
  624. DispatchQueue.main.async {
  625. self.hiddenProgressWindow()
  626. self.aiTranslationViewController.errorView.isHidden = false
  627. self.aiTranslationViewController.errorLabel.stringValue = result
  628. }
  629. }
  630. }
  631. }
  632. func downloadFile(filePath: String, downFileName: String) -> Void {
  633. guard let fileURL = URL(string: filePath) else {
  634. let alert = NSAlert()
  635. alert.alertStyle = .critical
  636. alert.messageText = NSLocalizedString("Invalid file link", comment: "")
  637. alert.runModal()
  638. return
  639. }
  640. let destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent(downFileName)
  641. if FileManager.default.fileExists(atPath: destinationURL.path) {
  642. do {
  643. try FileManager.default.removeItem(at: destinationURL)
  644. print("删除旧文件成功")
  645. } catch {
  646. print("删除旧文件失败:\(error)")
  647. }
  648. }
  649. let sessionConfiguration = URLSessionConfiguration.default
  650. let session = URLSession(configuration: sessionConfiguration)
  651. let downloadTask = session.downloadTask(with: fileURL) { (tempLocalURL, response, error) in
  652. if let error = error {
  653. let alert = NSAlert()
  654. alert.alertStyle = .critical
  655. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Download failure", comment: ""))
  656. alert.runModal()
  657. return
  658. }
  659. guard let tempLocalURL = tempLocalURL else {
  660. let alert = NSAlert()
  661. alert.alertStyle = .critical
  662. alert.messageText = NSLocalizedString("The download file temporary path is invalid", comment: "")
  663. alert.runModal()
  664. return
  665. }
  666. DispatchQueue.main.async {
  667. self.hiddenProgressWindow()
  668. }
  669. do {
  670. try FileManager.default.moveItem(at: tempLocalURL, to: destinationURL)
  671. NSDocumentController.shared.openDocument(withContentsOf: destinationURL, display: true) { document, documentWasAlreadyOpen, error in
  672. if error != nil {
  673. NSApp.presentError(error!)
  674. } else {
  675. }
  676. }
  677. } catch {
  678. let alert = NSAlert()
  679. alert.alertStyle = .critical
  680. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("File saving failure", comment: ""))
  681. alert.runModal()
  682. }
  683. }
  684. downloadTask.resume()
  685. }
  686. override func otherMouseDown(with event: NSEvent) {
  687. if historyFileViewController.selectFiles.count > 0 {
  688. let eventPoint = event.locationInWindow as NSPoint
  689. let x = eventPoint.x - 270.0
  690. if x >= 0 {
  691. let point = NSPoint(x: x, y: eventPoint.y)
  692. if historyFileViewController.historyFileCollectionView.frame.contains(point) ||
  693. historyFileViewController.historyFileTableView.frame.contains(point) ||
  694. historyFileViewController.deleteBox.frame.contains(point) ||
  695. historyFileViewController.listBox.frame.contains(point) ||
  696. historyFileViewController.thumbnailBox.frame.contains(point) {
  697. } else {
  698. self.historyFileViewController.selectFiles.removeAll()
  699. self.historyFileViewController.selectFiles_shift.removeAll()
  700. if self.historyFileViewController.showMode == .Thumbnail {
  701. self.historyFileViewController.historyFileCollectionView.reloadData()
  702. } else {
  703. self.historyFileViewController.historyFileTableView.reloadData()
  704. }
  705. }
  706. } else {
  707. self.historyFileViewController.selectFiles.removeAll()
  708. self.historyFileViewController.selectFiles_shift.removeAll()
  709. if self.historyFileViewController.showMode == .Thumbnail {
  710. self.historyFileViewController.historyFileCollectionView.reloadData()
  711. } else {
  712. self.historyFileViewController.historyFileTableView.reloadData()
  713. }
  714. }
  715. }
  716. }
  717. internal func showConvertWindow(type: KMPDFConvertType) {
  718. Task { @MainActor in
  719. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  720. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  721. return
  722. }
  723. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  724. var windowController: KMConvertBaseWindowController?
  725. if (type == .word) { /// Word
  726. windowController = KMConvertWordWindowController()
  727. } else if (type == .excel) {
  728. windowController = KMConvertExcelWindowController()
  729. } else if (type == .ppt || type == .rtf || type == .html || type == .text) {
  730. windowController = KMConvertPPTsWindowController()
  731. if (type == .ppt) {
  732. windowController?.subType = 1
  733. } else if (type == .rtf) {
  734. windowController?.subType = 2
  735. } else if (type == .html) {
  736. windowController?.subType = 3
  737. } else if (type == .text) {
  738. windowController?.subType = 4
  739. }
  740. } else if (type == .csv) {
  741. windowController = KMConvertCSVWindowController()
  742. } else if (type == .image) {
  743. windowController = KMConvertImageWindowController()
  744. }
  745. let model = KMDocumentModel(url: url)
  746. if (password != nil) {
  747. let _ = model.unlock(password!)
  748. }
  749. windowController?.documentModel = model
  750. windowController?.itemClick = { [weak self] index in
  751. if (self?.currentWindowController == nil) {
  752. return
  753. }
  754. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  755. self?.currentWindowController = nil
  756. }
  757. self.view.window?.beginSheet((windowController?.window)!)
  758. self.currentWindowController = windowController
  759. }
  760. }
  761. }
  762. // MARK: PDF Tools
  763. // 插入
  764. func insertPageAction(_ pdfDocument: CPDFDocument, _ password: String, _ pages: [CPDFPage], _ indexPage: Int) -> Void {
  765. if indexPage >= 0 {
  766. let insertPages: [CPDFPage] = pages
  767. for i in 0...insertPages.count-1 {
  768. let page = pages[i]
  769. // FIXME: 待底层库修改,使用 insertPageObject 插入,插入位置变为文档最后,暂用 insertPage 代替
  770. pdfDocument.insertPageObject(page, at: UInt(indexPage + i))
  771. }
  772. self.savePDFDocument(pdfDocument, password: password)
  773. }
  774. }
  775. func extractPageAction(_ pdfDocument: CPDFDocument, _ pages: [CPDFPage], _ oneDocumentPerPage: Bool, _ isDeletePage: Bool) -> Void {
  776. if pages.count < 1 {
  777. let alert = NSAlert()
  778. alert.alertStyle = .critical
  779. alert.messageText = NSLocalizedString("Please select two or more pages first to organize.", comment: "")
  780. alert.runModal()
  781. return
  782. }
  783. if !oneDocumentPerPage {
  784. let fileName = pdfDocument.getFileNameAccordingSelctPages(pages)
  785. let outputSavePanel = NSSavePanel()
  786. outputSavePanel.allowedFileTypes = ["pdf"]
  787. outputSavePanel.nameFieldStringValue = fileName
  788. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  789. if result == .OK {
  790. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  791. let saveFilePath = outputSavePanel.url?.path
  792. DispatchQueue.global().async {
  793. var pdf = CPDFDocument.init()
  794. let success = (pdf!.extractAsOneDocument(withPages: pages, savePath: saveFilePath)) as Bool
  795. DispatchQueue.main.async {
  796. if success {
  797. let workspace = NSWorkspace.shared
  798. let url = URL(fileURLWithPath: saveFilePath!)
  799. workspace.activateFileViewerSelecting([url])
  800. if isDeletePage {
  801. for page in pages {
  802. let indexPage = pdfDocument.index(for: page)
  803. pdfDocument.removePage(at: indexPage)
  804. }
  805. }
  806. }
  807. }
  808. }
  809. }
  810. }
  811. }
  812. } else {
  813. let panel = NSOpenPanel()
  814. panel.canChooseFiles = false
  815. panel.canChooseDirectories = true
  816. panel.canCreateDirectories = true
  817. panel.allowsMultipleSelection = false
  818. panel.beginSheetModal(for: self.view.window!) { result in
  819. if result == .OK {
  820. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  821. let outputURL = panel.url
  822. DispatchQueue.global().async {
  823. let folderName = String(pdfDocument.documentURL!.lastPathComponent.split(separator: ".")[0]) + "_extract"
  824. var filePath = URL(fileURLWithPath: outputURL!.path).appendingPathComponent(folderName).path
  825. var i = 1
  826. let testFilePath = filePath
  827. while FileManager.default.fileExists(atPath: filePath) {
  828. filePath = testFilePath + "\(i)"
  829. i += 1
  830. }
  831. try? FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
  832. let successArray = pdfDocument.extractPerPageDocument(withPages: pages, folerPath: filePath)
  833. DispatchQueue.main.async {
  834. if successArray!.count > 0 {
  835. NSWorkspace.shared.activateFileViewerSelecting(successArray!)
  836. if !isDeletePage {
  837. for page in pages {
  838. let indexPage = pdfDocument.index(for: page)
  839. pdfDocument.removePage(at: indexPage)
  840. }
  841. }
  842. }
  843. }
  844. }
  845. }
  846. }
  847. }
  848. }
  849. }
  850. // MARK: 快捷工具 Action
  851. func fastToolDidSelectAllTools() {
  852. // 首页 快捷工具 Tools按钮
  853. refreshRightBoxUI(.PDFTools)
  854. }
  855. func fastTool_Batch() { // Batch
  856. // KMBatchWindowController.openFile(nil, .Batch)
  857. }
  858. func fastTool_OCR() { // OCR
  859. // KMOCRWindowController.openFiles(window: self.view.window!)
  860. }
  861. func fastTool_ConvertPDF() { // 转换PDF
  862. // KMBatchWindowController.openFile(nil, .ConvertPDF)
  863. }
  864. func fastTool_ImageToPDF() { // 图片转PDF
  865. print("选中 快捷工具 图片转PDF")
  866. KMImageToPDFWindowController.openFiles(window: NSApp.mainWindow!)
  867. }
  868. func fastTool_MergePDF() { // MergePDF
  869. Task { @MainActor in
  870. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  871. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  872. return
  873. }
  874. let panel = NSOpenPanel()
  875. panel.allowedFileTypes = ["pdf"]
  876. panel.allowsMultipleSelection = true
  877. panel.beginSheetModal(for: self.view.window!) { response in
  878. if (response == .cancel) {
  879. return
  880. }
  881. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  882. var filepaths: Array<String> = []
  883. for url in panel.urls {
  884. filepaths.append(url.path)
  885. }
  886. let windowController = KMPDFEditAppendWindow(filePaths: filepaths)
  887. self.currentWindowController = windowController
  888. windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, indexs in
  889. })
  890. }
  891. }
  892. }
  893. }
  894. func fastTool_Compression() { // 压缩
  895. Task { @MainActor in
  896. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  897. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  898. return
  899. }
  900. NSOpenPanel.km_secure_openPanel(window: self.view.window!) { url, result, passowrd in
  901. if (url == nil) {
  902. return
  903. }
  904. if (result != nil && result! == .cancel) {
  905. return
  906. }
  907. self.showCompressWindow(url!, passowrd)
  908. }
  909. }
  910. }
  911. func showCompressWindow(_ url: URL, _ password: String?) {
  912. Task { @MainActor in
  913. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  914. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  915. return
  916. }
  917. let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  918. self.currentWindowController = windowController
  919. windowController.documentURL = url
  920. windowController.password = password
  921. windowController.itemClick = { [weak self] (index: Int) -> () in
  922. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  923. self?.currentWindowController = nil
  924. }
  925. windowController.resultCallback = { [weak self] (result: Bool, openDocument: Bool, fileURL: URL, error: String) in
  926. if result {
  927. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  928. self?.currentWindowController = nil
  929. if openDocument {
  930. if !fileURL.path.isPDFValid() {
  931. let alert = NSAlert()
  932. alert.alertStyle = .critical
  933. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  934. alert.runModal()
  935. return
  936. }
  937. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in
  938. if error != nil {
  939. NSApp.presentError(error!)
  940. return
  941. }
  942. }
  943. } else {
  944. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  945. }
  946. } else {
  947. let alert = NSAlert()
  948. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  949. alert.runModal()
  950. }
  951. }
  952. await self.view.window?.beginSheet(windowController.window!)
  953. }
  954. }
  955. func fastTool_Security() { // 安全
  956. Task { @MainActor in
  957. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  958. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  959. return
  960. }
  961. NSOpenPanel.km_secure_openPanel(window: self.view.window!, needOwner: true) { url, result, passowrd in
  962. if (url == nil) {
  963. return
  964. }
  965. if (result != nil && result! == .cancel) {
  966. return
  967. }
  968. let windowController = KMSecureEncryptWindowController(windowNibName: "KMSecureEncryptWindowController")
  969. windowController.documentURL = url!
  970. windowController.myDocument = CPDFDocument(url: url!)
  971. if (passowrd != nil) {
  972. windowController.myDocument.unlock(withPassword: passowrd)
  973. }
  974. self.currentWindowController = windowController
  975. let newDocument: CPDFDocument = CPDFDocument(url: url!)
  976. windowController.itemClick = { [weak self] (index: Int) -> () in
  977. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  978. self?.currentWindowController = nil
  979. }
  980. windowController.resultCallback = { [weak self] (result: Bool) -> () in
  981. let windowController_secure: KMSecureEncryptWindowController = self?.currentWindowController as! KMSecureEncryptWindowController
  982. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  983. self!.currentWindowController = nil
  984. if (passowrd != nil) {
  985. newDocument.unlock(withPassword: passowrd)
  986. }
  987. newDocument.setPasswordOptions(windowController_secure.options)
  988. let result = KMPasswordInputWindow.saveDocument(newDocument)
  989. if result {
  990. NSWorkspace.shared.activateFileViewerSelecting([newDocument.documentURL])
  991. } else {
  992. let alert = NSAlert()
  993. alert.messageText = NSLocalizedString("Failure", comment: "")
  994. alert.runModal()
  995. }
  996. }
  997. self.view.window?.beginSheet(windowController.window!)
  998. }
  999. }
  1000. }
  1001. func fastTool_FileCompare() { // 文件对比
  1002. print("选中 快捷工具 文件对比")
  1003. }
  1004. func fastTool_PDFToPPT() { // PDF转PPT
  1005. Task { @MainActor in
  1006. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1007. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1008. return
  1009. }
  1010. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1011. let windowController = KMConvertPPTsWindowController(windowNibName: "KMConvertBaseWindowController")
  1012. let model = KMDocumentModel(url: url)
  1013. windowController.subType = 1
  1014. if (password != nil) {
  1015. let _ = model.unlock(password!)
  1016. }
  1017. windowController.documentModel = model
  1018. windowController.itemClick = { [weak self] (index: Int) in
  1019. if (self?.currentWindowController == nil) {
  1020. return
  1021. }
  1022. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1023. self?.currentWindowController = nil
  1024. }
  1025. self.view.window?.beginSheet(windowController.window!)
  1026. self.currentWindowController = windowController
  1027. }
  1028. }
  1029. }
  1030. func fastTool_PDFToExcel() { // PDF转Excel
  1031. Task { @MainActor in
  1032. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1033. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1034. return
  1035. }
  1036. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1037. let windowController = KMConvertExcelWindowController(windowNibName: "KMConvertBaseWindowController")
  1038. let model = KMDocumentModel(url: url)
  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_PDFToWord() { // PDF转Word
  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 = KMConvertWordWindowController(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_PDFToImage() { // PDF转图片
  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. let windowController = KMConvertImageWindowController(windowNibName: "KMConvertBaseWindowController")
  1088. let model = KMDocumentModel(url: url)
  1089. if (password != nil) {
  1090. let _ = model.unlock(password!)
  1091. }
  1092. windowController.documentModel = model
  1093. windowController.itemClick = { [weak self] (index: Int) in
  1094. if (self?.currentWindowController == nil) {
  1095. return
  1096. }
  1097. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1098. self?.currentWindowController = nil
  1099. }
  1100. self.view.window?.beginSheet(windowController.window!)
  1101. self.currentWindowController = windowController
  1102. }
  1103. }
  1104. }
  1105. func fastTool_Watermark() { // 水印
  1106. KMBatchWindowController.openFile(nil, .Watermark)
  1107. }
  1108. func fastTool_Background() { // 背景
  1109. KMBatchWindowController.openFile(nil, .Background)
  1110. }
  1111. func fastTool_HeaderAndFooter() { // 页眉页脚
  1112. KMBatchWindowController.openFile(nil, .HeaderAndFooter)
  1113. }
  1114. func fastTool_BatesCode() { // 贝茨码
  1115. KMBatchWindowController.openFile(nil, .BatesCode)
  1116. }
  1117. func fastTool_Print() { // 打印
  1118. KMPrintWindowController.openFiles(window: self.view.window!)
  1119. }
  1120. func fastTool_BatchRemove() { // 批量移除
  1121. KMBatchWindowController.openFile(nil, .BatchRemove)
  1122. }
  1123. func fastTool_Insert() { // 插入
  1124. let openPanel = NSOpenPanel()
  1125. openPanel.prompt = "插入"
  1126. openPanel.allowsMultipleSelection = false
  1127. openPanel.allowedFileTypes = ["pdf"]
  1128. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1129. if result == .OK {
  1130. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1131. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Insert)
  1132. insertWindowController.beginSheetModal(for: self.view.window!) { pdfDocument, password, pages, indexPage in
  1133. self.insertPageAction(pdfDocument, password, pages, indexPage)
  1134. }
  1135. }
  1136. }
  1137. }
  1138. }
  1139. func fastTool_BreakUp() { // 拆分
  1140. let openPanel = NSOpenPanel()
  1141. openPanel.prompt = "提取"
  1142. openPanel.allowsMultipleSelection = false
  1143. openPanel.allowedFileTypes = ["pdf"]
  1144. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1145. if result == .OK {
  1146. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1147. let document = CPDFDocument(url: openPanel.url)
  1148. let model = KMPageEditSplitSettingModel()
  1149. model.documentURL = openPanel.url
  1150. model.fileName = model.documentURL.lastPathComponent
  1151. model.pathExtension = model.fileName.components(separatedBy: ".").last
  1152. let windowController = KMPageEditSplitWindowController(model)
  1153. windowController.hasPreView = true
  1154. self.view.window?.beginSheet(windowController.window!)
  1155. self.currentWindowController = windowController
  1156. windowController.itemClick = { [weak self] index, value in
  1157. if (index == 1) { /// 取消
  1158. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1159. self?.currentWindowController = nil
  1160. return
  1161. }
  1162. /// 拆分
  1163. let windowController_split: KMPageEditSplitWindowController = self?.currentWindowController as! KMPageEditSplitWindowController
  1164. let outputModel: KMPageEditSplitSettingModel = windowController_split.model! as! KMPageEditSplitSettingModel
  1165. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1166. self?.currentWindowController = nil
  1167. let panel = NSOpenPanel()
  1168. panel.canChooseFiles = false
  1169. panel.canChooseDirectories = true
  1170. panel.canCreateDirectories = true
  1171. panel.beginSheetModal(for: (self?.view.window)!) { response in
  1172. KMPageEditTools.split(document!, outputModel, panel.url!.path, outputModel.outputFileNameDeletePathExtension) { result, outputDocuments, error in
  1173. if (result) {
  1174. }
  1175. }
  1176. }
  1177. }
  1178. }
  1179. }
  1180. }
  1181. }
  1182. func fastTool_Extract() { // 提取
  1183. let openPanel = NSOpenPanel()
  1184. openPanel.prompt = "提取"
  1185. openPanel.allowsMultipleSelection = false
  1186. openPanel.allowedFileTypes = ["pdf"]
  1187. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1188. if result == .OK {
  1189. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1190. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Extract)
  1191. insertWindowController.beginSheetExtractModal(for: self.view.window!) { pdfDocument, pages, oneDocumentPerPage, isDeletePage in
  1192. self.extractPageAction(pdfDocument, pages, oneDocumentPerPage, isDeletePage)
  1193. }
  1194. }
  1195. }
  1196. }
  1197. }
  1198. func fastTool_MarkCipher() { // 标记密文
  1199. let openPanel = NSOpenPanel()
  1200. openPanel.allowsMultipleSelection = false
  1201. openPanel.allowedFileTypes = ["pdf"]
  1202. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1203. if result == .cancel {
  1204. return
  1205. }
  1206. if !openPanel.url!.path.isPDFValid() {
  1207. let alert = NSAlert()
  1208. alert.alertStyle = .critical
  1209. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1210. alert.runModal()
  1211. return
  1212. }
  1213. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1214. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1215. if (error != nil) {
  1216. NSApp.presentError(error!)
  1217. return
  1218. }
  1219. let toolbar = (document as! KMMainDocument).mainViewController?.toolbarController
  1220. toolbar?.enterRedact()
  1221. }
  1222. }
  1223. }
  1224. }
  1225. func fastTool_AutomaticFormRecognition() { // 表单自动识别
  1226. let openPanel = NSOpenPanel()
  1227. openPanel.prompt = "表单自动识别"
  1228. openPanel.allowsMultipleSelection = false
  1229. openPanel.allowedFileTypes = ["pdf"]
  1230. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1231. if result == .OK {
  1232. }
  1233. }
  1234. }
  1235. func fastTool_PageEdit() { // 页面编辑
  1236. let openPanel = NSOpenPanel()
  1237. openPanel.allowsMultipleSelection = false
  1238. openPanel.allowedFileTypes = ["pdf"]
  1239. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1240. if result == .cancel {
  1241. return
  1242. }
  1243. if !openPanel.url!.path.isPDFValid() {
  1244. let alert = NSAlert()
  1245. alert.alertStyle = .critical
  1246. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1247. alert.runModal()
  1248. return
  1249. }
  1250. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1251. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1252. if (error != nil) {
  1253. NSApp.presentError(error!)
  1254. return
  1255. }
  1256. let mainView = (document as! KMMainDocument).mainViewController
  1257. mainView?.enterPageEdit()
  1258. }
  1259. }
  1260. }
  1261. }
  1262. // MARK: MenuItem Action & PopoverItem Action
  1263. func popoverItemAction(_ count: String) {
  1264. if count == NSLocalizedString("New Blank Page", comment: "") {
  1265. openBlankPage("")
  1266. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  1267. importFromWebPage("")
  1268. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  1269. importFromScanner("")
  1270. }
  1271. }
  1272. @IBAction func escButtonAction(_ sender: Any) {
  1273. self.historyFileViewController.selectFiles.removeAll()
  1274. if self.historyFileViewController.showMode == .Thumbnail {
  1275. self.historyFileViewController.historyFileCollectionView.reloadData()
  1276. } else {
  1277. self.historyFileViewController.historyFileTableView.reloadData()
  1278. }
  1279. }
  1280. @IBAction func importFromFile(_ sender: Any) {
  1281. self.openSupportPDFButtonAction()
  1282. }
  1283. @IBAction func openBlankPage(_ sender: Any) {
  1284. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  1285. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  1286. let pdfDocument = CPDFDocument()
  1287. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  1288. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  1289. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  1290. if error != nil {
  1291. NSApp.presentError(error!)
  1292. } else {
  1293. if document is KMMainDocument {
  1294. let newDocument = document
  1295. (newDocument as! KMMainDocument).isNewCreated = true
  1296. }
  1297. }
  1298. }
  1299. }
  1300. @IBAction func importFromWebPage(_ sender: Any) {
  1301. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  1302. self.urlToPDFWindowController!.beginSheetModal(for: NSApp.mainWindow!) { filePath in
  1303. if filePath != nil && FileManager.default.fileExists(atPath: filePath) {
  1304. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  1305. if error != nil {
  1306. NSApp.presentError(error!)
  1307. } else {
  1308. if document is KMMainDocument {
  1309. (document as! KMMainDocument).isNewCreated = true
  1310. }
  1311. }
  1312. }
  1313. }
  1314. }
  1315. }
  1316. @IBAction func importFromScanner(_ sender: Any) {
  1317. deviceBrowserWC = KMDeviceBrowserWindowController.init(windowNibName: "KMDeviceBrowserWindowController")
  1318. deviceBrowserWC!.type = .scanner
  1319. deviceBrowserWC!.importScannerFileCallback = { [unowned self](url: NSURL) -> Void in
  1320. openFile(withFilePath: url as URL)
  1321. }
  1322. deviceBrowserWC!.showWindow(NSApp.mainWindow)
  1323. }
  1324. @IBAction func menuItemClick_mergePDF(_ sender: Any) {
  1325. fastTool_MergePDF()
  1326. }
  1327. @IBAction func menuItemClick_Compress(_ sender: Any) {
  1328. fastTool_Compression()
  1329. }
  1330. @IBAction func menuItemClick_Convert(_ sender: Any) {
  1331. fastTool_ConvertPDF()
  1332. }
  1333. @IBAction func menuItemClick_SettingPassword(_ sender: Any) {
  1334. fastTool_Security()
  1335. }
  1336. @IBAction func menuItemClick_RemovePassword(_ sender: Any) {
  1337. fastTool_Security()
  1338. }
  1339. func fetchUniquePath(_ originalPath: String) -> String {
  1340. var path = originalPath
  1341. let dManager = FileManager.default
  1342. if !dManager.fileExists(atPath: path) {
  1343. if path.extension.count < 1 {
  1344. path = path.stringByAppendingPathExtension("pdf")
  1345. }
  1346. return path
  1347. } else {
  1348. let originalFullFileName = path.lastPathComponent
  1349. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  1350. let originalExtension = path.extension
  1351. let startIndex: Int = 0
  1352. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  1353. let fileLocatePath = originalPath.substring(to: endIndex)
  1354. var i = 1
  1355. while (1 != 0) {
  1356. var newName = String(format: "%@%ld", originalFileName, i)
  1357. newName = String(format: "%@%@", newName, originalExtension)
  1358. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  1359. if !dManager.fileExists(atPath: newPath) {
  1360. return newPath
  1361. } else {
  1362. i+=1
  1363. continue
  1364. }
  1365. }
  1366. }
  1367. }
  1368. // func kNewDocumentTempSavePath(_ fileName: String) -> String {
  1369. // let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  1370. //// let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1371. // let append2 = searchPath!.stringByAppendingPathComponent(String(format: "%@", fileName))
  1372. // return append2
  1373. // }
  1374. // MARK: Notification
  1375. @objc func homeFileRectChange(_ notification: Notification) -> Void {
  1376. let window = notification.object
  1377. self.historyFileViewController.reloadData()
  1378. }
  1379. }
  1380. // MARK: window Menu
  1381. extension KMHomeViewController {
  1382. @IBAction func menuItemAction_showForwardTagPage(_ sender: Any) {
  1383. (self.myDocument as! KMMainDocument).browser.selectPreviousTab()
  1384. }
  1385. @IBAction func menuItemAction_showNextTagPage(_ sender: Any) {
  1386. (self.myDocument as! KMMainDocument).browser.selectNextTab()
  1387. }
  1388. @IBAction func menuItemAction_newTagPageToNewWindow(_ sender: Any) {
  1389. let browser = (self.myDocument as! KMMainDocument).browser
  1390. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.openNewWindow(sender)
  1391. }
  1392. @IBAction func menuItemAction_mergeAllWindow(_ sender: Any) {
  1393. let browser = (self.myDocument as! KMMainDocument).browser
  1394. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.mergeAllWindow(sender)
  1395. }
  1396. @IBAction func menuItemAction_currentWindowName(_ sender: Any) {
  1397. }
  1398. }
  1399. // MARK: file Menu
  1400. extension KMHomeViewController {
  1401. @IBAction func menuItemAction_closeWindow(_ sender: Any) {
  1402. self.view.window?.close()
  1403. }
  1404. @IBAction func menuItemAction_closeAllWindows(_ sender: Any) {
  1405. for window in NSApp.windows {
  1406. window.close()
  1407. }
  1408. }
  1409. @IBAction func menuItemAction_ConvertToWord(_ sender: Any) {
  1410. self.fastTool_PDFToWord()
  1411. }
  1412. @IBAction func menuItemAction_ConvertToExcel(_ sender: Any) {
  1413. self.fastTool_PDFToExcel()
  1414. }
  1415. @IBAction func menuItemAction_ConvertToPPT(_ sender: Any) {
  1416. self.fastTool_PDFToPPT()
  1417. }
  1418. @IBAction func menuItemAction_ConvertToRTF(_ sender: Any) {
  1419. self.showConvertWindow(type: .rtf)
  1420. }
  1421. @IBAction func menuItemAction_ConvertToHTML(_ sender: Any) {
  1422. self.showConvertWindow(type: .html)
  1423. }
  1424. @IBAction func menuItemAction_ConvertToText(_ sender: Any) {
  1425. self.showConvertWindow(type: .text)
  1426. }
  1427. @IBAction func menuItemAction_ConvertToCSV(_ sender: Any) {
  1428. self.showConvertWindow(type: .csv)
  1429. }
  1430. @IBAction func menuItemAction_ConvertToImage(_ sender: Any) {
  1431. self.fastTool_PDFToImage()
  1432. }
  1433. }
  1434. // MARK: help Menu
  1435. extension KMHomeViewController {
  1436. // @IBAction func menuItemAction_search(_ sender: Any) {
  1437. //
  1438. // }
  1439. }