A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
[DevToys 2.0] Added Extension manager (#901)
Etienne BAUDOUX67a02153659c
diff --git a/.nuke/build.schema.json b/.nuke/build.schema.jsonindex 9e6eb7678..f60885a1c 100644--- a/.nuke/build.schema.json+++ b/.nuke/build.schema.json@@ -1,7 +1,7 @@{"$schema": "http://json-schema.org/draft-04/schema#",- "title": "Build Schema","$ref": "#/definitions/build",+ "title": "Build Schema","definitions": {"build": {"type": "object",@@ -97,8 +97,9 @@"BuildGenerators","BuildPlugins","Clean",+ "GenerateSdkNuGet","PreliminaryCheck",- "Publish",+ "PublishApp","Restore","SetVersion","UnitTests"@@ -114,8 +115,9 @@"BuildGenerators","BuildPlugins","Clean",+ "GenerateSdkNuGet","PreliminaryCheck",- "Publish",+ "PublishApp","Restore","SetVersion","UnitTests"@@ -139,4 +141,4 @@}}}-}\ No newline at end of file+}diff --git a/src/Directory.Build.props b/src/Directory.Build.propsindex f42b20271..961621739 100644--- a/src/Directory.Build.props+++ b/src/Directory.Build.props@@ -26,6 +26,8 @@<OutputPath>$(BaseOutputPath)$(MSBuildProjectName)\</OutputPath><BaseIntermediateOutputPath>$(RepoRoot)obj\$(Platform)\$(MSBuildProjectName)\</BaseIntermediateOutputPath><IntermediateOutputPath>$(BaseIntermediateOutputPath)\$(Configuration)</IntermediateOutputPath>+ <PackageOutputPath>$(OutputPath)</PackageOutputPath>+ <PluginNupkgPath>$(RepoRoot)bin\$(Configuration)\Plugins</PluginNupkgPath><GeneratedFilesDir>$(BaseIntermediateOutputPath)Generated Files\</GeneratedFilesDir><PackagesConfigRestorePath>$(RepoRoot)packages\</PackagesConfigRestorePath>diff --git a/src/Directory.Packages.props b/src/Directory.Packages.propsindex 062148b08..643906268 100644--- a/src/Directory.Packages.props+++ b/src/Directory.Packages.props@@ -24,8 +24,9 @@<PackageVersion Include="Microsoft.TypeScript.MSBuild" Version="5.1.5" /><PackageVersion Include="Microsoft.Windows.CsWin32" Version="0.3.18-beta"/><PackageVersion Include="Moq" Version="4.18.4" />- <PackageVersion Include="System.Text.Json" Version="$(DotNetVersion)" />+ <PackageVersion Include="NuGet.Packaging" Version="6.6.1" /><PackageVersion Include="Nuke.Common" Version="7.0.2" />+ <PackageVersion Include="System.Text.Json" Version="$(DotNetVersion)" /><PackageVersion Include="System.CommandLine" Version="2.0.0-beta4.22272.1" /><PackageVersion Include="System.ComponentModel.Composition" Version="$(DotNetVersion)" /><PackageVersion Include="System.Threading.Tasks.Extensions" Version="4.5.4" />diff --git a/src/app/dev/DevToys.Api/DevToys.Api.csproj b/src/app/dev/DevToys.Api/DevToys.Api.csprojindex eaee65ced..e892f153e 100644--- a/src/app/dev/DevToys.Api/DevToys.Api.csproj+++ b/src/app/dev/DevToys.Api/DevToys.Api.csproj@@ -1,6 +1,16 @@-<Project Sdk="Microsoft.NET.Sdk">+<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFrameworks>$(NetCore)</TargetFrameworks>++ <!-- NuGet package -->+ <GeneratePackageOnBuild>True</GeneratePackageOnBuild>+ <Version>2.0.0-pre.2</Version>+ <Authors>veler,btiteux</Authors>+ <Description>SDK for developing extensions for DevToys 2.0 and higher</Description>+ <PackageProjectUrl>https://devtoys.app</PackageProjectUrl>+ <RepositoryUrl>https://github.com/veler/DevToys</RepositoryUrl>+ <PackageTags>devtoys</PackageTags>+ <PackageLicenseFile>LICENSE.md</PackageLicenseFile></PropertyGroup><ItemGroup>@@ -11,6 +21,14 @@<PackageReference Include="System.Threading.Tasks.Extensions" /></ItemGroup>+ <ItemGroup>+ <None Include="$(AssemblyName).props" Pack="true" PackagePath="build" />+ <None Include="$(RepoRoot)LICENSE.md" Link="LICENSE.md">+ <Pack>True</Pack>+ <PackagePath>\</PackagePath>+ </None>+ </ItemGroup>+<ItemGroup><Compile Update="Strings\ApiText\ApiText.Designer.cs"><DesignTime>True</DesignTime>@@ -25,4 +43,4 @@<LastGenOutput>ApiText.Designer.cs</LastGenOutput></EmbeddedResource></ItemGroup>-</Project>\ No newline at end of file+</Project>diff --git a/src/app/dev/DevToys.Api/DevToys.Api.props b/src/app/dev/DevToys.Api/DevToys.Api.propsnew file mode 100644index 000000000..93b5a4955--- /dev/null+++ b/src/app/dev/DevToys.Api/DevToys.Api.props@@ -0,0 +1,4 @@+<Project>+ <!-- See https://learn.microsoft.com/en-us/dotnet/core/project-sdk/msbuild-props#enabledynamicloading -->+ <EnableDynamicLoading>true</EnableDynamicLoading>+</Project>\ No newline at end of filediff --git a/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionInstallationManager.cs b/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionInstallationManager.csnew file mode 100644index 000000000..4201ce075--- /dev/null+++ b/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionInstallationManager.cs@@ -0,0 +1,65 @@+namespace DevToys.Blazor.BuiltInTools.ExtensionsManager;++public static class ExtensionInstallationManager+{+ public static string PreferredExtensionInstallationFolder { get; set; } = string.Empty;++ public static string[] ExtensionInstallationFolders { get; set; } = Array.Empty<string>();++ public static void UninstallExtensionsScheduledForRemoval()+ {+ if (!Directory.Exists(PreferredExtensionInstallationFolder))+ {+ return;+ }++ string scheduledForUninstallFilePath = Path.Combine(PreferredExtensionInstallationFolder, "uninstall.txt");+ if (File.Exists(scheduledForUninstallFilePath))+ {+ Process[] appInstances = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);++ // Only uninstall if there's only 1 instance of the app running.+ if (appInstances.Length == 1)+ {+ string[] lines = File.ReadAllLines(scheduledForUninstallFilePath);++ for (int i = 0; i < lines.Length; i++)+ {+ try+ {+ // Make sure we're not deleting something that's not in the extension folder. Could be a security concern otherwise.+ if (ExtensionInstallationFolders.Any(path => lines[i].StartsWith(path)))+ {+ if (Directory.Exists(lines[i]))+ {+ Directory.Delete(lines[i], true);+ }+ }+ }+ catch+ {+ // TODO: Log error.+ }+ }++ File.Delete(scheduledForUninstallFilePath);+ }+ }+ }++ public static void ScheduleExtensionToBeUninstalled(string extensionInstallationPath)+ {+ if (!Directory.Exists(PreferredExtensionInstallationFolder))+ {+ Directory.CreateDirectory(PreferredExtensionInstallationFolder);+ }++ string scheduledForUninstallFilePath = Path.Combine(PreferredExtensionInstallationFolder, "uninstall.txt");+ if (!File.Exists(scheduledForUninstallFilePath))+ {+ File.CreateText(scheduledForUninstallFilePath).Dispose();+ }++ File.AppendAllLines(scheduledForUninstallFilePath, new[] { extensionInstallationPath });+ }+}diff --git a/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionsManager.Designer.cs b/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionsManager.Designer.csnew file mode 100644index 000000000..9608c3574--- /dev/null+++ b/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionsManager.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.Blazor.BuiltInTools.ExtensionsManager {+ 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 ExtensionsManager {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal ExtensionsManager() {+ }++ /// <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.Blazor.BuiltInTools.ExtensionsManager.ExtensionsManager", typeof(ExtensionsManager).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 Manage extensions in DevToys.+ /// </summary>+ internal static string AccessibleName {+ get {+ return ResourceManager.GetString("AccessibleName", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Add and manager third-party extensions in DevToys.+ /// </summary>+ internal static string Description {+ get {+ return ResourceManager.GetString("Description", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to The extension '{0}' is already installed. If you are trying to update an extension that is already installed, please uninstall the older version first..+ /// </summary>+ internal static string ExtensionAlreadyInstalledDescription {+ get {+ return ResourceManager.GetString("ExtensionAlreadyInstalledDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Unable to install this extension.+ /// </summary>+ internal static string ExtensionAlreadyInstalledTitle {+ get {+ return ResourceManager.GetString("ExtensionAlreadyInstalledTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to {0} - {1}.+ /// </summary>+ internal static string ExtensionTitleInList {+ get {+ return ResourceManager.GetString("ExtensionTitleInList", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Find more extensions online.+ /// </summary>+ internal static string FindMoreExtension {+ get {+ return ResourceManager.GetString("FindMoreExtension", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Install an extension.+ /// </summary>+ internal static string InstallExtension {+ get {+ return ResourceManager.GetString("InstallExtension", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Create an extension for DevToys.+ /// </summary>+ internal static string LearnDevelopExtension {+ get {+ return ResourceManager.GetString("LearnDevelopExtension", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to OK.+ /// </summary>+ internal static string OKButtonText {+ get {+ return ResourceManager.GetString("OKButtonText", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Please close all DevToys windows and restart the app to apply the modifications..+ /// </summary>+ internal static string RestartRequiredInfoBarDescription {+ get {+ return ResourceManager.GetString("RestartRequiredInfoBarDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Restart is require for changes to take effect.+ /// </summary>+ internal static string RestartRequiredInfoBarTitle {+ get {+ return ResourceManager.GetString("RestartRequiredInfoBarTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Manage extensions.+ /// </summary>+ internal static string ShortDisplayTitle {+ get {+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Third-party extensions can modify the functionality of existing tools and access your computer without your permission. This may expose your data to the internet or install unwanted software on your device. We strongly recommend that you exercise caution and only install extensions that you trust. DevToys authors are not responsible for any damages or losses caused by extensions..+ /// </summary>+ internal static string WarningThirdPartyExtensionUsageDescription {+ get {+ return ResourceManager.GetString("WarningThirdPartyExtensionUsageDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to I understand.+ /// </summary>+ internal static string WarningThirdPartyExtensionUsageIUnderstand {+ get {+ return ResourceManager.GetString("WarningThirdPartyExtensionUsageIUnderstand", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Terms and Conditions.+ /// </summary>+ internal static string WarningThirdPartyExtensionUsageTermsConditions {+ get {+ return ResourceManager.GetString("WarningThirdPartyExtensionUsageTermsConditions", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Warning.+ /// </summary>+ internal static string WarningThirdPartyExtensionUsageTitle {+ get {+ return ResourceManager.GetString("WarningThirdPartyExtensionUsageTitle", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionsManager.resx b/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionsManager.resxnew file mode 100644index 000000000..67ecb27f6--- /dev/null+++ b/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionsManager.resx@@ -0,0 +1,169 @@+<?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>Manage extensions in DevToys</value>+ </data>+ <data name="Description" xml:space="preserve">+ <value>Add and manager third-party extensions in DevToys</value>+ </data>+ <data name="ExtensionAlreadyInstalledDescription" xml:space="preserve">+ <value>The extension '{0}' is already installed. If you are trying to update an extension that is already installed, please uninstall the older version first.</value>+ </data>+ <data name="ExtensionAlreadyInstalledTitle" xml:space="preserve">+ <value>Unable to install this extension</value>+ </data>+ <data name="ExtensionTitleInList" xml:space="preserve">+ <value>{0} - {1}</value>+ <comment>Example: "DevToys.Tools - 1.0.0"</comment>+ </data>+ <data name="FindMoreExtension" xml:space="preserve">+ <value>Find more extensions online</value>+ </data>+ <data name="InstallExtension" xml:space="preserve">+ <value>Install an extension</value>+ </data>+ <data name="LearnDevelopExtension" xml:space="preserve">+ <value>Create an extension for DevToys</value>+ </data>+ <data name="OKButtonText" xml:space="preserve">+ <value>OK</value>+ </data>+ <data name="RestartRequiredInfoBarDescription" xml:space="preserve">+ <value>Please close all DevToys windows and restart the app to apply the modifications.</value>+ </data>+ <data name="RestartRequiredInfoBarTitle" xml:space="preserve">+ <value>Restart is require for changes to take effect</value>+ </data>+ <data name="ShortDisplayTitle" xml:space="preserve">+ <value>Manage extensions</value>+ </data>+ <data name="WarningThirdPartyExtensionUsageDescription" xml:space="preserve">+ <value>Third-party extensions can modify the functionality of existing tools and access your computer without your permission. This may expose your data to the internet or install unwanted software on your device. We strongly recommend that you exercise caution and only install extensions that you trust. DevToys authors are not responsible for any damages or losses caused by extensions.</value>+ </data>+ <data name="WarningThirdPartyExtensionUsageIUnderstand" xml:space="preserve">+ <value>I understand</value>+ </data>+ <data name="WarningThirdPartyExtensionUsageTermsConditions" xml:space="preserve">+ <value>Terms and Conditions</value>+ </data>+ <data name="WarningThirdPartyExtensionUsageTitle" xml:space="preserve">+ <value>Warning</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionsManagerGuiTool.cs b/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionsManagerGuiTool.csnew file mode 100644index 000000000..ff62a0eb1--- /dev/null+++ b/src/app/dev/DevToys.Blazor/BuiltInTools/ExtensionsManager/ExtensionsManagerGuiTool.cs@@ -0,0 +1,383 @@+using System.Collections.Immutable;+using DevToys.Blazor.BuiltInTools.Settings;+using Newtonsoft.Json;+using NuGet.Packaging;+using NuGet.Packaging.Core;++namespace DevToys.Blazor.BuiltInTools.ExtensionsManager;++[Export(typeof(IGuiTool))]+[Name("Extensions Manager")]+[ToolDisplayInformation(+ IconFontName = "FluentSystemIcons",+ IconGlyph = '\uE9E8',+ ResourceManagerAssemblyIdentifier = nameof(DevToysBlazorResourceManagerAssemblyIdentifier),+ ResourceManagerBaseName = "DevToys.Blazor.BuiltInTools.ExtensionsManager.ExtensionsManager",+ ShortDisplayTitleResourceName = nameof(ExtensionsManager.ShortDisplayTitle),+ DescriptionResourceName = nameof(ExtensionsManager.Description),+ AccessibleNameResourceName = nameof(ExtensionsManager.AccessibleName))]+[MenuPlacement(MenuPlacement.Footer)]+[NotFavorable]+[NotSearchable]+[NoCompactOverlaySupport]+[Order(Before = SettingsGuiTool.SettingsInternalToolName)]+internal sealed class ExtensionsManagerGuiTool : IGuiTool+{+ private enum GridRows+ {+ TopButtons,+ InfoBars,+ ExtensionList+ }++ private enum GridColumns+ {+ Left,+ Right+ }++ private static readonly string[] sizeUnits = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };++ private readonly Lazy<UIToolView> _view = new(() => new(isScrollable: false));+ private readonly IUIInfoBar _restartRequiredInfoBar = InfoBar("restart-required-after-changing-extension-info-bar");+ private readonly IUIList _extensionList = List("installed-extensions-list");++ private bool _shownWarningInstallExtension;++#pragma warning disable IDE0044 // Add readonly modifier+ [Import]+ private IFileStorage _fileStorage = default!;+#pragma warning restore IDE0044 // Add readonly modifier++ public UIToolView View+ {+ get+ {+ LoadExtensionListAsync().Forget();+ return _view.Value+ .WithRootElement(+ Grid()+ .RowLargeSpacing()++ .Rows(+ (GridRows.TopButtons, Auto),+ (GridRows.InfoBars, Auto),+ (GridRows.ExtensionList, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Columns(+ (GridColumns.Left, Auto),+ (GridColumns.Right, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Cells(+ Cell(+ GridRows.TopButtons,+ GridColumns.Left,++ Stack()+ .Horizontal()++ .WithChildren(+ Button("install-extension-button")+ .Text(ExtensionsManager.InstallExtension)+ .OnClick(OnInstallExtensionButtonClickAsync),++ Button("find-more-extensions-online-button")+ .HyperlinkAppearance()+ .Text(ExtensionsManager.FindMoreExtension)+ .OnClick(OnFindMoreExtensionsOnlineButtonClick))),++ Cell(+ GridRows.TopButtons,+ GridColumns.Right,++ Button("learn-develop-extension-button")+ .AlignHorizontally(UIHorizontalAlignment.Right)+ .HyperlinkAppearance()+ .Text(ExtensionsManager.LearnDevelopExtension)+ .OnClick(OnLearnDevelopExtensionButtonClick)),++ Cell(+ GridRows.InfoBars,+ GridRows.InfoBars,+ GridColumns.Left,+ GridColumns.Right,++ _restartRequiredInfoBar+ .Informational()+ .Closable()+ .Title(ExtensionsManager.RestartRequiredInfoBarTitle)+ .Description(ExtensionsManager.RestartRequiredInfoBarDescription)),++ Cell(+ GridRows.ExtensionList,+ GridRows.ExtensionList,+ GridColumns.Left,+ GridColumns.Right,++ _extensionList+ .ForbidSelectItem())));+ }+ }++ public void OnDataReceived(string dataTypeName, object? parsedData)+ {+ throw new NotImplementedException();+ }++ private void OnFindMoreExtensionsOnlineButtonClick()+ {+ // TODO: Open documentation online+ Shell.OpenUrlInWebBrowser("http://url");+ }++ private void OnLearnDevelopExtensionButtonClick()+ {+ // TODO: Open documentation online+ Shell.OpenUrlInWebBrowser("http://url");+ }++ private async ValueTask OnInstallExtensionButtonClickAsync()+ {+ await ShowWarningUseThirdPartyExtensionMessageBoxAsync();++ PickedFile[] nugetPackages = await _fileStorage.PickOpenFilesAsync("nupkg");++ for (int i = 0; i < nugetPackages.Length; i++)+ {+ using PickedFile nugetPackage = nugetPackages[i];+ using var reader = new PackageArchiveReader(nugetPackage.Stream);++ NuspecReader nuspec = reader.NuspecReader;++ for (int j = 0; j < ExtensionInstallationManager.ExtensionInstallationFolders.Length; j++)+ {+ string potentialExtensionInstallationPath = Path.Combine(ExtensionInstallationManager.ExtensionInstallationFolders[j], nuspec.GetId());+ if (Directory.Exists(potentialExtensionInstallationPath))+ {+ // Extension is already installed.+ await ShowExtensionAlreadyInstalledMessageBoxAsync(nuspec.GetTitle());+ return;+ }+ }++ string extensionInstallationPath+ = Path.Combine(ExtensionInstallationManager.PreferredExtensionInstallationFolder, nuspec.GetId());++ // Unzip the extension.+ Directory.CreateDirectory(extensionInstallationPath);+ foreach (string? packagedFile in reader.GetFiles())+ {+ reader.ExtractFile(packagedFile, Path.Combine(extensionInstallationPath, packagedFile), null);+ }++ _extensionList.Items.Add(CreateExtensionListItem(nuspec, extensionInstallationPath));++ _restartRequiredInfoBar.Open();+ }+ }++ private void OnUninstallExtensionButtonClick(string extensionInstallationPath)+ {+ ExtensionInstallationManager.ScheduleExtensionToBeUninstalled(extensionInstallationPath);+ _restartRequiredInfoBar.Open();+ _extensionList.Items.RemoveValue(extensionInstallationPath);+ }++ private async Task LoadExtensionListAsync()+ {+ _extensionList.Items.Clear();++ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(CancellationToken.None);++ for (int i = 0; i < ExtensionInstallationManager.ExtensionInstallationFolders.Length; i++)+ {+ if (Directory.Exists(ExtensionInstallationManager.ExtensionInstallationFolders[i]))+ {+ IEnumerable<string> nuspecFiles+ = Directory.EnumerateFiles(ExtensionInstallationManager.ExtensionInstallationFolders[i], "*.nuspec", SearchOption.AllDirectories);++ foreach (string nuspecFile in nuspecFiles)+ {+ var nuspec = new NuspecReader(nuspecFile);+ _extensionList.Items.Add(CreateExtensionListItem(nuspec, Path.GetDirectoryName(nuspecFile)!));+ }+ }+ }+ }++ private IUIListItem CreateExtensionListItem(NuspecReader nuspec, string extensionInstallationPath)+ {+ ImmutableArray<IUIElement>.Builder actionBuilder = ImmutableArray.CreateBuilder<IUIElement>();++ // Calculate installation size.+ long size = 0;+ var dir = new DirectoryInfo(extensionInstallationPath);+ foreach (FileInfo fi in dir.GetFiles("*", SearchOption.AllDirectories))+ {+ size += fi.Length;+ }++ // Get project Url+ string? projectUrl = nuspec.GetProjectUrl();+ if (!string.IsNullOrEmpty(projectUrl))+ {+ actionBuilder.Add(+ Button()+ .Icon("FluentSystemIcons", '\uE6B1')+ .OnClick(() => NavigateToUrl(projectUrl)));+ }++ // Get project repository+ RepositoryMetadata repositoryInfo = nuspec.GetRepositoryMetadata();+ if (!string.IsNullOrEmpty(repositoryInfo?.Url))+ {+ actionBuilder.Add(+ Button()+ .Icon("FluentSystemIcons", '\uF0A6')+ .OnClick(() => NavigateToUrl(repositoryInfo.Url)));+ }++ // Add delete button.+ IUIButton uninstallButton+ = Button()+ .Icon("FluentSystemIcons", '\uE47B')+ .OnClick(() => OnUninstallExtensionButtonClick(extensionInstallationPath));+ actionBuilder.Add(uninstallButton);+ if (!extensionInstallationPath.StartsWith(ExtensionInstallationManager.PreferredExtensionInstallationFolder))+ {+ // We might not be able to uninstall the extension if it is installed in a different location because+ // it may require admin privileges(e.g.Program Files).+ uninstallButton.Disable();+ }++ // Create the item.+ return Item(+ Setting()+ .Icon("FluentSystemIcons", '\uE9E8')+ .Title(string.Format(ExtensionsManager.ExtensionTitleInList, nuspec.GetTitle(), nuspec.GetVersion()))+ .Description(nuspec.GetDescription())+ .InteractiveElement(+ Stack()+ .Horizontal()+ .MediumSpacing()+ .WithChildren(+ Label().Text(SizeWithUnit(size)),+ Stack()+ .Horizontal()+ .SmallSpacing()+ .WithChildren(actionBuilder.ToArray()))),+ extensionInstallationPath);++ static void NavigateToUrl(string url)+ {+ Shell.OpenUrlInWebBrowser(url);+ }+ }++ private async Task ShowWarningUseThirdPartyExtensionMessageBoxAsync()+ {+ if (_shownWarningInstallExtension)+ {+ return;+ }++ _shownWarningInstallExtension = true;++ await _view.Value.OpenDialogAsync(+ Stack()+ .Vertical()++ .WithChildren(+ Label()+ .Style(UILabelStyle.Subtitle)+ .Text(ExtensionsManager.WarningThirdPartyExtensionUsageTitle),+ Label()+ .Style(UILabelStyle.Body)+ .Text(ExtensionsManager.WarningThirdPartyExtensionUsageDescription)),++ footerContent:+ Stack()+ .AlignHorizontally(UIHorizontalAlignment.Right)+ .Horizontal()+ .WithChildren(+ Button("extension-third-party-warning-terms-service-button")+ .HyperlinkAppearance()+ .Text(ExtensionsManager.WarningThirdPartyExtensionUsageTermsConditions)+ .OnClick(OnTermsConditionsDialogButtonClick),+ Button("extension-third-party-warning-understand-button")+ .AccentAppearance()+ .Text(ExtensionsManager.WarningThirdPartyExtensionUsageIUnderstand)+ .OnClick(OnIUnderstandDialogButtonClick)),+ isDismissible: false);++ void OnTermsConditionsDialogButtonClick()+ {+ // TODO: Open the terms and conditions page.+ Shell.OpenUrlInWebBrowser("https://url");+ }++ void OnIUnderstandDialogButtonClick()+ {+ _view.Value.CurrentOpenedDialog?.Close();+ }++ await _view.Value.CurrentOpenedDialog!.DialogCloseAwaiter;+ }++ private async Task ShowExtensionAlreadyInstalledMessageBoxAsync(string extensionTitle)+ {+ await _view.Value.OpenDialogAsync(+ Stack()+ .Vertical()++ .WithChildren(+ Label()+ .Style(UILabelStyle.Subtitle)+ .Text(ExtensionsManager.ExtensionAlreadyInstalledTitle),+ Label()+ .Style(UILabelStyle.Body)+ .Text(string.Format(ExtensionsManager.ExtensionAlreadyInstalledDescription, extensionTitle))),++ Button("extension-already-exist-dialog-ok-button")+ .AlignHorizontally(UIHorizontalAlignment.Right)+ .Text(ExtensionsManager.OKButtonText)+ .OnClick(OnCloseDialogButtonClick),+ isDismissible: true);++ void OnCloseDialogButtonClick()+ {+ _view.Value.CurrentOpenedDialog?.Close();+ }+ }++ private static string SizeWithUnit(long value, int decimalPlaces = 1)+ {+ Guard.IsGreaterThan(decimalPlaces, 0);+ Guard.IsGreaterThanOrEqualTo(value, 0);++ if (value == 0)+ {+ return string.Format("{0:n" + decimalPlaces + "} bytes", 0);+ }++ // mag is 0 for bytes, 1 for KB, 2, for MB, etc.+ int mag = (int)Math.Log(value, 1024);++ // 1L << (mag * 10) == 2 ^ (10 * mag)+ // [i.e. the number of bytes in the unit corresponding to mag]+ decimal adjustedSize = (decimal)value / (1L << (mag * 10));++ // make adjustment when the value is large enough that+ // it would round up to 1000 or more+ if (Math.Round(adjustedSize, decimalPlaces) >= 1000)+ {+ mag += 1;+ adjustedSize /= 1024;+ }++ return string.Format(+ "{0:n" + decimalPlaces + "} {1}",+ adjustedSize,+ sizeUnits[mag]);+ }+}diff --git a/src/app/dev/DevToys.Blazor/DevToys.Blazor.csproj b/src/app/dev/DevToys.Blazor/DevToys.Blazor.csprojindex bb5a5a460..f3d99e844 100644--- a/src/app/dev/DevToys.Blazor/DevToys.Blazor.csproj+++ b/src/app/dev/DevToys.Blazor/DevToys.Blazor.csproj@@ -1,4 +1,4 @@-<Project Sdk="Microsoft.NET.Sdk.Razor">+<Project Sdk="Microsoft.NET.Sdk.Razor"><PropertyGroup><TargetFramework>$(NetCore)</TargetFramework>@@ -17,6 +17,7 @@<PrivateAssets>all</PrivateAssets><IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets></PackageReference>+ <PackageReference Include="NuGet.Packaging" /></ItemGroup><ItemGroup>@@ -50,10 +51,19 @@<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory></EmbeddedResource><EmbeddedResource Include="Assets\samples\json-sample.json" />+ <EmbeddedResource Update="BuiltInTools\ExtensionsManager\ExtensionsManager.resx">+ <Generator>ResXFileCodeGenerator</Generator>+ <LastGenOutput>ExtensionsManager.Designer.cs</LastGenOutput>+ </EmbeddedResource><EmbeddedResource Update="BuiltInTools\Settings\Settings.resx"><LastGenOutput>Settings.Designer.cs</LastGenOutput><Generator>ResXFileCodeGenerator</Generator></EmbeddedResource>+ <Compile Update="BuiltInTools\ExtensionsManager\ExtensionsManager.Designer.cs">+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ <DependentUpon>ExtensionsManager.resx</DependentUpon>+ </Compile><Compile Update="BuiltInTools\Settings\Settings.Designer.cs"><DependentUpon>Settings.resx</DependentUpon><DesignTime>True</DesignTime>diff --git a/src/app/dev/DevToys.Core/Mef/MefComposer.cs b/src/app/dev/DevToys.Core/Mef/MefComposer.csindex d6ebe6f9f..54a82d872 100644--- a/src/app/dev/DevToys.Core/Mef/MefComposer.cs+++ b/src/app/dev/DevToys.Core/Mef/MefComposer.cs@@ -11,7 +11,7 @@ public sealed partial class MefComposer : IDisposable{private readonly ILogger _logger;private readonly Assembly[] _assemblies;- private readonly string? _pluginFolder;+ private readonly string[]? _pluginFolders;private readonly object[] _customExports;private bool _isExportProviderDisposed = true;@@ -19,7 +19,7 @@ public sealed partial class MefComposer : IDisposablepublic CompositionContainer ExportProvider { get; private set; }- public MefComposer(Assembly[]? assemblies = null, string? pluginFolder = null, params object[] customExports)+ public MefComposer(Assembly[]? assemblies = null, string[]? pluginFolders = null, params object[] customExports){if (Provider is not null){@@ -29,7 +29,7 @@ public sealed partial class MefComposer : IDisposable_logger = this.Log();_assemblies = assemblies ?? Array.Empty<Assembly>();- _pluginFolder = pluginFolder;+ _pluginFolders = pluginFolders;_customExports = customExports ?? Array.Empty<object>();ExportProvider = InitializeMef();@@ -115,22 +115,28 @@ public sealed partial class MefComposer : IDisposablestring appFolder = AppContext.BaseDirectory;if (!string.IsNullOrEmpty(appFolder)){- string pluginFolder;- if (!string.IsNullOrEmpty(_pluginFolder))+ string[] pluginFolders;+ if (_pluginFolders is not null){- pluginFolder = Path.Combine(appFolder!, _pluginFolder!);+ pluginFolders = _pluginFolders;}else{- pluginFolder = Path.Combine(appFolder!, "Plugins");+ pluginFolders = new[] { Path.Combine(appFolder!, "Plugins") };}- if (Directory.Exists(pluginFolder))++ for (int i = 0; i < pluginFolders.Length; i++){- return Directory.EnumerateDirectories(pluginFolder, "*", SearchOption.TopDirectoryOnly);+ string pluginFolder = pluginFolders[i];+ if (Directory.Exists(pluginFolder))+ {+ foreach (string folder in Directory.EnumerateDirectories(pluginFolder, "*", SearchOption.TopDirectoryOnly))+ {+ yield return folder;+ }+ }}}-- return Array.Empty<string>();}[LoggerMessage(0, LogLevel.Information, "MEF composed in {duration} ms")]diff --git a/src/app/dev/DevToys.Core/Tools/GuiToolInstance.cs b/src/app/dev/DevToys.Core/Tools/GuiToolInstance.csindex e8e91b7c0..009798474 100644--- a/src/app/dev/DevToys.Core/Tools/GuiToolInstance.cs+++ b/src/app/dev/DevToys.Core/Tools/GuiToolInstance.cs@@ -110,6 +110,7 @@ public sealed partial class GuiToolInstance : ObservableObject_view= new(() =>{+ Exception? exception = null;try{return _instance.Value.View;@@ -117,10 +118,11 @@ public sealed partial class GuiToolInstance : ObservableObjectcatch (NotImplementedException) { }catch (Exception ex){+ exception = ex;LogGetToolViewFailed(ex, InternalComponentName);}- return new UIToolView(GUI.Label("unable-load-tool-view", $"Failed to load '{InternalComponentName}'."));+ return new UIToolView(GUI.Label("unable-load-tool-view", $"Failed to load '{InternalComponentName}'. " + exception?.Message));});}diff --git a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj b/src/app/dev/DevToys.Tools/DevToys.Tools.csprojindex 40220f8a4..be3a159d1 100644--- a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj+++ b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj@@ -4,10 +4,15 @@<!-- See https://learn.microsoft.com/en-us/dotnet/core/project-sdk/msbuild-props#enabledynamicloading --><EnableDynamicLoading>true</EnableDynamicLoading>-+<!-- NuGet package --><GeneratePackageOnBuild>True</GeneratePackageOnBuild>+ <Version>2.0.0-pre.2</Version><Title>DevToys.Tools</Title>+ <Description>A set of offline tools installed by default with DevToys.</Description>+ <PackageProjectUrl>https://devtoys.app</PackageProjectUrl>+ <RepositoryUrl>https://github.com/veler/DevToys</RepositoryUrl>+ <Authors>veler,btiteux</Authors></PropertyGroup><ItemGroup><ProjectReference Include="..\DevToys.Api\DevToys.Api.csproj">@@ -50,10 +55,12 @@<PackageReference Include="System.Text.Json" /></ItemGroup>- <Target Name="CopyPluginAfterBuild" AfterTargets="Build">- <ItemGroup>- <PluginOutput Include="$(OutputPath)\**\*" />- </ItemGroup>- <Copy SourceFiles="@(PluginOutput)" DestinationFolder="$(RepoRoot)bin\$(Configuration)\Plugins\DevToys.Tools" SkipUnchangedFiles="false" OverwriteReadOnlyFiles="true" Retries="10" RetryDelayMilliseconds="1000" />+ <Target Name="CopyPluginAfterBuild" AfterTargets="Pack">+ <Copy SourceFiles="$(PackageOutputPath)\$(PackageId).$(PackageVersion).nupkg"+ DestinationFolder="$(PluginNupkgPath)"+ SkipUnchangedFiles="false"+ OverwriteReadOnlyFiles="true"+ Retries="10"+ RetryDelayMilliseconds="1000" /></Target></Project>\ No newline at end of filediff --git a/src/app/dev/platforms/desktop/DevToys.CLI/DevToys.CLI.csproj b/src/app/dev/platforms/desktop/DevToys.CLI/DevToys.CLI.csprojindex 4e7379659..81493a5cb 100644--- a/src/app/dev/platforms/desktop/DevToys.CLI/DevToys.CLI.csproj+++ b/src/app/dev/platforms/desktop/DevToys.CLI/DevToys.CLI.csproj@@ -4,6 +4,7 @@<OutputType>Exe</OutputType><TargetFramework>$(NetCore)</TargetFramework><UseAppHost>True</UseAppHost>+ <PluginsInstallationFolder>$(OutputPath)\$(TargetFramework)\Plugins</PluginsInstallationFolder></PropertyGroup><ItemGroup>diff --git a/src/app/dev/platforms/desktop/DevToys.CLI/Program.cs b/src/app/dev/platforms/desktop/DevToys.CLI/Program.csindex 93f6d403d..92eaddfea 100644--- a/src/app/dev/platforms/desktop/DevToys.CLI/Program.cs+++ b/src/app/dev/platforms/desktop/DevToys.CLI/Program.cs@@ -64,9 +64,13 @@ internal partial class Program// Initialize MEF.var mefComposer= new MefComposer(- new[]+ assemblies: new[]{typeof(Program).Assembly+ },+ pluginFolders: new[]+ {+ Path.Combine(AppContext.BaseDirectory, "Plugins")});// Get all the command line tools.diff --git a/src/app/dev/platforms/desktop/DevToys.MacOS/DevToys.MacOS.csproj b/src/app/dev/platforms/desktop/DevToys.MacOS/DevToys.MacOS.csprojindex 1390d41bc..25399411c 100644--- a/src/app/dev/platforms/desktop/DevToys.MacOS/DevToys.MacOS.csproj+++ b/src/app/dev/platforms/desktop/DevToys.MacOS/DevToys.MacOS.csproj@@ -10,6 +10,7 @@<EnableDefaultCssItems>false</EnableDefaultCssItems><DefineConstants>$(DefineConstants);__MACCATALYST__</DefineConstants><RuntimeIdentifiers>maccatalyst-arm64</RuntimeIdentifiers>+ <PluginsInstallationFolder>$(OutputPath)\$(TargetFramework)\Plugins</PluginsInstallationFolder><!-- Display name --><ApplicationTitle>DevToys</ApplicationTitle>@@ -67,6 +68,7 @@<ItemGroup><Content Include="$(RepoRoot)\src\app\dev\platforms\desktop\DevToys.Windows\wwwroot\index.html" Link="wwwroot\index.html" />+ <Content Include="$(PluginsInstallationFolder)\**\*" Link="Plugins\%(RecursiveDir)%(Filename)%(Extension)"/></ItemGroup></Project>diff --git a/src/app/dev/platforms/desktop/DevToys.MacOS/MauiProgram.cs b/src/app/dev/platforms/desktop/DevToys.MacOS/MauiProgram.csindex 6a54a5a74..8d2e1249e 100644--- a/src/app/dev/platforms/desktop/DevToys.MacOS/MauiProgram.cs+++ b/src/app/dev/platforms/desktop/DevToys.MacOS/MauiProgram.cs@@ -1,5 +1,6 @@using DevToys.Api;using DevToys.Blazor.BuiltInTools;+using DevToys.Blazor.BuiltInTools.ExtensionsManager;using DevToys.Blazor.Core.Languages;using DevToys.Blazor.Core.Services;using DevToys.Business.ViewModels;@@ -50,14 +51,25 @@ public partial class MauiProgramargs.ExceptionMode = ObjCRuntime.MarshalManagedExceptionMode.UnwindNativeCode;};+ // Initialize extension installation folder, and uninstall extensions that are planned for being removed.+ string[] pluginFolders+ = new[]+ {+ Path.Combine(AppContext.BaseDirectory!, "../Resources/Plugins"),+ Constants.PluginInstallationFolder+ };+ ExtensionInstallationManager.PreferredExtensionInstallationFolder = Constants.PluginInstallationFolder;+ ExtensionInstallationManager.ExtensionInstallationFolders = pluginFolders;+ ExtensionInstallationManager.UninstallExtensionsScheduledForRemoval();+// Initialize MEF.MefComposer= new MefComposer(- new[] {+ assemblies: new[] {typeof(MainWindowViewModel).Assembly,typeof(DevToysBlazorResourceManagerAssemblyIdentifier).Assembly},- pluginFolder: "../Resources/Plugins");+ pluginFolders);LogInitialization((DateTime.Now - startTime).TotalMilliseconds);LogAppStarting();diff --git a/src/app/dev/platforms/desktop/DevToys.Windows/DevToys.Windows.csproj b/src/app/dev/platforms/desktop/DevToys.Windows/DevToys.Windows.csprojindex 6c3092ff7..914e94740 100644--- a/src/app/dev/platforms/desktop/DevToys.Windows/DevToys.Windows.csproj+++ b/src/app/dev/platforms/desktop/DevToys.Windows/DevToys.Windows.csproj@@ -9,6 +9,7 @@<ApplicationManifest>app.manifest</ApplicationManifest><AllowUnsafeBlocks>true</AllowUnsafeBlocks><ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>+ <PluginsInstallationFolder>$(OutputPath)\$(TargetFramework)\Plugins</PluginsInstallationFolder></PropertyGroup><ItemGroup>diff --git a/src/app/dev/platforms/desktop/DevToys.Windows/MainWindow.xaml.cs b/src/app/dev/platforms/desktop/DevToys.Windows/MainWindow.xaml.csindex 0d1fea5e3..30f25af96 100644--- a/src/app/dev/platforms/desktop/DevToys.Windows/MainWindow.xaml.cs+++ b/src/app/dev/platforms/desktop/DevToys.Windows/MainWindow.xaml.cs@@ -1,6 +1,8 @@-using System.Windows.Interop;+using System.IO;+using System.Windows.Interop;using DevToys.Api;using DevToys.Blazor.BuiltInTools;+using DevToys.Blazor.BuiltInTools.ExtensionsManager;using DevToys.Blazor.Core.Languages;using DevToys.Blazor.Core.Services;using DevToys.Business.ViewModels;@@ -41,13 +43,25 @@ public partial class MainWindow : MicaWindowWithOverlay// Listen for unhandled exceptions.AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;+ // Initialize extension installation folder, and uninstall extensions that are planned for being removed.+ string[] pluginFolders+ = new[]+ {+ Path.Combine(AppContext.BaseDirectory!, "Plugins"),+ Constants.PluginInstallationFolder+ };+ ExtensionInstallationManager.PreferredExtensionInstallationFolder = Constants.PluginInstallationFolder;+ ExtensionInstallationManager.ExtensionInstallationFolders = pluginFolders;+ ExtensionInstallationManager.UninstallExtensionsScheduledForRemoval();+// Initialize MEF._mefComposer= new MefComposer(- new[] {+ assemblies: new[] {typeof(MainWindowViewModel).Assembly,typeof(DevToysBlazorResourceManagerAssemblyIdentifier).Assembly- });+ },+ pluginFolders);LogInitialization((DateTime.Now - startTime).TotalMilliseconds);LogAppStarting();diff --git a/src/app/dev/platforms/desktop/Directory.Build.props b/src/app/dev/platforms/desktop/Directory.Build.propsindex 218874157..17b73bfe1 100644--- a/src/app/dev/platforms/desktop/Directory.Build.props+++ b/src/app/dev/platforms/desktop/Directory.Build.props@@ -1,10 +1,18 @@<Project><Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" />- <!-- Include DevToys.Tools and other plugins to the output --><ItemGroup>- <Content Include="$(RepoRoot)bin\$(Configuration)\Plugins\**\*" Link="Plugins\%(RecursiveDir)%(Filename)%(Extension)">+ <!-- HACK: This force MSBuild to check whether we rebuilt a plugin. If yes, then it forces to rebuild the current+ project and unpack the nupkg so we can debug a change we made to an extension. -->+ <UpToDateCheckInput Include="$(PluginNupkgPath)\**\*.nupkg" />+ </ItemGroup>++ <!-- Include DevToys.Tools and other plugins to the output -->+ <!--<ItemGroup>+ <Content Include="$(RepoRoot)bin\$(Configuration)\Plugins\**\*"+ Exclude="$(RepoRoot)bin\$(Configuration)\Plugins\**\*.nupkg"+ Link="Plugins\%(RecursiveDir)%(Filename)%(Extension)"><CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory></Content>- </ItemGroup>+ </ItemGroup>--></Project>\ No newline at end of filediff --git a/src/app/dev/platforms/desktop/Directory.Build.targets b/src/app/dev/platforms/desktop/Directory.Build.targetsindex 314b4fa3e..1f298b02b 100644--- a/src/app/dev/platforms/desktop/Directory.Build.targets+++ b/src/app/dev/platforms/desktop/Directory.Build.targets@@ -1,18 +1,29 @@<Project><Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.targets', '$(MSBuildThisFileDirectory)../'))" />+ <Target Name="ImportPluginOnBuild" BeforeTargets="Run" AfterTargets="Build">+ <Message Text="Importing plugins..." Importance="high" />+ <ItemGroup>+ <PluginNupkgFiles Include="$(PluginNupkgPath)\*.nupkg" />+ </ItemGroup>+ <Unzip+ SourceFiles="@(PluginNupkgFiles)"+ DestinationFolder="$(PluginsInstallationFolder)\$([System.String]::Copy('%(Filename)').Split('.')[0]).$([System.String]::Copy('%(Filename)').Split('.')[1])"+ SkipUnchangedFiles="true"+ OverwriteReadOnlyFiles="true"/>+ <Message Text="Plugins imported!" Importance="high" />+ </Target>+<Target Name="ImportPluginOnPublish" BeforeTargets="Publish"><Message Text="Importing plugins..." Importance="high" /><ItemGroup>- <PluginOutput Include="$(RepoRoot)bin\$(Configuration)\Plugins\**\*" />+ <PluginNupkgFiles Include="$(PluginNupkgPath)\*.nupkg" /></ItemGroup>- <Copy- SourceFiles="@(PluginOutput)"- DestinationFolder="$(PublishDir)\Plugins\%(RecursiveDir)"+ <Unzip+ SourceFiles="@(PluginNupkgFiles)"+ DestinationFolder="$(PluginsInstallationFolder)\$([System.String]::Copy('%(Filename)').Split('.')[0]).$([System.String]::Copy('%(Filename)').Split('.')[1])"SkipUnchangedFiles="true"- OverwriteReadOnlyFiles="true"- Retries="10"- RetryDelayMilliseconds="1000" />+ OverwriteReadOnlyFiles="true"/><Message Text="Plugins imported!" Importance="high" /></Target></Project>\ No newline at end of filediff --git a/src/build/AppVersion/AppVersionTask.cs b/src/build/AppVersion/AppVersionTask.csindex fd0d7b780..20491c944 100644--- a/src/build/AppVersion/AppVersionTask.cs+++ b/src/build/AppVersion/AppVersionTask.cs@@ -7,9 +7,11 @@ internal static class AppVersionTask{internal static void SetAppVersion(AbsolutePath rootDirectory){- string appVersion = GetAppVersion(rootDirectory);+ string[] appVersionNumberAppContent = GetAppVersionNumberFileContent(rootDirectory);+ string appVersion = GetAppVersion(appVersionNumberAppContent);+ string sdkVersion = GetSdkVersion(appVersionNumberAppContent);- var csharpUpdater = new CSharpUpdater(appVersion);+ var csharpUpdater = new CSharpUpdater(appVersion, sdkVersion);IReadOnlyCollection<AbsolutePath> assemblyVersionFiles= rootDirectory.GlobFiles("**/*AssemblyVersion.cs");foreach (AbsolutePath file in assemblyVersionFiles)@@ -18,6 +20,15 @@ internal static class AppVersionTaskcsharpUpdater.UpdateFile(file);}+ var projectUpdater = new ProjectUpdater(sdkVersion);+ IReadOnlyCollection<AbsolutePath> projectFiles+ = rootDirectory.GlobFiles("**/*DevToys.Api.csproj");+ foreach (AbsolutePath file in projectFiles)+ {+ Log.Information("Updating project version in {File}...", file);+ projectUpdater.UpdateFile(file);+ }+var appxManifestUpdater = new AppxManifestUpdater(appVersion);IReadOnlyCollection<AbsolutePath> appxmanifestFiles= rootDirectory.GlobFiles("**/*.appxmanifest");@@ -28,7 +39,7 @@ internal static class AppVersionTask}}- private static string GetAppVersion(AbsolutePath rootDirectory)+ private static string[] GetAppVersionNumberFileContent(AbsolutePath rootDirectory){AbsolutePath appVersionNumberFile = rootDirectory / "tools" / "app-version-number.txt";if (!appVersionNumberFile.FileExists())@@ -37,6 +48,29 @@ internal static class AppVersionTaskthrow new FileNotFoundException("Unable to find the app version number file.", appVersionNumberFile.ToString());}- return File.ReadAllText(appVersionNumberFile);+ return File.ReadAllLines(appVersionNumberFile);+ }++ private static string GetAppVersion(string[] appVersionNumberAppContent)+ {+ return GetVersion(appVersionNumberAppContent, "app");+ }++ private static string GetSdkVersion(string[] appVersionNumberAppContent)+ {+ return GetVersion(appVersionNumberAppContent, "sdk");+ }++ private static string GetVersion(string[] appVersionNumberAppContent, string name)+ {+ for (int i = 0; i < appVersionNumberAppContent.Length; i++)+ {+ if (appVersionNumberAppContent[i].StartsWith(name + ":"))+ {+ return appVersionNumberAppContent[i].Substring(name.Length + 1);+ }+ }++ return string.Empty;}}diff --git a/src/build/AppVersion/CSharpUpdater.cs b/src/build/AppVersion/CSharpUpdater.csindex 557a8dd76..4df67d055 100644--- a/src/build/AppVersion/CSharpUpdater.cs+++ b/src/build/AppVersion/CSharpUpdater.cs@@ -7,13 +7,14 @@ internal sealed class CSharpUpdater{private readonly List<CSharpVersionUpdateRule> _updateRules;- internal CSharpUpdater(string version)+ internal CSharpUpdater(string appVersion, string sdkVersion){_updateRules = new List<CSharpVersionUpdateRule>();- if (!string.IsNullOrEmpty(version))+ if (!string.IsNullOrEmpty(appVersion)){- _updateRules.Add(new CSharpVersionUpdateRule("AssemblyVersion", version));- _updateRules.Add(new CSharpVersionUpdateRule("AssemblyFileVersion", version));+ _updateRules.Add(new CSharpVersionUpdateRule("AssemblyVersion", appVersion));+ _updateRules.Add(new CSharpVersionUpdateRule("AssemblyFileVersion", appVersion));+ _updateRules.Add(new CSharpVersionUpdateRule("AssemblyInformationalVersion", sdkVersion));}}@@ -68,7 +69,7 @@ internal sealed class CSharpUpdater}string attributeMatch = string.Format("(?:(?:{0})|(?:{0}Attribute))", attributeName);- string pattern = @"^\s*\[assembly: " + attributeMatch + @"\(""(?<Version>[0-9\.\*]+)""\)\]";+ string pattern = @"^\s*\[assembly: " + attributeMatch + @"\(""(?<Version>[0-9(\-\w)?\.\*]+)""\)\]";var regex = new Regex(pattern);Match m = regex.Match(input);if (m.Success)diff --git a/src/build/AppVersion/ProjectUpdater.cs b/src/build/AppVersion/ProjectUpdater.csnew file mode 100644index 000000000..febdb77ed--- /dev/null+++ b/src/build/AppVersion/ProjectUpdater.cs@@ -0,0 +1,74 @@+using System.Collections.Generic;+using System.Text.RegularExpressions;+using System.IO;+using System;++internal sealed class ProjectUpdater+{+ private readonly List<ProjectVersionUpdateRule> _updateRules;++ internal ProjectUpdater(string sdkVersion)+ {+ _updateRules = new List<ProjectVersionUpdateRule>();+ if (!string.IsNullOrEmpty(sdkVersion))+ {+ _updateRules.Add(new ProjectVersionUpdateRule("Version", sdkVersion));+ }+ }++ public void UpdateFile(string fileName)+ {+ string[] lines = File.ReadAllLines(fileName);++ var outlines = new List<string>();+ foreach (string line in lines)+ {+ outlines.Add(UpdateLine(line));+ }++ File.WriteAllLines(fileName, outlines.ToArray());+ }++ private string UpdateLine(string line)+ {+ foreach (ProjectVersionUpdateRule rule in _updateRules)+ {+ if (UpdateLineWithRule(ref line, rule))+ {+ break;+ }+ }+ return line;+ }++ private static bool UpdateLineWithRule(ref string line, ProjectVersionUpdateRule rule)+ {+ bool updated = false;+ Group? g = GetVersionString(line, rule.ParameterName);+ if (g != null)+ {+ if (VersionString.TryParse(g.Value, out VersionString? v) && v is not null)+ {+ string newVersion = rule.Update(v);+ line = string.Concat(line.AsSpan(0, g.Index), newVersion, line.AsSpan(g.Index + g.Length));+ updated = true;+ }+ }++ return updated;+ }++ private static Group? GetVersionString(string input, string parameterName)+ {+ string parameterMatch = string.Format("(?:(?:{0})|(?:{0}Attribute))", parameterName);++ string pattern = @"^\s*\<" + parameterMatch + @">(?<Version>[0-9(\-\w)?\.\*]+)</" + parameterMatch + ">";+ var regex = new Regex(pattern);+ Match m = regex.Match(input);+ if (m.Success)+ {+ return m.Groups["Version"];+ }+ return null;+ }+}diff --git a/src/build/AppVersion/ProjectVersionUpdateRule.cs b/src/build/AppVersion/ProjectVersionUpdateRule.csnew file mode 100644index 000000000..28f7689d9--- /dev/null+++ b/src/build/AppVersion/ProjectVersionUpdateRule.cs@@ -0,0 +1,11 @@+internal class ProjectVersionUpdateRule+{+ private readonly VersionUpdateRule _updateRule;+ public ProjectVersionUpdateRule(string parameterName, string updateRule)+ {+ ParameterName = parameterName;+ _updateRule = new VersionUpdateRule(updateRule);+ }+ public string ParameterName { get; private set; }+ public string Update(VersionString v) { return _updateRule.Update(v); }+}diff --git a/src/build/AppVersion/VersionString.cs b/src/build/AppVersion/VersionString.csindex c7a7d03da..6013af510 100644--- a/src/build/AppVersion/VersionString.cs+++ b/src/build/AppVersion/VersionString.cs@@ -21,7 +21,7 @@ internal sealed class VersionStringprivate bool Parse(string input){- string pattern = @"^(?<Major>\d+)\.(?<Minor>\d+)\.(?:(?:(?<Build>\d+)\.(?<Revision>\*|\d+))|(?<Build>\*|\d+))$";+ string pattern = @"^(?<Major>\d+)\.(?<Minor>\d+)\.(?:(?:(?<Build>\d+|\d+\-\w*)\.(?<Revision>\*|\d+|\d+\-\w*))|(?<Build>\*|\d+|\d+\-\w*))$";var regex = new Regex(pattern);Match match = regex.Match(input);if (match.Success)diff --git a/src/build/AppVersion/VersionUpdateRule.cs b/src/build/AppVersion/VersionUpdateRule.csindex e81b5c71f..abe73b564 100644--- a/src/build/AppVersion/VersionUpdateRule.cs+++ b/src/build/AppVersion/VersionUpdateRule.cs@@ -13,7 +13,10 @@ internal sealed class VersionUpdateRule}foreach (string partRule in _partRules){- if (partRule == "+" || partRule == "=")+ if (partRule == "+"+ || partRule == "*"+ || partRule == "="+ || partRule.Contains("-pre")){// OK, valid rule}@@ -45,7 +48,7 @@ internal sealed class VersionUpdateRuleoutParts.Add(inParts[index]);}}- else if (rule == "+")+ else if (rule == "+" || rule == "*"){if (inPart.Length == 0){diff --git a/src/build/Build.cs b/src/build/Build.csindex fa5896981..8fc9e0104 100644--- a/src/build/Build.cs+++ b/src/build/Build.cs@@ -28,7 +28,7 @@ class Build : NukeBuild/// - Microsoft VisualStudio https://nuke.build/visualstudio/// - Microsoft VSCode https://nuke.build/vscode- public static int Main() => Execute<Build>(x => x.Publish);+ public static int Main() => Execute<Build>(x => x.PublishApp);[Parameter("Configuration to build - Default is 'Release'")]readonly Configuration Configuration = Configuration.Release;@@ -91,7 +91,7 @@ class Build : NukeBuild});Target SetVersion => _ => _- .DependentFor(Publish)+ .DependentFor(GenerateSdkNuGet).After(Restore).OnlyWhenDynamic(() => Configuration == Configuration.Release).Executes(() =>@@ -100,7 +100,7 @@ class Build : NukeBuild});Target BuildGenerators => _ => _- .DependentFor(Publish)+ .DependentFor(GenerateSdkNuGet).After(Restore).After(SetVersion).Executes(() =>@@ -118,14 +118,14 @@ class Build : NukeBuild});Target BuildPlugins => _ => _- .DependentFor(Publish)+ .DependentFor(GenerateSdkNuGet).After(Restore).After(SetVersion).After(BuildGenerators).Executes(() =>{Log.Information($"Building plugins ...");- Project project = WindowsSolution!.GetProject("DevToys.Tools");+ Project project = WindowsSolution!.GetAllProjects("DevToys.Tools").Single();DotNetBuild(s => s.SetProjectFile(project).SetConfiguration(Configuration)@@ -136,7 +136,7 @@ class Build : NukeBuild#pragma warning disable IDE0051 // Remove unused private membersTarget UnitTests => _ => _- .DependentFor(Publish)+ .DependentFor(GenerateSdkNuGet).After(Restore).After(SetVersion).After(BuildGenerators)@@ -154,11 +154,28 @@ class Build : NukeBuild});#pragma warning restore IDE0051 // Remove unused private members- Target Publish => _ => _+ Target GenerateSdkNuGet => _ => _+ .Description("Generate the DevToys SDK NuGet package").DependsOn(SetVersion).DependsOn(Restore).DependsOn(BuildGenerators).Executes(() =>+ {+ Log.Information($"Building NuGet packages ...");+ Project project = WindowsSolution!.GetAllProjects("DevToys.Api").Single();+ DotNetPack(s => s+ .SetProject(project)+ .SetConfiguration(Configuration)+ .SetPublishTrimmed(false)+ .SetVerbosity(DotNetVerbosity.Quiet)+ .SetProcessArgumentConfigurator(_ => _+ .Add($"/bl:\"{RootDirectory / "publish" / "Sdk"}.binlog\""))+ .SetOutputDirectory(RootDirectory / "publish" / "Sdk"));+ });++ Target PublishApp => _ => _+ .DependsOn(GenerateSdkNuGet)+ .Executes(() =>{if (PlatformTargets!.Contains(PlatformTarget.Windows)){@@ -265,7 +282,7 @@ class Build : NukeBuild}else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)){- project = WindowsSolution!.GetProject(publishProject);+ project = WindowsSolution!.GetAllProjects(publishProject).Single();foreach (string targetFramework in project.GetTargetFrameworks()){yield return new DotnetParameters(project.Path, "win10-x64", targetFramework, portable: false);@@ -292,7 +309,7 @@ class Build : NukeBuildif (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)){- project = WindowsSolution!.GetProject(publishProject);+ project = WindowsSolution!.GetAllProjects(publishProject).Single();foreach (string targetFramework in project.GetTargetFrameworks()){yield return new DotnetParameters(project.Path, "win10-arm64", targetFramework, portable: false, platform: "arm64");diff --git a/src/spellcheckerexclusion.dic b/src/spellcheckerexclusion.dicindex 6b1a82afb..8a054922f 100644--- a/src/spellcheckerexclusion.dic+++ b/src/spellcheckerexclusion.dic@@ -10,3 +10,4 @@ Doesntmonaconugetnuspec+nupkg