Skip to content

Commit

Permalink
Refactor plugin structure and enhance file handling
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ivandrofly committed Nov 24, 2024
1 parent fe7efc3 commit ff42be0
Show file tree
Hide file tree
Showing 4 changed files with 103 additions and 97 deletions.
81 changes: 70 additions & 11 deletions source/SaveAllFormat/EntryPoint.cs
Original file line number Diff line number Diff line change
@@ -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))
Expand All @@ -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)
{
Expand All @@ -31,8 +48,50 @@ public override string DoAction(Form parentForm, string srtText, double frameRat
}

return string.Empty;

}
}

public interface IPlugin
{
/// <summary>
/// Name of the plug-in
/// </summary>
string Name { get; }

/// <summary>
/// Text used in Subtitle Edit menu
/// </summary>
string Text { get; }

/// <summary>
/// Version number of plugin
/// </summary>
decimal Version { get; }

/// <summary>
/// Description of what plugin does
/// </summary>
string Description { get; }

/// <summary>
/// Can be one of these: file, tool, sync, translate, spellcheck
/// </summary>
string ActionType { get; }

/// <summary>
/// Shortcut used to active plugin - e.g. Control+Shift+F9
/// </summary>
string Shortcut { get; }

/// <summary>
/// This action of callsed when Subtitle Edit calls plugin
/// </summary>
string DoAction(Form parentForm,
string srtText,
double frameRate,
string uiLineBreak,
string file,
string videoFile,
string rawText);
}
}
}
7 changes: 6 additions & 1 deletion source/SaveAllFormat/ExportAllFormats.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<UseWindowsForms>true</UseWindowsForms>
<ImportWindowsDesktopTargets>true</ImportWindowsDesktopTargets>
<AssemblyVersion>2.0.0</AssemblyVersion>
<FileVersion>2.0.0</FileVersion>
</PropertyGroup>
<PropertyGroup />
<PropertyGroup>
<!-- <PostBuildEvent>copy $(TargetDir)\exportallformats.dll "%25appdata%25\Subtitle Edit\Plugins\"-->
<!--copy $(TargetDir)\exportallformats.pdb "%25appdata%25\Subtitle Edit\Plugins\"</PostBuildEvent>-->
</PropertyGroup>
<Import Project="..\Plugin-Shared\Plugin-Shared.projitems" Label="Shared" />
<ItemGroup>
<PackageReference Include="libse" />
</ItemGroup>
<!-- <Import Project="..\Plugin-Shared\Plugin-Shared.projitems" Label="Shared" />-->
</Project>
101 changes: 27 additions & 74 deletions source/SaveAllFormat/Main.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
{
Expand All @@ -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();
}
Expand All @@ -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<object>)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<string> 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<object>)prop.GetValue(_parentForm, null);
var listExtension = new HashSet<string>();

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);
Expand All @@ -170,4 +123,4 @@ private static string GetExportFileName(string file, string formatName, string e
return newName;
}
}
}
}
11 changes: 0 additions & 11 deletions source/SaveAllFormat/Utils/StringUtils.cs

This file was deleted.

0 comments on commit ff42be0

Please sign in to comment.