Compare commits

...

9 Commits

Author SHA1 Message Date
lincube
4679ee006f 0.5.20
我认为很稳定了,后面就要开始弄插件不稳定了
2026-03-12 12:25:22 +08:00
lincube
6952cb2c3e 0.5.19.1 2026-03-12 10:07:23 +08:00
lincube
d3356f3319 0.5.19
插件系统V2
2026-03-12 09:22:03 +08:00
lincube
57c5e41a5c 0.5.18 2026-03-12 00:34:49 +08:00
lincube
ce2b218dfa 0.5.17 2026-03-12 00:18:04 +08:00
lincube
efdfa68dab 0.5.16 2026-03-11 17:43:31 +08:00
lincube
87110f1d69 0.5.15
市场插件安装机制修复,然后修复了一大堆东西
2026-03-11 15:14:08 +08:00
lincube
e7a03404ce 0.5.14
二次启动拦截,统一了生命进程API
2026-03-11 09:40:36 +08:00
lincube
2781d7e0d9 0.5.13
插件市场安装优化
2026-03-11 06:38:11 +08:00
83 changed files with 4061 additions and 624 deletions

17
.github/FIX_REPORT.md vendored
View File

@@ -8,14 +8,14 @@ MSBUILD : error MSB1003: Specify a project or solution file.
The current working directory does not contain a project or solution file.
```
**原因**: 项目中缺少 `LanMountainDesktop.sln` 解决方案文件,但工作流尝试执行 `dotnet restore` 而没有指定项目。
**原因**: 项目中缺少 `LanMountainDesktop.slnx` 解决方案文件,但工作流尝试执行 `dotnet restore` 而没有指定项目。
---
## 🔧 已采取的修复
### 1. 创建解决方案文件
✅ 创建了标准的 `LanMountainDesktop.sln` 文件,包含:
### 1. 创建 `.slnx` 解决方案文件
✅ 创建了标准的 `LanMountainDesktop.slnx` 文件,包含:
- `LanMountainDesktop/LanMountainDesktop.csproj`
### 2. 验证本地构建工作
@@ -35,10 +35,10 @@ The current working directory does not contain a project or solution file.
## 📋 解决方案文件内容
包含主桌面项目的标准 Visual Studio 解决方案格式:
包含主桌面项目的标准 XML 解决方案格式:
```
LanMountainDesktop.sln
LanMountainDesktop.slnx
└── LanMountainDesktop (Desktop UI - Avalonia)
```
@@ -50,10 +50,11 @@ LanMountainDesktop.sln
```bash
# 1. 添加新创建的解决方案文件
git add LanMountainDesktop.sln
git add LanMountainDesktop.slnx
git add global.json
# 2. 提交
git commit -m "Add solution file for desktop project"
git commit -m "Migrate desktop solution to .slnx"
# 3. 推送
git push origin main
@@ -92,7 +93,7 @@ git push origin v1.0.1
| `.github/workflows/code-quality.yml` | 代码质量检查 | ✅ 可用 |
| `.github/workflows/release.yml` | 多平台发布 | ✅ 可用 |
| `.github/workflows/issue-management.yml` | Issue自动管理 | ✅ 可用 |
| `LanMountainDesktop.sln` | 解决方案文件 | ✅ 已修复 |
| `LanMountainDesktop.slnx` | 解决方案文件 | ✅ 已修复 |
---

3
.github/README.md vendored
View File

@@ -36,9 +36,10 @@
- 扩展契约与字段说明见组件系统文档:`LanMountainDesktop/ComponentSystem/README.md`
## 当前状态
- 项目包含桌面端与推荐后端两个子项目,并在同一 solution 中维护。
- 项目包含桌面端与推荐后端两个子项目,并在同一 `LanMountainDesktop.slnx` 工作区中维护。
- 配置默认写入本地:`%LOCALAPPDATA%\LanMountainDesktop\settings.json`
- 当前体验以 Windows 为主要目标平台。
- SDK 版本由仓库根目录 `global.json` 锁定。
## 运行说明
运行与环境准备已拆分到独立文档:[`run.md`](./run.md)

View File

@@ -9,7 +9,7 @@ on:
env:
DOTNET_VERSION: '10.0.x'
Solution_Name: LanMountainDesktop.sln
Solution_Name: LanMountainDesktop.slnx
jobs:
build-windows:
@@ -71,10 +71,10 @@ jobs:
dotnet-version: ${{ env.DOTNET_VERSION }}
- name: Restore
run: dotnet restore
run: dotnet restore ${{ env.Solution_Name }}
- name: Build
run: dotnet build --no-restore -c Release -v minimal
run: dotnet build ${{ env.Solution_Name }} --no-restore -c Release -v minimal
- name: Upload artifacts
uses: actions/upload-artifact@v4
@@ -101,10 +101,10 @@ jobs:
dotnet-version: ${{ env.DOTNET_VERSION }}
- name: Restore
run: dotnet restore
run: dotnet restore ${{ env.Solution_Name }}
- name: Build
run: dotnet build --no-restore -c Release -v minimal
run: dotnet build ${{ env.Solution_Name }} --no-restore -c Release -v minimal
- name: Upload artifacts
uses: actions/upload-artifact@v4

View File

@@ -8,7 +8,7 @@ on:
env:
DOTNET_VERSION: '10.0.x'
Solution_Name: LanMountainDesktop.sln
Solution_Name: LanMountainDesktop.slnx
jobs:
analyze:

View File

@@ -18,7 +18,7 @@ on:
env:
DOTNET_VERSION: '10.0.x'
Solution_Name: LanMountainDesktop.sln
Solution_Name: LanMountainDesktop.slnx
jobs:
prepare:

20
.gitignore vendored
View File

@@ -492,3 +492,23 @@ nul
/_build_verify_plugin_services
/LanMountainDesktop.PluginSdk/_build_verify_*/
/_build_obj
# LanMountainDesktop local workspace files
/.arts/
/.knox/
/.lingma/
/.tmp/
/publish-test/
/validator-restore.log
/temp_old_main.axaml
/temp_old_main_utf8.axaml
# LanMountainDesktop local packaging outputs
/build-installer/
/build-deb/
/dmg-temp/
/release-files/
/LanMountainDesktop.app/
/*.deb
/*.dmg
/*.AppImage

View File

@@ -67,6 +67,11 @@
"capability.message_bus.detail": "This sample plugin uses IPluginMessageBus to push clock ticks and state change notifications into plugin UI surfaces.",
"capability.widget_context.title": "PluginDesktopComponentContext",
"capability.widget_context.detail": "Widgets can read ComponentId, PlacementId, CellSize, and call GetService<T>() against the same plugin service container.",
"widget.close_desktop.display_name": "Close Desktop",
"widget.close_desktop.text": "Close Desktop",
"widget.close_desktop.hint": "Exit LanMountainDesktop on click",
"widget.close_desktop.unavailable": "Host lifecycle API is unavailable",
"widget.close_desktop.failed": "Host rejected the exit request",
"widget.subtitle.preview": "Preview surface | placed: {0}",
"widget.subtitle.placement": "Placement {0} | placed: {1}",
"common.dev": "dev",

View File

@@ -16,6 +16,7 @@ public sealed class SamplePlugin : PluginBase, IDisposable
var hostName = GetHostProperty(context, PluginHostPropertyKeys.HostApplicationName, "UnknownHost");
var hostVersion = GetHostProperty(context, PluginHostPropertyKeys.HostVersion, "UnknownVersion");
var sdkApiVersion = GetHostProperty(context, PluginHostPropertyKeys.PluginSdkApiVersion, "UnknownApiVersion");
var hostApplicationLifecycle = context.GetService<IHostApplicationLifecycle>();
var messageBus = context.GetService<IPluginMessageBus>()
?? throw new InvalidOperationException("Plugin message bus is not available.");
@@ -74,6 +75,19 @@ public sealed class SamplePlugin : PluginBase, IDisposable
allowStatusBarPlacement: false,
resizeMode: PluginDesktopComponentResizeMode.Proportional,
cornerRadiusResolver: cellSize => Math.Clamp(cellSize * 0.34, 18, 34)));
context.RegisterDesktopComponent(new PluginDesktopComponentRegistration(
"LanMountainDesktop.SamplePlugin.CloseDesktop",
localizer.GetString("widget.close_desktop.display_name", "关闭桌面"),
widgetContext => new SamplePluginCloseDesktopWidget(widgetContext),
iconKey: "DismissCircle",
category: localizer.GetString("widget.category", "鎻掍欢"),
minWidthCells: 2,
minHeightCells: 1,
allowDesktopPlacement: true,
allowStatusBarPlacement: false,
resizeMode: PluginDesktopComponentResizeMode.Free,
cornerRadiusResolver: cellSize => Math.Clamp(cellSize * 0.28, 14, 22)));
}
public void Dispose()

View File

@@ -0,0 +1,166 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using LanMountainDesktop.PluginSdk;
namespace LanMountainDesktop.SamplePlugin;
internal sealed class SamplePluginCloseDesktopWidget : Border
{
private readonly PluginLocalizer _localizer;
private readonly IHostApplicationLifecycle? _hostApplicationLifecycle;
private readonly TextBlock _titleTextBlock;
private readonly TextBlock _statusTextBlock;
public SamplePluginCloseDesktopWidget(PluginDesktopComponentContext context)
{
_localizer = PluginLocalizer.Create(context);
_hostApplicationLifecycle = context.GetService<IHostApplicationLifecycle>();
_titleTextBlock = new TextBlock
{
Text = T("widget.close_desktop.text", "关闭桌面"),
Foreground = Brushes.White,
FontWeight = FontWeight.SemiBold,
VerticalAlignment = VerticalAlignment.Center
};
_statusTextBlock = new TextBlock
{
Text = _hostApplicationLifecycle is null
? T("widget.close_desktop.unavailable", "宿主未提供退出接口")
: T("widget.close_desktop.hint", "点击后退出阑山桌面"),
Foreground = new SolidColorBrush(Color.Parse("#FFD4E7F6")),
VerticalAlignment = VerticalAlignment.Center
};
var contentGrid = new Grid
{
ColumnDefinitions = new ColumnDefinitions("Auto,*"),
ColumnSpacing = 14,
VerticalAlignment = VerticalAlignment.Center,
Children =
{
CreateIconShell(),
new StackPanel
{
Spacing = 2,
VerticalAlignment = VerticalAlignment.Center,
Children =
{
_titleTextBlock,
_statusTextBlock
}
}
}
};
Grid.SetColumn(contentGrid.Children[1], 1);
var actionButton = new Button
{
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Stretch,
VerticalContentAlignment = VerticalAlignment.Stretch,
Background = Brushes.Transparent,
BorderThickness = new Thickness(0),
Padding = new Thickness(0),
IsEnabled = _hostApplicationLifecycle is not null,
Content = contentGrid
};
actionButton.Click += OnButtonClick;
Background = new LinearGradientBrush
{
StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
EndPoint = new RelativePoint(1, 1, RelativeUnit.Relative),
GradientStops =
[
new GradientStop(Color.Parse("#FF0B1220"), 0),
new GradientStop(Color.Parse("#FF172554"), 0.55),
new GradientStop(Color.Parse("#FF7F1D1D"), 1)
]
};
BorderBrush = new SolidColorBrush(Color.Parse("#66FB7185"));
BorderThickness = new Thickness(1);
CornerRadius = new CornerRadius(18);
Padding = new Thickness(14, 10);
Child = actionButton;
SizeChanged += OnSizeChanged;
ApplyScale();
}
private Border CreateIconShell()
{
return new Border
{
Width = 36,
Height = 36,
CornerRadius = new CornerRadius(999),
Background = new SolidColorBrush(Color.Parse("#33F87171")),
BorderBrush = new SolidColorBrush(Color.Parse("#88FCA5A5")),
BorderThickness = new Thickness(1),
VerticalAlignment = VerticalAlignment.Center,
Child = new TextBlock
{
Text = "⏻",
FontSize = 18,
Foreground = Brushes.White,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
TextAlignment = TextAlignment.Center
}
};
}
private void OnButtonClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
if (_hostApplicationLifecycle?.TryExit(new HostApplicationLifecycleRequest(
Source: "SamplePlugin.CloseDesktopWidget",
Reason: "User invoked the sample plugin close-desktop widget.")) == true)
{
return;
}
_statusTextBlock.Text = T("widget.close_desktop.failed", "宿主未接受退出请求");
}
private void OnSizeChanged(object? sender, SizeChangedEventArgs e)
{
ApplyScale();
}
private void ApplyScale()
{
var basis = Bounds.Height > 1 ? Bounds.Height : 72;
Padding = new Thickness(Math.Clamp(basis * 0.18, 12, 18), Math.Clamp(basis * 0.14, 8, 14));
CornerRadius = new CornerRadius(Math.Clamp(basis * 0.32, 16, 24));
if (Child is not Button actionButton || actionButton.Content is not Grid contentGrid)
{
return;
}
if (contentGrid.Children[0] is Border iconShell)
{
var iconSize = Math.Clamp(basis * 0.58, 28, 40);
iconShell.Width = iconSize;
iconShell.Height = iconSize;
if (iconShell.Child is TextBlock iconText)
{
iconText.FontSize = Math.Clamp(iconSize * 0.5, 14, 20);
}
}
_titleTextBlock.FontSize = Math.Clamp(basis * 0.28, 14, 20);
_statusTextBlock.FontSize = Math.Clamp(basis * 0.18, 10, 13);
}
private string T(string key, string fallback)
{
return _localizer.GetString(key, fallback);
}
}

View File

@@ -0,0 +1,12 @@
namespace LanMountainDesktop.PluginSdk;
public sealed record HostApplicationLifecycleRequest(
string? Source = null,
string? Reason = null);
public interface IHostApplicationLifecycle
{
bool TryExit(HostApplicationLifecycleRequest? request = null);
bool TryRestart(HostApplicationLifecycleRequest? request = null);
}

View File

@@ -1,6 +1,9 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace LanMountainDesktop.PluginSdk;
public interface IPlugin
{
void Initialize(IPluginContext context);
void Initialize(HostBuilderContext context, IServiceCollection services);
}

View File

@@ -1,27 +1,6 @@
using System.Collections.Generic;
namespace LanMountainDesktop.PluginSdk;
public interface IPluginContext
[Obsolete("Plugin API 2.0.0 uses IPluginRuntimeContext and IServiceCollection-based initialization.")]
public interface IPluginContext : IPluginRuntimeContext
{
PluginManifest Manifest { get; }
string PluginDirectory { get; }
string DataDirectory { get; }
IServiceProvider Services { get; }
IReadOnlyDictionary<string, object?> Properties { get; }
T? GetService<T>();
bool TryGetProperty<T>(string key, out T? value);
void RegisterService<TService>(TService service)
where TService : class;
void RegisterSettingsPage(PluginSettingsPageRegistration registration);
void RegisterDesktopComponent(PluginDesktopComponentRegistration registration);
}

View File

@@ -0,0 +1,13 @@
namespace LanMountainDesktop.PluginSdk;
public interface IPluginExportRegistry
{
IReadOnlyList<PluginServiceExportDescriptor> GetExports();
IReadOnlyList<PluginServiceExportDescriptor> GetExports(Type contractType);
PluginServiceExportDescriptor? GetExport(Type contractType, string providerPluginId);
TContract? GetExport<TContract>(string providerPluginId)
where TContract : class;
}

View File

@@ -0,0 +1,18 @@
namespace LanMountainDesktop.PluginSdk;
public interface IPluginRuntimeContext
{
PluginManifest Manifest { get; }
string PluginDirectory { get; }
string DataDirectory { get; }
IServiceProvider Services { get; }
IReadOnlyDictionary<string, object?> Properties { get; }
T? GetService<T>();
bool TryGetProperty<T>(string key, out T? value);
}

View File

@@ -1,15 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>1.0.0</Version>
<Version>2.0.0</Version>
</PropertyGroup>
<ItemGroup>
<Compile Remove="_build_verify_*\**\*.cs" />
<PackageReference Include="Avalonia" Version="11.3.12" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.0" />
</ItemGroup>
</Project>

View File

@@ -1,8 +1,11 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace LanMountainDesktop.PluginSdk;
public abstract class PluginBase : IPlugin
{
public virtual void Initialize(IPluginContext context)
public virtual void Initialize(HostBuilderContext context, IServiceCollection services)
{
}
}

View File

@@ -7,7 +7,7 @@ public sealed class PluginDesktopComponentRegistration
public PluginDesktopComponentRegistration(
string componentId,
string displayName,
Func<PluginDesktopComponentContext, Control> controlFactory,
Func<IServiceProvider, PluginDesktopComponentContext, Control> controlFactory,
string iconKey = "PuzzlePiece",
string category = "Plugins",
int minWidthCells = 2,
@@ -40,13 +40,42 @@ public sealed class PluginDesktopComponentRegistration
CornerRadiusResolver = cornerRadiusResolver;
}
public PluginDesktopComponentRegistration(
string componentId,
string displayName,
Func<PluginDesktopComponentContext, Control> controlFactory,
string iconKey = "PuzzlePiece",
string category = "Plugins",
int minWidthCells = 2,
int minHeightCells = 2,
bool allowDesktopPlacement = true,
bool allowStatusBarPlacement = false,
PluginDesktopComponentResizeMode resizeMode = PluginDesktopComponentResizeMode.Proportional,
string? displayNameLocalizationKey = null,
Func<double, double>? cornerRadiusResolver = null)
: this(
componentId,
displayName,
(_, context) => controlFactory(context),
iconKey,
category,
minWidthCells,
minHeightCells,
allowDesktopPlacement,
allowStatusBarPlacement,
resizeMode,
displayNameLocalizationKey,
cornerRadiusResolver)
{
}
public string ComponentId { get; }
public string DisplayName { get; }
public string? DisplayNameLocalizationKey { get; }
public Func<PluginDesktopComponentContext, Control> ControlFactory { get; }
public Func<IServiceProvider, PluginDesktopComponentContext, Control> ControlFactory { get; }
public string IconKey { get; }

View File

@@ -26,7 +26,7 @@ public sealed class PluginLocalizer
public string LanguageCode { get; }
public static PluginLocalizer Create(IPluginContext context)
public static PluginLocalizer Create(IPluginRuntimeContext context)
{
ArgumentNullException.ThrowIfNull(context);
return new PluginLocalizer(context.PluginDirectory, ResolveLanguageCode(context.Properties));

View File

@@ -9,7 +9,8 @@ public sealed record PluginManifest(
string? Description = null,
string? Author = null,
string? Version = null,
string? ApiVersion = null)
string? ApiVersion = null,
IReadOnlyList<PluginSharedContractReference>? SharedContracts = null)
{
private static readonly JsonSerializerOptions SerializerOptions = new()
{
@@ -57,6 +58,7 @@ public sealed record PluginManifest(
private PluginManifest NormalizeAndValidate(string manifestPath)
{
var normalizedSharedContracts = NormalizeSharedContracts(manifestPath, SharedContracts);
var normalized = this with
{
Id = RequireValue(Id, nameof(Id), manifestPath),
@@ -65,7 +67,8 @@ public sealed record PluginManifest(
Description = NormalizeOptionalValue(Description),
Author = NormalizeOptionalValue(Author),
Version = NormalizeOptionalValue(Version),
ApiVersion = NormalizeOptionalValue(ApiVersion) ?? PluginSdkInfo.ApiVersion
ApiVersion = NormalizeOptionalValue(ApiVersion) ?? PluginSdkInfo.ApiVersion,
SharedContracts = normalizedSharedContracts
};
if (!System.Version.TryParse(normalized.ApiVersion, out var requestedVersion))
@@ -82,7 +85,41 @@ public sealed record PluginManifest(
if (requestedVersion.Major != currentVersion.Major)
{
throw new InvalidOperationException(
$"Plugin '{normalized.Id}' targets API version '{normalized.ApiVersion}', but the host provides '{PluginSdkInfo.ApiVersion}'.");
$"Plugin '{normalized.Id}' targets API version '{normalized.ApiVersion}', but the host provides '{PluginSdkInfo.ApiVersion}'. Upgrade the plugin to API {PluginSdkInfo.ApiVersion}.");
}
return normalized;
}
private static IReadOnlyList<PluginSharedContractReference> NormalizeSharedContracts(
string manifestPath,
IReadOnlyList<PluginSharedContractReference>? sharedContracts)
{
if (sharedContracts is null || sharedContracts.Count == 0)
{
return Array.Empty<PluginSharedContractReference>();
}
var normalized = new List<PluginSharedContractReference>(sharedContracts.Count);
var seenIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var contract in sharedContracts)
{
if (contract is null)
{
throw new InvalidOperationException(
$"Plugin manifest '{manifestPath}' contains a null shared contract declaration.");
}
var normalizedContract = contract.NormalizeAndValidate(manifestPath);
var contractKey = $"{normalizedContract.Id}@{normalizedContract.Version}";
if (!seenIds.Add(contractKey))
{
throw new InvalidOperationException(
$"Plugin manifest '{manifestPath}' declares duplicate shared contract '{contractKey}'.");
}
normalized.Add(normalizedContract);
}
return normalized;

View File

@@ -2,7 +2,7 @@ namespace LanMountainDesktop.PluginSdk;
public static class PluginSdkInfo
{
public const string ApiVersion = "1.0.0";
public const string ApiVersion = "2.0.0";
public const string ManifestFileName = "plugin.json";
public const string PackageFileExtension = ".laapp";
public const string DataDirectoryName = "Data";

View File

@@ -0,0 +1,95 @@
using Avalonia.Controls;
using Microsoft.Extensions.DependencyInjection;
namespace LanMountainDesktop.PluginSdk;
public static class PluginServiceCollectionExtensions
{
public static IServiceCollection AddPluginSettingsPage<TControl>(
this IServiceCollection services,
string id,
string title,
int sortOrder = 0)
where TControl : Control
{
ArgumentNullException.ThrowIfNull(services);
services.AddSingleton(new PluginSettingsPageRegistration(
id,
title,
provider => ActivatorUtilities.CreateInstance<TControl>(provider),
sortOrder));
return services;
}
public static IServiceCollection AddPluginDesktopComponent<TControl>(
this IServiceCollection services,
string componentId,
string displayName,
string iconKey = "PuzzlePiece",
string category = "Plugins",
int minWidthCells = 2,
int minHeightCells = 2,
bool allowDesktopPlacement = true,
bool allowStatusBarPlacement = false,
PluginDesktopComponentResizeMode resizeMode = PluginDesktopComponentResizeMode.Proportional,
string? displayNameLocalizationKey = null,
Func<double, double>? cornerRadiusResolver = null)
where TControl : Control
{
ArgumentNullException.ThrowIfNull(services);
services.AddSingleton(new PluginDesktopComponentRegistration(
componentId,
displayName,
(provider, context) => ActivatorUtilities.CreateInstance<TControl>(provider, context),
iconKey,
category,
minWidthCells,
minHeightCells,
allowDesktopPlacement,
allowStatusBarPlacement,
resizeMode,
displayNameLocalizationKey,
cornerRadiusResolver));
return services;
}
public static IServiceCollection AddPluginExport<TContract, TImplementation>(this IServiceCollection services)
where TContract : class
where TImplementation : class, TContract
{
ArgumentNullException.ThrowIfNull(services);
EnsureSingletonRegistration<TContract, TImplementation>(services);
if (!services.Any(descriptor =>
descriptor.ServiceType == typeof(PluginServiceExportRegistration) &&
descriptor.ImplementationInstance is PluginServiceExportRegistration existing &&
existing.ContractType == typeof(TContract) &&
existing.ImplementationType == typeof(TImplementation)))
{
services.AddSingleton(new PluginServiceExportRegistration(typeof(TContract), typeof(TImplementation)));
}
return services;
}
private static void EnsureSingletonRegistration<TContract, TImplementation>(IServiceCollection services)
where TContract : class
where TImplementation : class, TContract
{
var contractDescriptor = services.LastOrDefault(descriptor => descriptor.ServiceType == typeof(TContract));
if (contractDescriptor is null)
{
services.AddSingleton<TContract, TImplementation>();
return;
}
if (contractDescriptor.Lifetime != ServiceLifetime.Singleton)
{
throw new InvalidOperationException(
$"Exported contract '{typeof(TContract).FullName}' must be registered as Singleton.");
}
}
}

View File

@@ -0,0 +1,6 @@
namespace LanMountainDesktop.PluginSdk;
public sealed record PluginServiceExportDescriptor(
string ProviderPluginId,
Type ContractType,
object ServiceInstance);

View File

@@ -0,0 +1,17 @@
namespace LanMountainDesktop.PluginSdk;
public sealed class PluginServiceExportRegistration
{
public PluginServiceExportRegistration(Type contractType, Type implementationType)
{
ArgumentNullException.ThrowIfNull(contractType);
ArgumentNullException.ThrowIfNull(implementationType);
ContractType = contractType;
ImplementationType = implementationType;
}
public Type ContractType { get; }
public Type ImplementationType { get; }
}

View File

@@ -7,7 +7,7 @@ public sealed class PluginSettingsPageRegistration
public PluginSettingsPageRegistration(
string id,
string title,
Func<Control> contentFactory,
Func<IServiceProvider, Control> contentFactory,
int sortOrder = 0)
{
ArgumentException.ThrowIfNullOrWhiteSpace(id);
@@ -20,11 +20,20 @@ public sealed class PluginSettingsPageRegistration
SortOrder = sortOrder;
}
public PluginSettingsPageRegistration(
string id,
string title,
Func<Control> contentFactory,
int sortOrder = 0)
: this(id, title, _ => contentFactory(), sortOrder)
{
}
public string Id { get; }
public string Title { get; }
public int SortOrder { get; }
public Func<Control> ContentFactory { get; }
public Func<IServiceProvider, Control> ContentFactory { get; }
}

View File

@@ -0,0 +1,47 @@
using System.Text.Json.Serialization;
namespace LanMountainDesktop.PluginSdk;
public sealed record PluginSharedContractReference(
string Id,
string Version,
string AssemblyName)
{
[JsonIgnore]
public string NormalizedId => Id.Trim();
[JsonIgnore]
public string NormalizedVersion => Version.Trim();
[JsonIgnore]
public string NormalizedAssemblyName => AssemblyName.Trim();
internal PluginSharedContractReference NormalizeAndValidate(string manifestPath)
{
var normalized = this with
{
Id = RequireValue(Id, nameof(Id), manifestPath),
Version = RequireValue(Version, nameof(Version), manifestPath),
AssemblyName = RequireValue(AssemblyName, nameof(AssemblyName), manifestPath)
};
if (!System.Version.TryParse(normalized.Version, out _))
{
throw new InvalidOperationException(
$"Plugin manifest '{manifestPath}' declares invalid shared contract version '{normalized.Version}' for '{normalized.Id}'.");
}
return normalized;
}
private static string RequireValue(string? value, string propertyName, string manifestPath)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new InvalidOperationException(
$"Plugin manifest '{manifestPath}' is missing required shared contract property '{propertyName}'.");
}
return value.Trim();
}
}

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk" TreatAsLocalProperty="Version;PackageVersion;InformationalVersion;AssemblyVersion;FileVersion">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.0.0</Version>
<PackageVersion>$(Version)</PackageVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\LanMountainDesktop.PluginSdk\LanMountainDesktop.PluginSdk.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,242 @@
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using LanMountainDesktop.PluginSdk;
internal static class Program
{
private static readonly TimeSpan[] RetryDelays =
[
TimeSpan.FromMilliseconds(120),
TimeSpan.FromMilliseconds(250),
TimeSpan.FromMilliseconds(500)
];
private static async Task<int> Main(string[] args)
{
var result = new HelperResult();
string? resultPath = null;
try
{
var parsedArgs = ParseArgs(args);
if (!parsedArgs.TryGetValue("source", out var sourcePath) ||
!parsedArgs.TryGetValue("plugins-dir", out var pluginsDirectory) ||
!parsedArgs.TryGetValue("result", out resultPath) ||
string.IsNullOrWhiteSpace(sourcePath) ||
string.IsNullOrWhiteSpace(pluginsDirectory) ||
string.IsNullOrWhiteSpace(resultPath))
{
throw new InvalidOperationException("Required arguments: --source <path> --plugins-dir <path> --result <path>.");
}
var fullSourcePath = Path.GetFullPath(sourcePath);
var fullPluginsDirectory = Path.GetFullPath(pluginsDirectory);
resultPath = Path.GetFullPath(resultPath);
if (!File.Exists(fullSourcePath))
{
throw new FileNotFoundException($"Plugin package '{fullSourcePath}' was not found.", fullSourcePath);
}
var manifest = ReadManifestFromPackage(fullSourcePath);
Directory.CreateDirectory(fullPluginsDirectory);
var destinationPath = Path.Combine(fullPluginsDirectory, BuildInstalledPackageFileName(manifest.Id));
var stagingPath = destinationPath + ".incoming";
DeleteFileWithRetry(stagingPath);
CopyWithRetry(fullSourcePath, stagingPath, overwrite: true);
RemoveExistingPluginPackages(fullPluginsDirectory, manifest.Id, destinationPath, stagingPath);
MoveWithOverwriteRetry(stagingPath, destinationPath);
result = new HelperResult
{
Success = true,
InstalledPackagePath = destinationPath,
ManifestId = manifest.Id,
ManifestName = manifest.Name
};
}
catch (Exception ex)
{
result = new HelperResult
{
Success = false,
ErrorMessage = ex.Message
};
}
if (!string.IsNullOrWhiteSpace(resultPath))
{
var resultDirectory = Path.GetDirectoryName(resultPath);
if (!string.IsNullOrWhiteSpace(resultDirectory))
{
Directory.CreateDirectory(resultDirectory);
}
await File.WriteAllTextAsync(
resultPath,
JsonSerializer.Serialize(result, new JsonSerializerOptions
{
WriteIndented = true
}),
Encoding.UTF8);
}
return result.Success ? 0 : 1;
}
private static Dictionary<string, string> ParseArgs(string[] args)
{
var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < args.Length; i++)
{
var current = args[i];
if (!current.StartsWith("--", StringComparison.Ordinal))
{
continue;
}
var key = current[2..];
if (string.IsNullOrWhiteSpace(key) || i + 1 >= args.Length)
{
continue;
}
values[key] = args[++i];
}
return values;
}
private static PluginManifest ReadManifestFromPackage(string packagePath)
{
using var archive = ZipFile.OpenRead(packagePath);
var entries = archive.Entries
.Where(entry => string.Equals(entry.Name, PluginSdkInfo.ManifestFileName, StringComparison.OrdinalIgnoreCase))
.ToArray();
if (entries.Length == 0)
{
throw new InvalidOperationException(
$"Plugin package '{packagePath}' does not contain '{PluginSdkInfo.ManifestFileName}'.");
}
if (entries.Length > 1)
{
throw new InvalidOperationException(
$"Plugin package '{packagePath}' contains multiple '{PluginSdkInfo.ManifestFileName}' files.");
}
using var stream = entries[0].Open();
return PluginManifest.Load(stream, $"{packagePath}!/{entries[0].FullName}");
}
private static void RemoveExistingPluginPackages(string pluginsDirectory, string pluginId, string destinationPath, string stagingPath)
{
var runtimeRootDirectory = EnsureTrailingSeparator(Path.Combine(Path.GetFullPath(pluginsDirectory), PluginSdkInfo.RuntimeDirectoryName));
foreach (var existingPackagePath in Directory
.EnumerateFiles(pluginsDirectory, "*" + PluginSdkInfo.PackageFileExtension, SearchOption.AllDirectories)
.Select(Path.GetFullPath)
.Where(path => !path.StartsWith(runtimeRootDirectory, StringComparison.OrdinalIgnoreCase)))
{
try
{
if (string.Equals(existingPackagePath, Path.GetFullPath(destinationPath), StringComparison.OrdinalIgnoreCase) ||
string.Equals(existingPackagePath, Path.GetFullPath(stagingPath), StringComparison.OrdinalIgnoreCase))
{
continue;
}
var existingManifest = ReadManifestFromPackage(existingPackagePath);
if (!string.Equals(existingManifest.Id, pluginId, StringComparison.OrdinalIgnoreCase))
{
continue;
}
DeleteFileWithRetry(existingPackagePath);
}
catch
{
// Ignore unrelated or malformed packages while replacing an install target.
}
}
}
private static void CopyWithRetry(string sourcePath, string destinationPath, bool overwrite)
{
Retry(() => File.Copy(sourcePath, destinationPath, overwrite));
}
private static void MoveWithOverwriteRetry(string sourcePath, string destinationPath)
{
Retry(() => File.Move(sourcePath, destinationPath, overwrite: true));
}
private static void DeleteFileWithRetry(string filePath)
{
Retry(() =>
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
});
}
private static void Retry(Action action)
{
Exception? lastException = null;
for (var attempt = 0; attempt <= RetryDelays.Length; attempt++)
{
try
{
action();
return;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
lastException = ex;
if (attempt >= RetryDelays.Length)
{
break;
}
Thread.Sleep(RetryDelays[attempt]);
}
}
if (lastException is not null)
{
throw lastException;
}
}
private static string BuildInstalledPackageFileName(string pluginId)
{
var invalidChars = Path.GetInvalidFileNameChars();
var fileName = new string(pluginId.Select(ch => invalidChars.Contains(ch) ? '_' : ch).ToArray());
return fileName + PluginSdkInfo.PackageFileExtension;
}
private static string EnsureTrailingSeparator(string path)
{
return path.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)
? path
: path + Path.DirectorySeparatorChar;
}
private sealed class HelperResult
{
public bool Success { get; init; }
public string? InstalledPackagePath { get; init; }
public string? ManifestId { get; init; }
public string? ManifestName { get; init; }
public string? ErrorMessage { get; init; }
}
}

View File

@@ -0,0 +1,187 @@
using System.Text.Json;
using LanMountainDesktop.Models;
using LanMountainDesktop.Services;
using Xunit;
namespace LanMountainDesktop.Tests;
public sealed class ComponentSettingsServiceTests
{
[Fact]
public void Load_MigratesLegacySnapshotFileToCanonicalDocument()
{
using var sandbox = new ComponentSettingsSandbox();
File.WriteAllText(
sandbox.SettingsPath,
"""
{
"DesktopClockSecondHandMode": "Sweep",
"ImportedClassSchedules": [
{
"Id": "spring-2026",
"DisplayName": "Spring 2026",
"FilePath": "C:\\Schedules\\spring-2026.yaml"
}
],
"ActiveImportedClassScheduleId": "spring-2026"
}
""");
var service = sandbox.CreateService();
var snapshot = service.Load();
Assert.Equal("Sweep", snapshot.DesktopClockSecondHandMode);
Assert.Single(snapshot.ImportedClassSchedules);
using var document = JsonDocument.Parse(File.ReadAllText(sandbox.SettingsPath));
Assert.True(document.RootElement.TryGetProperty("defaultSettings", out var defaultSettings));
Assert.Equal("Sweep", defaultSettings.GetProperty("desktopClockSecondHandMode").GetString());
Assert.False(document.RootElement.TryGetProperty("DesktopClockSecondHandMode", out _));
}
[Fact]
public void Load_ReadsPascalCaseDocumentAndRewritesToCanonicalDocument()
{
using var sandbox = new ComponentSettingsSandbox();
File.WriteAllText(
sandbox.SettingsPath,
"""
{
"DefaultSettings": {
"DesktopClockSecondHandMode": "Tick"
},
"InstanceSettings": {
"DesktopClock::clock-2x2": {
"DesktopClockSecondHandMode": "Sweep"
}
},
"PluginSettings": {
"DesktopClock::clock-2x2": {
"SampleFlag": true
}
}
}
""");
var service = sandbox.CreateService();
var snapshot = service.LoadForComponent("DesktopClock", "clock-2x2");
var pluginSettings = service.LoadPluginSettings<SamplePluginSettings>("DesktopClock", "clock-2x2");
Assert.Equal("Sweep", snapshot.DesktopClockSecondHandMode);
Assert.True(pluginSettings.SampleFlag);
using var document = JsonDocument.Parse(File.ReadAllText(sandbox.SettingsPath));
Assert.True(document.RootElement.TryGetProperty("instanceSettings", out var instanceSettings));
Assert.True(instanceSettings.TryGetProperty("DesktopClock::clock-2x2", out var clockSettings));
Assert.Equal("Sweep", clockSettings.GetProperty("desktopClockSecondHandMode").GetString());
Assert.False(document.RootElement.TryGetProperty("InstanceSettings", out _));
}
[Fact]
public void SaveForComponent_RoundTripsInstanceAndPluginSettingsAcrossNewService()
{
using var sandbox = new ComponentSettingsSandbox();
var service = sandbox.CreateService();
service.SaveForComponent(
"DesktopClock",
"clock-2x2",
new ComponentSettingsSnapshot
{
DesktopClockSecondHandMode = "Sweep"
});
service.SaveForComponent(
"DesktopClassSchedule",
"class-schedule-2x2",
new ComponentSettingsSnapshot
{
ImportedClassSchedules =
[
new ImportedClassScheduleSnapshot
{
Id = "spring-2026",
DisplayName = "Spring 2026",
FilePath = "C:\\Schedules\\spring-2026.yaml"
}
],
ActiveImportedClassScheduleId = "spring-2026"
});
service.SavePluginSettings(
"DesktopClassSchedule",
"class-schedule-2x2",
new SamplePluginSettings
{
SampleFlag = true,
Title = "schedule-settings"
});
ComponentSettingsService.ResetCacheForTests();
var reloadedService = sandbox.CreateService();
var clockSnapshot = reloadedService.LoadForComponent("DesktopClock", "clock-2x2");
var classScheduleSnapshot = reloadedService.LoadForComponent("DesktopClassSchedule", "class-schedule-2x2");
var pluginSettings = reloadedService.LoadPluginSettings<SamplePluginSettings>(
"DesktopClassSchedule",
"class-schedule-2x2");
Assert.Equal("Sweep", clockSnapshot.DesktopClockSecondHandMode);
Assert.Single(classScheduleSnapshot.ImportedClassSchedules);
Assert.Equal("spring-2026", classScheduleSnapshot.ActiveImportedClassScheduleId);
Assert.True(pluginSettings.SampleFlag);
Assert.Equal("schedule-settings", pluginSettings.Title);
using var document = JsonDocument.Parse(File.ReadAllText(sandbox.SettingsPath));
Assert.True(document.RootElement.TryGetProperty("instanceSettings", out var instanceSettings));
Assert.True(instanceSettings.TryGetProperty("DesktopClock::clock-2x2", out _));
Assert.True(instanceSettings.TryGetProperty("DesktopClassSchedule::class-schedule-2x2", out _));
Assert.True(document.RootElement.TryGetProperty("pluginSettings", out var pluginSettingsNode));
Assert.True(pluginSettingsNode.TryGetProperty("DesktopClassSchedule::class-schedule-2x2", out _));
}
private sealed class ComponentSettingsSandbox : IDisposable
{
private readonly string _directoryPath = Path.Combine(
Path.GetTempPath(),
"LanMountainDesktop.ComponentSettingsTests",
Guid.NewGuid().ToString("N"));
public ComponentSettingsSandbox()
{
Directory.CreateDirectory(_directoryPath);
ComponentSettingsService.ResetCacheForTests();
}
public string SettingsPath => Path.Combine(_directoryPath, "component-settings.json");
public ComponentSettingsService CreateService()
{
return new ComponentSettingsService(_directoryPath);
}
public void Dispose()
{
ComponentSettingsService.ResetCacheForTests();
try
{
if (Directory.Exists(_directoryPath))
{
Directory.Delete(_directoryPath, true);
}
}
catch
{
// Temporary test directories are best-effort cleanup.
}
}
}
private sealed class SamplePluginSettings
{
public bool SampleFlag { get; set; }
public string Title { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LanMountainDesktop\LanMountainDesktop.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,43 @@
using System;
using System.Threading.Tasks;
using LanMountainDesktop.Services;
using Xunit;
namespace LanMountainDesktop.Tests;
public sealed class UiExceptionGuardTests
{
[Fact]
public async Task RunGuardedUiActionAsync_SwallowsNonFatalException_AndInvokesHandler()
{
var handlerCalled = false;
await UiExceptionGuard.RunGuardedUiActionAsync(
() => throw new InvalidOperationException("boom"),
"UnitTest.NonFatal",
onHandledException: ex =>
{
handlerCalled = ex is InvalidOperationException;
return Task.CompletedTask;
});
Assert.True(handlerCalled);
}
[Fact]
public async Task RunGuardedUiActionAsync_RethrowsFatalException()
{
await Assert.ThrowsAsync<OutOfMemoryException>(() =>
UiExceptionGuard.RunGuardedUiActionAsync(
() => throw new OutOfMemoryException("fatal"),
"UnitTest.Fatal"));
}
[Fact]
public void IsFatalException_ReturnsExpectedClassification()
{
Assert.True(UiExceptionGuard.IsFatalException(new OutOfMemoryException()));
Assert.True(UiExceptionGuard.IsFatalException(new AccessViolationException()));
Assert.False(UiExceptionGuard.IsFatalException(new InvalidOperationException()));
}
}

View File

@@ -1,37 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LanMountainDesktop", "LanMountainDesktop\LanMountainDesktop.csproj", "{00000001-0000-0000-0000-000000000001}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LanMountainDesktop.SamplePlugin", "LanAirApp\samples\LanMountainDesktop.SamplePlugin\LanMountainDesktop.SamplePlugin.csproj", "{BDCD028D-DB6E-4BD5-994A-65889DBDEE0C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LanMountainDesktop.PluginPackager", "LanAirApp\tools\LanMountainDesktop.PluginPackager\LanMountainDesktop.PluginPackager.csproj", "{AAE8578B-1F9D-4D4F-8B2E-0A98C55B0C31}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LanMountainDesktop.PluginSdk", "LanMountainDesktop.PluginSdk\LanMountainDesktop.PluginSdk.csproj", "{30A0F689-AACC-48C8-8BFE-BC7BFBA6CC55}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{00000001-0000-0000-0000-000000000001}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{00000001-0000-0000-0000-000000000001}.Debug|Any CPU.Build.0 = Debug|Any CPU
{00000001-0000-0000-0000-000000000001}.Release|Any CPU.ActiveCfg = Release|Any CPU
{00000001-0000-0000-0000-000000000001}.Release|Any CPU.Build.0 = Release|Any CPU
{BDCD028D-DB6E-4BD5-994A-65889DBDEE0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BDCD028D-DB6E-4BD5-994A-65889DBDEE0C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BDCD028D-DB6E-4BD5-994A-65889DBDEE0C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BDCD028D-DB6E-4BD5-994A-65889DBDEE0C}.Release|Any CPU.Build.0 = Release|Any CPU
{AAE8578B-1F9D-4D4F-8B2E-0A98C55B0C31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AAE8578B-1F9D-4D4F-8B2E-0A98C55B0C31}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AAE8578B-1F9D-4D4F-8B2E-0A98C55B0C31}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AAE8578B-1F9D-4D4F-8B2E-0A98C55B0C31}.Release|Any CPU.Build.0 = Release|Any CPU
{30A0F689-AACC-48C8-8BFE-BC7BFBA6CC55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{30A0F689-AACC-48C8-8BFE-BC7BFBA6CC55}.Debug|Any CPU.Build.0 = Debug|Any CPU
{30A0F689-AACC-48C8-8BFE-BC7BFBA6CC55}.Release|Any CPU.ActiveCfg = Release|Any CPU
{30A0F689-AACC-48C8-8BFE-BC7BFBA6CC55}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

7
LanMountainDesktop.slnx Normal file
View File

@@ -0,0 +1,7 @@
<Solution>
<Project Path="LanAirApp/tools/LanMountainDesktop.PluginPackager/LanMountainDesktop.PluginPackager.csproj" />
<Project Path="LanMountainDesktop.PluginSdk/LanMountainDesktop.PluginSdk.csproj" />
<Project Path="LanMountainDesktop.PluginsInstallHelper/LanMountainDesktop.PluginsInstallHelper.csproj" />
<Project Path="LanMountainDesktop/LanMountainDesktop.csproj" />
<Project Path="LanMountainDesktop.Tests/LanMountainDesktop.Tests.csproj" />
</Solution>

View File

@@ -8,10 +8,12 @@ using System.Linq;
using Avalonia.Markup.Xaml;
using Avalonia.Platform;
using Avalonia.Threading;
using LanMountainDesktop.ComponentSystem;
using LanMountainDesktop.Services;
using LanMountainDesktop.ViewModels;
using LanMountainDesktop.Views;
using AvaloniaWebView;
using LanMountainDesktop.PluginSdk;
namespace LanMountainDesktop;
@@ -19,12 +21,19 @@ public partial class App : Application
{
private readonly AppSettingsService _appSettingsService = new();
private readonly LocalizationService _localizationService = new();
private readonly IHostApplicationLifecycle _hostApplicationLifecycle = new HostApplicationLifecycleService();
private bool _exitCleanupCompleted;
private SettingsWindow? _traySettingsWindow;
private TrayIcons? _trayIcons;
private PluginRuntimeService? _pluginRuntimeService;
internal static SingleInstanceService? CurrentSingleInstanceService { get; set; }
internal static IHostApplicationLifecycle? CurrentHostApplicationLifecycle =>
(Current as App)?._hostApplicationLifecycle;
public PluginRuntimeService? PluginRuntimeService => _pluginRuntimeService;
public IHostApplicationLifecycle HostApplicationLifecycle => _hostApplicationLifecycle;
public override void Initialize()
{
@@ -51,14 +60,15 @@ public partial class App : Application
desktop.Exit += (_, _) =>
{
AppLogger.Info("App", "Desktop lifetime exit triggered.");
AppSettingsService.SettingsSaved -= OnAppSettingsSaved;
DisposeTrayIcon();
PerformExitCleanup();
};
desktop.MainWindow = new MainWindow
{
DataContext = new MainWindowViewModel(),
};
AppLogger.Info("App", $"Main window created. LogFile={AppLogger.LogFilePath}");
LogBrowserStartupDiagnostics();
CurrentSingleInstanceService?.StartActivationListener(ActivateMainWindow);
}
base.OnFrameworkInitializationCompleted();
@@ -66,12 +76,9 @@ public partial class App : Application
private void OnTrayExitClick(object? sender, EventArgs e)
{
DisposeTrayIcon();
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
desktop.Shutdown();
}
_ = _hostApplicationLifecycle.TryExit(new HostApplicationLifecycleRequest(
Source: "TrayMenu",
Reason: "User selected Exit App from the tray menu."));
}
private void OnTraySettingsClick(object? sender, EventArgs e)
@@ -114,18 +121,9 @@ public partial class App : Application
private void OnTrayRestartClick(object? sender, EventArgs e)
{
AppRestartService.TryRestartApplication();
}
private void OnAppSettingsSaved(string _)
{
Dispatcher.UIThread.Post(() =>
{
if (_trayIcons is not null)
{
InitializeTrayIcon();
}
}, DispatcherPriority.Background);
_ = _hostApplicationLifecycle.TryRestart(new HostApplicationLifecycleRequest(
Source: "TrayMenu",
Reason: "User selected Restart App from the tray menu."));
}
private void DisableAvaloniaDataAnnotationValidation()
@@ -246,6 +244,132 @@ public partial class App : Application
_trayIcons = null;
}
private void ActivateMainWindow()
{
Dispatcher.UIThread.Post(() =>
{
if (ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop)
{
return;
}
if (desktop.MainWindow is not Window mainWindow)
{
return;
}
try
{
if (!mainWindow.IsVisible)
{
mainWindow.Show();
}
if (mainWindow.WindowState == WindowState.Minimized)
{
mainWindow.WindowState = WindowState.Normal;
}
if (mainWindow.WindowState != WindowState.FullScreen)
{
mainWindow.WindowState = WindowState.FullScreen;
}
mainWindow.Activate();
mainWindow.Topmost = true;
mainWindow.Topmost = false;
if (mainWindow is MainWindow lanMountainMainWindow)
{
lanMountainMainWindow.ShowSingleInstanceNotice();
}
}
catch (Exception ex)
{
AppLogger.Warn("SingleInstance", "Failed to activate the existing main window.", ex);
}
}, DispatcherPriority.Send);
}
private void OnAppSettingsSaved(string _)
{
Dispatcher.UIThread.Post(() =>
{
if (_trayIcons is not null)
{
InitializeTrayIcon();
}
}, DispatcherPriority.Background);
}
private void PerformExitCleanup()
{
if (_exitCleanupCompleted)
{
return;
}
_exitCleanupCompleted = true;
AppSettingsService.SettingsSaved -= OnAppSettingsSaved;
try
{
_traySettingsWindow?.Close();
}
catch (Exception ex)
{
AppLogger.Warn("App", "Failed to close tray-opened settings window during shutdown.", ex);
}
finally
{
_traySettingsWindow = null;
}
try
{
_pluginRuntimeService?.Dispose();
}
catch (Exception ex)
{
AppLogger.Warn("PluginRuntime", "Failed to dispose plugin runtime during shutdown.", ex);
}
finally
{
_pluginRuntimeService = null;
}
AudioRecorderServiceFactory.DisposeSharedServices();
StudyAnalyticsServiceFactory.DisposeSharedService();
DisposeTrayIcon();
}
private void LogBrowserStartupDiagnostics()
{
try
{
var snapshot = new DesktopLayoutSettingsService().Load();
var browserPlacements = snapshot.DesktopComponentPlacements
.Where(placement => string.Equals(
placement.ComponentId,
BuiltInComponentIds.DesktopBrowser,
StringComparison.OrdinalIgnoreCase))
.ToList();
var runtimeAvailability = WebView2RuntimeProbe.GetAvailability();
AppLogger.Info(
"StartupDiagnostics",
$"Browser component diagnostics. HasBrowserPlacement={browserPlacements.Count > 0}; " +
$"ActivePageHasBrowser={browserPlacements.Any(item => item.PageIndex == snapshot.CurrentDesktopSurfaceIndex)}; " +
$"CurrentDesktopSurfaceIndex={snapshot.CurrentDesktopSurfaceIndex}; " +
$"WebViewRuntimeAvailable={runtimeAvailability.IsAvailable}; " +
$"WebViewRuntimeVersion={runtimeAvailability.Version ?? string.Empty}; " +
$"WebViewRuntimeMessage={runtimeAvailability.Message}");
}
catch (Exception ex)
{
AppLogger.Warn("StartupDiagnostics", "Failed to log browser component diagnostics.", ex);
}
}
private string L(string key, string fallback)
{
var snapshot = _appSettingsService.Load();

View File

@@ -26,6 +26,8 @@
<ItemGroup>
<ProjectReference Include="..\LanMountainDesktop.PluginSdk\LanMountainDesktop.PluginSdk.csproj" />
<ProjectReference Include="..\LanMountainDesktop.PluginsInstallHelper\LanMountainDesktop.PluginsInstallHelper.csproj"
ReferenceOutputAssembly="false" />
</ItemGroup>
<ItemGroup>
@@ -45,6 +47,8 @@
<PackageReference Include="FluentIcons.Avalonia" Version="2.0.319" />
<PackageReference Include="FluentIcons.Avalonia.Fluent" Version="2.0.319" />
<PackageReference Include="Material.Icons.Avalonia" Version="2.4.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.0" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.0" />
<PackageReference Include="LibVLCSharp.Avalonia" Version="3.9.5" />
<PackageReference Include="PortAudioSharp2" Version="1.0.6" />
@@ -56,4 +60,22 @@
<PackageReference Include="WebView.Avalonia.Desktop" Version="11.0.0.1" />
<PackageReference Include="YamlDotNet" Version="16.3.0" />
</ItemGroup>
<Target Name="CopyPluginsInstallHelperToOutput" AfterTargets="Build">
<ItemGroup>
<PluginsInstallHelperFiles Include="..\LanMountainDesktop.PluginsInstallHelper\bin\$(Configuration)\net10.0\**\*.*" />
</ItemGroup>
<Copy SourceFiles="@(PluginsInstallHelperFiles)"
DestinationFiles="@(PluginsInstallHelperFiles->'$(OutDir)PluginsInstallHelper\%(RecursiveDir)%(Filename)%(Extension)')"
SkipUnchangedFiles="true" />
</Target>
<Target Name="CopyPluginsInstallHelperToPublish" AfterTargets="Publish" Condition="'$(PublishDir)' != ''">
<ItemGroup>
<PluginsInstallHelperPublishFiles Include="..\LanMountainDesktop.PluginsInstallHelper\bin\$(Configuration)\net10.0\**\*.*" />
</ItemGroup>
<Copy SourceFiles="@(PluginsInstallHelperPublishFiles)"
DestinationFiles="@(PluginsInstallHelperPublishFiles->'$(PublishDir)PluginsInstallHelper\%(RecursiveDir)%(Filename)%(Extension)')"
SkipUnchangedFiles="true" />
</Target>
</Project>

View File

@@ -251,6 +251,7 @@
"settings.update.status_launching_installer": "Download complete. Launching installer...",
"settings.update.status_installer_missing": "Installer file was not found after download.",
"settings.update.status_installer_started": "Installer started. The app will close for update.",
"settings.update.status_elevation_cancelled": "Administrator permission was not granted. Update was cancelled.",
"settings.update.status_launch_failed_format": "Failed to start installer: {0}",
"settings.about.title": "About",
"settings.about.version_format": "Version: {0}",
@@ -742,7 +743,10 @@
"placement.fit": "Fit",
"placement.stretch": "Stretch",
"placement.center": "Center",
"placement.tile": "Tile"
}
"placement.tile": "Tile",
"single_instance.notice.title": "App already running",
"single_instance.notice.description": "The app is already running. There is no need to click multiple times to open it.",
"single_instance.notice.button": "OK"
}

View File

@@ -251,6 +251,7 @@
"settings.update.status_launching_installer": "下载完成,正在启动安装程序...",
"settings.update.status_installer_missing": "下载后未找到安装包文件。",
"settings.update.status_installer_started": "安装程序已启动,应用将关闭进行更新。",
"settings.update.status_elevation_cancelled": "未授予管理员权限,更新已取消。",
"settings.update.status_launch_failed_format": "启动安装程序失败:{0}",
"settings.about.title": "关于",
"settings.about.version_format": "版本号: {0}",
@@ -742,7 +743,10 @@
"placement.fit": "适应",
"placement.stretch": "拉伸",
"placement.center": "居中",
"placement.tile": "平铺"
}
"placement.tile": "平铺",
"single_instance.notice.title": "应用已经运行",
"single_instance.notice.description": "应用已经运行,无需多次点击打开。",
"single_instance.notice.button": "确定"
}

View File

@@ -1,8 +1,10 @@
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.WebView.Desktop;
using LanMountainDesktop.Services;
using System;
using System.Threading.Tasks;
namespace LanMountainDesktop;
@@ -16,6 +18,23 @@ sealed class Program
{
AppLogger.Initialize();
RegisterGlobalExceptionLogging();
var restartParentProcessId = AppRestartService.TryGetRestartParentProcessId(args);
using var singleInstance = AcquireSingleInstance(restartParentProcessId);
if (!singleInstance.IsPrimaryInstance)
{
if (restartParentProcessId is not null)
{
AppLogger.Warn(
"Startup",
$"Restart relaunch could not acquire the single-instance lock. pid={restartParentProcessId.Value}. Suppressing multi-open activation prompt.");
return;
}
AppLogger.Warn("Startup", "A secondary launch was blocked because another instance is already running.");
_ = singleInstance.TryNotifyPrimaryInstance(TimeSpan.FromSeconds(2));
return;
}
var diagnostics = StartupDiagnosticsService.Run(args);
StartupDiagnosticsService.ShowLegacyExecutableWarningIfNeeded(diagnostics);
@@ -24,6 +43,7 @@ sealed class Program
{
var renderMode = LoadConfiguredRenderMode();
AppLogger.Info("Startup", $"Resolved render mode '{renderMode}'.");
App.CurrentSingleInstanceService = singleInstance;
BuildAvaloniaApp(renderMode).StartWithClassicDesktopLifetime(args);
AppLogger.Info("Startup", "Application exited normally.");
}
@@ -32,6 +52,10 @@ sealed class Program
AppLogger.Critical("Startup", "Application terminated during startup.", ex);
throw;
}
finally
{
App.CurrentSingleInstanceService = null;
}
}
// Avalonia configuration, don't remove; also used by visual designer.
@@ -58,6 +82,41 @@ sealed class Program
return builder;
}
private static SingleInstanceService AcquireSingleInstance(int? restartParentProcessId)
{
var singleInstance = SingleInstanceService.CreateDefault();
if (singleInstance.IsPrimaryInstance || restartParentProcessId is null)
{
return singleInstance;
}
AppLogger.Info(
"Startup",
$"Restart relaunch detected. Waiting for previous instance pid={restartParentProcessId.Value} to exit before re-acquiring the single-instance lock.");
singleInstance.Dispose();
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(12);
WaitForRestartParentExit(restartParentProcessId.Value, deadline);
while (DateTime.UtcNow < deadline)
{
var retryInstance = SingleInstanceService.CreateDefault();
if (retryInstance.IsPrimaryInstance)
{
AppLogger.Info("Startup", "Restart relaunch acquired the single-instance lock.");
return retryInstance;
}
retryInstance.Dispose();
Thread.Sleep(150);
}
AppLogger.Warn(
"Startup",
$"Restart relaunch timed out while waiting for the single-instance lock. pid={restartParentProcessId.Value}.");
return SingleInstanceService.CreateDefault();
}
private static string LoadConfiguredRenderMode()
{
try
@@ -71,6 +130,27 @@ sealed class Program
}
}
private static void WaitForRestartParentExit(int processId, DateTime deadlineUtc)
{
try
{
using var process = Process.GetProcessById(processId);
var remaining = deadlineUtc - DateTime.UtcNow;
if (remaining > TimeSpan.Zero)
{
process.WaitForExit((int)Math.Ceiling(remaining.TotalMilliseconds));
}
}
catch (ArgumentException)
{
// The previous process already exited before we started waiting.
}
catch (Exception ex)
{
AppLogger.Warn("Startup", $"Failed while waiting for restart parent pid={processId} to exit.", ex);
}
}
private static void RegisterGlobalExceptionLogging()
{
AppDomain.CurrentDomain.UnhandledException += (_, eventArgs) =>
@@ -84,6 +164,7 @@ sealed class Program
TaskScheduler.UnobservedTaskException += (_, eventArgs) =>
{
AppLogger.Error("TaskScheduler", "Unobserved task exception.", eventArgs.Exception);
eventArgs.SetObserved();
};
}
}

View File

@@ -0,0 +1,3 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("LanMountainDesktop.Tests")]

View File

@@ -3,26 +3,19 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using LanMountainDesktop.PluginSdk;
namespace LanMountainDesktop.Services;
public static class AppRestartService
{
private const string RestartParentPidArgumentPrefix = "--restart-parent-pid=";
public static bool TryRestartApplication()
{
if (!TryRestartCurrentProcess())
{
return false;
}
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
desktop.Shutdown();
}
return true;
return App.CurrentHostApplicationLifecycle?.TryRestart(new HostApplicationLifecycleRequest(
Source: nameof(AppRestartService),
Reason: "Legacy restart entry point invoked.")) == true;
}
public static bool TryRestartCurrentProcess()
@@ -84,6 +77,21 @@ public static class AppRestartService
return null;
}
public static int? TryGetRestartParentProcessId(IReadOnlyList<string> commandLineArgs)
{
ArgumentNullException.ThrowIfNull(commandLineArgs);
foreach (var argument in commandLineArgs)
{
if (TryParseRestartParentProcessId(argument, out var processId))
{
return processId;
}
}
return null;
}
private static ProcessStartInfo CreateExecutableStartInfo(
string executablePath,
string? entryAssemblyPath,
@@ -97,6 +105,7 @@ public static class AppRestartService
};
AppendArguments(startInfo, commandLineArgs);
AppendRestartParentProcessArgument(startInfo);
return startInfo;
}
@@ -119,6 +128,7 @@ public static class AppRestartService
startInfo.ArgumentList.Add(entryAssemblyPath);
AppendArguments(startInfo, commandLineArgs);
AppendRestartParentProcessArgument(startInfo);
return startInfo;
}
@@ -126,10 +136,34 @@ public static class AppRestartService
{
for (var i = 1; i < commandLineArgs.Count; i++)
{
if (TryParseRestartParentProcessId(commandLineArgs[i], out _))
{
continue;
}
startInfo.ArgumentList.Add(commandLineArgs[i]);
}
}
private static void AppendRestartParentProcessArgument(ProcessStartInfo startInfo)
{
startInfo.ArgumentList.Add($"{RestartParentPidArgumentPrefix}{Environment.ProcessId}");
}
private static bool TryParseRestartParentProcessId(string? argument, out int processId)
{
processId = 0;
if (string.IsNullOrWhiteSpace(argument) ||
!argument.StartsWith(RestartParentPidArgumentPrefix, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return int.TryParse(
argument[RestartParentPidArgumentPrefix.Length..],
out processId) && processId > 0;
}
private static string? NormalizeExistingPath(string? path)
{
if (string.IsNullOrWhiteSpace(path))

View File

@@ -12,6 +12,8 @@ public sealed class ComponentSettingsService : IComponentInstanceSettingsStore
{
private static readonly JsonSerializerOptions SerializerOptions = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
@@ -29,9 +31,19 @@ public sealed class ComponentSettingsService : IComponentInstanceSettingsStore
private string _scopedPlacementId = string.Empty;
public ComponentSettingsService()
: this(Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"LanMountainDesktop"))
{
var appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var settingsDirectory = Path.Combine(appData, "LanMountainDesktop");
}
internal ComponentSettingsService(string settingsDirectory)
{
if (string.IsNullOrWhiteSpace(settingsDirectory))
{
throw new ArgumentException("Settings directory cannot be null or whitespace.", nameof(settingsDirectory));
}
_settingsPath = Path.Combine(settingsDirectory, "component-settings.json");
_legacyAppSettingsPath = Path.Combine(settingsDirectory, "settings.json");
}
@@ -345,10 +357,11 @@ public sealed class ComponentSettingsService : IComponentInstanceSettingsStore
}
ComponentSettingsDocumentSnapshot loadedSnapshot;
var loadedFromLegacy = false;
var loadDetails = ComponentSettingsLoadDetails.Empty;
if (hasFile)
{
loadedSnapshot = LoadSnapshotFromDisk();
loadDetails = LoadSnapshotFromDisk();
loadedSnapshot = loadDetails.Snapshot;
}
else if (TryLoadLegacySnapshot(out var migratedSnapshot))
{
@@ -356,7 +369,10 @@ public sealed class ComponentSettingsService : IComponentInstanceSettingsStore
{
DefaultSettings = NormalizeSnapshot(migratedSnapshot)
};
loadedFromLegacy = true;
loadDetails = new ComponentSettingsLoadDetails(
loadedSnapshot,
ComponentSettingsDocumentFormat.LegacySnapshot,
true);
}
else
{
@@ -364,40 +380,44 @@ public sealed class ComponentSettingsService : IComponentInstanceSettingsStore
}
var normalizedSnapshot = NormalizeDocument(loadedSnapshot);
if (loadedFromLegacy)
if (loadDetails.ShouldRewriteToCanonical)
{
writeTimeUtc = PersistSnapshotToDisk(normalizedSnapshot);
}
LogLoadDetails(loadDetails.Format, loadDetails.ShouldRewriteToCanonical, normalizedSnapshot);
UpdateCache(normalizedSnapshot, writeTimeUtc, nowUtc);
return normalizedSnapshot.Clone();
}
private ComponentSettingsDocumentSnapshot LoadSnapshotFromDisk()
private ComponentSettingsLoadDetails LoadSnapshotFromDisk()
{
try
{
var json = File.ReadAllText(_settingsPath);
using var document = JsonDocument.Parse(json);
if (document.RootElement.ValueKind == JsonValueKind.Object &&
(document.RootElement.TryGetProperty("defaultSettings", out _) ||
document.RootElement.TryGetProperty("instanceSettings", out _) ||
document.RootElement.TryGetProperty("pluginSettings", out _)))
if (TryGetDocumentFormat(document.RootElement, out var format))
{
var snapshot = JsonSerializer.Deserialize<ComponentSettingsDocumentSnapshot>(json, SerializerOptions);
return NormalizeDocument(snapshot);
return new ComponentSettingsLoadDetails(
snapshot ?? new ComponentSettingsDocumentSnapshot(),
format,
format == ComponentSettingsDocumentFormat.PascalCaseDocument);
}
var legacySnapshot = JsonSerializer.Deserialize<ComponentSettingsSnapshot>(json, SerializerOptions);
return new ComponentSettingsDocumentSnapshot
{
DefaultSettings = NormalizeSnapshot(legacySnapshot)
};
return new ComponentSettingsLoadDetails(
new ComponentSettingsDocumentSnapshot
{
DefaultSettings = NormalizeSnapshot(legacySnapshot)
},
ComponentSettingsDocumentFormat.LegacySnapshot,
true);
}
catch (Exception ex)
{
AppLogger.Warn("ComponentSettings", $"Failed to deserialize component settings from '{_settingsPath}'.", ex);
return new ComponentSettingsDocumentSnapshot();
return ComponentSettingsLoadDetails.Empty;
}
}
@@ -684,6 +704,79 @@ public sealed class ComponentSettingsService : IComponentInstanceSettingsStore
_lastProbeUtc = probeTimeUtc;
}
internal static void ResetCacheForTests()
{
lock (CacheGate)
{
_cachedPath = null;
_cachedSnapshot = null;
_cachedWriteTimeUtc = DateTime.MinValue;
_lastProbeUtc = DateTime.MinValue;
}
}
private void LogLoadDetails(
ComponentSettingsDocumentFormat format,
bool rewroteToCanonical,
ComponentSettingsDocumentSnapshot snapshot)
{
AppLogger.Info(
"ComponentSettings",
$"Loaded component settings document. Format={format}; RewroteToCanonical={rewroteToCanonical}; " +
$"InstanceSettings={snapshot.InstanceSettings.Count}; PluginSettings={snapshot.PluginSettings.Count}; Path={_settingsPath}");
}
private static bool TryGetDocumentFormat(
JsonElement rootElement,
out ComponentSettingsDocumentFormat format)
{
format = ComponentSettingsDocumentFormat.EmptyDocument;
if (rootElement.ValueKind != JsonValueKind.Object)
{
return false;
}
var hasDocumentProperties = false;
var requiresCanonicalRewrite = false;
foreach (var property in rootElement.EnumerateObject())
{
if (!IsDocumentPropertyName(property.Name))
{
continue;
}
hasDocumentProperties = true;
if (!IsCanonicalDocumentPropertyName(property.Name))
{
requiresCanonicalRewrite = true;
}
}
if (!hasDocumentProperties)
{
return false;
}
format = requiresCanonicalRewrite
? ComponentSettingsDocumentFormat.PascalCaseDocument
: ComponentSettingsDocumentFormat.CanonicalDocument;
return true;
}
private static bool IsDocumentPropertyName(string propertyName)
{
return string.Equals(propertyName, "defaultSettings", StringComparison.OrdinalIgnoreCase) ||
string.Equals(propertyName, "instanceSettings", StringComparison.OrdinalIgnoreCase) ||
string.Equals(propertyName, "pluginSettings", StringComparison.OrdinalIgnoreCase);
}
private static bool IsCanonicalDocumentPropertyName(string propertyName)
{
return string.Equals(propertyName, "defaultSettings", StringComparison.Ordinal) ||
string.Equals(propertyName, "instanceSettings", StringComparison.Ordinal) ||
string.Equals(propertyName, "pluginSettings", StringComparison.Ordinal);
}
private sealed class ComponentSettingsDocumentSnapshot
{
public ComponentSettingsSnapshot DefaultSettings { get; set; } = new();
@@ -771,4 +864,23 @@ public sealed class ComponentSettingsService : IComponentInstanceSettingsStore
public string Stcn24ForumSourceType { get; set; } = Stcn24ForumSourceTypes.LatestCreated;
}
private readonly record struct ComponentSettingsLoadDetails(
ComponentSettingsDocumentSnapshot Snapshot,
ComponentSettingsDocumentFormat Format,
bool ShouldRewriteToCanonical)
{
public static ComponentSettingsLoadDetails Empty { get; } = new(
new ComponentSettingsDocumentSnapshot(),
ComponentSettingsDocumentFormat.EmptyDocument,
false);
}
private enum ComponentSettingsDocumentFormat
{
EmptyDocument,
CanonicalDocument,
PascalCaseDocument,
LegacySnapshot
}
}

View File

@@ -118,13 +118,13 @@ public static class DesktopComponentRegistryFactory
contribution.Plugin.Manifest,
contribution.Plugin.Context.PluginDirectory,
contribution.Plugin.Context.DataDirectory,
contribution.Plugin.Context.Services,
contribution.Plugin.Services,
contribution.Plugin.Context.Properties,
contribution.Registration.ComponentId,
context.PlacementId,
context.CellSize);
return contribution.Registration.ControlFactory(pluginContext);
return contribution.Registration.ControlFactory(contribution.Plugin.Services, pluginContext);
}
catch (Exception ex)
{

View File

@@ -0,0 +1,75 @@
using System;
using System.Diagnostics;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;
using LanMountainDesktop.PluginSdk;
namespace LanMountainDesktop.Services;
public sealed class HostApplicationLifecycleService : IHostApplicationLifecycle
{
public bool TryExit(HostApplicationLifecycleRequest? request = null)
{
try
{
AppLogger.Info(
"HostLifecycle",
$"Exit requested. Source='{request?.Source ?? "Unknown"}'; Reason='{request?.Reason ?? string.Empty}'.");
if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop)
{
AppLogger.Warn("HostLifecycle", "Exit request ignored because desktop lifetime is unavailable.");
return false;
}
if (Dispatcher.UIThread.CheckAccess())
{
desktop.Shutdown();
}
else
{
Dispatcher.UIThread.Post(() => desktop.Shutdown(), DispatcherPriority.Send);
}
return true;
}
catch (Exception ex)
{
AppLogger.Warn("HostLifecycle", "Failed to exit the application.", ex);
return false;
}
}
public bool TryRestart(HostApplicationLifecycleRequest? request = null)
{
try
{
var startInfo = AppRestartService.CreateRestartStartInfo();
if (startInfo is null)
{
AppLogger.Warn(
"HostLifecycle",
$"Restart request rejected because restart start info could not be resolved. Source='{request?.Source ?? "Unknown"}'.");
return false;
}
Process.Start(startInfo);
var exitRequest = request is null
? new HostApplicationLifecycleRequest(Reason: "Restart accepted.")
: request with
{
Reason = string.IsNullOrWhiteSpace(request.Reason)
? "Restart accepted."
: request.Reason
};
return TryExit(exitRequest);
}
catch (Exception ex)
{
AppLogger.Warn("HostLifecycle", "Failed to restart the application.", ex);
return false;
}
}
}

View File

@@ -80,6 +80,19 @@ public static class AudioRecorderServiceFactory
{
return CreateRecorder();
}
public static void DisposeSharedServices()
{
if (SharedRecorderService.IsValueCreated)
{
SharedRecorderService.Value.Dispose();
}
if (SharedStudyMonitoringService.IsValueCreated)
{
SharedStudyMonitoringService.Value.Dispose();
}
}
}
internal sealed class NoOpAudioRecorderService(string reason) : IAudioRecorderService

View File

@@ -0,0 +1,186 @@
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace LanMountainDesktop.Services;
internal sealed class PluginsInstallHelperClient
{
private const int UserCanceledUacErrorCode = 1223;
private const string HelperExecutableName = "LanMountainDesktop.PluginsInstallHelper.exe";
public async Task<PluginsInstallHelperResult> InstallPackageAsync(
string packagePath,
string pluginsDirectory,
CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(packagePath);
ArgumentException.ThrowIfNullOrWhiteSpace(pluginsDirectory);
if (!OperatingSystem.IsWindows())
{
return new PluginsInstallHelperResult(
false,
null,
"Elevated helper install is only supported on Windows.");
}
var helperPath = ResolveHelperPath();
if (!File.Exists(helperPath))
{
return new PluginsInstallHelperResult(
false,
null,
$"Plugins install helper was not found at '{helperPath}'.");
}
var resultPath = Path.Combine(
Path.GetTempPath(),
"LanMountainDesktop",
"PluginInstallResults",
$"{Guid.NewGuid():N}.json");
Directory.CreateDirectory(Path.GetDirectoryName(resultPath)!);
try
{
using var process = StartHelperProcess(helperPath, packagePath, pluginsDirectory, resultPath);
if (process is null)
{
return new PluginsInstallHelperResult(false, null, "Failed to start plugins install helper.");
}
await process.WaitForExitAsync(cancellationToken);
var result = await ReadResultAsync(resultPath, cancellationToken);
if (result is not null)
{
return new PluginsInstallHelperResult(result.Success, result.InstalledPackagePath, result.ErrorMessage);
}
if (process.ExitCode == 0)
{
return new PluginsInstallHelperResult(
false,
null,
"Plugins install helper exited without producing a result file.");
}
return new PluginsInstallHelperResult(
false,
null,
string.Format(
CultureInfo.InvariantCulture,
"Plugins install helper exited with code {0}.",
process.ExitCode));
}
catch (Win32Exception ex) when (ex.NativeErrorCode == UserCanceledUacErrorCode)
{
return new PluginsInstallHelperResult(false, null, "Administrator permission request was canceled.");
}
finally
{
TryDeleteFile(resultPath);
}
}
private static Process? StartHelperProcess(
string helperPath,
string packagePath,
string pluginsDirectory,
string resultPath)
{
var startInfo = new ProcessStartInfo
{
FileName = helperPath,
Verb = "runas",
UseShellExecute = true,
WorkingDirectory = Path.GetDirectoryName(helperPath) ?? AppContext.BaseDirectory,
Arguments = string.Create(
CultureInfo.InvariantCulture,
$"--source {QuoteArgument(Path.GetFullPath(packagePath))} --plugins-dir {QuoteArgument(Path.GetFullPath(pluginsDirectory))} --result {QuoteArgument(Path.GetFullPath(resultPath))}")
};
return Process.Start(startInfo);
}
private static async Task<HelperResultFile?> ReadResultAsync(string resultPath, CancellationToken cancellationToken)
{
if (!File.Exists(resultPath))
{
return null;
}
await using var stream = File.OpenRead(resultPath);
return await JsonSerializer.DeserializeAsync<HelperResultFile>(stream, cancellationToken: cancellationToken);
}
private static string ResolveHelperPath()
{
return Path.Combine(AppContext.BaseDirectory, "PluginsInstallHelper", HelperExecutableName);
}
private static string QuoteArgument(string value)
{
if (string.IsNullOrEmpty(value))
{
return "\"\"";
}
if (!value.Contains('"') && !value.Contains(' ') && !value.Contains('\t'))
{
return value;
}
var builder = new StringBuilder();
builder.Append('"');
foreach (var ch in value)
{
if (ch == '"')
{
builder.Append("\\\"");
}
else
{
builder.Append(ch);
}
}
builder.Append('"');
return builder.ToString();
}
private static void TryDeleteFile(string path)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
}
}
catch
{
// Ignore temp file cleanup failures.
}
}
private sealed class HelperResultFile
{
public bool Success { get; init; }
public string? InstalledPackagePath { get; init; }
public string? ErrorMessage { get; init; }
}
}
internal sealed record PluginsInstallHelperResult(
bool Success,
string? InstalledPackagePath,
string? ErrorMessage);

View File

@@ -0,0 +1,151 @@
using System;
using System.IO.Pipes;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LanMountainDesktop.Services;
public sealed class SingleInstanceService : IDisposable
{
private readonly Mutex _mutex;
private readonly string _pipeName;
private readonly CancellationTokenSource _listenCts = new();
private bool _ownsMutex;
private bool _disposed;
private Task? _listenTask;
private SingleInstanceService(string mutexName, string pipeName)
{
_mutex = new Mutex(initiallyOwned: false, mutexName);
_pipeName = pipeName;
try
{
_ownsMutex = _mutex.WaitOne(TimeSpan.Zero, exitContext: false);
}
catch (AbandonedMutexException)
{
_ownsMutex = true;
}
}
public bool IsPrimaryInstance => _ownsMutex;
public static SingleInstanceService CreateDefault()
{
const string appId = "LanMountainDesktop";
var userName = Environment.UserName;
var scopeSeed = $"{appId}:{userName}";
var scopeHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(scopeSeed)));
var suffix = scopeHash[..16];
var mutexName = OperatingSystem.IsWindows()
? $"Local\\{appId}.SingleInstance.{suffix}"
: $"{appId}.SingleInstance.{suffix}";
return new SingleInstanceService(
mutexName,
$"{appId}.Activate.{suffix}");
}
public void StartActivationListener(Action onActivationRequested)
{
ArgumentNullException.ThrowIfNull(onActivationRequested);
if (!_ownsMutex || _disposed || _listenTask is not null)
{
return;
}
_listenTask = Task.Run(() => ListenForActivationAsync(onActivationRequested, _listenCts.Token));
}
public bool TryNotifyPrimaryInstance(TimeSpan timeout)
{
if (_ownsMutex || _disposed)
{
return false;
}
try
{
using var client = new NamedPipeClientStream(
serverName: ".",
pipeName: _pipeName,
direction: PipeDirection.Out,
options: PipeOptions.Asynchronous);
client.Connect((int)Math.Max(1, timeout.TotalMilliseconds));
client.WriteByte(1);
client.Flush();
return true;
}
catch (Exception ex)
{
AppLogger.Warn("SingleInstance", "Failed to notify the primary instance.", ex);
return false;
}
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
_listenCts.Cancel();
try
{
_listenTask?.Wait(TimeSpan.FromSeconds(1));
}
catch
{
// Ignore listener shutdown races during process exit.
}
_listenCts.Dispose();
if (_ownsMutex)
{
try
{
_mutex.ReleaseMutex();
}
catch (ApplicationException)
{
// Ownership may already be lost during shutdown.
}
}
_mutex.Dispose();
}
private async Task ListenForActivationAsync(Action onActivationRequested, CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
using var server = new NamedPipeServerStream(
_pipeName,
PipeDirection.In,
1,
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous);
await server.WaitForConnectionAsync(cancellationToken).ConfigureAwait(false);
await server.ReadAsync(new byte[1], cancellationToken).ConfigureAwait(false);
onActivationRequested();
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
AppLogger.Warn("SingleInstance", "Activation listener failed.", ex);
await Task.Delay(TimeSpan.FromMilliseconds(250), cancellationToken).ConfigureAwait(false);
}
}
}
}

View File

@@ -16,6 +16,14 @@ public static class StudyAnalyticsServiceFactory
{
return SharedService.Value;
}
public static void DisposeSharedService()
{
if (SharedService.IsValueCreated)
{
SharedService.Value.Dispose();
}
}
}
public sealed class StudyAnalyticsService : IStudyAnalyticsService
@@ -446,6 +454,7 @@ public sealed class StudyAnalyticsService : IStudyAnalyticsService
_disposed = true;
StopTimerLocked();
_samplingTimer.Dispose();
_audioRecorderService.Dispose();
}
}
@@ -759,4 +768,3 @@ public sealed class StudyAnalyticsService : IStudyAnalyticsService
_lastSessionReport = null;
}
}

View File

@@ -0,0 +1,80 @@
using System;
using System.Threading.Tasks;
namespace LanMountainDesktop.Services;
internal static class UiExceptionGuard
{
public static bool IsFatalException(Exception? exception)
{
return exception is OutOfMemoryException or AccessViolationException or StackOverflowException;
}
public static void FireAndForgetGuarded(
Func<Task> action,
string actionName,
string? context = null,
Func<Exception, Task>? onHandledException = null)
{
_ = RunGuardedUiActionAsync(action, actionName, context, onHandledException);
}
public static async Task RunGuardedUiActionAsync(
Func<Task> action,
string actionName,
string? context = null,
Func<Exception, Task>? onHandledException = null)
{
ArgumentNullException.ThrowIfNull(action);
try
{
await action();
}
catch (Exception ex) when (!IsFatalException(ex))
{
LogHandledException("GuardedUiAction", actionName, ex, context, isFatal: false);
if (onHandledException is not null)
{
try
{
await onHandledException(ex);
}
catch (Exception handlerEx) when (!IsFatalException(handlerEx))
{
LogHandledException("GuardedUiActionHandler", actionName, handlerEx, context, isFatal: false);
}
}
}
}
public static string BuildContext(params (string Key, object? Value)[] parts)
{
if (parts is null || parts.Length == 0)
{
return string.Empty;
}
return string.Join(
"; ",
Array.ConvertAll(parts, part => $"{part.Key}={part.Value ?? "<null>"}"));
}
private static void LogHandledException(
string category,
string actionName,
Exception exception,
string? context,
bool isFatal)
{
var message =
$"Action={actionName}; ExceptionType={exception.GetType().FullName}; IsFatal={isFatal}; Context={context ?? string.Empty}";
if (isFatal)
{
AppLogger.Critical(category, message, exception);
return;
}
AppLogger.Warn(category, message, exception);
}
}

View File

@@ -6,9 +6,20 @@ namespace LanMountainDesktop.Services;
internal static class WindowsNativeDialogService
{
private const uint Ok = 0x00000000;
private const uint IconInformation = 0x00000040;
private const uint IconWarning = 0x00000030;
public static void ShowInformation(string caption, string message)
{
Show(caption, message, Ok | IconInformation, "NativeDialog");
}
public static void ShowWarning(string caption, string message)
{
Show(caption, message, Ok | IconWarning, "StartupDiagnostics");
}
private static void Show(string caption, string message, uint type, string logCategory)
{
if (!OperatingSystem.IsWindows())
{
@@ -17,11 +28,11 @@ internal static class WindowsNativeDialogService
try
{
_ = MessageBoxW(IntPtr.Zero, message, caption, Ok | IconWarning);
_ = MessageBoxW(IntPtr.Zero, message, caption, type);
}
catch (Exception ex)
{
AppLogger.Warn("StartupDiagnostics", "Failed to show legacy executable warning dialog.", ex);
AppLogger.Warn(logCategory, "Failed to show native dialog.", ex);
}
}

View File

@@ -6,21 +6,27 @@ using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Styling;
using AvaloniaWebView;
using LanMountainDesktop.ComponentSystem;
using LanMountainDesktop.Services;
using WebViewCore.Events;
namespace LanMountainDesktop.Views.Components;
public partial class BrowserWidget : UserControl, IDesktopComponentWidget
, IDesktopPageVisibilityAwareComponentWidget, IDisposable
public partial class BrowserWidget : UserControl, IDesktopComponentWidget,
IDesktopPageVisibilityAwareComponentWidget, IComponentPlacementContextAware, IDisposable
{
private static readonly Uri DefaultHomeUri = new("https://www.bing.com");
private double _currentCellSize = 48;
private string _componentId = BuiltInComponentIds.DesktopBrowser;
private string _placementId = string.Empty;
private bool? _isNightModeApplied;
private Uri _lastKnownUri = DefaultHomeUri;
private bool _isOnActiveDesktopPage;
private bool _isAttachedToVisualTree;
private bool _isEditMode;
private bool _isWebViewActive = true;
private bool _isWebViewFaulted;
private readonly WebView2RuntimeAvailability _runtimeAvailability;
private bool _isDisposed;
@@ -45,8 +51,8 @@ public partial class BrowserWidget : UserControl, IDesktopComponentWidget
ApplyRuntimeUnavailableState();
}
AddressTextBox.Text = DefaultHomeUri.ToString();
UpdateWebViewActiveState();
NavigateTo(DefaultHomeUri);
}
public void Dispose()
@@ -74,17 +80,15 @@ public partial class BrowserWidget : UserControl, IDesktopComponentWidget
_currentCellSize = Math.Max(1, cellSize);
RootBorder.CornerRadius = new CornerRadius(Math.Clamp(_currentCellSize * 0.34, 12, 28));
RootBorder.Padding = new Thickness(
Math.Clamp(_currentCellSize * 0.20, 8, 18));
RootBorder.Padding = new Thickness(Math.Clamp(_currentCellSize * 0.20, 8, 18));
WebViewHostBorder.CornerRadius = new CornerRadius(Math.Clamp(_currentCellSize * 0.24, 10, 22));
AddressBarBorder.CornerRadius = new CornerRadius(Math.Clamp(_currentCellSize * 0.22, 10, 20));
AddressBarBorder.Padding = new Thickness(8, 6);
var rowSpacing = 8d;
if (RootBorder.Child is Grid rootGrid)
{
rootGrid.RowSpacing = rowSpacing;
rootGrid.RowSpacing = 8d;
}
var buttonSize = Math.Clamp(_currentCellSize * 0.72, 30, 36);
@@ -111,16 +115,33 @@ public partial class BrowserWidget : UserControl, IDesktopComponentWidget
AddressTextBox.Height = buttonSize;
}
public void SetDesktopPageContext(bool isOnActivePage, bool isEditMode)
{
_isOnActiveDesktopPage = isOnActivePage;
_isEditMode = isEditMode;
UpdateWebViewActiveState();
}
public void SetComponentPlacementContext(string componentId, string? placementId)
{
_componentId = string.IsNullOrWhiteSpace(componentId)
? BuiltInComponentIds.DesktopBrowser
: componentId.Trim();
_placementId = placementId?.Trim() ?? string.Empty;
}
private void OnAttachedToVisualTree(object? sender, VisualTreeAttachmentEventArgs e)
{
_isAttachedToVisualTree = true;
ApplyTheme(force: true);
UpdateWebViewActiveState();
}
private void OnDetachedFromVisualTree(object? sender, VisualTreeAttachmentEventArgs e)
{
_isAttachedToVisualTree = false;
_isOnActiveDesktopPage = false;
UpdateWebViewActiveState();
DeactivateWebView(clearUrl: false);
}
private void OnSizeChanged(object? sender, SizeChangedEventArgs e)
@@ -202,28 +223,20 @@ public partial class BrowserWidget : UserControl, IDesktopComponentWidget
private void OnRefreshButtonClick(object? sender, RoutedEventArgs e)
{
if (!_runtimeAvailability.IsAvailable)
if (!CanUseWebView())
{
return;
}
if (!_isWebViewActive)
if (!TryReloadWebView("Refresh"))
{
return;
TryNavigate(DefaultHomeUri, "RefreshFallback");
}
if (BrowserWebView.Url is not null)
{
BrowserWebView.Reload();
return;
}
NavigateTo(DefaultHomeUri);
}
private void OnGoButtonClick(object? sender, RoutedEventArgs e)
{
if (!_runtimeAvailability.IsAvailable)
if (!CanUseWebView())
{
return;
}
@@ -233,7 +246,7 @@ public partial class BrowserWidget : UserControl, IDesktopComponentWidget
private void OnAddressTextBoxKeyDown(object? sender, KeyEventArgs e)
{
if (!_runtimeAvailability.IsAvailable)
if (!CanUseWebView())
{
return;
}
@@ -249,7 +262,7 @@ public partial class BrowserWidget : UserControl, IDesktopComponentWidget
private void NavigateFromAddressBar()
{
if (!_runtimeAvailability.IsAvailable)
if (!CanUseWebView())
{
return;
}
@@ -269,7 +282,7 @@ public partial class BrowserWidget : UserControl, IDesktopComponentWidget
AddressTextBox.Text = uri.ToString();
if (_isWebViewActive)
{
BrowserWebView.Url = uri;
TryNavigate(uri, "NavigateTo");
}
}
@@ -284,25 +297,16 @@ public partial class BrowserWidget : UserControl, IDesktopComponentWidget
AddressTextBox.Text = e.Url.ToString();
}
public void SetDesktopPageContext(bool isOnActivePage, bool isEditMode)
{
_isOnActiveDesktopPage = isOnActivePage;
_isEditMode = isEditMode;
UpdateWebViewActiveState();
}
private void UpdateWebViewActiveState()
{
if (!_runtimeAvailability.IsAvailable)
if (!_runtimeAvailability.IsAvailable || _isWebViewFaulted)
{
_isWebViewActive = false;
BrowserWebView.Url = null;
BrowserWebView.IsVisible = false;
BrowserWebView.IsHitTestVisible = false;
ApplyRuntimeUnavailableState();
return;
}
var shouldBeActive = _isOnActiveDesktopPage && !_isEditMode && IsVisible;
var shouldBeActive = _isAttachedToVisualTree && _isOnActiveDesktopPage && !_isEditMode && IsVisible;
if (_isWebViewActive == shouldBeActive)
{
return;
@@ -311,40 +315,118 @@ public partial class BrowserWidget : UserControl, IDesktopComponentWidget
_isWebViewActive = shouldBeActive;
if (!_isWebViewActive)
{
if (BrowserWebView.Url is Uri currentUri)
{
_lastKnownUri = currentUri;
}
DeactivateWebView(clearUrl: false);
return;
}
BrowserWebView.IsHitTestVisible = false;
BrowserWebView.IsVisible = false;
BrowserWebView.Url = null;
ActivateWebView();
}
private void ActivateWebView()
{
if (_isWebViewFaulted || !_runtimeAvailability.IsAvailable)
{
ApplyRuntimeUnavailableState();
return;
}
BrowserWebView.IsVisible = true;
BrowserWebView.IsHitTestVisible = true;
BrowserWebView.Url = _lastKnownUri;
RefreshButton.IsEnabled = true;
GoButton.IsEnabled = true;
AddressTextBox.IsEnabled = true;
UnavailableOverlay.IsVisible = false;
TryNavigate(_lastKnownUri, "Activate");
}
private void DeactivateWebView(bool clearUrl)
{
BrowserWebView.IsHitTestVisible = false;
BrowserWebView.IsVisible = false;
if (clearUrl)
{
TryClearWebViewUrl();
}
}
private bool TryReloadWebView(string action)
{
try
{
BrowserWebView.Reload();
return true;
}
catch (Exception ex) when (!UiExceptionGuard.IsFatalException(ex))
{
EnterFaultedState(action, ex);
return false;
}
}
private bool TryNavigate(Uri uri, string action)
{
try
{
BrowserWebView.Url = uri;
return true;
}
catch (Exception ex) when (!UiExceptionGuard.IsFatalException(ex))
{
EnterFaultedState(action, ex);
return false;
}
}
private void TryClearWebViewUrl()
{
try
{
BrowserWebView.Url = null;
}
catch
{
// Best-effort cleanup only.
}
}
private bool CanUseWebView()
{
return _runtimeAvailability.IsAvailable && !_isWebViewFaulted && _isWebViewActive;
}
private void ApplyRuntimeUnavailableState()
{
_isWebViewActive = false;
BrowserWebView.Url = null;
BrowserWebView.IsVisible = false;
BrowserWebView.IsHitTestVisible = false;
RefreshButton.IsEnabled = false;
GoButton.IsEnabled = false;
AddressTextBox.IsEnabled = false;
AddressTextBox.Text = string.Empty;
AddressTextBox.Text = _lastKnownUri.ToString();
UnavailableMessageTextBlock.Text = string.IsNullOrWhiteSpace(_runtimeAvailability.Message)
? "WebView runtime unavailable."
: _runtimeAvailability.Message;
UnavailableMessageTextBlock.Text = _isWebViewFaulted
? "The browser component is temporarily unavailable. Restart the app to retry."
: string.IsNullOrWhiteSpace(_runtimeAvailability.Message)
? "WebView runtime unavailable."
: _runtimeAvailability.Message;
UnavailableOverlay.IsVisible = true;
}
private void EnterFaultedState(string action, Exception ex)
{
_isWebViewFaulted = true;
_isWebViewActive = false;
AppLogger.Warn(
"BrowserWidget",
$"Browser component faulted. Action={action}; ComponentId={_componentId}; PlacementId={_placementId}; RuntimeAvailability={_runtimeAvailability.IsAvailable}; RuntimeVersion={_runtimeAvailability.Version ?? string.Empty}; CurrentUrl={_lastKnownUri}",
ex);
TryClearWebViewUrl();
ApplyRuntimeUnavailableState();
}
private static Uri? TryNormalizeUri(string? rawText)
{
if (string.IsNullOrWhiteSpace(rawText))

View File

@@ -0,0 +1,226 @@
using System;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using LanMountainDesktop.Services;
namespace LanMountainDesktop.Views.Components;
internal sealed class DesktopComponentFailureView : UserControl, IDesktopComponentWidget
{
private readonly Border _rootBorder;
private readonly TextBlock _titleBlock;
private readonly TextBlock _summaryBlock;
private readonly TextBlock _statusBlock;
private readonly Button _toggleDetailsButton;
private readonly Button _copyReportButton;
private readonly Border _detailsBorder;
private readonly TextBox _reportTextBox;
private readonly string _componentId;
private readonly string? _placementId;
private readonly string _reportText;
private bool _detailsVisible;
public DesktopComponentFailureView(
string componentName,
string componentId,
string? placementId,
int? pageIndex,
string action,
Exception exception)
{
_componentId = componentId;
_placementId = placementId;
_reportText = BuildReport(componentName, componentId, placementId, pageIndex, action, exception);
_titleBlock = new TextBlock
{
Text = string.IsNullOrWhiteSpace(componentName) ? "组件暂时不可用" : componentName,
FontWeight = FontWeight.SemiBold,
TextWrapping = TextWrapping.Wrap
};
_summaryBlock = new TextBlock
{
Text = "该组件已临时停用,并由信息占位保留原位置。你可以展开详情或复制错误报告。",
Foreground = CreateBrush("#FFD6DEE9"),
TextWrapping = TextWrapping.Wrap
};
_statusBlock = new TextBlock
{
IsVisible = false,
Foreground = CreateBrush("#FF93C5FD"),
TextWrapping = TextWrapping.Wrap
};
_toggleDetailsButton = CreateButton("查看错误信息", OnToggleDetailsClick);
_copyReportButton = CreateButton("复制错误报告", OnCopyReportClick);
_reportTextBox = new TextBox
{
Text = _reportText,
IsReadOnly = true,
AcceptsReturn = true,
TextWrapping = TextWrapping.Wrap,
MinHeight = 96,
MaxHeight = 220,
Background = CreateBrush("#CC0F172A"),
Foreground = CreateBrush("#FFE2E8F0"),
BorderThickness = new Thickness(0),
Padding = new Thickness(8)
};
_detailsBorder = new Border
{
IsVisible = false,
Background = CreateBrush("#660F172A"),
BorderBrush = CreateBrush("#33475569"),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(12),
Child = _reportTextBox
};
_rootBorder = new Border
{
Background = CreateBrush("#D91E293B"),
BorderBrush = CreateBrush("#336B7280"),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(18),
Padding = new Thickness(14),
ClipToBounds = true,
Child = new StackPanel
{
Spacing = 8,
VerticalAlignment = VerticalAlignment.Center,
Children =
{
_titleBlock,
_summaryBlock,
new WrapPanel
{
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Left,
ItemSpacing = 8,
LineSpacing = 8,
Children =
{
_toggleDetailsButton,
_copyReportButton
}
},
_statusBlock,
_detailsBorder
}
}
};
Content = _rootBorder;
ApplyCellSize(48);
}
public void ApplyCellSize(double cellSize)
{
var normalized = Math.Max(1, cellSize);
_rootBorder.CornerRadius = new CornerRadius(Math.Clamp(normalized * 0.24, 12, 24));
_rootBorder.Padding = new Thickness(Math.Clamp(normalized * 0.24, 10, 18));
_titleBlock.FontSize = Math.Clamp(normalized * 0.36, 14, 22);
_summaryBlock.FontSize = Math.Clamp(normalized * 0.24, 11, 15);
_statusBlock.FontSize = Math.Clamp(normalized * 0.22, 10, 13);
_toggleDetailsButton.FontSize = Math.Clamp(normalized * 0.22, 10, 14);
_copyReportButton.FontSize = Math.Clamp(normalized * 0.22, 10, 14);
_toggleDetailsButton.Padding = new Thickness(Math.Clamp(normalized * 0.18, 8, 12), 6);
_copyReportButton.Padding = new Thickness(Math.Clamp(normalized * 0.18, 8, 12), 6);
_reportTextBox.FontSize = Math.Clamp(normalized * 0.2, 10, 13);
_reportTextBox.MaxHeight = Math.Clamp(normalized * 5.2, 120, 260);
}
private static Button CreateButton(string text, EventHandler<RoutedEventArgs> clickHandler)
{
var button = new Button
{
Content = text,
Background = CreateBrush("#80334155"),
Foreground = Brushes.White,
BorderBrush = CreateBrush("#335B6575"),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(999),
HorizontalAlignment = HorizontalAlignment.Left
};
button.Click += clickHandler;
return button;
}
private void OnToggleDetailsClick(object? sender, RoutedEventArgs e)
{
_detailsVisible = !_detailsVisible;
_detailsBorder.IsVisible = _detailsVisible;
_toggleDetailsButton.Content = _detailsVisible ? "隐藏错误信息" : "查看错误信息";
UpdateStatus(null);
}
private void OnCopyReportClick(object? sender, RoutedEventArgs e)
{
UiExceptionGuard.FireAndForgetGuarded(
CopyReportAsync,
"DesktopComponentFailureView.CopyReport",
UiExceptionGuard.BuildContext(
("ComponentId", _componentId),
("PlacementId", _placementId)));
}
private async Task CopyReportAsync()
{
var topLevel = TopLevel.GetTopLevel(this);
var clipboard = topLevel?.Clipboard;
if (clipboard is null)
{
UpdateStatus("当前环境不支持复制错误报告。");
return;
}
await clipboard.SetTextAsync(_reportText);
UpdateStatus("错误报告已复制到剪贴板。");
}
private void UpdateStatus(string? message)
{
_statusBlock.Text = message ?? string.Empty;
_statusBlock.IsVisible = !string.IsNullOrWhiteSpace(message);
}
private static string BuildReport(
string componentName,
string componentId,
string? placementId,
int? pageIndex,
string action,
Exception exception)
{
var version = Assembly.GetEntryAssembly()?.GetName().Version?.ToString() ?? "unknown";
var builder = new StringBuilder();
builder.AppendLine("LanMountainDesktop Component Failure Report");
builder.AppendLine($"GeneratedAt: {DateTimeOffset.Now:O}");
builder.AppendLine($"AppVersion: {version}");
builder.AppendLine($"Action: {action}");
builder.AppendLine($"ComponentName: {componentName}");
builder.AppendLine($"ComponentId: {componentId}");
builder.AppendLine($"PlacementId: {placementId ?? string.Empty}");
builder.AppendLine($"PageIndex: {pageIndex?.ToString() ?? string.Empty}");
builder.AppendLine($"ExceptionType: {exception.GetType().FullName}");
builder.AppendLine($"ExceptionMessage: {exception.Message}");
builder.AppendLine();
builder.AppendLine(exception.ToString());
return builder.ToString();
}
private static IBrush CreateBrush(string colorHex)
{
return new SolidColorBrush(Color.Parse(colorHex));
}
}

View File

@@ -1522,7 +1522,7 @@ public partial class MainWindow
placement.PlacementId = Guid.NewGuid().ToString("N");
}
var component = CreateDesktopComponentControl(placement.ComponentId, placement.PlacementId);
var component = CreateDesktopComponentControl(placement.ComponentId, placement.PlacementId, placement.PageIndex);
if (component is null)
{
return null;
@@ -1956,23 +1956,54 @@ public partial class MainWindow
return onLeft || onRight || onTop || onBottom;
}
private Control? CreateDesktopComponentControl(string componentId, string? placementId = null)
private Control? CreateDesktopComponentControl(string componentId, string? placementId = null, int? pageIndex = null)
{
if (!_componentRuntimeRegistry.TryGetDescriptor(componentId, out var runtimeDescriptor))
{
return null;
}
var component = runtimeDescriptor.CreateControl(
_currentDesktopCellSize,
_timeZoneService,
_weatherDataService,
_recommendationInfoService,
_calculatorDataService,
_componentSettingsService,
placementId);
component.Classes.Add(DesktopComponentClass);
return component;
return CreateDesktopComponentControl(runtimeDescriptor, _currentDesktopCellSize, placementId, pageIndex, "DesktopSurface");
}
private Control? CreateDesktopComponentControl(
DesktopComponentRuntimeDescriptor runtimeDescriptor,
double cellSize,
string? placementId,
int? pageIndex,
string action)
{
try
{
var component = runtimeDescriptor.CreateControl(
cellSize,
_timeZoneService,
_weatherDataService,
_recommendationInfoService,
_calculatorDataService,
_componentSettingsService,
placementId);
component.Classes.Add(DesktopComponentClass);
return component;
}
catch (Exception ex) when (!UiExceptionGuard.IsFatalException(ex))
{
AppLogger.Warn(
"ComponentRuntime",
$"Action={action}; ComponentId={runtimeDescriptor.Definition.Id}; PlacementId={placementId ?? string.Empty}; PageIndex={pageIndex?.ToString() ?? string.Empty}; ExceptionType={ex.GetType().FullName}; IsFatal=false",
ex);
var failureView = new DesktopComponentFailureView(
runtimeDescriptor.Definition.DisplayName,
runtimeDescriptor.Definition.Id,
placementId,
pageIndex,
action,
ex);
failureView.ApplyCellSize(cellSize);
failureView.Classes.Add(DesktopComponentClass);
return failureView;
}
}
private void CollapseComponentLibraryPanel()
@@ -3113,13 +3144,16 @@ public partial class MainWindow
var previewHeight = previewSpan.HeightCells * previewCellSize;
var renderCellSize = Math.Clamp(previewCellSize * 1.15, 26, 110);
var previewControl = descriptor.CreateControl(
var previewControl = CreateDesktopComponentControl(
descriptor,
renderCellSize,
_timeZoneService,
_weatherDataService,
_recommendationInfoService,
_calculatorDataService,
_componentSettingsService);
placementId: null,
pageIndex: null,
action: "ComponentLibraryPreview");
if (previewControl is null)
{
continue;
}
// Component library previews must stay non-interactive so drag gesture is reliable.
previewControl.IsHitTestVisible = false;
previewControl.Focusable = false;

View File

@@ -1195,11 +1195,22 @@ public partial class MainWindow
var restoreButton = new Button
{
Content = L("settings.launcher.restore_button", "Unhide"),
MinWidth = 110,
Padding = new Thickness(12, 6),
Width = 36,
Height = 36,
Padding = new Thickness(0),
Background = Brushes.Transparent,
BorderThickness = new Thickness(0),
Tag = new LauncherHiddenItemToken(hiddenItem.Kind, hiddenItem.Key)
};
restoreButton.Content = new FluentIcons.Avalonia.Fluent.SymbolIcon
{
Symbol = FluentIcons.Common.Symbol.Eye,
IconVariant = FluentIcons.Common.IconVariant.Regular,
FontSize = 18,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
ToolTip.SetTip(restoreButton, L("settings.launcher.restore_button", "Unhide"));
restoreButton.Click += OnRestoreLauncherHiddenItemClick;
return new SettingsExpanderItem

View File

@@ -2,6 +2,7 @@ using System.Threading.Tasks;
using Avalonia.Interactivity;
using Avalonia.Threading;
using FluentAvalonia.UI.Controls;
using LanMountainDesktop.PluginSdk;
using LanMountainDesktop.Services;
namespace LanMountainDesktop.Views;
@@ -77,7 +78,9 @@ public partial class MainWindow
var result = await dialog.ShowAsync(this);
if (result == ContentDialogResult.Primary)
{
if (!AppRestartService.TryRestartApplication())
if (App.CurrentHostApplicationLifecycle?.TryRestart(new HostApplicationLifecycleRequest(
Source: nameof(MainWindow),
Reason: "User confirmed a pending restart prompt.")) != true)
{
UpdatePendingRestartDock();
}

View File

@@ -158,6 +158,7 @@ public partial class MainWindow
}
ApplyTaskbarActionVisibility(GetCurrentTaskbarContext());
UpdateVideoWallpaperPreviewVisibility();
}
private void OnNightModeChecked(object? sender, RoutedEventArgs e)
@@ -344,6 +345,7 @@ public partial class MainWindow
var placement = GetSelectedWallpaperPlacement();
DesktopWallpaperLayer.Background = CreateWallpaperBrush(_wallpaperBitmap, placement, false);
WallpaperPreviewViewport.Background = CreateWallpaperBrush(_wallpaperBitmap, placement, true);
UpdateVideoWallpaperPreviewVisibility();
}
private void UpdateWallpaperDisplay()
@@ -628,12 +630,99 @@ public partial class MainWindow
EnableHardwareDecoding = false
};
}
}
if (_previewVideoWallpaperPlayer is null && WallpaperPreviewVideoView is not null)
private void EnsureDesktopVideoFrameRefreshTimer()
{
if (_desktopVideoFrameRefreshTimer is not null)
{
_previewVideoWallpaperPlayer = new MediaPlayer(_libVlc);
WallpaperPreviewVideoView.MediaPlayer = _previewVideoWallpaperPlayer;
return;
}
_desktopVideoFrameRefreshTimer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(33)
};
_desktopVideoFrameRefreshTimer.Tick += OnDesktopVideoFrameRefreshTimerTick;
}
private void StartDesktopVideoFrameRefreshTimer()
{
EnsureDesktopVideoFrameRefreshTimer();
if (_desktopVideoFrameRefreshTimer?.IsEnabled == false)
{
_desktopVideoFrameRefreshTimer.Start();
}
}
private void StopDesktopVideoFrameRefreshTimer()
{
if (_desktopVideoFrameRefreshTimer?.IsEnabled == true)
{
_desktopVideoFrameRefreshTimer.Stop();
}
}
private void OnDesktopVideoFrameRefreshTimerTick(object? sender, EventArgs e)
{
PushDesktopVideoFrameToWallpaperImage();
}
private void UpdateVideoWallpaperPreviewVisibility()
{
var shouldShowPreview =
_wallpaperMediaType == WallpaperMediaType.Video &&
_isSettingsOpen &&
SettingsPage.IsVisible &&
WallpaperSettingsPanel.IsVisible &&
_wallpaperPreviewSnapshotBitmap is not null;
WallpaperPreviewVideoImage.IsVisible = shouldShowPreview;
if (shouldShowPreview && !ReferenceEquals(WallpaperPreviewVideoImage.Source, _wallpaperPreviewSnapshotBitmap))
{
WallpaperPreviewVideoImage.Source = _wallpaperPreviewSnapshotBitmap;
}
}
private void InvalidateVideoWallpaperPreviewSnapshot()
{
_wallpaperPreviewSnapshotPending = true;
_wallpaperPreviewSnapshotBitmap?.Dispose();
_wallpaperPreviewSnapshotBitmap = null;
WallpaperPreviewVideoImage.Source = null;
}
private void CaptureVideoWallpaperPreviewSnapshotFromStagingBuffer()
{
if (!_wallpaperPreviewSnapshotPending ||
_desktopVideoStagingBuffer is null ||
_desktopVideoFrameWidth <= 0 ||
_desktopVideoFrameHeight <= 0 ||
_desktopVideoFramePitch <= 0)
{
return;
}
_wallpaperPreviewSnapshotBitmap?.Dispose();
_wallpaperPreviewSnapshotBitmap = new WriteableBitmap(
new PixelSize(_desktopVideoFrameWidth, _desktopVideoFrameHeight),
new Vector(96, 96),
PixelFormat.Bgra8888,
AlphaFormat.Opaque);
using var framebuffer = _wallpaperPreviewSnapshotBitmap.Lock();
var rows = Math.Min(framebuffer.Size.Height, _desktopVideoFrameHeight);
var bytesPerRow = Math.Min(framebuffer.RowBytes, _desktopVideoFramePitch);
for (var row = 0; row < rows; row++)
{
var sourceOffset = row * _desktopVideoFramePitch;
var destinationPtr = IntPtr.Add(framebuffer.Address, row * framebuffer.RowBytes);
Marshal.Copy(_desktopVideoStagingBuffer, sourceOffset, destinationPtr, bytesPerRow);
}
_wallpaperPreviewSnapshotPending = false;
WallpaperPreviewVideoImage.Source = _wallpaperPreviewSnapshotBitmap;
UpdateVideoWallpaperPreviewVisibility();
}
private bool ConfigureDesktopVideoRenderer()
@@ -685,6 +774,7 @@ public partial class MainWindow
(uint)_desktopVideoFrameHeight,
(uint)_desktopVideoFramePitch);
DesktopVideoWallpaperImage.Source = _desktopVideoBitmap;
InvalidateVideoWallpaperPreviewSnapshot();
return true;
}
catch
@@ -745,31 +835,6 @@ public partial class MainWindow
private void OnDesktopVideoFrameDisplay(IntPtr opaque, IntPtr picture)
{
Interlocked.Exchange(ref _desktopVideoFrameDirtyFlag, 1);
ScheduleDesktopVideoFrameUiRefresh();
}
private void ScheduleDesktopVideoFrameUiRefresh()
{
if (Interlocked.Exchange(ref _desktopVideoFrameUiRefreshScheduledFlag, 1) == 1)
{
return;
}
Dispatcher.UIThread.Post(() =>
{
try
{
PushDesktopVideoFrameToWallpaperImage();
}
finally
{
Interlocked.Exchange(ref _desktopVideoFrameUiRefreshScheduledFlag, 0);
if (Volatile.Read(ref _desktopVideoFrameDirtyFlag) == 1)
{
ScheduleDesktopVideoFrameUiRefresh();
}
}
}, DispatcherPriority.Render);
}
private void PushDesktopVideoFrameToWallpaperImage()
@@ -812,18 +877,22 @@ public partial class MainWindow
{
DesktopVideoWallpaperImage.Source = _desktopVideoBitmap;
}
CaptureVideoWallpaperPreviewSnapshotFromStagingBuffer();
}
private void ReleaseDesktopVideoRendererResources()
{
Interlocked.Exchange(ref _desktopVideoFrameDirtyFlag, 0);
Interlocked.Exchange(ref _desktopVideoFrameUiRefreshScheduledFlag, 0);
if (DesktopVideoWallpaperImage is not null)
{
DesktopVideoWallpaperImage.Source = null;
}
InvalidateVideoWallpaperPreviewSnapshot();
WallpaperPreviewVideoImage.Source = null;
_desktopVideoBitmap?.Dispose();
_desktopVideoBitmap = null;
_desktopVideoStagingBuffer = null;
@@ -855,10 +924,8 @@ public partial class MainWindow
{
EnsureVideoWallpaperPlayers();
if (_videoWallpaperPlayer is null ||
_previewVideoWallpaperPlayer is null ||
_libVlc is null ||
DesktopVideoWallpaperImage is null ||
WallpaperPreviewVideoView is null)
DesktopVideoWallpaperImage is null)
{
_wallpaperStatus = L("settings.wallpaper.video_player_unavailable", "Video player is unavailable.");
StopVideoWallpaper();
@@ -873,15 +940,13 @@ public partial class MainWindow
}
_videoWallpaperMedia?.Dispose();
_previewVideoWallpaperMedia?.Dispose();
_videoWallpaperMedia = new Media(_libVlc, new Uri(videoPath));
_previewVideoWallpaperMedia = new Media(_libVlc, new Uri(videoPath));
_videoWallpaperMedia.AddOption(":input-repeat=65535");
_previewVideoWallpaperMedia.AddOption(":input-repeat=65535");
InvalidateVideoWallpaperPreviewSnapshot();
_videoWallpaperPlayer.Play(_videoWallpaperMedia);
_previewVideoWallpaperPlayer.Play(_previewVideoWallpaperMedia);
StartDesktopVideoFrameRefreshTimer();
DesktopVideoWallpaperImage.IsVisible = true;
WallpaperPreviewVideoView.IsVisible = true;
UpdateVideoWallpaperPreviewVisibility();
}
catch (Exception ex)
{
@@ -897,26 +962,17 @@ public partial class MainWindow
DesktopVideoWallpaperImage.IsVisible = false;
}
if (WallpaperPreviewVideoView is not null)
{
WallpaperPreviewVideoView.IsVisible = false;
}
WallpaperPreviewVideoImage.IsVisible = false;
if (_videoWallpaperPlayer is not null)
{
_videoWallpaperPlayer.Stop();
}
if (_previewVideoWallpaperPlayer is not null)
{
_previewVideoWallpaperPlayer.Stop();
}
StopDesktopVideoFrameRefreshTimer();
ReleaseDesktopVideoRendererResources();
_videoWallpaperMedia?.Dispose();
_videoWallpaperMedia = null;
_previewVideoWallpaperMedia?.Dispose();
_previewVideoWallpaperMedia = null;
}
private void PersistSettings()
@@ -2379,7 +2435,14 @@ public partial class MainWindow
_isSettingsOpen = true;
UpdateDesktopPageAwareComponentContext();
UpdateAdaptiveTextSystem();
ApplyWallpaperBrush();
if (_wallpaperMediaType == WallpaperMediaType.Video)
{
UpdateVideoWallpaperPreviewVisibility();
}
else
{
ApplyWallpaperBrush();
}
ApplyTaskbarActionVisibility(GetCurrentTaskbarContext());
if (_settingsContentPanelTransform is not null)
{
@@ -2387,6 +2450,7 @@ public partial class MainWindow
}
SettingsPage.IsVisible = true;
SettingsPage.Opacity = 0;
UpdateVideoWallpaperPreviewVisibility();
UpdateSettingsViewportInsets(Math.Max(1, _currentDesktopCellSize));
UpdateWallpaperPreviewLayout();
@@ -2416,7 +2480,11 @@ public partial class MainWindow
_isSettingsOpen = false;
UpdateDesktopPageAwareComponentContext();
UpdateAdaptiveTextSystem();
ApplyWallpaperBrush();
UpdateVideoWallpaperPreviewVisibility();
if (_wallpaperMediaType != WallpaperMediaType.Video)
{
ApplyWallpaperBrush();
}
ApplyTaskbarActionVisibility(GetCurrentTaskbarContext());
if (immediate)
@@ -2608,7 +2676,7 @@ public partial class MainWindow
internal Border WallpaperPreviewHost => WallpaperSettingsPanel.FindControl<Border>("WallpaperPreviewHost")!;
internal Border WallpaperPreviewFrame => WallpaperSettingsPanel.FindControl<Border>("WallpaperPreviewFrame")!;
internal Border WallpaperPreviewViewport => WallpaperSettingsPanel.FindControl<Border>("WallpaperPreviewViewport")!;
internal LibVLCSharp.Avalonia.VideoView? WallpaperPreviewVideoView => WallpaperSettingsPanel.FindControl<LibVLCSharp.Avalonia.VideoView>("WallpaperPreviewVideoView");
internal Image WallpaperPreviewVideoImage => WallpaperSettingsPanel.FindControl<Image>("WallpaperPreviewVideoImage")!;
internal Grid WallpaperPreviewGrid => WallpaperSettingsPanel.FindControl<Grid>("WallpaperPreviewGrid")!;
internal Border WallpaperPreviewTopStatusBarHost => WallpaperSettingsPanel.FindControl<Border>("WallpaperPreviewTopStatusBarHost")!;
internal StackPanel WallpaperPreviewTopStatusComponentsPanel => WallpaperSettingsPanel.FindControl<StackPanel>("WallpaperPreviewTopStatusComponentsPanel")!;

View File

@@ -0,0 +1,58 @@
using System.Threading.Tasks;
using Avalonia.Threading;
using FluentAvalonia.UI.Controls;
using LanMountainDesktop.Services;
namespace LanMountainDesktop.Views;
public partial class MainWindow
{
private bool _isSingleInstancePromptVisible;
internal void ShowSingleInstanceNotice()
{
void ShowPrompt()
{
UiExceptionGuard.FireAndForgetGuarded(
ShowSingleInstanceNoticeCoreAsync,
"MainWindow.ShowSingleInstanceNotice");
}
if (Dispatcher.UIThread.CheckAccess())
{
ShowPrompt();
return;
}
Dispatcher.UIThread.Post(ShowPrompt, DispatcherPriority.Send);
}
private async Task ShowSingleInstanceNoticeCoreAsync()
{
if (_isSingleInstancePromptVisible)
{
return;
}
_isSingleInstancePromptVisible = true;
try
{
var dialog = new ContentDialog
{
Title = L("single_instance.notice.title", "应用已经运行"),
Content = L(
"single_instance.notice.description",
"应用已经运行,无需多次点击打开。"),
PrimaryButtonText = L("single_instance.notice.button", "确定"),
DefaultButton = ContentDialogButton.Primary
};
await dialog.ShowAsync(this);
}
finally
{
_isSingleInstancePromptVisible = false;
}
}
}

View File

@@ -1,11 +1,12 @@
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Threading;
using LanMountainDesktop.Models;
using LanMountainDesktop.PluginSdk;
using LanMountainDesktop.Services;
namespace LanMountainDesktop.Views;
@@ -357,7 +358,8 @@ public partial class MainWindow
{
FileName = installerPath,
WorkingDirectory = Path.GetDirectoryName(installerPath) ?? Environment.CurrentDirectory,
UseShellExecute = true
UseShellExecute = true,
Verb = "runas"
});
_updateStatusText = L(
@@ -365,7 +367,16 @@ public partial class MainWindow
"Installer started. The app will close for update.");
UpdateUpdatePanelState();
Dispatcher.UIThread.Post(Close, DispatcherPriority.Background);
_ = App.CurrentHostApplicationLifecycle?.TryExit(new HostApplicationLifecycleRequest(
Source: nameof(MainWindow),
Reason: "Update installer started successfully."));
}
catch (Win32Exception ex) when (ex.NativeErrorCode == 1223)
{
_updateStatusText = L(
"settings.update.status_elevation_cancelled",
"Administrator permission was not granted. Update was cancelled.");
UpdateUpdatePanelState();
}
catch (Exception ex)
{

View File

@@ -469,51 +469,53 @@
</ScrollViewer>
</ui:NavigationView>
<Border x:Name="PendingRestartDock"
Grid.Row="1"
IsVisible="False"
Classes="glass-panel"
CornerRadius="18"
Padding="14,12">
<Grid ColumnDefinitions="Auto,*,Auto"
ColumnSpacing="12">
<Border Width="34"
Height="34"
CornerRadius="17"
Background="{DynamicResource AdaptiveAccentBrush}">
<fi:FluentIcon Icon="ArrowSync"
IconVariant="Regular"
FontSize="16"
Foreground="White"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
<StackPanel Grid.Column="1"
Spacing="2"
VerticalAlignment="Center">
<TextBlock x:Name="PendingRestartDockTitleTextBlock"
FontSize="13"
FontWeight="SemiBold"
Text="Restart required" />
<TextBlock x:Name="PendingRestartDockDescriptionTextBlock"
TextWrapping="Wrap"
Foreground="{DynamicResource AdaptiveTextSecondaryBrush}"
Text="Your changes will apply after restarting the app." />
</StackPanel>
<Button x:Name="PendingRestartDockButton"
Grid.Column="2"
Padding="14,8"
Click="OnPendingRestartDockButtonClick">
<StackPanel Orientation="Horizontal" Spacing="8">
<StackPanel Grid.Row="1"
Spacing="12">
<Border x:Name="PendingRestartDock"
IsVisible="False"
Classes="glass-panel"
CornerRadius="18"
Padding="14,12">
<Grid ColumnDefinitions="Auto,*,Auto"
ColumnSpacing="12">
<Border Width="34"
Height="34"
CornerRadius="17"
Background="{DynamicResource AdaptiveAccentBrush}">
<fi:FluentIcon Icon="ArrowSync"
IconVariant="Regular" />
<TextBlock x:Name="PendingRestartDockButtonTextBlock"
VerticalAlignment="Center"
Text="Restart app" />
IconVariant="Regular"
FontSize="16"
Foreground="White"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
<StackPanel Grid.Column="1"
Spacing="2"
VerticalAlignment="Center">
<TextBlock x:Name="PendingRestartDockTitleTextBlock"
FontSize="13"
FontWeight="SemiBold"
Text="Restart required" />
<TextBlock x:Name="PendingRestartDockDescriptionTextBlock"
TextWrapping="Wrap"
Foreground="{DynamicResource AdaptiveTextSecondaryBrush}"
Text="Your changes will apply after restarting the app." />
</StackPanel>
</Button>
</Grid>
</Border>
<Button x:Name="PendingRestartDockButton"
Grid.Column="2"
Padding="14,8"
Click="OnPendingRestartDockButtonClick">
<StackPanel Orientation="Horizontal" Spacing="8">
<fi:FluentIcon Icon="ArrowSync"
IconVariant="Regular" />
<TextBlock x:Name="PendingRestartDockButtonTextBlock"
VerticalAlignment="Center"
Text="Restart app" />
</StackPanel>
</Button>
</Grid>
</Border>
</StackPanel>
</Grid>
</Border>
</Border>

View File

@@ -124,21 +124,21 @@ public partial class MainWindow : Window
private LibVLC? _libVlc;
private MediaPlayer? _videoWallpaperPlayer;
private Media? _videoWallpaperMedia;
private MediaPlayer? _previewVideoWallpaperPlayer;
private Media? _previewVideoWallpaperMedia;
private readonly object _desktopVideoFrameSync = new();
private MediaPlayer.LibVLCVideoLockCb? _desktopVideoLockCallback;
private MediaPlayer.LibVLCVideoUnlockCb? _desktopVideoUnlockCallback;
private MediaPlayer.LibVLCVideoDisplayCb? _desktopVideoDisplayCallback;
private DispatcherTimer? _desktopVideoFrameRefreshTimer;
private IntPtr _desktopVideoFrameBufferPtr;
private byte[]? _desktopVideoStagingBuffer;
private WriteableBitmap? _desktopVideoBitmap;
private WriteableBitmap? _wallpaperPreviewSnapshotBitmap;
private int _desktopVideoFrameWidth;
private int _desktopVideoFrameHeight;
private int _desktopVideoFramePitch;
private int _desktopVideoFrameBufferSize;
private int _desktopVideoFrameDirtyFlag;
private int _desktopVideoFrameUiRefreshScheduledFlag;
private bool _wallpaperPreviewSnapshotPending;
private string? _wallpaperPath;
private string _wallpaperStatus = "Current background uses solid color.";
private IReadOnlyList<Color> _recommendedColors = Array.Empty<Color>();
@@ -384,15 +384,15 @@ public partial class MainWindow : Window
{
PersistSettings();
StopVideoWallpaper();
_previewVideoWallpaperMedia?.Dispose();
_previewVideoWallpaperMedia = null;
_previewVideoWallpaperPlayer?.Dispose();
_previewVideoWallpaperPlayer = null;
DisposeLauncherResources();
_videoWallpaperMedia?.Dispose();
_videoWallpaperMedia = null;
_videoWallpaperPlayer?.Dispose();
_videoWallpaperPlayer = null;
_desktopVideoFrameRefreshTimer?.Stop();
_desktopVideoFrameRefreshTimer = null;
_wallpaperPreviewSnapshotBitmap?.Dispose();
_wallpaperPreviewSnapshotBitmap = null;
_libVlc?.Dispose();
_libVlc = null;
if (_weatherDataService is IDisposable weatherServiceDisposable)

View File

@@ -6,7 +6,6 @@
xmlns:fi="using:FluentIcons.Avalonia"
xmlns:ic="using:FluentIcons.Avalonia.Fluent"
xmlns:comp="using:LanMountainDesktop.Views.Components"
xmlns:vlc="clr-namespace:LibVLCSharp.Avalonia;assembly=LibVLCSharp.Avalonia"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="600"
x:Class="LanMountainDesktop.Views.SettingsPages.WallpaperSettingsPage">
<Grid x:Name="WallpaperSettingsPanel"
@@ -37,11 +36,12 @@
CornerRadius="12"
Background="#30111827">
<Grid>
<vlc:VideoView x:Name="WallpaperPreviewVideoView"
IsVisible="False"
IsHitTestVisible="False"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" />
<Image x:Name="WallpaperPreviewVideoImage"
IsVisible="False"
IsHitTestVisible="False"
Stretch="UniformToFill"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" />
<Grid x:Name="WallpaperPreviewGrid"
HorizontalAlignment="Center"

View File

@@ -1,7 +1,6 @@
using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using LibVLCSharp.Avalonia;
namespace LanMountainDesktop.Views;
public partial class SettingsWindow
@@ -14,7 +13,7 @@ public partial class SettingsWindow
internal Border WallpaperPreviewHost => WallpaperSettingsPanel.FindControl<Border>("WallpaperPreviewHost")!;
internal Border WallpaperPreviewFrame => WallpaperSettingsPanel.FindControl<Border>("WallpaperPreviewFrame")!;
internal Border WallpaperPreviewViewport => WallpaperSettingsPanel.FindControl<Border>("WallpaperPreviewViewport")!;
internal LibVLCSharp.Avalonia.VideoView? WallpaperPreviewVideoView => WallpaperSettingsPanel.FindControl<LibVLCSharp.Avalonia.VideoView>("WallpaperPreviewVideoView");
internal Image WallpaperPreviewVideoImage => WallpaperSettingsPanel.FindControl<Image>("WallpaperPreviewVideoImage")!;
internal Grid WallpaperPreviewGrid => WallpaperSettingsPanel.FindControl<Grid>("WallpaperPreviewGrid")!;
internal Border WallpaperPreviewTopStatusBarHost => WallpaperSettingsPanel.FindControl<Border>("WallpaperPreviewTopStatusBarHost")!;
internal StackPanel WallpaperPreviewTopStatusComponentsPanel => WallpaperSettingsPanel.FindControl<StackPanel>("WallpaperPreviewTopStatusComponentsPanel")!;

View File

@@ -29,6 +29,8 @@ public partial class SettingsWindow
_previewVideoWallpaperPlayer = null;
_previewVideoWallpaperMedia?.Dispose();
_previewVideoWallpaperMedia = null;
_previewVideoFrameRefreshTimer?.Stop();
_previewVideoFrameRefreshTimer = null;
_libVlc?.Dispose();
_libVlc = null;
@@ -254,6 +256,7 @@ public partial class SettingsWindow
}
ApplyTaskbarActionVisibility(GetCurrentTaskbarContext());
SyncVideoWallpaperPreviewPlayback();
}
private void PersistSettings()

View File

@@ -2,6 +2,7 @@ using System.Threading.Tasks;
using Avalonia.Interactivity;
using Avalonia.Threading;
using FluentAvalonia.UI.Controls;
using LanMountainDesktop.PluginSdk;
using LanMountainDesktop.Services;
namespace LanMountainDesktop.Views;
@@ -77,7 +78,9 @@ public partial class SettingsWindow
var result = await dialog.ShowAsync(this);
if (result == ContentDialogResult.Primary)
{
if (!AppRestartService.TryRestartApplication())
if (App.CurrentHostApplicationLifecycle?.TryRestart(new HostApplicationLifecycleRequest(
Source: nameof(SettingsWindow),
Reason: "User confirmed a pending restart prompt from settings.")) != true)
{
UpdatePendingRestartDock();
}

View File

@@ -1,13 +1,12 @@
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Interactivity;
using Avalonia.Threading;
using LanMountainDesktop.Models;
using LanMountainDesktop.PluginSdk;
using LanMountainDesktop.Services;
namespace LanMountainDesktop.Views;
@@ -250,23 +249,23 @@ public partial class SettingsWindow
{
FileName = installerPath,
WorkingDirectory = Path.GetDirectoryName(installerPath) ?? Environment.CurrentDirectory,
UseShellExecute = true
UseShellExecute = true,
Verb = "runas"
});
_updateStatusText = L("settings.update.status_installer_started", "Installer started. The app will close for update.");
UpdateUpdatePanelState();
Dispatcher.UIThread.Post(() =>
{
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
desktop.Shutdown();
}
else
{
Close();
}
}, DispatcherPriority.Background);
_ = App.CurrentHostApplicationLifecycle?.TryExit(new HostApplicationLifecycleRequest(
Source: nameof(SettingsWindow),
Reason: "Update installer started successfully from settings."));
}
catch (Win32Exception ex) when (ex.NativeErrorCode == 1223)
{
_updateStatusText = L(
"settings.update.status_elevation_cancelled",
"Administrator permission was not granted. Update was cancelled.");
UpdateUpdatePanelState();
}
catch (Exception ex)
{

View File

@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
@@ -12,6 +13,7 @@ using Avalonia.Media.Imaging;
using Avalonia.Platform;
using Avalonia.Styling;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
using LanMountainDesktop.Services;
using LanMountainDesktop.Theme;
using LibVLCSharp.Shared;
@@ -157,7 +159,7 @@ public partial class SettingsWindow
{
DesktopWallpaperLayer.Background = Brushes.Transparent;
WallpaperPreviewViewport.Background = GetThemeDefaultDesktopBackground();
PlayVideoWallpaper(_wallpaperVideoPath);
SyncVideoWallpaperPreviewPlayback();
return;
}
@@ -175,6 +177,36 @@ public partial class SettingsWindow
WallpaperPreviewViewport.Background = CreateWallpaperBrush(_wallpaperBitmap, placement, true);
}
private void SyncVideoWallpaperPreviewPlayback()
{
var shouldPlay =
_wallpaperMediaType == WallpaperMediaType.Video &&
!string.IsNullOrWhiteSpace(_wallpaperVideoPath) &&
WallpaperSettingsPanel.IsVisible;
if (!shouldPlay)
{
if (_previewVideoWallpaperPlayer?.IsPlaying == true)
{
StopPreviewVideoCapture(clearSnapshot: false);
}
WallpaperPreviewVideoImage.IsVisible = WallpaperPreviewVideoImage.Source is not null && WallpaperSettingsPanel.IsVisible;
return;
}
if (WallpaperPreviewVideoImage.Source is not null)
{
WallpaperPreviewVideoImage.IsVisible = true;
return;
}
if (_previewVideoWallpaperMedia is null || _previewVideoSnapshotPending)
{
PlayVideoWallpaper(_wallpaperVideoPath!);
}
}
private void UpdateWallpaperDisplay()
{
WallpaperPathTextBlock.Text = string.IsNullOrWhiteSpace(_wallpaperPath)
@@ -417,11 +449,239 @@ public partial class SettingsWindow
private void EnsureVideoWallpaperPlayers()
{
Core.Initialize();
_libVlc ??= new LibVLC();
_previewVideoWallpaperPlayer ??= new MediaPlayer(_libVlc);
if (WallpaperPreviewVideoView is not null)
_libVlc ??= new LibVLC("--quiet");
if (_previewVideoWallpaperPlayer is null)
{
WallpaperPreviewVideoView.MediaPlayer = _previewVideoWallpaperPlayer;
_previewVideoWallpaperPlayer = new MediaPlayer(_libVlc)
{
EnableHardwareDecoding = false
};
}
}
private void EnsurePreviewVideoFrameRefreshTimer()
{
if (_previewVideoFrameRefreshTimer is not null)
{
return;
}
_previewVideoFrameRefreshTimer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(33)
};
_previewVideoFrameRefreshTimer.Tick += OnPreviewVideoFrameRefreshTimerTick;
}
private void StartPreviewVideoFrameRefreshTimer()
{
EnsurePreviewVideoFrameRefreshTimer();
if (_previewVideoFrameRefreshTimer?.IsEnabled == false)
{
_previewVideoFrameRefreshTimer.Start();
}
}
private void StopPreviewVideoFrameRefreshTimer()
{
if (_previewVideoFrameRefreshTimer?.IsEnabled == true)
{
_previewVideoFrameRefreshTimer.Stop();
}
}
private void OnPreviewVideoFrameRefreshTimerTick(object? sender, EventArgs e)
{
PushPreviewVideoFrameToWallpaperImage();
}
private void StopPreviewVideoCapture(bool clearSnapshot)
{
WallpaperPreviewVideoImage.IsVisible = false;
_previewVideoWallpaperPlayer?.Stop();
StopPreviewVideoFrameRefreshTimer();
_previewVideoWallpaperMedia?.Dispose();
_previewVideoWallpaperMedia = null;
_previewVideoSnapshotPending = false;
if (clearSnapshot)
{
ReleasePreviewVideoRendererResources();
}
}
private bool ConfigurePreviewVideoRenderer()
{
if (_previewVideoWallpaperPlayer is null)
{
return false;
}
var hostWidth = Math.Max(1, WallpaperPreviewViewport.Bounds.Width);
var hostHeight = Math.Max(1, WallpaperPreviewViewport.Bounds.Height);
var pixelWidth = Math.Max(1, (int)Math.Round(hostWidth * RenderScaling));
var pixelHeight = Math.Max(1, (int)Math.Round(hostHeight * RenderScaling));
const int maxPixelCount = 1280 * 720;
var pixelCount = (long)pixelWidth * pixelHeight;
if (pixelCount > maxPixelCount)
{
var scale = Math.Sqrt((double)maxPixelCount / pixelCount);
pixelWidth = Math.Max(1, (int)Math.Round(pixelWidth * scale));
pixelHeight = Math.Max(1, (int)Math.Round(pixelHeight * scale));
}
var pitch = pixelWidth * 4;
var bufferSize = pitch * pixelHeight;
if (bufferSize <= 0)
{
return false;
}
if (pixelWidth == _previewVideoFrameWidth &&
pixelHeight == _previewVideoFrameHeight &&
_previewVideoFrameBufferPtr != IntPtr.Zero &&
_previewVideoBitmap is not null)
{
return true;
}
ReleasePreviewVideoRendererResources();
try
{
_previewVideoFrameWidth = pixelWidth;
_previewVideoFrameHeight = pixelHeight;
_previewVideoFramePitch = pitch;
_previewVideoFrameBufferSize = bufferSize;
_previewVideoFrameBufferPtr = Marshal.AllocHGlobal(_previewVideoFrameBufferSize);
_previewVideoStagingBuffer = new byte[_previewVideoFrameBufferSize];
_previewVideoBitmap = new WriteableBitmap(
new PixelSize(_previewVideoFrameWidth, _previewVideoFrameHeight),
new Vector(96, 96),
PixelFormat.Bgra8888,
AlphaFormat.Opaque);
EnsurePreviewVideoCallbacks();
_previewVideoWallpaperPlayer.SetVideoCallbacks(
_previewVideoLockCallback!,
_previewVideoUnlockCallback!,
_previewVideoDisplayCallback!);
_previewVideoWallpaperPlayer.SetVideoFormat(
"RV32",
(uint)_previewVideoFrameWidth,
(uint)_previewVideoFrameHeight,
(uint)_previewVideoFramePitch);
WallpaperPreviewVideoImage.Source = _previewVideoBitmap;
return true;
}
catch
{
ReleasePreviewVideoRendererResources();
return false;
}
}
private void EnsurePreviewVideoCallbacks()
{
_previewVideoLockCallback ??= OnPreviewVideoFrameLock;
_previewVideoUnlockCallback ??= OnPreviewVideoFrameUnlock;
_previewVideoDisplayCallback ??= OnPreviewVideoFrameDisplay;
}
private IntPtr OnPreviewVideoFrameLock(IntPtr opaque, IntPtr planes)
{
Monitor.Enter(_previewVideoFrameSync);
if (_previewVideoFrameBufferPtr == IntPtr.Zero)
{
Marshal.WriteIntPtr(planes, IntPtr.Zero);
Monitor.Exit(_previewVideoFrameSync);
return IntPtr.Zero;
}
Marshal.WriteIntPtr(planes, _previewVideoFrameBufferPtr);
return IntPtr.Zero;
}
private void OnPreviewVideoFrameUnlock(IntPtr opaque, IntPtr picture, IntPtr planes)
{
if (Monitor.IsEntered(_previewVideoFrameSync))
{
Monitor.Exit(_previewVideoFrameSync);
}
}
private void OnPreviewVideoFrameDisplay(IntPtr opaque, IntPtr picture)
{
Interlocked.Exchange(ref _previewVideoFrameDirtyFlag, 1);
}
private void PushPreviewVideoFrameToWallpaperImage()
{
if (Interlocked.Exchange(ref _previewVideoFrameDirtyFlag, 0) == 0)
{
return;
}
if (_previewVideoBitmap is null ||
_previewVideoStagingBuffer is null ||
_previewVideoFrameBufferPtr == IntPtr.Zero ||
_previewVideoFrameBufferSize <= 0)
{
return;
}
lock (_previewVideoFrameSync)
{
if (_previewVideoFrameBufferPtr == IntPtr.Zero)
{
return;
}
Marshal.Copy(_previewVideoFrameBufferPtr, _previewVideoStagingBuffer, 0, _previewVideoFrameBufferSize);
}
using var framebuffer = _previewVideoBitmap.Lock();
var rows = Math.Min(framebuffer.Size.Height, _previewVideoFrameHeight);
var bytesPerRow = Math.Min(framebuffer.RowBytes, _previewVideoFramePitch);
for (var row = 0; row < rows; row++)
{
var sourceOffset = row * _previewVideoFramePitch;
var destinationPtr = IntPtr.Add(framebuffer.Address, row * framebuffer.RowBytes);
Marshal.Copy(_previewVideoStagingBuffer, sourceOffset, destinationPtr, bytesPerRow);
}
if (!ReferenceEquals(WallpaperPreviewVideoImage.Source, _previewVideoBitmap))
{
WallpaperPreviewVideoImage.Source = _previewVideoBitmap;
}
if (_previewVideoSnapshotPending)
{
_previewVideoSnapshotPending = false;
WallpaperPreviewVideoImage.IsVisible = WallpaperSettingsPanel.IsVisible;
StopPreviewVideoCapture(clearSnapshot: false);
WallpaperPreviewVideoImage.IsVisible = WallpaperSettingsPanel.IsVisible;
}
}
private void ReleasePreviewVideoRendererResources()
{
Interlocked.Exchange(ref _previewVideoFrameDirtyFlag, 0);
WallpaperPreviewVideoImage.Source = null;
_previewVideoBitmap?.Dispose();
_previewVideoBitmap = null;
_previewVideoStagingBuffer = null;
_previewVideoFrameWidth = 0;
_previewVideoFrameHeight = 0;
_previewVideoFramePitch = 0;
_previewVideoFrameBufferSize = 0;
lock (_previewVideoFrameSync)
{
if (_previewVideoFrameBufferPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(_previewVideoFrameBufferPtr);
_previewVideoFrameBufferPtr = IntPtr.Zero;
}
}
}
@@ -437,7 +697,14 @@ public partial class SettingsWindow
try
{
EnsureVideoWallpaperPlayers();
if (_previewVideoWallpaperPlayer is null || _libVlc is null || WallpaperPreviewVideoView is null)
if (_previewVideoWallpaperPlayer is null || _libVlc is null)
{
_wallpaperStatus = L("settings.wallpaper.video_player_unavailable", "Video player is unavailable.");
StopVideoWallpaper();
return;
}
if (!ConfigurePreviewVideoRenderer())
{
_wallpaperStatus = L("settings.wallpaper.video_player_unavailable", "Video player is unavailable.");
StopVideoWallpaper();
@@ -447,8 +714,10 @@ public partial class SettingsWindow
_previewVideoWallpaperMedia?.Dispose();
_previewVideoWallpaperMedia = new Media(_libVlc, new Uri(videoPath));
_previewVideoWallpaperMedia.AddOption(":input-repeat=65535");
_previewVideoSnapshotPending = true;
WallpaperPreviewVideoImage.IsVisible = false;
_previewVideoWallpaperPlayer.Play(_previewVideoWallpaperMedia);
WallpaperPreviewVideoView.IsVisible = true;
StartPreviewVideoFrameRefreshTimer();
}
catch (Exception ex)
{
@@ -459,14 +728,7 @@ public partial class SettingsWindow
private void StopVideoWallpaper()
{
if (WallpaperPreviewVideoView is not null)
{
WallpaperPreviewVideoView.IsVisible = false;
}
_previewVideoWallpaperPlayer?.Stop();
_previewVideoWallpaperMedia?.Dispose();
_previewVideoWallpaperMedia = null;
StopPreviewVideoCapture(clearSnapshot: true);
}
private void OnRecommendedColorClick(object? sender, RoutedEventArgs e)

View File

@@ -873,11 +873,22 @@ public partial class SettingsWindow
var restoreButton = new Button
{
Content = L("settings.launcher.restore_button", "Unhide"),
MinWidth = 110,
Padding = new Thickness(12, 6),
Width = 36,
Height = 36,
Padding = new Thickness(0),
Background = Brushes.Transparent,
BorderThickness = new Thickness(0),
Tag = new LauncherHiddenItemToken(hiddenItem.Kind, hiddenItem.Key)
};
restoreButton.Content = new FluentIcons.Avalonia.Fluent.SymbolIcon
{
Symbol = FluentIcons.Common.Symbol.Eye,
IconVariant = FluentIcons.Common.IconVariant.Regular,
FontSize = 18,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
ToolTip.SetTip(restoreButton, L("settings.launcher.restore_button", "Unhide"));
restoreButton.Click += OnRestoreLauncherHiddenItemClick;
return new SettingsExpanderItem

View File

@@ -129,6 +129,20 @@ public partial class SettingsWindow : Window
private MediaPlayer? _previewVideoWallpaperPlayer;
private Media? _previewVideoWallpaperMedia;
private LibVLC? _libVlc;
private readonly object _previewVideoFrameSync = new();
private MediaPlayer.LibVLCVideoLockCb? _previewVideoLockCallback;
private MediaPlayer.LibVLCVideoUnlockCb? _previewVideoUnlockCallback;
private MediaPlayer.LibVLCVideoDisplayCb? _previewVideoDisplayCallback;
private DispatcherTimer? _previewVideoFrameRefreshTimer;
private IntPtr _previewVideoFrameBufferPtr;
private byte[]? _previewVideoStagingBuffer;
private WriteableBitmap? _previewVideoBitmap;
private int _previewVideoFrameWidth;
private int _previewVideoFrameHeight;
private int _previewVideoFramePitch;
private int _previewVideoFrameBufferSize;
private int _previewVideoFrameDirtyFlag;
private bool _previewVideoSnapshotPending;
private string? _wallpaperPath;
private string _wallpaperStatus = "Current background uses solid color.";
private IReadOnlyList<Color> _recommendedColors = Array.Empty<Color>();

View File

@@ -38,6 +38,8 @@ OutputBaseFilename={#MyAppName}-Setup-{#MyAppVersion}-{#MyAppArch}
Compression=lzma2/ultra64
SolidCompression=yes
WizardStyle=modern
; Leave PrivilegesRequiredOverridesAllowed unset so users cannot downgrade
; installation mode via dialog or /ALLUSERS /CURRENTUSER command-line switches.
PrivilegesRequired=admin
CloseApplications=yes
CloseApplicationsFilter={#MyAppExeName}
@@ -113,7 +115,7 @@ Name: "{autoprograms}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"
Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon
[Registry]
Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: string; ValueName: "{#MyAppName}"; ValueData: """{app}\{#MyAppExeName}"""; Tasks: startup; Flags: uninsdeletevalue
Root: HKA; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: string; ValueName: "{#MyAppName}"; ValueData: """{app}\{#MyAppExeName}"""; Tasks: startup; Flags: uninsdeletevalue
[Run]
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent

View File

@@ -5,6 +5,7 @@ using System.Threading;
using System.Threading.Tasks;
using LanMountainDesktop.PluginSdk;
using Microsoft.Extensions.Hosting;
namespace LanMountainDesktop.Plugins;
@@ -18,9 +19,12 @@ public sealed class LoadedPlugin : IDisposable, IAsyncDisposable
string assemblyPath,
Assembly assembly,
IPlugin plugin,
IPluginContext context,
IPluginRuntimeContext runtimeContext,
IServiceProvider services,
IReadOnlyList<PluginSettingsPageRegistration> settingsPages,
IReadOnlyList<PluginDesktopComponentRegistration> desktopComponents,
IReadOnlyList<PluginServiceExportDescriptor> exportedServices,
IReadOnlyList<IHostedService> hostedServices,
PluginLoadContext loadContext)
{
Manifest = manifest;
@@ -28,9 +32,12 @@ public sealed class LoadedPlugin : IDisposable, IAsyncDisposable
AssemblyPath = assemblyPath;
Assembly = assembly;
Plugin = plugin;
Context = context;
RuntimeContext = runtimeContext;
Services = services;
SettingsPages = settingsPages;
DesktopComponents = desktopComponents;
ExportedServices = exportedServices;
HostedServices = hostedServices;
LoadContext = loadContext;
}
@@ -44,14 +51,22 @@ public sealed class LoadedPlugin : IDisposable, IAsyncDisposable
public IPlugin Plugin { get; }
public IPluginContext Context { get; }
public IPluginRuntimeContext RuntimeContext { get; }
public IPluginRuntimeContext Context => RuntimeContext;
public IServiceProvider Services { get; }
public IReadOnlyList<PluginSettingsPageRegistration> SettingsPages { get; }
public IReadOnlyList<PluginDesktopComponentRegistration> DesktopComponents { get; }
public IReadOnlyList<PluginServiceExportDescriptor> ExportedServices { get; }
public PluginLoadContext LoadContext { get; }
private IReadOnlyList<IHostedService> HostedServices { get; }
public void Dispose()
{
DisposeAsync().AsTask().GetAwaiter().GetResult();
@@ -64,6 +79,18 @@ public sealed class LoadedPlugin : IDisposable, IAsyncDisposable
return;
}
for (var i = HostedServices.Count - 1; i >= 0; i--)
{
try
{
await HostedServices[i].StopAsync(CancellationToken.None);
}
catch
{
// Ignore plugin hosted service shutdown failures to allow unload cleanup.
}
}
if (Plugin is IAsyncDisposable asyncDisposable)
{
await asyncDisposable.DisposeAsync();
@@ -73,11 +100,20 @@ public sealed class LoadedPlugin : IDisposable, IAsyncDisposable
disposable.Dispose();
}
if (Context is IAsyncDisposable asyncContext)
if (Services is IAsyncDisposable asyncServices)
{
await asyncServices.DisposeAsync();
}
else if (Services is IDisposable disposableServices)
{
disposableServices.Dispose();
}
if (RuntimeContext is IAsyncDisposable asyncContext)
{
await asyncContext.DisposeAsync();
}
else if (Context is IDisposable disposableContext)
else if (RuntimeContext is IDisposable disposableContext)
{
disposableContext.Dispose();
}

View File

@@ -85,7 +85,7 @@ public partial class MainWindow
Control content;
try
{
content = contribution.Registration.ContentFactory();
content = contribution.Registration.ContentFactory(contribution.Plugin.Services);
}
catch (Exception ex)
{

View File

@@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.Linq;
using LanMountainDesktop.PluginSdk;
namespace LanMountainDesktop.Plugins;
internal sealed class PluginExportRegistry : IPluginExportRegistry
{
private readonly object _gate = new();
private readonly List<PluginServiceExportDescriptor> _exports = [];
public IReadOnlyList<PluginServiceExportDescriptor> GetExports()
{
lock (_gate)
{
return _exports.ToArray();
}
}
public IReadOnlyList<PluginServiceExportDescriptor> GetExports(Type contractType)
{
ArgumentNullException.ThrowIfNull(contractType);
lock (_gate)
{
return _exports
.Where(descriptor => descriptor.ContractType == contractType)
.ToArray();
}
}
public PluginServiceExportDescriptor? GetExport(Type contractType, string providerPluginId)
{
ArgumentNullException.ThrowIfNull(contractType);
ArgumentException.ThrowIfNullOrWhiteSpace(providerPluginId);
lock (_gate)
{
return _exports.FirstOrDefault(descriptor =>
descriptor.ContractType == contractType &&
string.Equals(descriptor.ProviderPluginId, providerPluginId, StringComparison.OrdinalIgnoreCase));
}
}
public TContract? GetExport<TContract>(string providerPluginId)
where TContract : class
{
return GetExport(typeof(TContract), providerPluginId)?.ServiceInstance as TContract;
}
public void ReplaceExports(string pluginId, IEnumerable<PluginServiceExportDescriptor> descriptors)
{
ArgumentException.ThrowIfNullOrWhiteSpace(pluginId);
ArgumentNullException.ThrowIfNull(descriptors);
lock (_gate)
{
_exports.RemoveAll(descriptor =>
string.Equals(descriptor.ProviderPluginId, pluginId, StringComparison.OrdinalIgnoreCase));
_exports.AddRange(descriptors);
}
}
public void RemoveExports(string pluginId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(pluginId);
lock (_gate)
{
_exports.RemoveAll(descriptor =>
string.Equals(descriptor.ProviderPluginId, pluginId, StringComparison.OrdinalIgnoreCase));
}
}
public void Clear()
{
lock (_gate)
{
_exports.Clear();
}
}
}

View File

@@ -12,6 +12,8 @@ using System.Threading.Tasks;
using LanMountainDesktop.Services;
using LanMountainDesktop.PluginSdk;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace LanMountainDesktop.Plugins;
@@ -135,19 +137,45 @@ public sealed class PluginLoader
{
PluginLoadContext? loadContext = null;
IPlugin? plugin = null;
PluginContext? context = null;
PluginRuntimeContext? runtimeContext = null;
ServiceProvider? pluginServices = null;
IReadOnlyList<IHostedService> hostedServices = Array.Empty<IHostedService>();
try
{
Directory.CreateDirectory(dataDirectory);
ValidatePluginRuntimeAssets(manifest, assemblyPath, pluginDirectory);
loadContext = new PluginLoadContext(assemblyPath, _options.SharedAssemblyNames);
var assembly = loadContext.LoadFromAssemblyPath(assemblyPath);
var pluginType = ResolvePluginType(assembly);
plugin = CreatePluginInstance(pluginType);
context = CreateContext(manifest, pluginDirectory, dataDirectory, services, properties);
runtimeContext = CreateRuntimeContext(manifest, pluginDirectory, dataDirectory, properties);
var serviceCollection = CreateServiceCollection(runtimeContext, services);
var hostBuilderContext = CreateHostBuilderContext(runtimeContext);
plugin.Initialize(context);
var settingsPages = context.GetSettingsPagesSnapshot();
var desktopComponents = context.GetDesktopComponentsSnapshot();
plugin.Initialize(hostBuilderContext, serviceCollection);
pluginServices = serviceCollection.BuildServiceProvider(new ServiceProviderOptions
{
ValidateScopes = false,
ValidateOnBuild = true
});
runtimeContext.SetServices(pluginServices);
var settingsPages = pluginServices
.GetServices<PluginSettingsPageRegistration>()
.OrderBy(page => page.SortOrder)
.ThenBy(page => page.Title, StringComparer.OrdinalIgnoreCase)
.ToArray();
var desktopComponents = pluginServices
.GetServices<PluginDesktopComponentRegistration>()
.OrderBy(component => component.Category, StringComparer.OrdinalIgnoreCase)
.ThenBy(component => component.DisplayName, StringComparer.OrdinalIgnoreCase)
.ToArray();
var exportedServices = ResolveExports(manifest, pluginServices);
hostedServices = pluginServices.GetServices<IHostedService>().ToArray();
StartHostedServices(hostedServices);
var loadedPlugin = new LoadedPlugin(
manifest,
@@ -155,17 +183,22 @@ public sealed class PluginLoader
assemblyPath,
assembly,
plugin,
context,
runtimeContext,
pluginServices,
settingsPages,
desktopComponents,
exportedServices,
hostedServices,
loadContext);
return PluginLoadResult.Success(sourcePath, manifest, loadedPlugin);
}
catch (Exception ex)
{
StopHostedServices(hostedServices);
DisposeInstance(pluginServices);
DisposeInstance(plugin);
DisposeInstance(context);
DisposeInstance(runtimeContext);
loadContext?.Unload();
return PluginLoadResult.Failure(sourcePath, manifest, ex);
}
@@ -243,23 +276,124 @@ public sealed class PluginLoader
}
}
private PluginContext CreateContext(
private PluginRuntimeContext CreateRuntimeContext(
PluginManifest manifest,
string pluginDirectory,
string dataDirectory,
IServiceProvider? services,
IReadOnlyDictionary<string, object?>? properties)
{
Directory.CreateDirectory(dataDirectory);
return new PluginContext(
return new PluginRuntimeContext(
manifest,
pluginDirectory,
dataDirectory,
services ?? NullServiceProvider.Instance,
CreateReadOnlyProperties(properties));
}
private ServiceCollection CreateServiceCollection(
PluginRuntimeContext runtimeContext,
IServiceProvider? hostServices)
{
var services = new ServiceCollection();
services.AddSingleton(runtimeContext);
services.AddSingleton<IPluginRuntimeContext>(runtimeContext);
services.AddSingleton(runtimeContext.Manifest);
services.AddSingleton<IReadOnlyDictionary<string, object?>>(runtimeContext.Properties);
services.AddSingleton<IPluginMessageBus, PluginMessageBus>();
RegisterHostService<IPluginPackageManager>(services, hostServices);
RegisterHostService<IHostApplicationLifecycle>(services, hostServices);
RegisterHostService<IPluginExportRegistry>(services, hostServices);
return services;
}
private static void RegisterHostService<TService>(IServiceCollection services, IServiceProvider? hostServices)
where TService : class
{
if (hostServices?.GetService(typeof(TService)) is TService service)
{
services.AddSingleton(service);
}
}
private static HostBuilderContext CreateHostBuilderContext(PluginRuntimeContext runtimeContext)
{
var hostBuilderContext = new HostBuilderContext(new Dictionary<object, object>());
hostBuilderContext.Properties["LanMountainDesktop.PluginManifest"] = runtimeContext.Manifest;
hostBuilderContext.Properties["LanMountainDesktop.PluginDirectory"] = runtimeContext.PluginDirectory;
hostBuilderContext.Properties["LanMountainDesktop.PluginDataDirectory"] = runtimeContext.DataDirectory;
hostBuilderContext.Properties["LanMountainDesktop.PluginRuntimeContext"] = runtimeContext;
foreach (var pair in runtimeContext.Properties)
{
if (pair.Value is not null)
{
hostBuilderContext.Properties[pair.Key] = pair.Value;
}
}
return hostBuilderContext;
}
private static IReadOnlyList<PluginServiceExportDescriptor> ResolveExports(
PluginManifest manifest,
IServiceProvider services)
{
return services
.GetServices<PluginServiceExportRegistration>()
.Select(registration =>
{
if (!IsSupportedExportContract(manifest, registration.ContractType))
{
throw new InvalidOperationException(
$"Plugin '{manifest.Id}' exported contract '{registration.ContractType.FullName}', but export contracts must come from LanMountainDesktop.PluginSdk or a manifest-declared shared contract assembly.");
}
return new PluginServiceExportDescriptor(
manifest.Id,
registration.ContractType,
services.GetService(registration.ContractType)
?? throw new InvalidOperationException(
$"Plugin '{manifest.Id}' exported contract '{registration.ContractType.FullName}', but no singleton service instance was registered."));
})
.ToArray();
}
private static bool IsSupportedExportContract(PluginManifest manifest, Type contractType)
{
if (contractType.Assembly == typeof(IPlugin).Assembly)
{
return true;
}
var assemblyFileName = contractType.Assembly.GetName().Name + ".dll";
return manifest.SharedContracts?.Any(contract =>
string.Equals(contract.AssemblyName, assemblyFileName, StringComparison.OrdinalIgnoreCase)) == true;
}
private static void StartHostedServices(IEnumerable<IHostedService> hostedServices)
{
foreach (var hostedService in hostedServices)
{
hostedService.StartAsync(CancellationToken.None).GetAwaiter().GetResult();
}
}
private static void StopHostedServices(IEnumerable<IHostedService> hostedServices)
{
foreach (var hostedService in hostedServices.Reverse())
{
try
{
hostedService.StopAsync(CancellationToken.None).GetAwaiter().GetResult();
}
catch
{
// Ignore best-effort shutdown during failed startup.
}
}
}
private IReadOnlyList<PluginCandidate> DiscoverCandidates(
string pluginsRootDirectory,
List<PluginLoadResult> preparationFailures)
@@ -436,6 +570,27 @@ public sealed class PluginLoader
return new ReadOnlyDictionary<string, object?>(map);
}
private static void ValidatePluginRuntimeAssets(
PluginManifest manifest,
string assemblyPath,
string pluginDirectory)
{
var depsFilePath = Path.ChangeExtension(assemblyPath, ".deps.json");
if (!File.Exists(depsFilePath))
{
throw new InvalidOperationException(
$"Plugin '{manifest.Id}' targets API {PluginSdkInfo.ApiVersion} and must include '{Path.GetFileName(depsFilePath)}' next to its main assembly.");
}
var runtimesDirectory = Path.Combine(pluginDirectory, "runtimes");
if (Directory.Exists(runtimesDirectory) &&
!Directory.EnumerateFiles(runtimesDirectory, "*", SearchOption.AllDirectories).Any())
{
throw new InvalidOperationException(
$"Plugin '{manifest.Id}' contains an empty 'runtimes' directory. Native/runtime assets must be packaged together with the plugin.");
}
}
private static Type ResolvePluginType(Assembly assembly)
{
var candidateTypes = GetLoadableTypes(assembly)
@@ -543,34 +698,19 @@ public sealed class PluginLoader
}
}
private sealed class PluginContext : IPluginContext, IDisposable, IAsyncDisposable
private sealed class PluginRuntimeContext : IPluginRuntimeContext
{
private readonly Dictionary<string, PluginSettingsPageRegistration> _settingsPages =
new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, PluginDesktopComponentRegistration> _desktopComponents =
new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<Type, object> _registeredServices = [];
private readonly List<object> _serviceRegistrationOrder = [];
private readonly object _serviceGate = new();
private readonly IServiceProvider _hostServices;
private int _disposed;
public PluginContext(
public PluginRuntimeContext(
PluginManifest manifest,
string pluginDirectory,
string dataDirectory,
IServiceProvider services,
IReadOnlyDictionary<string, object?> properties)
{
Manifest = manifest;
PluginDirectory = pluginDirectory;
DataDirectory = dataDirectory;
_hostServices = services;
Services = new PluginCompositeServiceProvider(this);
Properties = properties;
RegisterBuiltInService<IPluginContext>(this);
RegisterBuiltInService<IPluginMessageBus>(new PluginMessageBus());
Services = NullServiceProvider.Instance;
}
public PluginManifest Manifest { get; }
@@ -579,7 +719,7 @@ public sealed class PluginLoader
public string DataDirectory { get; }
public IServiceProvider Services { get; }
public IServiceProvider Services { get; private set; }
public IReadOnlyDictionary<string, object?> Properties { get; }
@@ -602,181 +742,9 @@ public sealed class PluginLoader
return false;
}
public void RegisterService<TService>(TService service)
where TService : class
public void SetServices(IServiceProvider services)
{
RegisterServiceCore(typeof(TService), service, allowOverride: false);
}
public void RegisterSettingsPage(PluginSettingsPageRegistration registration)
{
ArgumentNullException.ThrowIfNull(registration);
ThrowIfDisposed();
if (!_settingsPages.TryAdd(registration.Id, registration))
{
throw new InvalidOperationException(
$"Plugin '{Manifest.Id}' already registered a settings page with id '{registration.Id}'.");
}
}
public void RegisterDesktopComponent(PluginDesktopComponentRegistration registration)
{
ArgumentNullException.ThrowIfNull(registration);
ThrowIfDisposed();
if (!_desktopComponents.TryAdd(registration.ComponentId, registration))
{
throw new InvalidOperationException(
$"Plugin '{Manifest.Id}' already registered a desktop component with id '{registration.ComponentId}'.");
}
}
public IReadOnlyList<PluginSettingsPageRegistration> GetSettingsPagesSnapshot()
{
ThrowIfDisposed();
return _settingsPages.Values
.OrderBy(page => page.SortOrder)
.ThenBy(page => page.Title, StringComparer.OrdinalIgnoreCase)
.ToArray();
}
public IReadOnlyList<PluginDesktopComponentRegistration> GetDesktopComponentsSnapshot()
{
ThrowIfDisposed();
return _desktopComponents.Values
.OrderBy(component => component.Category, StringComparer.OrdinalIgnoreCase)
.ThenBy(component => component.DisplayName, StringComparer.OrdinalIgnoreCase)
.ToArray();
}
internal object? ResolveService(Type serviceType)
{
if (Volatile.Read(ref _disposed) != 0)
{
return null;
}
if (serviceType == typeof(IServiceProvider))
{
return Services;
}
lock (_serviceGate)
{
if (_registeredServices.TryGetValue(serviceType, out var service))
{
return service;
}
foreach (var registeredService in _registeredServices.Values)
{
if (serviceType.IsInstanceOfType(registeredService))
{
return registeredService;
}
}
}
return _hostServices.GetService(serviceType);
}
private void RegisterBuiltInService<TService>(TService service)
where TService : class
{
RegisterServiceCore(typeof(TService), service, allowOverride: true);
}
public void Dispose()
{
DisposeAsync().AsTask().GetAwaiter().GetResult();
}
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return;
}
object[] services;
lock (_serviceGate)
{
services = _serviceRegistrationOrder.ToArray();
_registeredServices.Clear();
_serviceRegistrationOrder.Clear();
}
_settingsPages.Clear();
_desktopComponents.Clear();
var disposedServices = new HashSet<object>(ReferenceEqualityComparer.Instance);
for (var i = services.Length - 1; i >= 0; i--)
{
var service = services[i];
if (ReferenceEquals(service, this) || !disposedServices.Add(service))
{
continue;
}
if (service is IAsyncDisposable asyncDisposable)
{
await asyncDisposable.DisposeAsync();
}
else if (service is IDisposable disposable)
{
disposable.Dispose();
}
}
}
private void RegisterServiceCore(Type serviceType, object service, bool allowOverride)
{
ArgumentNullException.ThrowIfNull(serviceType);
ArgumentNullException.ThrowIfNull(service);
ThrowIfDisposed();
if (!serviceType.IsInstanceOfType(service))
{
throw new InvalidOperationException(
$"Service instance '{service.GetType().FullName}' is not assignable to '{serviceType.FullName}'.");
}
lock (_serviceGate)
{
if (!allowOverride && _registeredServices.ContainsKey(serviceType))
{
throw new InvalidOperationException(
$"Plugin '{Manifest.Id}' already registered a service for '{serviceType.FullName}'.");
}
_registeredServices[serviceType] = service;
_serviceRegistrationOrder.Add(service);
}
}
private void ThrowIfDisposed()
{
if (Volatile.Read(ref _disposed) != 0)
{
throw new ObjectDisposedException(nameof(PluginContext));
}
}
}
private sealed class PluginCompositeServiceProvider : IServiceProvider
{
private readonly PluginContext _context;
public PluginCompositeServiceProvider(PluginContext context)
{
_context = context;
}
public object? GetService(Type serviceType)
{
ArgumentNullException.ThrowIfNull(serviceType);
return _context.ResolveService(serviceType);
Services = services ?? throw new ArgumentNullException(nameof(services));
}
}

View File

@@ -3,6 +3,8 @@ using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
@@ -37,6 +39,7 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
private readonly AirAppMarketReadmeService _readmeService;
private readonly AirAppMarketIconService _iconService;
private readonly Version? _hostVersion;
private readonly CancellationTokenSource _lifetimeCts = new();
private readonly TextBox _searchTextBox;
private readonly Button _refreshButton;
@@ -57,6 +60,8 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
private bool _isRefreshing;
private bool _isInstalling;
private bool _hasLoadedOnce;
private bool _isDisposed;
private bool _isAttachedToVisualTree;
public PluginMarketEmbeddedView(PluginRuntimeService runtime)
{
@@ -106,16 +111,8 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
_detailBorder = CreatePanelShell(18);
Content = BuildLayout();
AttachedToVisualTree += async (_, _) =>
{
if (_hasLoadedOnce)
{
return;
}
_hasLoadedOnce = true;
await RefreshAsync();
};
AttachedToVisualTree += OnAttachedToVisualTree;
DetachedFromVisualTree += OnDetachedFromVisualTree;
}
public void RefreshInstalledSnapshot()
@@ -134,18 +131,47 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
public void Dispose()
{
if (_isDisposed)
{
return;
}
_isDisposed = true;
_lifetimeCts.Cancel();
foreach (var bitmap in _iconBitmaps.Values)
{
bitmap?.Dispose();
}
_iconBitmaps.Clear();
_lifetimeCts.Dispose();
_iconService.Dispose();
_readmeService.Dispose();
_installService.Dispose();
_indexService.Dispose();
}
private void OnAttachedToVisualTree(object? sender, VisualTreeAttachmentEventArgs e)
{
_isAttachedToVisualTree = true;
if (_hasLoadedOnce)
{
return;
}
_hasLoadedOnce = true;
UiExceptionGuard.FireAndForgetGuarded(
RefreshAsync,
"PluginMarket.InitialLoad",
BuildMarketContext());
}
private void OnDetachedFromVisualTree(object? sender, VisualTreeAttachmentEventArgs e)
{
_isAttachedToVisualTree = false;
}
private Control BuildLayout()
{
var root = new Grid
@@ -197,14 +223,23 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
return root;
}
private async void OnRefreshClick(object? sender, RoutedEventArgs e)
private void OnRefreshClick(object? sender, RoutedEventArgs e)
{
await RefreshAsync();
UiExceptionGuard.FireAndForgetGuarded(
RefreshAsync,
"PluginMarket.Refresh",
BuildMarketContext(),
ex => HandleTopLevelUiActionExceptionAsync(
ex,
F(
"market.status.load_failed_format",
"Failed to load the plugin market: {0}",
DescribeException(ex))));
}
private async Task RefreshAsync()
{
if (_isRefreshing)
if (_isRefreshing || _isDisposed || _lifetimeCts.IsCancellationRequested)
{
return;
}
@@ -217,11 +252,19 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
{
RefreshInstalledSnapshot();
var result = await _indexService.LoadAsync();
var result = await _indexService.LoadAsync(_lifetimeCts.Token);
if (!CanUpdateUi())
{
return;
}
if (!result.Success || result.Document is null)
{
_document = null;
_selectedPlugin = null;
AppLogger.Warn(
"PluginMarket",
$"Refresh failed. Source=None; Warning={result.WarningMessage ?? string.Empty}; Error={result.ErrorMessage ?? string.Empty}; Context={BuildMarketContext()}");
SetStatus(
F(
"market.status.load_failed_format",
@@ -235,6 +278,9 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
_document = result.Document;
_marketSourceDisplay = result.SourceLocation ?? AirAppMarketDefaults.DefaultIndexUrl;
_selectedPlugin = ResolveSelectedPlugin(_selectedPlugin?.Id, result.Document.Plugins);
AppLogger.Info(
"PluginMarket",
$"Refresh completed. Source={result.Source}; PluginCount={result.Document.Plugins.Count}; SourceLocation={result.SourceLocation ?? string.Empty}; Warning={result.WarningMessage ?? string.Empty}; Context={BuildMarketContext()}");
var statusMessage = result.Source == AirAppMarketLoadSource.Cache
? F(
@@ -251,15 +297,43 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
RebuildSurface();
await EnsureReadmeLoadedAsync(_selectedPlugin);
}
catch (OperationCanceledException) when (_lifetimeCts.IsCancellationRequested)
{
AppLogger.Info("PluginMarket", $"Refresh canceled because the view is being disposed. Context={BuildMarketContext()}");
}
catch (Exception ex)
{
AppLogger.Warn(
"PluginMarket",
$"Refresh threw unexpectedly. ExceptionType={ex.GetType().FullName}; Classification={ClassifyException(ex)}; Context={BuildMarketContext()}",
ex);
if (CanUpdateUi())
{
SetStatus(
F(
"market.status.load_failed_format",
"Failed to load the plugin market: {0}",
DescribeException(ex)),
ErrorBrush);
_document = null;
_selectedPlugin = null;
RebuildSurface();
}
}
finally
{
_isRefreshing = false;
_refreshButton.IsEnabled = true;
_refreshButton.IsEnabled = !_isDisposed;
}
}
private void RebuildSurface()
{
if (_isDisposed)
{
return;
}
var filteredPlugins = GetFilteredPlugins();
_selectedPlugin = filteredPlugins.Count > 0
? ResolveSelectedPlugin(_selectedPlugin?.Id, filteredPlugins)
@@ -396,7 +470,10 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
HorizontalContentAlignment = HorizontalAlignment.Stretch,
Content = selectGrid
};
selectButton.Click += async (_, _) => await SelectPluginAsync(plugin);
selectButton.Click += (_, _) => UiExceptionGuard.FireAndForgetGuarded(
() => SelectPluginAsync(plugin),
"PluginMarket.SelectPlugin",
BuildMarketContext(plugin));
var rightPanel = new StackPanel
{
@@ -623,13 +700,22 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
HorizontalAlignment = HorizontalAlignment.Right
};
button.Click += async (_, _) =>
{
_selectedPlugin = plugin;
RebuildSurface();
await EnsureReadmeLoadedAsync(plugin);
await InstallSelectedPluginAsync(plugin);
};
button.Click += (_, _) => UiExceptionGuard.FireAndForgetGuarded(
async () =>
{
_selectedPlugin = plugin;
RebuildSurface();
await EnsureReadmeLoadedAsync(plugin);
await InstallSelectedPluginAsync(plugin);
},
"PluginMarket.InstallPlugin",
BuildMarketContext(plugin),
ex => HandleTopLevelUiActionExceptionAsync(
ex,
F(
"market.status.install_failed_format",
"Failed to install plugin: {0}",
DescribeException(ex))));
return button;
}
@@ -643,7 +729,7 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
private async Task InstallSelectedPluginAsync(AirAppMarketPluginEntry plugin)
{
if (_isInstalling)
if (_isInstalling || _isDisposed || _lifetimeCts.IsCancellationRequested)
{
return;
}
@@ -658,7 +744,12 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
try
{
var result = await _installService.InstallAsync(plugin);
var result = await _installService.InstallAsync(plugin, _lifetimeCts.Token);
if (!CanUpdateUi())
{
return;
}
if (!result.Success || result.Manifest is null)
{
SetStatus(
@@ -679,6 +770,12 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
SuccessBrush);
RebuildSurface();
}
catch (OperationCanceledException) when (_lifetimeCts.IsCancellationRequested)
{
AppLogger.Info(
"PluginMarket",
$"Install canceled because the view is being disposed. PluginId={plugin.Id}; Context={BuildMarketContext(plugin)}");
}
finally
{
_isInstalling = false;
@@ -690,6 +787,7 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
private async Task EnsureReadmeLoadedAsync(AirAppMarketPluginEntry? plugin)
{
if (plugin is null ||
_isDisposed ||
_readmeContents.ContainsKey(plugin.Id) ||
string.Equals(_loadingReadmePluginId, plugin.Id, StringComparison.OrdinalIgnoreCase))
{
@@ -702,19 +800,30 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
try
{
var readme = await _readmeService.LoadAsync(plugin);
var readme = await _readmeService.LoadAsync(plugin, _lifetimeCts.Token);
_readmeContents[plugin.Id] = string.IsNullOrWhiteSpace(readme)
? T("market.detail.readme_empty", "README is empty.")
: readme.Trim();
}
catch (OperationCanceledException) when (_lifetimeCts.IsCancellationRequested)
{
AppLogger.Info(
"PluginMarket",
$"README load canceled because the view is being disposed. PluginId={plugin.Id}; Context={BuildMarketContext(plugin)}");
}
catch (Exception ex)
{
AppLogger.Warn(
"PluginMarket",
$"README load failed. PluginId={plugin.Id}; ExceptionType={ex.GetType().FullName}; Classification={ClassifyException(ex)}; Context={BuildMarketContext(plugin)}",
ex);
_readmeErrors[plugin.Id] = ex.Message;
}
finally
{
_loadingReadmePluginId = null;
if (string.Equals(_selectedPlugin?.Id, plugin.Id, StringComparison.OrdinalIgnoreCase))
if (CanUpdateUi() &&
string.Equals(_selectedPlugin?.Id, plugin.Id, StringComparison.OrdinalIgnoreCase))
{
BuildDetailPanel();
}
@@ -724,6 +833,7 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
private async Task EnsureIconLoadedAsync(AirAppMarketPluginEntry? plugin)
{
if (plugin is null ||
_isDisposed ||
_iconBitmaps.ContainsKey(plugin.Id) ||
!_loadingIconPluginIds.Add(plugin.Id))
{
@@ -732,7 +842,13 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
try
{
_iconBitmaps[plugin.Id] = await _iconService.LoadAsync(plugin);
_iconBitmaps[plugin.Id] = await _iconService.LoadAsync(plugin, _lifetimeCts.Token);
}
catch (OperationCanceledException) when (_lifetimeCts.IsCancellationRequested)
{
AppLogger.Info(
"PluginMarket",
$"Icon load canceled because the view is being disposed. PluginId={plugin.Id}; Context={BuildMarketContext(plugin)}");
}
catch
{
@@ -741,8 +857,61 @@ internal sealed class PluginMarketEmbeddedView : UserControl, IDisposable
finally
{
_loadingIconPluginIds.Remove(plugin.Id);
if (CanUpdateUi())
{
RebuildSurface();
}
}
}
private Task HandleTopLevelUiActionExceptionAsync(Exception ex, string fallbackStatus)
{
if (CanUpdateUi())
{
SetStatus(fallbackStatus, ErrorBrush);
RebuildSurface();
}
return Task.CompletedTask;
}
private bool CanUpdateUi()
{
return !_isDisposed && _isAttachedToVisualTree && !_lifetimeCts.IsCancellationRequested;
}
private string BuildMarketContext(AirAppMarketPluginEntry? plugin = null)
{
return UiExceptionGuard.BuildContext(
("SelectedPluginId", _selectedPlugin?.Id),
("PluginId", plugin?.Id),
("Source", _marketSourceDisplay),
("IsRefreshing", _isRefreshing),
("IsInstalling", _isInstalling),
("IsDisposed", _isDisposed));
}
private static string ClassifyException(Exception ex)
{
return ex switch
{
OperationCanceledException => "Canceled",
TimeoutException => "Timeout",
HttpRequestException => "Network",
IOException => "IO",
_ => "Unexpected"
};
}
private static string DescribeException(Exception ex)
{
return ex switch
{
OperationCanceledException => "The request timed out or was canceled.",
TimeoutException => "The request timed out.",
HttpRequestException => ex.Message,
_ => ex.Message
};
}
private string GetReadmeContent(AirAppMarketPluginEntry plugin)

View File

@@ -43,10 +43,14 @@ internal sealed class AirAppMarketIndexService : IDisposable
null,
null);
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (OperationCanceledException ex)
{
networkError = ex;
}
catch (Exception ex)
{
networkError = ex;
@@ -71,10 +75,14 @@ internal sealed class AirAppMarketIndexService : IDisposable
null,
null);
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (OperationCanceledException ex)
{
networkError = ex;
}
catch (Exception ex)
{
networkError = ex;

View File

@@ -13,6 +13,7 @@ namespace LanMountainDesktop.Views.SettingsPages;
internal sealed class AirAppMarketInstallService : IDisposable
{
private readonly PluginRuntimeService _runtime;
private readonly PluginsInstallHelperClient _helperClient = new();
private readonly HttpClient _httpClient;
private readonly ResumableDownloadService _downloadService;
private readonly AirAppMarketReleaseResolverService _releaseResolverService;
@@ -77,19 +78,48 @@ internal sealed class AirAppMarketInstallService : IDisposable
}
}
await using var hashStream = File.OpenRead(downloadPath);
var hashBytes = await SHA256.HashDataAsync(hashStream, cancellationToken);
var actualHash = Convert.ToHexString(hashBytes).ToLowerInvariant();
var actualSize = new FileInfo(downloadPath).Length;
string actualHash;
await using (var hashStream = File.OpenRead(downloadPath))
{
var hashBytes = await SHA256.HashDataAsync(hashStream, cancellationToken);
actualHash = Convert.ToHexString(hashBytes).ToLowerInvariant();
}
if (!string.Equals(actualHash, plugin.Sha256, StringComparison.OrdinalIgnoreCase))
{
AppLogger.Error(
"PluginMarket",
$"SHA-256 verification failed. PluginId='{plugin.Id}'; Version='{plugin.Version}'; DownloadUrl='{resolvedDownloadUrl}'; DownloadPath='{downloadPath}'; ExpectedHash='{plugin.Sha256}'; ActualHash='{actualHash}'; ExpectedSize='{plugin.PackageSizeBytes}'; ActualSize='{actualSize}'.");
File.Delete(downloadPath);
return new AirAppMarketInstallResult(
false,
null,
$"SHA-256 mismatch. Expected {plugin.Sha256}, actual {actualHash}.");
$"SHA-256 mismatch. Expected {plugin.Sha256}, actual {actualHash}. Expected size {plugin.PackageSizeBytes}, actual size {actualSize}. Source {resolvedDownloadUrl}.");
}
PluginManifest manifest;
if (OperatingSystem.IsWindows())
{
var helperResult = await _helperClient.InstallPackageAsync(
downloadPath,
_runtime.PluginsDirectory,
cancellationToken);
if (!helperResult.Success || string.IsNullOrWhiteSpace(helperResult.InstalledPackagePath))
{
return new AirAppMarketInstallResult(
false,
null,
helperResult.ErrorMessage ?? "Plugins install helper failed.");
}
manifest = _runtime.RegisterInstalledPluginPackage(helperResult.InstalledPackagePath);
}
else
{
manifest = _runtime.InstallPluginPackage(downloadPath);
}
var manifest = _runtime.InstallPluginPackage(downloadPath);
AppLogger.Info(
"PluginMarket",
$"Install staged successfully. PluginId='{manifest.Id}'; InstalledName='{manifest.Name}'; PackagePath='{downloadPath}'.");

View File

@@ -215,6 +215,8 @@ internal sealed class AirAppMarketIndexDocument
public DateTimeOffset GeneratedAt { get; init; }
public List<AirAppMarketSharedContractEntry> Contracts { get; init; } = [];
public List<AirAppMarketPluginEntry> Plugins { get; init; } = [];
public static AirAppMarketIndexDocument Load(string json, string sourceName)
@@ -236,6 +238,23 @@ internal sealed class AirAppMarketIndexDocument
private AirAppMarketIndexDocument ValidateAndNormalize(string sourceName)
{
var contracts = Contracts ?? [];
var normalizedContracts = new List<AirAppMarketSharedContractEntry>(contracts.Count);
var seenContracts = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var contract in contracts)
{
var normalizedContract = contract.ValidateAndNormalize(sourceName);
var contractKey = $"{normalizedContract.Id}@{normalizedContract.Version}";
if (!seenContracts.Add(contractKey))
{
throw new InvalidOperationException(
$"Market index '{sourceName}' contains duplicate shared contract '{contractKey}'.");
}
normalizedContracts.Add(normalizedContract);
}
var plugins = Plugins ?? [];
var normalizedPlugins = new List<AirAppMarketPluginEntry>(plugins.Count);
var seenIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
@@ -260,6 +279,10 @@ internal sealed class AirAppMarketIndexDocument
GeneratedAt = GeneratedAt == default
? throw new InvalidOperationException($"Market index '{sourceName}' is missing a valid generatedAt timestamp.")
: GeneratedAt,
Contracts = normalizedContracts
.OrderBy(contract => contract.Id, StringComparer.OrdinalIgnoreCase)
.ThenBy(contract => contract.Version, StringComparer.OrdinalIgnoreCase)
.ToList(),
Plugins = normalizedPlugins
.OrderBy(plugin => plugin.Name, StringComparer.OrdinalIgnoreCase)
.ToList()
@@ -373,6 +396,56 @@ internal sealed class AirAppMarketIndexDocument
}
}
internal sealed class AirAppMarketSharedContractEntry
{
public string Id { get; init; } = string.Empty;
public string Version { get; init; } = string.Empty;
public string AssemblyName { get; init; } = string.Empty;
public string DownloadUrl { get; init; } = string.Empty;
public string Sha256 { get; init; } = string.Empty;
public long PackageSizeBytes { get; init; }
public AirAppMarketSharedContractEntry ValidateAndNormalize(string sourceName)
{
var normalizedSha = AirAppMarketIndexDocument.NormalizeValue(Sha256)?.ToLowerInvariant()
?? throw new InvalidOperationException(
$"Market index '{sourceName}' is missing required property '{nameof(Sha256)}' for a shared contract.");
if (normalizedSha.Length != 64 || normalizedSha.Any(ch => !Uri.IsHexDigit(ch)))
{
throw new InvalidOperationException(
$"Market index '{sourceName}' declares invalid SHA-256 '{normalizedSha}' for shared contract '{Id}'.");
}
var normalizedDownloadUrl = AirAppMarketIndexDocument.NormalizeValue(DownloadUrl)
?? throw new InvalidOperationException(
$"Market index '{sourceName}' is missing required property '{nameof(DownloadUrl)}' for shared contract '{Id}'.");
AirAppMarketIndexDocument.EnsureUrl(normalizedDownloadUrl, nameof(DownloadUrl), sourceName);
if (PackageSizeBytes <= 0)
{
throw new InvalidOperationException(
$"Market index '{sourceName}' declares invalid packageSizeBytes '{PackageSizeBytes}' for shared contract '{Id}'.");
}
return new AirAppMarketSharedContractEntry
{
Id = AirAppMarketIndexDocument.NormalizeValue(Id)
?? throw new InvalidOperationException($"Market index '{sourceName}' is missing a shared contract id."),
Version = AirAppMarketIndexDocument.NormalizeVersion(Version, nameof(Version), sourceName),
AssemblyName = AirAppMarketIndexDocument.NormalizeValue(AssemblyName)
?? throw new InvalidOperationException($"Market index '{sourceName}' is missing assemblyName for shared contract '{Id}'."),
DownloadUrl = normalizedDownloadUrl,
Sha256 = normalizedSha,
PackageSizeBytes = PackageSizeBytes
};
}
}
internal sealed class AirAppMarketPluginEntry
{
public string Id { get; init; } = string.Empty;

View File

@@ -12,6 +12,8 @@ using Avalonia.Markup.Xaml;
using LanMountainDesktop.Models;
using LanMountainDesktop.Plugins;
using LanMountainDesktop.PluginSdk;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace LanMountainDesktop.Services;
@@ -19,8 +21,12 @@ public sealed class PluginRuntimeService : IDisposable
{
private const string PendingDeletionFileName = ".pending-plugin-deletions.json";
private readonly PluginLoaderOptions _loaderOptions;
private readonly PluginLoader _loader;
private readonly AppSettingsService _appSettingsService = new();
private readonly IHostApplicationLifecycle _applicationLifecycle = new HostApplicationLifecycleService();
private readonly PluginExportRegistry _exportRegistry = new();
private readonly PluginSharedContractManager _sharedContractManager;
private readonly IServiceProvider _hostServices;
private readonly IPluginPackageManager _packageManager;
private readonly List<LoadedPlugin> _loadedPlugins = [];
@@ -33,9 +39,12 @@ public sealed class PluginRuntimeService : IDisposable
public PluginRuntimeService()
{
PluginsDirectory = Path.Combine(AppContext.BaseDirectory, "Extensions", "Plugins");
_sharedContractManager = new PluginSharedContractManager(
Path.Combine(GetUserDataRootDirectory(), "PluginMarket"));
_packageManager = new PluginRuntimePackageManager(this);
_hostServices = new PluginHostServiceProvider(_packageManager);
_loader = new PluginLoader(CreateOptions());
_hostServices = new PluginHostServiceProvider(_packageManager, _applicationLifecycle, _exportRegistry);
_loaderOptions = CreateOptions();
_loader = new PluginLoader(_loaderOptions);
}
public string PluginsDirectory { get; }
@@ -50,6 +59,8 @@ public sealed class PluginRuntimeService : IDisposable
public IReadOnlyList<PluginDesktopComponentContribution> DesktopComponents => _desktopComponents;
public IPluginExportRegistry ExportRegistry => _exportRegistry;
public void LoadInstalledPlugins()
{
Directory.CreateDirectory(PluginsDirectory);
@@ -100,6 +111,27 @@ public sealed class PluginRuntimeService : IDisposable
continue;
}
try
{
RegisterSharedContractsForLoad(candidate.Manifest);
}
catch (Exception ex)
{
var dependencyFailure = PluginLoadResult.Failure(candidate.SourcePath, candidate.Manifest, ex);
_loadResults.Add(dependencyFailure);
_catalog.Add(new PluginCatalogEntry(
candidate.Manifest,
candidate.SourcePath,
candidate.SourceKind == PluginCatalogSourceKind.Package,
true,
false,
ex.Message,
0,
0));
Debug.WriteLine($"[PluginRuntime] Failed to prepare dependencies for '{candidate.Manifest.Id}': {ex}");
continue;
}
var loadResult = candidate.SourceKind switch
{
PluginCatalogSourceKind.Package => _loader.LoadFromPackage(
@@ -196,6 +228,14 @@ public sealed class PluginRuntimeService : IDisposable
}
}
public PluginManifest RegisterInstalledPluginPackage(string packagePath)
{
lock (_packageMutationGate)
{
return RegisterInstalledPluginPackageCore(packagePath);
}
}
public bool DeleteInstalledPlugin(string pluginId)
{
lock (_packageMutationGate)
@@ -268,6 +308,7 @@ public sealed class PluginRuntimeService : IDisposable
Directory.CreateDirectory(PluginsDirectory);
var manifest = ReadManifestFromPackage(fullPackagePath);
_sharedContractManager.EnsureInstalled(manifest);
AppLogger.Info(
"PluginRuntime",
$"Installing package. PluginId='{manifest.Id}'; Source='{fullPackagePath}'; PluginsDirectory='{PluginsDirectory}'.");
@@ -288,19 +329,42 @@ public sealed class PluginRuntimeService : IDisposable
return new PluginPackageInstallResult(manifest, replacedExisting, RestartRequired: true);
}
private PluginManifest RegisterInstalledPluginPackageCore(string packagePath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(packagePath);
var fullPackagePath = Path.GetFullPath(packagePath);
if (!File.Exists(fullPackagePath))
{
throw new FileNotFoundException($"Plugin package '{fullPackagePath}' was not found.", fullPackagePath);
}
var manifest = ReadManifestFromPackage(fullPackagePath);
_sharedContractManager.EnsureInstalled(manifest);
AppLogger.Info(
"PluginRuntime",
$"Registering externally installed package. PluginId='{manifest.Id}'; Source='{fullPackagePath}'.");
UpdateCatalogAfterPackageInstall(manifest, fullPackagePath);
PendingRestartStateService.SetPending(PendingRestartStateService.PluginCatalogReason, true);
return manifest;
}
public void Dispose()
{
UnloadInstalledPlugins();
_sharedContractManager.Dispose();
}
private void UnloadInstalledPlugins()
{
for (var i = _loadedPlugins.Count - 1; i >= 0; i--)
{
_exportRegistry.RemoveExports(_loadedPlugins[i].Manifest.Id);
_loadedPlugins[i].Dispose();
}
_loadedPlugins.Clear();
_exportRegistry.Clear();
_loadResults.Clear();
_catalog.Clear();
_settingsPages.Clear();
@@ -455,10 +519,23 @@ public sealed class PluginRuntimeService : IDisposable
: path + Path.DirectorySeparatorChar;
}
private static string GetUserDataRootDirectory()
{
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
if (string.IsNullOrWhiteSpace(localAppData))
{
return Path.Combine(AppContext.BaseDirectory, "Data");
}
return Path.Combine(localAppData, "LanMountainDesktop");
}
private static PluginLoaderOptions CreateOptions()
{
var options = new PluginLoaderOptions();
AddSharedAssembly(options, typeof(App).Assembly);
AddSharedAssembly(options, typeof(IServiceCollection).Assembly);
AddSharedAssembly(options, typeof(HostBuilderContext).Assembly);
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
@@ -489,6 +566,8 @@ public sealed class PluginRuntimeService : IDisposable
private void CollectContributions(LoadedPlugin loadedPlugin)
{
_exportRegistry.ReplaceExports(loadedPlugin.Manifest.Id, loadedPlugin.ExportedServices);
foreach (var settingsPage in loadedPlugin.SettingsPages)
{
_settingsPages.Add(new PluginSettingsPageContribution(loadedPlugin, settingsPage));
@@ -500,6 +579,17 @@ public sealed class PluginRuntimeService : IDisposable
}
}
private void RegisterSharedContractsForLoad(PluginManifest manifest)
{
foreach (var assemblyName in _sharedContractManager.PrepareForLoad(manifest))
{
if (!string.IsNullOrWhiteSpace(assemblyName))
{
_loaderOptions.SharedAssemblyNames.Add(assemblyName);
}
}
}
private void ApplyPendingPluginDeletions()
{
var pendingPaths = ReadPendingPluginDeletions();
@@ -652,17 +742,37 @@ public sealed class PluginRuntimeService : IDisposable
private sealed class PluginHostServiceProvider : IServiceProvider
{
private readonly IPluginPackageManager _packageManager;
private readonly IHostApplicationLifecycle _applicationLifecycle;
private readonly IPluginExportRegistry _exportRegistry;
public PluginHostServiceProvider(IPluginPackageManager packageManager)
public PluginHostServiceProvider(
IPluginPackageManager packageManager,
IHostApplicationLifecycle applicationLifecycle,
IPluginExportRegistry exportRegistry)
{
_packageManager = packageManager;
_applicationLifecycle = applicationLifecycle;
_exportRegistry = exportRegistry;
}
public object? GetService(Type serviceType)
{
return serviceType == typeof(IPluginPackageManager)
? _packageManager
: null;
if (serviceType == typeof(IPluginPackageManager))
{
return _packageManager;
}
if (serviceType == typeof(IHostApplicationLifecycle))
{
return _applicationLifecycle;
}
if (serviceType == typeof(IPluginExportRegistry))
{
return _exportRegistry;
}
return null;
}
}

View File

@@ -130,7 +130,25 @@ public partial class PluginSettingsPage : UserControl
};
}
private async void OnInstallPluginPackageClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
private void OnInstallPluginPackageClick(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
UiExceptionGuard.FireAndForgetGuarded(
OnInstallPluginPackageAsync,
"PluginSettings.InstallPackage",
context: "Page=PluginSettings",
onHandledException: ex =>
{
SetPackageImportStatus(
F(
"settings.plugins.install_failed_format",
"Failed to install plugin package: {0}",
ex.Message),
isError: true);
return Task.CompletedTask;
});
}
private async Task OnInstallPluginPackageAsync()
{
var runtime = (Application.Current as App)?.PluginRuntimeService;
if (runtime is null)

View File

@@ -0,0 +1,272 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Runtime.Loader;
using System.Security.Cryptography;
using System.Threading;
using LanMountainDesktop.PluginSdk;
using LanMountainDesktop.Views.SettingsPages;
namespace LanMountainDesktop.Plugins;
internal sealed class PluginSharedContractManager : IDisposable
{
private readonly string _contractsDirectory;
private readonly AirAppMarketIndexService _indexService;
private readonly HttpClient _httpClient;
private readonly object _gate = new();
private readonly Dictionary<string, LoadedSharedContract> _loadedContracts =
new(StringComparer.OrdinalIgnoreCase);
public PluginSharedContractManager(string cacheDirectory)
{
ArgumentException.ThrowIfNullOrWhiteSpace(cacheDirectory);
_contractsDirectory = Path.Combine(
GetSharedContractRootDirectory(),
"SharedContracts");
_indexService = new AirAppMarketIndexService(new AirAppMarketCacheService(cacheDirectory));
_httpClient = new HttpClient
{
Timeout = TimeSpan.FromMinutes(2)
};
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("LanMountainDesktop-SharedContracts/1.0");
}
public string ContractsDirectory => _contractsDirectory;
public void EnsureInstalled(PluginManifest manifest, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(manifest);
if (manifest.SharedContracts is not { Count: > 0 })
{
return;
}
var document = LoadIndex(cancellationToken);
foreach (var reference in manifest.SharedContracts)
{
EnsureInstalled(document, reference, cancellationToken);
}
}
public IReadOnlyList<string> PrepareForLoad(PluginManifest manifest, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(manifest);
if (manifest.SharedContracts is not { Count: > 0 })
{
return Array.Empty<string>();
}
var assemblyNames = new List<string>(manifest.SharedContracts.Count);
foreach (var reference in manifest.SharedContracts)
{
var assemblyPath = GetInstalledAssemblyPath(reference);
if (!File.Exists(assemblyPath))
{
throw new InvalidOperationException(
$"Plugin '{manifest.Id}' requires shared contract '{reference.Id}' version '{reference.Version}', but '{assemblyPath}' is not installed. Install the dependency from the market first.");
}
var loaded = LoadSharedAssembly(reference, assemblyPath);
assemblyNames.Add(loaded.AssemblyName);
}
return assemblyNames;
}
public void Dispose()
{
_httpClient.Dispose();
_indexService.Dispose();
}
private void EnsureInstalled(
AirAppMarketIndexDocument document,
PluginSharedContractReference reference,
CancellationToken cancellationToken)
{
var entry = document.Contracts.FirstOrDefault(candidate =>
string.Equals(candidate.Id, reference.Id, StringComparison.OrdinalIgnoreCase) &&
string.Equals(candidate.Version, reference.Version, StringComparison.OrdinalIgnoreCase));
if (entry is null)
{
throw new InvalidOperationException(
$"Shared contract '{reference.Id}' version '{reference.Version}' is not published in the configured market index.");
}
if (!string.Equals(entry.AssemblyName, reference.AssemblyName, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(
$"Shared contract '{reference.Id}' version '{reference.Version}' expects assembly '{reference.AssemblyName}', but the market entry provides '{entry.AssemblyName}'.");
}
var destinationPath = GetInstalledAssemblyPath(reference);
if (IsInstalledAndMatches(destinationPath, entry))
{
return;
}
Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!);
var temporaryPath = destinationPath + ".download";
try
{
if (AirAppMarketDefaults.TryResolveWorkspaceFile(entry.DownloadUrl, out var localSourcePath))
{
File.Copy(localSourcePath, temporaryPath, overwrite: true);
}
else
{
using var response = _httpClient.GetAsync(entry.DownloadUrl, cancellationToken)
.GetAwaiter()
.GetResult();
response.EnsureSuccessStatusCode();
using var responseStream = response.Content.ReadAsStreamAsync(cancellationToken)
.GetAwaiter()
.GetResult();
using var fileStream = File.Create(temporaryPath);
responseStream.CopyTo(fileStream);
}
ValidateInstalledFile(temporaryPath, entry);
File.Move(temporaryPath, destinationPath, overwrite: true);
}
finally
{
TryDeleteFile(temporaryPath);
}
}
private AirAppMarketIndexDocument LoadIndex(CancellationToken cancellationToken)
{
var result = _indexService.LoadAsync(cancellationToken).GetAwaiter().GetResult();
if (!result.Success || result.Document is null)
{
throw new InvalidOperationException(
$"Failed to load market index for shared contract resolution: {result.ErrorMessage ?? "Unknown error"}");
}
return result.Document;
}
private LoadedSharedContract LoadSharedAssembly(
PluginSharedContractReference reference,
string assemblyPath)
{
var assemblyName = AssemblyLoadContext.GetAssemblyName(assemblyPath).Name
?? throw new InvalidOperationException($"Failed to determine assembly name of '{assemblyPath}'.");
lock (_gate)
{
if (_loadedContracts.TryGetValue(assemblyName, out var existing))
{
if (!string.Equals(existing.ContractId, reference.Id, StringComparison.OrdinalIgnoreCase) ||
!string.Equals(existing.ContractVersion, reference.Version, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(
$"Shared contract assembly '{assemblyName}' is already loaded as '{existing.ContractId}' version '{existing.ContractVersion}', so plugin dependency '{reference.Id}' version '{reference.Version}' cannot be activated in the same host process.");
}
return existing;
}
var assembly = AssemblyLoadContext.Default.Assemblies.FirstOrDefault(candidate =>
string.Equals(candidate.GetName().Name, assemblyName, StringComparison.OrdinalIgnoreCase))
?? AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);
var loaded = new LoadedSharedContract(reference.Id, reference.Version, assemblyName, assemblyPath, assembly);
_loadedContracts[assemblyName] = loaded;
return loaded;
}
}
private static bool IsInstalledAndMatches(string assemblyPath, AirAppMarketSharedContractEntry entry)
{
if (!File.Exists(assemblyPath))
{
return false;
}
try
{
ValidateInstalledFile(assemblyPath, entry);
return true;
}
catch
{
return false;
}
}
private static void ValidateInstalledFile(string assemblyPath, AirAppMarketSharedContractEntry entry)
{
var actualSize = new FileInfo(assemblyPath).Length;
if (actualSize != entry.PackageSizeBytes)
{
throw new InvalidOperationException(
$"Shared contract '{entry.Id}' version '{entry.Version}' size mismatch. Expected {entry.PackageSizeBytes}, actual {actualSize}.");
}
using var stream = File.OpenRead(assemblyPath);
var actualHash = Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant();
if (!string.Equals(actualHash, entry.Sha256, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(
$"Shared contract '{entry.Id}' version '{entry.Version}' hash mismatch. Expected {entry.Sha256}, actual {actualHash}.");
}
}
private string GetInstalledAssemblyPath(PluginSharedContractReference reference)
{
return Path.Combine(
_contractsDirectory,
Sanitize(reference.Id),
Sanitize(reference.Version),
reference.AssemblyName);
}
private static string GetSharedContractRootDirectory()
{
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
if (string.IsNullOrWhiteSpace(localAppData))
{
return Path.Combine(AppContext.BaseDirectory, "Data");
}
return Path.Combine(localAppData, "LanMountainDesktop");
}
private static string Sanitize(string value)
{
var invalidChars = Path.GetInvalidFileNameChars();
return new string(value.Select(ch => invalidChars.Contains(ch) ? '_' : ch).ToArray());
}
private static void TryDeleteFile(string path)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
}
}
catch
{
// Ignore cleanup failures.
}
}
private sealed record LoadedSharedContract(
string ContractId,
string ContractVersion,
string AssemblyName,
string AssemblyPath,
Assembly Assembly);
}

View File

@@ -47,6 +47,9 @@ This directory contains the host-side plugin runtime for LanMountainDesktop.
- load plugin assemblies
- integrate plugin settings pages and desktop components
- expose market and plugin management in the host UI
- build a plugin-scoped `IServiceCollection`/`ServiceProvider` for API `2.0.0` plugins
- resolve shared contract assemblies into a version-isolated cache before plugin activation
- expose explicit cross-plugin exports through `IPluginExportRegistry`
### Market install order
@@ -55,3 +58,9 @@ This directory contains the host-side plugin runtime for LanMountainDesktop.
3. If Release resolution fails, the host falls back to the repository root `.laapp` from `downloadUrl`.
4. Plugin details always come from the repository root `README.md`.
5. Market installs are staged and take effect after restart.
### Dependency model
- Plugin-private managed and native NuGet dependencies remain plugin-local and are resolved through `AssemblyDependencyResolver`.
- Shared contract assemblies are downloaded from the official market index, cached under `LocalAppData/LanMountainDesktop/SharedContracts/<id>/<version>/`, and loaded into the default context so host and plugins share the same contract types.
- Different contract versions are isolated on disk. If two active plugins request incompatible versions of the same shared assembly name in one process, the host fails the later activation with a clear error instead of loading an ambiguous contract.

View File

@@ -77,7 +77,7 @@ public partial class SettingsWindow
Control content;
try
{
content = contribution.Registration.ContentFactory();
content = contribution.Registration.ContentFactory(contribution.Plugin.Services);
}
catch (Exception ex)
{

View File

@@ -31,6 +31,7 @@
- Windows 是当前主要目标平台。
- 已提供组件系统、插件系统、主题系统和设置系统。
- 中文为主语言,英文为附加扩展语言。
- 仓库主入口解决方案文件已切换为 `LanMountainDesktop.slnx`SDK 版本由根目录 `global.json` 锁定。
### 运行说明

6
global.json Normal file
View File

@@ -0,0 +1,6 @@
{
"sdk": {
"version": "10.0.103",
"rollForward": "latestFeature"
}
}

8
run.md
View File

@@ -8,12 +8,14 @@
- 安装 .NET SDK 10。
- 桌面端建议在 Windows 上运行。
- 仓库主入口解决方案文件为 `LanMountainDesktop.slnx`
- SDK 版本由仓库根目录 `global.json` 锁定。
### 构建
```bash
dotnet restore
dotnet build LanMountainDesktop.sln -c Debug
dotnet build LanMountainDesktop.slnx -c Debug
```
### 运行桌面端
@@ -41,11 +43,13 @@ dotnet run --project LanMountainDesktop/LanMountainDesktop.csproj
This guide explains how to run LanMountainDesktop locally.
The repository entry solution is `LanMountainDesktop.slnx`, and the SDK version is pinned by the root `global.json`.
### Build
```bash
dotnet restore
dotnet build LanMountainDesktop.sln -c Debug
dotnet build LanMountainDesktop.slnx -c Debug
```
### Run