Some translation clean up

This commit is contained in:
Nikolaj Olsson 2024-05-09 15:15:02 +02:00
parent a306e4a1be
commit fe0130807f
8 changed files with 30 additions and 1297 deletions

View File

@ -4964,7 +4964,7 @@ namespace Nikse.SubtitleEdit.Forms
else
{
var originalLanguage = LanguageAutoDetect.AutoDetectGoogleLanguage(_subtitleOriginal);
suffix = "." + GenericTranslate.EvaluateDefaultTargetLanguageCode(originalLanguage);
suffix = "." + AutoTranslate.EvaluateDefaultTargetLanguageCode(originalLanguage);
}
}
else

View File

@ -1,347 +0,0 @@
using Nikse.SubtitleEdit.Controls;
namespace Nikse.SubtitleEdit.Forms.Translate
{
sealed partial class GenericTranslate
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.comboBoxSource = new Nikse.SubtitleEdit.Controls.NikseComboBox();
this.labelSource = new System.Windows.Forms.Label();
this.labelTarget = new System.Windows.Forms.Label();
this.comboBoxTarget = new Nikse.SubtitleEdit.Controls.NikseComboBox();
this.buttonTranslate = new System.Windows.Forms.Button();
this.buttonOK = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.labelPleaseWait = new System.Windows.Forms.Label();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.subtitleListViewTarget = new Nikse.SubtitleEdit.Controls.SubtitleListView();
this.subtitleListViewSource = new Nikse.SubtitleEdit.Controls.SubtitleListView();
this.labelApiKeyNotFound = new System.Windows.Forms.Label();
this.comboBoxTranslationServices = new Nikse.SubtitleEdit.Controls.NikseComboBox();
this.labelTranslationService = new System.Windows.Forms.Label();
this.labelParagraphHandling = new System.Windows.Forms.Label();
this.comboBoxParagraphHandling = new Nikse.SubtitleEdit.Controls.NikseComboBox();
this.SuspendLayout();
//
// comboBoxSource
//
this.comboBoxSource.BackColor = System.Drawing.SystemColors.Window;
this.comboBoxSource.BackColorDisabled = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240)))));
this.comboBoxSource.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(171)))), ((int)(((byte)(173)))), ((int)(((byte)(179)))));
this.comboBoxSource.BorderColorDisabled = System.Drawing.Color.FromArgb(((int)(((byte)(120)))), ((int)(((byte)(120)))), ((int)(((byte)(120)))));
this.comboBoxSource.ButtonForeColor = System.Drawing.SystemColors.ControlText;
this.comboBoxSource.ButtonForeColorDown = System.Drawing.Color.Orange;
this.comboBoxSource.ButtonForeColorOver = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(120)))), ((int)(((byte)(215)))));
this.comboBoxSource.DropDownHeight = 400;
this.comboBoxSource.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxSource.DropDownWidth = 121;
this.comboBoxSource.FormattingEnabled = true;
this.comboBoxSource.Location = new System.Drawing.Point(327, 35);
this.comboBoxSource.MaxLength = 32767;
this.comboBoxSource.Name = "comboBoxSource";
this.comboBoxSource.SelectedIndex = -1;
this.comboBoxSource.SelectedItem = null;
this.comboBoxSource.SelectedText = "";
this.comboBoxSource.Size = new System.Drawing.Size(121, 21);
this.comboBoxSource.TabIndex = 1;
this.comboBoxSource.UsePopupWindow = false;
this.comboBoxSource.TextChanged += new System.EventHandler(this.ComboBoxLanguageChanged);
//
// labelSource
//
this.labelSource.AutoSize = true;
this.labelSource.Location = new System.Drawing.Point(285, 40);
this.labelSource.Name = "labelSource";
this.labelSource.Size = new System.Drawing.Size(35, 13);
this.labelSource.TabIndex = 1;
this.labelSource.Text = "From:";
//
// labelTarget
//
this.labelTarget.AutoSize = true;
this.labelTarget.Location = new System.Drawing.Point(468, 40);
this.labelTarget.Name = "labelTarget";
this.labelTarget.Size = new System.Drawing.Size(23, 13);
this.labelTarget.TabIndex = 4;
this.labelTarget.Text = "To:";
//
// comboBoxTarget
//
this.comboBoxTarget.BackColor = System.Drawing.SystemColors.Window;
this.comboBoxTarget.BackColorDisabled = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240)))));
this.comboBoxTarget.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(171)))), ((int)(((byte)(173)))), ((int)(((byte)(179)))));
this.comboBoxTarget.BorderColorDisabled = System.Drawing.Color.FromArgb(((int)(((byte)(120)))), ((int)(((byte)(120)))), ((int)(((byte)(120)))));
this.comboBoxTarget.ButtonForeColor = System.Drawing.SystemColors.ControlText;
this.comboBoxTarget.ButtonForeColorDown = System.Drawing.Color.Orange;
this.comboBoxTarget.ButtonForeColorOver = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(120)))), ((int)(((byte)(215)))));
this.comboBoxTarget.DropDownHeight = 400;
this.comboBoxTarget.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxTarget.DropDownWidth = 121;
this.comboBoxTarget.FormattingEnabled = true;
this.comboBoxTarget.Location = new System.Drawing.Point(497, 35);
this.comboBoxTarget.MaxLength = 32767;
this.comboBoxTarget.Name = "comboBoxTarget";
this.comboBoxTarget.SelectedIndex = -1;
this.comboBoxTarget.SelectedItem = null;
this.comboBoxTarget.SelectedText = "";
this.comboBoxTarget.Size = new System.Drawing.Size(121, 21);
this.comboBoxTarget.TabIndex = 2;
this.comboBoxTarget.UsePopupWindow = false;
this.comboBoxTarget.TextChanged += new System.EventHandler(this.ComboBoxLanguageChanged);
//
// buttonTranslate
//
this.buttonTranslate.Location = new System.Drawing.Point(624, 34);
this.buttonTranslate.Name = "buttonTranslate";
this.buttonTranslate.Size = new System.Drawing.Size(75, 23);
this.buttonTranslate.TabIndex = 3;
this.buttonTranslate.Text = "Translate";
this.buttonTranslate.UseVisualStyleBackColor = true;
this.buttonTranslate.Click += new System.EventHandler(this.buttonTranslate_Click);
//
// buttonOK
//
this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonOK.Location = new System.Drawing.Point(882, 529);
this.buttonOK.Name = "buttonOK";
this.buttonOK.Size = new System.Drawing.Size(75, 23);
this.buttonOK.TabIndex = 92;
this.buttonOK.Text = "&OK";
this.buttonOK.UseVisualStyleBackColor = true;
this.buttonOK.Click += new System.EventHandler(this.ButtonOkClick);
//
// buttonCancel
//
this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Location = new System.Drawing.Point(963, 529);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 93;
this.buttonCancel.Text = "C&ancel";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// labelPleaseWait
//
this.labelPleaseWait.AutoSize = true;
this.labelPleaseWait.Location = new System.Drawing.Point(703, 23);
this.labelPleaseWait.Name = "labelPleaseWait";
this.labelPleaseWait.Size = new System.Drawing.Size(176, 13);
this.labelPleaseWait.TabIndex = 10;
this.labelPleaseWait.Text = "Please wait... this may take a while";
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(705, 39);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(192, 16);
this.progressBar1.TabIndex = 11;
//
// subtitleListViewTarget
//
this.subtitleListViewTarget.AllowColumnReorder = true;
this.subtitleListViewTarget.FirstVisibleIndex = -1;
this.subtitleListViewTarget.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.subtitleListViewTarget.FullRowSelect = true;
this.subtitleListViewTarget.GridLines = true;
this.subtitleListViewTarget.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.subtitleListViewTarget.HideSelection = false;
this.subtitleListViewTarget.Location = new System.Drawing.Point(471, 64);
this.subtitleListViewTarget.Name = "subtitleListViewTarget";
this.subtitleListViewTarget.OwnerDraw = true;
this.subtitleListViewTarget.Size = new System.Drawing.Size(428, 459);
this.subtitleListViewTarget.SubtitleFontBold = false;
this.subtitleListViewTarget.SubtitleFontName = "Tahoma";
this.subtitleListViewTarget.SubtitleFontSize = 8;
this.subtitleListViewTarget.TabIndex = 5;
this.subtitleListViewTarget.UseCompatibleStateImageBehavior = false;
this.subtitleListViewTarget.UseSyntaxColoring = true;
this.subtitleListViewTarget.View = System.Windows.Forms.View.Details;
this.subtitleListViewTarget.Click += new System.EventHandler(this.subtitleListViewTarget_DoubleClick);
this.subtitleListViewTarget.DoubleClick += new System.EventHandler(this.subtitleListViewTarget_DoubleClick);
//
// subtitleListViewSource
//
this.subtitleListViewSource.AllowColumnReorder = true;
this.subtitleListViewSource.FirstVisibleIndex = -1;
this.subtitleListViewSource.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.subtitleListViewSource.FullRowSelect = true;
this.subtitleListViewSource.GridLines = true;
this.subtitleListViewSource.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.subtitleListViewSource.HideSelection = false;
this.subtitleListViewSource.Location = new System.Drawing.Point(18, 64);
this.subtitleListViewSource.Name = "subtitleListViewSource";
this.subtitleListViewSource.OwnerDraw = true;
this.subtitleListViewSource.Size = new System.Drawing.Size(430, 459);
this.subtitleListViewSource.SubtitleFontBold = false;
this.subtitleListViewSource.SubtitleFontName = "Tahoma";
this.subtitleListViewSource.SubtitleFontSize = 8;
this.subtitleListViewSource.TabIndex = 4;
this.subtitleListViewSource.UseCompatibleStateImageBehavior = false;
this.subtitleListViewSource.UseSyntaxColoring = true;
this.subtitleListViewSource.View = System.Windows.Forms.View.Details;
this.subtitleListViewSource.Click += new System.EventHandler(this.subtitleListViewSource_DoubleClick);
this.subtitleListViewSource.DoubleClick += new System.EventHandler(this.subtitleListViewSource_DoubleClick);
//
// labelApiKeyNotFound
//
this.labelApiKeyNotFound.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.labelApiKeyNotFound.AutoSize = true;
this.labelApiKeyNotFound.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0)))));
this.labelApiKeyNotFound.Location = new System.Drawing.Point(388, 530);
this.labelApiKeyNotFound.Name = "labelApiKeyNotFound";
this.labelApiKeyNotFound.Size = new System.Drawing.Size(145, 13);
this.labelApiKeyNotFound.TabIndex = 12;
this.labelApiKeyNotFound.Text = "Warning: API key not found!";
//
// comboBoxTranslationServices
//
this.comboBoxTranslationServices.BackColor = System.Drawing.SystemColors.Window;
this.comboBoxTranslationServices.BackColorDisabled = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240)))));
this.comboBoxTranslationServices.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(171)))), ((int)(((byte)(173)))), ((int)(((byte)(179)))));
this.comboBoxTranslationServices.BorderColorDisabled = System.Drawing.Color.FromArgb(((int)(((byte)(120)))), ((int)(((byte)(120)))), ((int)(((byte)(120)))));
this.comboBoxTranslationServices.ButtonForeColor = System.Drawing.SystemColors.ControlText;
this.comboBoxTranslationServices.ButtonForeColorDown = System.Drawing.Color.Orange;
this.comboBoxTranslationServices.ButtonForeColorOver = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(120)))), ((int)(((byte)(215)))));
this.comboBoxTranslationServices.DropDownHeight = 400;
this.comboBoxTranslationServices.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxTranslationServices.DropDownWidth = 152;
this.comboBoxTranslationServices.FormattingEnabled = true;
this.comboBoxTranslationServices.Location = new System.Drawing.Point(84, 35);
this.comboBoxTranslationServices.MaxLength = 32767;
this.comboBoxTranslationServices.Name = "comboBoxTranslationServices";
this.comboBoxTranslationServices.SelectedIndex = -1;
this.comboBoxTranslationServices.SelectedItem = null;
this.comboBoxTranslationServices.SelectedText = "";
this.comboBoxTranslationServices.Size = new System.Drawing.Size(152, 21);
this.comboBoxTranslationServices.TabIndex = 0;
this.comboBoxTranslationServices.UsePopupWindow = false;
this.comboBoxTranslationServices.SelectedIndexChanged += new System.EventHandler(this.comboBoxTranslationServices_SelectedIndexChanged);
//
// labelTranslationService
//
this.labelTranslationService.AutoSize = true;
this.labelTranslationService.Location = new System.Drawing.Point(15, 40);
this.labelTranslationService.Name = "labelTranslationService";
this.labelTranslationService.Size = new System.Drawing.Size(46, 13);
this.labelTranslationService.TabIndex = 14;
this.labelTranslationService.Text = "Service:";
//
// labelParagraphHandling
//
this.labelParagraphHandling.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.labelParagraphHandling.AutoSize = true;
this.labelParagraphHandling.Location = new System.Drawing.Point(18, 530);
this.labelParagraphHandling.Name = "labelParagraphHandling";
this.labelParagraphHandling.Size = new System.Drawing.Size(105, 13);
this.labelParagraphHandling.TabIndex = 15;
this.labelParagraphHandling.Text = "Paragraph Handling:";
//
// comboBoxParagraphHandling
//
this.comboBoxParagraphHandling.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.comboBoxParagraphHandling.BackColor = System.Drawing.SystemColors.Window;
this.comboBoxParagraphHandling.BackColorDisabled = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240)))));
this.comboBoxParagraphHandling.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(171)))), ((int)(((byte)(173)))), ((int)(((byte)(179)))));
this.comboBoxParagraphHandling.BorderColorDisabled = System.Drawing.Color.FromArgb(((int)(((byte)(120)))), ((int)(((byte)(120)))), ((int)(((byte)(120)))));
this.comboBoxParagraphHandling.ButtonForeColor = System.Drawing.SystemColors.ControlText;
this.comboBoxParagraphHandling.ButtonForeColorDown = System.Drawing.Color.Orange;
this.comboBoxParagraphHandling.ButtonForeColorOver = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(120)))), ((int)(((byte)(215)))));
this.comboBoxParagraphHandling.DropDownHeight = 400;
this.comboBoxParagraphHandling.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxParagraphHandling.DropDownWidth = 165;
this.comboBoxParagraphHandling.FormattingEnabled = true;
this.comboBoxParagraphHandling.Location = new System.Drawing.Point(155, 527);
this.comboBoxParagraphHandling.MaxLength = 32767;
this.comboBoxParagraphHandling.Name = "comboBoxParagraphHandling";
this.comboBoxParagraphHandling.SelectedIndex = -1;
this.comboBoxParagraphHandling.SelectedItem = null;
this.comboBoxParagraphHandling.SelectedText = "";
this.comboBoxParagraphHandling.Size = new System.Drawing.Size(165, 21);
this.comboBoxParagraphHandling.TabIndex = 90;
this.comboBoxParagraphHandling.UsePopupWindow = false;
//
// GenericTranslate
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1053, 558);
this.Controls.Add(this.comboBoxParagraphHandling);
this.Controls.Add(this.labelParagraphHandling);
this.Controls.Add(this.labelTranslationService);
this.Controls.Add(this.comboBoxTranslationServices);
this.Controls.Add(this.labelApiKeyNotFound);
this.Controls.Add(this.comboBoxSource);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.labelPleaseWait);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOK);
this.Controls.Add(this.buttonTranslate);
this.Controls.Add(this.labelTarget);
this.Controls.Add(this.comboBoxTarget);
this.Controls.Add(this.subtitleListViewTarget);
this.Controls.Add(this.subtitleListViewSource);
this.Controls.Add(this.labelSource);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.KeyPreview = true;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(900, 500);
this.Name = "GenericTranslate";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Translate";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.GenericTranslate_FormClosing);
this.Shown += new System.EventHandler(this.GenericTranslate_Shown);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FormTranslate_KeyDown);
this.Resize += new System.EventHandler(this.Translate_Resize);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Nikse.SubtitleEdit.Controls.NikseComboBox comboBoxSource;
private System.Windows.Forms.Label labelSource;
private SubtitleListView subtitleListViewSource;
private SubtitleListView subtitleListViewTarget;
private System.Windows.Forms.Label labelTarget;
private Nikse.SubtitleEdit.Controls.NikseComboBox comboBoxTarget;
private System.Windows.Forms.Button buttonTranslate;
private System.Windows.Forms.Button buttonOK;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Label labelPleaseWait;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Label labelApiKeyNotFound;
private Nikse.SubtitleEdit.Controls.NikseComboBox comboBoxTranslationServices;
private System.Windows.Forms.Label labelTranslationService;
private System.Windows.Forms.Label labelParagraphHandling;
private Nikse.SubtitleEdit.Controls.NikseComboBox comboBoxParagraphHandling;
}
}

View File

@ -1,769 +0,0 @@
using Nikse.SubtitleEdit.Controls;
using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.SubtitleFormats;
using Nikse.SubtitleEdit.Core.Translate;
using Nikse.SubtitleEdit.Core.Translate.Processor;
using Nikse.SubtitleEdit.Core.Translate.Service;
using Nikse.SubtitleEdit.Logic;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Windows.Forms;
using MessageBox = Nikse.SubtitleEdit.Forms.SeMsgBox.MessageBox;
namespace Nikse.SubtitleEdit.Forms.Translate
{
public sealed partial class GenericTranslate : PositionAndSizeForm
{
public Subtitle TranslatedSubtitle { get; private set; }
private Subtitle _subtitle;
private Encoding _encoding;
private SubtitleFormat _subtitleFormat;
private bool _breakTranslation;
private const string SplitterString = "+-+";
private ITranslationService _translationService;
private bool[] _autoSplit;
private string _targetLanguageIsoCode;
private string _sourceLanguageIsoCode;
public GenericTranslate()
{
UiUtil.PreInitialize(this);
InitializeComponent();
UiUtil.FixFonts(this);
Text = LanguageSettings.Current.GoogleTranslate.Title;
labelSource.Text = LanguageSettings.Current.GoogleTranslate.From;
labelTarget.Text = LanguageSettings.Current.GoogleTranslate.To;
buttonTranslate.Text = LanguageSettings.Current.GoogleTranslate.Translate;
labelPleaseWait.Text = LanguageSettings.Current.GoogleTranslate.PleaseWait;
buttonOK.Text = LanguageSettings.Current.General.Ok;
buttonCancel.Text = LanguageSettings.Current.General.Cancel;
labelApiKeyNotFound.Text = string.Empty;
labelTranslationService.Text = LanguageSettings.Current.GoogleTranslate.Service;
comboBoxTranslationServices.Left = labelTranslationService.Left + labelTranslationService.Width + 5;
labelParagraphHandling.Text = LanguageSettings.Current.GoogleTranslate.LineMergeHandling;
comboBoxParagraphHandling.Left = labelParagraphHandling.Left + labelParagraphHandling.Width + 5;
subtitleListViewSource.InitializeLanguage(LanguageSettings.Current.General, Configuration.Settings);
subtitleListViewTarget.InitializeLanguage(LanguageSettings.Current.General, Configuration.Settings);
subtitleListViewSource.HideColumn(SubtitleListView.SubtitleColumn.CharactersPerSeconds);
subtitleListViewSource.HideColumn(SubtitleListView.SubtitleColumn.WordsPerMinute);
subtitleListViewTarget.HideColumn(SubtitleListView.SubtitleColumn.CharactersPerSeconds);
subtitleListViewTarget.HideColumn(SubtitleListView.SubtitleColumn.WordsPerMinute);
UiUtil.InitializeSubtitleFont(subtitleListViewSource);
UiUtil.InitializeSubtitleFont(subtitleListViewTarget);
subtitleListViewSource.AutoSizeColumns();
subtitleListViewSource.AutoSizeColumns();
UiUtil.FixLargeFonts(this, buttonOK);
ActiveControl = buttonTranslate;
}
internal void Initialize(Subtitle subtitle, Subtitle target, string title, Encoding encoding, SubtitleFormat subtitleFormat)
{
if (!string.IsNullOrEmpty(title))
{
Text = title;
}
labelPleaseWait.Visible = false;
progressBar1.Visible = false;
_subtitle = new Subtitle(subtitle);
_subtitle.Renumber(); // "Renumber" is required for translation engine atm
_encoding = encoding;
_subtitleFormat = subtitleFormat;
buttonTranslate.Enabled = false;
if (target != null)
{
TranslatedSubtitle = new Subtitle(target);
TranslatedSubtitle.Renumber();
subtitleListViewTarget.Fill(TranslatedSubtitle);
}
else
{
TranslatedSubtitle = new Subtitle(_subtitle);
foreach (var paragraph in TranslatedSubtitle.Paragraphs)
{
paragraph.Text = string.Empty;
}
}
_sourceLanguageIsoCode = EvaluateDefaultSourceLanguageCode(encoding, _subtitle);
_targetLanguageIsoCode = EvaluateDefaultTargetLanguageCode(_sourceLanguageIsoCode);
InitTranslationServices();
InitParagraphHandlingStrategies();
subtitleListViewSource.Fill(_subtitle);
Translate_Resize(null, null);
_autoSplit = new bool[_subtitle.Paragraphs.Count];
}
private void InitParagraphHandlingStrategies()
{
foreach (var translationProcessor in TranslationProcessorRepository.TranslationProcessors)
{
var t = translationProcessor.GetType();
if (t == typeof(NextLineMergeTranslationProcessor))
{
((NextLineMergeTranslationProcessor)translationProcessor).TranslatedName = LanguageSettings.Current.GoogleTranslate.ProcessorMergeNext;
}
else if (t == typeof(SentenceMergingTranslationProcessor))
{
((SentenceMergingTranslationProcessor)translationProcessor).TranslatedName = LanguageSettings.Current.GoogleTranslate.ProcessorSentence;
}
else if (t == typeof(SingleParagraphTranslationProcessor))
{
((SingleParagraphTranslationProcessor)translationProcessor).TranslatedName = LanguageSettings.Current.GoogleTranslate.ProcessorSingle;
}
comboBoxParagraphHandling.Items.Add(translationProcessor);
}
if (comboBoxParagraphHandling.Items.Count > 0)
{
for (var index = 0; index < comboBoxParagraphHandling.Items.Count; index++)
{
var item = comboBoxParagraphHandling.Items[index].ToString();
if (item == Configuration.Settings.Tools.TranslateMergeStrategy)
{
comboBoxParagraphHandling.SelectedIndex = index;
break;
}
}
if (comboBoxParagraphHandling.SelectedIndex == -1)
{
comboBoxParagraphHandling.SelectedIndex = 0;
}
}
}
private void InitTranslationServices()
{
AddTranslationService(GoogleTranslationInitializer.Init(this));
AddTranslationService(MicrosoftTranslationInitializer.Init());
if (comboBoxTranslationServices.Items.Count > 0 && comboBoxTranslationServices.SelectedIndex < 0)
{
comboBoxTranslationServices.SelectedIndex = 0;
}
}
public void AddTranslationService(ITranslationService translationService)
{
if (translationService != null)
{
comboBoxTranslationServices.Items.Add(translationService);
if (translationService.GetType().ToString() == Configuration.Settings.Tools.TranslateLastService)
{
comboBoxTranslationServices.SelectedIndex = comboBoxTranslationServices.Items.Count - 1;
}
}
}
private void EvaluateTranslateButtonStatus()
{
buttonTranslate.Enabled = comboBoxSource.SelectedItem != null && comboBoxTarget.SelectedItem != null && _translationService != null;
}
private void ComboBoxLanguageChanged(object sender, EventArgs e)
{
EvaluateTranslateButtonStatus();
}
private void SetupLanguageSettings()
{
FillComboWithLanguages(comboBoxSource, _translationService.GetSupportedSourceLanguages());
_sourceLanguageIsoCode = EvaluateDefaultSourceLanguageCode(_encoding, _subtitle);
SelectLanguageCode(comboBoxSource, _sourceLanguageIsoCode);
FillComboWithLanguages(comboBoxTarget, _translationService.GetSupportedTargetLanguages());
_targetLanguageIsoCode = EvaluateDefaultTargetLanguageCode(_sourceLanguageIsoCode);
SelectLanguageCode(comboBoxTarget, _targetLanguageIsoCode);
}
private void ReadLanguageSettings()
{
if (comboBoxSource.SelectedItem != null)
{
_sourceLanguageIsoCode = ((TranslationPair)comboBoxSource.SelectedItem).Code;
}
if (comboBoxTarget.SelectedItem != null)
{
_targetLanguageIsoCode = ((TranslationPair)comboBoxTarget.SelectedItem).Code;
}
}
public static string EvaluateDefaultSourceLanguageCode(Encoding encoding, Subtitle subtitle)
{
var defaultSourceLanguageCode = LanguageAutoDetect.AutoDetectGoogleLanguage(encoding); // Guess language via encoding
if (string.IsNullOrEmpty(defaultSourceLanguageCode))
{
defaultSourceLanguageCode = LanguageAutoDetect.AutoDetectGoogleLanguage(subtitle); // Guess language based on subtitle contents
}
return defaultSourceLanguageCode;
}
public static string EvaluateDefaultTargetLanguageCode(string defaultSourceLanguage)
{
var installedLanguages = new List<string>();
foreach (InputLanguage language in InputLanguage.InstalledInputLanguages)
{
var iso639 = Iso639Dash2LanguageCode.GetTwoLetterCodeFromEnglishName(language.LayoutName);
if (!string.IsNullOrEmpty(iso639) && !installedLanguages.Contains(iso639))
{
installedLanguages.Add(iso639.ToLowerInvariant());
}
}
var uiCultureTargetLanguage = Configuration.Settings.Tools.GoogleTranslateLastTargetLanguage;
if (uiCultureTargetLanguage == defaultSourceLanguage)
{
foreach (var s in Utilities.GetDictionaryLanguages())
{
var temp = s.Replace("[", string.Empty).Replace("]", string.Empty);
if (temp.Length > 4)
{
temp = temp.Substring(temp.Length - 5, 2).ToLowerInvariant();
if (temp != defaultSourceLanguage && installedLanguages.Any(p => p.Contains(temp)))
{
uiCultureTargetLanguage = temp;
break;
}
}
}
}
if (uiCultureTargetLanguage == defaultSourceLanguage)
{
foreach (var language in installedLanguages)
{
if (language != defaultSourceLanguage)
{
uiCultureTargetLanguage = language;
break;
}
}
}
if (uiCultureTargetLanguage == defaultSourceLanguage)
{
var name = CultureInfo.CurrentCulture.Name;
if (name.Length > 2)
{
name = name.Remove(0, name.Length - 2);
}
var iso = IsoCountryCodes.ThreeToTwoLetterLookup.FirstOrDefault(p => p.Value == name);
if (!iso.Equals(default(KeyValuePair<string, string>)))
{
var iso639 = Iso639Dash2LanguageCode.GetTwoLetterCodeFromThreeLetterCode(iso.Key);
if (!string.IsNullOrEmpty(iso639))
{
uiCultureTargetLanguage = iso639;
}
}
}
// Set target language to something different than source language
if (uiCultureTargetLanguage == defaultSourceLanguage && defaultSourceLanguage == "en")
{
uiCultureTargetLanguage = "es";
}
else if (uiCultureTargetLanguage == defaultSourceLanguage)
{
uiCultureTargetLanguage = "en";
}
return uiCultureTargetLanguage;
}
public static void SelectLanguageCode(NikseComboBox comboBox, string languageIsoCode)
{
var i = 0;
foreach (TranslationPair item in comboBox.Items)
{
if (item.Code == languageIsoCode)
{
comboBox.SelectedIndex = i;
return;
}
i++;
}
if (comboBox.SelectedIndex < 0 && comboBox.Items.Count > 0)
{
comboBox.SelectedIndex = 0;
}
}
private void buttonTranslate_Click(object sender, EventArgs e)
{
if (buttonTranslate.Text == LanguageSettings.Current.General.Cancel)
{
buttonTranslate.Enabled = false;
_breakTranslation = true;
buttonOK.Enabled = true;
buttonCancel.Enabled = true;
return;
}
var translationService = (ITranslationService)comboBoxTranslationServices.SelectedItem;
if (translationService is GoogleTranslationService &&
Configuration.Settings.Tools.GoogleTranslateNoKeyWarningShow &&
string.IsNullOrEmpty(Configuration.Settings.Tools.GoogleApiV2Key))
{
using (var form = new DialogDoNotShowAgain("Subtitle Edit", LanguageSettings.Current.GoogleTranslate.GoogleNoApiKeyWarning))
{
form.ShowDialog(this);
Configuration.Settings.Tools.GoogleTranslateNoKeyWarningShow = !form.DoNoDisplayAgain;
}
}
ReadLanguageSettings();
Translate();
buttonOK.Focus();
}
public static bool IsAvailableNetworkActive()
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
return false;
}
var interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var face in interfaces)
{
if (face.OperationalStatus == OperationalStatus.Up && face.NetworkInterfaceType != NetworkInterfaceType.Tunnel && face.NetworkInterfaceType != NetworkInterfaceType.Loopback)
{
var statistics = face.GetIPv4Statistics();
if (statistics.BytesReceived > 0 && statistics.BytesSent > 0)
{
return true;
}
}
}
return false;
}
private void Translate()
{
var translator = (ITranslationProcessor)comboBoxParagraphHandling.SelectedItem;
buttonOK.Enabled = false;
buttonCancel.Enabled = false;
_breakTranslation = false;
buttonTranslate.Text = LanguageSettings.Current.General.Cancel;
Cursor.Current = Cursors.WaitCursor;
progressBar1.Visible = true;
labelPleaseWait.Visible = true;
try
{
var selectedParagraphs = GetSelectedParagraphs();
progressBar1.Minimum = 0;
progressBar1.Maximum = selectedParagraphs.Count;
translator.Translate(_translationService, _sourceLanguageIsoCode, _targetLanguageIsoCode, selectedParagraphs, targetParagraphs =>
{
FillTranslatedText(targetParagraphs);
progressBar1.Value = selectedParagraphs.FindIndex(x => x.Number == targetParagraphs.Keys.Last());
Application.DoEvents();
return _breakTranslation;
});
}
finally
{
if (comboBoxParagraphHandling.Text != LanguageSettings.Current.GoogleTranslate.ProcessorSingle)
{
var indexesToRemove = new List<int>();
for (var i = 0; i < TranslatedSubtitle.Paragraphs.Count - 1; i++)
{
var p = TranslatedSubtitle.Paragraphs[i];
var next = TranslatedSubtitle.Paragraphs[i + 1];
if (!string.IsNullOrEmpty(p.Text) && string.IsNullOrEmpty(next.Text) &&
next.EndTime.TotalMilliseconds - p.StartTime.TotalMilliseconds < 10000)
{
p.EndTime = next.EndTime;
indexesToRemove.Add(i + 1);
}
}
foreach (var idx in indexesToRemove.OrderByDescending(p => p))
{
TranslatedSubtitle.Paragraphs.RemoveAt(idx);
}
subtitleListViewTarget.Fill(TranslatedSubtitle);
}
labelPleaseWait.Visible = false;
progressBar1.Visible = false;
Cursor.Current = Cursors.Default;
buttonTranslate.Text = LanguageSettings.Current.GoogleTranslate.Translate;
buttonTranslate.Enabled = true;
buttonOK.Enabled = true;
buttonCancel.Enabled = true;
Configuration.Settings.Tools.GoogleTranslateLastTargetLanguage = _targetLanguageIsoCode;
}
}
private static void ShowNetworkError(Exception exception)
{
MessageBox.Show("Subtitle Edit was unable to connect to the translation service." + Environment.NewLine +
"Try again later or check your internet connection." + Environment.NewLine +
Environment.NewLine +
"Error: " + exception.Message);
}
private List<Paragraph> GetSelectedParagraphs()
{
var selectedParagraphs = new List<Paragraph>();
var selectedItems = subtitleListViewSource.SelectedItems;
if (selectedItems.Count > 1)
{
// use selected items
foreach (ListViewItem selectedItem in selectedItems)
{
selectedParagraphs.Add(_subtitle.Paragraphs[selectedItem.Index]);
}
}
else if (selectedItems.Count == 1)
{
// use first selected index and forward
var idx = selectedItems[0].Index;
while (idx < _subtitle.Paragraphs.Count)
{
selectedParagraphs.Add(_subtitle.Paragraphs[idx]);
idx++;
}
}
else
{
// use all
selectedParagraphs = _subtitle.Paragraphs;
}
return selectedParagraphs;
}
private void FillTranslatedText(Dictionary<int, string> targetTexts)
{
var lastIndex = 0;
foreach (var targetText in targetTexts)
{
var paragraphNumber = targetText.Key;
var paragraphTargetText = targetText.Value;
lastIndex = TranslatedSubtitle.Paragraphs.FindIndex(x => x.Number == paragraphNumber);
var cleanText = CleanText(paragraphTargetText, lastIndex);
TranslatedSubtitle.Paragraphs[lastIndex].Text = cleanText;
}
subtitleListViewTarget.BeginUpdate();
subtitleListViewTarget.Fill(TranslatedSubtitle);
subtitleListViewTarget.SelectIndexAndEnsureVisible(lastIndex);
subtitleListViewTarget.EndUpdate();
}
private string CleanText(string s, int index)
{
var cleanText = s.Replace("</p>", string.Empty).Trim();
var indexOfP = cleanText.IndexOf(SplitterString.Trim(), StringComparison.Ordinal);
if (indexOfP >= 0 && indexOfP < 4)
{
cleanText = cleanText.Remove(0, indexOfP);
}
cleanText = cleanText.Replace(SplitterString, string.Empty).Trim();
if (cleanText.Contains('\n') && !cleanText.Contains('\r'))
{
cleanText = cleanText.Replace("\n", Environment.NewLine);
}
cleanText = cleanText.Replace(" ...", "...");
cleanText = cleanText.Replace("<br/>", Environment.NewLine);
cleanText = cleanText.Replace("<br />", Environment.NewLine);
cleanText = cleanText.Replace("< br/>", Environment.NewLine);
cleanText = cleanText.Replace("<br/ >", Environment.NewLine);
cleanText = cleanText.Replace("<br / >", Environment.NewLine);
cleanText = cleanText.Replace("< br />", Environment.NewLine);
cleanText = cleanText.Replace("< br / >", Environment.NewLine);
cleanText = cleanText.Replace("< br/ >", Environment.NewLine);
cleanText = cleanText.Replace(Environment.NewLine + " ", Environment.NewLine);
cleanText = cleanText.Replace(" " + Environment.NewLine, Environment.NewLine);
var formatType = _subtitleFormat.GetType();
if (formatType == typeof(AdvancedSubStationAlpha) || formatType == typeof(SubStationAlpha))
{
cleanText = cleanText.Replace("{i1}", "{\\i1}");
cleanText = cleanText.Replace("{i0}", "{\\i0}");
cleanText = cleanText.Replace("{b1}", "{\\b1}");
cleanText = cleanText.Replace("{b0}", "{\\b0}");
cleanText = cleanText.Replace("{u1}", "{\\u1}");
cleanText = cleanText.Replace("{u0}", "{\\u0}");
cleanText = cleanText.Replace("{s1}", "{\\s1}");
cleanText = cleanText.Replace("{s0}", "{\\s0}");
cleanText = cleanText.Replace("{c&H", "{\\c&H");
cleanText = cleanText.Replace("{1&H", "{\\1c&H");
cleanText = cleanText.Replace("{2c&H", "{\\2c&H");
cleanText = cleanText.Replace("{3c&H", "{\\3c&H");
cleanText = cleanText.Replace("{4c&H", "{\\4c&H");
cleanText = cleanText.Replace("{alpha&H", "{\\alpha&H");
cleanText = cleanText.Replace("{1a&H", "{\\1a&H");
cleanText = cleanText.Replace("{2a&H", "{\\2a&H");
cleanText = cleanText.Replace("{3a&H", "{\\3a&H");
cleanText = cleanText.Replace("{4a&H", "{\\4a&H");
cleanText = cleanText.Replace("{fn", "{\\fn");
cleanText = cleanText.Replace("{fs", "{\\fs");
cleanText = cleanText.Replace("{an", "{\\an");
cleanText = cleanText.Replace("{be", "{\\be");
cleanText = cleanText.Replace("{pos", "{\\pos");
cleanText = cleanText.Replace("{fad", "{\\fad");
cleanText = cleanText.Replace("{move", "{\\move");
cleanText = cleanText.Replace("{fscx", "{\\fscx");
cleanText = cleanText.Replace("{fscy", "{\\fscy");
cleanText = cleanText.Replace("{bord", "{\\bord");
cleanText = cleanText.Replace("{xbord", "{\\xbord");
cleanText = cleanText.Replace("{ybord", "{\\ybord");
cleanText = cleanText.Replace("{shad", "{\\shad");
cleanText = cleanText.Replace("{xshad", "{\\xshad");
cleanText = cleanText.Replace("{yshad", "{\\yshad");
cleanText = cleanText.Replace("{fr", "{\\fr");
cleanText = cleanText.Replace("{fsp", "{\\fsp");
cleanText = cleanText.Replace("{fay", "{\\fay");
cleanText = cleanText.Replace("{fax", "{\\fax");
cleanText = cleanText.Replace("{org(", "{\\org(");
cleanText = cleanText.Replace("{t(", "{\\t(");
cleanText = cleanText.Replace("{clip", "{\\clip");
cleanText = cleanText.Replace("{iclip", "{\\iclip");
cleanText = cleanText.Replace("{blur", "{\\blur");
}
cleanText = cleanText.Replace("<I>", "<i>");
cleanText = cleanText.Replace("< I>", "<i>");
cleanText = cleanText.Replace("</ i>", "</i>");
cleanText = cleanText.Replace("</ I>", "</i>");
cleanText = cleanText.Replace("</I>", "</i>");
cleanText = cleanText.Replace("< i >", "<i>");
if (cleanText.StartsWith("<i> ", StringComparison.Ordinal))
{
cleanText = cleanText.Remove(3, 1);
}
if (cleanText.EndsWith(" </i>", StringComparison.Ordinal))
{
cleanText = cleanText.Remove(cleanText.Length - 5, 1);
}
cleanText = cleanText.Replace(Environment.NewLine + "<i> ", Environment.NewLine + "<i>");
cleanText = cleanText.Replace(" </i>" + Environment.NewLine, "</i>" + Environment.NewLine);
if (_autoSplit[index])
{
cleanText = Utilities.AutoBreakLine(cleanText);
}
if (Utilities.GetNumberOfLines(cleanText) == 1 && Utilities.GetNumberOfLines(_subtitle.Paragraphs[index].Text) == 2)
{
if (!_autoSplit[index])
{
cleanText = Utilities.AutoBreakLine(cleanText);
}
}
return cleanText;
}
public static void FillComboWithLanguages(NikseComboBox comboBox, IEnumerable<TranslationPair> languages)
{
comboBox.Items.Clear();
foreach (var language in languages)
{
comboBox.Items.Add(language);
}
}
private void ButtonOkClick(object sender, EventArgs e)
{
DialogResult = subtitleListViewTarget.Items.Count > 0 ? DialogResult.OK : DialogResult.Cancel;
}
private void FormTranslate_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape && labelPleaseWait.Visible == false)
{
DialogResult = DialogResult.Cancel;
}
else if (e.KeyCode == Keys.Escape && labelPleaseWait.Visible)
{
_breakTranslation = true;
e.SuppressKeyPress = true;
}
else if (e.KeyData == UiUtil.HelpKeys)
{
UiUtil.ShowHelp("#translation");
}
}
private void Translate_Resize(object sender, EventArgs e)
{
int width = (Width / 2) - (subtitleListViewSource.Left * 3) + 19;
subtitleListViewSource.Width = width;
subtitleListViewTarget.Width = width;
int height = Height - (subtitleListViewSource.Top + buttonTranslate.Height + 60);
subtitleListViewSource.Height = height;
subtitleListViewTarget.Height = height;
comboBoxSource.Left = subtitleListViewSource.Left + (subtitleListViewSource.Width - comboBoxSource.Width);
labelSource.Left = comboBoxSource.Left - 5 - labelSource.Width;
subtitleListViewTarget.Left = width + (subtitleListViewSource.Left * 2);
labelTarget.Left = subtitleListViewTarget.Left;
comboBoxTarget.Left = labelTarget.Left + labelTarget.Width + 5;
buttonTranslate.Left = comboBoxTarget.Left + comboBoxTarget.Width + 9;
labelPleaseWait.Left = buttonTranslate.Left + buttonTranslate.Width + 9;
progressBar1.Left = labelPleaseWait.Left;
progressBar1.Width = subtitleListViewTarget.Width - (progressBar1.Left - subtitleListViewTarget.Left);
}
private static void SyncListViews(ListView listViewSelected, SubtitleListView listViewOther)
{
if (listViewSelected.SelectedItems.Count > 0)
{
var first = listViewSelected.TopItem.Index;
int index = listViewSelected.SelectedItems[0].Index;
if (index < listViewOther.Items.Count)
{
listViewOther.SelectIndexAndEnsureVisible(index, false);
if (first >= 0)
{
listViewOther.TopItem = listViewOther.Items[first];
}
}
}
}
private void subtitleListViewSource_DoubleClick(object sender, EventArgs e)
{
SyncListViews(subtitleListViewSource, subtitleListViewTarget);
}
private void subtitleListViewTarget_DoubleClick(object sender, EventArgs e)
{
SyncListViews(subtitleListViewTarget, subtitleListViewSource);
}
public string GetFileNameWithTargetLanguage(string oldFileName, string videoFileName, Subtitle oldSubtitle, SubtitleFormat subtitleFormat)
{
if (!string.IsNullOrEmpty(_targetLanguageIsoCode))
{
if (!string.IsNullOrEmpty(videoFileName))
{
return Path.GetFileNameWithoutExtension(videoFileName) + "." + _targetLanguageIsoCode.ToLowerInvariant() + subtitleFormat.Extension;
}
if (!string.IsNullOrEmpty(oldFileName))
{
var s = Path.GetFileNameWithoutExtension(oldFileName);
if (oldSubtitle != null)
{
var lang = "." + LanguageAutoDetect.AutoDetectGoogleLanguage(oldSubtitle);
if (lang.Length == 3 && s.EndsWith(lang, StringComparison.OrdinalIgnoreCase))
{
s = s.Remove(s.Length - 3);
}
}
return s + "." + _targetLanguageIsoCode.ToLowerInvariant() + subtitleFormat.Extension;
}
}
return null;
}
private void GenericTranslate_FormClosing(object sender, FormClosingEventArgs e)
{
Configuration.Settings.Tools.TranslateLastService = _translationService.GetType().ToString();
Configuration.Settings.Tools.TranslateMergeStrategy = comboBoxParagraphHandling.Text;
}
private void comboBoxTranslationServices_SelectedIndexChanged(object sender, EventArgs e)
{
_translationService = (ITranslationService)comboBoxTranslationServices.SelectedItem;
SetupLanguageSettings();
EvaluateTranslateButtonStatus();
}
private void GenericTranslate_Shown(object sender, EventArgs e)
{
buttonTranslate.Focus();
}
}
public class GoogleTranslationInitializer
{
public static GoogleTranslationService Init(IWin32Window owner = null)
{
GoogleTranslationService googleTranslationService = null;
try
{
if (string.IsNullOrEmpty(Configuration.Settings.Tools.GoogleApiV2Key))
{
googleTranslationService = new GoogleTranslationService(new GoogleTranslator1());
}
else
{
googleTranslationService = new GoogleTranslationService(new GoogleTranslator2(Configuration.Settings.Tools.GoogleApiV2Key));
}
}
catch (Exception e)
{
if (owner != null)
{
MessageBox.Show(e.Message + Environment.NewLine + e.InnerException?.Source + ": " + e.InnerException?.Message, "GoogleTranslationService");
}
}
return googleTranslationService;
}
}
public class MicrosoftTranslationInitializer
{
public static MicrosoftTranslationService Init(bool showError = false)
{
if (string.IsNullOrEmpty(Configuration.Settings.Tools.MicrosoftTranslatorApiKey))
{
if (showError)
{
MessageBox.Show(LanguageSettings.Current.GoogleTranslate.MsClientSecretNeeded, "MicrosoftTranslationService");
}
return null;
}
MicrosoftTranslationService microsoftTranslationService = null;
try
{
microsoftTranslationService = new MicrosoftTranslationService(Configuration.Settings.Tools.MicrosoftTranslatorApiKey, Configuration.Settings.Tools.MicrosoftTranslatorTokenEndpoint, Configuration.Settings.Tools.MicrosoftTranslatorCategory);
}
catch (Exception e)
{
if (showError)
{
MessageBox.Show(e.Message + Environment.NewLine + e.InnerException?.Source + ": " + e.InnerException?.Message, "MicrosoftTranslationService");
}
}
return microsoftTranslationService;
}
}
}

View File

@ -1,120 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -1,11 +1,11 @@
using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.AutoTranslate;
using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.Translate;
using Nikse.SubtitleEdit.Core.Translate.Service;
using Nikse.SubtitleEdit.Forms.Translate;
using Nikse.SubtitleEdit.Logic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
namespace Nikse.SubtitleEdit.Forms
@ -14,8 +14,8 @@ namespace Nikse.SubtitleEdit.Forms
{
public string TranslatedText { get; set; }
private GoogleTranslationService _googleTranslationService;
private MicrosoftTranslationService _microsoftTranslationService;
private IAutoTranslator _googleTranslationService;
private IAutoTranslator _microsoftTranslationService;
private string _toLanguage;
private string _fromLanguage;
@ -40,55 +40,31 @@ namespace Nikse.SubtitleEdit.Forms
buttonMicrosoft.Text = string.Empty;
}
private void InitLanguageComboboxes()
private void InitLanguageComboBoxes()
{
var googleSourceLanguages = new List<TranslationPair>();
var googleTargetLanguages = new List<TranslationPair>();
var googleSourceLanguages = _googleTranslationService.GetSupportedSourceLanguages();
var googleTargetLanguages = _googleTranslationService.GetSupportedTargetLanguages();
var microsoftSourceLanguages = new List<TranslationPair>();
var microsoftTargetLanguages = new List<TranslationPair>();
var microsoftSourceLanguages = _microsoftTranslationService.GetSupportedSourceLanguages();
var microsoftTargetLanguages = _microsoftTranslationService.GetSupportedTargetLanguages();
var targetLanguages = googleTargetLanguages.Intersect(microsoftTargetLanguages);
var fromLanguages = googleSourceLanguages.Intersect(microsoftSourceLanguages);
if (_googleTranslationService != null)
{
googleSourceLanguages = _googleTranslationService.GetSupportedSourceLanguages();
googleTargetLanguages = _googleTranslationService.GetSupportedSourceLanguages();
}
AutoTranslate.FillComboWithLanguages(comboBoxFrom, fromLanguages);
AutoTranslate.FillComboWithLanguages(comboBoxTo, targetLanguages);
if (_microsoftTranslationService != null)
{
microsoftSourceLanguages = _microsoftTranslationService.GetSupportedSourceLanguages();
microsoftTargetLanguages = _microsoftTranslationService.GetSupportedSourceLanguages();
}
IEnumerable<TranslationPair> targetLanguages;
IEnumerable<TranslationPair> fromLanguages;
if (_googleTranslationService == null || _microsoftTranslationService == null)
{
targetLanguages = googleTargetLanguages.Union(microsoftTargetLanguages);
fromLanguages = googleSourceLanguages.Union(microsoftSourceLanguages);
}
else
{
targetLanguages = googleTargetLanguages.Intersect(microsoftTargetLanguages);
fromLanguages = googleSourceLanguages.Intersect(microsoftSourceLanguages);
}
GenericTranslate.FillComboWithLanguages(comboBoxFrom, fromLanguages);
GenericTranslate.FillComboWithLanguages(comboBoxTo, targetLanguages);
GenericTranslate.SelectLanguageCode(comboBoxFrom, _fromLanguage);
GenericTranslate.SelectLanguageCode(comboBoxTo, _toLanguage);
AutoTranslate.SelectLanguageCode(comboBoxFrom, _fromLanguage);
AutoTranslate.SelectLanguageCode(comboBoxTo, _toLanguage);
}
internal void InitializeFromLanguage(string defaultFromLanguage)
{
_toLanguage = Configuration.Settings.Tools.GoogleTranslateLastTargetLanguage;
_fromLanguage = defaultFromLanguage;
if (_toLanguage == defaultFromLanguage)
{
foreach (string s in Utilities.GetDictionaryLanguages())
foreach (var s in Utilities.GetDictionaryLanguages())
{
string temp = s.Replace("[", string.Empty).Replace("]", string.Empty);
if (temp.Length > 4)
@ -112,10 +88,13 @@ namespace Nikse.SubtitleEdit.Forms
private void GoogleOrMicrosoftTranslate_Shown(object sender, EventArgs e)
{
_googleTranslationService = GoogleTranslationInitializer.Init();
_microsoftTranslationService = MicrosoftTranslationInitializer.Init(true);
_googleTranslationService = new GoogleTranslateV1();
_googleTranslationService.Initialize();
InitLanguageComboboxes();
_microsoftTranslationService = new MicrosoftTranslator();
_microsoftTranslationService.Initialize();
InitLanguageComboBoxes();
Refresh();
Translate();
@ -137,12 +116,12 @@ namespace Nikse.SubtitleEdit.Forms
if (_googleTranslationService != null)
{
buttonGoogle.Text = _googleTranslationService.Translate(_fromLanguage, _toLanguage, new List<Paragraph> { new Paragraph { Text = textBoxSourceText.Text } }).FirstOrDefault();
buttonGoogle.Text = _googleTranslationService.Translate(textBoxSourceText.Text, _fromLanguage, _toLanguage, CancellationToken.None).Result;
}
if (_microsoftTranslationService != null)
{
var result = _microsoftTranslationService.Translate(_fromLanguage, _toLanguage, new List<Paragraph> { new Paragraph { Text = textBoxSourceText.Text } });
buttonMicrosoft.Text = result[0];
var result = _microsoftTranslationService.Translate(textBoxSourceText.Text, _fromLanguage, _toLanguage, CancellationToken.None).Result;
buttonMicrosoft.Text = result;
}
}
}

View File

@ -734,12 +734,6 @@
<Compile Include="Forms\Translate\AutoTranslate.Designer.cs">
<DependentUpon>AutoTranslate.cs</DependentUpon>
</Compile>
<Compile Include="Forms\Translate\GenericTranslate.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Forms\Translate\GenericTranslate.Designer.cs">
<DependentUpon>GenericTranslate.cs</DependentUpon>
</Compile>
<Compile Include="Forms\ImportCdg.cs">
<SubType>Form</SubType>
</Compile>
@ -1572,10 +1566,10 @@
<Compile Include="Forms\WaveformUndocked.Designer.cs">
<DependentUpon>WaveformUndocked.cs</DependentUpon>
</Compile>
<Compile Include="Forms\GoogleOrMicrosoftTranslate.cs">
<Compile Include="Forms\Translate\GoogleOrMicrosoftTranslate.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Forms\GoogleOrMicrosoftTranslate.Designer.cs">
<Compile Include="Forms\Translate\GoogleOrMicrosoftTranslate.Designer.cs">
<DependentUpon>GoogleOrMicrosoftTranslate.cs</DependentUpon>
</Compile>
<Compile Include="Forms\TextPrompt.cs">
@ -2008,10 +2002,6 @@
<EmbeddedResource Include="Forms\Translate\AutoTranslate.resx">
<DependentUpon>AutoTranslate.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Forms\Translate\GenericTranslate.resx">
<DependentUpon>GenericTranslate.cs</DependentUpon>
<SubType>Designer</SubType>
</EmbeddedResource>
<EmbeddedResource Include="Forms\ImportCdg.resx">
<DependentUpon>ImportCdg.cs</DependentUpon>
</EmbeddedResource>
@ -2413,7 +2403,7 @@
<EmbeddedResource Include="Forms\WaveformUndocked.resx">
<DependentUpon>WaveformUndocked.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Forms\GoogleOrMicrosoftTranslate.resx">
<EmbeddedResource Include="Forms\Translate\GoogleOrMicrosoftTranslate.resx">
<DependentUpon>GoogleOrMicrosoftTranslate.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Forms\TextPrompt.resx">