KMAITranslationVC.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. //
  2. // KMAITranslationVC.swift
  3. // PDF Reader Pro
  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.km_init(hex: "#252629")
  49. self.aiTranslationLabel.font = NSFont.SFProTextSemiboldFont(20.0)
  50. self.supportPDFWordFileImageView.image = NSImage(named: "ic_function_other")
  51. self.supportPDFWordFileLabel.textColor = NSColor.km_init(hex: "#252629")
  52. self.supportPDFWordFileLabel.font = NSFont.SFProTextSemiboldFont(20.0)
  53. self.supportPDFWordFileSubLabel.textColor = NSColor.km_init(hex: "#94989C")
  54. self.supportPDFWordFileSubLabel.font = NSFont.SFProTextRegularFont(14.0)
  55. self.translationLanguageLabel.textColor = NSColor.km_init(hex: "#252629")
  56. self.translationLanguageLabel.font = NSFont.SFProTextRegularFont(14.0)
  57. self.automaticLabel.textColor = NSColor.km_init(hex: "#252629")
  58. self.automaticLabel.font = NSFont.SFProTextRegularFont(16.0)
  59. self.languageLabel.textColor = NSColor.km_init(hex: "#252629")
  60. self.languageLabel.font = NSFont.SFProTextRegularFont(16.0)
  61. self.automaticBox.cornerRadius = 4.0
  62. self.automaticBox.borderColor = NSColor.km_init(hex: "#DFE1E5")
  63. self.languageBox.cornerRadius = 4.0
  64. self.languageBox.borderColor = NSColor.km_init(hex: "#DFE1E5")
  65. self.languageImageView.image = NSImage(named: "ic_transtate")
  66. self.automaticBox.downCallback = { [weak self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  67. if downEntered {
  68. self?.languageAction(true)
  69. }
  70. }
  71. self.languageBox.downCallback = { [weak 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.km_init(hex: "#1770F4")
  78. self.selectYourFilesLabel.textColor = NSColor.km_init(hex: "#FFFFFF")
  79. self.selectYourFilesLabel.font = NSFont.SFProTextRegularFont(16.0)
  80. self.selectYourFilesImageView.image = NSImage(named: "icon_SelectYourFiles")
  81. self.orDropFileHereLabel.textColor = NSColor.km_init(hex: "#616469")
  82. self.orDropFileHereLabel.font = NSFont.SFProTextRegularFont(14.0)
  83. self.selectYourFilesBox.moveCallback = { [weak self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  84. if mouseEntered {
  85. self?.selectYourFilesBox.fillColor = NSColor.km_init(hex: "#3F8FF6")
  86. } else {
  87. self?.selectYourFilesBox.fillColor = NSColor.km_init(hex: "#1770F4")
  88. }
  89. }
  90. self.selectYourFilesBox.downCallback = { [weak 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?._selectFiles()
  97. // Task { @MainActor in
  98. // if await (KMLightMemberManager.manager.canPayFunction() == false) {
  99. // let _ = KMSubscribeWaterMarkWindowController.show(window: self.view.window!, type: .aiTranslate) { isSub, _, isClose in
  100. // if (isClose) {
  101. // return
  102. // }
  103. // if (isSub) {
  104. // self._selectFiles()
  105. // return
  106. // }
  107. // }
  108. // return
  109. // }
  110. // self._selectFiles()
  111. // }
  112. }
  113. }
  114. self.errorView.isHidden = true
  115. self.errorView.wantsLayer = true
  116. self.errorView.layer?.backgroundColor = NSColor.km_init(hex: "##36383B").cgColor
  117. self.errorView.layer?.cornerRadius = 4.0
  118. self.errorLabel.textColor = NSColor.km_init(hex: "#FFFFFF")
  119. self.errorLabel.font = NSFont.SFProTextRegularFont(14.0)
  120. }
  121. private func _selectFiles() {
  122. self.errorView.isHidden = true
  123. let openPanel = NSOpenPanel()
  124. openPanel.allowedFileTypes = ["pdf", "PDF", "docx", "doc"]
  125. openPanel.allowsMultipleSelection = false
  126. openPanel.beginSheetModal(for: self.view.window!) { result in
  127. if result == .OK {
  128. for url in openPanel.urls {
  129. let isExceedsLimit = self.isPDFPageCountExceedsLimit(filePath: url.path)
  130. if (url.pathExtension == "pdf") || url.pathExtension == "PDF" {
  131. if !url.path.isPDFValid() {
  132. let alert = NSAlert()
  133. alert.alertStyle = .critical
  134. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  135. alert.runModal()
  136. return
  137. }
  138. }
  139. if self.isFileGreaterThan10MB(atPath: url.path) {
  140. self.errorView.isHidden = false
  141. self.errorLabel.stringValue = NSLocalizedString("The uploaded file size cannot exceed 10MB", comment: "")
  142. } else if isExceedsLimit {
  143. self.errorView.isHidden = false
  144. self.errorLabel.stringValue = NSLocalizedString("Documents cannot exceed 30 pages", comment: "")
  145. } else {
  146. DispatchQueue.main.async {
  147. self.showProgressWindow()
  148. self.progressController?.maxValue = Double(100)
  149. }
  150. self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.timerTick), userInfo: nil, repeats: true)
  151. let infoDictionary = Bundle .main.infoDictionary!
  152. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  153. let languages = [self.automaticLabel.stringValue, self.languageLabel.stringValue]
  154. UserDefaults.standard.set(languages, forKey: "KMAITranslationLanguageArrayKey")
  155. UserDefaults.standard.synchronize()
  156. self.fromStr = self.languageAbbreviation(self.automaticLabel.stringValue)
  157. self.toStr = self.languageAbbreviation(self.languageLabel.stringValue)
  158. let alert = NSAlert()
  159. alert.messageText = NSLocalizedString("Processing times may be longer for larger documents. Thank you for your patience.", comment: "")
  160. alert.addButton(withTitle: NSLocalizedString("Continue", comment: ""))
  161. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  162. alert.beginSheetModal(for: self.view.window!) { [weak self] result in
  163. if (result == .alertFirstButtonReturn) {
  164. KMRequestServerManager.manager.aiTranslationFileUpload(file: url.path, version: majorVersion as! String) { [weak self] success, result in
  165. // self.hiddenProgressWindow()
  166. if success {
  167. let result: NSDictionary = result!.result
  168. let fileKey = result["fileKey"]
  169. let fileName = result["fileName"]
  170. let pageCount = result["pageCount"]
  171. if fileKey != nil {
  172. self?.fileTranslateHandle(fileKey as! String)
  173. }
  174. } else {
  175. let result: String = result!.message
  176. DispatchQueue.main.async {
  177. self?.hiddenProgressWindow()
  178. self?.errorView.isHidden = false
  179. self?.errorLabel.stringValue = result
  180. }
  181. }
  182. }
  183. } else if result == .alertSecondButtonReturn {
  184. DispatchQueue.main.async {
  185. self?.hiddenProgressWindow()
  186. }
  187. return
  188. }
  189. }
  190. }
  191. }
  192. }
  193. }
  194. }
  195. func initLocalization() -> Void {
  196. self.aiTranslationLabel.stringValue = NSLocalizedString("AI Translation", comment: "")
  197. self.supportPDFWordFileLabel.stringValue = NSLocalizedString("Support PDF and Word file", comment: "")
  198. self.supportPDFWordFileSubLabel.stringValue = NSLocalizedString("Limit document size to 10M, document page number to 30, 10w characters per month.", comment: "")
  199. self.translationLanguageLabel.stringValue = NSLocalizedString("Translation Language:", comment: "")
  200. self.selectYourFilesLabel.stringValue = NSLocalizedString("Select your file", comment: "")
  201. self.orDropFileHereLabel.stringValue = NSLocalizedString("or drop file here", comment: "")
  202. let languageArr = UserDefaults.standard.array(forKey: "KMAITranslationLanguageArrayKey") as? [String] ?? []
  203. if (languageArr.count > 0) {
  204. self.automaticLabel.stringValue = languageArr[0]
  205. self.languageLabel.stringValue = languageArr[1]
  206. } else {
  207. self.automaticLabel.stringValue = NSLocalizedString("Automatic", comment: "")
  208. self.languageLabel.stringValue = NSLocalizedString("English", comment: "")
  209. let languages = [NSLocalizedString("Automatic", comment: ""), NSLocalizedString("English", comment: "")]
  210. UserDefaults.standard.set(languages, forKey: "KMAITranslationLanguageArrayKey")
  211. UserDefaults.standard.synchronize()
  212. }
  213. }
  214. // MARK: Private Methods
  215. func fileTranslateHandle(_ fileKey: String) -> Void {
  216. let infoDictionary = Bundle .main.infoDictionary!
  217. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  218. // DispatchQueue.main.async {
  219. // self.showProgressWindow()
  220. // }
  221. KMRequestServerManager.manager.aiTranslationFileTranslateHandle(fileKey: fileKey, from: self.fromStr, to: self.toStr, version: majorVersion as! String) { [weak self] success, result in
  222. if success {
  223. let result: NSDictionary = result!.result
  224. let fileUrl: String = result["fileUrl"] as! String
  225. let downFileUrl: String = result["downFileUrl"] as! String
  226. let ossDownUrl: String = result["ossDownUrl"] as! String
  227. let fileName: String = result["fileName"] as! String
  228. let downFileName: String = result["downFileName"] as! String
  229. let from: String = result["from"] as! String
  230. let to: String = result["to"] as! String
  231. self?.downloadFile(filePath: ossDownUrl, downFileName: downFileName)
  232. } else {
  233. let result: String = result!.message
  234. DispatchQueue.main.async {
  235. self?.hiddenProgressWindow()
  236. self?.errorView.isHidden = false
  237. self?.errorLabel.stringValue = result
  238. }
  239. }
  240. }
  241. }
  242. func downloadFile(filePath: String, downFileName: String) -> Void {
  243. guard let fileURL = URL(string: filePath) else {
  244. let alert = NSAlert()
  245. alert.alertStyle = .critical
  246. alert.messageText = NSLocalizedString("Invalid file link", comment: "")
  247. alert.runModal()
  248. return
  249. }
  250. let destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent(downFileName)
  251. if FileManager.default.fileExists(atPath: destinationURL.path) {
  252. do {
  253. try FileManager.default.removeItem(at: destinationURL)
  254. KMPrint("删除旧文件成功")
  255. } catch {
  256. KMPrint("删除旧文件失败:\(error)")
  257. }
  258. }
  259. let sessionConfiguration = URLSessionConfiguration.default
  260. let session = URLSession(configuration: sessionConfiguration)
  261. let downloadTask = session.downloadTask(with: fileURL) { (tempLocalURL, response, error) in
  262. if let error = error {
  263. let alert = NSAlert()
  264. alert.alertStyle = .critical
  265. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Download failed", comment: ""))
  266. alert.runModal()
  267. return
  268. }
  269. guard let tempLocalURL = tempLocalURL else {
  270. let alert = NSAlert()
  271. alert.alertStyle = .critical
  272. alert.messageText = NSLocalizedString("Invalid temporary directory", comment: "")
  273. alert.runModal()
  274. return
  275. }
  276. DispatchQueue.main.async {
  277. self.hiddenProgressWindow()
  278. }
  279. do {
  280. try FileManager.default.moveItem(at: tempLocalURL, to: destinationURL)
  281. NSDocumentController.shared.openDocument(withContentsOf: destinationURL, 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 Identification" {
  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. func showProgressWindow() {
  353. let progress = SKProgressController()
  354. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  355. progress.window?.contentView?.wantsLayer = true
  356. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  357. progress.progressField.textColor = NSColor.white
  358. progress.message = NSLocalizedString("Translating...", comment: "")
  359. progress.closeBlock = { [weak self] in
  360. self?.hiddenProgressWindow()
  361. }
  362. self.progressController = progress
  363. self.view.window?.beginSheet(progress.window!)
  364. }
  365. func hiddenProgressWindow() {
  366. DispatchQueue.main.async {
  367. self.progressController?.doubleValue = 100.0
  368. }
  369. self.stopTimer()
  370. if (self.progressController != nil) {
  371. self.view.window?.endSheet((self.progressController?.window)!)
  372. self.progressController = nil
  373. KMRequestServer.requestServer.task?.cancel()
  374. }
  375. }
  376. func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
  377. let fileManager = FileManager.default
  378. do {
  379. let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
  380. if let fileSize = fileAttributes[.size] as? UInt64 {
  381. let megabyteSize = fileSize / (1024 * 1024)
  382. return megabyteSize >= 10
  383. }
  384. } catch {
  385. KMPrint("Error: \(error)")
  386. }
  387. return false
  388. }
  389. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  390. let url = URL(fileURLWithPath: filePath)
  391. guard let document = PDFDocument(url: url) else {
  392. return false
  393. }
  394. let pageCount = document.pageCount
  395. return pageCount > 30
  396. }
  397. @objc func timerTick() {
  398. timerCounter += 1.0
  399. self.progressController?.increment(by: 1.0)
  400. if timerCounter >= 95 {
  401. stopTimer()
  402. }
  403. }
  404. func stopTimer() {
  405. timer?.invalidate()
  406. timer = nil
  407. }
  408. // MARK: Action Methods
  409. func languageAction(_ isFromLanguage: Bool) -> Void {
  410. if (self.popover != nil && self.popover!.isShown) {
  411. self.popover?.close()
  412. self.popover = nil
  413. return
  414. }
  415. var languages = self.fromLanguages
  416. if !isFromLanguage {
  417. languages = self.toLanguages
  418. }
  419. let vc: KMAILanguagePopVC = KMAILanguagePopVC().initWithPopViewDataArr(languages)
  420. let createFilePopover: NSPopover = NSPopover.init()
  421. self.popover = createFilePopover
  422. createFilePopover.contentViewController = vc
  423. createFilePopover.animates = true
  424. createFilePopover.behavior = .semitransient
  425. createFilePopover.setValue(true, forKey: "shouldHideAnchor")
  426. if isFromLanguage {
  427. vc.selectString = self.automaticLabel.stringValue
  428. } else {
  429. vc.selectString = self.languageLabel.stringValue
  430. }
  431. vc.downCallback = { [unowned self] (language: String) -> Void in
  432. createFilePopover.close()
  433. if isFromLanguage {
  434. self.automaticLabel.stringValue = language
  435. self.fromStr = self.languageAbbreviation(language)
  436. } else {
  437. self.languageLabel.stringValue = language
  438. self.toStr = self.languageAbbreviation(language)
  439. }
  440. }
  441. if isFromLanguage {
  442. 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)
  443. vc.customBoxWidthLayoutConstraint.constant = automaticBox.frame.width
  444. } else {
  445. 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)
  446. vc.customBoxWidthLayoutConstraint.constant = languageBox.frame.width
  447. }
  448. }
  449. }