Skip to content
This repository was archived by the owner on Oct 11, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<ItemGroup Label="Infrastructure">
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.2" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.12" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.12" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="10.0.12" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.12" />
<PackageVersion Include="Serilog" Version="4.4.0" />
Expand Down
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,31 @@ Three widgets ship in the box:
The interface is available in **English and Simplified Chinese**, and follows the
system language until you pick one.

## Widget extension model

The shell depends only on `IWidgetProvider`. Providers are registered with
Microsoft.Extensions.DependencyInjection, and `WidgetRegistry` turns that ordered
set into the catalogue shown by the UI. Built-in widgets use
`services.AddBuiltInWidgets()`; an extension can register its own
`IWidgetProvider` in the same composition root. A duplicate widget ID now fails
at startup instead of silently choosing one provider, which makes plugin
configuration errors actionable.

Widgets communicate through typed, in-process messages exposed by
`IWidgetHost.Messages`; message contracts contain data only, and subscriptions
are disposed with the widget view model. See [the architecture guide](docs/architecture.md)
for module ownership, platform capability boundaries, persistence rules and the
theme/UI model.

This is intentionally **composition-time extensibility**, not yet arbitrary DLL
loading. Loading assemblies from a plugin directory needs an explicit isolation,
dependency-resolution, versioning, and trust policy; adding that before defining
those policies would make the app less predictable. When that host is introduced,
[`McMaster.NETCore.Plugins`](https://github.com/natemcmaster/DotNetCorePlugins)
is a good candidate to replace custom `AssemblyLoadContext` and dependency-probing
code. It should be isolated behind an `IWidgetProvider` discovery service, leaving
the widget shell and registry unchanged.

## Status

The desktop-layer mechanism, the shell and all three widgets are implemented and
Expand Down
101 changes: 101 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# DeskKit architecture

## Design boundary

DeskKit is a desktop host, not a collection of special-case windows. The host
owns process lifetime, persistence, platform integration and desktop placement.
Widgets own their own view, settings schema and widget-specific behaviour. The
boundary between the two is `DeskKit.Core`'s provider and host contracts.

```
DeskKit.App (Avalonia composition, shell, settings/tray)
├── DeskKit.Widgets (built-in widget modules)
├── DeskKit.Platform (capability implementations per OS)
└── DeskKit.Core (widget contracts, state model, persistence and pure rules)
```

Dependencies always point down this diagram. In particular, `Core` cannot
reference `App` or `Platform`; a widget cannot call Win32 or reach into another
widget's view model.

## Platform capabilities

`DeskKit.Platform` expresses host integration as capabilities:

| Capability | Contract | Windows implementation | Other platforms |
| --- | --- | --- | --- |
| Desktop placement and deliberate visibility | `IDesktopLayerService` | `WindowsDesktopLayerService` | `NullDesktopLayerService` |
| Window material | `IWindowMaterialService` | `WindowsWindowMaterialService` | `NullWindowMaterialService` |
| Login startup | `IAutoStartService` | `WindowsAutoStartService` | `NullAutoStartService` |
| File icons | `IShellIconLoader` | `WindowsShellIconLoader` | `NullShellIconLoader` |

`AddDeskKitPlatform()` is the only platform selection point used by the app.
New OS support therefore means adding implementations and extending that method,
not adding `OperatingSystem.Is…` branches in views or widgets. A null capability
must be a safe fallback, never an exception for a feature the host can simply
omit.

## Widget SDK and lifecycle

The SDK surface for a widget is deliberately small:

* `IWidgetProvider` describes a stable widget type and creates a view model for
one placement.
* `WidgetDescriptor` contains only identity, size and interaction policy; UI text
is a resource key so it can follow a runtime culture change.
* `WidgetContext` supplies placement, versioned settings and `IWidgetHost`.
* `WidgetViewModel` owns its Avalonia controls and is started after its window is
visible, then stopped and disposed before the window closes.

Providers are contributed through DI. `WidgetRegistry` preserves registration
order and rejects empty or duplicate IDs. This makes built-ins, test widgets and
future plugins use one composition seam. Runtime DLL discovery is intentionally
not part of this boundary until plugin versioning, isolation and trust policies
are specified.

## Widget communication

Widgets must not retain each other's view models. `IWidgetMessageBus` provides
typed, in-process publish/subscribe contracts through `IWidgetHost.Messages`.
Message types should be immutable data records in a small shared contract
assembly. Delivery is synchronous on the publisher's thread; UI subscribers must
marshal to Avalonia's UI thread where necessary, and each widget must dispose its
subscriptions with its view model. Persistent or cross-process workflows do not
belong on this bus.

For request/response, start with an explicit service contract owned by the host.
Do not layer a generic request bus over widget messages: doing so obscures
ownership, cancellation and failure handling.

## State and settings

`StateStore` is the single writer for `AppState` and SQLite is the source of
truth. It owns EF migrations, the pre-migration backup, old JSON import and the
read-only refusal rules for unavailable or newer schemas. Widget settings are
stored as versioned JSON per placement and migrated by the widget provider. The
shell debounces ordinary writes, but migrations and first-run seeding are saved
immediately.

New host-level data belongs in a typed `AppState`/EF entity migration. New
widget-level data belongs in the widget's settings plus an
`IWidgetSettingsMigrations` step. Neither should create an independent file.

## UI, theme and desktop behaviour

`ThemeService` owns application theme selection. Widgets consume semantic keys
from `WidgetTheme.axaml`; they must not hard-code light or dark content colours.
`IWindowMaterialService` resolves a requested platform material before widget
window layout is calculated, while `WidgetWindow` owns window-only concerns such
as card margins, drag/resize and snap glow. `WidgetShell` coordinates widgets;
it should not accumulate view rendering or native API calls.

## Library decisions

The project already uses Avalonia, CommunityToolkit.Mvvm, EF Core and Microsoft
DI where they reduce framework plumbing. Keep the message bus small and local:
MediatR would add indirection without solving a current cross-process or pipeline
need. If DLL plugins are introduced, evaluate `McMaster.NETCore.Plugins` to avoid
hand-written `AssemblyLoadContext` dependency resolution. For richer settings
validation, evaluate `FluentValidation` only once user-editable settings have
rules that are shared by UI and persistence; annotations or view-only validation
would otherwise split the rule source.
35 changes: 6 additions & 29 deletions src/DeskKit.App/App.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
using DeskKit.Core.Abstractions;
using DeskKit.Core.Services;
using DeskKit.Platform;
using DeskKit.Platform.Windows;
using DeskKit.Widgets;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -147,6 +146,7 @@ private static ServiceProvider BuildServices()
});

services.AddSingleton<StateStore>();
services.AddSingleton<IWidgetMessageBus, WidgetMessageBus>();
services.AddSingleton<TickService>();
services.AddSingleton<ThemeService>();
services.AddSingleton<INoticePresenter, NoticePresenter>();
Expand All @@ -155,36 +155,13 @@ private static ServiceProvider BuildServices()
// widgets' resource managers, and two of them would fight over the culture.
services.AddSingleton<LanguageService>();

services.AddSingleton<IDesktopLayerService>(_ =>
OperatingSystem.IsWindows()
? new WindowsDesktopLayerService()
: new NullDesktopLayerService());

services.AddSingleton<IWindowMaterialService>(_ =>
OperatingSystem.IsWindows()
? new WindowsWindowMaterialService()
: new NullWindowMaterialService());

services.AddSingleton<IAutoStartService>(_ =>
OperatingSystem.IsWindows()
? new WindowsAutoStartService()
: new NullAutoStartService());

services.AddSingleton<IShellIconLoader>(_ =>
OperatingSystem.IsWindows()
? new WindowsShellIconLoader()
: new NullShellIconLoader());
services.AddDeskKitPlatform();

// The shell only sees the contract. Built-ins and future plugins both add
// providers through DI, and the registry checks duplicate IDs at startup.
services.AddBuiltInWidgets();
services.AddSingleton(provider =>
{
var registry = new WidgetRegistry();
var iconLoader = provider.GetRequiredService<IShellIconLoader>();

foreach (var widgetProvider in BuiltInWidgets.CreateProviders(iconLoader))
registry.Register(widgetProvider);

return registry;
});
new WidgetRegistry(provider.GetServices<IWidgetProvider>()));

services.AddSingleton<WidgetShell>();

Expand Down
5 changes: 4 additions & 1 deletion src/DeskKit.App/Diagnostics/DesktopLayerSelfTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using DeskKit.App.Services;
using DeskKit.App.Views;
using DeskKit.Core;
using DeskKit.Core.Abstractions;
using DeskKit.Core.Data;
using DeskKit.Core.Services;
using DeskKit.Platform;
Expand Down Expand Up @@ -270,7 +271,8 @@ private static WidgetShell CreateShell(
WidgetRegistry? registry = null,
IDesktopLayerService? desktopLayer = null,
INoticePresenter? notices = null,
LanguageService? language = null) =>
LanguageService? language = null,
IWidgetMessageBus? messages = null) =>
new(
store ?? new StateStore(Path.Combine(directory, AppPaths.DatabaseFileName), directory),
registry ?? BuiltInRegistry(),
Expand All @@ -281,6 +283,7 @@ private static WidgetShell CreateShell(
new NullWindowMaterialService(),
language ?? new LanguageService(),
notices ?? NullNoticePresenter.Instance,
messages ?? new WidgetMessageBus(),
NullLogger<WidgetShell>.Instance);

/// <summary>
Expand Down
5 changes: 5 additions & 0 deletions src/DeskKit.App/Services/WidgetShell.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public sealed class WidgetShell : IWidgetHost, IDisposable
private readonly IWindowMaterialService _materials;
private readonly ILogger<WidgetShell> _logger;
private readonly INoticePresenter _notices;
private readonly IWidgetMessageBus _messages;
private readonly List<WidgetRuntime> _widgets = [];

/// <summary>The material every widget window carries, already resolved.</summary>
Expand All @@ -63,6 +64,7 @@ public WidgetShell(
IWindowMaterialService materials,
LanguageService languageService,
INoticePresenter notices,
IWidgetMessageBus messages,
ILogger<WidgetShell> logger)
{
_stateStore = stateStore;
Expand All @@ -74,6 +76,7 @@ public WidgetShell(
_materials = materials;
Language = languageService;
_notices = notices;
_messages = messages;
_logger = logger;

// Resolved once, at construction, because the answer changes the layout of
Expand Down Expand Up @@ -115,6 +118,8 @@ .. _widgets

public IReadOnlyList<ScreenBounds> Screens => ScreenProbe.GetScreens();

public IWidgetMessageBus Messages => _messages;

public void ShowSettings(WidgetViewModel widget)
{
OpenSettings(FindRuntime(widget));
Expand Down
33 changes: 33 additions & 0 deletions src/DeskKit.Core/Abstractions/IWidgetMessageBus.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
namespace DeskKit.Core.Abstractions;

/// <summary>
/// Marker interface for a message that may be exchanged by widget instances.
/// </summary>
/// <remarks>
/// A message contract belongs in a small shared package owned by the widgets
/// that use it. It must contain data only: widgets must not pass controls, view
/// models, or shell services through the bus.
/// </remarks>
public interface IWidgetMessage
{
}

/// <summary>
/// In-process communication boundary between independently developed widgets.
/// </summary>
/// <remarks>
/// Delivery is synchronous and takes place on the publishing thread. This keeps
/// the contract deterministic and avoids silently introducing a background UI
/// thread. A widget that changes Avalonia state must publish from, or marshal to,
/// the UI thread. Publishers do not need to know which widgets are listening.
/// </remarks>
public interface IWidgetMessageBus
{
/// <summary>Subscribes to one message contract.</summary>
IDisposable Subscribe<TMessage>(Action<TMessage> handler)
where TMessage : IWidgetMessage;

/// <summary>Publishes a message to the current subscribers of its contract.</summary>
void Publish<TMessage>(TMessage message)
where TMessage : IWidgetMessage;
}
8 changes: 8 additions & 0 deletions src/DeskKit.Core/Models/IWidgetHost.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
using DeskKit.Core.Abstractions;

namespace DeskKit.Core.Models;

/// <summary>Services a widget may use without knowing anything about the shell.</summary>
public interface IWidgetHost
{
/// <summary>
/// Sends and receives explicit data contracts between widgets without giving
/// one widget a reference to another widget's implementation.
/// </summary>
IWidgetMessageBus Messages { get; }

/// <summary>Current monitor layout, in physical pixels.</summary>
IReadOnlyList<ScreenBounds> Screens { get; }

Expand Down
78 changes: 78 additions & 0 deletions src/DeskKit.Core/Services/WidgetMessageBus.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
using DeskKit.Core.Abstractions;

namespace DeskKit.Core.Services;

/// <summary>
/// Process-wide implementation of <see cref="IWidgetMessageBus"/>.
/// </summary>
/// <remarks>
/// Handlers are invoked from a snapshot. A handler can therefore safely subscribe
/// or dispose itself while a message is being delivered, and a subscription never
/// keeps a widget alive after its view model disposes the returned handle.
/// </remarks>
public sealed class WidgetMessageBus : IWidgetMessageBus
{
private readonly object _gate = new();
private readonly Dictionary<Type, List<Delegate>> _handlers = [];

public IDisposable Subscribe<TMessage>(Action<TMessage> handler)
where TMessage : IWidgetMessage
{
ArgumentNullException.ThrowIfNull(handler);

lock (_gate)
{
if (!_handlers.TryGetValue(typeof(TMessage), out var handlers))
{
handlers = [];
_handlers.Add(typeof(TMessage), handlers);
}

handlers.Add(handler);
}

return new Subscription(this, typeof(TMessage), handler);
}

public void Publish<TMessage>(TMessage message)
where TMessage : IWidgetMessage
{
ArgumentNullException.ThrowIfNull(message);

Action<TMessage>[] handlers;
lock (_gate)
{
if (!_handlers.TryGetValue(typeof(TMessage), out var registered))
return;

handlers = registered.Cast<Action<TMessage>>().ToArray();
}

foreach (var handler in handlers)
handler(message);
}

private void Unsubscribe(Type messageType, Delegate handler)
{
lock (_gate)
{
if (!_handlers.TryGetValue(messageType, out var handlers))
return;

handlers.Remove(handler);
if (handlers.Count == 0)
_handlers.Remove(messageType);
}
}

private sealed class Subscription(WidgetMessageBus owner, Type messageType, Delegate handler) : IDisposable
{
private WidgetMessageBus? _owner = owner;

public void Dispose()
{
var owner = Interlocked.Exchange(ref _owner, null);
owner?.Unsubscribe(messageType, handler);
}
}
}
Loading
Loading