Skip to content

A Swiss Army knife for developers.

Improved Smart Detection for some tools.

Etienne Baudoux75e347507ad7
diff --git a/src/app/dev/DevToys.Api/Settings/SettingDefinition.cs b/src/app/dev/DevToys.Api/Settings/SettingDefinition.cs
index 54647a61c..21db69491 100644
--- a/src/app/dev/DevToys.Api/Settings/SettingDefinition.cs
+++ b/src/app/dev/DevToys.Api/Settings/SettingDefinition.cs
@@ -21,7 +21,6 @@ public readonly struct SettingDefinition<T> : IEquatable<SettingDefinition<T>>
/// Initializes a new instance of the <see cref="SettingDefinition"/> structure.
/// </summary>
/// <param name="name">The name of the setting. Should be unique.</param>
- /// <param name="isRoaming">Defines whether the setting can be synchronized with the user's Microsoft account.</param>
/// <param name="defaultValue">The default value of the setting.</param>
public SettingDefinition(string name, T defaultValue)
{
@@ -29,9 +28,7 @@ public readonly struct SettingDefinition<T> : IEquatable<SettingDefinition<T>>
if (name.Length > 255)
{
- // For both LocalSettings and RoamingSettings on Windows, the name of each setting
- // can be 255 characters in length at most.
- // see https://docs.microsoft.com/en-us/uwp/api/windows.storage.applicationdata.localsettings?view=winrt-22000#remarks
+ // Come one! Make it shorter!
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(name), "Setting name is limited to 255 characters.");
}
else if (name.Contains("="))
diff --git a/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs b/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs
index ed8ab938d..d8d8eba8d 100644
--- a/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs
+++ b/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs
@@ -9,5 +9,6 @@ public static class PredefinedCommonDataTypeNames
public const string Base64Image = "base64Image";
public const string Image = "image";
public const string File = "file";
+ public const string Files = "files";
public const string GZip = "gzip";
}
diff --git a/src/app/dev/DevToys.Tools/SmartDetection/Base64ImageFileDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/Base64ImageFileDataTypeDetector.cs
new file mode 100644
index 000000000..76d567b1e
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/SmartDetection/Base64ImageFileDataTypeDetector.cs
@@ -0,0 +1,32 @@
+namespace DevToys.Tools.SmartDetection;
+
+[Export(typeof(IDataTypeDetector))]
+[DataTypeName("Base64ImageFile", baseName: PredefinedCommonDataTypeNames.File)]
+internal sealed partial class Base64ImageFileDataTypeDetector : IDataTypeDetector
+{
+ internal static readonly string[] SupportedFileTypes = new[]
+ {
+ "bmp",
+ "gif",
+ "ico",
+ "jpg",
+ "jpeg",
+ "png",
+ "svg",
+ "webp"
+ };
+
+ public ValueTask<DataDetectionResult> TryDetectDataAsync(object data, DataDetectionResult? resultFromBaseDetector, CancellationToken cancellationToken)
+ {
+ if (resultFromBaseDetector is not null
+ && resultFromBaseDetector.Data is FileInfo dataFile)
+ {
+ if (SupportedFileTypes.Contains(dataFile.Extension.Trim('.'), StringComparer.OrdinalIgnoreCase))
+ {
+ return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: dataFile));
+ }
+ }
+
+ return ValueTask.FromResult(DataDetectionResult.Unsuccessful);
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/SmartDetection/FileDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/FileDataTypeDetector.cs
new file mode 100644
index 000000000..35445bfc6
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/SmartDetection/FileDataTypeDetector.cs
@@ -0,0 +1,18 @@
+namespace DevToys.Tools.SmartDetection;
+
+[Export(typeof(IDataTypeDetector))]
+[DataTypeName(PredefinedCommonDataTypeNames.File, baseName: PredefinedCommonDataTypeNames.Files)]
+internal sealed partial class FileDataTypeDetector : IDataTypeDetector
+{
+ public ValueTask<DataDetectionResult> TryDetectDataAsync(object data, DataDetectionResult? resultFromBaseDetector, CancellationToken cancellationToken)
+ {
+ if (resultFromBaseDetector is not null
+ && resultFromBaseDetector.Data is FileInfo[] dataFiles
+ && dataFiles.Length == 1)
+ {
+ return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: dataFiles[0]));
+ }
+
+ return ValueTask.FromResult(DataDetectionResult.Unsuccessful);
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/SmartDetection/FilesDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/FilesDataTypeDetector.cs
new file mode 100644
index 000000000..84597c069
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/SmartDetection/FilesDataTypeDetector.cs
@@ -0,0 +1,16 @@
+namespace DevToys.Tools.SmartDetection;
+
+[Export(typeof(IDataTypeDetector))]
+[DataTypeName(PredefinedCommonDataTypeNames.Files)]
+internal sealed partial class FilesDataTypeDetector : IDataTypeDetector
+{
+ public ValueTask<DataDetectionResult> TryDetectDataAsync(object data, DataDetectionResult? resultFromBaseDetector, CancellationToken cancellationToken)
+ {
+ if (data is FileInfo[] dataFiles)
+ {
+ return ValueTask.FromResult(new DataDetectionResult(true, dataFiles));
+ }
+
+ return ValueTask.FromResult(DataDetectionResult.Unsuccessful);
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/SmartDetection/ImageDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/ImageDataTypeDetector.cs
new file mode 100644
index 000000000..4e20a5d09
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/SmartDetection/ImageDataTypeDetector.cs
@@ -0,0 +1,18 @@
+using SixLabors.ImageSharp;
+
+namespace DevToys.Tools.SmartDetection;
+
+[Export(typeof(IDataTypeDetector))]
+[DataTypeName(PredefinedCommonDataTypeNames.Image)]
+internal sealed partial class ImageDataTypeDetector : IDataTypeDetector
+{
+ public ValueTask<DataDetectionResult> TryDetectDataAsync(object data, DataDetectionResult? resultFromBaseDetector, CancellationToken cancellationToken)
+ {
+ if (data is Image<SixLabors.ImageSharp.PixelFormats.Rgba32> dataImage)
+ {
+ return ValueTask.FromResult(new DataDetectionResult(true, dataImage));
+ }
+
+ return ValueTask.FromResult(DataDetectionResult.Unsuccessful);
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderGuiTool.cs
index 3adff3cc3..d622692fa 100644
--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderGuiTool.cs
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderGuiTool.cs
@@ -1,4 +1,6 @@
-using Microsoft.Extensions.Logging;
+using DevToys.Tools.SmartDetection;
+using Microsoft.Extensions.Logging;
+using SixLabors.ImageSharp;
namespace DevToys.Tools.Tools.EncodersDecoders.Base64Image;
@@ -16,6 +18,8 @@ namespace DevToys.Tools.Tools.EncodersDecoders.Base64Image;
AccessibleNameResourceName = nameof(Base64ImageEncoderDecoder.AccessibleName),
SearchKeywordsResourceName = nameof(Base64ImageEncoderDecoder.SearchKeywords))]
[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Base64Image)]
+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Image)]
+[AcceptedDataTypeName("Base64ImageFile")]
internal sealed partial class Base64ImageEncoderDecoderGuiTool : IGuiTool, IDisposable
{
private enum GridRows
@@ -29,6 +33,7 @@ internal sealed partial class Base64ImageEncoderDecoderGuiTool : IGuiTool, IDisp
Stretch
}
+ private readonly DisposableSemaphore _semaphore = new();
private readonly IFileStorage _fileStorage;
private readonly ILogger _logger;
private readonly IUIMultiLineTextInput _inputText = MultilineTextInput("base64-image-input-box");
@@ -79,7 +84,7 @@ internal sealed partial class Base64ImageEncoderDecoderGuiTool : IGuiTool, IDisp
_fileSelector
.CanSelectOneFile()
- .LimitFileTypesTo("bmp", "gif", "ico", "jpg", "jpeg", "png", "svg", "webp")
+ .LimitFileTypesTo(Base64ImageFileDataTypeDetector.SupportedFileTypes)
.OnFilesSelected(OnFileSelectedAsync)),
Cell(
@@ -88,18 +93,35 @@ internal sealed partial class Base64ImageEncoderDecoderGuiTool : IGuiTool, IDisp
_imageViewer))));
- public void OnDataReceived(string dataTypeName, object? parsedData)
+ public async void OnDataReceived(string dataTypeName, object? parsedData)
{
if (dataTypeName == PredefinedCommonDataTypeNames.Base64Image && parsedData is string base64Image)
{
_inputText.Text(base64Image); // This will trigger a conversion.
}
+ else if (dataTypeName == PredefinedCommonDataTypeNames.Image && parsedData is Image<SixLabors.ImageSharp.PixelFormats.Rgba32> image)
+ {
+ FileInfo temporaryFile = _fileStorage.CreateSelfDestroyingTempFile("png");
+
+ using (image)
+ {
+ using Stream fileStream = _fileStorage.OpenWriteFile(temporaryFile.FullName, replaceIfExist: true);
+ await image.SaveAsPngAsync(fileStream);
+ }
+
+ _fileSelector.WithFiles(SandboxedFileReader.FromFileInfo(temporaryFile)); // This will trigger a conversion.
+ }
+ else if (dataTypeName == "Base64ImageFile" && parsedData is FileInfo file)
+ {
+ _fileSelector.WithFiles(SandboxedFileReader.FromFileInfo(file)); // This will trigger a conversion.
+ }
}
public void Dispose()
{
_selectedFile?.Dispose();
_cancellationTokenSource?.Dispose();
+ _semaphore.Dispose();
}
private void OnInputTextChanged(string text)
@@ -146,58 +168,61 @@ internal sealed partial class Base64ImageEncoderDecoderGuiTool : IGuiTool, IDisp
try
{
- if (string.IsNullOrWhiteSpace(input))
- {
- _imageViewer.Clear();
- return;
- }
-
- string? trimmedData = input?.Trim();
-
- string fileExtension;
- if (trimmedData!.StartsWith("data:image/bmp;base64,", StringComparison.OrdinalIgnoreCase))
- {
- fileExtension = "bmp";
- }
- else if (trimmedData!.StartsWith("data:image/gif;base64,", StringComparison.OrdinalIgnoreCase))
- {
- fileExtension = "gif";
- }
- else if (trimmedData!.StartsWith("data:image/x-icon;base64,", StringComparison.OrdinalIgnoreCase))
- {
- fileExtension = "ico";
- }
- else if (trimmedData!.StartsWith("data:image/jpeg;base64,", StringComparison.OrdinalIgnoreCase))
- {
- fileExtension = "jpeg";
- }
- else if (trimmedData!.StartsWith("data:image/png;base64,", StringComparison.OrdinalIgnoreCase))
+ using (await _semaphore.WaitAsync(cancellationToken))
{
- fileExtension = "png";
+ if (string.IsNullOrWhiteSpace(input))
+ {
+ _imageViewer.Clear();
+ return;
+ }
+
+ string? trimmedData = input?.Trim();
+
+ string fileExtension;
+ if (trimmedData!.StartsWith("data:image/bmp;base64,", StringComparison.OrdinalIgnoreCase))
+ {
+ fileExtension = "bmp";
+ }
+ else if (trimmedData!.StartsWith("data:image/gif;base64,", StringComparison.OrdinalIgnoreCase))
+ {
+ fileExtension = "gif";
+ }
+ else if (trimmedData!.StartsWith("data:image/x-icon;base64,", StringComparison.OrdinalIgnoreCase))
+ {
+ fileExtension = "ico";
+ }
+ else if (trimmedData!.StartsWith("data:image/jpeg;base64,", StringComparison.OrdinalIgnoreCase))
+ {
+ fileExtension = "jpeg";
+ }
+ else if (trimmedData!.StartsWith("data:image/png;base64,", StringComparison.OrdinalIgnoreCase))
+ {
+ fileExtension = "png";
+ }
+ else if (trimmedData!.StartsWith("data:image/svg+xml;base64,", StringComparison.OrdinalIgnoreCase))
+ {
+ fileExtension = "svg";
+ }
+ else if (trimmedData!.StartsWith("data:image/webp;base64,", StringComparison.OrdinalIgnoreCase))
+ {
+ fileExtension = "webp";
+ }
+ else
+ {
+ return;
+ }
+
+ input = trimmedData.Substring(trimmedData.IndexOf(',') + 1);
+ byte[] bytes = Convert.FromBase64String(input);
+
+ FileInfo tempFile = _fileStorage.CreateSelfDestroyingTempFile(fileExtension);
+ using (FileStream tempFileStream = tempFile.OpenWrite())
+ {
+ await tempFileStream.WriteAsync(bytes, cancellationToken);
+ }
+
+ _imageViewer.WithFile(tempFile);
}
- else if (trimmedData!.StartsWith("data:image/svg+xml;base64,", StringComparison.OrdinalIgnoreCase))
- {
- fileExtension = "svg";
- }
- else if (trimmedData!.StartsWith("data:image/webp;base64,", StringComparison.OrdinalIgnoreCase))
- {
- fileExtension = "webp";
- }
- else
- {
- return;
- }
-
- input = trimmedData.Substring(trimmedData.IndexOf(',') + 1);
- byte[] bytes = Convert.FromBase64String(input);
-
- FileInfo tempFile = _fileStorage.CreateSelfDestroyingTempFile(fileExtension);
- using (FileStream tempFileStream = tempFile.OpenWrite())
- {
- await tempFileStream.WriteAsync(bytes, cancellationToken);
- }
-
- _imageViewer.WithFile(tempFile);
}
catch
{
@@ -209,33 +234,36 @@ internal sealed partial class Base64ImageEncoderDecoderGuiTool : IGuiTool, IDisp
{
await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
- using Stream stream = await file.GetNewAccessToFileContentAsync(cancellationToken);
-
- var bytes = new Memory<byte>(new byte[stream.Length]);
- await stream.ReadAsync(bytes, CancellationToken.None);
- string base64 = Convert.ToBase64String(bytes.Span);
-
- if (cancellationToken.IsCancellationRequested)
+ using (await _semaphore.WaitAsync(cancellationToken))
{
- return;
- }
+ using Stream stream = await file.GetNewAccessToFileContentAsync(cancellationToken);
- string fileExtension = Path.GetExtension(file.FileName);
- string output
- = fileExtension.ToLowerInvariant() switch
+ var bytes = new Memory<byte>(new byte[stream.Length]);
+ await stream.ReadAsync(bytes, CancellationToken.None);
+ string base64 = Convert.ToBase64String(bytes.Span);
+
+ if (cancellationToken.IsCancellationRequested)
{
- ".bmp" => "data:image/bmp;base64," + base64,
- ".gif" => "data:image/gif;base64," + base64,
- ".ico" => "data:image/x-icon;base64," + base64,
- ".jpg" or ".jpeg" => "data:image/jpeg;base64," + base64,
- ".png" => "data:image/png;base64," + base64,
- ".svg" => "data:image/svg+xml;base64," + base64,
- ".webp" => "data:image/webp;base64," + base64,
- _ => throw new NotSupportedException(),
- };
-
- _ignoreBase64DataChange = true;
- _inputText.Text(output);
- _ignoreBase64DataChange = false;
+ return;
+ }
+
+ string fileExtension = Path.GetExtension(file.FileName);
+ string output
+ = fileExtension.ToLowerInvariant() switch
+ {
+ ".bmp" => "data:image/bmp;base64," + base64,
+ ".gif" => "data:image/gif;base64," + base64,
+ ".ico" => "data:image/x-icon;base64," + base64,
+ ".jpg" or ".jpeg" => "data:image/jpeg;base64," + base64,
+ ".png" => "data:image/png;base64," + base64,
+ ".svg" => "data:image/svg+xml;base64," + base64,
+ ".webp" => "data:image/webp;base64," + base64,
+ _ => throw new NotSupportedException(),
+ };
+
+ _ignoreBase64DataChange = true;
+ _inputText.Text(output);
+ _ignoreBase64DataChange = false;
+ }
}
}
diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiTool.cs
index 03ae99d79..429bccec8 100644
--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiTool.cs
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiTool.cs
@@ -50,6 +50,7 @@ internal sealed partial class Base64TextEncoderDecoderGuiTool : IGuiTool, IDispo
private const Base64Encoding DefaultEncoding = Base64Encoding.Utf8;
+ private readonly DisposableSemaphore _semaphore = new();
private readonly ILogger _logger;
private readonly ISettingsProvider _settingsProvider;
private readonly IUISwitch _conversionModeSwitch = Switch("base64-text-conversion-mode-switch");
@@ -164,6 +165,7 @@ internal sealed partial class Base64TextEncoderDecoderGuiTool : IGuiTool, IDispo
public void Dispose()
{
_cancellationTokenSource?.Dispose();
+ _semaphore.Dispose();
}
private void OnConversionModeChanged(bool conversionMode)
@@ -209,6 +211,8 @@ internal sealed partial class Base64TextEncoderDecoderGuiTool : IGuiTool, IDispo
private async Task ConvertAsync(string input, CancellationToken cancellationToken)
{
+ using (await _semaphore.WaitAsync(cancellationToken))
+ {
await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
string conversionResult;
@@ -248,3 +252,4 @@ internal sealed partial class Base64TextEncoderDecoderGuiTool : IGuiTool, IDispo
_outputText.Text(conversionResult);
}
}
+}
diff --git a/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderGuiToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderGuiToolTests.cs
index abb5c9f77..e6eeda556 100644
--- a/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderGuiToolTests.cs
+++ b/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderGuiToolTests.cs
@@ -50,6 +50,6 @@ public sealed class Base64ImageEncoderDecoderGuiToolTests : MefBasedTest
_inputBox.Text(File.ReadAllText(inputFile.FullName));
await _tool.WorkTask;
- _imageViewer.ImageSource.Value.Should().BeOfType<FileInfo>();
+ _imageViewer.ImageSource.Value.Value.Should().BeOfType<FileInfo>();
}
}