From b4858d19fbad69810d211270bc5b280bf9909ea5 Mon Sep 17 00:00:00 2001
From: Moli <13026959681@163.com>
Date: 星期六, 02 五月 2026 23:17:10 +0800
Subject: [PATCH] Task Done

---
 src/Moli.Desktop.Tests/Host/DefaultContentInstallerTests.cs |   36 ++++
 src/Moli.Desktop/Host/DesktopHostBuilder.cs                 |    1 
 .gitignore                                                  |    1 
 docs/ops/local-run.md                                       |   48 ++++++
 src/Moli.Desktop/Host/DefaultContentInstaller.cs            |  203 +++++++++++++++++++++++++
 src/Moli.Desktop/Host/IDefaultContentInstaller.cs           |    6 
 samples/plugins/sample.system-info/index.html               |   72 +++++++++
 samples/plugins/sample.system-info/plugin.json              |   22 ++
 scripts/package-portable.ps1                                |   42 +++++
 src/Moli.Desktop/Moli.Desktop.csproj                        |    8 +
 src/Moli.Desktop/App.xaml.cs                                |    1 
 src/Moli.Desktop/Diagnostics/DiagnosticModels.cs            |    1 
 12 files changed, 441 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore
index 09bdb4c..e4a681d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,5 +2,6 @@
 obj/
 .vs/
 TestResults/
+artifacts/
 *.user
 *.suo
diff --git a/docs/ops/local-run.md b/docs/ops/local-run.md
new file mode 100644
index 0000000..df38a13
--- /dev/null
+++ b/docs/ops/local-run.md
@@ -0,0 +1,48 @@
+# Local Run: Moli.Desktop MVP
+
+## Prerequisites
+
+- Windows 11.
+- .NET SDK 10.
+- Microsoft Edge WebView2 Runtime.
+
+## Run From Source
+
+```powershell
+dotnet restore Moli.Desktop.slnx
+dotnet build Moli.Desktop.slnx
+dotnet run --project src/Moli.Desktop/Moli.Desktop.csproj
+```
+
+On first launch, the app copies bundled samples from `samples/plugins` into `%AppData%\DesktopEnhancer\plugins`, enables them in `plugins.json`, and creates default widget layout entries in `layout.json`.
+
+## Sample Plugins
+
+- `sample.wallpaper`: local animated wallpaper.
+- `sample.clock`: local clock widget.
+- `sample.system-info`: local system information placeholder widget.
+
+Runtime profile paths:
+
+- Config: `%AppData%\DesktopEnhancer\config`
+- Plugins: `%AppData%\DesktopEnhancer\plugins`
+- Logs: `%LocalAppData%\DesktopEnhancer\logs`
+- WebView2 data: `%LocalAppData%\DesktopEnhancer\WebView2`
+
+## Portable Zip
+
+```powershell
+.\scripts\package-portable.ps1
+```
+
+The default output is `artifacts\Moli.Desktop-win-x64.zip`. Extract the zip and run `Moli.Desktop.exe`; the package includes the sample plugins under `samples\plugins` so first-launch seeding works without the source tree.
+
+## Startup
+
+Use the tray menu item for startup control. It writes the current executable path to:
+
+```text
+HKCU\Software\Microsoft\Windows\CurrentVersion\Run\Moli.Desktop
+```
+
+The same setting is mirrored to `%AppData%\DesktopEnhancer\config\appsettings.json`.
diff --git a/samples/plugins/sample.system-info/index.html b/samples/plugins/sample.system-info/index.html
new file mode 100644
index 0000000..f009374
--- /dev/null
+++ b/samples/plugins/sample.system-info/index.html
@@ -0,0 +1,72 @@
+<!doctype html>
+<html lang="en">
+<head>
+  <meta charset="utf-8">
+  <title>Sample System Info</title>
+  <style>
+    html, body {
+      margin: 0;
+      width: 100%;
+      height: 100%;
+      background: transparent;
+      color: #edf5ef;
+      font-family: "Segoe UI", sans-serif;
+    }
+
+    body {
+      box-sizing: border-box;
+      padding: 18px 20px;
+      background: rgba(26, 44, 38, 0.82);
+      border-radius: 8px;
+    }
+
+    h1 {
+      margin: 0 0 12px;
+      font-size: 17px;
+      font-weight: 650;
+      letter-spacing: 0;
+    }
+
+    dl {
+      display: grid;
+      grid-template-columns: 86px 1fr;
+      gap: 7px 12px;
+      margin: 0;
+      font-size: 13px;
+    }
+
+    dt {
+      color: rgba(237, 245, 239, 0.68);
+    }
+
+    dd {
+      margin: 0;
+      font-variant-numeric: tabular-nums;
+      overflow: hidden;
+      text-overflow: ellipsis;
+      white-space: nowrap;
+    }
+  </style>
+</head>
+<body>
+  <h1>System Info</h1>
+  <dl>
+    <dt>Time</dt><dd id="time">--</dd>
+    <dt>Viewport</dt><dd id="viewport">--</dd>
+    <dt>Runtime</dt><dd id="runtime">Moli Desktop sample</dd>
+  </dl>
+  <script>
+    const time = document.getElementById("time");
+    const viewport = document.getElementById("viewport");
+
+    const render = () => {
+      time.textContent = new Date().toLocaleTimeString([], { hour12: false });
+      viewport.textContent = `${window.innerWidth} x ${window.innerHeight}`;
+    };
+
+    window.addEventListener("resize", render);
+    render();
+    setInterval(render, 5000);
+  </script>
+</body>
+</html>
diff --git a/samples/plugins/sample.system-info/plugin.json b/samples/plugins/sample.system-info/plugin.json
new file mode 100644
index 0000000..e6241ba
--- /dev/null
+++ b/samples/plugins/sample.system-info/plugin.json
@@ -0,0 +1,22 @@
+{
+  "id": "sample.system-info",
+  "name": "Sample System Info",
+  "version": "1.0.0",
+  "type": "widget",
+  "entry": "index.html",
+  "description": "Local system information placeholder widget for Moli.Desktop.",
+  "author": "Moli.Desktop",
+  "defaultLayout": {
+    "x": 120,
+    "y": 270,
+    "width": 360,
+    "height": 150,
+    "locked": false,
+    "clickThrough": false,
+    "opacity": 0.9,
+    "scale": 1.0
+  },
+  "config": {
+    "refreshSeconds": 5
+  }
+}
diff --git a/scripts/package-portable.ps1 b/scripts/package-portable.ps1
new file mode 100644
index 0000000..535be20
--- /dev/null
+++ b/scripts/package-portable.ps1
@@ -0,0 +1,42 @@
+param(
+    [string]$Configuration = "Release",
+    [string]$Runtime = "win-x64",
+    [string]$OutputRoot = "artifacts",
+    [switch]$SelfContained
+)
+
+$ErrorActionPreference = "Stop"
+
+$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..")
+$projectPath = Join-Path $repoRoot "src\Moli.Desktop\Moli.Desktop.csproj"
+$outputRootPath = Join-Path $repoRoot $OutputRoot
+$publishDir = Join-Path $outputRootPath "publish\Moli.Desktop"
+$zipPath = Join-Path $outputRootPath "Moli.Desktop-$Runtime.zip"
+$samplesSource = Join-Path $repoRoot "samples\plugins"
+$samplesTarget = Join-Path $publishDir "samples\plugins"
+
+New-Item -ItemType Directory -Force -Path $outputRootPath | Out-Null
+if (Test-Path -LiteralPath $publishDir) {
+    Remove-Item -LiteralPath $publishDir -Recurse -Force
+}
+if (Test-Path -LiteralPath $zipPath) {
+    Remove-Item -LiteralPath $zipPath -Force
+}
+
+$selfContainedValue = if ($SelfContained) { "true" } else { "false" }
+dotnet publish $projectPath `
+    --configuration $Configuration `
+    --runtime $Runtime `
+    --self-contained $selfContainedValue `
+    -p:PublishSingleFile=false `
+    --output $publishDir
+
+if (Test-Path -LiteralPath $samplesSource) {
+    New-Item -ItemType Directory -Force -Path $samplesTarget | Out-Null
+    Copy-Item -Path (Join-Path $samplesSource "*") -Destination $samplesTarget -Recurse -Force
+}
+
+Compress-Archive -Path (Join-Path $publishDir "*") -DestinationPath $zipPath -Force
+
+Write-Host "Portable package created:"
+Write-Host $zipPath
diff --git a/src/Moli.Desktop.Tests/Host/DefaultContentInstallerTests.cs b/src/Moli.Desktop.Tests/Host/DefaultContentInstallerTests.cs
new file mode 100644
index 0000000..a44dc21
--- /dev/null
+++ b/src/Moli.Desktop.Tests/Host/DefaultContentInstallerTests.cs
@@ -0,0 +1,36 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using Moli.Desktop.Configuration;
+using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Host;
+using Moli.Desktop.Plugins;
+
+namespace Moli.Desktop.Tests.Host;
+
+public class DefaultContentInstallerTests
+{
+    [Fact]
+    public async Task InstallAsync_CopiesSamplesAndSeedsRegistryAndLayouts()
+    {
+        var root = Path.Combine(Path.GetTempPath(), "Moli.Desktop.Tests", Guid.NewGuid().ToString("N"));
+        var paths = new DesktopPaths(Path.Combine(root, "app"), Path.Combine(root, "local"));
+        var diagnostics = new DiagnosticsService(paths, NullLogger<DiagnosticsService>.Instance);
+        var configuration = new JsonConfigurationService(paths, diagnostics);
+        var installer = new DefaultContentInstaller(paths, configuration, diagnostics);
+
+        await installer.InstallAsync();
+
+        Assert.True(File.Exists(Path.Combine(paths.PluginDirectory, "sample.wallpaper", "plugin.json")));
+        Assert.True(File.Exists(Path.Combine(paths.PluginDirectory, "sample.clock", "index.html")));
+        Assert.True(File.Exists(Path.Combine(paths.PluginDirectory, "sample.system-info", "index.html")));
+
+        var registry = await configuration.LoadPluginRegistryAsync();
+        Assert.Contains(registry.Plugins, item => item.Id == new PluginId("sample.wallpaper") && item.State == PluginState.Enabled);
+        Assert.Contains(registry.Plugins, item => item.Id == new PluginId("sample.clock") && item.State == PluginState.Enabled);
+        Assert.Contains(registry.Plugins, item => item.Id == new PluginId("sample.system-info") && item.State == PluginState.Enabled);
+
+        var layout = await configuration.LoadLayoutAsync();
+        Assert.Contains(layout.Instances, item => item.PluginId == new PluginId("sample.clock"));
+        Assert.Contains(layout.Instances, item => item.PluginId == new PluginId("sample.system-info"));
+        Assert.DoesNotContain(layout.Instances, item => item.PluginId == new PluginId("sample.wallpaper"));
+    }
+}
diff --git a/src/Moli.Desktop/App.xaml.cs b/src/Moli.Desktop/App.xaml.cs
index f2c1ef5..37f816d 100644
--- a/src/Moli.Desktop/App.xaml.cs
+++ b/src/Moli.Desktop/App.xaml.cs
@@ -20,6 +20,7 @@
 
         _host = DesktopHostBuilder.Create(e.Args).Build();
         await _host.StartAsync();
+        await _host.Services.GetRequiredService<IDefaultContentInstaller>().InstallAsync();
         await _host.Services.GetRequiredService<IDesktopRuntime>().StartAsync();
         await _host.Services.GetRequiredService<ITrayShell>().StartAsync();
 
diff --git a/src/Moli.Desktop/Diagnostics/DiagnosticModels.cs b/src/Moli.Desktop/Diagnostics/DiagnosticModels.cs
index a41e1e3..5876304 100644
--- a/src/Moli.Desktop/Diagnostics/DiagnosticModels.cs
+++ b/src/Moli.Desktop/Diagnostics/DiagnosticModels.cs
@@ -23,6 +23,7 @@
     public const string ConfigurationLoaded = "ConfigurationLoaded";
     public const string ConfigurationRecovered = "ConfigurationRecovered";
     public const string ConfigurationSaveFailed = "ConfigurationSaveFailed";
+    public const string SamplePluginsInstalled = "SamplePluginsInstalled";
     public const string PluginManifestInvalid = "PluginManifestInvalid";
     public const string PluginEntryMissing = "PluginEntryMissing";
     public const string WebViewNavigationFailed = "WebViewNavigationFailed";
diff --git a/src/Moli.Desktop/Host/DefaultContentInstaller.cs b/src/Moli.Desktop/Host/DefaultContentInstaller.cs
new file mode 100644
index 0000000..f72dd80
--- /dev/null
+++ b/src/Moli.Desktop/Host/DefaultContentInstaller.cs
@@ -0,0 +1,203 @@
+using System.IO;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Moli.Desktop.Configuration;
+using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Layout;
+using Moli.Desktop.Plugins;
+
+namespace Moli.Desktop.Host;
+
+/// <summary>Installs bundled sample plugins and initial layout entries for a fresh profile.</summary>
+public sealed class DefaultContentInstaller : IDefaultContentInstaller
+{
+    private static readonly HashSet<string> DefaultSamplePluginIds = new(StringComparer.OrdinalIgnoreCase)
+    {
+        "sample.wallpaper",
+        "sample.clock",
+        "sample.system-info"
+    };
+
+    private readonly DesktopPaths _paths;
+    private readonly IConfigurationService _configuration;
+    private readonly IDiagnosticsService _diagnostics;
+    private readonly JsonSerializerOptions _jsonOptions = new()
+    {
+        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
+        PropertyNameCaseInsensitive = true,
+        Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
+    };
+
+    public DefaultContentInstaller(
+        DesktopPaths paths,
+        IConfigurationService configuration,
+        IDiagnosticsService diagnostics)
+    {
+        _paths = paths;
+        _configuration = configuration;
+        _diagnostics = diagnostics;
+    }
+
+    public async Task InstallAsync(CancellationToken cancellationToken = default)
+    {
+        var sourceRoot = ResolveSamplePluginRoot();
+        if (sourceRoot is null)
+        {
+            _diagnostics.Record(DiagnosticSeverity.Warning, "SamplePluginsMissing", "Bundled sample plugins were not found.");
+            return;
+        }
+
+        Directory.CreateDirectory(_paths.PluginDirectory);
+        var manifests = new List<(PluginManifest Manifest, string DirectoryName)>();
+
+        foreach (var sourceDirectory in Directory.EnumerateDirectories(sourceRoot))
+        {
+            cancellationToken.ThrowIfCancellationRequested();
+            var manifestPath = Path.Combine(sourceDirectory, "plugin.json");
+            if (!File.Exists(manifestPath))
+            {
+                continue;
+            }
+
+            var manifest = await ReadManifestAsync(manifestPath, cancellationToken).ConfigureAwait(false);
+            if (manifest is null)
+            {
+                continue;
+            }
+
+            if (!DefaultSamplePluginIds.Contains(manifest.Id))
+            {
+                continue;
+            }
+
+            var targetDirectory = Path.Combine(_paths.PluginDirectory, manifest.Id);
+            CopyDirectoryMissingFiles(sourceDirectory, targetDirectory);
+            manifests.Add((manifest, manifest.Id));
+        }
+
+        if (manifests.Count == 0)
+        {
+            return;
+        }
+
+        await SeedPluginRegistryAsync(manifests.Select(item => item.Manifest), cancellationToken).ConfigureAwait(false);
+        await SeedWidgetLayoutsAsync(manifests.Select(item => item.Manifest), cancellationToken).ConfigureAwait(false);
+
+        _diagnostics.Record(
+            DiagnosticSeverity.Info,
+            DiagnosticCodes.SamplePluginsInstalled,
+            "Bundled sample plugins are available.",
+            new Dictionary<string, string> { ["count"] = manifests.Count.ToString() });
+    }
+
+    private async Task<PluginManifest?> ReadManifestAsync(string manifestPath, CancellationToken cancellationToken)
+    {
+        try
+        {
+            await using var stream = File.OpenRead(manifestPath);
+            return await JsonSerializer.DeserializeAsync<PluginManifest>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
+        }
+        catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
+        {
+            _diagnostics.Record(
+                DiagnosticSeverity.Warning,
+                DiagnosticCodes.PluginManifestInvalid,
+                "Bundled sample plugin manifest could not be read.",
+                new Dictionary<string, string> { ["path"] = manifestPath, ["exception"] = ex.GetType().Name });
+            return null;
+        }
+    }
+
+    private async Task SeedPluginRegistryAsync(IEnumerable<PluginManifest> manifests, CancellationToken cancellationToken)
+    {
+        var registry = await _configuration.LoadPluginRegistryAsync(cancellationToken).ConfigureAwait(false);
+        var changed = false;
+
+        foreach (var manifest in manifests)
+        {
+            var id = new PluginId(manifest.Id);
+            if (registry.Plugins.Any(item => item.Id == id))
+            {
+                continue;
+            }
+
+            registry.Plugins.Add(new PluginRegistryItem
+            {
+                Id = id,
+                State = PluginState.Enabled,
+                UpdatedAt = DateTimeOffset.UtcNow
+            });
+            changed = true;
+        }
+
+        if (changed)
+        {
+            await _configuration.SavePluginRegistryAsync(registry, cancellationToken).ConfigureAwait(false);
+        }
+    }
+
+    private async Task SeedWidgetLayoutsAsync(IEnumerable<PluginManifest> manifests, CancellationToken cancellationToken)
+    {
+        var layout = await _configuration.LoadLayoutAsync(cancellationToken).ConfigureAwait(false);
+        var changed = false;
+
+        foreach (var manifest in manifests.Where(manifest => manifest.Type == PluginType.Widget))
+        {
+            var pluginId = new PluginId(manifest.Id);
+            if (layout.Instances.Any(instance => instance.PluginId == pluginId))
+            {
+                continue;
+            }
+
+            layout.Instances.Add(new WidgetLayout
+            {
+                InstanceId = new WidgetInstanceId($"{manifest.Id}.default"),
+                PluginId = pluginId,
+                MonitorId = new MonitorId("primary"),
+                Bounds = new RectD(
+                    manifest.DefaultLayout.X,
+                    manifest.DefaultLayout.Y,
+                    manifest.DefaultLayout.Width,
+                    manifest.DefaultLayout.Height),
+                IsLocked = manifest.DefaultLayout.Locked,
+                ClickThrough = manifest.DefaultLayout.ClickThrough,
+                Opacity = manifest.DefaultLayout.Opacity,
+                Scale = manifest.DefaultLayout.Scale
+            });
+            changed = true;
+        }
+
+        if (changed)
+        {
+            await _configuration.SaveLayoutAsync(layout, cancellationToken).ConfigureAwait(false);
+        }
+    }
+
+    private static void CopyDirectoryMissingFiles(string sourceDirectory, string targetDirectory)
+    {
+        Directory.CreateDirectory(targetDirectory);
+
+        foreach (var sourceFile in Directory.EnumerateFiles(sourceDirectory, "*", SearchOption.AllDirectories))
+        {
+            var relativePath = Path.GetRelativePath(sourceDirectory, sourceFile);
+            var targetFile = Path.Combine(targetDirectory, relativePath);
+            Directory.CreateDirectory(Path.GetDirectoryName(targetFile)!);
+            if (!File.Exists(targetFile))
+            {
+                File.Copy(sourceFile, targetFile);
+            }
+        }
+    }
+
+    private static string? ResolveSamplePluginRoot()
+    {
+        var candidates = new[]
+        {
+            Path.Combine(AppContext.BaseDirectory, "samples", "plugins"),
+            Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "samples", "plugins")),
+            Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", "samples", "plugins"))
+        };
+
+        return candidates.FirstOrDefault(Directory.Exists);
+    }
+}
diff --git a/src/Moli.Desktop/Host/DesktopHostBuilder.cs b/src/Moli.Desktop/Host/DesktopHostBuilder.cs
index 40733f6..ecadec5 100644
--- a/src/Moli.Desktop/Host/DesktopHostBuilder.cs
+++ b/src/Moli.Desktop/Host/DesktopHostBuilder.cs
@@ -30,6 +30,7 @@
             {
                 services.AddSingleton<DesktopPaths>();
                 services.AddSingleton<IDiagnosticsService, DiagnosticsService>();
+                services.AddSingleton<IDefaultContentInstaller, DefaultContentInstaller>();
                 services.AddSingleton<IRuntimeEventBus, RuntimeEventBus>();
                 services.AddSingleton<IRuntimeSurfaceController, RuntimeSurfaceController>();
                 services.AddSingleton<IDesktopRuntime, DesktopRuntimeCoordinator>();
diff --git a/src/Moli.Desktop/Host/IDefaultContentInstaller.cs b/src/Moli.Desktop/Host/IDefaultContentInstaller.cs
new file mode 100644
index 0000000..387c9e4
--- /dev/null
+++ b/src/Moli.Desktop/Host/IDefaultContentInstaller.cs
@@ -0,0 +1,6 @@
+namespace Moli.Desktop.Host;
+
+public interface IDefaultContentInstaller
+{
+    Task InstallAsync(CancellationToken cancellationToken = default);
+}
diff --git a/src/Moli.Desktop/Moli.Desktop.csproj b/src/Moli.Desktop/Moli.Desktop.csproj
index 44e155b..9d0ee8a 100644
--- a/src/Moli.Desktop/Moli.Desktop.csproj
+++ b/src/Moli.Desktop/Moli.Desktop.csproj
@@ -14,4 +14,12 @@
     <PackageReference Include="Microsoft.Web.WebView2" Version="1.0.3912.50" />
   </ItemGroup>
 
+  <ItemGroup>
+    <Content Include="..\..\samples\plugins\**\*">
+      <Link>samples\plugins\%(RecursiveDir)%(Filename)%(Extension)</Link>
+      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
+    </Content>
+  </ItemGroup>
+
 </Project>

--
Gitblit v1.9.1