From bb560cd9db391a5f8a4261aec657284e502ad49e Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Wed, 22 Nov 2023 16:02:31 +0100 Subject: [PATCH] Update test plugin to properly release the resources when being stopped --- src/DesktopMagicPlugin.Test/PluginScript.cs | 45 +++++++++++++++------ 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/src/DesktopMagicPlugin.Test/PluginScript.cs b/src/DesktopMagicPlugin.Test/PluginScript.cs index e51e1d2..2d59030 100644 --- a/src/DesktopMagicPlugin.Test/PluginScript.cs +++ b/src/DesktopMagicPlugin.Test/PluginScript.cs @@ -6,14 +6,13 @@ using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; +using System.Threading; using System.Threading.Tasks; namespace DesktopMagic.PluginTest; public class GifPlugin : Plugin { - private const string SaveFilePath = "gifPath.txt"; - [Setting("gif-path", "Gif path:")] private readonly TextBox input = new TextBox(""); @@ -22,22 +21,33 @@ public class GifPlugin : Plugin private readonly List bitmaps = []; + private readonly CancellationTokenSource cancellationTokenSource; private int frameCount = -1; - public override void Start() + public GifPlugin() + { + cancellationTokenSource = new CancellationTokenSource(); + } + + public override async void Start() { input.OnValueChanged += Input_OnValueChanged; - if (File.Exists(SaveFilePath)) - { - input.Value = File.ReadAllText(SaveFilePath); - } + + await LoadGif(); + } + + public override void Stop() + { + cancellationTokenSource.Cancel(); + + bitmaps.Clear(); } public override Bitmap Main() { if (bitmaps.Count == 0) { - return new Bitmap(1, 1); + return null; } frameCount++; @@ -50,9 +60,14 @@ public class GifPlugin : Plugin return bitmaps[frameCount]; } - private void Input_OnValueChanged() + private async void Input_OnValueChanged() { - _ = Task.Run(() => + await LoadGif(); + } + + private Task LoadGif() + { + return Task.Run(() => { try { @@ -63,15 +78,19 @@ public class GifPlugin : Plugin PropertyItem item = gif.GetPropertyItem(0x5100); // FrameDelay in libgdiplus - UpdateInterval = (item.Value[0] + item.Value[1] * 256) * 10; //FrameDelay in ms + UpdateInterval = (item.Value[0] + (item.Value[1] * 256)) * 10; //FrameDelay in ms bitmaps.Clear(); for (int i = 0; i < gif.GetFrameCount(FrameDimension.Time); i++) { + cancellationTokenSource.Token.ThrowIfCancellationRequested(); + _ = gif.SelectActiveFrame(FrameDimension.Time, i); bitmaps.Add(new Bitmap(gif)); + + info.Value = $"Loading frame {i + 1} of {gif.GetFrameCount(FrameDimension.Time)}"; } - File.WriteAllText(SaveFilePath, input.Value); + info.Value = string.Empty; } else @@ -83,6 +102,6 @@ public class GifPlugin : Plugin { info.Value = $"Error: {ex.Message}"; } - }); + }, cancellationTokenSource.Token); } } \ No newline at end of file