KMAITranslationConfirmWindowController.swift 19 KB

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