KMAITranslationConfirmWindowController.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. //
  2. // KMAITranslationConfirmWindowController.swift
  3. // PDF Master
  4. //
  5. // Created by wanjun on 2023/5/25.
  6. //
  7. import Cocoa
  8. class KMAITranslationConfirmWindowController: NSWindowController {
  9. @IBOutlet weak var label: NSTextField!
  10. @IBOutlet weak var subLabel: NSTextField!
  11. @IBOutlet weak var cancelBox: NSBox!
  12. @IBOutlet weak var cancelLabel: NSTextField!
  13. @IBOutlet weak var cancelButton: NSButton!
  14. @IBOutlet weak var translateBox: NSBox!
  15. @IBOutlet weak var translateLabel: NSTextField!
  16. @IBOutlet weak var translateButton: NSButton!
  17. @IBOutlet weak var fromBox: NSBox!
  18. @IBOutlet weak var fromLabel: NSTextField!
  19. @IBOutlet weak var toBox: NSBox!
  20. @IBOutlet weak var toLabel: NSTextField!
  21. @IBOutlet weak var languageImageView: NSImageView!
  22. @IBOutlet weak var tipsLabel1: NSTextField!
  23. @IBOutlet weak var tipsLabel2: NSTextField!
  24. @IBOutlet weak var prePDFView: KMCustomPDFView?
  25. var filePath: String = ""
  26. var progressController: SKProgressController?
  27. var fromStr: String = "auto"
  28. var toStr: String = "en"
  29. 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"]
  30. 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"]
  31. var popover: NSPopover?
  32. var saveFileUrl: URL = URL(fileURLWithPath: "")
  33. deinit {
  34. self.prePDFView?.removeFromSuperview()
  35. self.prePDFView = nil
  36. }
  37. override func windowDidLoad() {
  38. super.windowDidLoad()
  39. self.initLocalization()
  40. self.initializeUI()
  41. let document = CPDFDocument(url: URL(fileURLWithPath: self.filePath))
  42. self.prePDFView?.document = document!
  43. if (self.prePDFView?.documentView() != nil) {
  44. self.prePDFView?.documentView().enclosingScrollView?.hasVerticalScroller = false
  45. self.prePDFView?.documentView().enclosingScrollView?.hasHorizontalScroller = false
  46. }
  47. }
  48. func initializeUI() -> Void {
  49. self.label.textColor = NSColor(hex: "#252629")
  50. self.label.font = NSFont.SFProTextSemibold(16.0)
  51. self.subLabel.textColor = NSColor(hex: "##616469")
  52. self.subLabel.font = NSFont.SFProTextRegular(12.0)
  53. self.fromBox.fillColor = NSColor(hex: "#FFFFFF")
  54. self.fromBox.borderColor = NSColor(hex: "#DFE1E5")
  55. self.fromLabel.textColor = NSColor(hex: "#252629")
  56. self.fromLabel.font = NSFont.SFProTextRegular(14.0)
  57. self.toBox.fillColor = NSColor(hex: "#FFFFFF")
  58. self.toBox.borderColor = NSColor(hex: "#DFE1E5")
  59. self.toLabel.textColor = NSColor(hex: "#252629")
  60. self.toLabel.font = NSFont.SFProTextRegular(14.0)
  61. self.languageImageView.image = NSImage(named: "ic_transtate")
  62. self.tipsLabel1.textColor = NSColor(hex: "#94989C")
  63. self.tipsLabel1.font = NSFont.SFProTextRegular(12.0)
  64. self.tipsLabel2.textColor = NSColor(hex: "#94989C")
  65. self.tipsLabel2.font = NSFont.SFProTextRegular(12.0)
  66. self.cancelBox.fillColor = NSColor(hex: "#F5F5F5")
  67. self.cancelBox.cornerRadius = 5.0
  68. self.cancelBox.borderWidth = 0.0
  69. self.cancelLabel.textColor = NSColor(hex: "#4D4D4D")
  70. self.cancelLabel.font = NSFont.SFProTextRegular(13.0)
  71. self.translateBox.fillColor = NSColor(hex: "#4B91F7")
  72. self.translateBox.cornerRadius = 5.0
  73. self.translateBox.borderWidth = 0.0
  74. self.translateLabel.textColor = NSColor(hex: "#FFFFFF")
  75. self.translateLabel.font = NSFont.SFProTextRegular(13.0)
  76. self.prePDFView?.backgroundColor = NSColor(hex: "#F7F8FA")
  77. }
  78. func initLocalization() -> Void {
  79. self.label.stringValue = NSLocalizedString("AI Translation", comment: "")
  80. self.subLabel.stringValue = NSLocalizedString("Translation Language", comment: "")
  81. self.cancelLabel.stringValue = NSLocalizedString("Cancel", comment: "")
  82. self.translateLabel.stringValue = NSLocalizedString("Translate", comment: "")
  83. self.fromLabel.stringValue = "Automatic"
  84. self.toLabel.stringValue = "English"
  85. self.tipsLabel1.stringValue = NSLocalizedString("Scanned PDF files are not supported", comment: "")
  86. self.tipsLabel2.stringValue = NSLocalizedString("Limit document size to 10M, document page number to 30, 10w characters per month.", comment: "")
  87. }
  88. override func mouseDown(with event: NSEvent) {
  89. if self.popover != nil {
  90. self.popover?.close()
  91. self.popover = nil
  92. }
  93. }
  94. // MARK: Private Methods
  95. // MARK: Action Methods
  96. @IBAction func translateAction(_ sender: NSButton) {
  97. if !KMLightMemberManager.manager.isLogin() {
  98. KMLoginWindowController.show(window: NSApp.mainWindow!)
  99. return
  100. }
  101. let filePathUrl = URL(fileURLWithPath: self.filePath)
  102. let fileNameWithoutExtension = filePathUrl.deletingPathExtension().lastPathComponent
  103. let newFileName = fileNameWithoutExtension + "_aiTranslation"
  104. let outputSavePanel = NSSavePanel()
  105. outputSavePanel.title = NSLocalizedString("Translate", comment: "")
  106. outputSavePanel.allowedFileTypes = ["pdf"]
  107. outputSavePanel.nameFieldStringValue = newFileName
  108. outputSavePanel.directoryURL = filePathUrl.deletingLastPathComponent()
  109. let result = outputSavePanel.runModal()
  110. if result == .OK {
  111. self.saveFileUrl = outputSavePanel.url!
  112. DispatchQueue.main.async {
  113. self.showProgressWindow()
  114. }
  115. let infoDictionary = Bundle .main.infoDictionary!
  116. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  117. KMRequestServerManager.manager.aiTranslationFileUpload(file: self.filePath, version: "1.0.1") { [unowned self] success, result in
  118. if success {
  119. let result: NSDictionary = result!.result
  120. let fileKey = result["fileKey"]
  121. let fileName = result["fileName"]
  122. let pageCount = result["pageCount"]
  123. if fileKey != nil {
  124. self.fileTranslateHandle(fileKey as! String)
  125. }
  126. } else {
  127. let result: String = result!.message
  128. DispatchQueue.main.async {
  129. self.hiddenProgressWindow()
  130. let alert = NSAlert()
  131. alert.alertStyle = .critical
  132. alert.messageText = result
  133. alert.runModal()
  134. }
  135. }
  136. }
  137. } else {
  138. outputSavePanel.close()
  139. }
  140. }
  141. @IBAction func cancelAction(_ sender: NSButton) {
  142. NSApp.mainWindow!.endSheet(self.window!)
  143. self.window?.orderOut(self)
  144. }
  145. @IBAction func fromLanguageAction(_ sender: NSButton) {
  146. self.languageAction(true)
  147. }
  148. @IBAction func toLanguageAction(_ sender: NSButton) {
  149. self.languageAction(false)
  150. }
  151. func languageAction(_ isFromLanguage: Bool) -> Void {
  152. if (self.popover != nil && self.popover!.isShown) {
  153. self.popover?.close()
  154. self.popover = nil
  155. return
  156. }
  157. var languages = self.fromLanguages
  158. if !isFromLanguage {
  159. languages = self.toLanguages
  160. }
  161. let vc: KMAILanguagePopVC = KMAILanguagePopVC().initWithPopViewDataArr(languages)
  162. let createFilePopover: NSPopover = NSPopover.init()
  163. self.popover = createFilePopover
  164. createFilePopover.contentViewController = vc
  165. createFilePopover.animates = true
  166. createFilePopover.behavior = .semitransient
  167. createFilePopover.setValue(true, forKey: "shouldHideAnchor")
  168. if isFromLanguage {
  169. vc.selectString = self.fromLabel.stringValue
  170. } else {
  171. vc.selectString = self.toLabel.stringValue
  172. }
  173. vc.downCallback = { [unowned self] (language: String) -> Void in
  174. createFilePopover.close()
  175. if isFromLanguage {
  176. self.fromLabel.stringValue = language
  177. self.fromStr = self.languageAbbreviation(language)
  178. } else {
  179. self.toLabel.stringValue = language
  180. self.toStr = self.languageAbbreviation(language)
  181. }
  182. }
  183. if isFromLanguage {
  184. createFilePopover.show(relativeTo: CGRect(x: fromBox.bounds.origin.x, y: 10, width: fromBox.bounds.size.width, height: fromBox.bounds.size.height), of: fromBox, preferredEdge: .maxY)
  185. vc.customBoxWidthLayoutConstraint.constant = fromBox.frame.width
  186. } else {
  187. createFilePopover.show(relativeTo: CGRect(x: toBox.bounds.origin.x, y: 10, width: toBox.bounds.size.width, height: toBox.bounds.size.height), of: toBox, preferredEdge: .maxY)
  188. vc.customBoxWidthLayoutConstraint.constant = toBox.frame.width
  189. }
  190. }
  191. // MARK: Private Methods
  192. func showProgressWindow() {
  193. let progress = SKProgressController()
  194. progress.message = NSLocalizedString("Translating...", comment: "")
  195. progress.window?.backgroundColor = NSColor(hex: "#36383B")
  196. progress.window?.contentView?.wantsLayer = true
  197. progress.window?.contentView?.layer?.backgroundColor = NSColor(hex: "#36383B").cgColor
  198. progress.progressField.textColor = NSColor.white
  199. progress.closeBlock = { [unowned self] in
  200. }
  201. self.progressController = progress
  202. self.window?.beginSheet(progress.window!)
  203. }
  204. func hiddenProgressWindow() {
  205. if (self.progressController != nil) {
  206. self.window?.endSheet((self.progressController?.window)!)
  207. self.progressController = nil
  208. }
  209. }
  210. func fileTranslateHandle(_ fileKey: String) -> Void {
  211. let infoDictionary = Bundle .main.infoDictionary!
  212. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  213. KMRequestServerManager.manager.aiTranslationFileTranslateHandle(fileKey: fileKey, from: self.fromStr, to: self.toStr, version: "1.0.1") { success, result in
  214. if success {
  215. let result: NSDictionary = result!.result
  216. let fileUrl: String = result["fileUrl"] as! String
  217. let downFileUrl: String = result["downFileUrl"] as! String
  218. let ossDownUrl: String = result["ossDownUrl"] as! String
  219. let fileName: String = result["fileName"] as! String
  220. let downFileName: String = result["downFileName"] as! String
  221. let from: String = result["from"] as! String
  222. let to: String = result["to"] as! String
  223. self.downloadFile(filePath: ossDownUrl, downFileName: downFileName)
  224. } else {
  225. let result: String = result!.message
  226. DispatchQueue.main.async {
  227. self.hiddenProgressWindow()
  228. let alert = NSAlert()
  229. alert.alertStyle = .critical
  230. alert.messageText = result
  231. alert.runModal()
  232. }
  233. }
  234. }
  235. }
  236. func downloadFile(filePath: String, downFileName: String) -> Void {
  237. guard let fileURL = URL(string: filePath) else {
  238. let alert = NSAlert()
  239. alert.alertStyle = .critical
  240. alert.messageText = NSLocalizedString("Invalid file link", comment: "")
  241. alert.runModal()
  242. return
  243. }
  244. // let filePathUrl = URL(fileURLWithPath: self.filePath)
  245. // let fileNameWithoutExtension = filePathUrl.deletingPathExtension().lastPathComponent
  246. // let fileExtension = filePathUrl.pathExtension
  247. // let newFileName = fileNameWithoutExtension + "_aiTranslation" + "." + fileExtension
  248. // let destinationURL = filePathUrl.deletingLastPathComponent().appendingPathComponent(newFileName)
  249. if FileManager.default.fileExists(atPath: self.saveFileUrl.path) {
  250. do {
  251. try FileManager.default.removeItem(at: self.saveFileUrl)
  252. print("删除旧文件成功")
  253. } catch {
  254. print("删除旧文件失败:\(error)")
  255. }
  256. }
  257. let sessionConfiguration = URLSessionConfiguration.default
  258. let session = URLSession(configuration: sessionConfiguration)
  259. let downloadTask = session.downloadTask(with: fileURL) { (tempLocalURL, response, error) in
  260. if let error = error {
  261. let alert = NSAlert()
  262. alert.alertStyle = .critical
  263. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Download failed", comment: ""))
  264. alert.runModal()
  265. return
  266. }
  267. guard let tempLocalURL = tempLocalURL else {
  268. let alert = NSAlert()
  269. alert.alertStyle = .critical
  270. alert.messageText = NSLocalizedString("Invalid temporary directory", comment: "")
  271. alert.runModal()
  272. return
  273. }
  274. DispatchQueue.main.async {
  275. self.hiddenProgressWindow()
  276. // NSApp.mainWindow!.endSheet(self.window!)
  277. self.window?.orderOut(self)
  278. }
  279. do {
  280. try FileManager.default.moveItem(at: tempLocalURL, to: self.saveFileUrl)
  281. NSDocumentController.shared.openDocument(withContentsOf: self.saveFileUrl, display: true) { document, documentWasAlreadyOpen, error in
  282. if error != nil {
  283. NSApp.presentError(error!)
  284. } else {
  285. }
  286. }
  287. } catch {
  288. let alert = NSAlert()
  289. alert.alertStyle = .critical
  290. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Failed to save file", comment: ""))
  291. alert.runModal()
  292. }
  293. }
  294. downloadTask.resume()
  295. }
  296. func languageAbbreviation(_ language: String) -> String {
  297. if language == "Automatic" {
  298. return "auto"
  299. } else if language == "English" {
  300. return "en"
  301. } else if language == "Simplified Chinese" {
  302. return "zh"
  303. } else if language == "Traditional Chinese" {
  304. return "cht"
  305. } else if language == "Japanese" {
  306. return "jp"
  307. } else if language == "Korean" {
  308. return "kor"
  309. } else if language == "French" {
  310. return "fra"
  311. } else if language == "Spanish" {
  312. return "spa"
  313. } else if language == "Italian" {
  314. return "it"
  315. } else if language == "German" {
  316. return "de"
  317. } else if language == "Portuguese" {
  318. return "pt"
  319. } else if language == "Russian" {
  320. return "ru"
  321. } else if language == "Vietnamese" {
  322. return "vie"
  323. } else if language == "Thai" {
  324. return "th"
  325. } else if language == "Arabic" {
  326. return "ara"
  327. } else if language == "Greek" {
  328. return "el"
  329. } else if language == "Bulgarian" {
  330. return "bul"
  331. } else if language == "Finnish" {
  332. return "fin"
  333. } else if language == "Slovene" {
  334. return "slo"
  335. } else if language == "Dutch" {
  336. return "nl"
  337. } else if language == "Czech" {
  338. return "cs"
  339. } else if language == "Swedish" {
  340. return "swe"
  341. } else if language == "Polish" {
  342. return "pl"
  343. } else if language == "Danish" {
  344. return "dan"
  345. } else if language == "Romanian" {
  346. return "rom"
  347. } else if language == "Hungarian" {
  348. return "hu"
  349. }
  350. return "auto"
  351. }
  352. }