From 590d96da053ce95e3d92e8229c7e1d0d19e3959b Mon Sep 17 00:00:00 2001 From: Ivandro Jao Date: Sun, 24 Nov 2024 15:22:20 +0000 Subject: [PATCH] Refactor plugin structure and enhance file handling Removed unused StringUtils.cs and modified EntryPoint to implement IPlugin interface. Updated Main.cs to improve file import and error handling, leveraging Subtitle class and async export functionality for better performance. --- source/SaveAllFormat/EntryPoint.cs | 81 +++++++++++++-- source/SaveAllFormat/ExportAllFormats.csproj | 7 +- source/SaveAllFormat/Main.cs | 101 +++++-------------- source/SaveAllFormat/Utils/StringUtils.cs | 11 -- 4 files changed, 103 insertions(+), 97 deletions(-) delete mode 100644 source/SaveAllFormat/Utils/StringUtils.cs diff --git a/source/SaveAllFormat/EntryPoint.cs b/source/SaveAllFormat/EntryPoint.cs index a363b1b7..9dc9c98a 100644 --- a/source/SaveAllFormat/EntryPoint.cs +++ b/source/SaveAllFormat/EntryPoint.cs @@ -1,15 +1,20 @@ -using System.Windows.Forms; +using System.IO; +using System.Windows.Forms; +using Nikse.SubtitleEdit.Core.Common; +using Nikse.SubtitleEdit.Core.SubtitleFormats; namespace Nikse.SubtitleEdit.PluginLogic { - public class ExportAllFormats : EntryPointBase + public class ExportAllFormats : IPlugin { - public ExportAllFormats() - : base("Export to all formats", "Export to all formats (non binary)", 1.2m, "Export current subtitle to all available text format.", "file", string.Empty) - { - } + public string Name { get; } = "Export all formats"; + public string Text { get; } = "Export all formats"; + public decimal Version { get; } = 2.0m; + public string Description { get; } = "Export current subtitle to all available text format."; + public string ActionType { get; } = "file"; + public string Shortcut { get; } = string.Empty; - public override string DoAction(Form parentForm, string srtText, double frameRate, string uiLineBreak, string file, string videoFile, string rawText) + public string DoAction(Form parentForm, string srtText, double frameRate, string uiLineBreak, string file, string videoFile, string rawText) { // subtitle not loaded if (string.IsNullOrWhiteSpace(srtText)) @@ -18,11 +23,23 @@ public override string DoAction(Form parentForm, string srtText, double frameRat return string.Empty; } + if (!File.Exists(file)) + { + MessageBox.Show("File not found: " + file, "File not found", MessageBoxButtons.OK, MessageBoxIcon.Error); + return string.Empty; + } + + var subtitle = Subtitle.Parse(file); + if (subtitle is null) + { + MessageBox.Show("Could not parse subtitle file: " + file, "Could not parse subtitle file", MessageBoxButtons.OK, MessageBoxIcon.Error); + return string.Empty; + } // initialize context - Init(srtText, uiLineBreak, file); + // Init(srtText, uiLineBreak, file); // show main form - using (var main = new Main(parentForm, file)) + using (var main = new Main(parentForm, subtitle)) { if (main.ShowDialog(parentForm) == DialogResult.Cancel) { @@ -31,8 +48,50 @@ public override string DoAction(Form parentForm, string srtText, double frameRat } return string.Empty; - } + } + + public interface IPlugin + { + /// + /// Name of the plug-in + /// + string Name { get; } + + /// + /// Text used in Subtitle Edit menu + /// + string Text { get; } + + /// + /// Version number of plugin + /// + decimal Version { get; } + + /// + /// Description of what plugin does + /// + string Description { get; } + + /// + /// Can be one of these: file, tool, sync, translate, spellcheck + /// + string ActionType { get; } + + /// + /// Shortcut used to active plugin - e.g. Control+Shift+F9 + /// + string Shortcut { get; } + /// + /// This action of callsed when Subtitle Edit calls plugin + /// + string DoAction(Form parentForm, + string srtText, + double frameRate, + string uiLineBreak, + string file, + string videoFile, + string rawText); } -} +} \ No newline at end of file diff --git a/source/SaveAllFormat/ExportAllFormats.csproj b/source/SaveAllFormat/ExportAllFormats.csproj index 7d2304e9..ad054fe6 100644 --- a/source/SaveAllFormat/ExportAllFormats.csproj +++ b/source/SaveAllFormat/ExportAllFormats.csproj @@ -4,11 +4,16 @@ false true true + 2.0.0 + 2.0.0 - + + + + \ No newline at end of file diff --git a/source/SaveAllFormat/Main.cs b/source/SaveAllFormat/Main.cs index 58b970ed..6b1c6602 100644 --- a/source/SaveAllFormat/Main.cs +++ b/source/SaveAllFormat/Main.cs @@ -5,14 +5,18 @@ using System.Linq; using System.Reflection; using System.Text; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; +using Nikse.SubtitleEdit.Core.Common; +using Nikse.SubtitleEdit.Core.SubtitleFormats; namespace Nikse.SubtitleEdit.PluginLogic { public partial class Main : Form { private readonly Form _parentForm; + private readonly Subtitle _subtitle; private readonly string _file; private string _exportLocation; private volatile string _selExtension; @@ -21,28 +25,21 @@ public partial class Main : Form // todo: add support to export specific format e.g: xml, txt... // todo: add ui with options - public Main(Form parentForm, string file) + public Main(Form parentForm, Subtitle subtitle) { + InitializeComponent(); + if (parentForm is null) { throw new ArgumentNullException(nameof(parentForm)); } - if (string.IsNullOrWhiteSpace(file)) - { - throw new ArgumentException($"'{nameof(file)}' cannot be null or whitespace", nameof(file)); - } - - InitializeComponent(); progressBar1.Visible = false; _parentForm = parentForm; - _file = file; + _subtitle = subtitle; // event handlers - buttonCancel.Click += delegate - { - DialogResult = DialogResult.Cancel; - }; + buttonCancel.Click += delegate { DialogResult = DialogResult.Cancel; }; textBoxLocation.DoubleClick += delegate { @@ -57,10 +54,11 @@ public Main(Form parentForm, string file) comboBoxExtension.BeginUpdate(); comboBoxExtension.Items.Add("all"); - foreach (var extension in GetAvailableExtensions()) + foreach (var extension in SubtitleFormat.AllSubtitleFormats.Select(f => f.Extension)) { comboBoxExtension.Items.Add(extension); } + comboBoxExtension.SelectedIndex = 0; comboBoxExtension.EndUpdate(); } @@ -76,86 +74,41 @@ private void buttonBrowse_Click(object sender, EventArgs e) return; } - _exportLocation = folderBrowse.SelectedPath; - textBoxLocation.Text = _exportLocation; + textBoxLocation.Text = _exportLocation = folderBrowse.SelectedPath; } } - private void buttonExport_Click(object sender, EventArgs e) + private async void buttonExport_Click(object sender, EventArgs e) { - // validate output path if (!Path.IsPathRooted(_exportLocation)) { MessageBox.Show("Invalid output path", "Invalid output", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - //progressBar1.Style = ProgressBarStyle.Continuous; - //progressBar1.Visible = true; - - var subtitleFormat = Utils.AssemblyUtils.GetLibse().GetType("Nikse.SubtitleEdit.Core.SubtitleFormats.SubtitleFormat"); - var prop = subtitleFormat.GetProperty("AllSubtitleFormats", BindingFlags.Public | BindingFlags.Static); - var subtitle = _parentForm.GetType().GetField("_subtitle", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(_parentForm); - - //var parallelOptions = new ParallelOptions(); - //TaskScheduler.FromCurrentSynchronizationContext(); - // run export parallel (faster) - _selExtension = comboBoxExtension.SelectedItem.ToString(); - Parallel.ForEach((IEnumerable)prop.GetValue(default, default), format => + await Task.Run(() => { - try + ParallelLoopResult parallelLoopResult = Parallel.ForEach(SubtitleFormat.AllSubtitleFormats, exportFormat => { - var name = format.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance).GetValue(format, default); - var extension = (string)format.GetType().GetProperty("Extension", BindingFlags.Public | BindingFlags.Instance).GetValue(format, default); - - // filter by extension - if (_selExtension.Equals("all") == false && !_selExtension.Equals(extension, StringComparison.OrdinalIgnoreCase)) + try { - return; + var outputFileName = Path.Combine(_exportLocation, GetExportFileName(_subtitle.FileName, exportFormat.Name, exportFormat.Extension)); + var content = exportFormat.ToText(_subtitle, _subtitle.FileName); + File.WriteAllText(outputFileName, content, Encoding.UTF8); } + catch (Exception ex) + { + Trace.WriteLine(ex.Message); + } + }); + SpinWait.SpinUntil(() => parallelLoopResult.IsCompleted); + }).ConfigureAwait(true); - var mi = format.GetType().GetMethod("ToText", BindingFlags.Public | BindingFlags.Instance /*| BindingFlags.DeclaredOnly*/, default, new Type[] { subtitle.GetType(), typeof(string) }, default); - var result = (string)mi.Invoke(format, new[] { subtitle, name }); - File.WriteAllText(Path.Combine(_exportLocation, GetExportFileName(_file, (string)name, extension)), result, Encoding.UTF8); - } - catch (Exception ex) - { - Trace.WriteLine(ex.Message); - } - }); - - //progressBar1.Style = ProgressBarStyle.Blocks; - //progressBar1.Visible = false; - - // Explorer.ex "C:\Demo" Process.Start("explorer", $"\"{_exportLocation}\""); MessageBox.Show(_parentForm, "Export completed!", "Subtitle exported", MessageBoxButtons.OK, MessageBoxIcon.Information); } - private IEnumerable GetAvailableExtensions() - { - var assembly = _parentForm.GetType().Assembly; - if (assembly == null) - { - throw new InvalidCastException(); - } - - var assemblyLibse = Utils.AssemblyUtils.GetLibse(); - var subtitleFormat = assemblyLibse.GetType("Nikse.SubtitleEdit.Core.SubtitleFormats.SubtitleFormat"); - var prop = subtitleFormat.GetProperty("AllSubtitleFormats", BindingFlags.Public | BindingFlags.Static); - var formats = (IEnumerable)prop.GetValue(_parentForm, null); - var listExtension = new HashSet(); - - foreach (var item in formats) - { - var extension = (string)item.GetType().GetProperty("Extension").GetValue(item, null); - listExtension.Add(extension); - } - - return listExtension; - } - private static string GetExportFileName(string file, string formatName, string extension) { string fileName = Path.GetFileNameWithoutExtension(file); @@ -170,4 +123,4 @@ private static string GetExportFileName(string file, string formatName, string e return newName; } } -} +} \ No newline at end of file diff --git a/source/SaveAllFormat/Utils/StringUtils.cs b/source/SaveAllFormat/Utils/StringUtils.cs deleted file mode 100644 index d8ae1bfb..00000000 --- a/source/SaveAllFormat/Utils/StringUtils.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Nikse.SubtitleEdit.PluginLogic.Utils -{ - class StringUtils - { - } -}