KMAITranslationVC.swift 19 KB

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