Ver Fonte

Palettes api changes and resources in ext

flabbet há 1 ano atrás
pai
commit
2cbe0f151b

+ 6 - 0
samples/PixiEditorExtensionSamples.sln

@@ -15,6 +15,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_References", "_References"
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample4_CreatePopup", "Sample4_CreatePopup\Sample4_CreatePopup.csproj", "{93ADCE51-F671-4374-84AC-5AB07A098F27}"
 EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample5_Resources", "Sample5_Resources\Sample5_Resources.csproj", "{51E1742D-132F-4CE9-9313-67FF1AC785D6}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -44,6 +46,10 @@ Global
 		{93ADCE51-F671-4374-84AC-5AB07A098F27}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{93ADCE51-F671-4374-84AC-5AB07A098F27}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{93ADCE51-F671-4374-84AC-5AB07A098F27}.Release|Any CPU.Build.0 = Release|Any CPU
+		{51E1742D-132F-4CE9-9313-67FF1AC785D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{51E1742D-132F-4CE9-9313-67FF1AC785D6}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{51E1742D-132F-4CE9-9313-67FF1AC785D6}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{51E1742D-132F-4CE9-9313-67FF1AC785D6}.Release|Any CPU.Build.0 = Release|Any CPU
 	EndGlobalSection
 	GlobalSection(NestedProjects) = preSolution
 		{FD9B4C32-4D2E-410E-BC6B-787779BEB6E2} = {7CC35BC4-829F-4EF4-8EB6-E1D46206E7DC}

+ 16 - 0
samples/Sample5_Resources/Program.cs

@@ -0,0 +1,16 @@
+using ResourcesSample;
+
+namespace CreatePopupSample;
+
+public static class Program
+{
+    /// <summary>
+    ///     The entry point of the application. This will be executed when extension is loaded.
+    /// You can use this method, but there are special methods that are used for initialization. You won't be able to access PixiEditor Api at this point.
+    /// See <see cref="ResourcesSampleExtension"/> for more information.
+    /// </summary>
+    public static void Main()
+    {
+
+    }
+}

+ 1 - 0
samples/Sample5_Resources/Resources/ExampleFile.txt

@@ -0,0 +1 @@
+I am loaded from resources

+ 26 - 0
samples/Sample5_Resources/ResourcesSampleExtension.cs

@@ -0,0 +1,26 @@
+using System.IO;
+using PixiEditor.Extensions.Wasm;
+
+namespace ResourcesSample;
+
+public class ResourcesSampleExtension : WasmExtension
+{
+    /// <summary>
+    ///     This method is called when extension is loaded.
+    ///  All extensions are first loaded and then initialized. This method is called before <see cref="OnInitialized"/>.
+    /// </summary>
+    public override void OnLoaded()
+    {
+
+    }
+
+    /// <summary>
+    ///     This method is called when extension is initialized. After this method is called, you can use Api property to access PixiEditor API.
+    /// </summary>
+    public override void OnInitialized()
+    {
+        // By default, you can't access any files from the file system, however you can access files from the Resources folder.
+        // This folder contains files that you put in the Resources folder in the extension project.
+        Api.Logger.Log(File.ReadAllText("Resources/ExampleFile.txt"));
+    }
+}

+ 42 - 0
samples/Sample5_Resources/Sample5_Resources.csproj

@@ -0,0 +1,42 @@
+<Project Sdk="Microsoft.NET.Sdk">
+    <PropertyGroup>
+        <TargetFramework>net8.0</TargetFramework>
+        <RuntimeIdentifier>wasi-wasm</RuntimeIdentifier>
+        <OutputType>Exe</OutputType>
+        <PublishTrimmed>true</PublishTrimmed>
+        <WasmSingleFileBundle>true</WasmSingleFileBundle>
+        <GenerateExtensionPackage>true</GenerateExtensionPackage>
+        <PixiExtOutputPath>..\..\src\PixiEditor.AvaloniaUI.Desktop\bin\Debug\net8.0\win-x64\Extensions</PixiExtOutputPath>
+        <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
+        <RootNamespace>ResourcesSample</RootNamespace>
+    </PropertyGroup>
+
+    <ItemGroup>
+        <None Remove="extension.json" />
+        <Content Include="extension.json">
+            <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+        </Content>
+    </ItemGroup>
+
+    <ItemGroup>
+        <Content Include="Localization\*">
+            <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+        </Content>
+    </ItemGroup>
+
+    <ItemGroup>
+        <Content Include="Resources\*">
+            <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+        </Content>
+    </ItemGroup>
+
+    <!--Below is not required if you use Nuget package, this sample references project directly, so it must be here-->
+    <ItemGroup>
+        <ProjectReference Include="..\..\src\PixiEditor.Extensions.Wasm\PixiEditor.Extensions.Wasm.csproj" />
+    </ItemGroup>
+
+    <!--Below is not required if you use Nuget package, this sample references project directly, so it must be here-->
+    <Import Project="..\..\src\PixiEditor.Extensions.Wasm\build\PixiEditor.Extensions.Wasm.props"/>
+    <Import Project="..\..\src\PixiEditor.Extensions.Wasm\build\PixiEditor.Extensions.Wasm.targets" />
+
+</Project>

+ 27 - 0
samples/Sample5_Resources/extension.json

@@ -0,0 +1,27 @@
+{
+  "displayName": "Sample Extension - Resources",
+  "uniqueName": "yourCompany.Samples.Resources",
+  "description": "Sample localization extension for PixiEditor",
+  "version": "1.0.0",
+  "author": {
+    "name": "PixiEditor",
+    "email": "[email protected]",
+    "website": "https://pixieditor.net"
+  },
+  "publisher": {
+    "name": "PixiEditor",
+    "email": "[email protected]",
+    "website": "https://pixieditor.net"
+  },
+  "contributors": [
+    {
+      "name": "flabbet",
+      "email": "[email protected]",
+      "website": "https://github.com/flabbet"
+    }
+  ],
+  "license": "MIT",
+  "categories": [
+    "Extension"
+  ]
+}

+ 1 - 1
src/PixiEditor.AvaloniaUI/Helpers/ServiceCollectionHelpers.cs

@@ -100,6 +100,7 @@ internal static class ServiceCollectionHelpers
             .AddSingleton<IToolHandler, BrightnessToolViewModel>(x => (BrightnessToolViewModel)x.GetService<IBrightnessToolHandler>())
             .AddSingleton<IToolHandler, ZoomToolViewModel>()
             // Palette Parsers
+            .AddSingleton<PaletteProvider>()
             .AddSingleton<PaletteFileParser, JascFileParser>()
             .AddSingleton<PaletteFileParser, ClsFileParser>()
             .AddSingleton<PaletteFileParser, DeluxePaintParser>()
@@ -126,7 +127,6 @@ internal static class ServiceCollectionHelpers
 
     public static IServiceCollection AddExtensionServices(this IServiceCollection collection, ExtensionLoader loader) =>
         collection.AddSingleton<IWindowProvider, WindowProvider>(x => new WindowProvider(loader, x))
-            .AddSingleton<IPaletteProvider, PaletteProvider>()
             .AddSingleton<ElementMap>(x =>
             {
                 ElementMap elementMap = new ElementMap();

+ 14 - 1
src/PixiEditor.AvaloniaUI/Models/ExtensionServices/PaletteProvider.cs

@@ -10,7 +10,7 @@ using PixiEditor.Platform;
 
 namespace PixiEditor.AvaloniaUI.Models.ExtensionServices;
 
-internal sealed class PaletteProvider : IPaletteProvider
+internal sealed class PaletteProvider
 {
     public ObservableCollection<PaletteFileParser> AvailableParsers { get; set; }
     public ObservableCollection<PaletteListDataSource> DataSources => dataSources;
@@ -21,6 +21,13 @@ internal sealed class PaletteProvider : IPaletteProvider
         dataSources = new ObservableCollection<PaletteListDataSource>();
     }
 
+    /// <summary>
+    ///     Fetches palettes from the provider.
+    /// </summary>
+    /// <param name="startIndex">Starting fetch index. Palettes before said index won't be fetched.</param>
+    /// <param name="items">Max amount of palettes to fetch.</param>
+    /// <param name="filtering">Filtering settings for fetching.</param>
+    /// <returns>List of palettes.</returns>
     public async AsyncCall<List<IPalette>> FetchPalettes(int startIndex, int items, FilteringSettings filtering)
     {
         List<IPalette> allPalettes = new();
@@ -33,6 +40,12 @@ internal sealed class PaletteProvider : IPaletteProvider
         return allPalettes;
     }
 
+    /// <summary>
+    ///     Adds a palette to the provider. This means that the palette will be saved in local storage.
+    /// </summary>
+    /// <param name="palette">Palette to save.</param>
+    /// <param name="overwrite">If true and palette with the same name exists, it will be overwritten. If false and palette with the same name exists, it will not be added.</param>
+    /// <returns>True if adding palette was successful.</returns>
     public async AsyncCall<bool> AddPalette(IPalette palette, bool overwrite = false)
     {
         LocalPalettesFetcher localPalettesFetcher = dataSources.OfType<LocalPalettesFetcher>().FirstOrDefault();

+ 1 - 1
src/PixiEditor.AvaloniaUI/ViewModels/SubViewModels/ColorsViewModel.cs

@@ -369,7 +369,7 @@ internal class ColorsViewModel : SubViewModel<ViewModelMain>, IColorsHandler
 
     public void SetupPaletteProviders(IServiceProvider services)
     {
-        PaletteProvider = (PaletteProvider)services.GetService<IPaletteProvider>();
+        PaletteProvider = services.GetService<PaletteProvider>();
         PaletteProvider.AvailableParsers =
             new ObservableCollection<PaletteFileParser>(services.GetServices<PaletteFileParser>());
         var dataSources = services.GetServices<PaletteListDataSource>();

+ 7 - 0
src/PixiEditor.Extensions.CommonApi/Async/AsyncCall.cs

@@ -152,6 +152,13 @@ public class AsyncCall<TResult> : AsyncCall
         Failed += (exception) => asyncCall.SetException(exception);
         return asyncCall;
     }
+    
+    public static AsyncCall<TResult> FromResult(TResult result)
+    {
+        AsyncCall<TResult> asyncCall = new AsyncCall<TResult>();
+        asyncCall.SetResult(result);
+        return asyncCall;
+    }
 
     public static AsyncCall<TResult> FromTask(Task<TResult> task)
     {

+ 0 - 29
src/PixiEditor.Extensions.CommonApi/Palettes/IPaletteProvider.cs

@@ -1,29 +0,0 @@
-using PixiEditor.Extensions.CommonApi.Async;
-
-namespace PixiEditor.Extensions.CommonApi.Palettes;
-
-public interface IPaletteProvider
-{
-    /// <summary>
-    ///     Fetches palettes from the provider.
-    /// </summary>
-    /// <param name="startIndex">Starting fetch index. Palettes before said index won't be fetched.</param>
-    /// <param name="items">Max amount of palettes to fetch.</param>
-    /// <param name="filtering">Filtering settings for fetching.</param>
-    /// <returns>List of palettes.</returns>
-    public AsyncCall<List<IPalette>> FetchPalettes(int startIndex, int items, FilteringSettings filtering);
-
-    /// <summary>
-    ///     Adds a palette to the provider. This means that the palette will be saved in local storage.
-    /// </summary>
-    /// <param name="palette">Palette to save.</param>
-    /// <param name="overwrite">If true and palette with the same name exists, it will be overwritten. If false and palette with the same name exists, it will not be added.</param>
-    /// <returns>True if adding palette was successful.</returns>
-    public AsyncCall<bool> AddPalette(IPalette palette, bool overwrite = false);
-
-    /// <summary>
-    ///     Registers a palette list data source. This means that the provider will use the data source to fetch palettes.
-    /// </summary>
-    /// <param name="dataSource">Data source to register.</param>
-    public void RegisterDataSource(PaletteListDataSource dataSource);
-}

+ 1 - 0
src/PixiEditor.Extensions.MSPackageBuilder/PackageBuilder.cs

@@ -12,6 +12,7 @@ public static class PackageBuilder
     {
         new ElementToInclude("extension.json", true), new ElementToInclude("AppBundle/*.wasm", true),
         new ElementToInclude("Localization/", false),
+        new ElementToInclude("Resources/", false),
     };
 
     private static readonly string[] FilesToExclude = new[] { "dotnet.wasm", };

+ 0 - 22
src/PixiEditor.Extensions.Wasm/Api/Palettes/PaletteProvider.cs

@@ -1,22 +0,0 @@
-using PixiEditor.Extensions.CommonApi.Async;
-using PixiEditor.Extensions.CommonApi.Palettes;
-
-namespace PixiEditor.Extensions.Wasm.Api.Palettes;
-
-public class PaletteProvider : IPaletteProvider
-{
-    public AsyncCall<List<IPalette>> FetchPalettes(int startIndex, int items, FilteringSettings filtering)
-    {
-        throw new NotImplementedException();
-    }
-
-    public AsyncCall<bool> AddPalette(IPalette palette, bool overwrite = false)
-    {
-        throw new NotImplementedException();
-    }
-
-    public void RegisterDataSource(PaletteListDataSource dataSource)
-    {
-        throw new NotImplementedException();
-    }
-}

+ 4 - 0
src/PixiEditor.Extensions.Wasm/PixiEditor.Extensions.Wasm.csproj

@@ -25,6 +25,10 @@
     <PackageReference Include="Microsoft.Build.Utilities.Core" Version="17.8.3"/>
   </ItemGroup>
 
+  <ItemGroup>
+    <Folder Include="Api\Palettes\" />
+  </ItemGroup>
+
   <Target Name="PackTaskDependencies" BeforeTargets="GenerateNuspec">
     <ItemGroup>
       <_PackageFiles Include="build\**" BuildAction="Content" PackagePath="build"/>

BIN
src/PixiEditor.Extensions.Wasm/build/PixiEditor.Extensions.MSPackageBuilder.dll


+ 7 - 0
src/PixiEditor.Extensions.WasmRuntime/WasmRuntime.cs

@@ -19,6 +19,13 @@ public class WasmRuntime
         wasiConfig.WithInheritedStandardError().WithInheritedStandardInput().WithInheritedStandardOutput()
             .WithInheritedArgs().WithInheritedEnvironment();
 
+        string resourcesPath = Path.Combine(Path.GetDirectoryName(path), "Resources");
+
+        if (Directory.Exists(resourcesPath))
+        {
+            wasiConfig.WithPreopenedDirectory(resourcesPath, "Resources/");
+        }
+
         using var config = new Config().WithDebugInfo(true)
             .WithCraneliftDebugVerifier(true)
             .WithReferenceTypes(true)

+ 0 - 1
src/PixiEditor.Extensions/ExtensionServices.cs

@@ -10,7 +10,6 @@ public class ExtensionServices
 {
     public IServiceProvider Services { get; private set; }
     public IWindowProvider? Windowing => Services.GetService<IWindowProvider>();
-    public IPaletteProvider? PaletteProvider => Services.GetService<IPaletteProvider>();
     public IFileSystemProvider? FileSystem => Services.GetService<IFileSystemProvider>();
     public IPreferences? Preferences => Services.GetService<IPreferences>();
 

+ 1 - 1
src/PixiEditor/Models/AppExtensions/Services/PaletteProvider.cs

@@ -7,7 +7,7 @@ using PixiEditor.Models.DataProviders;
 
 namespace PixiEditor.Models.AppExtensions.Services;
 
-internal sealed class PaletteProvider : IPaletteProvider
+internal sealed class PaletteProvider
 {
     public WpfObservableRangeCollection<PaletteFileParser> AvailableParsers { get; set; }
     public WpfObservableRangeCollection<PaletteListDataSource> DataSources => dataSources;

+ 1 - 1
src/PixiEditor/ViewModels/SubViewModels/Main/ColorsViewModel.cs

@@ -348,7 +348,7 @@ internal class ColorsViewModel : SubViewModel<ViewModelMain>
 
     public void SetupPaletteProviders(IServiceProvider services)
     {
-        PaletteProvider = (PaletteProvider)services.GetService<IPaletteProvider>();
+        PaletteProvider = (PaletteProvider)services.GetService<PaletteProvider>();
         PaletteProvider.AvailableParsers =
             new WpfObservableRangeCollection<PaletteFileParser>(services.GetServices<PaletteFileParser>());
         var dataSources = services.GetServices<PaletteListDataSource>();