A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Added better unhandled exception support. Added GuiToolProvider service.
Etienne Baudouxb0244794ce42
diff --git a/src/app/dev/DevToys.Api/MatchSpan.cs b/src/app/dev/DevToys.Api/MatchSpan.csnew file mode 100644index 000000000..7e7768f0e--- /dev/null+++ b/src/app/dev/DevToys.Api/MatchSpan.cs@@ -0,0 +1,23 @@+namespace DevToys.Api;++/// <summary>+/// Represents a span in text.+/// </summary>+public record MatchSpan+{+ /// <summary>+ /// Gets the position at which the span starts.+ /// </summary>+ public int StartPosition { get; }++ /// <summary>+ /// Gets the length of the span.+ /// </summary>+ public int Length { get; }++ public MatchSpan(int startPosition, int length)+ {+ StartPosition = startPosition;+ Length = length;+ }+}diff --git a/src/app/dev/DevToys.Api/Tool/GUI/GuiToolGroup.cs b/src/app/dev/DevToys.Api/Tool/GUI/GuiToolGroup.csnew file mode 100644index 000000000..c7caf5935--- /dev/null+++ b/src/app/dev/DevToys.Api/Tool/GUI/GuiToolGroup.cs@@ -0,0 +1,45 @@+namespace DevToys.Api;++/// <summary>+/// Represents a group or category in the main menu of the app.+/// </summary>+/// <example>+/// <code>+/// [Export(typeof(GuiToolGroup))]+/// [Name("Encoders / Decoders")]+/// [Order(After = "Converters")] // Optional+/// internal sealed class MyGroup : IGuiTool+/// {+/// [ImportingConstructor]+/// internal MyGroup()+/// {+/// IconFontName = "Fluent System-Regular";+/// IconGlyph = "\u0108";+/// DisplayTitle = Sample.CommandDescription;+/// AccessibleName = Sample.CommandDescription;+/// }+/// }+/// </code>+/// </example>+public class GuiToolGroup+{+ /// <summary>+ /// Gets or sets the name of the font to use to display the <see cref="IconGlyph"/>.+ /// </summary>+ public virtual string IconFontName { get; protected set; } = string.Empty;++ /// <summary>+ /// Gets or sets a glyph for the icon of the group.+ /// </summary>+ public virtual string IconGlyph { get; protected set; } = string.Empty;++ /// <summary>+ /// Gets or sets the title to display in the menu.+ /// </summary>+ public virtual string DisplayTitle { get; protected set; } = string.Empty;++ /// <summary>+ /// (optional) Gets or sets the name of the group that will be told to the user when using screen reader.+ /// </summary>+ public virtual string AccessibleName { get; protected set; } = string.Empty;+}diff --git a/src/app/dev/DevToys.Api/Tool/GUI/IGuiTool.cs b/src/app/dev/DevToys.Api/Tool/GUI/IGuiTool.csindex 9fd1a45b4..6b055cef6 100644--- a/src/app/dev/DevToys.Api/Tool/GUI/IGuiTool.cs+++ b/src/app/dev/DevToys.Api/Tool/GUI/IGuiTool.cs@@ -1,34 +1,45 @@namespace DevToys.Api;/// <summary>-/// Represents the factory for tool with a GUI.+/// Represents the declaration of a tool with a GUI./// </summary>+/// <remarks>+/// The project containing the <see cref="System.Resources.ResourceManager"/> with all the strings for the tool should contain an implementation+/// of <see cref="IResourceManagerAssemblyIdentifier"/> as shown in the example.+/// </remarks>/// <example>/// <code>/// [Export(typeof(IGuiTool))]-/// [Name("Base64 Encode / Decoder")]+/// [Name("Base64 Encoder / Decoder")]/// [Author("John Doe")]/// [ToolDisplayInformation(/// IconFontName = "Fluent System-Regular",/// IconGlyph = "\u0108",+/// GroupName = "Encoders / Decoders", // <seealso cref="GuiToolGroup"/>+/// ResourceManagerAssemblyIdentifier = nameof(MyResourceManagerAssemblyIdentifier), // <seealso cref="IResourceManagerAssemblyIdentifier"/>/// ResourceManagerBaseName = "MyProject.Strings",-/// MenuDisplayTitleResourceName = nameof(Strings.MenuDisplayTitle),-/// SearchDisplayTitleResourceName = nameof(Strings.SearchDisplayTitle),-/// DescriptionResourceName = nameof(Strings.Description),-/// AccessibleNameResourceName = nameof(Strings.AccessibleName),-/// SearchKeywordsResourceName = nameof(Strings.SearchKeywords))]-/// [TargetPlatform(Platform.Windows)] // Optional-/// [TargetPlatform(Platform.WASM)] // Optional-/// [Parent("Encoders / Decoders")] // Optional-/// [Order(Before = "Base64 Image Decoder")] // Optional-/// [NotSearchable] // Optional-/// [NotFavorable] // Optional-/// [NoCompactOverlaySupport] // Optional-/// [MenuPlacement(MenuPlacement.Footer)] // Optional-/// [CompactOverlaySize(height: 200, width: 250)] // Optional+/// ShortDisplayTitleResourceName = nameof(MyProject.Strings.ShortDisplayTitle),+/// LongDisplayTitleResourceName = nameof(MyProject.Strings.LongDisplayTitle), // Optional+/// DescriptionResourceName = nameof(MyProject.Strings.Description), // Optional+/// AccessibleNameResourceName = nameof(MyProject.Strings.AccessibleName), // Optional+/// SearchKeywordsResourceName = nameof(MyProject.Strings.SearchKeywords))] // Optional+/// [TargetPlatform(Platform.Windows)] // Optional+/// [TargetPlatform(Platform.WASM)] // Optional+/// [Order(Before = "Base64 Image Decoder")] // Optional+/// [MenuPlacement(MenuPlacement.Footer)] // Optional+/// [NotSearchable] // Optional+/// [NotFavorable] // Optional+/// [NoCompactOverlaySupport] // Optional+/// [CompactOverlaySize(height: 200, width: 250)] // Optional/// internal sealed class Base64GuiTool : IGuiTool/// {/// }+///+/// [Export(typeof(IResourceManagerAssemblyIdentifier))]+/// [Name(nameof(MyResourceManagerAssemblyIdentifier))]+/// public sealed class MyResourceManagerAssemblyIdentifier : IResourceManagerAssemblyIdentifier+/// {+/// }/// </code>/// </example>public interface IGuiTooldiff --git a/src/app/dev/DevToys.Api/Tool/IResourceManagerAssemblyIdentifier.cs b/src/app/dev/DevToys.Api/Tool/IResourceManagerAssemblyIdentifier.csnew file mode 100644index 000000000..b94a4989c--- /dev/null+++ b/src/app/dev/DevToys.Api/Tool/IResourceManagerAssemblyIdentifier.cs@@ -0,0 +1,17 @@+namespace DevToys.Api;++/// <summary>+/// Represents the factory for command line tool.+/// </summary>+/// <example>+/// <code>+/// [Export(typeof(IResourceManagerAssemblyIdentifier))]+/// [Name(nameof(MyResourceManagerAssemblyIdentifier))]+/// internal sealed class MyResourceManagerAssemblyIdentifier : IResourceManagerAssemblyIdentifier+/// {+/// }+/// </code>+/// </example>+public interface IResourceManagerAssemblyIdentifier+{+}diff --git a/src/app/dev/DevToys.Api/Tool/Metadata/Attributes/MenuPlacement.cs b/src/app/dev/DevToys.Api/Tool/Metadata/Attributes/MenuPlacement.csindex 082591741..cb1aa8a57 100644--- a/src/app/dev/DevToys.Api/Tool/Metadata/Attributes/MenuPlacement.cs+++ b/src/app/dev/DevToys.Api/Tool/Metadata/Attributes/MenuPlacement.cs@@ -3,6 +3,5 @@public enum MenuPlacement{Body,- Header,Footer}diff --git a/src/app/dev/DevToys.Api/Tool/Metadata/Attributes/ParentAttribute.cs b/src/app/dev/DevToys.Api/Tool/Metadata/Attributes/ParentAttribute.csdeleted file mode 100644index 81aa5e969..000000000--- a/src/app/dev/DevToys.Api/Tool/Metadata/Attributes/ParentAttribute.cs+++ /dev/null@@ -1,17 +0,0 @@-namespace DevToys.Api;--/// <summary>-/// Indicates the parent tool of the current one.-/// The name should corresponds to an existing <see cref="NameAttribute.InternalComponentName"/> value, or null if no parent.-/// </summary>-[MetadataAttribute]-[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]-public sealed class ParentAttribute : Attribute-{- public string Parent { get; set; }-- public ParentAttribute(string? name)- {- Parent = name ?? string.Empty;- }-}diff --git a/src/app/dev/DevToys.Api/Tool/Metadata/Attributes/ToolDisplayInformationAttribute.cs b/src/app/dev/DevToys.Api/Tool/Metadata/Attributes/ToolDisplayInformationAttribute.csindex ba3195874..99764522a 100644--- a/src/app/dev/DevToys.Api/Tool/Metadata/Attributes/ToolDisplayInformationAttribute.cs+++ b/src/app/dev/DevToys.Api/Tool/Metadata/Attributes/ToolDisplayInformationAttribute.cs@@ -7,18 +7,49 @@[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]public sealed class ToolDisplayInformationAttribute : Attribute{+ private string _resourceManagerAssemblyIdentifier = string.Empty;private string _resourceManagerBaseName = string.Empty;- private string _menuDisplayTitleResourceName = string.Empty;- private string _searchDisplayTitleResourceName = string.Empty;+ private string _shortDisplayTitleResourceName = string.Empty;+ private string _longDisplayTitleResourceName = string.Empty;private string _descriptionResourceName = string.Empty;private string _accessibleNameResourceName = string.Empty;private string _searchkeywordsResourceName = string.Empty;private string _iconGlyph = string.Empty;private string _iconFontName = string.Empty;+ private string _groupName = string.Empty;++ /// <summary>+ /// Indicates the group in which the tool should appear.+ /// The name should corresponds to an existing <see cref="NameAttribute.InternalComponentName"/> value from an exported+ /// <see cref="GuiToolGroup"/>.+ /// </summary>+ public string GroupName+ {+ get => _groupName;+ set+ {+ Guard.IsNotNullOrEmpty(value);+ _groupName = value;+ }+ }++ /// <summary>+ /// Gets or sets the name of the <see cref="IResourceManagerAssemblyIdentifier"/> that contains the type indicated by+ /// <see cref="ResourceManagerBaseName"/>.+ /// </summary>+ public string ResourceManagerAssemblyIdentifier+ {+ get => _resourceManagerAssemblyIdentifier;+ set+ {+ Guard.IsNotNullOrEmpty(value);+ _resourceManagerAssemblyIdentifier = value;+ }+ }/// <summary>/// Gets or sets the name of the resource manager's base name to use when looking for resource string- /// for <see cref="MenuDisplayTitleResourceName"/>, <see cref="SearchDisplayTitleResourceName"/>,+ /// for <see cref="ShortDisplayTitleResourceName"/>, <see cref="LongDisplayTitleResourceName"/>,/// <see cref="DescriptionResourceName"/>, <see cref="AccessibleNameResourceName"/> and <see cref="SearchKeywordsResourceName"/>./// </summary>public string ResourceManagerBaseName@@ -32,33 +63,33 @@ public sealed class ToolDisplayInformationAttribute : Attribute}/// <summary>- /// Gets or sets the title of the tool in the main menu of the app, for example "JSON".+ /// Gets or sets the short title of the tool in the main menu of the app, for example "JSON"./// </summary>- public string MenuDisplayTitleResourceName+ public string ShortDisplayTitleResourceName{- get => _menuDisplayTitleResourceName;+ get => _shortDisplayTitleResourceName;set{Guard.IsNotNullOrWhiteSpace(value);- _menuDisplayTitleResourceName = value;+ _shortDisplayTitleResourceName = value;}}/// <summary>- /// Gets or sets the title of the tool that will be displayed in the search bar. Sometimes- /// it is needed to have a different one than the name showed in the menu to increase- /// result accuracy. For example, while <see cref="MenuDisplayTitleResourceName"/> could be "JSON"- /// for a tool that is under the Formatter category, <see cref="SearchDisplayTitleResourceName"/>+ /// Gets or sets the long title of the tool that will be displayed in the search bar or at the top of the current tool.+ /// Sometimes it is needed to have a different one than the name showed in the menu to increase+ /// result accuracy. For example, while <see cref="ShortDisplayTitleResourceName"/> could be "JSON"+ /// for a tool that is under the Formatter category, <see cref="LongDisplayTitleResourceName"/>/// could be "JSON Formatter", which can be helpful to differentiate from other similar/// tools like "JSON Converter"./// </summary>- public string SearchDisplayTitleResourceName+ public string LongDisplayTitleResourceName{- get => _searchDisplayTitleResourceName;+ get => _longDisplayTitleResourceName;set{Guard.IsNotNullOrWhiteSpace(value);- _searchDisplayTitleResourceName = value;+ _longDisplayTitleResourceName = value;}}diff --git a/src/app/dev/DevToys.Core/DevToys.Core.csproj b/src/app/dev/DevToys.Core/DevToys.Core.csprojindex 2d8eabb79..d232b3577 100644--- a/src/app/dev/DevToys.Core/DevToys.Core.csproj+++ b/src/app/dev/DevToys.Core/DevToys.Core.csproj@@ -4,10 +4,12 @@</PropertyGroup><ItemGroup><ProjectReference Include="..\DevToys.Api\DevToys.Api.csproj" />+ <ProjectReference Include="..\DevToys.Localization\DevToys.Localization.csproj" /></ItemGroup><ItemGroup><PackageReference Include="CommunityToolkit.Common" /><PackageReference Include="CommunityToolkit.Diagnostics" />+ <PackageReference Include="CommunityToolkit.Mvvm" /><PackageReference Include="Microsoft.Extensions.Logging.Abstractions" /><PackageReference Include="Newtonsoft.Json" /><PackageReference Include="System.ComponentModel.Composition" />diff --git a/src/app/dev/DevToys.Core/OSHelper.cs b/src/app/dev/DevToys.Core/OSHelper.csnew file mode 100644index 000000000..5be7083e4--- /dev/null+++ b/src/app/dev/DevToys.Core/OSHelper.cs@@ -0,0 +1,39 @@+using System.Runtime.InteropServices;+using DevToys.Api;++namespace DevToys.Core;++public static class OSHelper+{+ public static bool IsOsSupported(IReadOnlyList<Platform> targetPlatforms)+ {+ if (targetPlatforms.Count > 0)+ {+ Platform currentPlatform;+ if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))+ {+ currentPlatform = Platform.MacCatalyst;+ }+ else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))+ {+ currentPlatform = Platform.Windows;+ }+ else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD))+ {+ currentPlatform = Platform.Linux;+ }+ else+ {+ ThrowHelper.ThrowPlatformNotSupportedException();+ return false;+ }++ if (!targetPlatforms.Contains(currentPlatform))+ {+ return false;+ }+ }++ return true;+ }+}diff --git a/src/app/dev/DevToys.Core/Settings/PredefinedSettings.cs b/src/app/dev/DevToys.Core/Settings/PredefinedSettings.csindex d1bcdde8d..5e02c09ee 100644--- a/src/app/dev/DevToys.Core/Settings/PredefinedSettings.cs+++ b/src/app/dev/DevToys.Core/Settings/PredefinedSettings.cs@@ -20,4 +20,28 @@ public static class PredefinedSettings= new(name: nameof(Theme),defaultValue: AvailableApplicationTheme.Default);++ /// <summary>+ /// The internal name of the tool the most recently used.+ /// </summary>+ public static readonly SettingDefinition<string> RecentTool1+ = new(+ name: nameof(RecentTool1),+ defaultValue: string.Empty);++ /// <summary>+ /// The internal name of the tool the second most recently used.+ /// </summary>+ public static readonly SettingDefinition<string> RecentTool2+ = new(+ name: nameof(RecentTool2),+ defaultValue: string.Empty);++ /// <summary>+ /// The internal name of the tool the third most recently used.+ /// </summary>+ public static readonly SettingDefinition<string> RecentTool3+ = new(+ name: nameof(RecentTool3),+ defaultValue: string.Empty);}diff --git a/src/app/dev/DevToys.Core/Settings/SettingsProvider.cs b/src/app/dev/DevToys.Core/Settings/SettingsProvider.csindex 1e3349fe6..99dde6d99 100644--- a/src/app/dev/DevToys.Core/Settings/SettingsProvider.cs+++ b/src/app/dev/DevToys.Core/Settings/SettingsProvider.cs@@ -38,7 +38,6 @@ internal sealed class SettingsProvider : ISettingsProvider}}- SetSetting(settingDefinition, settingDefinition.DefaultValue);return settingDefinition.DefaultValue;}diff --git a/src/app/dev/DevToys.Core/Tools/GuiToolInstance.cs b/src/app/dev/DevToys.Core/Tools/GuiToolInstance.csnew file mode 100644index 000000000..57e5ae792--- /dev/null+++ b/src/app/dev/DevToys.Core/Tools/GuiToolInstance.cs@@ -0,0 +1,97 @@+using System.Reflection;+using System.Resources;+using DevToys.Api;+using DevToys.Core.Tools.Metadata;+using Microsoft.Extensions.Logging;+using Uno.Extensions;++namespace DevToys.Core.Tools;++[DebuggerDisplay($"InternalComponentName = {{{nameof(InternalComponentName)}}}")]+public sealed partial class GuiToolInstance+{+ private readonly ILogger _logger;+ private readonly Lazy<IGuiTool, GuiToolMetadata> _guiToolDefinition;+ private readonly Lazy<IGuiTool> _instance;+ private readonly Lazy<ResourceManager?> _resourceManager;++ internal GuiToolInstance(Lazy<IGuiTool, GuiToolMetadata> guiToolDefinition, Assembly? resourceManagerAssembly)+ {+ _logger = this.Log();+ _guiToolDefinition = guiToolDefinition;+ _resourceManager = new(() => GetResourceManager(resourceManagerAssembly));++ _instance = new(() =>+ {+ IGuiTool instance = _guiToolDefinition.Value;+ LogInstanceCreated(_guiToolDefinition.Metadata.InternalComponentName);+ return instance;+ });+ LogInitialized(_guiToolDefinition.Metadata.InternalComponentName);+ }++ public string InternalComponentName => _guiToolDefinition.Metadata.InternalComponentName;++ public string Author => _guiToolDefinition.Metadata.Author;++ public string IconFontName => _guiToolDefinition.Metadata.IconFontName;++ public string IconGlyph => _guiToolDefinition.Metadata.IconGlyph;++ public string ShortDisplayTitle => GetDisplayString(_guiToolDefinition.Metadata.ShortDisplayTitleResourceName);++ public string LongDisplayTitle => GetDisplayString(_guiToolDefinition.Metadata.LongDisplayTitleResourceName);++ public string Description => GetDisplayString(_guiToolDefinition.Metadata.DescriptionResourceName);++ public string AccessibleName => GetDisplayString(_guiToolDefinition.Metadata.AccessibleNameResourceName);++ public string SearchKeywords => GetDisplayString(_guiToolDefinition.Metadata.SearchKeywordsResourceName);++ public bool NotSearchable => _guiToolDefinition.Metadata.NotSearchable;++ public bool NotFavorable => _guiToolDefinition.Metadata.NotFavorable;++ public bool NoCompactOverlaySupport => _guiToolDefinition.Metadata.NoCompactOverlaySupport;++ public int? CompactOverlayHeight => _guiToolDefinition.Metadata.CompactOverlayHeight;++ public int? CompactOverlayWidth => _guiToolDefinition.Metadata.CompactOverlayWidth;++ public string GroupName => _guiToolDefinition.Metadata.GroupName;++ /// <summary>+ /// Gets the instance of the tool.+ /// Calling this property be expensive the first time as it will create the instance.+ /// </summary>+ public IGuiTool ToolInstance => _instance.Value;++ private ResourceManager? GetResourceManager(Assembly? resourceManagerAssembly)+ {+ ResourceManager? resourceManager = null;++ if (resourceManagerAssembly is not null)+ {+ // Load resource manager, if needed.+ resourceManager+ = !string.IsNullOrWhiteSpace(_guiToolDefinition.Metadata.ResourceManagerBaseName)+ ? new ResourceManager(_guiToolDefinition.Metadata.ResourceManagerBaseName, resourceManagerAssembly)+ : null;+ }++ return resourceManager;+ }++ private string GetDisplayString(string resourceName)+ {+ return _resourceManager.Value is not null && !string.IsNullOrWhiteSpace(resourceName)+ ? _resourceManager.Value.GetString(resourceName) ?? string.Empty+ : string.Empty;+ }++ [LoggerMessage(0, LogLevel.Information, "Initialized '{toolName}' tool instance manager.")]+ partial void LogInitialized(string toolName);++ [LoggerMessage(1, LogLevel.Information, "Instance of '{toolName}' tool created.")]+ partial void LogInstanceCreated(string toolName);+}diff --git a/src/app/dev/DevToys.Core/Tools/GuiToolProvider.cs b/src/app/dev/DevToys.Core/Tools/GuiToolProvider.csindex 51d731206..6a497778e 100644--- a/src/app/dev/DevToys.Core/Tools/GuiToolProvider.cs+++ b/src/app/dev/DevToys.Core/Tools/GuiToolProvider.cs@@ -1,4 +1,12 @@-using DevToys.Api;+using System.Collections.ObjectModel;+using System.Reflection;+using DevToys.Api;+using DevToys.Core.Settings;+using DevToys.Core.Tools.Metadata;+using DevToys.Core.Tools.ViewItems;+using DevToys.Localization.Strings.MainMenu;+using Microsoft.Extensions.Logging;+using Uno.Extensions;namespace DevToys.Core.Tools;@@ -6,20 +14,408 @@ namespace DevToys.Core.Tools;/// Provides information about tools in the app./// </summary>[Export(typeof(GuiToolProvider))]-public sealed class GuiToolProvider+public sealed partial class GuiToolProvider{+ private readonly ILogger _logger;+ private readonly IEnumerable<Lazy<IResourceManagerAssemblyIdentifier, ResourceManagerAssemblyIdentifierMetadata>> _resourceManagerAssemblyIdentifiers;+ private readonly IEnumerable<Lazy<GuiToolGroup, GuiToolGroupMetadata>> _guiToolGroups;+ private readonly ISettingsProvider _settingsProvider;+ private readonly IReadOnlyList<GuiToolInstance> _footerToolInstances;+ private readonly IReadOnlyList<GuiToolInstance> _bodyToolInstances;++ private ObservableCollection<INotifyPropertyChanged>? _headerAndBodyToolViewItems;+ private ReadOnlyObservableCollection<INotifyPropertyChanged>? _headerAndBodyToolViewItemsReadOnly;+ private ObservableCollection<GuiToolViewItem>? _footerToolViewItems;+ private ReadOnlyObservableCollection<GuiToolViewItem>? _footerToolViewItemsReadOnly;+ private GroupViewItem? _favoriteToolsGroupViewItem;+ private SeparatorViewItem? _separatorAfterAllToolsItem;+ private SeparatorViewItem? _separatorAfterRecentTools;+[ImportingConstructor]public GuiToolProvider(- [ImportMany] IEnumerable<Lazy<IGuiTool, GuiToolMetadata>> guiTools)+ [ImportMany] IEnumerable<Lazy<IGuiTool, GuiToolMetadata>> guiTools,+ [ImportMany] IEnumerable<Lazy<GuiToolGroup, GuiToolGroupMetadata>> guiToolGroups,+ [ImportMany] IEnumerable<Lazy<IResourceManagerAssemblyIdentifier, ResourceManagerAssemblyIdentifierMetadata>> resourceManagerAssemblyIdentifiers,+ ISettingsProvider settingsProvider)+ {+ _logger = this.Log();+ _resourceManagerAssemblyIdentifiers = resourceManagerAssemblyIdentifiers;+ _settingsProvider = settingsProvider;+ _guiToolGroups = guiToolGroups;++ BuildGuiToolInstances(+ guiTools,+ out IReadOnlyList<GuiToolInstance>? allTools,+ out _footerToolInstances,+ out _bodyToolInstances);++ AllTools = allTools;+ }++ /// <summary>+ /// Gets a flat list containing all the tools available, ordered.+ /// </summary>+ public IReadOnlyList<GuiToolInstance> AllTools { get; }++ /// <summary>+ /// Gets a hierarchical list containing all the tools available, ordered, to display in the top and body menu.+ /// This includes "All tools" menu item, recents and favorites.+ /// </summary>+ public ReadOnlyObservableCollection<INotifyPropertyChanged> HeaderAndBodyToolViewItems{+ get+ {+ if (_headerAndBodyToolViewItems is null)+ {+ Guard.IsNull(_headerAndBodyToolViewItemsReadOnly);+ _headerAndBodyToolViewItems = new(BuildHeaderAndBodyToolViewItems());+ _headerAndBodyToolViewItemsReadOnly = new(_headerAndBodyToolViewItems);+ }++ Guard.IsNotNull(_headerAndBodyToolViewItemsReadOnly);+ return _headerAndBodyToolViewItemsReadOnly;+ }+ }++ /// <summary>+ /// Gets a flat list containing all the footer tools available, ordered.+ /// </summary>+ public ReadOnlyObservableCollection<GuiToolViewItem> FooterToolViewItems+ {+ get+ {+ if (_footerToolViewItems is null)+ {+ Guard.IsNull(_footerToolViewItemsReadOnly);+ _footerToolViewItems = new(BuildFooterToolViewItems());+ _footerToolViewItemsReadOnly = new(_footerToolViewItems);+ }++ Guard.IsNotNull(_footerToolViewItemsReadOnly);+ return _footerToolViewItemsReadOnly;+ }+ }++ /// <summary>+ /// Sets a tool as the most recently used one.+ /// </summary>+ public void SetMostRecentUsedTool(GuiToolInstance guiToolInstance)+ {+ Guard.IsNotNull(guiToolInstance);+ _settingsProvider.SetSetting(PredefinedSettings.RecentTool3, _settingsProvider.GetSetting(PredefinedSettings.RecentTool2));+ _settingsProvider.SetSetting(PredefinedSettings.RecentTool2, _settingsProvider.GetSetting(PredefinedSettings.RecentTool1));+ _settingsProvider.SetSetting(PredefinedSettings.RecentTool1, guiToolInstance.InternalComponentName);++ LogSetMostRecentUsedTool(guiToolInstance.InternalComponentName);+ }++ /// <summary>+ /// Sets whether the given tool is marked as favorite or not.+ /// </summary>+ public void SetToolIsFavorite(GuiToolInstance guiToolInstance, bool isFavorite)+ {+ SettingDefinition<bool> isFavoriteSettingDefinition = CreateIsToolFavoriteSettingDefinition(guiToolInstance.InternalComponentName);+ _settingsProvider.SetSetting(isFavoriteSettingDefinition, isFavorite);++ // Update the list in the menu.+ if (_headerAndBodyToolViewItems is not null)+ {+ Guard.HasSizeGreaterThan((ICollection<INotifyPropertyChanged>)_headerAndBodyToolViewItems!, 2);+ Guard.IsOfType<SeparatorViewItem>(_headerAndBodyToolViewItems[1]);++ if (isFavorite) // Add the tool to the favorites+ {+ if (_favoriteToolsGroupViewItem is null)+ {+ var newFavoriteToolViewItem = new GuiToolViewItem(guiToolInstance);+ CreateFavoriteGroupViewItem(new[] { newFavoriteToolViewItem });+ Guard.IsNotNull(_favoriteToolsGroupViewItem);+ }+ else+ {+ Guard.IsNotNull(_favoriteToolsGroupViewItem.Children);+ var newFavoriteToolViewItem = new GuiToolViewItem(guiToolInstance);+ _favoriteToolsGroupViewItem.Children!.Insert(0, newFavoriteToolViewItem);+ }++ // If the "Favorites" menu item isn't present in the meny, add it after the Recent tools (if any).+ if (!_headerAndBodyToolViewItems.Contains(_favoriteToolsGroupViewItem))+ {+ int separatorIndex = -1;+ if (_separatorAfterRecentTools is not null)+ {+ separatorIndex = _headerAndBodyToolViewItems.IndexOf(_separatorAfterRecentTools);+ }+ else+ {+ Guard.IsNotNull(_separatorAfterAllToolsItem);+ separatorIndex = _headerAndBodyToolViewItems.IndexOf(_separatorAfterAllToolsItem);+ }++ _headerAndBodyToolViewItems.Insert(separatorIndex + 1, _favoriteToolsGroupViewItem);+ }+ }+ else // Remove the tool to the favorites+ {+ if (_favoriteToolsGroupViewItem is not null)+ {+ Guard.IsNotNull(_favoriteToolsGroupViewItem.Children);+ GuiToolViewItem? favoriteToolToRemove = _favoriteToolsGroupViewItem.Children.FirstOrDefault(t => t.ToolInstance == guiToolInstance);+ if (favoriteToolToRemove is not null)+ {+ _favoriteToolsGroupViewItem.Children.Remove(favoriteToolToRemove);+ }++ // If the "Favorites" menu item is empty, remove it from the menu.+ if (_favoriteToolsGroupViewItem.Children.Count == 0)+ {+ _headerAndBodyToolViewItems.Remove(_favoriteToolsGroupViewItem);+ }+ }+ }+ }+ }++ private void BuildGuiToolInstances(+ IEnumerable<Lazy<IGuiTool, GuiToolMetadata>> guiTools,+ out IReadOnlyList<GuiToolInstance> allTools,+ out IReadOnlyList<GuiToolInstance> footerTools,+ out IReadOnlyList<GuiToolInstance> bodyTools)+ {+ var allToolInstances = new List<GuiToolInstance>();+ var footerToolInstances = new List<GuiToolInstance>();+ var bodyToolInstances = new List<GuiToolInstance>();++ // Order all the tools.+ guiTools = ExtensionOrderer.Order(guiTools);++ foreach (Lazy<IGuiTool, GuiToolMetadata> guiToolDefinition in guiTools)+ {+ // Make sure the tool is supported by the current OS. If no platform is precised by the tool,+ // it means it's supported by every OS.+ if (!OSHelper.IsOsSupported(guiToolDefinition.Metadata.TargetPlatforms))+ {+ Debug.WriteLine($"Ignoring '{guiToolDefinition.Metadata.InternalComponentName}' tool as it isn't supported by the current OS.");+ continue;+ }++ // if possible, get the resource manager for the tool.+ Assembly? resourceManagerAssembly = null;+ if (!string.IsNullOrEmpty(guiToolDefinition.Metadata.ResourceManagerAssemblyIdentifier))+ {+ resourceManagerAssembly = GetResourceManagerAssembly(guiToolDefinition.Metadata.ResourceManagerAssemblyIdentifier);+ }++ // Create the tool instance and store it in a menu placement list.+ var instance = new GuiToolInstance(guiToolDefinition, resourceManagerAssembly);+ allToolInstances.Add(instance);++ switch (guiToolDefinition.Metadata.MenuPlacement)+ {+ case null:+ case MenuPlacement.Body:+ bodyToolInstances.Add(instance);+ break;+ case MenuPlacement.Footer:+ footerToolInstances.Add(instance);+ break;++ default:+ ThrowHelper.ThrowNotSupportedException();+ break;+ }+ }++ allTools = allToolInstances;+ footerTools = footerToolInstances;+ bodyTools = bodyToolInstances;+ }++ private IEnumerable<GuiToolViewItem> BuildFooterToolViewItems()+ {+ foreach (GuiToolInstance item in _footerToolInstances)+ {+ yield return new GuiToolViewItem(item);+ }}/// <summary>- /// Gets a flat list containing all the tools available.+ /// Creates the list of menu items to display at the top in the navigation view./// </summary>- internal IEnumerable<string> GetAllTools()+ /// <remarks>+ /// It generates the following pattern:+ /// - All Tools+ /// - ---------+ /// - Recent tool 1+ /// - Recent tool 2+ /// - Recent tool 3+ /// - ---------+ /// - Favorites (expanded by default when the app starts)+ /// | - Tool 1+ /// | - Tool 2+ /// - Converters+ /// - Encoders / Decoders+ /// - ...etc+ /// </remarks>+ /// <returns></returns>+ private IEnumerable<INotifyPropertyChanged> BuildHeaderAndBodyToolViewItems()+ {+ // "All tools" menu item.+ yield return new GroupViewItem(+ iconFontName: "FluentSystemIcons-Regular",+ iconGlyph: "\uF480",+ displayTitle: MainMenu.AllToolsDisplayTitle,+ accessibleName: MainMenu.AllToolsAccessibleName);++ // Separator.+ _separatorAfterAllToolsItem = new SeparatorViewItem();+ yield return _separatorAfterAllToolsItem;++ // Recent tools.+ foreach (INotifyPropertyChanged recentToolItem in BuildRecentToolViewItems())+ {+ yield return recentToolItem;+ }++ // Favorites.+ foreach (INotifyPropertyChanged favoriteToolItem in BuildFavoriteToolViewItems())+ {+ yield return favoriteToolItem;+ }++ // All other tools+ foreach (INotifyPropertyChanged groupAndChildren in BuildAllToolsTreeViewItems())+ {+ yield return groupAndChildren;+ }+ }++ private IEnumerable<INotifyPropertyChanged> BuildRecentToolViewItems(){- return null;+ GuiToolInstance? recentTool1 = GetToolFromInternalName(_settingsProvider.GetSetting(PredefinedSettings.RecentTool1));+ GuiToolInstance? recentTool2 = GetToolFromInternalName(_settingsProvider.GetSetting(PredefinedSettings.RecentTool2));+ GuiToolInstance? recentTool3 = GetToolFromInternalName(_settingsProvider.GetSetting(PredefinedSettings.RecentTool3));+ if (recentTool1 is not null || recentTool2 is not null || recentTool3 is not null)+ {+ if (recentTool1 is not null)+ {+ yield return new GuiToolViewItem(recentTool1);+ }++ if (recentTool2 is not null)+ {+ yield return new GuiToolViewItem(recentTool2);+ }++ if (recentTool3 is not null)+ {+ yield return new GuiToolViewItem(recentTool3);+ }++ // Separator.+ _separatorAfterRecentTools = new SeparatorViewItem();+ yield return _separatorAfterRecentTools;+ }}++ private IEnumerable<INotifyPropertyChanged> BuildFavoriteToolViewItems()+ {+ var favoriteTools = new List<GuiToolViewItem>();+ for (int i = 0; i < AllTools.Count; i++)+ {+ GuiToolInstance tool = AllTools[i];+ SettingDefinition<bool> isFavoriteSettingDefinition = CreateIsToolFavoriteSettingDefinition(tool.InternalComponentName);+ bool isFavorite = _settingsProvider.GetSetting(isFavoriteSettingDefinition);+ if (isFavorite)+ {+ favoriteTools.Add(new GuiToolViewItem(tool));+ }+ }++ if (favoriteTools.Count > 0)+ {+ // Create favorite group.+ yield return CreateFavoriteGroupViewItem(favoriteTools);+ }+ }++ private IEnumerable<INotifyPropertyChanged> BuildAllToolsTreeViewItems()+ {+ var groups = new Dictionary<string, Lazy<GroupViewItem, GuiToolGroupMetadata>>();++ // For each tool+ for (int i = 0; i < _bodyToolInstances.Count; i++)+ {+ GuiToolInstance tool = _bodyToolInstances[i];++ // Find the group associated to the tool.+ Lazy<GuiToolGroup, GuiToolGroupMetadata>? toolGroup = _guiToolGroups.FirstOrDefault(g => string.Equals(g.Metadata.InternalComponentName, tool.GroupName, StringComparison.Ordinal));++ if (toolGroup is null)+ {+ ThrowHelper.ThrowInvalidDataException($"Unable to find the group named '{tool.GroupName}' that the tool '{tool.InternalComponentName}' is pointing to.");+ return null;+ }++ // Create a group view presentation, if needed.+ if (!groups.TryGetValue(tool.GroupName, out Lazy<GroupViewItem, GuiToolGroupMetadata>? groupViewItem))+ {+ groupViewItem = new(() => new GroupViewItem(toolGroup.Value, new ObservableCollection<GuiToolViewItem>()), toolGroup.Metadata);+ groups[tool.GroupName] = groupViewItem;+ }++ // Add the tool to the group.+ Guard.IsNotNull(groupViewItem.Value.Children);+ groupViewItem.Value.Children.Add(new GuiToolViewItem(tool));+ }++ // Order tools groups.+ IEnumerable<GroupViewItem> orderedGroups = ExtensionOrderer.Order(groups.Values).Select(g => g.Value);+ return orderedGroups;+ }++ private Assembly GetResourceManagerAssembly(string resourceManagerAssemblyIdentifier)+ {+ foreach (Lazy<IResourceManagerAssemblyIdentifier, ResourceManagerAssemblyIdentifierMetadata> item in _resourceManagerAssemblyIdentifiers)+ {+ if (string.Equals(item.Metadata.InternalComponentName, resourceManagerAssemblyIdentifier, StringComparison.Ordinal))+ {+ return item.Value.GetType().Assembly;+ }+ }++ throw new InvalidDataException($"Unable to find the {nameof(ToolDisplayInformationAttribute.ResourceManagerAssemblyIdentifier)} '{resourceManagerAssemblyIdentifier}'.");+ }++ private GuiToolInstance? GetToolFromInternalName(string name)+ {+ if (string.IsNullOrEmpty(name))+ {+ return null;+ }++ return AllTools.FirstOrDefault(t => string.Equals(t.InternalComponentName, name, StringComparison.Ordinal));+ }++ private GroupViewItem CreateFavoriteGroupViewItem(IReadOnlyList<GuiToolViewItem> favoriteTools)+ {+ Guard.IsNull(_favoriteToolsGroupViewItem);+ _favoriteToolsGroupViewItem+ = new GroupViewItem(+ iconFontName: "FluentSystemIcons-Regular",+ iconGlyph: "\uF70F",+ displayTitle: MainMenu.FavoriteToolsDisplayTitle,+ accessibleName: MainMenu.FavoriteToolsAccessibleName,+ children: new(favoriteTools));+ return _favoriteToolsGroupViewItem;+ }++ private static SettingDefinition<bool> CreateIsToolFavoriteSettingDefinition(string name)+ {+ return new SettingDefinition<bool>($"{name}_IsFavorite", defaultValue: false);+ }++ [LoggerMessage(0, LogLevel.Information, "Set '{toolName}' as the most recently used tool.")]+ partial void LogSetMostRecentUsedTool(string toolName);}diff --git a/src/app/dev/DevToys.Core/Tools/Metadata/GuiToolGroupMetadata.cs b/src/app/dev/DevToys.Core/Tools/Metadata/GuiToolGroupMetadata.csnew file mode 100644index 000000000..4b7e0fac8--- /dev/null+++ b/src/app/dev/DevToys.Core/Tools/Metadata/GuiToolGroupMetadata.cs@@ -0,0 +1,49 @@+using DevToys.Api;++namespace DevToys.Core.Tools.Metadata;++[DebuggerDisplay($"InternalComponentName = {{{nameof(InternalComponentName)}}}")]+public sealed class GuiToolGroupMetadata : IOrderableMetadata+{+ public string InternalComponentName { get; }++ public IReadOnlyList<string> Before { get; }++ public IReadOnlyList<string> After { get; }++ public GuiToolGroupMetadata(IDictionary<string, object> metadata)+ {+ InternalComponentName = metadata.GetValueOrDefault(nameof(NameAttribute.InternalComponentName)) as string ?? string.Empty;+ Before = metadata.GetValueOrDefault(nameof(OrderAttribute.Before)) as IReadOnlyList<string> ?? Array.Empty<string>();+ After = metadata.GetValueOrDefault(nameof(OrderAttribute.After)) as IReadOnlyList<string> ?? Array.Empty<string>();+ Guard.IsNotNullOrWhiteSpace(InternalComponentName);++ if (Before.Count > 0)+ {+ var before = new List<string>();+ for (int i = 0; i < Before.Count; i++)+ {+ if (!string.IsNullOrEmpty(Before[i]))+ {+ before.Add(Before[i]);+ }+ }++ Before = before;+ }++ if (After.Count > 0)+ {+ var after = new List<string>();+ for (int i = 0; i < After.Count; i++)+ {+ if (!string.IsNullOrEmpty(After[i]))+ {+ after.Add(After[i]);+ }+ }++ After = after;+ }+ }+}diff --git a/src/app/dev/DevToys.Core/Tools/GuiToolMetadata.cs b/src/app/dev/DevToys.Core/Tools/Metadata/GuiToolMetadata.cssimilarity index 54%rename from src/app/dev/DevToys.Core/Tools/GuiToolMetadata.csrename to src/app/dev/DevToys.Core/Tools/Metadata/GuiToolMetadata.csindex c3232983f..f4e86268f 100644--- a/src/app/dev/DevToys.Core/Tools/GuiToolMetadata.cs+++ b/src/app/dev/DevToys.Core/Tools/Metadata/GuiToolMetadata.cs@@ -1,10 +1,10 @@using DevToys.Api;using DevToys.Api.Tool.Metadata.Attributes;-namespace DevToys.Core.Tools;+namespace DevToys.Core.Tools.Metadata;[DebuggerDisplay($"InternalComponentName = {{{nameof(InternalComponentName)}}}")]-public sealed class GuiToolMetadata+public sealed class GuiToolMetadata : IOrderableMetadata{public string InternalComponentName { get; }@@ -14,11 +14,13 @@ public sealed class GuiToolMetadatapublic string IconGlyph { get; }+ public string ResourceManagerAssemblyIdentifier { get; }+public string ResourceManagerBaseName { get; }- public string MenuDisplayTitleResourceName { get; }+ public string ShortDisplayTitleResourceName { get; }- public string SearchDisplayTitleResourceName { get; }+ public string LongDisplayTitleResourceName { get; }public string DescriptionResourceName { get; }@@ -26,11 +28,11 @@ public sealed class GuiToolMetadatapublic string SearchKeywordsResourceName { get; }- public string ParentTool { get; }+ public string GroupName { get; }- public string Before { get; }+ public IReadOnlyList<string> Before { get; }- public string After { get; }+ public IReadOnlyList<string> After { get; }public bool NotSearchable { get; }@@ -52,15 +54,16 @@ public sealed class GuiToolMetadataAuthor = metadata.GetValueOrDefault(nameof(AuthorAttribute.Author)) as string ?? string.Empty;IconFontName = metadata.GetValueOrDefault(nameof(ToolDisplayInformationAttribute.IconFontName)) as string ?? string.Empty;IconGlyph = metadata.GetValueOrDefault(nameof(ToolDisplayInformationAttribute.IconGlyph)) as string ?? string.Empty;+ ResourceManagerAssemblyIdentifier = metadata.GetValueOrDefault(nameof(ToolDisplayInformationAttribute.ResourceManagerAssemblyIdentifier)) as string ?? string.Empty;ResourceManagerBaseName = metadata.GetValueOrDefault(nameof(ToolDisplayInformationAttribute.ResourceManagerBaseName)) as string ?? string.Empty;- MenuDisplayTitleResourceName = metadata.GetValueOrDefault(nameof(ToolDisplayInformationAttribute.MenuDisplayTitleResourceName)) as string ?? string.Empty;- SearchDisplayTitleResourceName = metadata.GetValueOrDefault(nameof(ToolDisplayInformationAttribute.SearchDisplayTitleResourceName)) as string ?? string.Empty;+ ShortDisplayTitleResourceName = metadata.GetValueOrDefault(nameof(ToolDisplayInformationAttribute.ShortDisplayTitleResourceName)) as string ?? string.Empty;+ LongDisplayTitleResourceName = metadata.GetValueOrDefault(nameof(ToolDisplayInformationAttribute.LongDisplayTitleResourceName)) as string ?? string.Empty;DescriptionResourceName = metadata.GetValueOrDefault(nameof(ToolDisplayInformationAttribute.DescriptionResourceName)) as string ?? string.Empty;AccessibleNameResourceName = metadata.GetValueOrDefault(nameof(ToolDisplayInformationAttribute.AccessibleNameResourceName)) as string ?? string.Empty;SearchKeywordsResourceName = metadata.GetValueOrDefault(nameof(ToolDisplayInformationAttribute.SearchKeywordsResourceName)) as string ?? string.Empty;- ParentTool = metadata.GetValueOrDefault(nameof(ParentAttribute.Parent)) as string ?? string.Empty;- Before = metadata.GetValueOrDefault(nameof(OrderAttribute.Before)) as string ?? string.Empty;- After = metadata.GetValueOrDefault(nameof(OrderAttribute.After)) as string ?? string.Empty;+ GroupName = metadata.GetValueOrDefault(nameof(ToolDisplayInformationAttribute.GroupName)) as string ?? string.Empty;+ Before = metadata.GetValueOrDefault(nameof(OrderAttribute.Before)) as IReadOnlyList<string> ?? Array.Empty<string>();+ After = metadata.GetValueOrDefault(nameof(OrderAttribute.After)) as IReadOnlyList<string> ?? Array.Empty<string>();NotSearchable = metadata.GetValueOrDefault(nameof(NotSearchableAttribute.NotSearchable)) as bool? ?? false;NotFavorable = metadata.GetValueOrDefault(nameof(NotFavorableAttribute.NotFavorable)) as bool? ?? false;NoCompactOverlaySupport = metadata.GetValueOrDefault(nameof(NoCompactOverlaySupportAttribute.NoCompactOverlaySupport)) as bool? ?? false;@@ -72,7 +75,48 @@ public sealed class GuiToolMetadataGuard.IsNotNullOrWhiteSpace(Author);Guard.IsNotNullOrWhiteSpace(IconFontName);Guard.IsNotNullOrWhiteSpace(IconGlyph);- Guard.IsNotNullOrWhiteSpace(ResourceManagerBaseName);- Guard.IsNotNullOrWhiteSpace(MenuDisplayTitleResourceName);+ Guard.IsNotNullOrWhiteSpace(GroupName);+ Guard.IsNotNullOrWhiteSpace(ShortDisplayTitleResourceName);++ if (!string.IsNullOrEmpty(ShortDisplayTitleResourceName)+ || !string.IsNullOrEmpty(LongDisplayTitleResourceName)+ || !string.IsNullOrEmpty(DescriptionResourceName)+ || !string.IsNullOrEmpty(AccessibleNameResourceName)+ || !string.IsNullOrEmpty(SearchKeywordsResourceName))+ {+ if (string.IsNullOrEmpty(ResourceManagerAssemblyIdentifier)+ || string.IsNullOrEmpty(ResourceManagerBaseName))+ {+ ThrowHelper.ThrowInvalidDataException($"The tool '{InternalComponentName}' has references to one or multiple resource name(s) but does not provide a '{nameof(ToolDisplayInformationAttribute.ResourceManagerAssemblyIdentifier)}' or '{nameof(ToolDisplayInformationAttribute.ResourceManagerBaseName)}'.");+ }+ }++ if (Before.Count > 0)+ {+ var before = new List<string>();+ for (int i = 0; i < Before.Count; i++)+ {+ if (!string.IsNullOrEmpty(Before[i]))+ {+ before.Add(Before[i]);+ }+ }++ Before = before;+ }++ if (After.Count > 0)+ {+ var after = new List<string>();+ for (int i = 0; i < After.Count; i++)+ {+ if (!string.IsNullOrEmpty(After[i]))+ {+ after.Add(After[i]);+ }+ }++ After = after;+ }}}diff --git a/src/app/dev/DevToys.Core/Tools/ResourceManagerAssemblyIdentifierMetadata.cs b/src/app/dev/DevToys.Core/Tools/ResourceManagerAssemblyIdentifierMetadata.csnew file mode 100644index 000000000..67dcb84a0--- /dev/null+++ b/src/app/dev/DevToys.Core/Tools/ResourceManagerAssemblyIdentifierMetadata.cs@@ -0,0 +1,15 @@+using DevToys.Api;++namespace DevToys.Core.Tools;++[DebuggerDisplay($"InternalComponentName = {{{nameof(InternalComponentName)}}}")]+public sealed class ResourceManagerAssemblyIdentifierMetadata+{+ public string InternalComponentName { get; }++ public ResourceManagerAssemblyIdentifierMetadata(IDictionary<string, object> metadata)+ {+ InternalComponentName = metadata.GetValueOrDefault(nameof(NameAttribute.InternalComponentName)) as string ?? string.Empty;+ Guard.IsNotNullOrWhiteSpace(InternalComponentName);+ }+}diff --git a/src/app/dev/DevToys.Core/Tools/ViewItems/GroupViewItem.cs b/src/app/dev/DevToys.Core/Tools/ViewItems/GroupViewItem.csnew file mode 100644index 000000000..f05af752f--- /dev/null+++ b/src/app/dev/DevToys.Core/Tools/ViewItems/GroupViewItem.cs@@ -0,0 +1,66 @@+using System.Collections.ObjectModel;+using CommunityToolkit.Mvvm.ComponentModel;+using DevToys.Api;++namespace DevToys.Core.Tools.ViewItems;++/// <summary>+/// Represents a group or category in the main menu.+/// </summary>+[DebuggerDisplay($"DisplayTitle = {{{nameof(DisplayTitle)}}}")]+public sealed class GroupViewItem : ObservableObject+{+ internal GroupViewItem(+ GuiToolGroup groupInfo,+ ObservableCollection<GuiToolViewItem>? children = null)+ : this(+ groupInfo.IconFontName,+ groupInfo.IconGlyph,+ groupInfo.DisplayTitle,+ groupInfo.AccessibleName,+ children)+ {+ }++ internal GroupViewItem(+ string iconFontName,+ string iconGlyph,+ string displayTitle,+ string accessibleName,+ ObservableCollection<GuiToolViewItem>? children = null)+ {+ Guard.IsNotNullOrWhiteSpace(iconFontName);+ Guard.IsNotNullOrWhiteSpace(iconGlyph);+ Guard.IsNotNullOrWhiteSpace(displayTitle);+ DisplayTitle = displayTitle;+ AccessibleName = accessibleName ?? string.Empty;+ IconFontName = iconFontName;+ IconGlyph = iconGlyph;+ Children = children;+ }++ /// <summary>+ /// Gets the long title to display in the menu.+ /// </summary>+ public string DisplayTitle { get; }++ /// <summary>+ /// Gets the name of the group that will be told to the user when using screen reader.+ /// </summary>+ public string AccessibleName { get; }++ /// <summary>+ /// Gets the name of the font to use to display the <see cref="IconGlyph"/>.+ /// </summary>+ public string IconFontName { get; }++ /// <summary>+ /// Gets a glyph for the icon of the group.+ /// </summary>+ public string IconGlyph { get; }++ /// <summary>+ /// Gets all the children items of this group.+ /// </summary>+ public ObservableCollection<GuiToolViewItem>? Children { get; }+}diff --git a/src/app/dev/DevToys.Core/Tools/ViewItems/GuiToolViewItem.cs b/src/app/dev/DevToys.Core/Tools/ViewItems/GuiToolViewItem.csnew file mode 100644index 000000000..c5682ddab--- /dev/null+++ b/src/app/dev/DevToys.Core/Tools/ViewItems/GuiToolViewItem.cs@@ -0,0 +1,50 @@+using CommunityToolkit.Mvvm.ComponentModel;+using DevToys.Api;++namespace DevToys.Core.Tools.ViewItems;++/// <summary>+/// Represents a tool in the main menu.+/// </summary>+[DebuggerDisplay($"InternalComponentName = {{{nameof(ToolInstance)}.{nameof(GuiToolInstance.InternalComponentName)}}}")]+public sealed partial class GuiToolViewItem : ObservableObject+{+ private readonly bool _showLongDisplayTitle;++ public GuiToolViewItem(GuiToolInstance instance, bool showLongDisplayTitle = true)+ {+ Guard.IsNotNull(instance);+ ToolInstance = instance;+ _showLongDisplayTitle = showLongDisplayTitle;+ }++ /// <summary>+ /// Gets or sets the list of spans that matched a search.+ /// </summary>+ [ObservableProperty]+ private MatchSpan[]? _matchedSpans;++ /// <summary>+ /// Gets or sets whether the tool is recommended to be used (for example, after detecting a compatible data from Smart Detection).+ /// </summary>+ [ObservableProperty]+ private bool _isRecommended;++ /// <summary>+ /// Gets the instance of the tool.+ /// </summary>+ public GuiToolInstance ToolInstance { get; }++ public string MenuDisplayTitle+ {+ get+ {+ if (!_showLongDisplayTitle || string.IsNullOrWhiteSpace(ToolInstance.LongDisplayTitle))+ {+ return ToolInstance.ShortDisplayTitle;+ }++ return ToolInstance.LongDisplayTitle;+ }+ }+}diff --git a/src/app/dev/DevToys.Core/Tools/ViewItems/SeparatorViewItem.cs b/src/app/dev/DevToys.Core/Tools/ViewItems/SeparatorViewItem.csnew file mode 100644index 000000000..9898c8d02--- /dev/null+++ b/src/app/dev/DevToys.Core/Tools/ViewItems/SeparatorViewItem.cs@@ -0,0 +1,10 @@+using CommunityToolkit.Mvvm.ComponentModel;++namespace DevToys.Core.Tools.ViewItems;++/// <summary>+/// Represents a separator in the main menu.+/// </summary>+public sealed class SeparatorViewItem : ObservableObject+{+}diff --git a/src/app/dev/DevToys.Localization/DevToys.Localization.csproj b/src/app/dev/DevToys.Localization/DevToys.Localization.csprojindex c4af19f99..a3797ecc3 100644--- a/src/app/dev/DevToys.Localization/DevToys.Localization.csproj+++ b/src/app/dev/DevToys.Localization/DevToys.Localization.csproj@@ -10,6 +10,11 @@<PackageReference Include="System.ComponentModel.Composition" /></ItemGroup><ItemGroup>+ <Compile Update="Strings\MainMenu\MainMenu.Designer.cs">+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ <DependentUpon>MainMenu.resx</DependentUpon>+ </Compile><Compile Update="Strings\MainWindow\MainWindow.Designer.cs"><DesignTime>True</DesignTime><AutoGen>True</AutoGen>@@ -30,6 +35,10 @@<Generator>PublicResXFileCodeGenerator</Generator><LastGenOutput>Settings.Designer.cs</LastGenOutput></EmbeddedResource>+ <EmbeddedResource Update="Strings\MainMenu\MainMenu.resx">+ <Generator>PublicResXFileCodeGenerator</Generator>+ <LastGenOutput>MainMenu.Designer.cs</LastGenOutput>+ </EmbeddedResource></ItemGroup><ItemGroup><AdditionalFiles Include="**\*.resx" />diff --git a/src/app/dev/DevToys.Localization/Strings/MainMenu/MainMenu.Designer.cs b/src/app/dev/DevToys.Localization/Strings/MainMenu/MainMenu.Designer.csnew file mode 100644index 000000000..7e6e65a2d--- /dev/null+++ b/src/app/dev/DevToys.Localization/Strings/MainMenu/MainMenu.Designer.cs@@ -0,0 +1,99 @@+//------------------------------------------------------------------------------+// <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.Localization.Strings.MainMenu {+ 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()]+ public class MainMenu {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal MainMenu() {+ }++ /// <summary>+ /// Returns the cached ResourceManager instance used by this class.+ /// </summary>+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]+ public static global::System.Resources.ResourceManager ResourceManager {+ get {+ if (object.ReferenceEquals(resourceMan, null)) {+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Localization.Strings.MainMenu.MainMenu", typeof(MainMenu).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)]+ public static global::System.Globalization.CultureInfo Culture {+ get {+ return resourceCulture;+ }+ set {+ resourceCulture = value;+ }+ }++ /// <summary>+ /// Looks up a localized string similar to All tools.+ /// </summary>+ public static string AllToolsAccessibleName {+ get {+ return ResourceManager.GetString("AllToolsAccessibleName", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to All tools.+ /// </summary>+ public static string AllToolsDisplayTitle {+ get {+ return ResourceManager.GetString("AllToolsDisplayTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Favorite tools.+ /// </summary>+ public static string FavoriteToolsAccessibleName {+ get {+ return ResourceManager.GetString("FavoriteToolsAccessibleName", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Favorites.+ /// </summary>+ public static string FavoriteToolsDisplayTitle {+ get {+ return ResourceManager.GetString("FavoriteToolsDisplayTitle", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Localization/Strings/MainMenu/MainMenu.resx b/src/app/dev/DevToys.Localization/Strings/MainMenu/MainMenu.resxnew file mode 100644index 000000000..2e0b3c6eb--- /dev/null+++ b/src/app/dev/DevToys.Localization/Strings/MainMenu/MainMenu.resx@@ -0,0 +1,132 @@+<?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="AllToolsAccessibleName" xml:space="preserve">+ <value>All tools</value>+ </data>+ <data name="AllToolsDisplayTitle" xml:space="preserve">+ <value>All tools</value>+ </data>+ <data name="FavoriteToolsAccessibleName" xml:space="preserve">+ <value>Favorite tools</value>+ </data>+ <data name="FavoriteToolsDisplayTitle" xml:space="preserve">+ <value>Favorites</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/DevToysToolsResourceManagerAssemblyIdentifier.cs b/src/app/dev/DevToys.Tools/DevToysToolsResourceManagerAssemblyIdentifier.csnew file mode 100644index 000000000..3237c6761--- /dev/null+++ b/src/app/dev/DevToys.Tools/DevToysToolsResourceManagerAssemblyIdentifier.cs@@ -0,0 +1,9 @@+using DevToys.Api;++namespace DevToys.Tools;++[Export(typeof(IResourceManagerAssemblyIdentifier))]+[Name(nameof(DevToysToolsResourceManagerAssemblyIdentifier))]+public sealed class DevToysToolsResourceManagerAssemblyIdentifier : IResourceManagerAssemblyIdentifier+{+}diff --git a/src/app/dev/DevToys.Tools/Dummy.cs b/src/app/dev/DevToys.Tools/Dummy.csdeleted file mode 100644index 3f58a43f6..000000000--- a/src/app/dev/DevToys.Tools/Dummy.cs+++ /dev/null@@ -1,4 +0,0 @@-namespace DevToys.Tools;-public class Dummy-{-}diff --git a/src/app/dev/DevToys.Tools/Sample/SampleToolFactory.cs b/src/app/dev/DevToys.Tools/Sample/SampleToolFactory.csindex d19c795e8..b34da1e90 100644--- a/src/app/dev/DevToys.Tools/Sample/SampleToolFactory.cs+++ b/src/app/dev/DevToys.Tools/Sample/SampleToolFactory.cs@@ -9,8 +9,8 @@ namespace DevToys.Tools.Sample;[CommandName(Name = "base64",Alias = "b64",- DescriptionResourceName = nameof(Sample.CommandDescription),- ResourceManagerBaseName = "DevToys.Tools.Sample.Sample")]+ ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",+ DescriptionResourceName = nameof(Sample.CommandDescription))][TargetPlatform(Platform.Windows)] // Optional. Not putting any attribute means every platforms are supported.[TargetPlatform(Platform.Linux)][TargetPlatform(Platform.MacCatalyst)]@@ -41,9 +41,11 @@ internal sealed class SampleCommandLineTool : ICommandLineTool[ToolDisplayInformation(IconFontName = "Fluent System-Regular",IconGlyph = "\u0108",+ GroupName = "Encoders / Decoders",+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),ResourceManagerBaseName = "DevToys.Tools.Sample.Sample",- MenuDisplayTitleResourceName = nameof(Sample.CommandDescription),- SearchDisplayTitleResourceName = nameof(Sample.CommandDescription),+ ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),+ LongDisplayTitleResourceName = nameof(Sample.CommandDescription),DescriptionResourceName = nameof(Sample.CommandDescription),AccessibleNameResourceName = nameof(Sample.CommandDescription),SearchKeywordsResourceName = nameof(Sample.CommandDescription))]@@ -55,3 +57,17 @@ internal sealed class SampleGuiTool : IGuiTool{public UIElement View => throw new NotImplementedException();}++[Export(typeof(GuiToolGroup))]+[Name("Encoders / Decoders")]+internal sealed class EncodersDecodersGroup : GuiToolGroup+{+ [ImportingConstructor]+ internal EncodersDecodersGroup()+ {+ IconFontName = "Fluent System-Regular";+ IconGlyph = "\u0108";+ DisplayTitle = Sample.CommandDescription;+ AccessibleName = Sample.CommandDescription;+ }+}diff --git a/src/app/dev/DevToys.UI/Views/MainWindow.xaml b/src/app/dev/DevToys.UI/Views/MainWindow.xamlindex 5e009aeef..2a3101242 100644--- a/src/app/dev/DevToys.UI/Views/MainWindow.xaml+++ b/src/app/dev/DevToys.UI/Views/MainWindow.xaml@@ -28,7 +28,7 @@</Grid.BackgroundTransition><!-- Draggable area of the title bar. -->- <!--<Grid x:Name="DraggableArea" Grid.Column="1" controls:BackdropWindow.IsWindowDraggableArea="True"/>-->+ <Grid x:Name="DraggableArea" Height="32" VerticalAlignment="Top" controls:BackdropWindow.IsWindowDraggableArea="True"/><!-- Navigation view --><NavigationViewdiff --git a/src/app/dev/platforms/desktop/DevToys.CLI/Program.cs b/src/app/dev/platforms/desktop/DevToys.CLI/Program.csindex 2a4165242..c7d9d7c65 100644--- a/src/app/dev/platforms/desktop/DevToys.CLI/Program.cs+++ b/src/app/dev/platforms/desktop/DevToys.CLI/Program.cs@@ -4,6 +4,7 @@ using System.Runtime.InteropServices;using System.Text;using DevToys.Api;using DevToys.CLI.Core.FileStorage;+using DevToys.Core;using DevToys.Core.Logging;using DevToys.Core.Mef;using DevToys.Tools;@@ -58,45 +59,52 @@ internal partial class Programprivate static async Task MainAsync(string[] args){- var rootCommand = new RootCommand("DevToys");-- // Initialize MEF.- var mefComposer- = new MefComposer(- new[]- {- typeof(Dummy).Assembly,+ try+ {+ var rootCommand = new RootCommand("DevToys");++ // Initialize MEF.+ var mefComposer+ = new MefComposer(+ new[]+ {+ typeof(DevToysToolsResourceManagerAssemblyIdentifier).Assembly,typeof(Program).Assembly- });-- // Get all the command line tools.- IEnumerable<Lazy<ICommandLineTool, CommandLineToolMetadata>> commandLineTools- = mefComposer.Provider.ImportMany<ICommandLineTool, CommandLineToolMetadata>();+ });- var commands = new List<CommandToICommandLineToolMap>();+ // Get all the command line tools.+ IEnumerable<Lazy<ICommandLineTool, CommandLineToolMetadata>> commandLineTools+ = mefComposer.Provider.ImportMany<ICommandLineTool, CommandLineToolMetadata>();- // For each tool, try to create a System.CommandLine.Command and register it.- foreach (Lazy<ICommandLineTool, CommandLineToolMetadata> commandLineTool in commandLineTools)- {- CommandToICommandLineToolMap? command = CreateCommandForTool(commandLineTool);+ var commands = new List<CommandToICommandLineToolMap>();- if (command is not null)+ // For each tool, try to create a System.CommandLine.Command and register it.+ foreach (Lazy<ICommandLineTool, CommandLineToolMetadata> commandLineTool in commandLineTools){- commands.Add(command);- rootCommand.AddCommand(command.CommandDefinition);+ CommandToICommandLineToolMap? command = CreateCommandForTool(commandLineTool);++ if (command is not null)+ {+ commands.Add(command);+ rootCommand.AddCommand(command.CommandDefinition);+ }}- }- // Parse the command prompt arguments and run the appropriate command, if possible.- int exitCode = await rootCommand.InvokeAsync(args);- Environment.ExitCode = exitCode;+ // Parse the command prompt arguments and run the appropriate command, if possible.+ int exitCode = await rootCommand.InvokeAsync(args);+ Environment.ExitCode = exitCode;+ }+ catch (Exception ex)+ {+ LogUnhandledException(logger, ex);+ }}private static CommandToICommandLineToolMap? CreateCommandForTool(Lazy<ICommandLineTool, CommandLineToolMetadata> commandLineTool){// Make sure the tool is supported by the current OS. If no platform is precised by the tool,// it means it's supported by every OS.- if (!IsOsSupported(commandLineTool.Metadata))+ if (!OSHelper.IsOsSupported(commandLineTool.Metadata.TargetPlatforms)){Debug.WriteLine($"Ignoring '{commandLineTool.Metadata.InternalComponentName}' tool as it isn't supported by the current OS.");return null;@@ -130,37 +138,6 @@ internal partial class Programreturn command;}- private static bool IsOsSupported(CommandLineToolMetadata metadata)- {- if (metadata.TargetPlatforms.Count > 0)- {- Platform currentPlatform;- if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))- {- currentPlatform = Platform.MacCatalyst;- }- else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))- {- currentPlatform = Platform.Windows;- }- else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD))- {- currentPlatform = Platform.Linux;- }- else- {- throw new NotSupportedException();- }-- if (!metadata.TargetPlatforms.Contains(currentPlatform))- {- return false;- }- }-- return true;- }-[LoggerMessage(0, LogLevel.Information, "Logger initialized in {duration} ms")]static partial void LogLoggerInitialization(ILogger logger, double duration);@@ -175,4 +152,7 @@ internal partial class Program[LoggerMessage(4, LogLevel.Information, "Exit code: {ExitCode}")]static partial void LogExitCode(ILogger logger, int exitCode);++ [LoggerMessage(5, LogLevel.Critical, "Unhandled exception !!! (╯°□°)╯︵ ┻━┻")]+ static partial void LogUnhandledException(ILogger logger, Exception exception);}diff --git a/src/app/dev/platforms/desktop/DevToys.MauiBlazor/GlobalExceptionHandler.cs b/src/app/dev/platforms/desktop/DevToys.MauiBlazor/GlobalExceptionHandler.csnew file mode 100644index 000000000..2817da4cd--- /dev/null+++ b/src/app/dev/platforms/desktop/DevToys.MauiBlazor/GlobalExceptionHandler.cs@@ -0,0 +1,69 @@+namespace DevToys.MauiBlazor;++internal static class GlobalExceptionHandler+{+#if __WINDOWS__+ private static Exception? _lastFirstChanceException;+#endif++ public static event UnhandledExceptionEventHandler? UnhandledException;++ static GlobalExceptionHandler()+ {+ // This is the normal event expected, and should still be used.+ // It will fire for exceptions from iOS and Mac Catalyst,+ // and for exceptions on background threads from WinUI 3.++ AppDomain.CurrentDomain.UnhandledException += (sender, args) =>+ {+ UnhandledException?.Invoke(sender, args);+ };++#if __MACCATALYST__++ // For iOS and Mac Catalyst+ // Exceptions will flow through AppDomain.CurrentDomain.UnhandledException,+ // but we need to set UnwindNativeCode to get it to work correctly.+ //+ // See: https://github.com/xamarin/xamarin-macios/issues/15252++ ObjCRuntime.Runtime.MarshalManagedException += (_, args) =>+ {+ args.ExceptionMode = ObjCRuntime.MarshalManagedExceptionMode.UnwindNativeCode;+ };++#elif __WINDOWS__++ // For WinUI 3:+ //+ // * Exceptions on background threads are caught by AppDomain.CurrentDomain.UnhandledException,+ // not by Microsoft.UI.Xaml.Application.Current.UnhandledException+ // See: https://github.com/microsoft/microsoft-ui-xaml/issues/5221+ //+ // * Exceptions caught by Microsoft.UI.Xaml.Application.Current.UnhandledException have details removed,+ // but that can be worked around by saved by trapping first chance exceptions+ // See: https://github.com/microsoft/microsoft-ui-xaml/issues/7160+ //++ AppDomain.CurrentDomain.FirstChanceException += (_, args) =>+ {+ _lastFirstChanceException = args.Exception;+ };++ Microsoft.UI.Xaml.Application.Current.UnhandledException += (sender, args) =>+ {+ Exception? exception = args.Exception;++ if (exception.StackTrace is null)+ {+ exception = _lastFirstChanceException;+ }++ if (exception is not null)+ {+ UnhandledException?.Invoke(sender, new UnhandledExceptionEventArgs(exception, true));+ }+ };+#endif+ }+}diff --git a/src/app/dev/platforms/desktop/DevToys.MauiBlazor/MauiProgram.cs b/src/app/dev/platforms/desktop/DevToys.MauiBlazor/MauiProgram.csindex 902deec17..933373531 100644--- a/src/app/dev/platforms/desktop/DevToys.MauiBlazor/MauiProgram.cs+++ b/src/app/dev/platforms/desktop/DevToys.MauiBlazor/MauiProgram.cs@@ -12,14 +12,16 @@ using Uno.Extensions;namespace DevToys.MauiBlazor;-public static class MauiProgram+public static partial class MauiProgram{internal static readonly Lazy<MefComposer> MefComposer= new(() => new MefComposer(new[] {- typeof(Dummy).Assembly+ typeof(DevToysToolsResourceManagerAssemblyIdentifier).Assembly}));+ private static MauiApp? app;+public static MauiApp CreateMauiApp(){MauiAppBuilder builder = MauiApp.CreateBuilder();@@ -48,6 +50,9 @@ public static class MauiProgramMauiApp app = builder.Build();+ MauiProgram.app = app;+ GlobalExceptionHandler.UnhandledException += GlobalExceptionHandler_UnhandledException;+ILoggerFactory loggerFactory = app.Services.GetRequiredService<ILoggerFactory>();global::Uno.Extensions.LogExtensionPoint.AmbientLoggerFactory = loggerFactory;@@ -62,4 +67,13 @@ public static class MauiProgramreturn app;}++ private static void GlobalExceptionHandler_UnhandledException(object sender, UnhandledExceptionEventArgs e)+ {+ Guard.IsNotNull(app);+ LogUnhandledException(app.Log(), (Exception)e.ExceptionObject);+ }++ [LoggerMessage(5, LogLevel.Critical, "Unhandled exception !!! (╯°□°)╯︵ ┻━┻")]+ static partial void LogUnhandledException(ILogger logger, Exception exception);}diff --git a/src/app/dev/shared/App.xaml.cs b/src/app/dev/shared/App.xaml.csindex 9416cf5ae..59c8ed537 100644--- a/src/app/dev/shared/App.xaml.cs+++ b/src/app/dev/shared/App.xaml.cs@@ -58,7 +58,7 @@ public sealed partial class App : Application= new MefComposer(new[]{- typeof(Dummy).Assembly,+ typeof(DevToysToolsResourceManagerAssemblyIdentifier).Assembly,typeof(MainWindow).Assembly});@@ -260,7 +260,7 @@ public sealed partial class App : Application[LoggerMessage(1, LogLevel.Information, "App is shutting down...")]partial void LogAppShuttingDown();- [LoggerMessage(2, LogLevel.Error, "Unhandled exception !!! (╯°□°)╯︵ ┻━┻")]+ [LoggerMessage(2, LogLevel.Critical, "Unhandled exception !!! (╯°□°)╯︵ ┻━┻")]partial void LogUnhandledException(Exception exception);[LoggerMessage(3, LogLevel.Information, "Logger initialized in {duration} ms")]diff --git a/src/app/tests/DevToys.UnitTests/Core/Tools/GuiToolProviderTests.cs b/src/app/tests/DevToys.UnitTests/Core/Tools/GuiToolProviderTests.csnew file mode 100644index 000000000..fe480f52d--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Core/Tools/GuiToolProviderTests.cs@@ -0,0 +1,102 @@+using System.Collections.ObjectModel;+using System.ComponentModel;+using DevToys.Core.Tools;+using DevToys.Core.Tools.ViewItems;++namespace DevToys.UnitTests.Core.Tools;++public class GuiToolProviderTests : MefBasedTest+{+ [Fact]+ public void TitleResourceResolution()+ {+ GuiToolProvider guiToolProvider = MefProvider.Import<GuiToolProvider>();+ GuiToolInstance toolInstance = guiToolProvider.AllTools.FirstOrDefault(t => t.InternalComponentName == "MockTool");++ Assert.Equal("Sample title", toolInstance.LongDisplayTitle);+ Assert.Equal("Sample title", toolInstance.ShortDisplayTitle);+ }++ [Fact]+ public void ToolOrdering()+ {+ GuiToolProvider guiToolProvider = MefProvider.Import<GuiToolProvider>();++ Assert.Equal("MockTool", guiToolProvider.AllTools[0].InternalComponentName);+ Assert.Equal("MockTool2", guiToolProvider.AllTools[1].InternalComponentName);+ }++ [Fact]+ public void ToolsMenu()+ {+ GuiToolProvider guiToolProvider = MefProvider.Import<GuiToolProvider>();++ ReadOnlyObservableCollection<INotifyPropertyChanged> menuItems = guiToolProvider.HeaderAndBodyToolViewItems;+ Assert.Equal(3, menuItems.Count);+ Assert.IsType<GroupViewItem>(menuItems[0]);+ Assert.IsType<SeparatorViewItem>(menuItems[1]);+ Assert.IsType<GroupViewItem>(menuItems[2]);++ Assert.Equal("All tools", ((GroupViewItem)menuItems[0]).DisplayTitle);+ Assert.Null(((GroupViewItem)menuItems[0]).Children);+ Assert.Equal("Group title", ((GroupViewItem)menuItems[2]).DisplayTitle);+ Assert.Equal(2, ((GroupViewItem)menuItems[2]).Children.Count);+ Assert.Equal("MockTool", ((GroupViewItem)menuItems[2]).Children[0].ToolInstance.InternalComponentName);+ Assert.Equal("MockTool2", ((GroupViewItem)menuItems[2]).Children[1].ToolInstance.InternalComponentName);+ }++ [Fact]+ public void ToolsMenuRecent()+ {+ GuiToolProvider guiToolProvider = MefProvider.Import<GuiToolProvider>();++ ReadOnlyObservableCollection<INotifyPropertyChanged> menuItems = guiToolProvider.HeaderAndBodyToolViewItems;+ Assert.Equal(3, menuItems.Count);+ Assert.IsType<GroupViewItem>(menuItems[0]);+ Assert.IsType<SeparatorViewItem>(menuItems[1]);+ Assert.IsType<GroupViewItem>(menuItems[2]);++ guiToolProvider.SetMostRecentUsedTool(((GroupViewItem)menuItems[2]).Children[0].ToolInstance);++ // Menu should be unchanged.+ Assert.Equal(3, menuItems.Count);+ Assert.IsType<GroupViewItem>(menuItems[0]);+ Assert.IsType<SeparatorViewItem>(menuItems[1]);+ Assert.IsType<GroupViewItem>(menuItems[2]);+ }++ [Fact]+ public void ToolsMenuFavorites()+ {+ GuiToolProvider guiToolProvider = MefProvider.Import<GuiToolProvider>();+ ReadOnlyObservableCollection<INotifyPropertyChanged> menuItems = guiToolProvider.HeaderAndBodyToolViewItems;++ GuiToolViewItem toolToSetAsFavorite = ((GroupViewItem)menuItems[2]).Children[0];++ // At first, no favorites at all.+ Assert.Equal(3, menuItems.Count);+ Assert.IsType<GroupViewItem>(menuItems[0]);+ Assert.IsType<SeparatorViewItem>(menuItems[1]);+ Assert.IsType<GroupViewItem>(menuItems[2]);++ // Set item as favorite. The menu should then have "Favorites" group.+ guiToolProvider.SetToolIsFavorite(toolToSetAsFavorite.ToolInstance, isFavorite: true);+ Assert.Equal(4, menuItems.Count);+ Assert.IsType<GroupViewItem>(menuItems[0]);+ Assert.IsType<SeparatorViewItem>(menuItems[1]);+ Assert.IsType<GroupViewItem>(menuItems[2]);+ Assert.IsType<GroupViewItem>(menuItems[3]);+ Assert.Equal("Favorites", ((GroupViewItem)menuItems[2]).DisplayTitle);+ Assert.Equal("Group title", ((GroupViewItem)menuItems[3]).DisplayTitle);+ Assert.Single(((GroupViewItem)menuItems[2]).Children);+ Assert.Equal(toolToSetAsFavorite.ToolInstance, ((GroupViewItem)menuItems[2]).Children[0].ToolInstance);+ Assert.NotEqual(toolToSetAsFavorite, ((GroupViewItem)menuItems[2]).Children[0]);++ // Unfavorite the item. The menu should remove "Favorite" group because the group is now empty.+ guiToolProvider.SetToolIsFavorite(toolToSetAsFavorite.ToolInstance, isFavorite: false);+ Assert.Equal(3, menuItems.Count);+ Assert.IsType<GroupViewItem>(menuItems[0]);+ Assert.IsType<SeparatorViewItem>(menuItems[1]);+ Assert.IsType<GroupViewItem>(menuItems[2]);+ }+}diff --git a/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj b/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csprojindex edce13cf5..2418fdd34 100644--- a/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj+++ b/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj@@ -20,6 +20,22 @@<ItemGroup><ProjectReference Include="..\..\dev\DevToys.Api\DevToys.Api.csproj" />+ <ProjectReference Include="..\..\dev\DevToys.Core\DevToys.Core.csproj" />+ </ItemGroup>++ <ItemGroup>+ <Compile Update="Mocks\Tools\MockToolResource.Designer.cs">+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ <DependentUpon>MockToolResource.resx</DependentUpon>+ </Compile>+ </ItemGroup>++ <ItemGroup>+ <EmbeddedResource Update="Mocks\Tools\MockToolResource.resx">+ <Generator>ResXFileCodeGenerator</Generator>+ <LastGenOutput>MockToolResource.Designer.cs</LastGenOutput>+ </EmbeddedResource></ItemGroup></Project>diff --git a/src/app/tests/DevToys.UnitTests/MefBasedTest.cs b/src/app/tests/DevToys.UnitTests/MefBasedTest.csnew file mode 100644index 000000000..315a42faa--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/MefBasedTest.cs@@ -0,0 +1,31 @@+using System.Globalization;+using System.Reflection;+using DevToys.Core.Mef;+using DevToys.Core.Settings;++namespace DevToys.UnitTests;++public abstract class MefBasedTest+{+ private readonly MefComposer _mefComposer;++ protected IMefProvider MefProvider => _mefComposer.Provider;++ protected MefBasedTest(params Assembly[] assembliesToLoad)+ {+ var assemblies+ = new List<Assembly>(assembliesToLoad)+ {+ typeof(MefBasedTest).Assembly+ };++ // Initialize MEF.+ _mefComposer+ = new MefComposer(+ assemblies.ToArray());++ // Set language to english for unit tests.+ CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");+ CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("en-US");+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Mocks/MockIFileStorage.cs b/src/app/tests/DevToys.UnitTests/Mocks/MockIFileStorage.csnew file mode 100644index 000000000..4c6e02f7e--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Mocks/MockIFileStorage.cs@@ -0,0 +1,32 @@+using System.ComponentModel.Composition;+using System.IO;+using System.Threading.Tasks;+using DevToys.Api.Core;++namespace DevToys.UnitTests.Mocks;++[Export(typeof(IFileStorage))]+internal class MockIFileStorage : IFileStorage+{+ public string AppCacheDirectory => throw new NotImplementedException();++ public bool FileExists(string relativeOrAbsoluteFilePath)+ {+ throw new NotImplementedException();+ }++ public Stream OpenReadFile(string relativeOrAbsoluteFilePath)+ {+ throw new NotImplementedException();+ }++ public Stream OpenWriteFile(string relativeOrAbsoluteFilePath, bool replaceIfExist)+ {+ throw new NotImplementedException();+ }++ public ValueTask<string> PickSaveFileAsync(string[] fileTypes)+ {+ throw new NotImplementedException();+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Mocks/MockISettingsStorage.cs b/src/app/tests/DevToys.UnitTests/Mocks/MockISettingsStorage.csnew file mode 100644index 000000000..2f1c57304--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Mocks/MockISettingsStorage.cs@@ -0,0 +1,25 @@+using System.ComponentModel.Composition;+using DevToys.Core.Settings;++namespace DevToys.UnitTests.Mocks;++[Export(typeof(ISettingsStorage))]+internal class MockISettingsStorage : ISettingsStorage+{+ private readonly Dictionary<string, object> _settings = new();++ public void ResetSetting(string settingName)+ {+ throw new NotImplementedException();+ }++ public bool TryReadSetting(string settingName, out object value)+ {+ return _settings.TryGetValue(settingName, out value);+ }++ public void WriteSetting(string settingName, object value)+ {+ _settings[settingName] = value;+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockGuiToolGroup.cs b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockGuiToolGroup.csnew file mode 100644index 000000000..2888b9e81--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockGuiToolGroup.cs@@ -0,0 +1,17 @@+using System.ComponentModel.Composition;++namespace DevToys.UnitTests.Mocks.Tools;++[Export(typeof(GuiToolGroup))]+[Name("MockGroup")]+internal sealed class MockGuiToolGroup : GuiToolGroup+{+ [ImportingConstructor]+ internal MockGuiToolGroup()+ {+ IconFontName = "Fluent System-Regular";+ IconGlyph = "\u0108";+ DisplayTitle = "Group title";+ AccessibleName = "Group title";+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockIGuiTool.cs b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockIGuiTool.csnew file mode 100644index 000000000..46d60b47d--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockIGuiTool.cs@@ -0,0 +1,42 @@+using System.ComponentModel.Composition;++namespace DevToys.UnitTests.Mocks.Tools;++[Export(typeof(IGuiTool))]+[Name("MockTool2")]+[Order(After = "MockTool")]+[Author("John Doe")]+[ToolDisplayInformation(+ IconFontName = "Fluent System-Regular",+ IconGlyph = "\u0108",+ GroupName = "MockGroup",+ ResourceManagerAssemblyIdentifier = nameof(MockResourceManagerAssemblyIdentifier),+ ResourceManagerBaseName = "DevToys.UnitTests.Mocks.Tools.MockToolResource",+ ShortDisplayTitleResourceName = nameof(MockToolResource.Title),+ LongDisplayTitleResourceName = nameof(MockToolResource.Title),+ DescriptionResourceName = nameof(MockToolResource.Title),+ AccessibleNameResourceName = nameof(MockToolResource.Title),+ SearchKeywordsResourceName = nameof(MockToolResource.Title))]+internal sealed class MockIGuiTool2 : IGuiTool+{+ public UIElement View => throw new NotImplementedException();+}++[Export(typeof(IGuiTool))]+[Name("MockTool")]+[Author("John Doe")]+[ToolDisplayInformation(+ IconFontName = "Fluent System-Regular",+ IconGlyph = "\u0108",+ GroupName = "MockGroup",+ ResourceManagerAssemblyIdentifier = nameof(MockResourceManagerAssemblyIdentifier),+ ResourceManagerBaseName = "DevToys.UnitTests.Mocks.Tools.MockToolResource",+ ShortDisplayTitleResourceName = nameof(MockToolResource.Title),+ LongDisplayTitleResourceName = nameof(MockToolResource.Title),+ DescriptionResourceName = nameof(MockToolResource.Title),+ AccessibleNameResourceName = nameof(MockToolResource.Title),+ SearchKeywordsResourceName = nameof(MockToolResource.Title))]+internal sealed class MockIGuiTool : IGuiTool+{+ public UIElement View => throw new NotImplementedException();+}diff --git a/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockResourceManagerAssemblyIdentifier.cs b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockResourceManagerAssemblyIdentifier.csnew file mode 100644index 000000000..7f8e58f20--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockResourceManagerAssemblyIdentifier.cs@@ -0,0 +1,9 @@+using System.ComponentModel.Composition;++namespace DevToys.UnitTests.Mocks.Tools;++[Export(typeof(IResourceManagerAssemblyIdentifier))]+[Name(nameof(MockResourceManagerAssemblyIdentifier))]+internal sealed class MockResourceManagerAssemblyIdentifier : IResourceManagerAssemblyIdentifier+{+}diff --git a/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockToolResource.Designer.cs b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockToolResource.Designer.csnew file mode 100644index 000000000..63a0e2b0c--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockToolResource.Designer.cs@@ -0,0 +1,72 @@+//------------------------------------------------------------------------------+// <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.UnitTests.Mocks.Tools {+ 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 MockToolResource {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal MockToolResource() {+ }++ /// <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.UnitTests.Mocks.Tools.MockToolResource", typeof(MockToolResource).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 Sample title.+ /// </summary>+ internal static string Title {+ get {+ return ResourceManager.GetString("Title", resourceCulture);+ }+ }+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockToolResource.resx b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockToolResource.resxnew file mode 100644index 000000000..d13b320b7--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockToolResource.resx@@ -0,0 +1,123 @@+<?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="Title" xml:space="preserve">+ <value>Sample title</value>+ </data>+</root>\ No newline at end of file