mirror of
https://github.com/wwiinnddyy/LanMountainDesktop.git
synced 2026-06-20 23:54:26 +08:00
* Add Windows system chrome patchers (Harmony) Introduce support for toggling the system chrome on Windows using Harmony patchers. Adds Lib.Harmony.Thin to package props and project, new patcher infrastructure (ChromePatchState, PatcherEntrance) and two Harmony patches that disable FluentAvalonia's Windows chrome when configured. Program.cs now loads the chrome setting and installs patchers conditionally on Windows/x86-x64. Settings viewmodel and view updated: expose IsWindowsOs, require restart on appearance changes, migrate SettingsWindow to FAAppWindow and adapt titlebar/layout (include Windows caption placeholder and footer menu items). Also add a .gitkeep and a build log file. * Refactor settings window UI and theming Improve theming and layout for the Settings window and related services. - MaterialSurfaceService: add special material parameters for SettingsWindowBackground (lower alpha, no blur) and avoid hot-switching real backdrops for non-settings windows. - GlassEffectService: add AdaptiveSettingsWindowTintBrush + ResolveSettingsWindowTintAlpha to provide optional content tinting tied to system material mode. - SettingsWindowService: refactor theme application into ApplyThemeVariantAndResources, ensure settings window material is applied at show/activate times, and tidy theme/resource application flow. - SettingsWindow.axaml / .axaml.cs: restructure title bar (separate Grid.Row=0 border) and FANavigationView host, add pane-footer toggle button for :minimal layout, use dynamic corner radius resource, and update toggle/visibility/icon logic and responsive layout code. - SettingsPages: remove some IconText usages and adjust margins; use DesignCornerRadiusLg for update card corner radius. - Add NuGet.Config to set local globalPackagesFolder and ignore .nuget/packages in .gitignore. These changes aim to improve visuals, avoid backdrop overdraw, and make the settings window behavior consistent across themes and layouts. * Add localization and localize settings pages Add many new localization keys (en-US and zh-CN) for notifications, developer tools, about page, status bar, and video wallpaper. Update Notification, Dev, About and StatusBar view models to use LocalizationService, expose localized ObservableProperties, and refresh localized text at construction. Localize selection options and test notification texts, and fix notification severity handling. Wire up XAML to the new localized properties (About/Dev/StatusBar pages) and update the settings page title for notifications. Also adjust copyright line generation and replace hardcoded placeholders with bound Watermark properties. * Redesign settings window with fluent shell & search Rebuild the settings window as a Fluent shell: adds a custom 48-DIP titlebar with Back, pane toggle, icon/title, search box, restart/more menu, and caption-button spacer; moves compact pane toggle into the titlebar and preserves FANavigationView as the primary navigation surface. Introduces a SettingsSearchService (with UI AutoComplete integration, search indexing, navigation-by-result, and search result highlighting) plus focused tests for search filtering and theme material normalization. Adds navigation history/back stack, updates SettingsViewModels for new bindings and localization keys, and updates General/Apearance pages to expose new strings and options. Implements an "auto" system material mode: default in AppSettingsSnapshot, new MaterialAuto constants and normalization/resolution logic in ThemeAppearanceValues, WindowMaterialService and MaterialSurfaceService adjustments to prefer Mica on Win11 and Acrylic on Win10 using TransparencyLevelHint. GlassEffectService and AppearanceThemeService updated to use effective material mode and to track live theme state changes. Adds localization entries (en-US, zh-CN), spec/tasks docs, and other UI/style tweaks to support the redesign. * fix.修折叠与展开按钮 * Add OOBE startup presentation and settings merge Introduce a new OOBE step for "Startup & Presentation" that exposes startup and UI preferences in OobeWindow (toggles for taskbar, slide/fade transitions, fused popup, and autostart). Add HostAppSettingsOobeMerger to read/write Host settings.json (PascalCase fields) and MergeStartupPresentation behavior, plus LauncherWindowsStartupService to sync the current Launcher into the Windows Run key on Windows. Wire UI handlers, persist choices on Next, and load defaults when entering the step. Include unit tests for the merger, adjust SettingsWindow navigation pane/toggle handling, and update docs/LAUNCHER.md to describe the new OOBE step and implementation files. * Move whiteboard persistence to file storage Switch whiteboard note storage from legacy DB rows to per-note JSON files and add migration support. Update WhiteboardNoteSnapshot schema (version bump, viewport, canvas, expires, PathSvgData) and change IWhiteboardNotePersistenceService.SaveNote to return bool to surface write failures (e.g. read-only files). Implement file-based WhiteboardNotePersistenceService with legacy DB migration/cleanup, retention handling, and logging. Add comprehensive unit tests for persistence, stroke path builder, SVG import and viewport helper. Also add ThirdParty/DotNetCampus.InkCanvas project and reference it in the main csproj, and bump PostHog package to 2.6.0. * Introduce render gate and chart caching Replace UI DispatcherTimer polling with a StudySnapshotRenderGate across multiple widgets to queue and apply only the latest analytics snapshot; components updated include StudyDeductionReasonsWidget, StudyEnvironmentWidget, StudyInterruptDensityWidget, StudyNoiseCurveWidget. Add StudySnapshotRenderGate implementation to coordinate rendering and monitoring leases and update subscription/lease lifecycle handling (subscribe/unsubscribe, Acquire/Dispose leases, Clear/Dispose gate). Rewrite chart controls (StudyNoiseCurveChartControl and StudyNoiseDistributionScatterChartControl) to use stable logical-time origins, split series into static vs dynamic tails, add geometry/sample caching, stable jitter/coordinate mapping helpers, and expose internal helpers & counts for testing. Add unit tests (StudyComponentRenderingTests) covering the render gate and chart behaviors (layer counts, logical X mapping, stable jitter, cache rebuild). These changes improve rendering correctness and performance by avoiding redundant renders and enabling deterministic chart layout. * Use MaterialColorSnapshot in appearance flow Introduce unified material/color spec and tests, and refactor appearance plumbing to use MaterialColorSnapshot as the single source of truth. Add .trae material-color-service spec/checklist/tasks and integration/unit tests for plugin mapping and appearance VM behavior. AppearanceChangedEvent extended with new appearance change flags and HasChanged logic. ComponentEditorMaterialThemeAdapter rewritten to accept MaterialColorSnapshot and derive palette from snapshot data. Simplify AppearanceSettingsPageViewModel and related view code: remove legacy preview/custom-seed UI logic, preserve material/color fields when updating theme or corner radius, and update save calls to use with-expressions. Update ComponentEditorWindow to use adapter-provided OnPrimary brush and minor docs updates. * Add material color services, plugin DTOs, and tests Introduce IPC wire-format appearance DTOs (PluginIsolation.Contracts) and clarify they are distinct from the runtime PluginSdk snapshot. Update PluginSdk comments to document the runtime-facing snapshot shape. Change ComponentColorSchemeHelper to use the HostMaterialColorProvider and add an overload that accepts a MaterialColorSnapshot. Add new services and pipelines (MaterialColorService, MaterialSurfaceService, WindowMaterialService, WallpaperColorPipeline) and refactor AppearanceThemeService to depend on MaterialColorService while removing legacy internal implementations. Add multiple unit tests (ComponentColorSchemeHelper, PluginAppearanceBoundary, SettingsCatalogService, WallpaperSettingsPageViewModel) and update localization resources with new material_color and wallpaper keys. * Add CODE_WIKI and update localization Add a comprehensive CODE_WIKI.md documenting project architecture, modules, startup flow, plugin system, testing and developer workflows. Update localization resources (en-US.json, zh-CN.json) with new/translated keys for wallpaper controls (custom color UI), material & color settings (semantic roles, surfaces, refresh/polling state), appearance (corner radius), status bar font size options, privacy policy text, component library labels, clock settings, and new language entry (Korean). Also modify settings-related ViewModels and Settings page views to surface these new features and texts (MaterialColorSettingsPageViewModel.cs, SettingsViewModels.cs, WallpaperSettingsPageViewModel.cs, MainWindow.SettingsHardCut.Stubs.cs, ComponentsSettingsPage.axaml, WallpaperSettingsPage.axaml). * Add Data settings page and storage scanner Introduce a new "Data" settings page to visualize and manage local app storage. Adds DataStorageService (scanning, disk info, clean operations), DataSettingsPageViewModel, XAML view and code-behind, and HexToColor/HexToBrush converters; registers converters in App.axaml. Also update localization strings for the new page and add icon mapping so the settings entry uses the Database icon. Enables per-category and global cleaning workflows and formatted size display. * Add IPC backoff/retries and safer disposal Introduce exponential backoff, jitter and retry logic across IPC components to improve robustness and avoid tight retry loops; make disposal idempotent and add connection guards. Key changes: - LauncherCoordinatorIpcServer / LauncherIpcServer: add backoff constants, ComputeBackoff(), consecutive error tracking and delayed retries with jitter. - LanMountainDesktopIpcClient / LauncherIpcClient: add connect retry loops, timeouts, delayed retries, improved error logging, and use ArrayPool for buffered async writes; ensure proper cleanup on failures. - PublicIpcHostService: add disposed flag, guard OnPeerConnected and Dispose, and clear connected peers on dispose. - Add many auto-generated commit analysis docs under docs/auto_commit_md and new scripts for analyzing/generating commit docs. These changes aim to make IPC connection handling more resilient and resource-safe. * Add preview controls and settings UI tweaks Introduce GridPreviewControl and CornerRadiusPreviewControl for visual previews and wire them into the Components settings (add ScreenAspectRatio, CornerRadiusPreviewValue, and screen aspect init). Refactor ComponentsSettingsPage UI to show live previews. Improve DataSettingsPage layout and storage bar logic (use item percentages directly, include remaining segment, adjust visuals and visibility triggers). Simplify LauncherSettingsPage header/appearance layout. Add SECURITY_AUDIT_REPORT.md, analysis summary, mockup HTML, and a local .claude settings file. * Add install checkpoint/resume and DDSS workflows Introduce install checkpoint support and resume logic for updates, plus related locking and validation. Adds InstallCheckpoint model, AppJsonContext serialization, and UpdatePaths helpers for deployment lock, apply-in-progress lock and install-checkpoint path. UpdateEngineService gains checkpoint load/save/delete, incoming-state validation, resume logic for PLONDS and legacy updates, apply lock handling, and safer cleanup; ApplyPendingPlondsUpdateAsync and ApplyPendingUpdate flow updated accordingly. Add DeploymentLock contract and extend UpdateState with pause/resume/cancel helpers. Tests updated to cover stale/valid checkpoint resume and legacy/PLONDS flows. CI: enhance ddss-publish to detect release channel, validate S3 assets, prepare and atomically publish channel pointer; add ddss-rollback workflow to publish rollbacks; adjust plonds-build concurrency and release events. * changed.更了好多 * fix.消息盒子媒体播放器组件服务修复 * change.重做天气,为回到系统提供自定义功能。 * feat.airapp与融合桌面 * feat.动画优化与更新界面 * feat.数字时钟,白板功能修复 * feat.完善了时钟轻应用,为启动器提供了多语言支持 * feat.发布与打包优化 * changed.天气选项卡更新
850 lines
34 KiB
C#
850 lines
34 KiB
C#
using System.Diagnostics;
|
||
using Avalonia;
|
||
using Avalonia.Controls;
|
||
using Avalonia.Controls.ApplicationLifetimes;
|
||
using Avalonia.Markup.Xaml;
|
||
using Avalonia.Threading;
|
||
using LanMountainDesktop.Launcher.Models;
|
||
using LanMountainDesktop.Launcher.Resources;
|
||
using LanMountainDesktop.Launcher.Services;
|
||
using LanMountainDesktop.Launcher.Services.AirApp;
|
||
using LanMountainDesktop.Launcher.Services.Ipc;
|
||
using LanMountainDesktop.Launcher.Views;
|
||
using LanMountainDesktop.Shared.Contracts.Launcher;
|
||
using LanMountainDesktop.Shared.IPC;
|
||
using LanMountainDesktop.Shared.IPC.Abstractions.Services;
|
||
|
||
namespace LanMountainDesktop.Launcher;
|
||
|
||
public partial class App : Application
|
||
{
|
||
public override void Initialize()
|
||
{
|
||
if (Design.IsDesignMode)
|
||
{
|
||
AvaloniaXamlLoader.Load(this);
|
||
return;
|
||
}
|
||
|
||
Logger.Initialize();
|
||
var context = LauncherRuntimeContext.Current;
|
||
var execution = LauncherExecutionContext.Capture();
|
||
Logger.Info(
|
||
$"Launcher App initialize. Command='{context.Command}'; IsGuiMode={context.IsGuiCommand}; " +
|
||
$"IsPreview={context.IsPreviewCommand}; IsDebugMode={context.IsDebugMode}; " +
|
||
$"LaunchSource='{context.LaunchSource}'; IsElevated={execution.IsElevated}; " +
|
||
$"UserSid='{execution.UserSid ?? string.Empty}'; ExplicitAppRoot='{context.ExplicitAppRoot ?? "<none>"}'.");
|
||
|
||
AvaloniaXamlLoader.Load(this);
|
||
}
|
||
|
||
public override void OnFrameworkInitializationCompleted()
|
||
{
|
||
if (Design.IsDesignMode)
|
||
{
|
||
base.OnFrameworkInitializationCompleted();
|
||
return;
|
||
}
|
||
|
||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||
{
|
||
desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown;
|
||
|
||
var context = LauncherRuntimeContext.Current;
|
||
var execution = LauncherExecutionContext.Capture();
|
||
Logger.Info(
|
||
$"Framework initialization completed. Command='{context.Command}'; IsPreview={context.IsPreviewCommand}; " +
|
||
$"IsDebugMode={context.IsDebugMode}; LaunchSource='{context.LaunchSource}'; " +
|
||
$"IsElevated={execution.IsElevated}; UserSid='{execution.UserSid ?? string.Empty}'.");
|
||
|
||
if (HandlePreviewCommand(context, desktop))
|
||
{
|
||
base.OnFrameworkInitializationCompleted();
|
||
return;
|
||
}
|
||
|
||
if (context.IsAirAppBrokerCommand)
|
||
{
|
||
_ = RunAirAppBrokerAsync(desktop, context);
|
||
base.OnFrameworkInitializationCompleted();
|
||
return;
|
||
}
|
||
|
||
// 调试模式:只显示 DevDebugWindow,不走正常启动流程
|
||
// 避免启动主程序后 Launcher 自动退出,导致开发者无法预览 UI
|
||
if (context.IsDebugMode && !context.IsPreviewCommand &&
|
||
!string.Equals(context.Command, "apply-update", StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
Logger.Info("Debug mode active — showing DevDebugWindow instead of normal launch flow.");
|
||
var devDebugWindow = new DevDebugWindow();
|
||
devDebugWindow.Show();
|
||
base.OnFrameworkInitializationCompleted();
|
||
return;
|
||
}
|
||
|
||
if (string.Equals(context.Command, "apply-update", StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
var updateWindow = new UpdateWindow();
|
||
updateWindow.Show();
|
||
_ = RunApplyUpdateWithWindowAsync(desktop, context, updateWindow);
|
||
}
|
||
else
|
||
{
|
||
var splashWindow = CreateSplashWindow();
|
||
splashWindow.Show();
|
||
_ = RunCoordinatorWithSplashAsync(desktop, context, splashWindow);
|
||
}
|
||
}
|
||
|
||
base.OnFrameworkInitializationCompleted();
|
||
}
|
||
|
||
private static async Task RunAirAppBrokerAsync(
|
||
IClassicDesktopStyleApplicationLifetime desktop,
|
||
CommandContext context)
|
||
{
|
||
var appRoot = Commands.ResolveAppRoot(context);
|
||
var requesterPid = context.GetIntOption("requester-pid", 0);
|
||
var dataLocationResolver = new DataLocationResolver(appRoot);
|
||
Logger.Info($"Air APP broker starting. AppRoot='{appRoot}'; RequesterPid={requesterPid}.");
|
||
|
||
using var airAppIpcHost = new LauncherAirAppLifecycleIpcHost(
|
||
new LauncherAirAppLifecycleService(
|
||
new AirAppProcessStarter(
|
||
new AirAppHostLocator(),
|
||
() => appRoot,
|
||
() => null,
|
||
() => dataLocationResolver.ResolveDataRoot())));
|
||
airAppIpcHost.Start();
|
||
|
||
await WaitForAirAppBrokerExitAsync(requesterPid, airAppIpcHost.LifecycleService).ConfigureAwait(false);
|
||
|
||
Logger.Info("Air APP broker exiting.");
|
||
await Dispatcher.UIThread.InvokeAsync(() => desktop.Shutdown(0), DispatcherPriority.Background);
|
||
}
|
||
|
||
internal static async Task WaitForAirAppBrokerExitAsync(
|
||
int requesterPid,
|
||
LauncherAirAppLifecycleService airAppLifecycleService)
|
||
{
|
||
while (ShouldKeepAirAppBrokerAlive(requesterPid, airAppLifecycleService))
|
||
{
|
||
await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
|
||
}
|
||
}
|
||
|
||
internal static bool ShouldKeepAirAppBrokerAlive(
|
||
int requesterPid,
|
||
LauncherAirAppLifecycleService airAppLifecycleService)
|
||
{
|
||
return TryGetLiveProcess(requesterPid) || airAppLifecycleService.HasLiveAirApps();
|
||
}
|
||
|
||
private bool HandlePreviewCommand(CommandContext context, IClassicDesktopStyleApplicationLifetime desktop)
|
||
{
|
||
switch (context.Command.ToLowerInvariant())
|
||
{
|
||
case "preview-splash":
|
||
{
|
||
Logger.Info("Preview command: splash.");
|
||
var splashWindow = CreateSplashWindow();
|
||
splashWindow.SetDebugMode(true);
|
||
splashWindow.Show();
|
||
_ = SimulateSplashPreviewAsync(desktop, splashWindow);
|
||
return true;
|
||
}
|
||
case "preview-error":
|
||
{
|
||
Logger.Info("Preview command: error.");
|
||
var errorWindow = new ErrorWindow();
|
||
errorWindow.SetErrorMessage(Strings.Preview_ErrorMessage);
|
||
errorWindow.Show();
|
||
_ = WaitForWindowCloseAsync(desktop, errorWindow);
|
||
return true;
|
||
}
|
||
case "preview-multi-instance":
|
||
{
|
||
Logger.Info("Preview command: multi-instance prompt.");
|
||
var promptWindow = new MultiInstancePromptWindow();
|
||
promptWindow.SetDetails(Environment.ProcessId, "ForegroundDesktop");
|
||
promptWindow.Show();
|
||
_ = WaitForWindowCloseAsync(desktop, promptWindow);
|
||
return true;
|
||
}
|
||
case "preview-update":
|
||
{
|
||
Logger.Info("Preview command: update.");
|
||
var updateWindow = new UpdateWindow();
|
||
updateWindow.SetDebugMode(true);
|
||
updateWindow.Show();
|
||
_ = SimulateUpdatePreviewAsync(desktop, updateWindow);
|
||
return true;
|
||
}
|
||
case "preview-oobe":
|
||
{
|
||
Logger.Info("Preview command: oobe.");
|
||
var oobeWindow = new OobeWindow();
|
||
oobeWindow.Show();
|
||
_ = SimulateOobePreviewAsync(desktop, oobeWindow);
|
||
return true;
|
||
}
|
||
case "preview-debug":
|
||
{
|
||
Logger.Info("Preview command: debug window.");
|
||
var devDebugWindow = new DevDebugWindow();
|
||
devDebugWindow.Show();
|
||
return true;
|
||
}
|
||
default:
|
||
return false;
|
||
}
|
||
}
|
||
|
||
private static SplashWindow CreateSplashWindow()
|
||
{
|
||
var window = new SplashWindow();
|
||
TrySetSplashVersionInfo(window, LauncherRuntimeContext.Current);
|
||
return window;
|
||
}
|
||
|
||
private static void TrySetSplashVersionInfo(SplashWindow window, CommandContext context)
|
||
{
|
||
try
|
||
{
|
||
var appRoot = Commands.ResolveAppRoot(context);
|
||
var versionInfo = new DeploymentLocator(appRoot).GetVersionInfo();
|
||
window.SetVersionInfo(versionInfo.Version, versionInfo.Codename);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Logger.Warn($"Failed to set splash version info before coordinator start: {ex.Message}");
|
||
}
|
||
}
|
||
|
||
private async Task SimulateSplashPreviewAsync(IClassicDesktopStyleApplicationLifetime desktop, SplashWindow window)
|
||
{
|
||
var stages = new[] { "initializing", "update", "plugins", "launch", "ready" };
|
||
var messages = new[] { Strings.Preview_SplashInitializing, Strings.Preview_SplashCheckingUpdates, Strings.Preview_SplashCheckingPlugins, Strings.Preview_SplashLaunchingHost, Strings.Preview_SplashReady };
|
||
var reporter = (ISplashStageReporter)window;
|
||
|
||
for (var i = 0; i < stages.Length; i++)
|
||
{
|
||
reporter.Report(stages[i], messages[i]);
|
||
await Task.Delay(800).ConfigureAwait(false);
|
||
}
|
||
|
||
await Task.Delay(5000).ConfigureAwait(false);
|
||
await Dispatcher.UIThread.InvokeAsync(() => desktop.Shutdown(0));
|
||
}
|
||
|
||
private async Task SimulateUpdatePreviewAsync(IClassicDesktopStyleApplicationLifetime desktop, UpdateWindow window)
|
||
{
|
||
var stages = new[] { "verify", "extract", "apply", "plugins", "cleanup" };
|
||
|
||
for (var i = 0; i < stages.Length; i++)
|
||
{
|
||
window.Report(stages[i], string.Format(Strings.Preview_UpdateProcessing, stages[i]), (i + 1) * 20);
|
||
await Task.Delay(600).ConfigureAwait(false);
|
||
}
|
||
|
||
window.ReportComplete(true, null);
|
||
await Task.Delay(3000).ConfigureAwait(false);
|
||
await Dispatcher.UIThread.InvokeAsync(() => desktop.Shutdown(0));
|
||
}
|
||
|
||
private async Task SimulateOobePreviewAsync(IClassicDesktopStyleApplicationLifetime desktop, OobeWindow window)
|
||
{
|
||
try
|
||
{
|
||
await window.WaitForEnterAsync().ConfigureAwait(false);
|
||
Logger.Info("OOBE preview completed by user.");
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Logger.Error("OOBE preview failed.", ex);
|
||
}
|
||
|
||
await Dispatcher.UIThread.InvokeAsync(() => desktop.Shutdown(0));
|
||
}
|
||
|
||
private async Task WaitForWindowCloseAsync(IClassicDesktopStyleApplicationLifetime desktop, Window window)
|
||
{
|
||
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
window.Closed += (_, _) => tcs.TrySetResult();
|
||
await tcs.Task.ConfigureAwait(false);
|
||
await Dispatcher.UIThread.InvokeAsync(() => desktop.Shutdown(0));
|
||
}
|
||
|
||
private static async Task RunCoordinatorWithSplashAsync(
|
||
IClassicDesktopStyleApplicationLifetime desktop,
|
||
CommandContext context,
|
||
SplashWindow splashWindow)
|
||
{
|
||
LauncherResult result;
|
||
SplashWindow? currentSplashWindow = splashWindow;
|
||
var appRoot = Commands.ResolveAppRoot(context);
|
||
var dataLocationResolver = new DataLocationResolver(appRoot);
|
||
var startupAttemptRegistry = new StartupAttemptRegistry();
|
||
var coordinatorPipeName = LauncherCoordinatorIpcServer.CreatePipeName();
|
||
var successPolicy = LauncherFlowCoordinator.ResolveSuccessPolicyKey(context);
|
||
if (!startupAttemptRegistry.TryReserveCoordinator(
|
||
context.LaunchSource,
|
||
successPolicy,
|
||
coordinatorPipeName,
|
||
out var reservedAttempt,
|
||
out var activeCoordinatorAttempt))
|
||
{
|
||
result = await AttachToExistingCoordinatorAsync(
|
||
context,
|
||
currentSplashWindow,
|
||
activeCoordinatorAttempt).ConfigureAwait(false);
|
||
|
||
Logger.Info($"Secondary launcher completed. Success={result.Success}; Code='{result.Code}'.");
|
||
await WriteLauncherResultAsync(context, result).ConfigureAwait(false);
|
||
|
||
Environment.ExitCode = result.Success ? 0 : 1;
|
||
await Dispatcher.UIThread.InvokeAsync(() => desktop.Shutdown(Environment.ExitCode), DispatcherPriority.Background);
|
||
return;
|
||
}
|
||
|
||
using var airAppIpcHost = new LauncherAirAppLifecycleIpcHost(
|
||
new LauncherAirAppLifecycleService(
|
||
new AirAppProcessStarter(
|
||
new AirAppHostLocator(),
|
||
() => appRoot,
|
||
() => null,
|
||
() => dataLocationResolver.ResolveDataRoot())));
|
||
airAppIpcHost.Start();
|
||
|
||
using var coordinatorServer = new LauncherCoordinatorIpcServer(
|
||
coordinatorPipeName,
|
||
BuildCoordinatorStatusFromAttempt(reservedAttempt),
|
||
HandleCoordinatorRequestAsync,
|
||
startupAttemptRegistry.UpdateOwnedCoordinatorHeartbeat);
|
||
coordinatorServer.Start();
|
||
|
||
while (true)
|
||
{
|
||
try
|
||
{
|
||
Logger.Info(
|
||
$"Coordinator start. Command='{context.Command}'; AppRoot='{appRoot}'; " +
|
||
$"IsDebugMode={context.IsDebugMode}; LaunchSource='{context.LaunchSource}'; " +
|
||
$"ResultPath='{context.GetOption("result") ?? "<none>"}'.");
|
||
|
||
var deploymentLocator = new DeploymentLocator(appRoot);
|
||
var coordinator = new LauncherFlowCoordinator(
|
||
context,
|
||
deploymentLocator,
|
||
new OobeStateService(appRoot),
|
||
new UpdateEngineService(deploymentLocator),
|
||
new PluginInstallerService(),
|
||
startupAttemptRegistry,
|
||
coordinatorServer);
|
||
|
||
result = await coordinator.RunAsync(currentSplashWindow).ConfigureAwait(false);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Logger.Error("Coordinator threw an unhandled exception.", ex);
|
||
result = new LauncherResult
|
||
{
|
||
Success = false,
|
||
Stage = "launch",
|
||
Code = "exception",
|
||
Message = $"Launcher failed: {ex.Message}",
|
||
ErrorMessage = ex.ToString()
|
||
};
|
||
}
|
||
|
||
if (result.Success ||
|
||
result.Code == "host_not_found" ||
|
||
(!string.Equals(result.Stage, "launch", StringComparison.OrdinalIgnoreCase) &&
|
||
!string.Equals(result.Stage, "launchHost", StringComparison.OrdinalIgnoreCase)))
|
||
{
|
||
break;
|
||
}
|
||
|
||
var failureAction = await ShowFailureWindowAsync(result).ConfigureAwait(false);
|
||
if (failureAction == ErrorWindowResult.Exit)
|
||
{
|
||
break;
|
||
}
|
||
|
||
if (failureAction == ErrorWindowResult.ActivateExisting &&
|
||
await TryActivateExistingInstanceAsync().ConfigureAwait(false))
|
||
{
|
||
result = new LauncherResult
|
||
{
|
||
Success = true,
|
||
Stage = "launch",
|
||
Code = "activation_requested",
|
||
Message = "Launcher activated the existing desktop instance.",
|
||
Details = result.Details
|
||
};
|
||
break;
|
||
}
|
||
|
||
currentSplashWindow = CreateSplashWindow();
|
||
currentSplashWindow.Show();
|
||
}
|
||
|
||
Logger.Info($"Coordinator completed. Success={result.Success}; Stage='{result.Stage}'; Code='{result.Code}'.");
|
||
await WriteLauncherResultAsync(context, result).ConfigureAwait(false);
|
||
|
||
Environment.ExitCode = result.Success ? 0 : 1;
|
||
if (result.Success)
|
||
{
|
||
var hostPid = ResolveManagedHostPid(result, startupAttemptRegistry.GetOwnedAttempt()?.HostPid ?? 0);
|
||
await WaitForManagedProcessesToExitAsync(hostPid, airAppIpcHost.LifecycleService).ConfigureAwait(false);
|
||
}
|
||
|
||
await Dispatcher.UIThread.InvokeAsync(() => desktop.Shutdown(Environment.ExitCode), DispatcherPriority.Background);
|
||
}
|
||
|
||
private static int ResolveManagedHostPid(LauncherResult result, int fallbackHostPid)
|
||
{
|
||
if (result.Details.TryGetValue("hostPid", out var hostPidText) &&
|
||
int.TryParse(hostPidText, out var hostPid))
|
||
{
|
||
return hostPid;
|
||
}
|
||
|
||
if (result.Details.TryGetValue("existingHostPid", out var existingHostPidText) &&
|
||
int.TryParse(existingHostPidText, out var existingHostPid))
|
||
{
|
||
return existingHostPid;
|
||
}
|
||
|
||
return fallbackHostPid;
|
||
}
|
||
|
||
private static async Task WaitForManagedProcessesToExitAsync(
|
||
int hostPid,
|
||
LauncherAirAppLifecycleService airAppLifecycleService)
|
||
{
|
||
Logger.Info($"Launcher entering managed background lifetime. HostPid={hostPid}.");
|
||
while (TryGetLiveProcess(hostPid) || airAppLifecycleService.HasLiveAirApps())
|
||
{
|
||
await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
|
||
}
|
||
|
||
Logger.Info("Launcher managed background lifetime completed; no host or Air APP process remains.");
|
||
}
|
||
|
||
private static async Task<LauncherResult> AttachToExistingCoordinatorAsync(
|
||
CommandContext context,
|
||
SplashWindow? splashWindow,
|
||
StartupAttemptRecord? activeCoordinatorAttempt)
|
||
{
|
||
var reporter = splashWindow as ISplashStageReporter;
|
||
reporter?.Report("activation", Strings.Preview_ActivationConnecting);
|
||
|
||
if (activeCoordinatorAttempt is not null &&
|
||
!string.IsNullOrWhiteSpace(activeCoordinatorAttempt.CoordinatorPipeName))
|
||
{
|
||
var command = string.Equals(context.LaunchSource, "restart", StringComparison.OrdinalIgnoreCase)
|
||
? LauncherCoordinatorCommands.Attach
|
||
: LauncherCoordinatorCommands.ActivateDesktop;
|
||
var request = new LauncherCoordinatorRequest
|
||
{
|
||
Command = command,
|
||
LaunchSource = context.LaunchSource,
|
||
SuccessPolicy = LauncherFlowCoordinator.ResolveSuccessPolicyKey(context)
|
||
};
|
||
|
||
var response = await new LauncherCoordinatorIpcClient()
|
||
.SendAsync(activeCoordinatorAttempt.CoordinatorPipeName, request, TimeSpan.FromSeconds(2))
|
||
.ConfigureAwait(false);
|
||
|
||
if (response is not null)
|
||
{
|
||
reporter?.Report("activation", response.Message);
|
||
await DismissSplashIfNeededAsync(splashWindow).ConfigureAwait(false);
|
||
var success = response.Accepted ||
|
||
IsRecoverableActivationFailure(response.ActivationResult, response.Status);
|
||
return new LauncherResult
|
||
{
|
||
Success = success,
|
||
Stage = "launch",
|
||
Code = success && !response.Accepted ? "attached_to_launcher_coordinator" : response.Code,
|
||
Message = success && !response.Accepted
|
||
? "Attached to the active Launcher coordinator; desktop startup is still in progress."
|
||
: response.Message,
|
||
Details = BuildCoordinatorResultDetails(response.Status, response.ActivationResult)
|
||
};
|
||
}
|
||
}
|
||
|
||
var activation = await TryActivateExistingInstanceWithStatusAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
|
||
if (activation is not null)
|
||
{
|
||
reporter?.Report("activation", activation.Message);
|
||
await DismissSplashIfNeededAsync(splashWindow).ConfigureAwait(false);
|
||
var success = activation.Accepted || IsRecoverableActivationFailure(activation, null);
|
||
return new LauncherResult
|
||
{
|
||
Success = success,
|
||
Stage = "launch",
|
||
Code = activation.Accepted
|
||
? "existing_host_activated"
|
||
: success
|
||
? "existing_host_startup_pending"
|
||
: "existing_host_activation_failed",
|
||
Message = success && !activation.Accepted
|
||
? "Existing desktop process is still starting; Launcher attached without starting another process."
|
||
: activation.Message,
|
||
Details = BuildCoordinatorResultDetails(null, activation)
|
||
};
|
||
}
|
||
|
||
await DismissSplashIfNeededAsync(splashWindow).ConfigureAwait(false);
|
||
return new LauncherResult
|
||
{
|
||
Success = false,
|
||
Stage = "launch",
|
||
Code = "launcher_coordinator_unavailable",
|
||
Message = "Another Launcher is coordinating startup, but it did not respond in time.",
|
||
Details = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||
{
|
||
["activeCoordinatorPid"] = activeCoordinatorAttempt?.CoordinatorPid.ToString() ?? string.Empty,
|
||
["activeCoordinatorPipeName"] = activeCoordinatorAttempt?.CoordinatorPipeName ?? string.Empty,
|
||
["activeAttemptId"] = activeCoordinatorAttempt?.AttemptId ?? string.Empty,
|
||
["activeHostPid"] = activeCoordinatorAttempt?.HostPid.ToString() ?? string.Empty
|
||
}
|
||
};
|
||
}
|
||
|
||
private static async Task<LauncherCoordinatorResponse> HandleCoordinatorRequestAsync(
|
||
LauncherCoordinatorRequest request,
|
||
LauncherCoordinatorStatus status)
|
||
{
|
||
if (string.Equals(request.Command, LauncherCoordinatorCommands.ActivateDesktop, StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
var activation = await TryActivateExistingInstanceWithStatusAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
|
||
if (activation is not null)
|
||
{
|
||
if (!activation.Accepted && IsRecoverableActivationFailure(activation, status))
|
||
{
|
||
return new LauncherCoordinatorResponse
|
||
{
|
||
Accepted = true,
|
||
Code = "attached_to_launcher_coordinator",
|
||
Message = "Attached to the active Launcher coordinator; desktop startup is still in progress.",
|
||
Status = status,
|
||
ActivationResult = activation
|
||
};
|
||
}
|
||
|
||
return new LauncherCoordinatorResponse
|
||
{
|
||
Accepted = activation.Accepted,
|
||
Code = activation.Accepted ? "existing_host_activated" : "existing_host_activation_failed",
|
||
Message = activation.Message,
|
||
Status = status,
|
||
ActivationResult = activation
|
||
};
|
||
}
|
||
|
||
return new LauncherCoordinatorResponse
|
||
{
|
||
Accepted = true,
|
||
Code = "attached_to_launcher_coordinator",
|
||
Message = "Attached to the active Launcher coordinator; desktop startup is still in progress.",
|
||
Status = status
|
||
};
|
||
}
|
||
|
||
return new LauncherCoordinatorResponse
|
||
{
|
||
Accepted = true,
|
||
Code = "attached_to_launcher_coordinator",
|
||
Message = "Attached to the active Launcher coordinator.",
|
||
Status = status
|
||
};
|
||
}
|
||
|
||
private static LauncherCoordinatorStatus BuildCoordinatorStatusFromAttempt(StartupAttemptRecord attempt)
|
||
{
|
||
return new LauncherCoordinatorStatus
|
||
{
|
||
AttemptId = attempt.AttemptId,
|
||
CoordinatorPid = Environment.ProcessId,
|
||
HostPid = attempt.HostPid,
|
||
HostProcessAlive = TryGetLiveProcess(attempt.HostPid),
|
||
LaunchSource = attempt.LaunchSource,
|
||
SuccessPolicy = attempt.SuccessPolicy,
|
||
LastObservedStage = attempt.LastObservedStage,
|
||
LastObservedMessage = attempt.LastObservedMessage,
|
||
PublicIpcConnected = attempt.PublicIpcConnected || attempt.IpcConnected,
|
||
State = attempt.State.ToString(),
|
||
SoftTimeoutShown = attempt.State is StartupAttemptState.SoftTimeout or StartupAttemptState.DetachedWaiting,
|
||
Completed = attempt.State is StartupAttemptState.Succeeded or StartupAttemptState.Failed,
|
||
Succeeded = attempt.State == StartupAttemptState.Succeeded,
|
||
UpdatedAtUtc = attempt.UpdatedAtUtc
|
||
};
|
||
}
|
||
|
||
private static bool IsRecoverableActivationFailure(
|
||
PublicShellActivationResult? activation,
|
||
LauncherCoordinatorStatus? status)
|
||
{
|
||
if (activation is { Accepted: true })
|
||
{
|
||
return false;
|
||
}
|
||
|
||
if (status is { Completed: false, HostProcessAlive: true })
|
||
{
|
||
return true;
|
||
}
|
||
|
||
var shellStatus = activation?.Status;
|
||
if (shellStatus is null || !shellStatus.PublicIpcReady)
|
||
{
|
||
return false;
|
||
}
|
||
|
||
return !shellStatus.MainWindowOpened ||
|
||
!shellStatus.DesktopVisible ||
|
||
string.Equals(activation?.Code, "shell_not_ready", StringComparison.OrdinalIgnoreCase) ||
|
||
string.Equals(activation?.Code, "startup_pending", StringComparison.OrdinalIgnoreCase);
|
||
}
|
||
|
||
private static Dictionary<string, string> BuildCoordinatorResultDetails(
|
||
LauncherCoordinatorStatus? status,
|
||
PublicShellActivationResult? activation)
|
||
{
|
||
var details = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||
{
|
||
["coordinatorPid"] = status?.CoordinatorPid.ToString() ?? string.Empty,
|
||
["coordinatorAttemptId"] = status?.AttemptId ?? string.Empty,
|
||
["hostPid"] = status?.HostPid.ToString() ?? activation?.Status.ProcessId.ToString() ?? string.Empty,
|
||
["hostProcessAlive"] = status?.HostProcessAlive.ToString() ?? string.Empty,
|
||
["publicIpcConnected"] = (status?.PublicIpcConnected ?? activation is not null).ToString(),
|
||
["startupStage"] = status?.LastObservedStage.ToString() ?? string.Empty,
|
||
["startupState"] = status?.State ?? string.Empty,
|
||
["activationAccepted"] = activation?.Accepted.ToString() ?? string.Empty,
|
||
["shellState"] = activation?.Status.ShellState ?? status?.ShellStatus?.ShellState ?? string.Empty,
|
||
["trayState"] = activation?.Status.Tray.State ?? status?.ShellStatus?.Tray.State ?? string.Empty,
|
||
["taskbarUsable"] = activation?.Status.Taskbar.IsUsable.ToString() ?? status?.ShellStatus?.Taskbar.IsUsable.ToString() ?? string.Empty
|
||
};
|
||
|
||
return details;
|
||
}
|
||
|
||
private static async Task DismissSplashIfNeededAsync(SplashWindow? splashWindow)
|
||
{
|
||
if (splashWindow is null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
try
|
||
{
|
||
await splashWindow.DismissAsync().ConfigureAwait(false);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Logger.Warn($"Failed to dismiss splash after coordinator attach: {ex.Message}");
|
||
}
|
||
}
|
||
|
||
private static async Task WriteLauncherResultAsync(CommandContext context, LauncherResult result)
|
||
{
|
||
var resultPath = context.GetOption("result");
|
||
if (string.IsNullOrWhiteSpace(resultPath))
|
||
{
|
||
return;
|
||
}
|
||
|
||
try
|
||
{
|
||
await Commands.WriteResultIfNeededAsync(resultPath, result).ConfigureAwait(false);
|
||
Logger.Info($"Launcher result written to '{Path.GetFullPath(resultPath)}'.");
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Logger.Error($"Failed to write launcher result to '{resultPath}'.", ex);
|
||
}
|
||
}
|
||
|
||
private static async Task<ErrorWindowResult> ShowFailureWindowAsync(LauncherResult result)
|
||
{
|
||
ErrorWindow? errorWindow = null;
|
||
var hostProcessAlive = result.Details.TryGetValue("hostProcessAlive", out var hostProcessAliveText) &&
|
||
bool.TryParse(hostProcessAliveText, out var hostProcessAliveValue) &&
|
||
hostProcessAliveValue;
|
||
var hostPid = result.Details.TryGetValue("hostPid", out var hostPidText) &&
|
||
int.TryParse(hostPidText, out var parsedPid)
|
||
? parsedPid
|
||
: (int?)null;
|
||
|
||
await Dispatcher.UIThread.InvokeAsync(() =>
|
||
{
|
||
try
|
||
{
|
||
errorWindow = new ErrorWindow();
|
||
if (hostProcessAlive)
|
||
{
|
||
errorWindow.ConfigureForRunningHostFailure(hostPid);
|
||
}
|
||
else
|
||
{
|
||
errorWindow.ConfigureForGenericFailure(allowRetry: true);
|
||
}
|
||
|
||
errorWindow.SetErrorMessage(
|
||
$"Failed to start LanMountainDesktop.\n\nStage: {result.Stage}\nCode: {result.Code}\n\n{result.Message}");
|
||
errorWindow.Show();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Logger.Error("Failed to show launcher failure window.", ex);
|
||
}
|
||
});
|
||
|
||
if (errorWindow is null)
|
||
{
|
||
return ErrorWindowResult.Exit;
|
||
}
|
||
|
||
try
|
||
{
|
||
return await errorWindow.WaitForChoiceAsync().ConfigureAwait(false);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Logger.Error("Failure window closed unexpectedly.", ex);
|
||
return ErrorWindowResult.Exit;
|
||
}
|
||
}
|
||
|
||
private static async Task<bool> TryActivateExistingInstanceAsync()
|
||
{
|
||
var activation = await TryActivateExistingInstanceWithStatusAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
|
||
return activation?.Accepted == true;
|
||
}
|
||
|
||
private static async Task<PublicShellActivationResult?> TryActivateExistingInstanceWithStatusAsync(TimeSpan timeout)
|
||
{
|
||
try
|
||
{
|
||
using var ipcClient = new LanMountainDesktopIpcClient();
|
||
var connectTask = ipcClient.ConnectAsync();
|
||
var completedTask = await Task.WhenAny(connectTask, Task.Delay(timeout)).ConfigureAwait(false);
|
||
if (completedTask != connectTask)
|
||
{
|
||
return null;
|
||
}
|
||
|
||
await connectTask.ConfigureAwait(false);
|
||
if (!ipcClient.IsConnected)
|
||
{
|
||
return null;
|
||
}
|
||
|
||
var shellProxy = ipcClient.CreateProxy<IPublicShellControlService>();
|
||
var activationTask = shellProxy.ActivateMainWindowWithStatusAsync();
|
||
completedTask = await Task.WhenAny(activationTask, Task.Delay(timeout)).ConfigureAwait(false);
|
||
if (completedTask != activationTask)
|
||
{
|
||
return null;
|
||
}
|
||
|
||
return await activationTask.ConfigureAwait(false);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Logger.Warn($"Failed to activate the existing desktop instance: {ex.Message}");
|
||
return null;
|
||
}
|
||
}
|
||
|
||
private static bool TryGetLiveProcess(int processId)
|
||
{
|
||
if (processId <= 0)
|
||
{
|
||
return false;
|
||
}
|
||
|
||
try
|
||
{
|
||
using var process = Process.GetProcessById(processId);
|
||
return !process.HasExited;
|
||
}
|
||
catch
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
private static async Task RunApplyUpdateWithWindowAsync(
|
||
IClassicDesktopStyleApplicationLifetime desktop,
|
||
CommandContext context,
|
||
UpdateWindow window)
|
||
{
|
||
var appRoot = Commands.ResolveAppRoot(context);
|
||
var deploymentLocator = new DeploymentLocator(appRoot);
|
||
var updateEngine = new UpdateEngineService(deploymentLocator);
|
||
var pluginInstaller = new PluginInstallerService();
|
||
var pluginUpgrades = new PluginUpgradeQueueService(pluginInstaller);
|
||
|
||
var success = true;
|
||
string? errorMessage = null;
|
||
|
||
try
|
||
{
|
||
await Dispatcher.UIThread.InvokeAsync(() => window.Report("verify", Strings.Update_Verifying, 10));
|
||
var updateResult = await updateEngine.ApplyPendingUpdateAsync().ConfigureAwait(false);
|
||
if (!updateResult.Success)
|
||
{
|
||
success = false;
|
||
errorMessage = updateResult.Message;
|
||
}
|
||
|
||
if (success)
|
||
{
|
||
await Dispatcher.UIThread.InvokeAsync(() => window.Report("plugins", Strings.Update_ApplyingPlugins, 60));
|
||
var pluginsDir = context.GetOption("plugins-dir") ?? Path.Combine(appRoot, "plugins");
|
||
var queueResult = pluginUpgrades.ApplyPendingUpgrades(pluginsDir);
|
||
if (!queueResult.Success && queueResult.Code != "noop")
|
||
{
|
||
Logger.Error($"Plugin upgrade failed during apply-update: {queueResult.Message}");
|
||
}
|
||
}
|
||
|
||
if (success)
|
||
{
|
||
await Dispatcher.UIThread.InvokeAsync(() => window.Report("cleanup", Strings.Update_CleaningUp, 90));
|
||
deploymentLocator.CleanupOldDeployments(minVersionsToKeep: 3);
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
success = false;
|
||
errorMessage = ex.Message;
|
||
Logger.Error("Apply-update flow failed.", ex);
|
||
}
|
||
|
||
await Dispatcher.UIThread.InvokeAsync(() => window.ReportComplete(success, errorMessage));
|
||
await Task.Delay(success ? 1500 : 5000).ConfigureAwait(false);
|
||
|
||
await Commands.WriteResultIfNeededAsync(context.GetOption("result"), new LauncherResult
|
||
{
|
||
Success = success,
|
||
Stage = "apply-update",
|
||
Code = success ? "ok" : "failed",
|
||
Message = success ? "Update applied successfully." : (errorMessage ?? "Unknown error"),
|
||
Details = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||
{
|
||
["command"] = context.Command,
|
||
["launchSource"] = context.LaunchSource
|
||
}
|
||
}).ConfigureAwait(false);
|
||
|
||
Environment.ExitCode = success ? 0 : 1;
|
||
await Dispatcher.UIThread.InvokeAsync(() => desktop.Shutdown(Environment.ExitCode), DispatcherPriority.Background);
|
||
}
|
||
}
|