Skip to content

A Swiss Army knife for developers.

Fixed more bugs with Smart Detection and SandboxedFileReader

Etienne Baudoux851a1aba549d
diff --git a/src/app/dev/DevToys.Api/Core/SandboxedFileReader.cs b/src/app/dev/DevToys.Api/Core/SandboxedFileReader.cs
index 42413cf7a..c73706935 100644
--- a/src/app/dev/DevToys.Api/Core/SandboxedFileReader.cs
+++ b/src/app/dev/DevToys.Api/Core/SandboxedFileReader.cs
@@ -17,6 +17,12 @@ public abstract class SandboxedFileReader : IDisposable
private bool _disposed;
private List<Stream>? _fileAccesses;
+ public static SandboxedFileReader FromFileInfo(FileInfo fileInfo)
+ {
+ Guard.IsNotNull(fileInfo);
+ return new SimpleSandboxedFileReader(fileInfo);
+ }
+
/// <summary>
/// Initializes a new instance of the <see cref="SandboxedFileReader"/> class.
/// </summary>
diff --git a/src/app/dev/DevToys.Api/Core/SimpleSandboxedFileReader.cs b/src/app/dev/DevToys.Api/Core/SimpleSandboxedFileReader.cs
new file mode 100644
index 000000000..75c87a9fa
--- /dev/null
+++ b/src/app/dev/DevToys.Api/Core/SimpleSandboxedFileReader.cs
@@ -0,0 +1,43 @@
+namespace DevToys.Api;
+
+/// <summary>
+/// Represents a read-only access to a file on the file system.
+/// </summary>
+/// <remarks>
+/// The file can be read and accessed multiple times in parallel.
+/// In some cases, the file's resulting stream is non-seekable.
+/// Disposing the <see cref="SandboxedFileReader"/> will close the access to the file.
+/// </remarks>
+[DebuggerDisplay($"FileName = {{{nameof(FileName)}}}")]
+internal sealed class SimpleSandboxedFileReader : SandboxedFileReader
+{
+ private readonly FileInfo _fileInfo;
+
+ internal SimpleSandboxedFileReader(FileInfo fileInfo)
+ : base(fileInfo.Name)
+ {
+ if (!fileInfo.Exists)
+ {
+ throw new FileNotFoundException("Unable to find the indicated file.", fileInfo.FullName);
+ }
+
+ _fileInfo = fileInfo;
+ }
+
+ protected override ValueTask<Stream> OpenReadFileAsync(CancellationToken cancellationToken)
+ {
+ if (!_fileInfo.Exists)
+ {
+ throw new FileNotFoundException("Unable to find the indicated file.", _fileInfo.FullName);
+ }
+
+ return ValueTask.FromResult(
+ (Stream)new FileStream(
+ _fileInfo.FullName,
+ FileMode.Open,
+ FileAccess.Read,
+ FileShare.Read,
+ SandboxedFileReader.BufferSize,
+ FileOptions.Asynchronous | FileOptions.SequentialScan));
+ }
+}
diff --git a/src/app/dev/DevToys.Api/Core/Threading/TaskExtensions.cs b/src/app/dev/DevToys.Api/Core/Threading/TaskExtensions.cs
index 40fac5f73..3f4918d4f 100644
--- a/src/app/dev/DevToys.Api/Core/Threading/TaskExtensions.cs
+++ b/src/app/dev/DevToys.Api/Core/Threading/TaskExtensions.cs
@@ -19,6 +19,20 @@ public static class TaskExtensions
{
}
+ /// <summary>
+ /// Runs a task without waiting for its result.
+ /// </summary>
+ public static void Forget(this ValueTask _)
+ {
+ }
+
+ /// <summary>
+ /// Runs a task without waiting for its result.
+ /// </summary>
+ public static void Forget<T>(this ValueTask<T> _)
+ {
+ }
+
/// <summary>
/// Runs a task without waiting for its result. Swallows or handle any exception caused by the task.
/// </summary>
@@ -35,6 +49,22 @@ public static class TaskExtensions
}
}
+ /// <summary>
+ /// Runs a task without waiting for its result. Swallows or handle any exception caused by the task.
+ /// </summary>
+ /// <param name="errorHandler">The action to run when an exception is caught.</param>
+ public static async void ForgetSafely(this ValueTask task, Action<Exception>? errorHandler = null)
+ {
+ try
+ {
+ await task.ConfigureAwait(true);
+ }
+ catch (Exception ex)
+ {
+ errorHandler?.Invoke(ex);
+ }
+ }
+
/// <summary>
/// Gets the result of the task synchronously, on the current thread.
/// </summary>
diff --git a/src/app/dev/DevToys.Blazor/Components/UIElements/UIImageViewerPresenter.razor.cs b/src/app/dev/DevToys.Blazor/Components/UIElements/UIImageViewerPresenter.razor.cs
index 1d7d57660..22afb8566 100644
--- a/src/app/dev/DevToys.Blazor/Components/UIElements/UIImageViewerPresenter.razor.cs
+++ b/src/app/dev/DevToys.Blazor/Components/UIElements/UIImageViewerPresenter.razor.cs
@@ -38,6 +38,7 @@ public partial class UIImageViewerPresenter : MefComponentBase
_cancellationTokenSource?.Cancel();
_cancellationTokenSource?.Dispose();
UIImageViewer.ImageSourceChanged -= UIImageViewer_ImageSourceChanged;
+ _semaphore.Dispose();
await base.DisposeAsync();
}
diff --git a/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.cs b/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.cs
index 6bceff817..175d26549 100644
--- a/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.cs
+++ b/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.cs
@@ -116,7 +116,7 @@ internal sealed partial class MainWindowViewModel : ObservableRecipient
= _oldSmartDetectedTools.FirstOrDefault(tool => tool.ToolInstance == guiToolViewItem.ToolInstance);
if (smartDetectedTool is not null)
{
- _ = guiToolViewItem.ToolInstance.View; // Do nothing with the view but trigger to instance because PassSmartDetectedData may assume the UI is instantiated.
+ // Send the data to the tool.
guiToolViewItem.ToolInstance.PassSmartDetectedData(smartDetectedTool.DataTypeName, smartDetectedTool.ParsedData);
}
}
@@ -258,7 +258,7 @@ internal sealed partial class MainWindowViewModel : ObservableRecipient
{
// Then let's navigate immediately to it and set the detected data as an input.
SelectedMenuItem = firstToolViewItem;
- _ = detectedTools[0].ToolInstance.View; // Do nothing with the view but trigger to instance because `PassSmartDetectedData` may assume the UI is instantiated.
+
// Send the data to the tool.
detectedTools[0].ToolInstance.PassSmartDetectedData(detectedTools[0].DataTypeName, detectedTools[0].ParsedData);
}
@@ -357,6 +357,7 @@ internal sealed partial class MainWindowViewModel : ObservableRecipient
// If this is not null, it means that the user has selected a tool that has been detected by Smart Detection.
if (message.SmartDetectionInfo is not null)
{
+ // Send the data to the tool.
message.Value.PassSmartDetectedData(message.SmartDetectionInfo.DataTypeName, message.SmartDetectionInfo.ParsedData);
}
}
diff --git a/src/app/dev/DevToys.Core/Tools/GuiToolInstance.cs b/src/app/dev/DevToys.Core/Tools/GuiToolInstance.cs
index 22399e47f..0ae549771 100644
--- a/src/app/dev/DevToys.Core/Tools/GuiToolInstance.cs
+++ b/src/app/dev/DevToys.Core/Tools/GuiToolInstance.cs
@@ -94,8 +94,12 @@ public sealed partial class GuiToolInstance : ObservableObject, IDisposable
/// </summary>
public void PassSmartDetectedData(string dataTypeName, object? parsedData)
{
+ // Ensure the view is created. We do this because `OnDataReceived` may assume the UI is instantiated.
+ _ = View;
+
try
{
+ // Send the data to the tool.
_instance.Value.OnDataReceived(dataTypeName, parsedData);
}
catch (NotImplementedException) { }
diff --git a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterGuiTool.cs
index 8bb3478ba..75805e998 100644
--- a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterGuiTool.cs
+++ b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterGuiTool.cs
@@ -47,6 +47,7 @@ internal sealed partial class JsonYamlConverterGuiTool : IGuiTool, IDisposable
Footer
}
+ private readonly DisposableSemaphore _semaphore = new();
private readonly ILogger _logger;
private readonly ISettingsProvider _settingsProvider;
private readonly IUIMultiLineTextInput _inputTextArea = MultilineTextInput("json-to-yaml-input-text-area");
@@ -159,6 +160,7 @@ internal sealed partial class JsonYamlConverterGuiTool : IGuiTool, IDisposable
public void Dispose()
{
_cancellationTokenSource?.Dispose();
+ _semaphore.Dispose();
}
private void OnConversionModeChanged(JsonToYamlConversion conversionMode)
@@ -199,15 +201,18 @@ internal sealed partial class JsonYamlConverterGuiTool : IGuiTool, IDisposable
private async Task ConvertAsync(string input, CancellationToken cancellationToken)
{
- await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
-
- ToolResult<string> conversionResult = await JsonYamlHelper.ConvertAsync(
- input,
- _settingsProvider.GetSetting(conversionMode),
- _settingsProvider.GetSetting(indentationMode),
- _logger,
- cancellationToken);
- _outputTextArea.Text(conversionResult.Data);
+ using (await _semaphore.WaitAsync(cancellationToken))
+ {
+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
+
+ ToolResult<string> conversionResult = await JsonYamlHelper.ConvertAsync(
+ input,
+ _settingsProvider.GetSetting(conversionMode),
+ _settingsProvider.GetSetting(indentationMode),
+ _logger,
+ cancellationToken);
+ _outputTextArea.Text(conversionResult.Data);
+ }
}
private void SetJsonToYamlConversion()
diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/EncodersDecoders.Designer.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/EncodersDecoders.Designer.cs
index c33c77d99..04ed99695 100644
--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/EncodersDecoders.Designer.cs
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/EncodersDecoders.Designer.cs
@@ -61,7 +61,7 @@ namespace DevToys.Tools.Tools.EncodersDecoders {
}
/// <summary>
- /// Looks up a localized string similar to .
+ /// Looks up a localized string similar to Encoders and decoders.
/// </summary>
internal static string AccessibleName {
get {
diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoderGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoderGuiTool.cs
index 7dc91333d..6188be27a 100644
--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoderGuiTool.cs
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoderGuiTool.cs
@@ -40,6 +40,7 @@ internal sealed partial class GZipEncoderDecoderGuiTool : IGuiTool, IDisposable
Stretch
}
+ private readonly DisposableSemaphore _semaphore = new();
private readonly ILogger _logger;
private readonly ISettingsProvider _settingsProvider;
private readonly IUISwitch _compressionModeSwitch = Switch("gzip-compression-mode-switch");
@@ -155,6 +156,7 @@ internal sealed partial class GZipEncoderDecoderGuiTool : IGuiTool, IDisposable
public void Dispose()
{
_cancellationTokenSource?.Dispose();
+ _semaphore.Dispose();
}
private void OnCompressionModeChanged(bool conversionMode)
@@ -195,16 +197,19 @@ internal sealed partial class GZipEncoderDecoderGuiTool : IGuiTool, IDisposable
private async Task ConvertAsync(string input, CancellationToken cancellationToken)
{
- await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
+ using (await _semaphore.WaitAsync(cancellationToken))
+ {
+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
- (string data, double differencePercentage) conversionResult
- = await GZipHelper.CompressOrDecompressAsync(
- input,
- _settingsProvider.GetSetting(compressionMode),
- _logger,
- cancellationToken);
+ (string data, double differencePercentage) conversionResult
+ = await GZipHelper.CompressOrDecompressAsync(
+ input,
+ _settingsProvider.GetSetting(compressionMode),
+ _logger,
+ cancellationToken);
- _compressionRatioInfoBar.Description(string.Format(GZipEncoderDecoder.CompressionRatioValue, conversionResult.differencePercentage));
- _outputText.Text(conversionResult.data);
+ _compressionRatioInfoBar.Description(string.Format(GZipEncoderDecoder.CompressionRatioValue, conversionResult.differencePercentage));
+ _outputText.Text(conversionResult.data);
+ }
}
}
diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoderGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoderGuiTool.cs
index 09f4fabc1..161c488c4 100644
--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoderGuiTool.cs
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoderGuiTool.cs
@@ -38,6 +38,7 @@ internal sealed partial class HtmlEncoderDecoderGuiTool : IGuiTool, IDisposable
Stretch
}
+ private readonly DisposableSemaphore _semaphore = new();
private readonly ILogger _logger;
private readonly ISettingsProvider _settingsProvider;
private readonly IUISwitch _conversionModeSwitch = Switch("html-conversion-mode-switch");
@@ -136,6 +137,7 @@ internal sealed partial class HtmlEncoderDecoderGuiTool : IGuiTool, IDisposable
public void Dispose()
{
_cancellationTokenSource?.Dispose();
+ _semaphore.Dispose();
}
private void OnConversionModeChanged(bool conversionMode)
@@ -160,13 +162,16 @@ internal sealed partial class HtmlEncoderDecoderGuiTool : IGuiTool, IDisposable
private async Task ConvertAsync(string input, CancellationToken cancellationToken)
{
- await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
-
- _outputText.Text(
- HtmlHelper.EncodeOrDecode(
- input,
- _settingsProvider.GetSetting(conversionMode),
- _logger,
- cancellationToken));
+ using (await _semaphore.WaitAsync(cancellationToken))
+ {
+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
+
+ _outputText.Text(
+ HtmlHelper.EncodeOrDecode(
+ input,
+ _settingsProvider.GetSetting(conversionMode),
+ _logger,
+ cancellationToken));
+ }
}
}
diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoderGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoderGuiTool.cs
index 661645fcc..56e411ad3 100644
--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoderGuiTool.cs
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoderGuiTool.cs
@@ -38,6 +38,7 @@ internal sealed partial class UrlEncoderDecoderGuiTool : IGuiTool, IDisposable
Stretch
}
+ private readonly DisposableSemaphore _semaphore = new();
private readonly ILogger _logger;
private readonly ISettingsProvider _settingsProvider;
private readonly IUISwitch _conversionModeSwitch = Switch("url-conversion-mode-switch");
@@ -136,6 +137,7 @@ internal sealed partial class UrlEncoderDecoderGuiTool : IGuiTool, IDisposable
public void Dispose()
{
_cancellationTokenSource?.Dispose();
+ _semaphore.Dispose();
}
private void OnConversionModeChanged(bool conversionMode)
@@ -160,13 +162,16 @@ internal sealed partial class UrlEncoderDecoderGuiTool : IGuiTool, IDisposable
private async Task ConvertAsync(string input, CancellationToken cancellationToken)
{
- await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
-
- _outputText.Text(
- UrlHelper.EncodeOrDecode(
- input,
- _settingsProvider.GetSetting(conversionMode),
- _logger,
- cancellationToken));
+ using (await _semaphore.WaitAsync(cancellationToken))
+ {
+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
+
+ _outputText.Text(
+ UrlHelper.EncodeOrDecode(
+ input,
+ _settingsProvider.GetSetting(conversionMode),
+ _logger,
+ cancellationToken));
+ }
}
}
diff --git a/src/app/dev/platforms/desktop/DevToys.Linux/Core/FileStorage.cs b/src/app/dev/platforms/desktop/DevToys.Linux/Core/FileStorage.cs
index 819ea083e..3d86826a7 100644
--- a/src/app/dev/platforms/desktop/DevToys.Linux/Core/FileStorage.cs
+++ b/src/app/dev/platforms/desktop/DevToys.Linux/Core/FileStorage.cs
@@ -252,7 +252,7 @@ internal sealed class FileStorage : GObject.Object, IFileStorage
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
- fileResult.Add(new LinuxSandboxedFileReader(filePath, this));
+ fileResult.Add(SandboxedFileReader.FromFileInfo(new FileInfo(filePath)));
}
}
}
diff --git a/src/app/dev/platforms/desktop/DevToys.Linux/Core/LinuxSandboxedFileReader.cs b/src/app/dev/platforms/desktop/DevToys.Linux/Core/LinuxSandboxedFileReader.cs
deleted file mode 100644
index c4328e204..000000000
--- a/src/app/dev/platforms/desktop/DevToys.Linux/Core/LinuxSandboxedFileReader.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using System.IO;
-using DevToys.Api;
-
-namespace DevToys.Linux.Core;
-
-internal sealed class LinuxSandboxedFileReader : SandboxedFileReader
-{
- private readonly string _fullPath;
- private readonly IFileStorage _fileStorage;
-
- public LinuxSandboxedFileReader(string fullPath, IFileStorage fileStorage)
- : base(fullPath)
- {
- Guard.IsNotNull(fileStorage);
- Guard.IsNotNullOrWhiteSpace(fullPath);
- _fileStorage = fileStorage;
- _fullPath = fullPath;
- }
-
- protected override ValueTask<Stream> OpenReadFileAsync(CancellationToken cancellationToken)
- {
- return ValueTask.FromResult<Stream>(_fileStorage.OpenReadFile(_fullPath));
- }
-}
diff --git a/src/app/dev/platforms/desktop/DevToys.Windows/Core/FileStorage.cs b/src/app/dev/platforms/desktop/DevToys.Windows/Core/FileStorage.cs
index e454fef88..9d5ceff9a 100644
--- a/src/app/dev/platforms/desktop/DevToys.Windows/Core/FileStorage.cs
+++ b/src/app/dev/platforms/desktop/DevToys.Windows/Core/FileStorage.cs
@@ -110,7 +110,7 @@ internal sealed class FileStorage : IFileStorage
if (openFileDialog.ShowDialog() == true)
{
- return new WindowsSandboxedFileReader(openFileDialog.FileName, this);
+ return SandboxedFileReader.FromFileInfo(new FileInfo(openFileDialog.FileName));
}
return null;
@@ -141,7 +141,7 @@ internal sealed class FileStorage : IFileStorage
var result = new SandboxedFileReader[fileNames.Length];
for (int i = 0; i < fileNames.Length; i++)
{
- result[i] = new WindowsSandboxedFileReader(fileNames[i], this);
+ result[i] = SandboxedFileReader.FromFileInfo(new FileInfo(fileNames[i]));
}
return result;
diff --git a/src/app/dev/platforms/desktop/DevToys.Windows/Core/WindowsSandboxedFileReader.cs b/src/app/dev/platforms/desktop/DevToys.Windows/Core/WindowsSandboxedFileReader.cs
deleted file mode 100644
index ebdedd689..000000000
--- a/src/app/dev/platforms/desktop/DevToys.Windows/Core/WindowsSandboxedFileReader.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using System.IO;
-using DevToys.Api;
-
-namespace DevToys.Windows.Core;
-
-internal sealed class WindowsSandboxedFileReader : SandboxedFileReader
-{
- private readonly string _fullPath;
- private readonly IFileStorage _fileStorage;
-
- public WindowsSandboxedFileReader(string fullPath, IFileStorage fileStorage)
- : base(fullPath)
- {
- Guard.IsNotNull(fileStorage);
- Guard.IsNotNullOrWhiteSpace(fullPath);
- _fileStorage = fileStorage;
- _fullPath = fullPath;
- }
-
- protected override ValueTask<Stream> OpenReadFileAsync(CancellationToken cancellationToken)
- {
- return ValueTask.FromResult<Stream>(_fileStorage.OpenReadFile(_fullPath));
- }
-}