Skip to content

Commit ff42be0

Browse files
committed
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.
1 parent fe7efc3 commit ff42be0

File tree

4 files changed

+103
-97
lines changed

4 files changed

+103
-97
lines changed

source/SaveAllFormat/EntryPoint.cs

Lines changed: 70 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,20 @@
1-
using System.Windows.Forms;
1+
using System.IO;
2+
using System.Windows.Forms;
3+
using Nikse.SubtitleEdit.Core.Common;
4+
using Nikse.SubtitleEdit.Core.SubtitleFormats;
25

36
namespace Nikse.SubtitleEdit.PluginLogic
47
{
5-
public class ExportAllFormats : EntryPointBase
8+
public class ExportAllFormats : IPlugin
69
{
7-
public ExportAllFormats()
8-
: base("Export to all formats", "Export to all formats (non binary)", 1.2m, "Export current subtitle to all available text format.", "file", string.Empty)
9-
{
10-
}
10+
public string Name { get; } = "Export all formats";
11+
public string Text { get; } = "Export all formats";
12+
public decimal Version { get; } = 2.0m;
13+
public string Description { get; } = "Export current subtitle to all available text format.";
14+
public string ActionType { get; } = "file";
15+
public string Shortcut { get; } = string.Empty;
1116

12-
public override string DoAction(Form parentForm, string srtText, double frameRate, string uiLineBreak, string file, string videoFile, string rawText)
17+
public string DoAction(Form parentForm, string srtText, double frameRate, string uiLineBreak, string file, string videoFile, string rawText)
1318
{
1419
// subtitle not loaded
1520
if (string.IsNullOrWhiteSpace(srtText))
@@ -18,11 +23,23 @@ public override string DoAction(Form parentForm, string srtText, double frameRat
1823
return string.Empty;
1924
}
2025

26+
if (!File.Exists(file))
27+
{
28+
MessageBox.Show("File not found: " + file, "File not found", MessageBoxButtons.OK, MessageBoxIcon.Error);
29+
return string.Empty;
30+
}
31+
32+
var subtitle = Subtitle.Parse(file);
33+
if (subtitle is null)
34+
{
35+
MessageBox.Show("Could not parse subtitle file: " + file, "Could not parse subtitle file", MessageBoxButtons.OK, MessageBoxIcon.Error);
36+
return string.Empty;
37+
}
2138
// initialize context
22-
Init(srtText, uiLineBreak, file);
39+
// Init(srtText, uiLineBreak, file);
2340

2441
// show main form
25-
using (var main = new Main(parentForm, file))
42+
using (var main = new Main(parentForm, subtitle))
2643
{
2744
if (main.ShowDialog(parentForm) == DialogResult.Cancel)
2845
{
@@ -31,8 +48,50 @@ public override string DoAction(Form parentForm, string srtText, double frameRat
3148
}
3249

3350
return string.Empty;
34-
3551
}
52+
}
53+
54+
public interface IPlugin
55+
{
56+
/// <summary>
57+
/// Name of the plug-in
58+
/// </summary>
59+
string Name { get; }
60+
61+
/// <summary>
62+
/// Text used in Subtitle Edit menu
63+
/// </summary>
64+
string Text { get; }
65+
66+
/// <summary>
67+
/// Version number of plugin
68+
/// </summary>
69+
decimal Version { get; }
70+
71+
/// <summary>
72+
/// Description of what plugin does
73+
/// </summary>
74+
string Description { get; }
75+
76+
/// <summary>
77+
/// Can be one of these: file, tool, sync, translate, spellcheck
78+
/// </summary>
79+
string ActionType { get; }
80+
81+
/// <summary>
82+
/// Shortcut used to active plugin - e.g. Control+Shift+F9
83+
/// </summary>
84+
string Shortcut { get; }
3685

86+
/// <summary>
87+
/// This action of callsed when Subtitle Edit calls plugin
88+
/// </summary>
89+
string DoAction(Form parentForm,
90+
string srtText,
91+
double frameRate,
92+
string uiLineBreak,
93+
string file,
94+
string videoFile,
95+
string rawText);
3796
}
38-
}
97+
}

source/SaveAllFormat/ExportAllFormats.csproj

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,16 @@
44
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
55
<UseWindowsForms>true</UseWindowsForms>
66
<ImportWindowsDesktopTargets>true</ImportWindowsDesktopTargets>
7+
<AssemblyVersion>2.0.0</AssemblyVersion>
8+
<FileVersion>2.0.0</FileVersion>
79
</PropertyGroup>
810
<PropertyGroup />
911
<PropertyGroup>
1012
<!-- <PostBuildEvent>copy $(TargetDir)\exportallformats.dll "%25appdata%25\Subtitle Edit\Plugins\"-->
1113
<!--copy $(TargetDir)\exportallformats.pdb "%25appdata%25\Subtitle Edit\Plugins\"</PostBuildEvent>-->
1214
</PropertyGroup>
13-
<Import Project="..\Plugin-Shared\Plugin-Shared.projitems" Label="Shared" />
15+
<ItemGroup>
16+
<PackageReference Include="libse" />
17+
</ItemGroup>
18+
<!-- <Import Project="..\Plugin-Shared\Plugin-Shared.projitems" Label="Shared" />-->
1419
</Project>

source/SaveAllFormat/Main.cs

Lines changed: 27 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,18 @@
55
using System.Linq;
66
using System.Reflection;
77
using System.Text;
8+
using System.Threading;
89
using System.Threading.Tasks;
910
using System.Windows.Forms;
11+
using Nikse.SubtitleEdit.Core.Common;
12+
using Nikse.SubtitleEdit.Core.SubtitleFormats;
1013

1114
namespace Nikse.SubtitleEdit.PluginLogic
1215
{
1316
public partial class Main : Form
1417
{
1518
private readonly Form _parentForm;
19+
private readonly Subtitle _subtitle;
1620
private readonly string _file;
1721
private string _exportLocation;
1822
private volatile string _selExtension;
@@ -21,28 +25,21 @@ public partial class Main : Form
2125
// todo: add support to export specific format e.g: xml, txt...
2226
// todo: add ui with options
2327

24-
public Main(Form parentForm, string file)
28+
public Main(Form parentForm, Subtitle subtitle)
2529
{
30+
InitializeComponent();
31+
2632
if (parentForm is null)
2733
{
2834
throw new ArgumentNullException(nameof(parentForm));
2935
}
3036

31-
if (string.IsNullOrWhiteSpace(file))
32-
{
33-
throw new ArgumentException($"'{nameof(file)}' cannot be null or whitespace", nameof(file));
34-
}
35-
36-
InitializeComponent();
3737
progressBar1.Visible = false;
3838
_parentForm = parentForm;
39-
_file = file;
39+
_subtitle = subtitle;
4040

4141
// event handlers
42-
buttonCancel.Click += delegate
43-
{
44-
DialogResult = DialogResult.Cancel;
45-
};
42+
buttonCancel.Click += delegate { DialogResult = DialogResult.Cancel; };
4643

4744
textBoxLocation.DoubleClick += delegate
4845
{
@@ -57,10 +54,11 @@ public Main(Form parentForm, string file)
5754

5855
comboBoxExtension.BeginUpdate();
5956
comboBoxExtension.Items.Add("all");
60-
foreach (var extension in GetAvailableExtensions())
57+
foreach (var extension in SubtitleFormat.AllSubtitleFormats.Select(f => f.Extension))
6158
{
6259
comboBoxExtension.Items.Add(extension);
6360
}
61+
6462
comboBoxExtension.SelectedIndex = 0;
6563
comboBoxExtension.EndUpdate();
6664
}
@@ -76,86 +74,41 @@ private void buttonBrowse_Click(object sender, EventArgs e)
7674
return;
7775
}
7876

79-
_exportLocation = folderBrowse.SelectedPath;
80-
textBoxLocation.Text = _exportLocation;
77+
textBoxLocation.Text = _exportLocation = folderBrowse.SelectedPath;
8178
}
8279
}
8380

84-
private void buttonExport_Click(object sender, EventArgs e)
81+
private async void buttonExport_Click(object sender, EventArgs e)
8582
{
86-
// validate output path
8783
if (!Path.IsPathRooted(_exportLocation))
8884
{
8985
MessageBox.Show("Invalid output path", "Invalid output", MessageBoxButtons.OK, MessageBoxIcon.Error);
9086
return;
9187
}
9288

93-
//progressBar1.Style = ProgressBarStyle.Continuous;
94-
//progressBar1.Visible = true;
95-
96-
var subtitleFormat = Utils.AssemblyUtils.GetLibse().GetType("Nikse.SubtitleEdit.Core.SubtitleFormats.SubtitleFormat");
97-
var prop = subtitleFormat.GetProperty("AllSubtitleFormats", BindingFlags.Public | BindingFlags.Static);
98-
var subtitle = _parentForm.GetType().GetField("_subtitle", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(_parentForm);
99-
100-
//var parallelOptions = new ParallelOptions();
101-
//TaskScheduler.FromCurrentSynchronizationContext();
102-
// run export parallel (faster)
103-
10489
_selExtension = comboBoxExtension.SelectedItem.ToString();
105-
Parallel.ForEach((IEnumerable<object>)prop.GetValue(default, default), format =>
90+
await Task.Run(() =>
10691
{
107-
try
92+
ParallelLoopResult parallelLoopResult = Parallel.ForEach(SubtitleFormat.AllSubtitleFormats, exportFormat =>
10893
{
109-
var name = format.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance).GetValue(format, default);
110-
var extension = (string)format.GetType().GetProperty("Extension", BindingFlags.Public | BindingFlags.Instance).GetValue(format, default);
111-
112-
// filter by extension
113-
if (_selExtension.Equals("all") == false && !_selExtension.Equals(extension, StringComparison.OrdinalIgnoreCase))
94+
try
11495
{
115-
return;
96+
var outputFileName = Path.Combine(_exportLocation, GetExportFileName(_subtitle.FileName, exportFormat.Name, exportFormat.Extension));
97+
var content = exportFormat.ToText(_subtitle, _subtitle.FileName);
98+
File.WriteAllText(outputFileName, content, Encoding.UTF8);
11699
}
100+
catch (Exception ex)
101+
{
102+
Trace.WriteLine(ex.Message);
103+
}
104+
});
105+
SpinWait.SpinUntil(() => parallelLoopResult.IsCompleted);
106+
}).ConfigureAwait(true);
117107

118-
var mi = format.GetType().GetMethod("ToText", BindingFlags.Public | BindingFlags.Instance /*| BindingFlags.DeclaredOnly*/, default, new Type[] { subtitle.GetType(), typeof(string) }, default);
119-
var result = (string)mi.Invoke(format, new[] { subtitle, name });
120-
File.WriteAllText(Path.Combine(_exportLocation, GetExportFileName(_file, (string)name, extension)), result, Encoding.UTF8);
121-
}
122-
catch (Exception ex)
123-
{
124-
Trace.WriteLine(ex.Message);
125-
}
126-
});
127-
128-
//progressBar1.Style = ProgressBarStyle.Blocks;
129-
//progressBar1.Visible = false;
130-
131-
// Explorer.ex "C:\Demo"
132108
Process.Start("explorer", $"\"{_exportLocation}\"");
133109
MessageBox.Show(_parentForm, "Export completed!", "Subtitle exported", MessageBoxButtons.OK, MessageBoxIcon.Information);
134110
}
135111

136-
private IEnumerable<string> GetAvailableExtensions()
137-
{
138-
var assembly = _parentForm.GetType().Assembly;
139-
if (assembly == null)
140-
{
141-
throw new InvalidCastException();
142-
}
143-
144-
var assemblyLibse = Utils.AssemblyUtils.GetLibse();
145-
var subtitleFormat = assemblyLibse.GetType("Nikse.SubtitleEdit.Core.SubtitleFormats.SubtitleFormat");
146-
var prop = subtitleFormat.GetProperty("AllSubtitleFormats", BindingFlags.Public | BindingFlags.Static);
147-
var formats = (IEnumerable<object>)prop.GetValue(_parentForm, null);
148-
var listExtension = new HashSet<string>();
149-
150-
foreach (var item in formats)
151-
{
152-
var extension = (string)item.GetType().GetProperty("Extension").GetValue(item, null);
153-
listExtension.Add(extension);
154-
}
155-
156-
return listExtension;
157-
}
158-
159112
private static string GetExportFileName(string file, string formatName, string extension)
160113
{
161114
string fileName = Path.GetFileNameWithoutExtension(file);
@@ -170,4 +123,4 @@ private static string GetExportFileName(string file, string formatName, string e
170123
return newName;
171124
}
172125
}
173-
}
126+
}

source/SaveAllFormat/Utils/StringUtils.cs

Lines changed: 0 additions & 11 deletions
This file was deleted.

0 commit comments

Comments
 (0)