KMAITranslationVC.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. //
  2. // KMAITranslationVC.swift
  3. // PDF Master
  4. //
  5. // Created by wanjun on 2023/5/22.
  6. //
  7. import Cocoa
  8. class KMAITranslationVC: NSViewController {
  9. @IBOutlet weak var aiTranslationLabel: NSTextField!
  10. @IBOutlet weak var aiTranslationView: KMDottedLineView!
  11. @IBOutlet weak var supportPDFWordFileImageView: NSImageView!
  12. @IBOutlet weak var supportPDFWordFileLabel: NSTextField!
  13. @IBOutlet weak var supportPDFWordFileSubLabel: NSTextField!
  14. @IBOutlet weak var translationLanguageLabel: NSTextField!
  15. @IBOutlet weak var automaticBox: KMBox!
  16. @IBOutlet weak var automaticLabel: NSTextField!
  17. @IBOutlet weak var languageBox: KMBox!
  18. @IBOutlet weak var languageLabel: NSTextField!
  19. @IBOutlet weak var languageImageView: NSImageView!
  20. @IBOutlet weak var selectYourFilesBox: KMBox!
  21. @IBOutlet weak var selectYourFilesLabel: NSTextField!
  22. @IBOutlet weak var selectYourFilesImageView: NSImageView!
  23. @IBOutlet weak var orDropFileHereLabel: NSTextField!
  24. @IBOutlet weak var errorView: NSView!
  25. @IBOutlet weak var errorLabel: NSTextField!
  26. var fromStr: String = "auto"
  27. var toStr: String = "en"
  28. var fromLanguages: [String] = ["Automatic", "English", "Simplified Chinese", "Traditional Chinese", "Japanese", "Korean", "French", "Spanish", "Italian", "German", "Portuguese", "Russian", "Vietnamese", "Thai", "Arabic", "Greek", "Bulgarian", "Finnish", "Slovene", "Dutch", "Czech", "Swedish", "Polish", "Danish", "Romanian", "Hungarian"]
  29. var toLanguages: [String] = ["English", "Simplified Chinese", "Traditional Chinese", "Japanese", "Korean", "French", "Spanish", "Italian", "German", "Portuguese", "Russian", "Vietnamese", "Thai", "Arabic", "Greek", "Bulgarian", "Finnish", "Slovene", "Dutch", "Czech", "Swedish", "Polish", "Danish", "Romanian", "Hungarian"]
  30. var popover: NSPopover?
  31. var progressController: SKProgressController?
  32. var timer: Timer?
  33. var timerCounter = 0.0
  34. override func viewDidLoad() {
  35. super.viewDidLoad()
  36. // Do view setup here.
  37. self.initLocalization()
  38. self.initializeUI()
  39. }
  40. override func viewDidAppear() {
  41. super.viewDidAppear()
  42. self.errorView.isHidden = true
  43. self.initLocalization()
  44. }
  45. // MARK: initialize
  46. func initializeUI() -> Void {
  47. self.aiTranslationView.canHover = false
  48. self.aiTranslationLabel.textColor = NSColor(hex: "#252629")
  49. self.aiTranslationLabel.font = NSFont.SFProTextSemibold(20.0)
  50. self.supportPDFWordFileImageView.image = NSImage(named: "ic_function_other")
  51. self.supportPDFWordFileLabel.textColor = NSColor(hex: "#252629")
  52. self.supportPDFWordFileLabel.font = NSFont.SFProTextSemibold(20.0)
  53. self.supportPDFWordFileSubLabel.textColor = NSColor(hex: "#94989C")
  54. self.supportPDFWordFileSubLabel.font = NSFont.SFProTextRegular(14.0)
  55. self.translationLanguageLabel.textColor = NSColor(hex: "#252629")
  56. self.translationLanguageLabel.font = NSFont.SFProTextRegular(14.0)
  57. self.automaticLabel.textColor = NSColor(hex: "#252629")
  58. self.automaticLabel.font = NSFont.SFProTextRegular(16.0)
  59. self.languageLabel.textColor = NSColor(hex: "#252629")
  60. self.languageLabel.font = NSFont.SFProTextRegular(16.0)
  61. self.automaticBox.cornerRadius = 4.0
  62. self.automaticBox.borderColor = NSColor(hex: "#DFE1E5")
  63. self.languageBox.cornerRadius = 4.0
  64. self.languageBox.borderColor = NSColor(hex: "#DFE1E5")
  65. self.languageImageView.image = NSImage(named: "ic_transtate")
  66. self.automaticBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  67. if downEntered {
  68. self.languageAction(true)
  69. }
  70. }
  71. self.languageBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  72. if downEntered {
  73. self.languageAction(false)
  74. }
  75. }
  76. self.selectYourFilesBox.cornerRadius = 4.0
  77. self.selectYourFilesBox.fillColor = NSColor(hex: "#1770F4")
  78. self.selectYourFilesLabel.textColor = NSColor(hex: "#FFFFFF")
  79. self.selectYourFilesLabel.font = NSFont.SFProTextRegular(16.0)
  80. self.selectYourFilesImageView.image = NSImage(named: "icon_SelectYourFiles")
  81. self.orDropFileHereLabel.textColor = NSColor(hex: "#616469")
  82. self.orDropFileHereLabel.font = NSFont.SFProTextRegular(14.0)
  83. self.selectYourFilesBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  84. if mouseEntered {
  85. self.selectYourFilesBox.fillColor = NSColor(hex: "#3F8FF6")
  86. } else {
  87. self.selectYourFilesBox.fillColor = NSColor(hex: "#1770F4")
  88. }
  89. }
  90. self.selectYourFilesBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  91. if downEntered {
  92. if !KMLightMemberManager.manager.isLogin() {
  93. KMLoginWindowController.show(window: NSApp.mainWindow!)
  94. return
  95. }
  96. self.errorView.isHidden = true
  97. let openPanel = NSOpenPanel()
  98. openPanel.allowedFileTypes = ["pdf", "PDF", "docx", "doc"]
  99. openPanel.allowsMultipleSelection = false
  100. openPanel.beginSheetModal(for: self.view.window!) { result in
  101. if result == .OK {
  102. for url in openPanel.urls {
  103. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: url.path)
  104. if (url.pathExtension == "pdf") || url.pathExtension == "PDF" {
  105. if !url.path.isPDFValid() {
  106. let alert = NSAlert()
  107. alert.alertStyle = .critical
  108. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  109. alert.runModal()
  110. return
  111. }
  112. }
  113. if self.isFileGreaterThan10MB(atPath: url.path) {
  114. self.errorView.isHidden = false
  115. self.errorLabel.stringValue = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  116. } else if isExceedsLimit {
  117. self.errorView.isHidden = false
  118. self.errorLabel.stringValue = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  119. } else {
  120. DispatchQueue.main.async {
  121. self.showProgressWindow()
  122. self.progressController?.maxValue = Double(100)
  123. }
  124. timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerTick), userInfo: nil, repeats: true)
  125. let infoDictionary = Bundle .main.infoDictionary!
  126. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  127. let languages = [self.automaticLabel.stringValue, self.languageLabel.stringValue]
  128. UserDefaults.standard.set(languages, forKey: "KMAITranslationLanguageArrayKey")
  129. UserDefaults.standard.synchronize()
  130. KMRequestServerManager.manager.aiTranslationFileUpload(file: url.path, version: majorVersion as! String) { [unowned self] success, result in
  131. // self.hiddenProgressWindow()
  132. if success {
  133. let result: NSDictionary = result!.result
  134. let fileKey = result["fileKey"]
  135. let fileName = result["fileName"]
  136. let pageCount = result["pageCount"]
  137. if fileKey != nil {
  138. self.fileTranslateHandle(fileKey as! String)
  139. }
  140. } else {
  141. let result: String = result!.message
  142. DispatchQueue.main.async {
  143. self.hiddenProgressWindow()
  144. self.errorView.isHidden = false
  145. self.errorLabel.stringValue = result
  146. }
  147. }
  148. }
  149. }
  150. }
  151. }
  152. }
  153. }
  154. }
  155. self.errorView.isHidden = true
  156. self.errorView.wantsLayer = true
  157. self.errorView.layer?.backgroundColor = NSColor(hex: "##36383B").cgColor
  158. self.errorView.layer?.cornerRadius = 4.0
  159. self.errorLabel.textColor = NSColor(hex: "#FFFFFF")
  160. self.errorLabel.font = NSFont.SFProTextRegular(14.0)
  161. }
  162. func initLocalization() -> Void {
  163. self.aiTranslationLabel.stringValue = NSLocalizedString("AI Translation", comment: "")
  164. self.supportPDFWordFileLabel.stringValue = NSLocalizedString("Support PDF and Word file", comment: "")
  165. self.supportPDFWordFileSubLabel.stringValue = NSLocalizedString("Limit document size to 10M, document page number to 30, 10w characters per month.", comment: "")
  166. self.translationLanguageLabel.stringValue = NSLocalizedString("Translation Language:", comment: "")
  167. self.selectYourFilesLabel.stringValue = NSLocalizedString("Select your file", comment: "")
  168. self.orDropFileHereLabel.stringValue = NSLocalizedString("or drop file here", comment: "")
  169. let languageArr = UserDefaults.standard.array(forKey: "KMAITranslationLanguageArrayKey") as? [String] ?? []
  170. if (languageArr.count > 0) {
  171. self.automaticLabel.stringValue = languageArr[0]
  172. self.languageLabel.stringValue = languageArr[1]
  173. } else {
  174. self.automaticLabel.stringValue = NSLocalizedString("Automatic", comment: "")
  175. self.languageLabel.stringValue = NSLocalizedString("English", comment: "")
  176. let languages = [NSLocalizedString("Automatic", comment: ""), NSLocalizedString("English", comment: "")]
  177. UserDefaults.standard.set(languages, forKey: "KMAITranslationLanguageArrayKey")
  178. UserDefaults.standard.synchronize()
  179. }
  180. }
  181. // MARK: Private Methods
  182. func fileTranslateHandle(_ fileKey: String) -> Void {
  183. let infoDictionary = Bundle .main.infoDictionary!
  184. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  185. // DispatchQueue.main.async {
  186. // self.showProgressWindow()
  187. // }
  188. KMRequestServerManager.manager.aiTranslationFileTranslateHandle(fileKey: fileKey, from: self.fromStr, to: self.toStr, version: majorVersion as! String) { success, result in
  189. if success {
  190. let result: NSDictionary = result!.result
  191. let fileUrl: String = result["fileUrl"] as! String
  192. let downFileUrl: String = result["downFileUrl"] as! String
  193. let ossDownUrl: String = result["ossDownUrl"] as! String
  194. let fileName: String = result["fileName"] as! String
  195. let downFileName: String = result["downFileName"] as! String
  196. let from: String = result["from"] as! String
  197. let to: String = result["to"] as! String
  198. self.downloadFile(filePath: ossDownUrl, downFileName: downFileName)
  199. } else {
  200. let result: String = result!.message
  201. DispatchQueue.main.async {
  202. self.hiddenProgressWindow()
  203. self.errorView.isHidden = false
  204. self.errorLabel.stringValue = result
  205. }
  206. }
  207. }
  208. }
  209. func downloadFile(filePath: String, downFileName: String) -> Void {
  210. guard let fileURL = URL(string: filePath) else {
  211. let alert = NSAlert()
  212. alert.alertStyle = .critical
  213. alert.messageText = NSLocalizedString("Invalid file link", comment: "")
  214. alert.runModal()
  215. return
  216. }
  217. let destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent(downFileName)
  218. if FileManager.default.fileExists(atPath: destinationURL.path) {
  219. do {
  220. try FileManager.default.removeItem(at: destinationURL)
  221. print("删除旧文件成功")
  222. } catch {
  223. print("删除旧文件失败:\(error)")
  224. }
  225. }
  226. let sessionConfiguration = URLSessionConfiguration.default
  227. let session = URLSession(configuration: sessionConfiguration)
  228. let downloadTask = session.downloadTask(with: fileURL) { (tempLocalURL, response, error) in
  229. if let error = error {
  230. let alert = NSAlert()
  231. alert.alertStyle = .critical
  232. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Download failed", comment: ""))
  233. alert.runModal()
  234. return
  235. }
  236. guard let tempLocalURL = tempLocalURL else {
  237. let alert = NSAlert()
  238. alert.alertStyle = .critical
  239. alert.messageText = NSLocalizedString("Invalid temporary directory", comment: "")
  240. alert.runModal()
  241. return
  242. }
  243. DispatchQueue.main.async {
  244. self.hiddenProgressWindow()
  245. }
  246. do {
  247. try FileManager.default.moveItem(at: tempLocalURL, to: destinationURL)
  248. NSDocumentController.shared.openDocument(withContentsOf: destinationURL, display: true) { document, documentWasAlreadyOpen, error in
  249. if error != nil {
  250. NSApp.presentError(error!)
  251. } else {
  252. }
  253. }
  254. } catch {
  255. let alert = NSAlert()
  256. alert.alertStyle = .critical
  257. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Failed to save file", comment: ""))
  258. alert.runModal()
  259. }
  260. }
  261. downloadTask.resume()
  262. }
  263. func languageAbbreviation(_ language: String) -> String {
  264. if language == "Automatic Identification" {
  265. return "auto"
  266. } else if language == "English" {
  267. return "en"
  268. } else if language == "Simplified Chinese" {
  269. return "zh"
  270. } else if language == "Traditional Chinese" {
  271. return "cht"
  272. } else if language == "Japanese" {
  273. return "jp"
  274. } else if language == "Korean" {
  275. return "kor"
  276. } else if language == "French" {
  277. return "fra"
  278. } else if language == "Spanish" {
  279. return "spa"
  280. } else if language == "Italian" {
  281. return "it"
  282. } else if language == "German" {
  283. return "de"
  284. } else if language == "Portuguese" {
  285. return "pt"
  286. } else if language == "Russian" {
  287. return "ru"
  288. } else if language == "Vietnamese" {
  289. return "vie"
  290. } else if language == "Thai" {
  291. return "th"
  292. } else if language == "Arabic" {
  293. return "ara"
  294. } else if language == "Greek" {
  295. return "el"
  296. } else if language == "Bulgarian" {
  297. return "bul"
  298. } else if language == "Finnish" {
  299. return "fin"
  300. } else if language == "Slovene" {
  301. return "slo"
  302. } else if language == "Dutch" {
  303. return "nl"
  304. } else if language == "Czech" {
  305. return "cs"
  306. } else if language == "Swedish" {
  307. return "swe"
  308. } else if language == "Polish" {
  309. return "pl"
  310. } else if language == "Danish" {
  311. return "dan"
  312. } else if language == "Romanian" {
  313. return "rom"
  314. } else if language == "Hungarian" {
  315. return "hu"
  316. }
  317. return "auto"
  318. }
  319. func showProgressWindow() {
  320. let progress = SKProgressController()
  321. progress.message = NSLocalizedString("Translating...", comment: "")
  322. progress.window?.backgroundColor = NSColor(hex: "#36383B")
  323. progress.window?.contentView?.wantsLayer = true
  324. progress.window?.contentView?.layer?.backgroundColor = NSColor(hex: "#36383B").cgColor
  325. progress.progressField.textColor = NSColor.white
  326. progress.closeBlock = { [unowned self] in
  327. }
  328. self.progressController = progress
  329. self.view.window?.beginSheet(progress.window!)
  330. }
  331. func hiddenProgressWindow() {
  332. DispatchQueue.main.async {
  333. self.progressController?.doubleValue = 100.0
  334. }
  335. self.stopTimer()
  336. if (self.progressController != nil) {
  337. self.view.window?.endSheet((self.progressController?.window)!)
  338. self.progressController = nil
  339. }
  340. }
  341. func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
  342. let fileManager = FileManager.default
  343. do {
  344. let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
  345. if let fileSize = fileAttributes[.size] as? UInt64 {
  346. let megabyteSize = fileSize / (1024 * 1024)
  347. return megabyteSize >= 10
  348. }
  349. } catch {
  350. print("Error: \(error)")
  351. }
  352. return false
  353. }
  354. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  355. let url = URL(fileURLWithPath: filePath)
  356. guard let document = PDFDocument(url: url) else {
  357. return false
  358. }
  359. let pageCount = document.pageCount
  360. return pageCount > 30
  361. }
  362. @objc func timerTick() {
  363. timerCounter += 1.0
  364. self.progressController?.increment(by: 1.0)
  365. if timerCounter >= 95 {
  366. stopTimer()
  367. }
  368. }
  369. func stopTimer() {
  370. timer?.invalidate()
  371. timer = nil
  372. }
  373. // MARK: Action Methods
  374. func languageAction(_ isFromLanguage: Bool) -> Void {
  375. if (self.popover != nil && self.popover!.isShown) {
  376. self.popover?.close()
  377. self.popover = nil
  378. return
  379. }
  380. var languages = self.fromLanguages
  381. if !isFromLanguage {
  382. languages = self.toLanguages
  383. }
  384. let vc: KMAILanguagePopVC = KMAILanguagePopVC().initWithPopViewDataArr(languages)
  385. let createFilePopover: NSPopover = NSPopover.init()
  386. self.popover = createFilePopover
  387. createFilePopover.contentViewController = vc
  388. createFilePopover.animates = true
  389. createFilePopover.behavior = .semitransient
  390. createFilePopover.setValue(true, forKey: "shouldHideAnchor")
  391. if isFromLanguage {
  392. vc.selectString = self.automaticLabel.stringValue
  393. } else {
  394. vc.selectString = self.languageLabel.stringValue
  395. }
  396. vc.downCallback = { [unowned self] (language: String) -> Void in
  397. createFilePopover.close()
  398. if isFromLanguage {
  399. self.automaticLabel.stringValue = language
  400. self.fromStr = self.languageAbbreviation(language)
  401. } else {
  402. self.languageLabel.stringValue = language
  403. self.toStr = self.languageAbbreviation(language)
  404. }
  405. }
  406. if isFromLanguage {
  407. createFilePopover.show(relativeTo: CGRect(x: automaticBox.bounds.origin.x, y: 10, width: automaticBox.bounds.size.width, height: automaticBox.bounds.size.height), of: automaticBox, preferredEdge: .maxY)
  408. vc.customBoxWidthLayoutConstraint.constant = automaticBox.frame.width
  409. } else {
  410. createFilePopover.show(relativeTo: CGRect(x: languageBox.bounds.origin.x, y: 10, width: languageBox.bounds.size.width, height: languageBox.bounds.size.height), of: languageBox, preferredEdge: .maxY)
  411. vc.customBoxWidthLayoutConstraint.constant = languageBox.frame.width
  412. }
  413. }
  414. }