KMHomeViewController+Action.swift 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620
  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. if !path.isPDFValid() {
  574. let alert = NSAlert()
  575. alert.alertStyle = .critical
  576. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  577. alert.runModal()
  578. } else {
  579. let infoDictionary = Bundle .main.infoDictionary!
  580. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  581. DispatchQueue.main.async {
  582. self.showProgressWindow()
  583. }
  584. KMRequestServerManager.manager.aiTranslationFileUpload(file: path, version: "1.0.1") { [unowned self] success, result in
  585. if success {
  586. let result: NSDictionary = result!.result
  587. let fileKey = result["fileKey"]
  588. let fileName = result["fileName"]
  589. let pageCount = result["pageCount"]
  590. if fileKey != nil {
  591. self.fileTranslateHandle(fileKey as! String)
  592. }
  593. } else {
  594. let result: String = result!.message
  595. DispatchQueue.main.async {
  596. self.hiddenProgressWindow()
  597. self.aiTranslationViewController.errorView.isHidden = false
  598. self.aiTranslationViewController.errorLabel.stringValue = result
  599. }
  600. }
  601. }
  602. }
  603. }
  604. }
  605. func fileTranslateHandle(_ fileKey: String) -> Void {
  606. let infoDictionary = Bundle .main.infoDictionary!
  607. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  608. KMRequestServerManager.manager.aiTranslationFileTranslateHandle(fileKey: fileKey, from: self.aiTranslationViewController.fromStr, to: self.aiTranslationViewController.toStr, version: "1.0.1") { success, result in
  609. if success {
  610. let result: NSDictionary = result!.result
  611. let fileUrl: String = result["fileUrl"] as! String
  612. let downFileUrl: String = result["downFileUrl"] as! String
  613. let ossDownUrl: String = result["ossDownUrl"] as! String
  614. let fileName: String = result["fileName"] as! String
  615. let downFileName: String = result["downFileName"] as! String
  616. let from: String = result["from"] as! String
  617. let to: String = result["to"] as! String
  618. self.downloadFile(filePath: ossDownUrl, downFileName: downFileName)
  619. } else {
  620. let result: String = result!.message
  621. DispatchQueue.main.async {
  622. self.hiddenProgressWindow()
  623. self.aiTranslationViewController.errorView.isHidden = false
  624. self.aiTranslationViewController.errorLabel.stringValue = result
  625. }
  626. }
  627. }
  628. }
  629. func downloadFile(filePath: String, downFileName: String) -> Void {
  630. guard let fileURL = URL(string: filePath) else {
  631. let alert = NSAlert()
  632. alert.alertStyle = .critical
  633. alert.messageText = NSLocalizedString("Invalid file link", comment: "")
  634. alert.runModal()
  635. return
  636. }
  637. let destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent(downFileName)
  638. if FileManager.default.fileExists(atPath: destinationURL.path) {
  639. do {
  640. try FileManager.default.removeItem(at: destinationURL)
  641. print("删除旧文件成功")
  642. } catch {
  643. print("删除旧文件失败:\(error)")
  644. }
  645. }
  646. let sessionConfiguration = URLSessionConfiguration.default
  647. let session = URLSession(configuration: sessionConfiguration)
  648. let downloadTask = session.downloadTask(with: fileURL) { (tempLocalURL, response, error) in
  649. if let error = error {
  650. let alert = NSAlert()
  651. alert.alertStyle = .critical
  652. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Download failure", comment: ""))
  653. alert.runModal()
  654. return
  655. }
  656. guard let tempLocalURL = tempLocalURL else {
  657. let alert = NSAlert()
  658. alert.alertStyle = .critical
  659. alert.messageText = NSLocalizedString("The download file temporary path is invalid", comment: "")
  660. alert.runModal()
  661. return
  662. }
  663. DispatchQueue.main.async {
  664. self.hiddenProgressWindow()
  665. }
  666. do {
  667. try FileManager.default.moveItem(at: tempLocalURL, to: destinationURL)
  668. NSDocumentController.shared.openDocument(withContentsOf: destinationURL, display: true) { document, documentWasAlreadyOpen, error in
  669. if error != nil {
  670. NSApp.presentError(error!)
  671. } else {
  672. }
  673. }
  674. } catch {
  675. let alert = NSAlert()
  676. alert.alertStyle = .critical
  677. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("File saving failure", comment: ""))
  678. alert.runModal()
  679. }
  680. }
  681. downloadTask.resume()
  682. }
  683. override func otherMouseDown(with event: NSEvent) {
  684. if historyFileViewController.selectFiles.count > 0 {
  685. let eventPoint = event.locationInWindow as NSPoint
  686. let x = eventPoint.x - 270.0
  687. if x >= 0 {
  688. let point = NSPoint(x: x, y: eventPoint.y)
  689. if historyFileViewController.historyFileCollectionView.frame.contains(point) ||
  690. historyFileViewController.historyFileTableView.frame.contains(point) ||
  691. historyFileViewController.deleteBox.frame.contains(point) ||
  692. historyFileViewController.listBox.frame.contains(point) ||
  693. historyFileViewController.thumbnailBox.frame.contains(point) {
  694. } else {
  695. self.historyFileViewController.selectFiles.removeAll()
  696. self.historyFileViewController.selectFiles_shift.removeAll()
  697. if self.historyFileViewController.showMode == .Thumbnail {
  698. self.historyFileViewController.historyFileCollectionView.reloadData()
  699. } else {
  700. self.historyFileViewController.historyFileTableView.reloadData()
  701. }
  702. }
  703. } else {
  704. self.historyFileViewController.selectFiles.removeAll()
  705. self.historyFileViewController.selectFiles_shift.removeAll()
  706. if self.historyFileViewController.showMode == .Thumbnail {
  707. self.historyFileViewController.historyFileCollectionView.reloadData()
  708. } else {
  709. self.historyFileViewController.historyFileTableView.reloadData()
  710. }
  711. }
  712. }
  713. }
  714. internal func showConvertWindow(type: KMPDFConvertType) {
  715. Task { @MainActor in
  716. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  717. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  718. return
  719. }
  720. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  721. var windowController: KMConvertBaseWindowController?
  722. if (type == .word) { /// Word
  723. windowController = KMConvertWordWindowController()
  724. } else if (type == .excel) {
  725. windowController = KMConvertExcelWindowController()
  726. } else if (type == .ppt || type == .rtf || type == .html || type == .text) {
  727. windowController = KMConvertPPTsWindowController()
  728. if (type == .ppt) {
  729. windowController?.subType = 1
  730. } else if (type == .rtf) {
  731. windowController?.subType = 2
  732. } else if (type == .html) {
  733. windowController?.subType = 3
  734. } else if (type == .text) {
  735. windowController?.subType = 4
  736. }
  737. } else if (type == .csv) {
  738. windowController = KMConvertCSVWindowController()
  739. } else if (type == .image) {
  740. windowController = KMConvertImageWindowController()
  741. }
  742. let model = KMDocumentModel(url: url)
  743. if (password != nil) {
  744. let _ = model.unlock(password!)
  745. }
  746. windowController?.documentModel = model
  747. windowController?.itemClick = { [weak self] index in
  748. if (self?.currentWindowController == nil) {
  749. return
  750. }
  751. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  752. self?.currentWindowController = nil
  753. }
  754. self.view.window?.beginSheet((windowController?.window)!)
  755. self.currentWindowController = windowController
  756. }
  757. }
  758. }
  759. // MARK: PDF Tools
  760. // 插入
  761. func insertPageAction(_ pdfDocument: CPDFDocument, _ password: String, _ pages: [CPDFPage], _ indexPage: Int) -> Void {
  762. if indexPage >= 0 {
  763. let insertPages: [CPDFPage] = pages
  764. for i in 0...insertPages.count-1 {
  765. let page = pages[i]
  766. // FIXME: 待底层库修改,使用 insertPageObject 插入,插入位置变为文档最后,暂用 insertPage 代替
  767. pdfDocument.insertPageObject(page, at: UInt(indexPage + i))
  768. }
  769. self.savePDFDocument(pdfDocument, password: password)
  770. }
  771. }
  772. func extractPageAction(_ pdfDocument: CPDFDocument, _ pages: [CPDFPage], _ oneDocumentPerPage: Bool, _ isDeletePage: Bool) -> Void {
  773. if pages.count < 1 {
  774. let alert = NSAlert()
  775. alert.alertStyle = .critical
  776. alert.messageText = NSLocalizedString("Please select two or more pages first to organize.", comment: "")
  777. alert.runModal()
  778. return
  779. }
  780. if !oneDocumentPerPage {
  781. let fileName = pdfDocument.getFileNameAccordingSelctPages(pages)
  782. let outputSavePanel = NSSavePanel()
  783. outputSavePanel.allowedFileTypes = ["pdf"]
  784. outputSavePanel.nameFieldStringValue = fileName
  785. outputSavePanel.beginSheetModal(for: self.view.window!) { result in
  786. if result == .OK {
  787. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  788. let saveFilePath = outputSavePanel.url?.path
  789. DispatchQueue.global().async {
  790. var pdf = CPDFDocument.init()
  791. let success = (pdf!.extractAsOneDocument(withPages: pages, savePath: saveFilePath)) as Bool
  792. DispatchQueue.main.async {
  793. if success {
  794. let workspace = NSWorkspace.shared
  795. let url = URL(fileURLWithPath: saveFilePath!)
  796. workspace.activateFileViewerSelecting([url])
  797. if isDeletePage {
  798. for page in pages {
  799. let indexPage = pdfDocument.index(for: page)
  800. pdfDocument.removePage(at: indexPage)
  801. }
  802. }
  803. }
  804. }
  805. }
  806. }
  807. }
  808. }
  809. } else {
  810. let panel = NSOpenPanel()
  811. panel.canChooseFiles = false
  812. panel.canChooseDirectories = true
  813. panel.canCreateDirectories = true
  814. panel.allowsMultipleSelection = false
  815. panel.beginSheetModal(for: self.view.window!) { result in
  816. if result == .OK {
  817. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  818. let outputURL = panel.url
  819. DispatchQueue.global().async {
  820. let folderName = String(pdfDocument.documentURL!.lastPathComponent.split(separator: ".")[0]) + "_extract"
  821. var filePath = URL(fileURLWithPath: outputURL!.path).appendingPathComponent(folderName).path
  822. var i = 1
  823. let testFilePath = filePath
  824. while FileManager.default.fileExists(atPath: filePath) {
  825. filePath = testFilePath + "\(i)"
  826. i += 1
  827. }
  828. try? FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
  829. let successArray = pdfDocument.extractPerPageDocument(withPages: pages, folerPath: filePath)
  830. DispatchQueue.main.async {
  831. if successArray!.count > 0 {
  832. NSWorkspace.shared.activateFileViewerSelecting(successArray!)
  833. if !isDeletePage {
  834. for page in pages {
  835. let indexPage = pdfDocument.index(for: page)
  836. pdfDocument.removePage(at: indexPage)
  837. }
  838. }
  839. }
  840. }
  841. }
  842. }
  843. }
  844. }
  845. }
  846. }
  847. // MARK: 快捷工具 Action
  848. func fastToolDidSelectAllTools() {
  849. // 首页 快捷工具 Tools按钮
  850. refreshRightBoxUI(.PDFTools)
  851. }
  852. func fastTool_Batch() { // Batch
  853. // KMBatchWindowController.openFile(nil, .Batch)
  854. }
  855. func fastTool_OCR() { // OCR
  856. // KMOCRWindowController.openFiles(window: self.view.window!)
  857. }
  858. func fastTool_ConvertPDF() { // 转换PDF
  859. // KMBatchWindowController.openFile(nil, .ConvertPDF)
  860. }
  861. func fastTool_ImageToPDF() { // 图片转PDF
  862. print("选中 快捷工具 图片转PDF")
  863. KMImageToPDFWindowController.openFiles(window: NSApp.mainWindow!)
  864. }
  865. func fastTool_MergePDF() { // MergePDF
  866. Task { @MainActor in
  867. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  868. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  869. return
  870. }
  871. let panel = NSOpenPanel()
  872. panel.allowedFileTypes = ["pdf"]
  873. panel.allowsMultipleSelection = true
  874. panel.beginSheetModal(for: self.view.window!) { response in
  875. if (response == .cancel) {
  876. return
  877. }
  878. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  879. var filepaths: Array<String> = []
  880. for url in panel.urls {
  881. filepaths.append(url.path)
  882. }
  883. let windowController = KMPDFEditAppendWindow(filePaths: filepaths)
  884. self.currentWindowController = windowController
  885. windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, indexs in
  886. })
  887. }
  888. }
  889. }
  890. }
  891. func fastTool_Compression() { // 压缩
  892. Task { @MainActor in
  893. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  894. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  895. return
  896. }
  897. NSOpenPanel.km_secure_openPanel(window: self.view.window!) { url, result, passowrd in
  898. if (url == nil) {
  899. return
  900. }
  901. if (result != nil && result! == .cancel) {
  902. return
  903. }
  904. self.showCompressWindow(url!, passowrd)
  905. }
  906. }
  907. }
  908. func showCompressWindow(_ url: URL, _ password: String?) {
  909. Task { @MainActor in
  910. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  911. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  912. return
  913. }
  914. let windowController = KMCompressWindowController(windowNibName: "KMCompressWindowController")
  915. self.currentWindowController = windowController
  916. windowController.documentURL = url
  917. windowController.password = password
  918. windowController.itemClick = { [weak self] (index: Int) -> () in
  919. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  920. self?.currentWindowController = nil
  921. }
  922. windowController.resultCallback = { [weak self] (result: Bool, openDocument: Bool, fileURL: URL, error: String) in
  923. if result {
  924. self!.view.window?.endSheet(self!.currentWindowController!.window!)
  925. self?.currentWindowController = nil
  926. if openDocument {
  927. if !fileURL.path.isPDFValid() {
  928. let alert = NSAlert()
  929. alert.alertStyle = .critical
  930. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  931. alert.runModal()
  932. return
  933. }
  934. NSDocumentController.shared.openDocument(withContentsOf: fileURL, display: true) { document, result, error in
  935. if error != nil {
  936. NSApp.presentError(error!)
  937. return
  938. }
  939. }
  940. } else {
  941. NSWorkspace.shared.activateFileViewerSelecting([fileURL])
  942. }
  943. } else {
  944. let alert = NSAlert()
  945. alert.messageText = NSLocalizedString("Compress Faild", comment: "")
  946. alert.runModal()
  947. }
  948. }
  949. await self.view.window?.beginSheet(windowController.window!)
  950. }
  951. }
  952. func fastTool_Security() { // 安全
  953. Task { @MainActor in
  954. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  955. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  956. return
  957. }
  958. NSOpenPanel.km_secure_openPanel(window: self.view.window!, needOwner: true) { url, result, passowrd in
  959. if (url == nil) {
  960. return
  961. }
  962. if (result != nil && result! == .cancel) {
  963. return
  964. }
  965. let windowController = KMSecureEncryptWindowController(windowNibName: "KMSecureEncryptWindowController")
  966. windowController.documentURL = url!
  967. windowController.myDocument = CPDFDocument(url: url!)
  968. if (passowrd != nil) {
  969. windowController.myDocument.unlock(withPassword: passowrd)
  970. }
  971. self.currentWindowController = windowController
  972. let newDocument: CPDFDocument = CPDFDocument(url: url!)
  973. windowController.itemClick = { [weak self] (index: Int) -> () in
  974. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  975. self?.currentWindowController = nil
  976. }
  977. windowController.resultCallback = { [weak self] (result: Bool) -> () in
  978. let windowController_secure: KMSecureEncryptWindowController = self?.currentWindowController as! KMSecureEncryptWindowController
  979. self!.view.window?.endSheet((self?.currentWindowController?.window!)!)
  980. self!.currentWindowController = nil
  981. if (passowrd != nil) {
  982. newDocument.unlock(withPassword: passowrd)
  983. }
  984. newDocument.setPasswordOptions(windowController_secure.options)
  985. let result = KMPasswordInputWindow.saveDocument(newDocument)
  986. if result {
  987. NSWorkspace.shared.activateFileViewerSelecting([newDocument.documentURL])
  988. } else {
  989. let alert = NSAlert()
  990. alert.messageText = NSLocalizedString("Failure", comment: "")
  991. alert.runModal()
  992. }
  993. }
  994. self.view.window?.beginSheet(windowController.window!)
  995. }
  996. }
  997. }
  998. func fastTool_FileCompare() { // 文件对比
  999. print("选中 快捷工具 文件对比")
  1000. }
  1001. func fastTool_PDFToPPT() { // PDF转PPT
  1002. Task { @MainActor in
  1003. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1004. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1005. return
  1006. }
  1007. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1008. let windowController = KMConvertPPTsWindowController(windowNibName: "KMConvertBaseWindowController")
  1009. let model = KMDocumentModel(url: url)
  1010. windowController.subType = 1
  1011. if (password != nil) {
  1012. let _ = model.unlock(password!)
  1013. }
  1014. windowController.documentModel = model
  1015. windowController.itemClick = { [weak self] (index: Int) in
  1016. if (self?.currentWindowController == nil) {
  1017. return
  1018. }
  1019. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1020. self?.currentWindowController = nil
  1021. }
  1022. self.view.window?.beginSheet(windowController.window!)
  1023. self.currentWindowController = windowController
  1024. }
  1025. }
  1026. }
  1027. func fastTool_PDFToExcel() { // PDF转Excel
  1028. Task { @MainActor in
  1029. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1030. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1031. return
  1032. }
  1033. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1034. let windowController = KMConvertExcelWindowController(windowNibName: "KMConvertBaseWindowController")
  1035. let model = KMDocumentModel(url: url)
  1036. if (password != nil) {
  1037. let _ = model.unlock(password!)
  1038. }
  1039. windowController.documentModel = model
  1040. windowController.itemClick = { [weak self] (index: Int) in
  1041. if (self?.currentWindowController == nil) {
  1042. return
  1043. }
  1044. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1045. self?.currentWindowController = nil
  1046. }
  1047. self.view.window?.beginSheet(windowController.window!)
  1048. self.currentWindowController = windowController
  1049. }
  1050. }
  1051. }
  1052. func fastTool_PDFToWord() { // PDF转Word
  1053. Task { @MainActor in
  1054. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1055. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1056. return
  1057. }
  1058. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1059. let windowController = KMConvertWordWindowController(windowNibName: "KMConvertBaseWindowController")
  1060. let model = KMDocumentModel(url: url)
  1061. if (password != nil) {
  1062. let _ = model.unlock(password!)
  1063. }
  1064. windowController.documentModel = model
  1065. windowController.itemClick = { [weak self] (index: Int) in
  1066. if (self?.currentWindowController == nil) {
  1067. return
  1068. }
  1069. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1070. self?.currentWindowController = nil
  1071. }
  1072. self.view.window?.beginSheet(windowController.window!)
  1073. self.currentWindowController = windowController
  1074. }
  1075. }
  1076. }
  1077. func fastTool_PDFToImage() { // PDF转图片
  1078. Task { @MainActor in
  1079. if await (KMLightMemberManager.manager.canUseAdvanced() == false) {
  1080. let _ = KMComparativeTableViewController.show(window: self.view.window!)
  1081. return
  1082. }
  1083. NSOpenPanel.km_secure_openPanel_success(window: self.view.window!) { url, password in
  1084. let windowController = KMConvertImageWindowController(windowNibName: "KMConvertBaseWindowController")
  1085. let model = KMDocumentModel(url: url)
  1086. if (password != nil) {
  1087. let _ = model.unlock(password!)
  1088. }
  1089. windowController.documentModel = model
  1090. windowController.itemClick = { [weak self] (index: Int) in
  1091. if (self?.currentWindowController == nil) {
  1092. return
  1093. }
  1094. self?.view.window?.endSheet((self?.currentWindowController?.window)!)
  1095. self?.currentWindowController = nil
  1096. }
  1097. self.view.window?.beginSheet(windowController.window!)
  1098. self.currentWindowController = windowController
  1099. }
  1100. }
  1101. }
  1102. func fastTool_Watermark() { // 水印
  1103. KMBatchWindowController.openFile(nil, .Watermark)
  1104. }
  1105. func fastTool_Background() { // 背景
  1106. KMBatchWindowController.openFile(nil, .Background)
  1107. }
  1108. func fastTool_HeaderAndFooter() { // 页眉页脚
  1109. KMBatchWindowController.openFile(nil, .HeaderAndFooter)
  1110. }
  1111. func fastTool_BatesCode() { // 贝茨码
  1112. KMBatchWindowController.openFile(nil, .BatesCode)
  1113. }
  1114. func fastTool_Print() { // 打印
  1115. KMPrintWindowController.openFiles(window: self.view.window!)
  1116. }
  1117. func fastTool_BatchRemove() { // 批量移除
  1118. KMBatchWindowController.openFile(nil, .BatchRemove)
  1119. }
  1120. func fastTool_Insert() { // 插入
  1121. let openPanel = NSOpenPanel()
  1122. openPanel.prompt = "插入"
  1123. openPanel.allowsMultipleSelection = false
  1124. openPanel.allowedFileTypes = ["pdf"]
  1125. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1126. if result == .OK {
  1127. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1128. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Insert)
  1129. insertWindowController.beginSheetModal(for: self.view.window!) { pdfDocument, password, pages, indexPage in
  1130. self.insertPageAction(pdfDocument, password, pages, indexPage)
  1131. }
  1132. }
  1133. }
  1134. }
  1135. }
  1136. func fastTool_BreakUp() { // 拆分
  1137. let openPanel = NSOpenPanel()
  1138. openPanel.prompt = "提取"
  1139. openPanel.allowsMultipleSelection = false
  1140. openPanel.allowedFileTypes = ["pdf"]
  1141. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1142. if result == .OK {
  1143. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1144. let document = CPDFDocument(url: openPanel.url)
  1145. let model = KMPageEditSplitSettingModel()
  1146. model.documentURL = openPanel.url
  1147. model.fileName = model.documentURL.lastPathComponent
  1148. model.pathExtension = model.fileName.components(separatedBy: ".").last
  1149. let windowController = KMPageEditSplitWindowController(model)
  1150. windowController.hasPreView = true
  1151. self.view.window?.beginSheet(windowController.window!)
  1152. self.currentWindowController = windowController
  1153. windowController.itemClick = { [weak self] index, value in
  1154. if (index == 1) { /// 取消
  1155. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1156. self?.currentWindowController = nil
  1157. return
  1158. }
  1159. /// 拆分
  1160. let windowController_split: KMPageEditSplitWindowController = self?.currentWindowController as! KMPageEditSplitWindowController
  1161. let outputModel: KMPageEditSplitSettingModel = windowController_split.model! as! KMPageEditSplitSettingModel
  1162. self?.view.window?.endSheet((self?.currentWindowController!.window)!)
  1163. self?.currentWindowController = nil
  1164. let panel = NSOpenPanel()
  1165. panel.canChooseFiles = false
  1166. panel.canChooseDirectories = true
  1167. panel.canCreateDirectories = true
  1168. panel.beginSheetModal(for: (self?.view.window)!) { response in
  1169. KMPageEditTools.split(document!, outputModel, panel.url!.path, outputModel.outputFileNameDeletePathExtension) { result, outputDocuments, error in
  1170. if (result) {
  1171. }
  1172. }
  1173. }
  1174. }
  1175. }
  1176. }
  1177. }
  1178. }
  1179. func fastTool_Extract() { // 提取
  1180. let openPanel = NSOpenPanel()
  1181. openPanel.prompt = "提取"
  1182. openPanel.allowsMultipleSelection = false
  1183. openPanel.allowedFileTypes = ["pdf"]
  1184. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1185. if result == .OK {
  1186. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1187. let insertWindowController: KMPDFInsertPageWindow = KMPDFInsertPageWindow.init(documentPath: openPanel.url!, toolType: .Extract)
  1188. insertWindowController.beginSheetExtractModal(for: self.view.window!) { pdfDocument, pages, oneDocumentPerPage, isDeletePage in
  1189. self.extractPageAction(pdfDocument, pages, oneDocumentPerPage, isDeletePage)
  1190. }
  1191. }
  1192. }
  1193. }
  1194. }
  1195. func fastTool_MarkCipher() { // 标记密文
  1196. let openPanel = NSOpenPanel()
  1197. openPanel.allowsMultipleSelection = false
  1198. openPanel.allowedFileTypes = ["pdf"]
  1199. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1200. if result == .cancel {
  1201. return
  1202. }
  1203. if !openPanel.url!.path.isPDFValid() {
  1204. let alert = NSAlert()
  1205. alert.alertStyle = .critical
  1206. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1207. alert.runModal()
  1208. return
  1209. }
  1210. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1211. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1212. if (error != nil) {
  1213. NSApp.presentError(error!)
  1214. return
  1215. }
  1216. let toolbar = (document as! KMMainDocument).mainViewController?.toolbarController
  1217. toolbar?.enterRedact()
  1218. }
  1219. }
  1220. }
  1221. }
  1222. func fastTool_AutomaticFormRecognition() { // 表单自动识别
  1223. let openPanel = NSOpenPanel()
  1224. openPanel.prompt = "表单自动识别"
  1225. openPanel.allowsMultipleSelection = false
  1226. openPanel.allowedFileTypes = ["pdf"]
  1227. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1228. if result == .OK {
  1229. }
  1230. }
  1231. }
  1232. func fastTool_PageEdit() { // 页面编辑
  1233. let openPanel = NSOpenPanel()
  1234. openPanel.allowsMultipleSelection = false
  1235. openPanel.allowedFileTypes = ["pdf"]
  1236. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  1237. if result == .cancel {
  1238. return
  1239. }
  1240. if !openPanel.url!.path.isPDFValid() {
  1241. let alert = NSAlert()
  1242. alert.alertStyle = .critical
  1243. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1244. alert.runModal()
  1245. return
  1246. }
  1247. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  1248. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { document, result, error in
  1249. if (error != nil) {
  1250. NSApp.presentError(error!)
  1251. return
  1252. }
  1253. let mainView = (document as! KMMainDocument).mainViewController
  1254. mainView?.enterPageEdit()
  1255. }
  1256. }
  1257. }
  1258. }
  1259. // MARK: MenuItem Action & PopoverItem Action
  1260. func popoverItemAction(_ count: String) {
  1261. if count == NSLocalizedString("New Blank Page", comment: "") {
  1262. openBlankPage("")
  1263. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  1264. importFromWebPage("")
  1265. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  1266. importFromScanner("")
  1267. }
  1268. }
  1269. @IBAction func escButtonAction(_ sender: Any) {
  1270. self.historyFileViewController.selectFiles.removeAll()
  1271. if self.historyFileViewController.showMode == .Thumbnail {
  1272. self.historyFileViewController.historyFileCollectionView.reloadData()
  1273. } else {
  1274. self.historyFileViewController.historyFileTableView.reloadData()
  1275. }
  1276. }
  1277. @IBAction func importFromFile(_ sender: Any) {
  1278. self.openSupportPDFButtonAction()
  1279. }
  1280. @IBAction func openBlankPage(_ sender: Any) {
  1281. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  1282. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath())
  1283. let pdfDocument = CPDFDocument()
  1284. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  1285. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  1286. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  1287. if error != nil {
  1288. NSApp.presentError(error!)
  1289. } else {
  1290. if document is KMMainDocument {
  1291. let newDocument = document
  1292. (newDocument as! KMMainDocument).isNewCreated = true
  1293. }
  1294. }
  1295. }
  1296. }
  1297. @IBAction func importFromWebPage(_ sender: Any) {
  1298. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  1299. self.urlToPDFWindowController!.beginSheetModal(for: NSApp.mainWindow!) { filePath in
  1300. if filePath != nil && FileManager.default.fileExists(atPath: filePath) {
  1301. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  1302. if error != nil {
  1303. NSApp.presentError(error!)
  1304. } else {
  1305. if document is KMMainDocument {
  1306. (document as! KMMainDocument).isNewCreated = true
  1307. }
  1308. }
  1309. }
  1310. }
  1311. }
  1312. }
  1313. @IBAction func importFromScanner(_ sender: Any) {
  1314. deviceBrowserWC = KMDeviceBrowserWindowController.init(windowNibName: "KMDeviceBrowserWindowController")
  1315. deviceBrowserWC!.type = .scanner
  1316. deviceBrowserWC!.importScannerFileCallback = { [unowned self](url: NSURL) -> Void in
  1317. openFile(withFilePath: url as URL)
  1318. }
  1319. deviceBrowserWC!.showWindow(NSApp.mainWindow)
  1320. }
  1321. @IBAction func menuItemClick_mergePDF(_ sender: Any) {
  1322. fastTool_MergePDF()
  1323. }
  1324. @IBAction func menuItemClick_Compress(_ sender: Any) {
  1325. fastTool_Compression()
  1326. }
  1327. @IBAction func menuItemClick_Convert(_ sender: Any) {
  1328. fastTool_ConvertPDF()
  1329. }
  1330. @IBAction func menuItemClick_SettingPassword(_ sender: Any) {
  1331. fastTool_Security()
  1332. }
  1333. @IBAction func menuItemClick_RemovePassword(_ sender: Any) {
  1334. fastTool_Security()
  1335. }
  1336. func fetchUniquePath(_ originalPath: String) -> String {
  1337. var path = originalPath
  1338. let dManager = FileManager.default
  1339. if !dManager.fileExists(atPath: path) {
  1340. if path.extension.count < 1 {
  1341. path = path.stringByAppendingPathExtension("pdf")
  1342. }
  1343. return path
  1344. } else {
  1345. let originalFullFileName = path.lastPathComponent
  1346. let originalFileName = path.lastPathComponent.deletingPathExtension.lastPathComponent
  1347. let originalExtension = path.extension
  1348. let startIndex: Int = 0
  1349. let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
  1350. let fileLocatePath = originalPath.substring(to: endIndex)
  1351. var i = 1
  1352. while (1 != 0) {
  1353. var newName = String(format: "%@%ld", originalFileName, i)
  1354. newName = String(format: "%@%@", newName, originalExtension)
  1355. let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
  1356. if !dManager.fileExists(atPath: newPath) {
  1357. return newPath
  1358. } else {
  1359. i+=1
  1360. continue
  1361. }
  1362. }
  1363. }
  1364. }
  1365. // func kNewDocumentTempSavePath(_ fileName: String) -> String {
  1366. // let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  1367. //// let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1368. // let append2 = searchPath!.stringByAppendingPathComponent(String(format: "%@", fileName))
  1369. // return append2
  1370. // }
  1371. // MARK: Notification
  1372. @objc func homeFileRectChange(_ notification: Notification) -> Void {
  1373. let window = notification.object
  1374. self.historyFileViewController.reloadData()
  1375. }
  1376. }
  1377. // MARK: window Menu
  1378. extension KMHomeViewController {
  1379. @IBAction func menuItemAction_showForwardTagPage(_ sender: Any) {
  1380. (self.myDocument as! KMMainDocument).browser.selectPreviousTab()
  1381. }
  1382. @IBAction func menuItemAction_showNextTagPage(_ sender: Any) {
  1383. (self.myDocument as! KMMainDocument).browser.selectNextTab()
  1384. }
  1385. @IBAction func menuItemAction_newTagPageToNewWindow(_ sender: Any) {
  1386. let browser = (self.myDocument as! KMMainDocument).browser
  1387. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.openNewWindow(sender)
  1388. }
  1389. @IBAction func menuItemAction_mergeAllWindow(_ sender: Any) {
  1390. let browser = (self.myDocument as! KMMainDocument).browser
  1391. ((browser as! KMBrowser).windowController as? KMBrowserWindowController)?.mergeAllWindow(sender)
  1392. }
  1393. @IBAction func menuItemAction_currentWindowName(_ sender: Any) {
  1394. }
  1395. }
  1396. // MARK: file Menu
  1397. extension KMHomeViewController {
  1398. @IBAction func menuItemAction_closeWindow(_ sender: Any) {
  1399. self.view.window?.close()
  1400. }
  1401. @IBAction func menuItemAction_closeAllWindows(_ sender: Any) {
  1402. for window in NSApp.windows {
  1403. window.close()
  1404. }
  1405. }
  1406. @IBAction func menuItemAction_ConvertToWord(_ sender: Any) {
  1407. self.fastTool_PDFToWord()
  1408. }
  1409. @IBAction func menuItemAction_ConvertToExcel(_ sender: Any) {
  1410. self.fastTool_PDFToExcel()
  1411. }
  1412. @IBAction func menuItemAction_ConvertToPPT(_ sender: Any) {
  1413. self.fastTool_PDFToPPT()
  1414. }
  1415. @IBAction func menuItemAction_ConvertToRTF(_ sender: Any) {
  1416. self.showConvertWindow(type: .rtf)
  1417. }
  1418. @IBAction func menuItemAction_ConvertToHTML(_ sender: Any) {
  1419. self.showConvertWindow(type: .html)
  1420. }
  1421. @IBAction func menuItemAction_ConvertToText(_ sender: Any) {
  1422. self.showConvertWindow(type: .text)
  1423. }
  1424. @IBAction func menuItemAction_ConvertToCSV(_ sender: Any) {
  1425. self.showConvertWindow(type: .csv)
  1426. }
  1427. @IBAction func menuItemAction_ConvertToImage(_ sender: Any) {
  1428. self.fastTool_PDFToImage()
  1429. }
  1430. }
  1431. // MARK: help Menu
  1432. extension KMHomeViewController {
  1433. // @IBAction func menuItemAction_search(_ sender: Any) {
  1434. //
  1435. // }
  1436. }