-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathServiceCollectionExtensions.cs
More file actions
329 lines (279 loc) · 15.9 KB
/
Copy pathServiceCollectionExtensions.cs
File metadata and controls
329 lines (279 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
using LoupixDeck.Controllers;
using LoupixDeck.Models;
using LoupixDeck.Registry;
using LoupixDeck.Services;
using LoupixDeck.Services.ActiveWindow;
using LoupixDeck.Services.AppSwitching;
using LoupixDeck.Services.Commands;
using LoupixDeck.Services.FolderNavigation;
using LoupixDeck.Services.Macros;
using LoupixDeck.Services.Mouse;
using LoupixDeck.Services.Plugins;
using LoupixDeck.Services.SystemPower;
using LoupixDeck.Utils;
using LoupixDeck.ViewModels;
using LoupixDeck.Views;
using Microsoft.Extensions.DependencyInjection;
namespace LoupixDeck;
/// <summary>
/// DI wiring for the issue #116 root + per-device topology.
///
/// <see cref="AddRootServices"/> registers the device-agnostic singletons (OS input,
/// config/asset IO, macro store, plugin discovery). <see cref="AddDeviceServices"/>
/// builds one child collection per device: it forwards the root singletons in via
/// <see cref="Forward{T}"/> and registers everything device-bound — including the
/// command catalog and the plugin-host wiring — so command activation and plugin
/// delegates resolve through THIS device's provider. Phase 1 instantiates exactly one
/// device; Phase 2 starts N child providers.
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>Re-expose a root-container singleton inside a device child collection.
/// The instance stays the single root instance; only the resolution is forwarded.</summary>
private static void Forward<T>(this IServiceCollection collection, IServiceProvider root)
where T : class
=> collection.AddSingleton(_ => root.GetRequiredService<T>());
// ───────────────────────── Root (device-agnostic) ─────────────────────────
public static void AddRootServices(this IServiceCollection collection)
{
// Registry of every device brought up this session — process-wide concerns
// (quit → shut down all devices' plugins) and phase-3 UI/CLI reach devices through it.
collection.AddSingleton<IDeviceHostRegistry, DeviceHostRegistry>();
// Routes the shared plugins' host calls to the device that triggered them.
collection.AddSingleton<IDeviceRouter, DeviceRouter>();
// Plugins are loaded once (shared instances); per-call device targeting is via
// the router. Loading natively-interop deps (e.g. NAudio/COM) per device would
// clash across collectible load contexts, so a single shared load is required.
collection.AddSingleton<IPluginManager, PluginManager>();
collection.AddSingleton<IConfigService, ConfigService>();
collection.AddSingleton<IAssetService, AssetService>();
collection.AddSingleton<IDBusController, DBusController>();
collection.AddSingleton<ICommandRunner, CommandRunner>();
if (OperatingSystem.IsLinux())
collection.AddSingleton<ISystemPowerService, LinuxSystemPowerService>();
#if WINDOWS
else if (OperatingSystem.IsWindows())
collection.AddSingleton<ISystemPowerService, WindowsSystemPowerService>();
#endif
else
collection.AddSingleton<ISystemPowerService, NoOpSystemPowerService>();
// Foreground-window monitor. The Linux monitor needs no #if guard (it only uses
// Process + /proc); only the Windows type lives behind #if WINDOWS.
if (OperatingSystem.IsLinux())
collection.AddSingleton<IActiveWindowMonitor, LinuxActiveWindowMonitor>();
#if WINDOWS
else if (OperatingSystem.IsWindows())
collection.AddSingleton<IActiveWindowMonitor, WindowsActiveWindowMonitor>();
#endif
else
collection.AddSingleton<IActiveWindowMonitor, NoOpActiveWindowMonitor>();
// User-defined macros: in-memory store (macros.json), shared across devices.
collection.AddSingleton<IMacroManager, MacroManager>();
// Runtime USB hot-plug (issue #116 phase 3b): the OS-native watcher signals
// topology changes; the manager diffs them against the running device set and
// raises attach/detach events App turns into provider/VM bring-up + teardown.
collection.AddSingleton<Services.HotPlug.IDeviceWatcher>(_ => Services.HotPlug.DeviceWatcher.Create());
collection.AddSingleton<Services.HotPlug.IHotPlugManager, Services.HotPlug.HotPlugManager>();
}
// ───────────────────────── Device (per-device child) ─────────────────────────
public static void AddDeviceServices(this IServiceCollection collection, ResolvedDevice resolved,
IServiceProvider root)
{
ArgumentNullException.ThrowIfNull(resolved);
ArgumentNullException.ThrowIfNull(root);
var deviceInfo = resolved.Info;
collection.AddSingleton(resolved);
collection.AddSingleton(deviceInfo);
// Re-expose the root singletons device-bound services depend on.
collection.Forward<IConfigService>(root);
collection.Forward<IAssetService>(root);
collection.Forward<IDBusController>(root);
collection.Forward<ICommandRunner>(root);
collection.Forward<ISystemPowerService>(root);
collection.Forward<IActiveWindowMonitor>(root);
collection.Forward<IMacroManager>(root);
collection.Forward<IDeviceHostRegistry>(root);
collection.Forward<IDeviceRouter>(root);
collection.Forward<IPluginManager>(root);
// OS input injection. Device-bound because the Windows routers read this
// device's LoupedeckConfig.InterceptionEnabled to pick SendInput vs the
// Interception driver per call.
if (OperatingSystem.IsLinux())
{
collection.AddSingleton<IUInputKeyboard, UInputKeyboard>();
// No Interception on Linux — register a stand-in so SettingsViewModel still resolves.
collection.AddSingleton<IInterceptionService, NoOpInterceptionService>();
// Virtual mouse for macro mouse steps (uinput-backed).
collection.AddSingleton<IVirtualMouse, UInputMouse>();
}
else
{
// Two concrete keyboard backends plus a router that picks between them per call:
// SendInput (always works) and Interception (kernel driver, reaches raw-input apps).
collection.AddSingleton<WindowsUInputKeyboard>();
collection.AddSingleton<InterceptionKeyboard>();
collection.AddSingleton<IUInputKeyboard, WindowsKeyboardRouter>();
// Manages downloading/installing/uninstalling the Interception driver (settings page).
collection.AddSingleton<IInterceptionService, InterceptionService>();
// Virtual mouse for macro mouse steps — same backend split as the keyboard:
// SendInput (always works) and Interception, picked per call by a router.
collection.AddSingleton<WindowsVirtualMouse>();
collection.AddSingleton<InterceptionMouse>();
collection.AddSingleton<IVirtualMouse, WindowsMouseRouter>();
}
collection.AddSingleton(provider =>
{
var configService = provider.GetRequiredService<IConfigService>();
var configPath = FileDialogHelper.GetConfigPath(deviceInfo, resolved.Serial);
var config = configService.LoadConfig<LoupedeckConfig>(configPath);
if (config == null)
{
config = new LoupedeckConfig
{
DeviceVid = deviceInfo.VendorId,
DevicePid = deviceInfo.ProductId,
DeviceSerial = resolved.Serial
};
// First launch for this device — seed the serial port/baud from any
// existing sibling config so the user does not have to re-run InitSetup
// just because they switched device type (the port is hardware, not
// device-type-specific). Crucial for the LOUPIXDECK_FAKE_DEVICE flow:
// without this the fresh config has no port → device times out →
// App.InitializeDevices catches and shuts down silently.
SeedSerialPortFromSibling(config, configService, deviceInfo);
}
return config;
});
collection.AddSingleton<IDeviceService, LoupedeckDeviceService>();
collection.AddSingleton<IPageManager, PageManager>();
// Command catalog — device-scoped so command activation
// (SysCommandService → ActivatorUtilities.CreateInstance(this provider))
// resolves the device-bound services commands inject.
collection.AddSingleton<ICommandService, CommandService>();
collection.AddSingleton<ICommandBuilder, CommandBuilder>();
collection.AddSingleton<ISysCommandService, SysCommandService>();
collection.AddSingleton<ICommandProvider, CoreCommandProvider>();
collection.AddSingleton<ICommandProvider, PluginCommandProvider>();
collection.AddSingleton<ICommandRegistry, CommandRegistry>();
// The command-selection menu is assembled generically from these contributors.
collection.AddSingleton<IMenuContributor, CommandGroupMenuContributor>();
collection.AddSingleton<IMenuContributor, UserMacroMenuContributor>();
collection.AddSingleton<IPluginMenuSource, PluginMenuContributor>();
collection.AddSingleton<IMenuTreeBuilder, MenuTreeBuilder>();
// Sequential macro-step executor (uses this device's command service).
collection.AddSingleton<MacroRunner>();
// Per-device plugin state: side-strip attachment (reads the shared root
// plugin list), install/enable, hot-reload.
collection.AddSingleton<ISideStripProviderRegistry, SideStripProviderRegistry>();
collection.AddSingleton<IPluginInstaller, PluginInstaller>();
collection.AddSingleton<IPluginReloadService, PluginReloadService>();
collection.AddSingleton<IDynamicTextManager, DynamicTextManager>();
collection.AddSingleton<IFolderNavigationService, FolderNavigationService>();
collection.AddSingleton<IExclusiveModeService, ExclusiveModeService>();
collection.AddSingleton<INativeHapticService, NativeHapticService>();
collection.AddSingleton<IAppSwitchingService, AppSwitchingService>();
collection.AddSingleton<LoupedeckLiveSController>();
collection.AddSingleton<IDeviceController>(sp => sp.GetRequiredService<LoupedeckLiveSController>());
collection.AddTransient<MainWindowViewModel>();
InitDialogs(collection);
}
private static void SeedSerialPortFromSibling(LoupedeckConfig fresh, IConfigService configService,
DeviceRegistry.DeviceInfo self)
{
try
{
var candidates = DeviceRegistry.SupportedDevices
.Where(d => d.Slug != self.Slug)
.Select(d => FileDialogHelper.GetConfigPath(d))
.Where(File.Exists)
.OrderByDescending(File.GetLastWriteTimeUtc)
.ToList();
foreach (var path in candidates)
{
var sibling = configService.LoadConfig<LoupedeckConfig>(path);
if (sibling == null || string.IsNullOrEmpty(sibling.DevicePort)) continue;
fresh.DevicePort = sibling.DevicePort;
fresh.DeviceBaudrate = sibling.DeviceBaudrate;
Console.WriteLine($"[Config] Seeded {self.Slug} port from sibling: {sibling.DevicePort} @ {sibling.DeviceBaudrate}");
return;
}
}
catch (Exception ex)
{
Console.WriteLine($"[Config] Sibling-port seed failed: {ex.Message}");
}
}
private static void InitDialogs(IServiceCollection collection)
{
collection.AddTransient<SimpleButtonSettings>();
collection.AddTransient<SimpleButtonSettingsViewModel>();
collection.AddTransient<RotaryButtonSettings>();
collection.AddTransient<RotaryButtonSettingsViewModel>();
collection.AddTransient<TouchButtonSettings>();
collection.AddTransient<TouchButtonSettingsViewModel>();
collection.AddTransient<SymbolPicker>();
collection.AddTransient<SymbolPickerViewModel>();
collection.AddTransient<TouchPageWallpaperSettings>();
collection.AddTransient<TouchPageWallpaperSettingsViewModel>();
collection.AddTransient<PageCommandsSettings>();
collection.AddTransient<PageCommandsSettingsViewModel>();
collection.AddTransient<Settings>();
collection.AddTransient<SettingsViewModel>();
collection.AddTransient<MacroEditor>();
collection.AddTransient<MacroEditorViewModel>();
collection.AddTransient<About>();
collection.AddTransient<AboutViewModel>();
collection.AddSingleton<IDialogService, DialogService>();
}
/// <summary>Root-level one-time init: shared macro store + the static bitmap
/// renderer's asset resolver. Runs once on the root provider.</summary>
public static void RootPostInit(this IServiceProvider root)
{
// Load user macros once — execution and menus read from memory afterwards.
root.GetRequiredService<IMacroManager>().Load();
// Let the (static) bitmap renderer resolve image-layer assets via DI.
var assetService = root.GetRequiredService<IAssetService>();
BitmapHelper.AssetResolver = assetService.Load;
}
/// <summary>Per-device one-time init: dialog registration, haptic materialization,
/// config self-heal, layer-handler rewiring. Runs on each device provider.</summary>
public static void DevicePostInit(this IServiceProvider services)
{
var dialogService = services.GetRequiredService<IDialogService>();
dialogService.Register<SimpleButtonSettingsViewModel, SimpleButtonSettings>();
dialogService.Register<RotaryButtonSettingsViewModel, RotaryButtonSettings>();
dialogService.Register<TouchButtonSettingsViewModel, TouchButtonSettings>();
dialogService.Register<SymbolPickerViewModel, SymbolPicker>();
dialogService.Register<TouchPageWallpaperSettingsViewModel, TouchPageWallpaperSettings>();
dialogService.Register<PageCommandsSettingsViewModel, PageCommandsSettings>();
dialogService.Register<SettingsViewModel, Settings>();
dialogService.Register<MacroEditorViewModel, MacroEditor>();
dialogService.Register<AboutViewModel, About>();
// Heal configs that were saved before HapticSteps had ObjectCreationHandling.Replace —
// those files accumulated duplicate steps on every save+load round.
var hapticConfig = services.GetRequiredService<LoupedeckConfig>();
while (hapticConfig.HapticSteps.Count > SettingsViewModel.MaxHapticSteps)
hapticConfig.HapticSteps.RemoveAt(hapticConfig.HapticSteps.Count - 1);
if (hapticConfig.HapticSteps.Count == 0)
hapticConfig.HapticSteps.Add(new HapticStep());
// Materialize the haptic service so it subscribes to config/page events,
// and push the persisted config to the device once it's connected.
services.GetRequiredService<INativeHapticService>().Apply();
// After config load, rewire per-layer PropertyChanged handlers so edits
// trigger TouchButton.Refresh(). The collection setter in TouchButton
// wires its own CollectionChanged hook, but layers created by the JSON
// converter bypass AttachLayerHandlers.
var config = services.GetRequiredService<LoupedeckConfig>();
if (config.TouchButtonPages != null)
{
foreach (var page in config.TouchButtonPages)
{
if (page?.TouchButtons == null) continue;
foreach (var button in page.TouchButtons)
{
button?.RewireLayerHandlers();
}
}
}
}
}