A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Added QR Code reader / generator tool (#1012)
Etienne BAUDOUXd0db491d161b
diff --git a/src/Directory.Packages.props b/src/Directory.Packages.propsindex b48103aeb..0f9107de8 100644--- a/src/Directory.Packages.props+++ b/src/Directory.Packages.props@@ -43,5 +43,7 @@<PackageVersion Include="xunit" Version="$(XUnit)" /><PackageVersion Include="xunit.runner.visualstudio" Version="$(XUnit)" /><PackageVersion Include="YamlDotNet" Version="13.0.0" />+ <PackageVersion Include="ZXing.Net" Version="0.16.9" />+ <PackageVersion Include="ZXing.Net.Bindings.ImageSharp.V3" Version="0.16.15" /></ItemGroup></Project>\ No newline at end of filediff --git a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIImageViewer.cs b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIImageViewer.csindex 729fd49d1..82db13a5e 100644--- a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIImageViewer.cs+++ b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIImageViewer.cs@@ -1,4 +1,5 @@-using OneOf;+using System.Collections.ObjectModel;+using OneOf;namespace DevToys.Api;@@ -13,16 +14,27 @@ public interface IUIImageViewer : IUITitledElement/// </summary>OneOf<FileInfo, Image, SandboxedFileReader>? ImageSource { get; }+ /// <summary>+ /// Gets the custom actions to perform when the user saves the image with a specific file extension.+ /// </summary>+ IReadOnlyDictionary<string, Func<FileStream, ValueTask>> CustomActionPerFileExtensionOnSaving { get; }+/// <summary>/// Raised when <see cref="ImageSource"/> is changed./// </summary>event EventHandler? ImageSourceChanged;++ /// <summary>+ /// Raised when <see cref="CustomActionPerFileExtensionOnSaving"/> is changed.+ /// </summary>+ event EventHandler? CustomActionPerFileExtensionOnSavingChanged;}[DebuggerDisplay($"Id = {{{nameof(Id)}}}, FileName = {{{nameof(Title)}}}")]internal sealed class UIImageViewer : UITitledElement, IUIImageViewer, IDisposable{private OneOf<FileInfo, Image, SandboxedFileReader>? _imageSource = default;+ private IReadOnlyDictionary<string, Func<FileStream, ValueTask>> _customActionPerFileExtensionOnSaving = ReadOnlyDictionary<string, Func<FileStream, ValueTask>>.Empty;internal UIImageViewer(string? id): base(id)@@ -45,7 +57,14 @@ internal sealed class UIImageViewer : UITitledElement, IUIImageViewer, IDisposab}}+ public IReadOnlyDictionary<string, Func<FileStream, ValueTask>> CustomActionPerFileExtensionOnSaving+ {+ get => _customActionPerFileExtensionOnSaving;+ internal set => SetPropertyValue(ref _customActionPerFileExtensionOnSaving, value, CustomActionPerFileExtensionOnSavingChanged);+ }+public event EventHandler? ImageSourceChanged;+ public event EventHandler? CustomActionPerFileExtensionOnSavingChanged;public void Dispose(){@@ -114,6 +133,44 @@ public static partial class GUIreturn element;}+ /// <summary>+ /// Adds a custom action to perform when the user saves the image with a specific file extension.+ /// </summary>+ /// <remarks>+ /// As a side effect of this method, the specified file extension will be available in the Save File Dialog when the user decides to save the image.+ /// When the user saves the image with the specified <paramref name="fileExtension"/>, the specified <paramref name="action"/> will be invoked+ /// with a <see cref="FileStream"/> pointing to the file to save. The <paramref name="action"/> is responsible for writing the image to the file.+ /// </remarks>+ /// <param name="fileExtension">The file extension to handle</param>+ /// <param name="action">The action to perform when the user wishes to save the image with the given <paramref name="fileExtension"/>.</param>+ public static IUIImageViewer ManuallyHandleSaveAs(this IUIImageViewer element, string fileExtension, Func<FileStream, ValueTask> action)+ {+ fileExtension = "." + fileExtension.ToLowerInvariant().Trim().TrimStart('.');++ var imageViewer = (UIImageViewer)element;+ var customActions = new Dictionary<string, Func<FileStream, ValueTask>>(imageViewer.CustomActionPerFileExtensionOnSaving)+ {+ [fileExtension] = action+ };+ imageViewer.CustomActionPerFileExtensionOnSaving = new ReadOnlyDictionary<string, Func<FileStream, ValueTask>>(customActions);+ return element;+ }++ /// <summary>+ /// Removes the custom action to perform when the user saves the image with a specific file extension.+ /// </summary>+ /// <param name="fileExtension">The file extension to remove.</param>+ public static IUIImageViewer RemoveManuallyHandleSaveAs(this IUIImageViewer element, string fileExtension)+ {+ fileExtension = "." + fileExtension.ToLowerInvariant().Trim().TrimStart('.');++ var imageViewer = (UIImageViewer)element;+ var customActions = imageViewer.CustomActionPerFileExtensionOnSaving.ToDictionary();+ customActions.Remove(fileExtension);+ imageViewer.CustomActionPerFileExtensionOnSaving = new ReadOnlyDictionary<string, Func<FileStream, ValueTask>>(customActions);+ return element;+ }+/// <summary>/// Clears the value of <see cref="IUIImageViewer.ImageSource"/>./// </summary>diff --git a/src/app/dev/DevToys.Blazor/Components/UIElements/UIImageViewerPresenter.razor.cs b/src/app/dev/DevToys.Blazor/Components/UIElements/UIImageViewerPresenter.razor.csindex 26ce32b9d..48af6c43b 100644--- a/src/app/dev/DevToys.Blazor/Components/UIElements/UIImageViewerPresenter.razor.cs+++ b/src/app/dev/DevToys.Blazor/Components/UIElements/UIImageViewerPresenter.razor.cs@@ -71,7 +71,8 @@ public partial class UIImageViewerPresenter : MefComponentBase},async (Image image) =>{- FileInfo tempFile = _fileStorage.CreateSelfDestroyingTempFile(image.Metadata.DecodedImageFormat!.FileExtensions.FirstOrDefault());+ string? fileExtension = image.Metadata.DecodedImageFormat?.FileExtensions.FirstOrDefault() ?? "png";+ FileInfo tempFile = _fileStorage.CreateSelfDestroyingTempFile(fileExtension);await image.SaveAsync(tempFile.FullName);Shell.OpenFileInShell(tempFile.FullName);},@@ -126,24 +127,39 @@ public partial class UIImageViewerPresenter : MefComponentBasestring fileExtension= UIImageViewer.ImageSource.Value.Match((FileInfo imageFileInfo) => imageFileInfo.Extension,- (Image image) => image.Metadata.DecodedImageFormat!.FileExtensions.FirstOrDefault() ?? string.Empty,+ (Image image) => image.Metadata.DecodedImageFormat?.FileExtensions.FirstOrDefault() ?? "png",(SandboxedFileReader imagePickedFile) => Path.GetExtension(imagePickedFile.FileName));if (!string.IsNullOrWhiteSpace(fileExtension)){- Stream? pickedFile = await _fileStorage.PickSaveFileAsync(fileExtension);+ var fileExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)+ {+ fileExtension+ };+ foreach (string customFileExtension in UIImageViewer.CustomActionPerFileExtensionOnSaving.Keys)+ {+ fileExtensions.Add(customFileExtension);+ }++ await using FileStream? pickedFile = await _fileStorage.PickSaveFileAsync(fileExtensions.ToArray());if (pickedFile is not null){+ string userSelectedFileExtension = Path.GetExtension(pickedFile.Name).ToLowerInvariant();+ if (UIImageViewer.CustomActionPerFileExtensionOnSaving.TryGetValue(userSelectedFileExtension, out Func<FileStream, ValueTask>? customAction))+ {+ // The user has selected a file extension for which we have a custom action defined by the developer.+ await customAction(pickedFile);+ return;+ }+await UIImageViewer.ImageSource.Value.Match(async (FileInfo imageFileInfo) =>{using FileStream fileStream = imageFileInfo.OpenRead();await fileStream.CopyToAsync(pickedFile);},- (Image image) => image.SaveAsync(pickedFile, image.Metadata.DecodedImageFormat!),+ (Image image) => image.SaveAsync(pickedFile, image.Metadata.DecodedImageFormat ?? PngFormat.Instance),(SandboxedFileReader imagePickedFile) => imagePickedFile.CopyFileContentToAsync(pickedFile, CancellationToken.None));-- await pickedFile.DisposeAsync();}}}diff --git a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj b/src/app/dev/DevToys.Tools/DevToys.Tools.csprojindex 6c3865ab2..4df689b8e 100644--- a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj+++ b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj@@ -123,6 +123,11 @@<AutoGen>True</AutoGen><DependentUpon>PasswordGenerator.resx</DependentUpon></Compile>+ <Compile Update="Tools\EncodersDecoders\QRCode\QRCodeEncoderDecoder.Designer.cs">+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ <DependentUpon>QRCodeEncoderDecoder.resx</DependentUpon>+ </Compile><Compile Update="Tools\Generators\UUID\UUIDGenerator.Designer.cs"><DesignTime>True</DesignTime><AutoGen>True</AutoGen>@@ -247,6 +252,10 @@<Generator>ResXFileCodeGenerator</Generator><LastGenOutput>PasswordGenerator.Designer.cs</LastGenOutput></EmbeddedResource>+ <EmbeddedResource Update="Tools\EncodersDecoders\QRCode\QRCodeEncoderDecoder.resx">+ <Generator>ResXFileCodeGenerator</Generator>+ <LastGenOutput>QRCodeEncoderDecoder.Designer.cs</LastGenOutput>+ </EmbeddedResource><EmbeddedResource Update="Tools\Generators\UUID\UUIDGenerator.resx"><Generator>ResXFileCodeGenerator</Generator><LastGenOutput>UUIDGenerator.Designer.cs</LastGenOutput>@@ -312,6 +321,8 @@<PackageReference Include="YamlDotNet" /><PackageReference Include="Markdig" /><PackageReference Include="Markdown.ColorCode" />+ <PackageReference Include="ZXing.Net" />+ <PackageReference Include="ZXing.Net.Bindings.ImageSharp.V3" /></ItemGroup><Target Name="IncludeAllFilesInTargetDir" BeforeTargets="_GetPackageFiles">diff --git a/src/app/dev/DevToys.Tools/Helpers/QrCodeHelper.cs b/src/app/dev/DevToys.Tools/Helpers/QrCodeHelper.csnew file mode 100644index 000000000..43009c211--- /dev/null+++ b/src/app/dev/DevToys.Tools/Helpers/QrCodeHelper.cs@@ -0,0 +1,76 @@+using System.IO;+using SixLabors.ImageSharp;+using SixLabors.ImageSharp.PixelFormats;+using ZXing;+using ZXing.Common;+using static ZXing.Rendering.SvgRenderer;+using ZXing.QrCode.Internal;+using ZXing.Rendering;++namespace DevToys.Tools.Helpers;++internal static class QrCodeHelper+{+ internal static Image<Rgba32> GenerateQrCode(string text)+ {+ var barcodeWriter = new ZXing.ImageSharp.BarcodeWriter<Rgba32>+ {+ Format = BarcodeFormat.QR_CODE,+ Options = new EncodingOptions+ {+ Height = 1024,+ Width = 1024,+ Margin = 2+ }+ };++ Image<Rgba32> image = barcodeWriter.Write(text);+ return image;+ }++ internal static string GenerateSvgQrCode(string text)+ {+ BarcodeWriterSvg barcodeWriter = new()+ {+ Format = BarcodeFormat.QR_CODE,+ Renderer = new SvgRenderer()+ };++ EncodingOptions encodingOptions = new()+ {+ Width = 1024,+ Height = 1024,+ Margin = 2,+ };+ encodingOptions.Hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);+ barcodeWriter.Options = encodingOptions;++ SvgImage svg = barcodeWriter.Write(text);+ return svg.Content;+ }++ internal static async Task<string> ReadQrCodeAsync(Stream stream, CancellationToken cancellationToken)+ {+ using Image<Rgba32> bitmap = await Image.LoadAsync<Rgba32>(stream, cancellationToken);++ var barcodeReader = new ZXing.ImageSharp.BarcodeReader<Rgba32>()+ {+ AutoRotate = true,+ Options =+ {+ TryHarder = true,+ TryInverted = true,+ PossibleFormats = new List<BarcodeFormat> { BarcodeFormat.QR_CODE }+ }+ };++ Result decodedQrCode = barcodeReader.Decode(bitmap);++ if (decodedQrCode is not null && !string.IsNullOrWhiteSpace(decodedQrCode.Text))+ {+ return decodedQrCode.Text;+ }++ return string.Empty;+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/QRCode/QRCodeEncoderDecoder.Designer.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/QRCode/QRCodeEncoderDecoder.Designer.csnew file mode 100644index 000000000..e8d522ae7--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/QRCode/QRCodeEncoderDecoder.Designer.cs@@ -0,0 +1,162 @@+//------------------------------------------------------------------------------+// <auto-generated>+// This code was generated by a tool.+// Runtime Version:4.0.30319.42000+//+// Changes to this file may cause incorrect behavior and will be lost if+// the code is regenerated.+// </auto-generated>+//------------------------------------------------------------------------------++namespace DevToys.Tools.Tools.EncodersDecoders.QRCode {+ using System;+++ /// <summary>+ /// A strongly-typed resource class, for looking up localized strings, etc.+ /// </summary>+ // This class was auto-generated by the StronglyTypedResourceBuilder+ // class via a tool like ResGen or Visual Studio.+ // To add or remove a member, edit your .ResX file then rerun ResGen+ // with the /str option, or rebuild your VS project.+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]+ internal class QRCodeEncoderDecoder {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal QRCodeEncoderDecoder() {+ }++ /// <summary>+ /// Returns the cached ResourceManager instance used by this class.+ /// </summary>+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]+ internal static global::System.Resources.ResourceManager ResourceManager {+ get {+ if (object.ReferenceEquals(resourceMan, null)) {+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Tools.Tools.EncodersDecoders.QRCode.QRCodeEncoderDecoder", typeof(QRCodeEncoderDecoder).Assembly);+ resourceMan = temp;+ }+ return resourceMan;+ }+ }++ /// <summary>+ /// Overrides the current thread's CurrentUICulture property for all+ /// resource lookups using this strongly typed resource class.+ /// </summary>+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]+ internal static global::System.Globalization.CultureInfo Culture {+ get {+ return resourceCulture;+ }+ set {+ resourceCulture = value;+ }+ }++ /// <summary>+ /// Looks up a localized string similar to QR Code Encoder and Decoder tool.+ /// </summary>+ internal static string AccessibleName {+ get {+ return ResourceManager.GetString("AccessibleName", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Read or generate a QR Code from a text. Can be exported as SVG..+ /// </summary>+ internal static string Description {+ get {+ return ResourceManager.GetString("Description", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Export as SVG.+ /// </summary>+ internal static string ExportAsSvgButtonTitle {+ get {+ return ResourceManager.GetString("ExportAsSvgButtonTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to QR Code.+ /// </summary>+ internal static string ImageWithQrCode {+ get {+ return ResourceManager.GetString("ImageWithQrCode", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Image file path containing a QR Code to decode / text file path containing the text to convert to a QR Code.+ /// </summary>+ internal static string InputOptionDescription {+ get {+ return ResourceManager.GetString("InputOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Text.+ /// </summary>+ internal static string InputText {+ get {+ return ResourceManager.GetString("InputText", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to QR Code Encoder / Decoder.+ /// </summary>+ internal static string LongDisplayTitle {+ get {+ return ResourceManager.GetString("LongDisplayTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to No QR Code found in this image.+ /// </summary>+ internal static string NoQrCodeFound {+ get {+ return ResourceManager.GetString("NoQrCodeFound", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Path to the output file.+ /// </summary>+ internal static string OutputFileOptionDescription {+ get {+ return ResourceManager.GetString("OutputFileOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to QRCode URL.+ /// </summary>+ internal static string SearchKeywords {+ get {+ return ResourceManager.GetString("SearchKeywords", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to QR Code.+ /// </summary>+ internal static string ShortDisplayTitle {+ get {+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/QRCode/QRCodeEncoderDecoder.resx b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/QRCode/QRCodeEncoderDecoder.resxnew file mode 100644index 000000000..0d7047233--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/QRCode/QRCodeEncoderDecoder.resx@@ -0,0 +1,154 @@+<?xml version="1.0" encoding="utf-8"?>+<root>+ <!--+ Microsoft ResX Schema++ Version 2.0++ The primary goals of this format is to allow a simple XML format+ that is mostly human readable. The generation and parsing of the+ various data types are done through the TypeConverter classes+ associated with the data types.++ Example:++ ... ado.net/XML headers & schema ...+ <resheader name="resmimetype">text/microsoft-resx</resheader>+ <resheader name="version">2.0</resheader>+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">+ <value>[base64 mime encoded serialized .NET Framework object]</value>+ </data>+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>+ <comment>This is a comment</comment>+ </data>++ There are any number of "resheader" rows that contain simple+ name/value pairs.++ Each data row contains a name, and value. The row also contains a+ type or mimetype. Type corresponds to a .NET class that support+ text/value conversion through the TypeConverter architecture.+ Classes that don't support this are serialized and stored with the+ mimetype set.++ The mimetype is used for serialized objects, and tells the+ ResXResourceReader how to depersist the object. This is currently not+ extensible. For a given mimetype the value must be set accordingly:++ Note - application/x-microsoft.net.object.binary.base64 is the format+ that the ResXResourceWriter will generate, however the reader can+ read any of the formats listed below.++ mimetype: application/x-microsoft.net.object.binary.base64+ value : The object must be serialized with+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter+ : and then encoded with base64 encoding.++ mimetype: application/x-microsoft.net.object.soap.base64+ value : The object must be serialized with+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter+ : and then encoded with base64 encoding.++ mimetype: application/x-microsoft.net.object.bytearray.base64+ value : The object must be serialized into a byte array+ : using a System.ComponentModel.TypeConverter+ : and then encoded with base64 encoding.+ -->+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />+ <xsd:element name="root" msdata:IsDataSet="true">+ <xsd:complexType>+ <xsd:choice maxOccurs="unbounded">+ <xsd:element name="metadata">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" />+ </xsd:sequence>+ <xsd:attribute name="name" use="required" type="xsd:string" />+ <xsd:attribute name="type" type="xsd:string" />+ <xsd:attribute name="mimetype" type="xsd:string" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="assembly">+ <xsd:complexType>+ <xsd:attribute name="alias" type="xsd:string" />+ <xsd:attribute name="name" type="xsd:string" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="data">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="resheader">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" />+ </xsd:complexType>+ </xsd:element>+ </xsd:choice>+ </xsd:complexType>+ </xsd:element>+ </xsd:schema>+ <resheader name="resmimetype">+ <value>text/microsoft-resx</value>+ </resheader>+ <resheader name="version">+ <value>2.0</value>+ </resheader>+ <resheader name="reader">+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <resheader name="writer">+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <data name="AccessibleName" xml:space="preserve">+ <value>QR Code Encoder and Decoder tool</value>+ </data>+ <data name="Description" xml:space="preserve">+ <value>Read or generate a QR Code from a text. Can be exported as SVG.</value>+ </data>+ <data name="ExportAsSvgButtonTitle" xml:space="preserve">+ <value>Export as SVG</value>+ </data>+ <data name="ImageWithQrCode" xml:space="preserve">+ <value>QR Code</value>+ </data>+ <data name="InputOptionDescription" xml:space="preserve">+ <value>Image file path containing a QR Code to decode / text file path containing the text to convert to a QR Code</value>+ </data>+ <data name="InputText" xml:space="preserve">+ <value>Text</value>+ </data>+ <data name="LongDisplayTitle" xml:space="preserve">+ <value>QR Code Encoder / Decoder</value>+ </data>+ <data name="NoQrCodeFound" xml:space="preserve">+ <value>No QR Code found in this image</value>+ </data>+ <data name="OutputFileOptionDescription" xml:space="preserve">+ <value>Path to the output file</value>+ </data>+ <data name="SearchKeywords" xml:space="preserve">+ <value>QRCode URL</value>+ <comment>Alternative search keywords.</comment>+ </data>+ <data name="ShortDisplayTitle" xml:space="preserve">+ <value>QR Code</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/QRCode/QRCodeEncoderDecoderCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/QRCode/QRCodeEncoderDecoderCommandLineTool.csnew file mode 100644index 000000000..1f93afb42--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/QRCode/QRCodeEncoderDecoderCommandLineTool.cs@@ -0,0 +1,151 @@+using DevToys.Tools.Helpers;+using DevToys.Tools.SmartDetection;+using DevToys.Tools.Strings.GlobalStrings;+using Microsoft.Extensions.Logging;+using OneOf;+using SixLabors.ImageSharp;+using SixLabors.ImageSharp.PixelFormats;++namespace DevToys.Tools.Tools.EncodersDecoders.QRCode;++[Export(typeof(ICommandLineTool))]+[Name("QRCodeEncoderDecoder")]+[CommandName(+ Name = "qrcode",+ ResourceManagerBaseName = "DevToys.Tools.Tools.EncodersDecoders.QRCode.QRCodeEncoderDecoder",+ DescriptionResourceName = nameof(QRCodeEncoderDecoder.Description))]+internal class QRCodeEncoderDecoderCommandLineTool : ICommandLineTool+{+ private readonly Lazy<string[]> _supportedFileTypes+ = new(() =>+ {+ var extensions = new List<string>(StaticImageFileDataTypeDetector.SupportedFileTypes);+ extensions.Add(".svg");+ return extensions.ToArray();+ });++#pragma warning disable IDE0044 // Add readonly modifier+ [Import]+ private IFileStorage _fileStorage = null!;+#pragma warning restore IDE0044 // Add readonly modifier++ [CommandLineOption(+ Name = "input",+ Alias = "i",+ IsRequired = true,+ DescriptionResourceName = nameof(QRCodeEncoderDecoder.InputOptionDescription))]+ internal OneOf<FileInfo, string>? Input { get; set; }++ [CommandLineOption(+ Name = "outputFile",+ Alias = "o",+ DescriptionResourceName = nameof(QRCodeEncoderDecoder.OutputFileOptionDescription))]+ internal FileInfo? OutputFile { get; set; }++ public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)+ {+ if (!Input.HasValue)+ {+ return -1;+ }++ return await Input.Value.Match(+ async file =>+ {+ if (!file.Exists)+ {+ Console.Error.WriteLine(string.Format(GlobalStrings.FileNotFound, file.FullName));+ return -1;+ }++ string fileExtension = file.Extension;+ bool isImageFile = StaticImageFileDataTypeDetector.SupportedFileTypes.Any(ext => ext.Equals(fileExtension, StringComparison.OrdinalIgnoreCase));+ if (isImageFile)+ {+ await DecodeQRCodeAsync(file, cancellationToken);+ }+ else+ {+ string text = await File.ReadAllTextAsync(file.FullName, cancellationToken);+ return await EncodeQRCodeAsync(text, cancellationToken);+ }++ return 0;+ },+ async text => await EncodeQRCodeAsync(text, cancellationToken));+ }++ private async ValueTask<int> EncodeQRCodeAsync(string input, CancellationToken cancellationToken)+ {+ try+ {+ if (string.IsNullOrWhiteSpace(input))+ {+ return -1;+ }++ string filePath;+ if (OutputFile is null)+ {+ using FileStream? fileStream = await _fileStorage.PickSaveFileAsync(_supportedFileTypes.Value);+ if (fileStream is null)+ {+ return -1;+ }++ filePath = fileStream.Name;+ }+ else+ {+ filePath = OutputFile.FullName;+ }++ if (cancellationToken.IsCancellationRequested)+ {+ return -1;+ }++ if (File.Exists(filePath))+ {+ File.Delete(filePath);+ }++ if (Path.GetExtension(filePath).Equals(".svg", StringComparison.OrdinalIgnoreCase))+ {+ string svg = QrCodeHelper.GenerateSvgQrCode(input);+ using var fileWriter = new StreamWriter(filePath);+ await fileWriter.WriteAsync(svg);+ }+ else+ {+ using Image<Rgba32> image = QrCodeHelper.GenerateQrCode(input);+ await image.SaveAsync(filePath, cancellationToken);+ }++ return 0;+ }+ catch+ {+ return -1;+ }+ finally+ {+ }+ }++ private async ValueTask<int> DecodeQRCodeAsync(FileInfo file, CancellationToken cancellationToken)+ {+ using Stream stream = _fileStorage.OpenReadFile(file.FullName);++ string output = await QrCodeHelper.ReadQrCodeAsync(stream, cancellationToken);++ if (string.IsNullOrEmpty(output))+ {+ Console.Error.WriteLine(QRCodeEncoderDecoder.NoQrCodeFound);+ return -1;+ }++ await FileHelper.WriteOutputAsync(output, OutputFile, cancellationToken);+ return 0;+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/QRCode/QRCodeEncoderDecoderGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/QRCode/QRCodeEncoderDecoderGuiTool.csnew file mode 100644index 000000000..68ee24e6e--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/QRCode/QRCodeEncoderDecoderGuiTool.cs@@ -0,0 +1,223 @@+using DevToys.Tools.Helpers;+using Microsoft.Extensions.Logging;+using SixLabors.ImageSharp;+using SixLabors.ImageSharp.PixelFormats;+using ZXing;+using ZXing.Common;+using ZXing.QrCode.Internal;+using ZXing.Rendering;+using static ZXing.Rendering.SvgRenderer;++namespace DevToys.Tools.Tools.EncodersDecoders.QRCode;++[Export(typeof(IGuiTool))]+[Name("QRCodeEncoderDecoder")]+[ToolDisplayInformation(+ IconFontName = "FluentSystemIcons",+ IconGlyph = '\uE9EC',+ GroupName = PredefinedCommonToolGroupNames.EncodersDecoders,+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),+ ResourceManagerBaseName = "DevToys.Tools.Tools.EncodersDecoders.QRCode.QRCodeEncoderDecoder",+ ShortDisplayTitleResourceName = nameof(QRCodeEncoderDecoder.ShortDisplayTitle),+ LongDisplayTitleResourceName = nameof(QRCodeEncoderDecoder.LongDisplayTitle),+ DescriptionResourceName = nameof(QRCodeEncoderDecoder.Description),+ AccessibleNameResourceName = nameof(QRCodeEncoderDecoder.AccessibleName),+ SearchKeywordsResourceName = nameof(QRCodeEncoderDecoder.SearchKeywords))]+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Image)]+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Text)]+internal sealed partial class QRCodeEncoderDecoderGuiTool : IGuiTool, IDisposable+{+ private enum GridRows+ {+ FileInput,+ ImagePreviewer+ }++ private enum GridColumns+ {+ Stretch+ }++ private readonly DisposableSemaphore _semaphore = new();+ private readonly IFileStorage _fileStorage;+ private readonly ILogger _logger;+ private readonly IUIMultiLineTextInput _inputText = MultilineTextInput("qrcode-input-box");+ private readonly IUIFileSelector _fileSelector = FileSelector("qrcode-file-selector");+ private readonly IUIImageViewer _imageViewer = ImageViewer("qrcode-preview");+ private readonly IUIButton _exportAsSvgButton = Button("qrcode-export-as-svg-button");++ private SandboxedFileReader? _selectedFile;+ private CancellationTokenSource? _cancellationTokenSource;+ private bool _ignoreTextChange;++ [ImportingConstructor]+ public QRCodeEncoderDecoderGuiTool(IFileStorage fileStorage)+ {+ _fileStorage = fileStorage;+ _logger = this.Log();+ }++ // For unit tests.+ internal Task? WorkTask { get; private set; }++ public UIToolView View+ => new(+ isScrollable: true,+ SplitGrid()+ .Vertical()+ .LeftPaneLength(new UIGridLength(4, UIGridUnitType.Fraction))+ .RightPaneLength(new UIGridLength(2, UIGridUnitType.Fraction))++ .WithLeftPaneChild(+ _inputText+ .Title(QRCodeEncoderDecoder.InputText)+ .AlwaysWrap()+ .CanCopyWhenEditable()+ .OnTextChanged(OnInputTextChanged))++ .WithRightPaneChild(+ Grid()+ .RowLargeSpacing()++ .Rows(+ (GridRows.FileInput, Auto),+ (GridRows.ImagePreviewer, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Columns(+ (GridColumns.Stretch, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Cells(+ Cell(+ GridRows.FileInput,+ GridColumns.Stretch,++ _fileSelector+ .CanSelectOneFile()+ .LimitFileTypesToImages()+ .OnFilesSelected(OnFileSelectedAsync)),++ Cell(+ GridRows.ImagePreviewer,+ GridColumns.Stretch,++ _imageViewer+ .Title(QRCodeEncoderDecoder.ImageWithQrCode)+ .ManuallyHandleSaveAs("svg", OnSaveAsSvgAsync)))));++ public async void OnDataReceived(string dataTypeName, object? parsedData)+ {+ if (dataTypeName == PredefinedCommonDataTypeNames.Text && parsedData is string text)+ {+ _inputText.Text(text); // This will trigger a conversion.+ }+ else if (dataTypeName == PredefinedCommonDataTypeNames.Image && parsedData is Image<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.+ }+ }++ public void Dispose()+ {+ _selectedFile?.Dispose();+ _cancellationTokenSource?.Cancel();+ _cancellationTokenSource?.Dispose();+ _semaphore.Dispose();+ }++ private async ValueTask OnSaveAsSvgAsync(FileStream fileStream)+ {+ string svg = QrCodeHelper.GenerateSvgQrCode(_inputText.Text);+ using var fileWriter = new StreamWriter(fileStream);+ await fileWriter.WriteAsync(svg);+ }++ private void OnInputTextChanged(string text)+ {+ if (!_ignoreTextChange)+ {+ StartConvert(text);+ }+ }++ private ValueTask OnFileSelectedAsync(SandboxedFileReader[] files)+ {+ Guard.HasSizeEqualTo(files, 1);++ _selectedFile?.Dispose();+ _selectedFile = files[0];+ _imageViewer.WithPickedFile(_selectedFile, false);++ StartConvert(_selectedFile);+ return ValueTask.CompletedTask;+ }++ private void StartConvert(SandboxedFileReader file)+ {+ _cancellationTokenSource?.Cancel();+ _cancellationTokenSource?.Dispose();+ _cancellationTokenSource = new CancellationTokenSource();++ WorkTask = DecodeQRCodeAsync(file, _cancellationTokenSource.Token);+ }++ private void StartConvert(string text)+ {+ _cancellationTokenSource?.Cancel();+ _cancellationTokenSource?.Dispose();+ _cancellationTokenSource = new CancellationTokenSource();++ WorkTask = EncodeQRCodeAsync(text, _cancellationTokenSource.Token);+ }++ private async Task EncodeQRCodeAsync(string input, CancellationToken cancellationToken)+ {+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);++ try+ {+ using (await _semaphore.WaitAsync(cancellationToken))+ {+ if (string.IsNullOrWhiteSpace(input))+ {+ _imageViewer.Clear();+ return;+ }++ Image<Rgba32> image = QrCodeHelper.GenerateQrCode(input); // Do not dispose the image. Will be disposed by the image viewer when the image is replaced.++ _imageViewer.WithImage(image, disposeAutomatically: true);+ _exportAsSvgButton.Enable();+ }+ }+ catch+ {+ _imageViewer.Clear();+ }+ }++ private async Task DecodeQRCodeAsync(SandboxedFileReader file, CancellationToken cancellationToken)+ {+ _exportAsSvgButton.Disable();++ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);++ using (await _semaphore.WaitAsync(cancellationToken))+ {+ using Stream stream = await file.GetNewAccessToFileContentAsync(cancellationToken);++ string output = await QrCodeHelper.ReadQrCodeAsync(stream, cancellationToken);++ _ignoreTextChange = true;+ _inputText.Text(output);+ _ignoreTextChange = false;+ }+ }+}