A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Ported Text Escape/ Unescape tool (#1019)
Etienne BAUDOUXe158745bac81
diff --git a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj b/src/app/dev/DevToys.Tools/DevToys.Tools.csprojindex 4f5fdd6c0..9b35e645b 100644--- a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj+++ b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj@@ -168,6 +168,11 @@<AutoGen>True</AutoGen><DependentUpon>TextCompare.resx</DependentUpon></Compile>+ <Compile Update="Tools\Text\EscapeUnescape\EscapeUnescape.Designer.cs">+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ <DependentUpon>EscapeUnescape.resx</DependentUpon>+ </Compile><Compile Update="Tools\Text\MarkdownPreview\MarkdownPreview.Designer.cs"><DesignTime>True</DesignTime><AutoGen>True</AutoGen>@@ -298,6 +303,10 @@<Generator>ResXFileCodeGenerator</Generator><LastGenOutput>TextCompare.Designer.cs</LastGenOutput></EmbeddedResource>+ <EmbeddedResource Update="Tools\Text\EscapeUnescape\EscapeUnescape.resx">+ <Generator>ResXFileCodeGenerator</Generator>+ <LastGenOutput>EscapeUnescape.Designer.cs</LastGenOutput>+ </EmbeddedResource><EmbeddedResource Update="Tools\Text\MarkdownPreview\MarkdownPreview.resx"><Generator>ResXFileCodeGenerator</Generator><LastGenOutput>MarkdownPreview.Designer.cs</LastGenOutput>diff --git a/src/app/dev/DevToys.Tools/Helpers/StringHelper.cs b/src/app/dev/DevToys.Tools/Helpers/StringHelper.csindex 24ac401bc..48e0ac298 100644--- a/src/app/dev/DevToys.Tools/Helpers/StringHelper.cs+++ b/src/app/dev/DevToys.Tools/Helpers/StringHelper.cs@@ -2,6 +2,7 @@using System.Text.RegularExpressions;using DevToys.Tools.Helpers.Core;using DevToys.Tools.Models;+using Microsoft.Extensions.Logging;namespace DevToys.Tools.Helpers;@@ -9,6 +10,174 @@ internal static class StringHelper{private static readonly Random random = new();+ internal static bool HasEscapeCharacters(string text)+ {+ // TODO: This could be improved. Using multiple Contains means we have to iterate through the text multiple times.+ return text.Contains("\\n")+ || text.Contains("\\r")+ || text.Contains("\\\\")+ || text.Contains("\\\"")+ || text.Contains("\\t")+ || text.Contains("\\f")+ || text.Contains("\\b");+ }++ internal static ResultInfo<string> EscapeString(string? data, ILogger logger, CancellationToken cancellationToken)+ {+ if (string.IsNullOrWhiteSpace(data))+ {+ return new(string.Empty, HasSucceeded: true);+ }++ var encoded = new StringBuilder();++ try+ {+ int i = 0;+ while (i < data!.Length)+ {+ if (cancellationToken.IsCancellationRequested)+ {+ return new(string.Empty, HasSucceeded: false);+ }++ string replacementString = string.Empty;+ int jumpLength = 0;+ if (TextMatchAtIndex(data, "\n", i))+ {+ jumpLength = 1;+ replacementString = "\\n";+ }+ else if (TextMatchAtIndex(data, "\r", i))+ {+ jumpLength = 1;+ replacementString = "\\r";+ }+ else if (TextMatchAtIndex(data, "\t", i))+ {+ jumpLength = 1;+ replacementString = "\\t";+ }+ else if (TextMatchAtIndex(data, "\b", i))+ {+ jumpLength = 1;+ replacementString = "\\b";+ }+ else if (TextMatchAtIndex(data, "\f", i))+ {+ jumpLength = 1;+ replacementString = "\\f";+ }+ else if (TextMatchAtIndex(data, "\"", i))+ {+ jumpLength = 1;+ replacementString = "\\\"";+ }+ else if (TextMatchAtIndex(data, "\\", i))+ {+ jumpLength = 1;+ replacementString = "\\\\";+ }++ if (!string.IsNullOrEmpty(replacementString) && jumpLength > 0)+ {+ encoded.Append(replacementString);+ i += jumpLength;+ }+ else+ {+ encoded.Append(data[i]);+ i++;+ }+ }+ }+ catch (Exception ex)+ {+ logger.LogError(ex, "Failed to escape text");+ return new(ex.Message, HasSucceeded: false);+ }++ return new(encoded.ToString(), HasSucceeded: true);+ }++ internal static ResultInfo<string> UnescapeString(string? data, ILogger logger, CancellationToken cancellationToken)+ {+ if (string.IsNullOrWhiteSpace(data))+ {+ return new(string.Empty, HasSucceeded: false);+ }++ var decoded = new StringBuilder();++ try+ {+ int i = 0;+ while (i < data!.Length)+ {+ if (cancellationToken.IsCancellationRequested)+ {+ return new(string.Empty, HasSucceeded: false);+ }++ string replacementString = string.Empty;+ int jumpLength = 0;+ if (TextMatchAtIndex(data, "\\n", i))+ {+ jumpLength = 2;+ replacementString = "\n";+ }+ else if (TextMatchAtIndex(data, "\\r", i))+ {+ jumpLength = 2;+ replacementString = "\r";+ }+ else if (TextMatchAtIndex(data, "\\t", i))+ {+ jumpLength = 2;+ replacementString = "\t";+ }+ else if (TextMatchAtIndex(data, "\\b", i))+ {+ jumpLength = 2;+ replacementString = "\b";+ }+ else if (TextMatchAtIndex(data, "\\f", i))+ {+ jumpLength = 2;+ replacementString = "\f";+ }+ else if (TextMatchAtIndex(data, "\\\"", i))+ {+ jumpLength = 2;+ replacementString = "\"";+ }+ else if (TextMatchAtIndex(data, "\\\\", i))+ {+ jumpLength = 2;+ replacementString = "\\";+ }++ if (!string.IsNullOrEmpty(replacementString) && jumpLength > 0)+ {+ decoded.Append(replacementString);+ i += jumpLength;+ }+ else+ {+ decoded.Append(data[i]);+ i++;+ }+ }+ }+ catch (Exception ex)+ {+ logger.LogError(ex, "Failed to escape text");+ return new(ex.Message, HasSucceeded: false);+ }++ return new(decoded.ToString(), HasSucceeded: true);+ }+internal static string SortLinesAlphabetically(string text, EndOfLineSequence endOfLineSequence){return SortLines(@@ -711,4 +880,27 @@ internal static class StringHelper// Rebuilt the text.return lines.BuildStringFromListOfLines(endOfLineSequence);}++ private static bool TextMatchAtIndex(string data, string test, int startIndex)+ {+ if (string.IsNullOrEmpty(test))+ {+ return false;+ }++ if (data.Length < test.Length)+ {+ return false;+ }++ for (int i = 0; i < test.Length; i++)+ {+ if (data[startIndex + i] != test[i])+ {+ return false;+ }+ }++ return true;+ }}diff --git a/src/app/dev/DevToys.Tools/SmartDetection/EscapedCharactersDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/EscapedCharactersDetector.csnew file mode 100644index 000000000..e4eb1b929--- /dev/null+++ b/src/app/dev/DevToys.Tools/SmartDetection/EscapedCharactersDetector.cs@@ -0,0 +1,29 @@++using DevToys.Tools.Helpers;++namespace DevToys.Tools.SmartDetection;++[Export(typeof(IDataTypeDetector))]+[DataTypeName(InternalName, baseName: PredefinedCommonDataTypeNames.Text)]+internal sealed class EscapedCharactersDetector : IDataTypeDetector+{+ internal const string InternalName = "TextWithEscapedCharacters";++ public ValueTask<DataDetectionResult> TryDetectDataAsync(object rawData, DataDetectionResult? resultFromBaseDetector, CancellationToken cancellationToken)+ {+ if (resultFromBaseDetector is not null+ && resultFromBaseDetector.Data is string dataString+ && !long.TryParse(dataString, out _)+ && !string.IsNullOrWhiteSpace(dataString))+ {+ bool hasEscapedCharacters = StringHelper.HasEscapeCharacters(dataString);++ if (hasEscapedCharacters)+ {+ return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: dataString));+ }+ }++ return ValueTask.FromResult(DataDetectionResult.Unsuccessful);+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Text/EscapeUnescape/EscapeUnescape.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Text/EscapeUnescape/EscapeUnescape.Designer.csnew file mode 100644index 000000000..017dcd4a9--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Text/EscapeUnescape/EscapeUnescape.Designer.cs@@ -0,0 +1,207 @@+//------------------------------------------------------------------------------+// <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.Text.EscapeUnescape {+ 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 EscapeUnescape {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal EscapeUnescape() {+ }++ /// <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.Text.EscapeUnescape.EscapeUnescape", typeof(EscapeUnescape).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 Text Escape and Unescape tool.+ /// </summary>+ internal static string AccessibleName {+ get {+ return ResourceManager.GetString("AccessibleName", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Configuration.+ /// </summary>+ internal static string ConfigurationTitle {+ get {+ return ResourceManager.GetString("ConfigurationTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Unescape.+ /// </summary>+ internal static string ConversionDecode {+ get {+ return ResourceManager.GetString("ConversionDecode", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Select which conversion mode you want to use.+ /// </summary>+ internal static string ConversionDescription {+ get {+ return ResourceManager.GetString("ConversionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Escape.+ /// </summary>+ internal static string ConversionEncode {+ get {+ return ResourceManager.GetString("ConversionEncode", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Whether to escape or unescape the input text.+ /// </summary>+ internal static string ConversionOptionDescription {+ get {+ return ResourceManager.GetString("ConversionOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Conversion.+ /// </summary>+ internal static string ConversionTitle {+ get {+ return ResourceManager.GetString("ConversionTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Escapes or unescapes a string, removing characters that could prevent parsing..+ /// </summary>+ internal static string Description {+ get {+ return ResourceManager.GetString("Description", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Input file selected doesn't exist.+ /// </summary>+ internal static string InputFileNotFound {+ get {+ return ResourceManager.GetString("InputFileNotFound", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Text or path to a file to convert to escaped or unescaped text.+ /// </summary>+ internal static string InputOptionDescription {+ get {+ return ResourceManager.GetString("InputOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Input.+ /// </summary>+ internal static string InputTitle {+ get {+ return ResourceManager.GetString("InputTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Please specify an input text or an input file.+ /// </summary>+ internal static string InvalidInputOrFileCommand {+ get {+ return ResourceManager.GetString("InvalidInputOrFileCommand", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Text Escape / Unescape.+ /// </summary>+ internal static string LongDisplayTitle {+ get {+ return ResourceManager.GetString("LongDisplayTitle", 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 Output.+ /// </summary>+ internal static string OutputTitle {+ get {+ return ResourceManager.GetString("OutputTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Escape / Unescape.+ /// </summary>+ internal static string ShortDisplayTitle {+ get {+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Text/EscapeUnescape/EscapeUnescape.resx b/src/app/dev/DevToys.Tools/Tools/Text/EscapeUnescape/EscapeUnescape.resxnew file mode 100644index 000000000..75131928e--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Text/EscapeUnescape/EscapeUnescape.resx@@ -0,0 +1,168 @@+<?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>Text Escape and Unescape tool</value>+ </data>+ <data name="ConfigurationTitle" xml:space="preserve">+ <value>Configuration</value>+ </data>+ <data name="ConversionDecode" xml:space="preserve">+ <value>Unescape</value>+ </data>+ <data name="ConversionDescription" xml:space="preserve">+ <value>Select which conversion mode you want to use</value>+ </data>+ <data name="ConversionEncode" xml:space="preserve">+ <value>Escape</value>+ </data>+ <data name="ConversionOptionDescription" xml:space="preserve">+ <value>Whether to escape or unescape the input text</value>+ </data>+ <data name="ConversionTitle" xml:space="preserve">+ <value>Conversion</value>+ </data>+ <data name="Description" xml:space="preserve">+ <value>Escapes or unescapes a string, removing characters that could prevent parsing.</value>+ </data>+ <data name="InputFileNotFound" xml:space="preserve">+ <value>Input file selected doesn't exist</value>+ </data>+ <data name="InputOptionDescription" xml:space="preserve">+ <value>Text or path to a file to convert to escaped or unescaped text</value>+ </data>+ <data name="InputTitle" xml:space="preserve">+ <value>Input</value>+ </data>+ <data name="InvalidInputOrFileCommand" xml:space="preserve">+ <value>Please specify an input text or an input file</value>+ </data>+ <data name="LongDisplayTitle" xml:space="preserve">+ <value>Text Escape / Unescape</value>+ </data>+ <data name="OutputFileOptionDescription" xml:space="preserve">+ <value>Path to the output file</value>+ </data>+ <data name="OutputTitle" xml:space="preserve">+ <value>Output</value>+ </data>+ <data name="ShortDisplayTitle" xml:space="preserve">+ <value>Escape / Unescape</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/Text/EscapeUnescape/EscapeUnescapeCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/Text/EscapeUnescape/EscapeUnescapeCommandLineTool.csnew file mode 100644index 000000000..622bc0094--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Text/EscapeUnescape/EscapeUnescapeCommandLineTool.cs@@ -0,0 +1,78 @@+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using Microsoft.Extensions.Logging;+using OneOf;++namespace DevToys.Tools.Tools.Text.EscapeUnescape;++[Export(typeof(ICommandLineTool))]+[Name("EscapeUnescape")]+[CommandName(+ Name = "escape",+ Alias = "esc",+ ResourceManagerBaseName = "DevToys.Tools.Tools.Text.EscapeUnescape.EscapeUnescape",+ DescriptionResourceName = nameof(EscapeUnescape.Description))]+internal sealed class EscapeUnescapeCommandLineTool : ICommandLineTool+{+#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(EscapeUnescape.InputOptionDescription))]+ private OneOf<FileInfo, string>? Input { get; set; }++ [CommandLineOption(+ Name = "outputFile",+ Alias = "o",+ DescriptionResourceName = nameof(EscapeUnescape.OutputFileOptionDescription))]+ internal FileInfo? OutputFile { get; set; }++ [CommandLineOption(+ Name = "conversion",+ Alias = "c",+ DescriptionResourceName = nameof(EscapeUnescape.ConversionOptionDescription))]+ private EncodingConversion EncodingConversionMode { get; set; } = EncodingConversion.Encode;++ public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)+ {+ ResultInfo<string> result;+ if (!Input.HasValue)+ {+ Console.Error.WriteLine(EscapeUnescape.InvalidInputOrFileCommand);+ return -1;+ }++ result = await Input.Value.ReadAllTextAsync(_fileStorage, cancellationToken);+ if (!result.HasSucceeded)+ {+ Console.Error.WriteLine(EscapeUnescape.InputFileNotFound);+ return -1;+ }++ Guard.IsNotNull(result.Data);+ ResultInfo<string> output = EncodingConversionMode switch+ {+ EncodingConversion.Encode => StringHelper.EscapeString(result.Data, logger, cancellationToken),+ EncodingConversion.Decode => StringHelper.UnescapeString(result.Data, logger, cancellationToken),+ _ => throw new NotSupportedException(),+ };++ cancellationToken.ThrowIfCancellationRequested();++ if (output.HasSucceeded)+ {+ await FileHelper.WriteOutputAsync(output.Data, OutputFile, cancellationToken);+ return 0;+ }+ else+ {+ Console.Error.WriteLine(output.Data);+ return -1;+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Text/EscapeUnescape/EscapeUnescapeGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Text/EscapeUnescape/EscapeUnescapeGuiTool.csnew file mode 100644index 000000000..457a43bbf--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Text/EscapeUnescape/EscapeUnescapeGuiTool.cs@@ -0,0 +1,187 @@+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using DevToys.Tools.SmartDetection;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.Tools.Text.EscapeUnescape;++[Export(typeof(IGuiTool))]+[Name("EscapeUnescape")]+[ToolDisplayInformation(+ IconFontName = "DevToys-Tools-Icons",+ IconGlyph = '\u0130',+ GroupName = PredefinedCommonToolGroupNames.Text,+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),+ ResourceManagerBaseName = "DevToys.Tools.Tools.Text.EscapeUnescape.EscapeUnescape",+ ShortDisplayTitleResourceName = nameof(EscapeUnescape.ShortDisplayTitle),+ LongDisplayTitleResourceName = nameof(EscapeUnescape.LongDisplayTitle),+ DescriptionResourceName = nameof(EscapeUnescape.Description),+ AccessibleNameResourceName = nameof(EscapeUnescape.AccessibleName))]+[AcceptedDataTypeName(EscapedCharactersDetector.InternalName)]+internal sealed class EscapeUnescapeGuiTool : IGuiTool, IDisposable+{+ /// <summary>+ /// Whether the tool should escape or unescape the text.+ /// </summary>+ private static readonly SettingDefinition<EncodingConversion> conversionMode+ = new(+ name: $"{nameof(EscapeUnescapeGuiTool)}.{nameof(conversionMode)}",+ defaultValue: EncodingConversion.Encode);+ private enum GridRows+ {+ Settings,+ Input,+ Output+ }++ private enum GridColumns+ {+ Stretch+ }+++ private readonly DisposableSemaphore _semaphore = new();+ private readonly ILogger _logger;+ private readonly ISettingsProvider _settingsProvider;+ private readonly IUISwitch _conversionModeSwitch = Switch("text-escape-unescape-conversion-mode-switch");+ private readonly IUIMultiLineTextInput _inputText = MultilineTextInput("text-escape-unescape-input-box");+ private readonly IUIMultiLineTextInput _outputText = MultilineTextInput("text-escape-unescape-output-box");++ private CancellationTokenSource? _cancellationTokenSource;++ [ImportingConstructor]+ public EscapeUnescapeGuiTool(ISettingsProvider settingsProvider)+ {+ _logger = this.Log();+ _settingsProvider = settingsProvider;++ if (_settingsProvider.GetSetting(conversionMode) == EncodingConversion.Encode)+ {+ _conversionModeSwitch.On();+ }+ }++ // For unit tests.+ internal Task? WorkTask { get; private set; }++ public UIToolView View+ => new(+ isScrollable: true,+ Grid()+ .RowLargeSpacing()++ .Rows(+ (GridRows.Settings, Auto),+ (GridRows.Input, new UIGridLength(1, UIGridUnitType.Fraction)),+ (GridRows.Output, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Columns(+ (GridColumns.Stretch, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Cells(+ Cell(+ GridRows.Settings,+ GridColumns.Stretch,++ Stack()+ .Vertical()+ .SmallSpacing()++ .WithChildren(+ Label()+ .Text(EscapeUnescape.ConfigurationTitle),++ Setting("text-escape-unescape-conversion-mode-setting")+ .Icon("FluentSystemIcons", '\uF18D')+ .Title(EscapeUnescape.ConversionTitle)+ .Description(EscapeUnescape.ConversionDescription)++ .InteractiveElement(+ _conversionModeSwitch+ .OnText(EscapeUnescape.ConversionEncode)+ .OffText(EscapeUnescape.ConversionDecode)+ .OnToggle(OnConversionModeChanged)))),++ Cell(+ GridRows.Input,+ GridColumns.Stretch,++ _inputText+ .Title(EscapeUnescape.InputTitle)+ .OnTextChanged(OnInputTextChanged)),++ Cell(+ GridRows.Output,+ GridColumns.Stretch,++ _outputText+ .Title(EscapeUnescape.OutputTitle)+ .ReadOnly()+ .Extendable())));++ public void OnDataReceived(string dataTypeName, object? parsedData)+ {+ if (dataTypeName == EscapedCharactersDetector.InternalName && parsedData is string text)+ {+ _conversionModeSwitch.Off(); // Switch to Unescape mode+ _inputText.Text(text); // This will trigger a conversion.+ }+ }++ public void Dispose()+ {+ _cancellationTokenSource?.Cancel();+ _cancellationTokenSource?.Dispose();+ _semaphore.Dispose();+ }++ private void OnConversionModeChanged(bool conversionMode)+ {+ _settingsProvider.SetSetting(+ EscapeUnescapeGuiTool.conversionMode,+ conversionMode ? EncodingConversion.Encode : EncodingConversion.Decode);+ _inputText.Text(_outputText.Text); // This will trigger a conversion.+ }++ private void OnInputTextChanged(string text)+ {+ StartConvert(text);+ }++ private void StartConvert(string text)+ {+ _cancellationTokenSource?.Cancel();+ _cancellationTokenSource?.Dispose();+ _cancellationTokenSource = new CancellationTokenSource();++ WorkTask = ConvertAsync(text, _settingsProvider.GetSetting(conversionMode), _cancellationTokenSource.Token);+ }++ private async Task ConvertAsync(string input, EncodingConversion conversionMode, CancellationToken cancellationToken)+ {+ using (await _semaphore.WaitAsync(cancellationToken))+ {+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);++ ResultInfo<string> conversionResult = conversionMode switch+ {+ EncodingConversion.Encode+ => StringHelper.EscapeString(+ input,+ _logger,+ cancellationToken),++ EncodingConversion.Decode+ => StringHelper.UnescapeString(+ input,+ _logger,+ cancellationToken),++ _ => throw new NotSupportedException(),+ };++ cancellationToken.ThrowIfCancellationRequested();+ _outputText.Text(conversionResult.Data);+ }+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/StringHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/StringHelperTests.csindex d38972f0c..c50c92324 100644--- a/src/app/tests/DevToys.UnitTests/Tools/Helpers/StringHelperTests.cs+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/StringHelperTests.cs@@ -266,4 +266,27 @@ public class StringHelperTests.Should().NotBe(Text2);}++ [Theory]+ [InlineData(null, "")]+ [InlineData("", "")]+ [InlineData("hello world", "hello world")]+ [InlineData("hello\rworld", "hello\\rworld")]+ internal void EscapeString(string input, string expectedResult)+ {+ StringHelper.EscapeString(input, new MockILogger(), CancellationToken.None)+ .Data.Should().Be(expectedResult);+ }++ [Theory]+ [InlineData(null, "")]+ [InlineData("", "")]+ [InlineData("hello world", "hello world")]+ [InlineData("hello\rworld", "hello\rworld")]+ [InlineData("hello\\rworld", "hello\rworld")]+ internal void UnescapeString(string input, string expectedResult)+ {+ StringHelper.UnescapeString(input, new MockILogger(), CancellationToken.None)+ .Data.Should().Be(expectedResult);+ }}diff --git a/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/EscapedCharacterDetectorTests.cs b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/EscapedCharacterDetectorTests.csnew file mode 100644index 000000000..f8c07707a--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/EscapedCharacterDetectorTests.cs@@ -0,0 +1,30 @@+using System.Diagnostics.CodeAnalysis;+using System.Threading.Tasks;+using DevToys.Tools.SmartDetection;+using Microsoft.Extensions.Logging;++namespace DevToys.UnitTests.Tools.SmartDetection;++public class EscapedCharacterDetectorTests+{+ [Theory]+ [InlineData(null, false)]+ [InlineData("", false)]+ [InlineData(" ", false)]+ [InlineData("hello world", false)]+ [InlineData("hello\rworld", false)]+ [InlineData("hello\\rworld", true)]+ public async Task TryDetectDataAsync(string input, bool expectedResult)+ {+ LoggingExtensions.LoggerFactory ??= LoggerFactory.Create(builder => { });++ DataDetectionResult dataDetectionResult = new(false, input);+ EscapedCharactersDetector detector = new();+ DataDetectionResult result = await detector.TryDetectDataAsync(+ input,+ dataDetectionResult,+ default);++ result.Success.Should().Be(expectedResult);+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/JsonArrayDataTypeDetectorTests.cs b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/JsonArrayDataTypeDetectorTests.csindex cd65406f4..6235ef3a3 100644--- a/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/JsonArrayDataTypeDetectorTests.cs+++ b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/JsonArrayDataTypeDetectorTests.cs@@ -5,7 +5,6 @@ using Microsoft.Extensions.Logging;namespace DevToys.UnitTests.Tools.SmartDetection;-[ExcludeFromCodeCoverage]public class JsonArrayDataTypeDetectorTests{[Theory]diff --git a/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/JsonDataTypeDetectorTests.cs b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/JsonDataTypeDetectorTests.csindex 1f56c9da4..93aec3999 100644--- a/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/JsonDataTypeDetectorTests.cs+++ b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/JsonDataTypeDetectorTests.cs@@ -5,7 +5,6 @@ using Microsoft.Extensions.Logging;namespace DevToys.UnitTests.Tools.SmartDetection;-[ExcludeFromCodeCoverage]public class JsonDataTypeDetectorTests{[Theory]diff --git a/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/XmlDataTypeDetectorTests.cs b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/XmlDataTypeDetectorTests.csindex df3b7e6ae..fb5e2bd23 100644--- a/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/XmlDataTypeDetectorTests.cs+++ b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/XmlDataTypeDetectorTests.cs@@ -5,7 +5,6 @@ using Microsoft.Extensions.Logging;namespace DevToys.UnitTests.Tools.SmartDetection;-[ExcludeFromCodeCoverage]public class XmlDataTypeDetectorTests{[Theory]diff --git a/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/YamlDataTypeDetectorTests.cs b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/YamlDataTypeDetectorTests.csindex ac448de0d..b921cb6bb 100644--- a/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/YamlDataTypeDetectorTests.cs+++ b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/YamlDataTypeDetectorTests.cs@@ -5,7 +5,6 @@ using Microsoft.Extensions.Logging;namespace DevToys.UnitTests.Tools.SmartDetection;-[ExcludeFromCodeCoverage]public class YamlDataTypeDetectorTests{[Theory]diff --git a/src/app/tests/DevToys.UnitTests/Tools/Text/EscapeUnescape/EscapeUnescapeGuiToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Text/EscapeUnescape/EscapeUnescapeGuiToolTests.csnew file mode 100644index 000000000..799c0944f--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/Text/EscapeUnescape/EscapeUnescapeGuiToolTests.cs@@ -0,0 +1,50 @@+using System.Threading.Tasks;+using DevToys.Core.Tools.Metadata;+using DevToys.Tools.Tools.Text.EscapeUnescape;++namespace DevToys.UnitTests.Tools.EncodersDecoders.Base64Text;++public sealed class EscapeUnescapeGuiToolTests : MefBasedTest+{+ private readonly EscapeUnescapeGuiTool _tool;+ private readonly UIToolView _toolView;+ private readonly IUIMultiLineTextInput _inputBox;+ private readonly IUIMultiLineTextInput _outputBox;++ public EscapeUnescapeGuiToolTests()+ : base(typeof(EscapeUnescapeGuiTool).Assembly)+ {+ _tool = (EscapeUnescapeGuiTool)MefProvider.ImportMany<IGuiTool, GuiToolMetadata>()+ .Single(t => t.Metadata.InternalComponentName == "EscapeUnescape")+ .Value;++ _toolView = _tool.View;++ _inputBox = (IUIMultiLineTextInput)_toolView.GetChildElementById("text-escape-unescape-input-box");+ _outputBox = (IUIMultiLineTextInput)_toolView.GetChildElementById("text-escape-unescape-output-box");+ }++ [Fact]+ public async Task SwitchConversionMode()+ {+ var conversionMode = (IUISwitch)_toolView.GetChildElementById("text-escape-unescape-conversion-mode-switch");++ _inputBox.Text("hello\rworld");+ await _tool.WorkTask;+ _outputBox.Text.Should().Be("hello\\rworld");++ conversionMode.Off(); // Switch to Unescape++ await _tool.WorkTask;+ _inputBox.Text.Should().Be("hello\\rworld");+ await _tool.WorkTask;+ _outputBox.Text("hello\rworld");++ conversionMode.On(); // Switch to Escape+ await _tool.WorkTask;++ _inputBox.Text("hello\rworld\r");+ await _tool.WorkTask;+ _outputBox.Text.Should().Be("hello\\rworld\\r");+ }+}diff --git a/src/spellcheckerexclusion.dic b/src/spellcheckerexclusion.dicindex 6650fd081..6aabb700d 100644--- a/src/spellcheckerexclusion.dic+++ b/src/spellcheckerexclusion.dic@@ -24,3 +24,4 @@ colorblindsimulatorEcmasinglelinelipsum+Unescape