Snapshot for release 2026.10.21.3 (internal 04b831a)

This commit is contained in:
Tom Bohar 2026-10-21 21:03:43 -04:00
commit c4efe5821d
46 changed files with 2657 additions and 213 deletions

View file

@ -7,6 +7,10 @@
WindowStartupLocation="CenterOwner"
Title="Account Profile"
Background="#132028">
<Window.Resources>
<!-- The "show password" eye (the same one in FirstLoginDialog.axaml). -->
<StreamGeometry x:Key="EyeIcon">F0 M8,3 C4.4,3 1.6,5.3 0.5,8 C1.6,10.7 4.4,13 8,13 C11.6,13 14.4,10.7 15.5,8 C14.4,5.3 11.6,3 8,3 Z M8,4.3 C5.3,4.3 3,5.9 2,8 C3,10.1 5.3,11.7 8,11.7 C10.7,11.7 13,10.1 14,8 C13,5.9 10.7,4.3 8,4.3 Z M8,5.5 A2.5,2.5 0 1 1 8,10.5 A2.5,2.5 0 1 1 8,5.5 Z</StreamGeometry>
</Window.Resources>
<Grid RowDefinitions="*,Auto" Margin="18">
<StackPanel Spacing="12">
<TextBlock Text="Server" Foreground="#EAF0F4" />
@ -14,10 +18,22 @@
<TextBlock Text="Account" Foreground="#EAF0F4" />
<TextBox x:Name="AccountBox" />
<TextBlock Text="Password" Foreground="#EAF0F4" />
<TextBox x:Name="PasswordBox"
PasswordChar="*"
RevealPassword="False"
Watermark="Leave blank to keep the saved password hidden" />
<!-- The eye shows the password; with the box empty, the saved one (SavedPasswordReveal). -->
<Grid ColumnDefinitions="*,Auto">
<TextBox x:Name="PasswordBox"
Grid.Column="0"
Margin="0,0,6,0"
PasswordChar="*"
RevealPassword="False"
Watermark="Leave blank to keep the saved password" />
<ToggleButton x:Name="ShowPasswordToggle"
Grid.Column="1"
VerticalAlignment="Stretch"
ToolTip.Tip="Show password"
AutomationProperties.Name="Show password">
<PathIcon Data="{StaticResource EyeIcon}" Width="16" Height="16" />
</ToggleButton>
</Grid>
<CheckBox x:Name="ClearPasswordCheckBox"
Content="Clear saved password"
Foreground="#EAF0F4" />

View file

@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Platform.Storage;
using RynthCore.App;
@ -13,6 +14,8 @@ internal partial class AccountProfileDialog : Window
private readonly LaunchAccountProfile _profile;
private readonly List<LaunchServerProfile> _servers;
private readonly Func<string, string, List<string>> _knownCharactersFor;
// The eye beside the password box; it keeps no copy of the password.
private readonly SavedPasswordReveal _passwordReveal;
private List<string> _knownCharacters = [];
// Set once the player picks in "Log in as"; until then the saved choice is kept as it is
@ -27,6 +30,7 @@ internal partial class AccountProfileDialog : Window
_profile = profile;
_servers = servers;
_knownCharactersFor = knownCharactersFor;
_passwordReveal = SavedPasswordReveal.For(profile);
InitializeComponent();
ServerComboBox.ItemsSource = _servers.Select(s => s.DisplayName).ToList();
@ -41,7 +45,7 @@ internal partial class AccountProfileDialog : Window
? "Password needs re-entering: the saved one can't be read on this Windows user (settings copied from another user or PC?). Type it again to launch this account."
: !profile.HasSavedPassword
? "No password is saved for this profile yet. The game client won't start without one; you'll be asked for it on the first launch."
: "A password is saved for this profile, encrypted for this Windows user. It stays hidden unless you replace or clear it.";
: "A password is saved for this profile, encrypted for this Windows user. The eye shows it; type a new one to replace it.";
ServerComboBox.SelectionChanged += (_, _) => RefreshLoginAs();
AccountBox.TextChanged += (_, _) => RefreshLoginAs();
@ -52,12 +56,34 @@ internal partial class AccountProfileDialog : Window
};
RefreshLoginAs();
ShowPasswordToggle.IsCheckedChanged += (_, _) => OnShowPasswordChanged();
// The plain text lives only in the box, and only while the dialog is open.
Closed += (_, _) =>
{
PasswordBox.Text = string.Empty;
_passwordReveal.Reset();
};
SaveButton.Click += (_, _) => SaveAndClose();
CancelButton.Click += (_, _) => Close(false);
BrowseUserPrefsButton.Click += async (_, _) => await BrowseUserPrefsAsync();
SnapshotUserPrefsButton.Click += (_, _) => SnapshotLiveUserPrefs();
}
/// <summary>
/// The eye: on shows what's typed, or the saved password (decrypted now) when the box is empty;
/// off hides it and empties the box again if it still holds the saved password unchanged.
/// </summary>
private void OnShowPasswordChanged()
{
bool show = ShowPasswordToggle.IsChecked == true;
PasswordBox.Text = show ? _passwordReveal.EyeOn(PasswordBox.Text) : _passwordReveal.EyeOff(PasswordBox.Text);
PasswordBox.RevealPassword = show;
string tip = show ? SavedPasswordReveal.HideTip : SavedPasswordReveal.ShowTip;
ToolTip.SetTip(ShowPasswordToggle, tip);
AutomationProperties.SetName(ShowPasswordToggle, tip);
}
/// <summary>Lists the characters known for the account on the chosen server in "Log in as".</summary>
private void RefreshLoginAs()
{
@ -181,12 +207,14 @@ internal partial class AccountProfileDialog : Window
{
_profile.ClearPassword();
}
else if (!string.IsNullOrEmpty(PasswordBox.Text))
else if (_passwordReveal.PasswordToSave(PasswordBox.Text) is string newPassword)
{
// Encrypted at once (DPAPI, this Windows user); the plain text isn't kept on the profile.
_profile.SetPassword(PasswordBox.Text);
// A blank box, or the saved password the eye showed left unchanged, keeps the saved one.
_profile.SetPassword(newPassword);
}
PasswordBox.Text = string.Empty;
_passwordReveal.Reset();
_profile.Alias = AliasBox.Text?.Trim() ?? string.Empty;
_profile.UserPrefsPath = UserPrefsPathBox.Text?.Trim() ?? string.Empty;

View file

@ -7,7 +7,7 @@ namespace RynthCore.App.Avalonia;
/// <summary>
/// Read-modify-write access to %APPDATA%\RynthCore\engine.json. The launcher
/// owns a few engine-side flags (DComp overlay toggle, plugin paths, etc.)
/// owns a few engine-side flags (plugin paths, etc.)
/// but the engine has its own flags that the launcher should never overwrite
/// (EnableImGuiShell, EnableImGuiBackend, EngineHookCount, ...). This helper
/// preserves every field it doesn't touch so those don't get clobbered when

View file

@ -7,6 +7,10 @@
WindowStartupLocation="CenterOwner"
Title="First Login"
Background="#132028">
<Window.Resources>
<!-- The same eye as the account editor's (AccountProfileDialog.axaml). -->
<StreamGeometry x:Key="EyeIcon">F0 M8,3 C4.4,3 1.6,5.3 0.5,8 C1.6,10.7 4.4,13 8,13 C11.6,13 14.4,10.7 15.5,8 C14.4,5.3 11.6,3 8,3 Z M8,4.3 C5.3,4.3 3,5.9 2,8 C3,10.1 5.3,11.7 8,11.7 C10.7,11.7 13,10.1 14,8 C13,5.9 10.7,4.3 8,4.3 Z M8,5.5 A2.5,2.5 0 1 1 8,10.5 A2.5,2.5 0 1 1 8,5.5 Z</StreamGeometry>
</Window.Resources>
<Grid RowDefinitions="*,Auto" Margin="18">
<StackPanel Spacing="10">
<TextBlock x:Name="HeaderText" Foreground="#EAF0F4" FontSize="16" FontWeight="SemiBold" TextWrapping="Wrap" />
@ -22,9 +26,22 @@
<StackPanel x:Name="PasswordPanel" Spacing="10">
<TextBlock Text="Password" Foreground="#EAF0F4" />
<TextBox x:Name="PasswordBox" PasswordChar="*" RevealPassword="False" />
<!-- The eyes only reveal what's typed (nothing is saved yet to show). -->
<Grid ColumnDefinitions="*,Auto">
<TextBox x:Name="PasswordBox" Grid.Column="0" Margin="0,0,6,0" PasswordChar="*" RevealPassword="False" />
<ToggleButton x:Name="ShowPasswordToggle" Grid.Column="1" VerticalAlignment="Stretch"
ToolTip.Tip="Show password" AutomationProperties.Name="Show password">
<PathIcon Data="{StaticResource EyeIcon}" Width="16" Height="16" />
</ToggleButton>
</Grid>
<TextBlock Text="Confirm password" Foreground="#EAF0F4" />
<TextBox x:Name="ConfirmBox" PasswordChar="*" RevealPassword="False" />
<Grid ColumnDefinitions="*,Auto">
<TextBox x:Name="ConfirmBox" Grid.Column="0" Margin="0,0,6,0" PasswordChar="*" RevealPassword="False" />
<ToggleButton x:Name="ShowConfirmToggle" Grid.Column="1" VerticalAlignment="Stretch"
ToolTip.Tip="Show password" AutomationProperties.Name="Show password">
<PathIcon Data="{StaticResource EyeIcon}" Width="16" Height="16" />
</ToggleButton>
</Grid>
</StackPanel>
<TextBlock Text="The password is saved encrypted for this Windows user, like the other accounts."
Foreground="#9AA8B3" TextWrapping="Wrap" />

View file

@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using RynthCore.App;
namespace RynthCore.App.Avalonia;
@ -53,12 +55,31 @@ internal partial class FirstLoginDialog : Window
AccountBox.TextChanged += (_, _) => OnAccountChanged();
ReuseSavedPasswordCheckBox.IsCheckedChanged += (_, _) => UpdatePasswordPanel();
ShowPasswordToggle.IsCheckedChanged += (_, _) => Reveal(PasswordBox, ShowPasswordToggle);
ShowConfirmToggle.IsCheckedChanged += (_, _) => Reveal(ConfirmBox, ShowConfirmToggle);
// The plain text lives only in the boxes, and only while the dialog is open.
Closed += (_, _) =>
{
PasswordBox.Text = string.Empty;
ConfirmBox.Text = string.Empty;
};
LoginButton.Click += (_, _) => LogInAndClose();
CancelButton.Click += (_, _) => Close(false);
OnAccountChanged();
}
/// <summary>An eye: shows or hides what's typed in its box (nothing saved to fill in here).</summary>
private static void Reveal(TextBox box, ToggleButton eye)
{
bool show = eye.IsChecked == true;
box.RevealPassword = show;
string tip = show ? SavedPasswordReveal.HideTip : SavedPasswordReveal.ShowTip;
ToolTip.SetTip(eye, tip);
AutomationProperties.SetName(eye, tip);
}
/// <summary>Re-reads the account's characters and whether another profile's password can be reused.</summary>
private void OnAccountChanged()
{

View file

@ -110,8 +110,9 @@
<Grid Grid.Row="1" ColumnDefinitions="3*,Auto,2*">
<TabControl x:Name="MainTabs" Grid.Column="0" Margin="14,0,0,0" Padding="0">
<TabItem Header="Launcher">
<!-- Named so we can reset Offset on tab select; * rows inside this scroll
must not be used (they claim infinite height and clip Updates/Launch Targets). -->
<!-- Named so the tab keeps the player's scroll position (MainWindow.KeepLauncherScroll);
* rows inside this scroll must not be used (they claim infinite height and clip
Updates/Launch Targets). -->
<ScrollViewer x:Name="LauncherScroll"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled">
@ -130,6 +131,8 @@
<Button x:Name="UpdateCardActionButton" IsVisible="False" Margin="0,0,8,6"
Background="#26C1A6" Foreground="#0B1218" FontWeight="SemiBold" />
<Button x:Name="CheckUpdatesButton" Content="Check for updates" Margin="0,0,0,6" />
<Button x:Name="RollbackButton" Content="Roll back…" Margin="8,0,0,6" IsVisible="False"
ToolTip.Tip="Go back to an earlier RynthCore release if this one broke something. Updates then wait for a newer release." />
</WrapPanel>
</Grid>
<StackPanel x:Name="UpdateCardWhatsNewPanel" Spacing="2" IsVisible="False" />
@ -383,9 +386,9 @@
<TextBox x:Name="EnginePathTextBox" Watermark="C:\Games\RynthCore\Runtime\RynthCore.Engine.dll" />
<TextBlock Text="Extra Launch Arguments" Foreground="#EAF0F4" />
<TextBox x:Name="LaunchArgumentsTextBox"
Watermark="Optional arguments appended by the host"
AcceptsReturn="True"
MinHeight="64"
Watermark="Optional arguments added after each account's login"
ToolTip.Tip="Added to the end of every launch's command line, after the account, password and server the profiles set. It can't contain -a, -v, -h, -p or -rodat: set those in the account and server profiles. One line."
AcceptsReturn="False"
TextWrapping="Wrap" />
<Button x:Name="SavePathsButton"
Content="Save Runtime Paths"
@ -458,9 +461,6 @@
<TextBlock Text="These flags are read by RynthCore.Engine on each AC client launch. They write to %APPDATA%\RynthCore\engine.json — other engine flags in that file are preserved untouched."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
<CheckBox x:Name="EnableDcompOverlayCheckBox"
Content="Use DComp overlay (experimental, GPU-rendered)"
ToolTip.Tip="When ON, the engine starts the new DirectComposition overlay instead of the production AvaloniaOverlay. Mutually exclusive — Avalonia is single-app-per-process. Toggle takes effect on next AC client launch (a hot reload won't switch overlays)." />
<CheckBox x:Name="EnableImGuiBackendCheckBox"
Content="ImGui panels (preview)"
ToolTip.Tip="When ON, the engine runs its in-client ImGui layer, which docked panels move to as their ImGui versions are finished (choose per panel with /rc ui). Popped-out panels stay Avalonia windows. Costs nothing while no ImGui panel is open. Takes effect on next AC client launch or engine reload (RL)." />

View file

@ -106,6 +106,8 @@ internal partial class MainWindow : Window
private readonly Dictionary<string, DateTime> _autoLaunchAttemptTimesUtc = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DateTime> _autoLaunchServerDownNoticeTimesUtc = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DateTime> _autoLaunchNeedsPasswordNoticeTimesUtc = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DateTime> _autoLaunchNoServerNoticeTimesUtc = new(StringComparer.OrdinalIgnoreCase);
private DateTime _extraArgumentsNoticeUtc = DateTime.MinValue;
private readonly Dictionary<string, ServerAvailabilityState> _serverStatuses = new(StringComparer.OrdinalIgnoreCase);
private readonly List<PluginDefinition> _plugins =
[
@ -165,36 +167,80 @@ internal partial class MainWindow : Window
_updateTimer.Tick += async (_, _) => await CheckForUpdatesAsync();
_updateTimer.Start();
_ = CheckForUpdatesAsync();
// Keep Updates + Launch Targets reachable: a bad * row under this scroll used to
// leave Offset stuck with those cards clipped above the viewport.
MainTabs.SelectionChanged += (_, _) =>
{
if (MainTabs.SelectedIndex == 0)
ResetLauncherScrollToTop();
};
WireLauncherScroll();
Opened += async (_, _) =>
{
ResetLauncherScrollToTop();
await AskAboutUsageStatsOnceAsync();
await CleanUpDecalBridgeIfUnusedAsync(atStartup: true);
await CheckFolderAccessAtStartupAsync(); // MainWindow.FolderAccess.cs: can the game client save?
};
}
/// <summary>
/// Scroll the Launcher tab back to the top so Updates and Launch Targets stay reachable.
/// </summary>
private void ResetLauncherScrollToTop()
// ── The Launcher tab keeps the player's scroll position ───────────────────
// Player report R-20261021-183803-97c0: scrolled down, the tab jumped back to the top. It was
// reset on every SelectionChanged that reached the tab control, and that event bubbles: every
// ComboBox and ListBox inside the tabs raised it there too, and the launch targets' character
// dropdowns are refilled every 2 s (RefreshLaunchTargetCharacterSelections), the server list
// every 15 s, the lists whenever a profile changes. Now only the tab control's own selection
// counts, and selecting the tab puts the player back where they were.
// The reset worked around an earlier layout bug (a * row in the profile cards under this
// scroll left Updates and Launch Targets clipped above the viewport). That is fixed in the
// layout itself (all-Auto rows, MaxHeight on the lists, MainWindow.axaml), the ScrollViewer
// clamps a restored offset to the content's current height, and the Plugins tab's update
// button still opens this tab at the top, where the update card is.
private global::Avalonia.Vector _launcherScrollOffset;
private bool _launcherScrollRestorePending;
private void WireLauncherScroll()
{
try { LauncherScroll.Offset = new global::Avalonia.Vector(0, 0); }
catch { /* designer / pre-init */ }
// ScrollChanged bubbles too (the Launch Targets list and the profile lists scroll inside).
LauncherScroll.ScrollChanged += (_, e) =>
{
if (ReferenceEquals(e.Source, LauncherScroll) && MainTabs.SelectedIndex == 0 && !_launcherScrollRestorePending)
_launcherScrollOffset = LauncherScroll.Offset;
};
MainTabs.SelectionChanged += (_, e) =>
{
if (ReferenceEquals(e.Source, MainTabs) && MainTabs.SelectedIndex == 0)
KeepLauncherScroll();
};
}
/// <summary>
/// Puts the Launcher tab back where the player had it once layout has run: called when the tab
/// is selected again and before its content is refilled (lists, launch targets, update card).
/// Runs before input, so it never undoes the player's own scrolling.
/// </summary>
private void KeepLauncherScroll()
{
if (_launcherScrollRestorePending)
return;
_launcherScrollRestorePending = true;
Dispatcher.UIThread.Post(() =>
{
_launcherScrollRestorePending = false;
try
{
if (MainTabs.SelectedIndex == 0 && LauncherScroll.Offset != _launcherScrollOffset)
LauncherScroll.Offset = _launcherScrollOffset; // clamped to the content by the ScrollViewer
}
catch { /* window closing */ }
}, DispatcherPriority.Loaded);
}
/// <summary>The Plugins tab's "show the update card": the Launcher tab, at the top.</summary>
private void ShowLauncherTabAtTop()
{
_launcherScrollOffset = default;
MainTabs.SelectedIndex = 0;
KeepLauncherScroll(); // also when the tab was already showing
}
private void WireEvents()
{
AddServerButton.Click += async (_, _) => await AddServerAsync();
EditServerButton.Click += async (_, _) => await EditServerAsync();
DeleteServerButton.Click += (_, _) => DeleteServer();
DeleteServerButton.Click += async (_, _) => await DeleteServerAsync();
AddAccountButton.Click += async (_, _) => await AddAccountAsync();
EditAccountButton.Click += async (_, _) => await EditAccountAsync();
@ -217,10 +263,11 @@ internal partial class MainWindow : Window
FixFolderPermissionsButton.Click += async (_, _) => await FixFolderPermissionsAsync();
AddPluginDllButton.Click += async (_, _) => await AddPluginDllAsync();
CheckUpdatesButton.Click += async (_, _) => await CheckForUpdatesAsync();
RollbackButton.Click += async (_, _) => await RollBackAsync();
UpdateCardActionButton.Click += async (_, _) => await OnUpdateCardActionAsync();
CancelDownloadButton.Click += (_, _) => CancelDownload();
UpdateCardNewPluginsButton.Click += (_, _) => ShowAvailablePlugins();
ShowUpdateCardButton.Click += (_, _) => MainTabs.SelectedIndex = 0;
ShowUpdateCardButton.Click += (_, _) => ShowLauncherTabAtTop();
AutoUpdatePluginsCheckBox.IsChecked = _settings.AutoUpdatePlugins;
AutoUpdatePluginsCheckBox.IsCheckedChanged += (_, _) =>
{
@ -336,6 +383,12 @@ internal partial class MainWindow : Window
? _settings.EnginePath
: _injector.TryResolveEnginePath(null) ?? string.Empty;
LaunchArgumentsTextBox.Text = _settings.LaunchArguments;
// A whole-line override saved by an older launcher (with -a/-v/-h) would now ride along
// on every account: launches refuse it, so say so up front.
if (AcLaunchArgumentBuilder.ExtraArgumentsProblem(_settings.LaunchArguments, out _) is string extraProblem)
{
try { AppendActivity($"Runtime > Extra Launch Arguments: {extraProblem} Launches are blocked until it is fixed."); } catch { }
}
AllowMultipleClientsCheckBox.IsChecked = _settings.AllowMultipleClients;
SkipIntroVideosCheckBox.IsChecked = _settings.SkipIntroVideos;
@ -355,8 +408,9 @@ internal partial class MainWindow : Window
// Engine flags live in %APPDATA%\RynthCore\engine.json, not the
// launcher's own settings. The engine reads them on init; the launcher
// just provides a UI window into the same file.
EnableDcompOverlayCheckBox.IsChecked = EngineJsonStore.GetBool("EnableDcompOverlay") ?? false;
EnableDcompOverlayCheckBox.IsCheckedChanged += OnEnableDcompOverlayChanged;
// (No "Use DComp overlay" box any more: the DComp overlay is an Avalonia app, and the
// shipped CoreCLR engine runs without Avalonia (EngineSettings.EnableAvaloniaOverlay is
// always false there), so EnableDcompOverlay changed nothing. A saved key is left alone.)
// The engine treats a missing key as true.
EnableImGuiBackendCheckBox.IsChecked = EngineJsonStore.GetBool("EnableImGuiBackend") ?? true;
EnableImGuiBackendCheckBox.IsCheckedChanged += OnEnableImGuiBackendChanged;
@ -376,20 +430,6 @@ internal partial class MainWindow : Window
}
}
private void OnEnableDcompOverlayChanged(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
{
bool value = EnableDcompOverlayCheckBox.IsChecked == true;
try
{
EngineJsonStore.SetBool("EnableDcompOverlay", value);
AppendActivity($"Engine setting saved: EnableDcompOverlay={value}. Takes effect on next AC client launch.");
}
catch (Exception ex)
{
AppendActivity($"Failed to save EnableDcompOverlay to engine.json: {ex.Message}");
}
}
private void BuildPluginLoadout()
{
PluginLoadoutPanel.Children.Clear();
@ -674,6 +714,7 @@ internal partial class MainWindow : Window
private void RefreshLists()
{
KeepLauncherScroll();
_suppressPrimarySelectionChanged = true;
try
{
@ -693,9 +734,19 @@ internal partial class MainWindow : Window
private void RefreshSummary()
{
LaunchServerProfile? server = GetSelectedServer();
LaunchAccountProfile? account = GetSelectedAccount();
// The preview shows what a launch does: the account on its own server, not on the one
// selected in the server list (the launch never uses that one for it).
LaunchServerProfile? server = account != null ? ResolveServerForAccount(account) : null;
int checkedTargets = _settings.CheckedLaunchAccountProfileIds?.Count ?? 0;
if (account != null && server == null)
{
string noServer = $"{account.DisplayName}: {AccountServerRules.NoServerMessage(account, _settings.ServerProfiles.Count > 0)}";
SummaryText.Text = noServer;
LaunchProfileStatusText.Text = noServer;
LaunchPreviewText.Text = noServer;
return;
}
if (server == null || account == null)
{
SummaryText.Text = checkedTargets == 0
@ -774,13 +825,24 @@ internal partial class MainWindow : Window
await RefreshServerStatusesAsync();
}
private void DeleteServer()
private async Task DeleteServerAsync()
{
int index = ServerProfilesList.SelectedIndex;
if (index < 0 || index >= _settings.ServerProfiles.Count)
return;
string removedServerId = _settings.ServerProfiles[index].Id;
// Refused while accounts log on to it: they are never moved to another server (their
// passwords belong to this one). AccountServerRules says why refusing beats clearing.
LaunchServerProfile toRemove = _settings.ServerProfiles[index];
if (AccountServerRules.DeleteBlocker(toRemove, _settings.AccountProfiles) is string blocker)
{
AppendActivity($"Server not deleted: {toRemove.DisplayName} still has " +
$"{AccountServerRules.AccountsOn(toRemove, _settings.AccountProfiles).Count} account(s). Move or delete them first.");
await DecalBridgeDialog.InfoAsync(this, "Server still in use", blocker);
return;
}
string removedServerId = toRemove.Id;
bool removedSelected = string.Equals(removedServerId, _settings.SelectedServerProfileId, StringComparison.OrdinalIgnoreCase);
_settings.ServerProfiles.RemoveAt(index);
if (removedSelected)
@ -790,7 +852,7 @@ internal partial class MainWindow : Window
RefreshLists();
ServerProfilesList.SelectedIndex = Math.Min(index, _settings.ServerProfiles.Count - 1);
RefreshSummary();
AppendActivity($"Server removed: {index + 1}");
AppendActivity($"Server removed: {toRemove.DisplayName}");
}
private async System.Threading.Tasks.Task AddAccountAsync()
@ -973,6 +1035,7 @@ internal partial class MainWindow : Window
private void RefreshLaunchTargets()
{
KeepLauncherScroll();
LaunchTargetsPanel.Children.Clear();
_launchTargetStatusTexts.Clear();
_launchTargetChecks.Clear();
@ -986,13 +1049,10 @@ internal partial class MainWindow : Window
{
LaunchAccountProfile account = _settings.AccountProfiles[accountIndex];
// Try to find the associated server, or fallback to the first one if not set or invalid
LaunchServerProfile? server = _settings.ServerProfiles.FirstOrDefault(s => s.Id == account.ServerId);
if (server == null && _settings.ServerProfiles.Count > 0)
{
server = _settings.ServerProfiles.FirstOrDefault();
account.ServerId = server?.Id ?? string.Empty;
}
// The account's own server only. An account whose server is missing used to be bound
// to the first server here (and saved), which sent its password to that server on
// the next launch; now it shows "No Server" and can't launch (AccountServerRules).
LaunchServerProfile? server = ResolveServerForAccount(account);
var container = new Grid
{
@ -1118,7 +1178,7 @@ internal partial class MainWindow : Window
button.Click += async (_, _) =>
{
LaunchServerProfile? server = _settings.ServerProfiles.FirstOrDefault(s => s.Id == account.ServerId);
LaunchServerProfile? server = ResolveServerForAccount(account);
var dialog = new LoginCommandsDialog(account, server);
await dialog.ShowDialog(this);
if (dialog.ChangesSaved)
@ -1524,11 +1584,15 @@ internal partial class MainWindow : Window
return;
}
// Ensure the account is associated with the currently selected server if it doesn't have one
// An account that never had a server (added before any server existed) takes the one
// selected beside it, at the player's click and said in Activity. An account that names
// a server, even a deleted one, is never changed here (AccountServerRules).
LaunchServerProfile? selectedServer = GetSelectedServer();
if (selectedServer != null && string.IsNullOrEmpty(account.ServerId))
if (selectedServer != null && string.IsNullOrWhiteSpace(account.ServerId))
{
account.ServerId = selectedServer.Id;
SaveSettings();
AppendActivity($"{account.DisplayName} had no server; it now logs on to {selectedServer.DisplayName}.");
}
_settings.CheckedLaunchAccountProfileIds ??= [];
@ -1553,7 +1617,11 @@ internal partial class MainWindow : Window
SaveSettings();
RefreshSummary();
if (appendActivity)
{
AppendActivity("Runtime paths saved.");
if (AcLaunchArgumentBuilder.ExtraArgumentsProblem(_settings.LaunchArguments, out _) is string extraProblem)
AppendActivity($"Launches are blocked until this is fixed: {extraProblem}");
}
}
private void SaveLaunchBehavior(bool appendActivity = true)
@ -1661,10 +1729,17 @@ internal partial class MainWindow : Window
return;
}
string overrideArguments = isAutomaticLaunch ? string.Empty : LaunchArgumentsTextBox.Text?.Trim() ?? string.Empty;
if (!string.IsNullOrWhiteSpace(overrideArguments) && accountsToLaunch.Count > 1)
// Extra Launch Arguments go after each account's own arguments, for manual and automatic
// launches alike. They used to replace the whole line instead (and only manually, one
// account at a time); ExtraArgumentsProblem refuses what an old override would carry.
if (AcLaunchArgumentBuilder.ExtraArgumentsProblem(LaunchArgumentsTextBox.Text, out string extraArguments) is string extraProblem)
{
AppendActivity("Launch blocked: manual launch arguments can only be used with one account at a time.");
DateTime nowUtc = DateTime.UtcNow;
if (!isAutomaticLaunch || nowUtc - _extraArgumentsNoticeUtc >= AutoLaunchNeedsPasswordLogCooldown)
{
_extraArgumentsNoticeUtc = nowUtc;
AppendActivity($"Launch blocked: {extraProblem}");
}
return;
}
@ -1710,26 +1785,23 @@ internal partial class MainWindow : Window
// No usable password: the client would refuse to start ("You can only run the game from
// the launcher program") and exit within seconds. A manual launch asks for it (and the
// account) in the First Login dialog; an automatic one skips the account.
if (string.IsNullOrWhiteSpace(overrideArguments))
var ready = new List<LaunchAccountProfile>(accountsToLaunch.Count);
foreach (LaunchAccountProfile account in accountsToLaunch)
{
var ready = new List<LaunchAccountProfile>(accountsToLaunch.Count);
foreach (LaunchAccountProfile account in accountsToLaunch)
{
if (!AcLaunchArgumentBuilder.NeedsPassword(account))
ready.Add(account);
else if (isAutomaticLaunch)
AppendActivity($"Auto launch skipped for {account.DisplayName}: {AcLaunchArgumentBuilder.MissingPasswordMessage(account.AccountName)}");
else if (await PromptFirstLoginAsync(account))
ready.Add(account);
else
AppendActivity($"Launch cancelled for {account.DisplayName}: no password entered.");
}
if (ready.Count == 0)
return;
accountsToLaunch = ready;
if (!AcLaunchArgumentBuilder.NeedsPassword(account))
ready.Add(account);
else if (isAutomaticLaunch)
AppendActivity($"Auto launch skipped for {account.DisplayName}: {AcLaunchArgumentBuilder.MissingPasswordMessage(account.AccountName)}");
else if (await PromptFirstLoginAsync(account))
ready.Add(account);
else
AppendActivity($"Launch cancelled for {account.DisplayName}: no password entered.");
}
if (ready.Count == 0)
return;
accountsToLaunch = ready;
SaveRuntimePaths(appendActivity: !isAutomaticLaunch);
SaveLaunchBehavior(appendActivity: !isAutomaticLaunch);
@ -1771,7 +1843,7 @@ internal partial class MainWindow : Window
{
if (!TryGetLaunchArgumentsForAccount(
account,
allowArgumentOverride: !isAutomaticLaunch,
extraArguments,
out string launchArguments,
out string launchSummary,
out string error))
@ -2100,7 +2172,7 @@ internal partial class MainWindow : Window
LaunchServerProfile? server = ResolveServerForAccount(account);
if (server == null)
{
AppendActivity($"Launch blocked for {account.DisplayName}: add a server profile first.");
AppendActivity($"Launch blocked for {account.DisplayName}: {AccountServerRules.NoServerMessage(account, _settings.ServerProfiles.Count > 0)}");
return false;
}
@ -2163,38 +2235,27 @@ internal partial class MainWindow : Window
SessionStateStore.WriteForProcess(processId, record);
}
/// <param name="extraArguments">Extra Launch Arguments, already checked by
/// <see cref="AcLaunchArgumentBuilder.ExtraArgumentsProblem"/>; appended after the account's own.</param>
private bool TryGetLaunchArgumentsForAccount(
LaunchAccountProfile account,
bool allowArgumentOverride,
string extraArguments,
out string arguments,
out string launchSummary,
out string error)
{
string overrideArguments = allowArgumentOverride
? LaunchArgumentsTextBox.Text?.Trim() ?? string.Empty
: string.Empty;
if (!string.IsNullOrWhiteSpace(overrideArguments))
{
arguments = overrideArguments;
launchSummary = string.IsNullOrWhiteSpace(account.DisplayName)
? "Manual argument override"
: $"Manual argument override / {account.DisplayName}";
error = string.Empty;
return true;
}
LaunchServerProfile? server = ResolveServerForAccount(account);
if (server == null)
{
arguments = string.Empty;
launchSummary = string.Empty;
error = "Select a server profile, or enter manual launch arguments.";
error = AccountServerRules.NoServerMessage(account, _settings.ServerProfiles.Count > 0);
return false;
}
try
{
arguments = _launchArgumentBuilder.BuildArguments(server, account);
arguments = AcLaunchArgumentBuilder.WithExtraArguments(_launchArgumentBuilder.BuildArguments(server, account), extraArguments);
launchSummary = _launchArgumentBuilder.Describe(server, account);
error = string.Empty;
return true;
@ -2208,18 +2269,12 @@ internal partial class MainWindow : Window
}
}
private LaunchServerProfile? ResolveServerForAccount(LaunchAccountProfile account)
{
if (!string.IsNullOrWhiteSpace(account.ServerId))
{
LaunchServerProfile? savedServer = _settings.ServerProfiles.FirstOrDefault(server =>
string.Equals(server.Id, account.ServerId, StringComparison.OrdinalIgnoreCase));
if (savedServer != null)
return savedServer;
}
return GetSelectedServer() ?? _settings.ServerProfiles.FirstOrDefault();
}
/// <summary>
/// The server profile the account names, or null. No fallback to the selected or first
/// server: that would send this account's password to a server it doesn't belong to.
/// </summary>
private LaunchServerProfile? ResolveServerForAccount(LaunchAccountProfile account) =>
AccountServerRules.ServerFor(account, _settings.ServerProfiles);
private List<LaunchAccountProfile> GetCheckedLaunchAccounts()
{
@ -2514,7 +2569,10 @@ internal partial class MainWindow : Window
_updateChecking = false;
AnnounceNewPlugins(_updateCheck);
BuildAvailablePlugins();
if (_settings.AutoUpdatePlugins && (_updateCheck.PluginsToUpdate.Any() || _updateCheck.Companions.Count > 0
if (_updateCheck.HoldEnded)
EndRollbackHold($"RynthCore {_updateCheck.Manifest.Version} is out: updates are back on after the rollback.");
// After Roll back, the release the player left isn't installed again by itself (RynthUpdater.Rollback.cs).
if (_settings.AutoUpdatePlugins && !_updateCheck.Held && (_updateCheck.PluginsToUpdate.Any() || _updateCheck.Companions.Count > 0
|| (_updateCheck.NavDataUpdateAvailable && !_navDataCancelledThisSession)))
await ApplyPluginUpdatesAsync(automatic: true);
SendUsageReportIfDue(); // opt-in only, at most once a day, never awaited
@ -2686,7 +2744,7 @@ internal partial class MainWindow : Window
{
switch (_updateCard?.Kind)
{
case UpdateCardKind.CoreUpdate: await InstallCoreUpdateAsync(); break;
case UpdateCardKind.CoreUpdate or UpdateCardKind.Held: await InstallCoreUpdateAsync(); break;
case UpdateCardKind.PluginUpdates: await UpdatePluginsAsync(); break;
}
}
@ -2704,6 +2762,7 @@ internal partial class MainWindow : Window
/// <summary>Redraws the front page's update card, the Plugins tab's status line and the header.</summary>
private void RefreshUpdateCard()
{
KeepLauncherScroll();
RefreshMapPacksCard();
RynthUpdater.CheckResult? c = _updateCheck;
bool coreUpdate = c?.CoreUpdateAvailable == true;
@ -2725,23 +2784,26 @@ internal partial class MainWindow : Window
ClientsRunning = coreUpdate && _download == null ? RynthCoreClientsRunning() : 0,
Download = _download,
CanCancel = _downloadCts is { IsCancellationRequested: false },
HeldFromVersion = c is { Held: true } ? FormatRelease(c.HoldThrough) : "",
});
_updateCard = card;
UpdateCardTitle.Text = card.Title;
UpdateCardTitle.Foreground = Brush.Parse(card.Kind switch
{
UpdateCardKind.CoreUpdate or UpdateCardKind.PluginUpdates => "#F2C14E",
UpdateCardKind.CoreUpdate or UpdateCardKind.PluginUpdates or UpdateCardKind.Held => "#F2C14E",
UpdateCardKind.Error => "#E57373",
_ => "#26C1A6",
});
UpdateCardBorder.BorderBrush = Brush.Parse(card.Kind is UpdateCardKind.CoreUpdate or UpdateCardKind.PluginUpdates ? "#F2C14E" : "#243742");
UpdateCardBorder.BorderBrush = Brush.Parse(card.Kind is UpdateCardKind.CoreUpdate or UpdateCardKind.PluginUpdates or UpdateCardKind.Held ? "#F2C14E" : "#243742");
UpdateCardDetail.Text = card.Detail;
UpdateCardDetail.IsVisible = card.Detail.Length > 0;
UpdateCardActionButton.IsVisible = card.ActionButton != null;
UpdateCardActionButton.Content = card.ActionButton ?? "";
UpdateCardActionButton.IsEnabled = !_updateBusy;
CheckUpdatesButton.IsVisible = card.ShowCheckButton;
RollbackButton.IsVisible = card.ShowCheckButton && _updater.IsConfigured && _updater.InstalledCoreRelease > 0;
RollbackButton.IsEnabled = !_updateBusy;
UpdateCardWhatsNewPanel.Children.Clear();
if (card.WhatsNew.Count > 0)
@ -2874,6 +2936,7 @@ internal partial class MainWindow : Window
RefreshUpdateCard();
try
{
if (_updateCheck.HoldThrough > 0) EndRollbackHold(null); // updating by hand ends a rollback's hold
await ApplyPluginUpdatesAsync(automatic: false);
}
catch (Exception ex)
@ -2950,6 +3013,88 @@ internal partial class MainWindow : Window
BuildPluginLoadout();
}
/// <summary>
/// Roll back (RynthUpdater.Rollback.cs): with every game client closed, picks an earlier release,
/// downloads and verifies it, puts its plugins in place, holds updates, then runs its installer (the
/// launcher restarts as that release).
/// </summary>
private async Task RollBackAsync()
{
if (_updateBusy) return;
int running = RynthCoreClientsRunning();
if (running > 0)
{
AppendActivity($"Close your {running} game client(s) running RynthCore or its Decal bridge first: going back replaces files they have open.");
return;
}
_updateBusy = true;
RefreshUpdateCard();
try
{
IReadOnlyList<RynthUpdater.RollbackTarget> targets = await _updater.ListRollbackTargetsAsync();
if (targets.Count == 0)
{
AppendActivity($"There's no earlier release to go back to (going back works to releases from {FormatRelease(RynthUpdater.FirstRollbackRelease)} on).");
return;
}
var dialog = new RollbackDialog(targets, FormatRelease(_updater.InstalledCoreRelease));
RynthUpdater.RollbackTarget? chosen = await dialog.ShowDialog<RynthUpdater.RollbackTarget?>(this);
if (chosen == null) return;
RynthUpdater.RollbackPlan plan = await RunDownloadAsync((progress, ct) =>
_updater.PrepareRollbackAsync(chosen, _pluginDllPaths.ToList(), progress, ct));
if (RynthCoreClientsRunning() > 0)
{
AppendActivity("A RynthCore client started meanwhile. Close it, then press Roll back again. Nothing was changed.");
return;
}
List<string> plugins = _updater.ApplyRollbackPlugins(plan);
// The rolled-back launcher may be older than the hold: it would update the plugins straight back.
bool turnOff = _settings.AutoUpdatePlugins;
_updater.StartHold(plan.LeavingRelease, turnOff);
if (turnOff)
{
_settings.AutoUpdatePlugins = false;
AutoUpdatePluginsCheckBox.IsChecked = false;
SaveSettings();
}
AppendActivity($"Going back to RynthCore {plan.Manifest.Version}" +
(plugins.Count > 0 ? $" (plugins: {string.Join(", ", plugins)})" : "") +
$"; the launcher restarts when it's done. Updates are on hold until a release newer than {FormatRelease(plan.LeavingRelease)} comes out.");
RynthUpdater.RunInstaller(plan.InstallerPath);
(Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.Shutdown();
}
catch (OperationCanceledException)
{
AppendActivity("Going back cancelled. Nothing was changed.");
}
catch (Exception ex)
{
AppendActivity($"Going back failed: {ex.Message}");
}
finally
{
_updateBusy = false;
RefreshUpdateCard();
}
}
/// <summary>Ends a rollback's hold and turns automatic plugin updates back on if the rollback turned them off.</summary>
private void EndRollbackHold(string? message)
{
bool restore = _updater.HoldTurnedOffAutoUpdate;
_updater.EndHold();
if (restore && !_settings.AutoUpdatePlugins)
{
_settings.AutoUpdatePlugins = true;
AutoUpdatePluginsCheckBox.IsChecked = true;
SaveSettings();
}
if (message != null) AppendActivity(message);
}
private async Task InstallCoreUpdateAsync()
{
if (_updateBusy || _updateCheck is not { CoreUpdateAvailable: true } c) return;
@ -2971,6 +3116,7 @@ internal partial class MainWindow : Window
AppendActivity("A RynthCore client started meanwhile. Close it, then press Update RynthCore again.");
return;
}
if (c.HoldThrough > 0) EndRollbackHold(null); // going forward by hand ends a rollback's hold
AppendActivity($"Installing RynthCore {c.Manifest.Core.Version}; the launcher restarts when it's done.");
RynthUpdater.RunInstaller(installer);
(Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.Shutdown();
@ -3918,8 +4064,14 @@ internal partial class MainWindow : Window
{
try
{
// Never decrypts: a saved password shows as the mask.
return _launchArgumentBuilder.BuildMaskedArguments(server, account);
// Never decrypts: a saved password shows as the mask. Extra Launch Arguments follow,
// as they do at launch.
string masked = _launchArgumentBuilder.BuildMaskedArguments(server, account);
if (AcLaunchArgumentBuilder.NeedsPassword(account))
return masked; // the message saying why, not a command line
return AcLaunchArgumentBuilder.ExtraArgumentsProblem(LaunchArgumentsTextBox.Text, out string extra) is string problem
? problem
: AcLaunchArgumentBuilder.WithExtraArguments(masked, extra);
}
catch (Exception ex)
{
@ -4710,6 +4862,13 @@ internal partial class MainWindow : Window
if (HasTrackedPresence(account, server, activeContexts, activeSessions))
continue;
// No server profile (deleted, or never picked): never launched on another server.
if (server == null)
{
MaybeLogAutoLaunchNoServer(account, nowUtc);
continue;
}
if (IsServerKnownDown(server))
{
MaybeLogAutoLaunchServerDown(account, server, nowUtc);
@ -4787,6 +4946,18 @@ internal partial class MainWindow : Window
AppendActivity($"Auto launch waiting for {account.DisplayName}: {AcLaunchArgumentBuilder.MissingPasswordMessage(account.AccountName)}");
}
private void MaybeLogAutoLaunchNoServer(LaunchAccountProfile account, DateTime nowUtc)
{
if (_autoLaunchNoServerNoticeTimesUtc.TryGetValue(account.Id, out DateTime lastNoticeUtc) &&
nowUtc - lastNoticeUtc < AutoLaunchNeedsPasswordLogCooldown)
{
return;
}
_autoLaunchNoServerNoticeTimesUtc[account.Id] = nowUtc;
AppendActivity($"Auto launch skipped for {account.DisplayName}: {AccountServerRules.NoServerMessage(account, _settings.ServerProfiles.Count > 0)}");
}
private bool IsServerKnownDown(LaunchServerProfile? server)
{
if (server == null)
@ -4960,16 +5131,23 @@ internal partial class MainWindow : Window
// "(None)" at the top — selecting it opts out of auto-login for this account
detectedCharacters.Insert(0, LaunchAccountProfile.NoneOption);
string? wanted = account.CharacterName == LaunchAccountProfile.NoneOption
? LaunchAccountProfile.NoneOption
: !string.IsNullOrWhiteSpace(account.CharacterName) && detectedCharacters.Contains(account.CharacterName)
? account.CharacterName
: null;
// This runs every 2 s: refill a dropdown only when its list or choice changed, so the
// Launcher tab isn't refilled (and its selection events raised) for nothing.
if (dropdown.ItemsSource is IEnumerable<string> shown && shown.SequenceEqual(detectedCharacters)
&& Equals(dropdown.SelectedItem as string, wanted))
continue;
KeepLauncherScroll();
_suppressLaunchTargetCharacterSelectionChanged = true;
try
{
dropdown.ItemsSource = detectedCharacters;
if (account.CharacterName == LaunchAccountProfile.NoneOption)
dropdown.SelectedItem = LaunchAccountProfile.NoneOption;
else
dropdown.SelectedItem = !string.IsNullOrWhiteSpace(account.CharacterName) && detectedCharacters.Contains(account.CharacterName)
? account.CharacterName
: null;
dropdown.SelectedItem = wanted;
}
finally
{
@ -5078,6 +5256,7 @@ internal partial class MainWindow : Window
private void RefreshServerProfileDisplay()
{
KeepLauncherScroll();
int selectedIndex = ServerProfilesList.SelectedIndex;
_suppressPrimarySelectionChanged = true;
try

View file

@ -0,0 +1,26 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="RynthCore.App.Avalonia.RollbackDialog"
Width="600"
SizeToContent="Height"
CanResize="False"
WindowStartupLocation="CenterOwner"
Title="Roll back"
Background="#132028">
<Grid RowDefinitions="*,Auto" Margin="18">
<StackPanel Spacing="10">
<TextBlock x:Name="HeaderText" Foreground="#EAF0F4" FontSize="16" FontWeight="SemiBold" TextWrapping="Wrap" />
<TextBlock Foreground="#9AA8B3" TextWrapping="Wrap"
Text="Pick the release to go back to. Your settings, profiles and accounts stay as they are." />
<ScrollViewer MaxHeight="380" VerticalScrollBarVisibility="Auto">
<StackPanel x:Name="ReleasesPanel" Spacing="10" />
</ScrollViewer>
<TextBlock x:Name="HoldText" Foreground="#9AA8B3" TextWrapping="Wrap" />
</StackPanel>
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8" Margin="0,16,0,0">
<Button x:Name="CancelButton" Content="Cancel" />
<Button x:Name="RollbackButton" Content="Go back" IsEnabled="False"
Background="#26C1A6" Foreground="#0B1218" FontWeight="SemiBold" />
</StackPanel>
</Grid>
</Window>

View file

@ -0,0 +1,60 @@
using System.Collections.Generic;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Media;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Roll back's choice (RynthUpdater.Rollback.cs): the earlier releases whose signed manifests verified,
/// newest first, each with its date and first changes. Closes with the chosen target, or null.
/// </summary>
internal partial class RollbackDialog : Window
{
private const int ChangesShown = 3;
private RynthUpdater.RollbackTarget? _chosen;
public RollbackDialog() : this(new List<RynthUpdater.RollbackTarget>(), "") { } // the XAML previewer
public RollbackDialog(IReadOnlyList<RynthUpdater.RollbackTarget> targets, string installedVersion)
{
InitializeComponent();
HeaderText.Text = $"Go back from RynthCore {installedVersion}";
HoldText.Text = "Every game client must be closed. The launcher installs that release and restarts; " +
"updates then wait until a release newer than this one comes out, or until you press Update RynthCore.";
foreach (RynthUpdater.RollbackTarget t in targets)
{
var choice = new RadioButton { GroupName = "release", Tag = t };
var body = new StackPanel { Spacing = 2 };
body.Children.Add(new TextBlock
{
Text = $"RynthCore {t.Version} · {t.Manifest.PublishedUtc.ToLocalTime():MMM d}",
Foreground = Brush.Parse("#EAF0F4"), FontWeight = FontWeight.SemiBold,
});
IReadOnlyList<string> lines = t.Manifest.Changes.Count > 0
? t.Manifest.Changes.Take(ChangesShown).ToList()
: (t.Manifest.Notes.Length > 0 ? new[] { t.Manifest.Notes } : new string[0]);
foreach (string line in lines)
body.Children.Add(new TextBlock
{
Text = "• " + (line.Length > 160 ? line[..159].TrimEnd() + "…" : line),
Foreground = Brush.Parse("#C5D0D8"), TextWrapping = TextWrapping.Wrap,
});
if (t.Manifest.Changes.Count > ChangesShown)
body.Children.Add(new TextBlock { Text = $"…and {t.Manifest.Changes.Count - ChangesShown} more.", Foreground = Brush.Parse("#9AA8B3") });
choice.Content = body;
choice.IsCheckedChanged += (_, _) =>
{
if (choice.IsChecked != true) return;
_chosen = (RynthUpdater.RollbackTarget)choice.Tag!;
RollbackButton.Content = $"Go back to {_chosen.Version}";
RollbackButton.IsEnabled = true;
};
ReleasesPanel.Children.Add(choice);
}
CancelButton.Click += (_, _) => Close(null);
RollbackButton.Click += (_, _) => Close(_chosen);
}
}

View file

@ -46,6 +46,7 @@
<Compile Include="..\RynthCore.App\KnownServerCatalog.cs" Link="Shared\KnownServerCatalog.cs" />
<Compile Include="..\RynthCore.App\LaunchAccountProfile.cs" Link="Shared\LaunchAccountProfile.cs" />
<Compile Include="..\RynthCore.App\AccountPasswordProtection.cs" Link="Shared\AccountPasswordProtection.cs" />
<Compile Include="..\RynthCore.App\SavedPasswordReveal.cs" Link="Shared\SavedPasswordReveal.cs" />
<Compile Include="..\RynthCore.App\InjectionMode.cs" Link="Shared\InjectionMode.cs" />
<Compile Include="..\RynthCore.App\DecalLocator.cs" Link="Shared\DecalLocator.cs" />
<Compile Include="..\RynthCore.App\DecalBridgeRegistration.cs" Link="Shared\DecalBridgeRegistration.cs" />
@ -55,6 +56,7 @@
<Compile Include="..\RynthCore.App\AcLaunchArgumentBuilder.cs" Link="Shared\AcLaunchArgumentBuilder.cs" />
<Compile Include="..\RynthCore.App\AcClientCommandLine.cs" Link="Shared\AcClientCommandLine.cs" />
<Compile Include="..\RynthCore.App\FirstLoginRules.cs" Link="Shared\FirstLoginRules.cs" />
<Compile Include="..\RynthCore.App\AccountServerRules.cs" Link="Shared\AccountServerRules.cs" />
<Compile Include="..\RynthCore.App\CrashDumpWriterRule.cs" Link="Shared\CrashDumpWriterRule.cs" />
<Compile Include="..\RynthCore.App\AcClientLaunchSettingsService.cs" Link="Shared\AcClientLaunchSettingsService.cs" />
<Compile Include="..\RynthCore.App\UserPrefsSwapRecovery.cs" Link="Shared\UserPrefsSwapRecovery.cs" />

View file

@ -0,0 +1,198 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.App.Avalonia;
/// <summary>
/// Roll back: go back to an earlier release when a new one broke something (2026-10-21).
///
/// Every release keeps its own signed manifest beside its files on the server
/// (releases/&lt;release&gt;/update.json; Publish-Update.ps1 uploads it, and did by hand for 2026.10.19.1
/// on). Which releases exist comes from releases.json (unsigned; only used to find candidates); each
/// candidate is offered only once its own manifest verifies, and everything a rollback downloads is
/// checked against that manifest's signed sizes and hashes, exactly like an update. Only releases older
/// than the installed one, and not older than <see cref="FirstRollbackRelease"/>.
///
/// A rollback puts back that release's build of every plugin the player has (the files it ships; other
/// plugins are left alone), then runs that release's installer (the core: engine, launcher, RynthAi),
/// with every game client closed, like a core update. Afterwards updates are held
/// (<see cref="StartHold"/>): no automatic plugin updates while the feed offers nothing newer than the
/// release left behind, so the launcher doesn't put it straight back. The hold ends by itself when a
/// newer release comes out, or when the player updates by hand.
///
/// A launcher from before this feature (the rolled-back one may be) knows nothing of the hold, so a
/// rollback also turns "Update plugins automatically" off, and a later launcher turns it back on when
/// the hold ends (<see cref="HoldTurnedOffAutoUpdate"/>).
/// </summary>
internal sealed partial class RynthUpdater
{
/// <summary>The oldest release whose signed manifest is kept on the server (2026.10.19.1).</summary>
public const int FirstRollbackRelease = 2026101901;
/// <summary>How many earlier releases Roll back offers.</summary>
public const int RollbackChoices = 5;
private const long MaxReleasesListBytes = 4L << 20;
/// <summary>Tests lower it; the launcher uses <see cref="FirstRollbackRelease"/>.</summary>
internal int RollbackFloor { get; set; } = FirstRollbackRelease;
/// <summary>An earlier release Roll back can install, from its own verified manifest.</summary>
public sealed record RollbackTarget(Manifest Manifest)
{
public int Release => Manifest.Release;
public string Version => Manifest.Version;
}
/// <summary>What a prepared rollback installs: the verified installer and the player's plugins, staged.</summary>
public sealed record RollbackPlan(Manifest Manifest, int LeavingRelease, string InstallerPath,
IReadOnlyList<(PluginEntry Entry, string Path, string Staged)> Plugins);
/// <summary>"2026.10.21.2" → 2026102102 (Publish-Update.ps1's numbering); 0 when it isn't a release version.</summary>
public static int ReleaseOf(string? version)
{
string[] p = (version ?? "").Trim().Split('.');
if (p.Length != 4) return 0;
if (!int.TryParse(p[0], out int y) || !int.TryParse(p[1], out int m) || !int.TryParse(p[2], out int d) || !int.TryParse(p[3], out int n))
return 0;
if (y < 2000 || y > 2999 || m < 1 || m > 12 || d < 1 || d > 31 || n < 0 || n > 99) return 0;
return y * 1000000 + m * 10000 + d * 100 + n;
}
/// <summary>
/// The earlier releases Roll back offers, newest first: up to <paramref name="max"/>, older than the
/// installed release, not older than <see cref="RollbackFloor"/>, each with a manifest that verifies.
/// A release whose manifest is missing or doesn't verify is skipped.
/// </summary>
public async Task<IReadOnlyList<RollbackTarget>> ListRollbackTargetsAsync(int max = RollbackChoices, CancellationToken ct = default)
{
if (!IsConfigured)
throw new InvalidOperationException("updates are not set up in this build (no signing key)");
int installed = InstalledCoreRelease;
if (installed <= 0)
throw new InvalidOperationException("this RynthCore wasn't installed from a release, so there's nothing to go back from");
byte[] list = await DownloadBytesAsync(_allowedPrefix + "releases.json", MaxReleasesListBytes, ct);
var candidates = new List<int>();
using (JsonDocument doc = JsonDocument.Parse(list))
{
foreach (JsonElement r in doc.RootElement.GetProperty("releases").EnumerateArray())
{
int release = r.TryGetProperty("version", out JsonElement v) ? ReleaseOf(v.GetString()) : 0;
if (release > 0 && release < installed && release >= RollbackFloor && !candidates.Contains(release))
candidates.Add(release);
}
}
var targets = new List<RollbackTarget>();
foreach (int release in candidates.OrderByDescending(r => r))
{
if (targets.Count >= max) break;
try { targets.Add(new RollbackTarget(await LoadReleaseManifestAsync(release, ct))); }
catch (OperationCanceledException) { throw; }
catch { /* no signed manifest kept for it, or it doesn't verify: not offered */ }
}
return targets;
}
/// <summary>
/// <paramref name="release"/>'s own signed manifest (releases/&lt;release&gt;/update.json). Throws unless a
/// trusted key signed it, it is that release (not another one served under its name) and it is
/// older than the installed release.
/// </summary>
public async Task<Manifest> LoadReleaseManifestAsync(int release, CancellationToken ct = default)
{
byte[] envelope = await DownloadBytesAsync($"{_allowedPrefix}releases/{release}/update.json", MaxFeedBytes, ct);
Manifest m = ParseManifest(VerifyEnvelope(envelope, _trustedKeys));
if (m.Release != release || m.Core.Release != release)
throw new InvalidDataException($"releases/{release} holds the manifest of release {m.Release}");
if (m.Release >= InstalledCoreRelease)
throw new InvalidDataException($"{m.Version} isn't older than the installed release");
return m;
}
/// <summary>
/// Downloads and verifies everything <paramref name="target"/> installs: its installer, and its build of
/// each plugin in <paramref name="pluginPaths"/> that it ships (staged, not installed yet). Nothing is
/// changed if any download fails.
/// </summary>
public async Task<RollbackPlan> PrepareRollbackAsync(RollbackTarget target, IEnumerable<string> pluginPaths,
IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
Manifest m = target.Manifest;
int leaving = InstalledCoreRelease;
string installer = await DownloadInstallerAsync(m.Core, progress, ct);
string stage = Path.Combine(UpdatesDir, $"rollback-{m.Release}");
Directory.CreateDirectory(stage);
var byFile = m.Plugins.ToDictionary(p => p.File, StringComparer.OrdinalIgnoreCase);
var staged = new Dictionary<PluginEntry, string>();
var plugins = new List<(PluginEntry, string, string)>();
foreach (string path in pluginPaths.Distinct(StringComparer.OrdinalIgnoreCase))
{
if (!File.Exists(path) || !byFile.TryGetValue(Path.GetFileName(path), out PluginEntry? e)) continue;
if (!staged.TryGetValue(e, out string? file))
{
file = Path.Combine(stage, e.File);
bool have = File.Exists(file) && new FileInfo(file).Length == e.Size &&
string.Equals(Sha256File(file), e.Sha256, StringComparison.OrdinalIgnoreCase);
if (!have)
{
string part = file + ".part";
await DownloadVerifiedAsync(e.Url, e.Size, e.Sha256, MaxPluginBytes, part, ct, $"{e.Name} {m.Version}", progress);
File.Move(part, file, overwrite: true);
}
staged[e] = file;
}
plugins.Add((e, path, file));
}
return new RollbackPlan(m, leaving, installer, plugins);
}
/// <summary>
/// Puts the staged plugins in place (the replaced file kept as .previous, as an update does) and
/// returns what changed. Stamped with the release's time, so a later check doesn't take them for a
/// local build. Call with every game client closed, before running the installer.
/// </summary>
public List<string> ApplyRollbackPlugins(RollbackPlan plan)
{
var done = new List<string>();
foreach (var (entry, path, file) in plan.Plugins)
{
string fresh = path + ".new";
File.Copy(file, fresh, overwrite: true);
File.SetLastWriteTimeUtc(fresh, plan.Manifest.PublishedUtc);
File.Copy(path, path + ".previous", overwrite: true);
File.Move(fresh, path, overwrite: true);
done.Add($"{entry.Name} → {plan.Manifest.Version}");
}
return done;
}
// ── The hold ───────────────────────────────────────────────────────────────
/// <summary>The release the player rolled back from (0: no hold).</summary>
public int HeldThroughRelease => ReadStateInt("holdThrough");
/// <summary>True when the rollback turned "Update plugins automatically" off (turned back on when the hold ends).</summary>
public bool HoldTurnedOffAutoUpdate => ReadStateBool("holdTurnedOffAutoUpdate");
/// <summary>Holds updates through <paramref name="leavingRelease"/> (the release rolled back from).</summary>
public void StartHold(int leavingRelease, bool turnedOffAutoUpdate) => WriteState(s =>
{
s["holdThrough"] = leavingRelease;
s["holdTurnedOffAutoUpdate"] = turnedOffAutoUpdate;
});
/// <summary>Ends a rollback's hold (a newer release is out, or the player updated by hand).</summary>
public void EndHold() => WriteState(s =>
{
s.Remove("holdThrough");
s.Remove("holdTurnedOffAutoUpdate");
});
}

View file

@ -95,6 +95,15 @@ internal sealed partial class RynthUpdater
public bool NavDataUpdateAvailable => NavData is { State: NavDataState.NeedsUpdate };
/// <summary>The optional World Map sizes: what the feed offers and what is installed. Not part of "Update plugins": the player chooses.</summary>
public IReadOnlyList<MapPackStatus> MapPacks { get; init; } = Array.Empty<MapPackStatus>();
/// <summary>
/// The release the player went back from with Roll back (0: none; RynthUpdater.Rollback.cs). While
/// the feed offers nothing newer and the player hasn't updated past it, updates are held.
/// </summary>
public int HoldThrough { get; init; }
/// <summary>Held after a rollback: no automatic plugin updates; the card says so.</summary>
public bool Held => HoldThrough > 0 && Manifest.Release <= HoldThrough && InstalledCoreRelease < HoldThrough;
/// <summary>A rollback's hold is over: a newer release is out, or the player updated past it by hand.</summary>
public bool HoldEnded => HoldThrough > 0 && !Held;
}
/// <summary>
@ -153,6 +162,10 @@ internal sealed partial class RynthUpdater
return coreBringsIt ? $"needs RynthCore {core.Version}" : $"needs a newer RynthCore (API {e.MinEngineApi})";
}
/// <summary>Where installers (and a rollback's plugins) are downloaded: %LOCALAPPDATA%\RynthCore\updates. Tests set it.</summary>
internal string UpdatesDir { get; set; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "updates");
/// <summary>False until the signing keys exist: with no trusted key nothing can verify.</summary>
public bool IsConfigured => _trustedKeys.Count > 0;
@ -220,6 +233,7 @@ internal sealed partial class RynthUpdater
MapPacks = CheckMapPacks(manifest),
Available = available,
NewlyAnnounced = available.Where(a => fresh.Contains(a.Entry.Name)).ToList(),
HoldThrough = HeldThroughRelease,
};
}
@ -317,11 +331,13 @@ internal sealed partial class RynthUpdater
// ── Core ──────────────────────────────────────────────────────────────────
/// <summary>Downloads (or reuses) the release installer, verified, and returns its path.</summary>
public async Task<string> DownloadInstallerAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
public Task<string> DownloadInstallerAsync(CheckResult check, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default) =>
DownloadInstallerAsync(check.Manifest.Core, progress, ct);
/// <summary>Downloads (or reuses) <paramref name="core"/>'s installer, verified, and returns its path.</summary>
public async Task<string> DownloadInstallerAsync(InstallerEntry core, IProgress<DownloadProgress>? progress = null, CancellationToken ct = default)
{
InstallerEntry core = check.Manifest.Core;
string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"RynthCore", "updates", core.Release.ToString());
string dir = Path.Combine(UpdatesDir, core.Release.ToString());
Directory.CreateDirectory(dir);
string path = Path.Combine(dir, "RynthCore-Setup.exe");
if (File.Exists(path) && new FileInfo(path).Length == core.Size &&
@ -522,24 +538,45 @@ internal sealed partial class RynthUpdater
catch { }
}
private int ReadHighestRelease()
private int ReadHighestRelease() => ReadStateInt("highestRelease");
private void WriteHighestRelease(int release) => WriteState(s => s["highestRelease"] = release);
// update-state.json holds several values (the replay guard's highest release, a rollback's hold):
// each write changes its own keys and keeps the rest.
private System.Text.Json.Nodes.JsonObject ReadState()
{
try
{
if (!File.Exists(StatePath)) return 0;
using var doc = JsonDocument.Parse(File.ReadAllText(StatePath));
return doc.RootElement.TryGetProperty("highestRelease", out JsonElement v) ? v.GetInt32() : 0;
if (File.Exists(StatePath) && System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(StatePath)) is System.Text.Json.Nodes.JsonObject o)
return o;
}
catch { }
return new System.Text.Json.Nodes.JsonObject();
}
private int ReadStateInt(string key)
{
try { return ReadState()[key]?.GetValue<int>() ?? 0; }
catch { return 0; }
}
private void WriteHighestRelease(int release)
private bool ReadStateBool(string key)
{
try { return ReadState()[key]?.GetValue<bool>() ?? false; }
catch { return false; }
}
private void WriteState(Action<System.Text.Json.Nodes.JsonObject> change)
{
try
{
System.Text.Json.Nodes.JsonObject state = ReadState();
change(state);
Directory.CreateDirectory(_stateDir);
string tmp = StatePath + ".tmp";
File.WriteAllText(tmp, $"{{\"highestRelease\": {release}}}", Encoding.UTF8);
File.WriteAllText(tmp, state.ToJsonString(), Encoding.UTF8);
File.Move(tmp, StatePath, overwrite: true);
}
catch { }

View file

@ -6,7 +6,7 @@ using System.Linq;
namespace RynthCore.App.Avalonia;
/// <summary>What the update card on the launcher's front page is showing.</summary>
public enum UpdateCardKind { NotConfigured, NotChecked, Checking, Error, UpToDate, CoreUpdate, PluginUpdates, Downloading }
public enum UpdateCardKind { NotConfigured, NotChecked, Checking, Error, UpToDate, CoreUpdate, PluginUpdates, Downloading, Held }
/// <summary>Everything the card needs to know, gathered by the window (no UI types, so tests can build it).</summary>
public sealed record UpdateCardInput
@ -32,6 +32,8 @@ public sealed record UpdateCardInput
public int ClientsRunning { get; init; }
/// <summary>The download in progress, if any.</summary>
public DownloadProgress? Download { get; init; }
/// <summary>After Roll back: the version the player went back from, while updates are held (else "").</summary>
public string HeldFromVersion { get; init; } = "";
public bool CanCancel { get; init; }
}
@ -53,7 +55,7 @@ public sealed record UpdateCard(
/// <summary>
/// The front page's update card as a pure function of <see cref="UpdateCardInput"/>: up to date,
/// RynthCore update (installs once every game client is closed), plugin updates, downloading
/// (bar, MB, speed, time left, step), errors, and a line about new plugins.
/// (bar, MB, speed, time left, step), errors, a line about new plugins, and the hold after a Roll back.
/// </summary>
public static class UpdateCardModel
{
@ -105,6 +107,18 @@ public static class UpdateCardModel
string checkedLine = i.LastChecked is { } lc ? $"Last checked {FormatWhen(lc)}." : "";
IReadOnlyList<string> whatsNew = WhatsNew(i.Changes, i.Notes);
if (i.HeldFromVersion.Length > 0)
{
// Roll back: the launcher doesn't push the release the player left straight back.
var detail = new List<string> { $"You went back from {i.HeldFromVersion}. Updates are on hold until a newer release comes out." };
if (i.CoreUpdateAvailable)
detail.Add($"{UpdateCoreButton} goes forward to {i.AvailableVersion} now.");
if (checkedLine.Length > 0) detail.Add(checkedLine);
return new UpdateCard(UpdateCardKind.Held, $"RynthCore {installed} - rolled back", string.Join(" ", detail),
Array.Empty<string>(), true, i.CoreUpdateAvailable ? UpdateCoreButton : null, false, null, false, newLine,
$"RynthCore {installed} - rolled back from {i.HeldFromVersion}; updates on hold.");
}
if (i.CoreUpdateAvailable)
{
var detail = new List<string> { $"You have {installed}. The update installs once every game client is closed." };

View file

@ -128,6 +128,59 @@ internal sealed class AcLaunchArgumentBuilder
return null;
}
/// <summary>
/// The switches the launcher writes itself from the account and its server profile (ACE and
/// GDLE lines above). Extra Launch Arguments may not repeat them.
/// </summary>
public static readonly IReadOnlyList<string> LoginSwitches = ["-a", "-v", "-h", "-p", "-rodat"];
/// <summary>
/// Checks the Runtime tab's "Extra Launch Arguments" and gives them as one line
/// (<paramref name="normalized"/>) to put after each account's own arguments with
/// <see cref="WithExtraArguments"/>. Null = fine (an empty box is fine); else why the launch
/// can't go ahead, and <paramref name="normalized"/> is empty.
///
/// The box used to replace the whole command line, account, password and host included (and
/// only for one manual launch at a time), though it was labelled "appended". It now appends,
/// for every launch. So it may not carry the login switches (<see cref="LoginSwitches"/>): a
/// saved old override would otherwise ride along on every account and could log each of them
/// in as the override's account, or send their passwords to the override's host. Line breaks
/// and tabs become spaces (the client splits on spaces only), and a quote left open is refused
/// (the client would then drop the whole line, login included).
/// </summary>
public static string? ExtraArgumentsProblem(string? extra, out string normalized)
{
normalized = string.Empty;
string line = (extra ?? string.Empty).Replace("\r\n", " ").Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' ').Trim();
if (line.Length == 0)
return null;
List<string>? args = AcClientCommandLine.Split(line);
if (args == null)
return "Extra Launch Arguments have a quote mark left open; the client would ignore its whole command line, login included. Close or remove the quote.";
foreach (string arg in args)
{
foreach (string loginSwitch in LoginSwitches)
{
if (string.Equals(arg, loginSwitch, StringComparison.OrdinalIgnoreCase))
return $"Extra Launch Arguments can't contain {loginSwitch}: the account and its server profile set " +
$"{string.Join(", ", LoginSwitches)} themselves. Remove it (an old whole-line override goes in the account and server profiles now).";
}
}
normalized = line;
return null;
}
/// <summary>
/// <paramref name="accountArguments"/> (from <see cref="BuildArguments"/> or
/// <see cref="BuildMaskedArguments"/>) followed by extra arguments already checked by
/// <see cref="ExtraArgumentsProblem"/>.
/// </summary>
public static string WithExtraArguments(string accountArguments, string normalizedExtra) =>
string.IsNullOrWhiteSpace(normalizedExtra) ? accountArguments : accountArguments + " " + normalizedExtra;
/// <summary>One argument by acclient's own rules (AcClientCommandLine), not the C runtime's.</summary>
private static string Quote(string value) => AcClientCommandLine.Token(value);
}

View file

@ -0,0 +1,81 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace RynthCore.App;
/// <summary>
/// Which server an account logs on to, and when a server profile may be deleted. Pure: no UI,
/// no files.
///
/// An account's name and password belong to one server, so an account only ever resolves to the
/// server profile it names (<see cref="LaunchAccountProfile.ServerId"/>). There is no fallback to
/// the selected or the first server: that fallback re-pointed every account of a deleted server
/// at another one and saved it, so the next launch (or an automatic relaunch within seconds) sent
/// one server's account name and password to a different server's operator, with nothing on
/// screen (structural audit 2026-10-21, F2). An account whose server profile is missing has no
/// server until the player picks one in its editor, and it doesn't launch.
///
/// Deleting a server that accounts still use is refused, with the accounts named, rather than
/// leaving them with no server. Refusing changes nothing behind the player's back: they move each
/// account to its new server (or delete it) and then delete the server. The other choice, clearing
/// the accounts' server, would quietly stop checked accounts from auto-launching (overnight
/// multi-boxing) with only a line in Activity. The no-server rule above stays as the backstop for
/// accounts whose server went some other way (settings copied from another PC, a second
/// launcher, a hand edit).
/// </summary>
internal static class AccountServerRules
{
/// <summary>
/// The server profile <paramref name="account"/> names, or null when it names none or one
/// that isn't in <paramref name="servers"/>. Never another server.
/// </summary>
public static LaunchServerProfile? ServerFor(LaunchAccountProfile account, IEnumerable<LaunchServerProfile> servers)
{
ArgumentNullException.ThrowIfNull(account);
string id = account.ServerId?.Trim() ?? string.Empty;
if (id.Length == 0 || servers == null)
return null;
return servers.FirstOrDefault(s => s != null && string.Equals(s.Id, id, StringComparison.OrdinalIgnoreCase));
}
/// <summary>The accounts that log on to <paramref name="server"/>.</summary>
public static List<LaunchAccountProfile> AccountsOn(LaunchServerProfile server, IEnumerable<LaunchAccountProfile> accounts)
{
ArgumentNullException.ThrowIfNull(server);
if (accounts == null || string.IsNullOrWhiteSpace(server.Id))
return [];
return accounts
.Where(a => a != null && string.Equals(a.ServerId?.Trim(), server.Id.Trim(), StringComparison.OrdinalIgnoreCase))
.ToList();
}
/// <summary>
/// Why <paramref name="server"/> can't be deleted (it names the accounts that use it), or null
/// when no account uses it.
/// </summary>
public static string? DeleteBlocker(LaunchServerProfile server, IEnumerable<LaunchAccountProfile> accounts)
{
List<LaunchAccountProfile> users = AccountsOn(server, accounts);
if (users.Count == 0)
return null;
const int MaxNamed = 8;
IEnumerable<string> names = users.Take(MaxNamed).Select(a => " - " + a.DisplayName);
string more = users.Count > MaxNamed ? $"\n ...and {users.Count - MaxNamed} more" : string.Empty;
return $"{server.DisplayName} can't be deleted while {users.Count} account(s) log on to it:\n" +
string.Join("\n", names) + more + "\n\n" +
"Their names and passwords belong to that server, so they are never moved to another one for you. " +
"Edit each account and pick its server (or delete the account), then delete the server.";
}
/// <summary>Why <paramref name="account"/> can't launch: it has no server profile.</summary>
public static string NoServerMessage(LaunchAccountProfile account, bool anyServerProfiles)
{
ArgumentNullException.ThrowIfNull(account);
return anyServerProfiles
? $"account '{account.AccountName}' has no server (its server profile was deleted or never set). " +
"Edit the account and pick the server it logs on to; it isn't sent to another server in the meantime."
: $"account '{account.AccountName}' has no server. Add a server profile, then edit the account and pick it.";
}
}

View file

@ -0,0 +1,85 @@
using System;
namespace RynthCore.App;
/// <summary>
/// The "show password" eye beside the account editor's password box. Pure: no UI.
///
/// The box starts empty ("leave blank to keep the saved password"). Turning the eye on with the
/// box empty fills it with the saved password, decrypted at that moment, so the player can read
/// it; with something typed, the eye only reveals what was typed. Turning the eye off empties the
/// box again when it still holds the saved password it was filled with, so blank = keep holds,
/// and saving it unchanged keeps the saved password as it is (nothing re-encrypted). A saved
/// password that can't be read on this Windows user (needs re-entering) is never filled in.
///
/// Keeps no copy of the password: only whether the box was filled; the box's text is compared
/// with a fresh decrypt. Never log what these return.
/// </summary>
internal sealed class SavedPasswordReveal
{
public const string ShowTip = "Show password";
public const string HideTip = "Hide password";
// The saved password decrypted now; null when none is saved or it can't be read here.
private readonly Func<string?> _readSaved;
public SavedPasswordReveal(Func<string?> readSaved)
{
_readSaved = readSaved ?? throw new ArgumentNullException(nameof(readSaved));
}
/// <summary>For an account profile (the editor's draft): its saved password, if readable.</summary>
public static SavedPasswordReveal For(LaunchAccountProfile profile)
{
ArgumentNullException.ThrowIfNull(profile);
return new SavedPasswordReveal(() =>
profile.HasSavedPassword && !profile.PasswordNeedsReentry
&& profile.TryGetPasswordForLaunch(out string saved, out _) && saved.Length > 0
? saved
: null);
}
/// <summary>True while the box holds the saved password the eye filled in.</summary>
public bool FilledFromSaved { get; private set; }
/// <summary>The eye turned on: the box's text, or the saved password when the box is empty.</summary>
public string EyeOn(string? boxText)
{
if (string.IsNullOrEmpty(boxText) && _readSaved() is string saved)
{
FilledFromSaved = true;
return saved;
}
FilledFromSaved = false;
return boxText ?? string.Empty;
}
/// <summary>
/// The eye turned off: the box's new text. Empty again when it still holds the saved password
/// it was filled with; anything the player typed or changed stays.
/// </summary>
public string EyeOff(string? boxText)
{
string text = boxText ?? string.Empty;
bool unchanged = HoldsSaved(text);
FilledFromSaved = false;
return unchanged ? string.Empty : text;
}
/// <summary>
/// What Save does with the box: null = keep the saved password as it is (the box is blank, or
/// holds the saved password the eye showed, unchanged); otherwise the new password to save.
/// </summary>
public string? PasswordToSave(string? boxText)
{
if (string.IsNullOrEmpty(boxText) || HoldsSaved(boxText))
return null;
return boxText;
}
/// <summary>Forgets the fill (the dialog closes).</summary>
public void Reset() => FilledFromSaved = false;
private bool HoldsSaved(string text) =>
FilledFromSaved && text.Length > 0 && _readSaved() is string saved && string.Equals(saved, text, StringComparison.Ordinal);
}

View file

@ -5,13 +5,17 @@
//
// Order matters. Each phase is wrapped so a failure does not abort the rest:
//
// 0. TickPump.StopAndJoin — the plugin pump stops (and its frame in flight
// finishes) before any plugin is shut down: no Tick alongside a Shutdown.
// 1. EndSceneHook.Uninstall — chains into EngineFrameController.Shutdown which
// tears down PluginManager (RynthPluginShutdown + FreeLibrary plugins),
// OverlayTextureRenderer, DX9Backend, and destroys the ImGui context.
// 2. Drain — sleep so any in-flight EndScene call has returned through the
// trampoline before we tear down anything else.
// 3. AvaloniaOverlay.Stop — Dispatcher shutdown, join STA thread.
// 4. PluginManager.ShutdownAll — defensive (no-op if step 1 already ran).
// 4. PluginManager.ShutdownAll — defensive (no-op if step 1 already ran; it
// tries again if step 1 left the plugins alone because the pump was
// still inside a frame).
// 5. MH_DisableHook(ALL) + MH_Uninitialize — safety net for Compatibility/*
// hooks that aren't in the ImGui chain.
//
@ -140,6 +144,17 @@ internal static class EngineLifecycle
// plugin-mutating UI command while the plugins are shutting down.
Step("UiDataHub.Disarm", () => UI.Data.UiDataHub.Disarm());
// Stop the plugin pump (and wait for a frame in flight) BEFORE anything below can
// shut a plugin down: EndSceneHook.Uninstall runs PluginManager.ShutdownAll (through
// EngineFrameController.Shutdown), and a pump still running would call a plugin's Tick
// and events on its own thread while that plugin's Shutdown frees what they use on
// this one (audit 2026-10-21, 01 #1). It used to stop further down, after the plugins
// were already gone; only the WM_CLOSE path (Win32Backend) stopped it first. Every
// shutdown comes through here: the loader's hot reload, ExitProcess and
// RtlExitUserProcess, WM_CLOSE, the bar's Sd button. If a frame is still running when
// the wait ends, ShutdownAll leaves the plugins alone (PluginShutdownGate).
Step("TickPump.StopAndJoin", () => EntryPoint.StopTickPumpAndJoin());
// AC's UI-pass hook draws the world overlays mid-frame from the same render-side
// state EndSceneHook.Uninstall tears down: stop it first (its 80 ms drain covers both).
Step("AcUiPassHook.Uninstall", () => AcUiPassHook.Uninstall());
@ -166,17 +181,14 @@ internal static class EngineLifecycle
Step("Win32Backend.Shutdown (input subclass)", () => ImGuiBackend.Win32Backend.Shutdown());
Step("HotkeyService.Shutdown", () => Hotkeys.HotkeyService.Shutdown());
// Stop the dispatch-file watcher and the auto-ID drain timer before the
// tick pump and plugins go away — both otherwise keep firing in the old
// generation's (intentionally still-mapped) module across hot-reloads.
// Stop the dispatch-file watcher and the auto-ID drain timer — both
// otherwise keep firing in the old generation's (intentionally
// still-mapped) module across hot-reloads.
Step("ChatFileDispatcher.Stop", () => Compatibility.ChatFileDispatcher.Stop());
Step("LogSettings.StopWatcher", () => LogSettings.StopWatcher());
Step("AutoIdService.Stop", () => Compatibility.AutoIdService.Stop());
// Stop the headless tick pump BEFORE plugin shutdown / FreeLibrary.
// Otherwise the pump's TickAll/ProcessPendingActions can be mid-call
// into a plugin whose code pages we're about to unmap → AV.
Step("TickPump.StopAndJoin", () => EntryPoint.StopTickPumpAndJoin());
// (The plugin pump stopped at the top, before the plugins were shut down.)
// spike/decal-bridge: after the pump (its only reader) has stopped.
Step("DecalBridgeHost.Shutdown", () => Compatibility.DecalBridgeHost.Shutdown());

View file

@ -1312,7 +1312,11 @@ public static class EntryPoint
{
try
{
if (!EngineThreads.Sleep(DecalCoexistencePluginInitDelay))
// In short steps that watch the pump's stop flag: a teardown in these seconds
// (a reload right after login) then finds this thread gone at once rather than
// after the delay, and plugins are never initialised for a dying generation
// (StopTickPumpAndJoin, PluginShutdownGate).
if (!SleepUnlessPumpStopRequested(DecalCoexistencePluginInitDelay))
return;
// Reseed the qualities pointer from the live player object
@ -1601,10 +1605,13 @@ public static class EntryPoint
internal static bool StopTickPumpAndJoin(int timeoutMs = 2000)
{
Compatibility.GameTickHooks.HeadlessPrefetch = false; // no more prefetch work once teardown starts
// Before the null check: a pump that starts after this (a login bootstrap racing the
// teardown) leaves its loop at once instead of ticking a generation being torn down.
Interlocked.Exchange(ref _tickPumpStopRequested, 1);
if (_tickPumpThread == null)
return true;
Interlocked.Exchange(ref _tickPumpStopRequested, 1);
if (_tickPumpThread == Thread.CurrentThread)
return Volatile.Read(ref _tickPumpExited) != 0; // never wait for itself
long deadline = Environment.TickCount64 + timeoutMs;
while (Volatile.Read(ref _tickPumpExited) == 0 && Environment.TickCount64 < deadline)
@ -1612,10 +1619,31 @@ public static class EntryPoint
bool exited = Volatile.Read(ref _tickPumpExited) != 0;
if (!exited)
RynthLog.Plugin($"DecalCoexistence: tick pump did NOT exit within {timeoutMs}ms.");
RynthLog.Plugin($"Plugin tick pump did NOT exit within {timeoutMs}ms{DescribePumpInside()}.");
return exited;
}
private static string DescribePumpInside()
{
try { string? inside = Plugins.PluginManager.DescribePumpDispatch(); return inside != null ? " (" + inside + ")" : ""; }
catch { return ""; }
}
/// <summary>
/// For PluginManager.ShutdownAll: stops the plugin pump if it is still running, waits up
/// to <paramref name="timeoutMs"/> for its frame in flight, and says whether the plugins
/// may be shut down now (PluginShutdownGate). At once when the pump already stopped (every
/// EngineLifecycle.Shutdown stops it first) or never started.
/// </summary>
internal static Plugins.PluginShutdownGate.Verdict StopTickPumpForPluginShutdown(int timeoutMs)
{
Thread? pump = _tickPumpThread;
bool onPump = pump != null && pump == Thread.CurrentThread;
if (pump != null && !onPump && Volatile.Read(ref _tickPumpExited) == 0)
StopTickPumpAndJoin(timeoutMs);
return Plugins.PluginShutdownGate.Decide(pump != null, Volatile.Read(ref _tickPumpExited) != 0, onPump);
}
/// <summary>
/// Non-blocking request for the headless plugin pump (NormalPluginPump /
/// DecalCoexistence) to stop. Sets the same flag as <see cref="StopTickPumpAndJoin"/>
@ -1630,6 +1658,22 @@ public static class EntryPoint
Interlocked.Exchange(ref _tickPumpStopRequested, 1);
}
/// <summary>
/// Sleeps <paramref name="total"/> in steps of at most 100 ms. False (stop now) as soon as
/// the pump's stop is requested or the engine's threads are stopped.
/// </summary>
private static bool SleepUnlessPumpStopRequested(TimeSpan total)
{
long end = Environment.TickCount64 + (long)total.TotalMilliseconds;
while (Volatile.Read(ref _tickPumpStopRequested) == 0)
{
long left = end - Environment.TickCount64;
if (left <= 0) return true;
if (!EngineThreads.Sleep((int)Math.Min(left, 100))) return false;
}
return false;
}
private static Thread? _initThread;
private static int _initAbortLogged;

View file

@ -9,7 +9,11 @@
// asked for a button (WindowFlags.BarButton: RynthSort, Oracle, ...; tooltip =
// its title; the set is rebuilt as plugins come and go), one per window a plugin
// draws that asked for one (its manifest's "windows" with "bar", UI/Sections/
// PluginWindows.cs), reload (RL) and pop out.
// PluginWindows.cs; an engine panel such a window has taken over loses its own
// button), reload (RL) and pop out.
// A button whose window is open, docked or popped out, draws highlighted in the
// theme's accent (RynthTheme.BarButtonOpen*); the ILT and Scripts buttons while
// any window in their menu is (UI/BarOpenState.cs; one IsOpen lookup a key).
// Dragging the grip moves the bar; the position is the shared bar= row in
// panel_state.txt. Right-click the grip for the bar's menu: its size, its rows
// and "Report a problem" (panel buttons have no menu). Pop out moves the ImGui
@ -65,8 +69,12 @@ internal static class ImGuiBar
// Window: a plugin's script window with a bar button of its own (WindowFlags.BarButton);
// the button toggles it through ScriptWindowRegistry, like the Scripts menu does.
// OpenKey: the panel whose open state lights the button (BarOpenState.KeyFor).
private sealed record ButtonInfo(string Title, string Id, string Icon, bool Letter, string Tooltip,
ScriptWindow? Window = null);
string OpenKey, ScriptWindow? Window = null);
// The open check every highlight uses (one set lookup a key), as one delegate: no allocation a frame.
private static readonly Func<string, bool> IsOpenCheck = ImGuiPanelHost.IsOpen;
// Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button.
// Item Count has no icon of its own since 2026-10-18: Inventory's Count button, /rc itemcount, the Character menu.
@ -147,6 +155,9 @@ internal static class ImGuiBar
private static ScriptBarItem[]? _builtScriptButtons;
private static int _builtImGuiOnlyMask;
private static int _builtPluginWindows = -1;
// The Scripts menu's panel keys (its button lights while any is open), rebuilt with the snapshot.
private static ScriptBarItem[]? _scriptKeysFor;
private static string[] _scriptKeys = Array.Empty<string>();
private static string _tooltip = "";
private static bool _placed;
private static Vector2 _pos, _persistedPos;
@ -457,12 +468,15 @@ internal static class ImGuiBar
PushBarButtonStyle(s);
ImFontPtr letterFont = ImGuiFonts.Get(UiFont.UiBold11);
// A button whose window is open (docked or popped out) draws in the theme's accent
// (BarOpenState); a menu button (ILT, Scripts) while any window it lists is open.
foreach (ButtonInfo b in _buttons!)
{
NextSlot(ref slot, perRow, iconsX, s, iconFont, popped);
if (IconButton(b.Id, b.Letter ? letterFont : iconFont, b.Icon, square, RynthTheme.BarText))
bool open = BarOpenState.IsOpen(b.OpenKey, IsOpenCheck);
if (IconButton(b.Id, b.Letter ? letterFont : iconFont, b.Icon, square, RynthTheme.BarText, open))
{
if (b.Window != null) ScriptWindowRegistry.PlayerSetVisible(b.Window, !ImGuiPanelHost.IsOpen(b.Window.PanelKey));
if (b.Window != null) ScriptWindowRegistry.PlayerSetVisible(b.Window, !open);
else PanelRouter.Toggle(b.Title);
}
SafeImGui.SetItemTooltip(b.Tooltip);
@ -474,7 +488,8 @@ internal static class ImGuiBar
{
NextSlot(ref slot, perRow, iconsX, s, iconFont, popped);
string? only = iltCount == 1 ? FirstIltPanel() : null;
if (IconButton("##ilt", iconFont, PhosphorIcons.Leaf, square, RynthTheme.BarText))
bool open = BarOpenState.AnyOpen(IltPanels, IsOpenCheck);
if (IconButton("##ilt", iconFont, PhosphorIcons.Leaf, square, RynthTheme.BarText, open))
{
if (only != null) PanelRouter.Toggle(only);
else ImGuiNET.ImGui.OpenPopup("##ilt_menu");
@ -488,7 +503,8 @@ internal static class ImGuiBar
if (scripts.Length > 0)
{
NextSlot(ref slot, perRow, iconsX, s, iconFont, popped);
if (IconButton("##scripts", iconFont, PhosphorIcons.AppWindow, square, RynthTheme.BarText))
bool open = BarOpenState.AnyOpen(ScriptKeys(scripts), IsOpenCheck);
if (IconButton("##scripts", iconFont, PhosphorIcons.AppWindow, square, RynthTheme.BarText, open))
ImGuiNET.ImGui.OpenPopup("##scripts_menu");
ImGuiNET.ImGui.SetItemTooltip("Script windows");
}
@ -610,11 +626,32 @@ internal static class ImGuiBar
}
}
/// <summary>A square bar button (the bar's button style) with an icon, or a letter, centred on it.</summary>
private static bool IconButton(string id, ImFontPtr font, string icon, Vector2 size, uint color)
/// <summary>The Scripts menu's panel keys, rebuilt only when its snapshot changes (a new array then). AC thread.</summary>
private static string[] ScriptKeys(ScriptBarItem[] items)
{
if (ReferenceEquals(items, _scriptKeysFor)) return _scriptKeys;
var keys = new string[items.Length];
for (int i = 0; i < items.Length; i++) keys[i] = items[i].PanelKey;
_scriptKeys = keys;
_scriptKeysFor = items;
return keys;
}
/// <summary>
/// A square bar button (the bar's button style) with an icon, or a letter, centred on it.
/// <paramref name="open"/>: its window is open, so it draws in the theme's accent.
/// </summary>
private static bool IconButton(string id, ImFontPtr font, string icon, Vector2 size, uint color, bool open = false)
{
Vector2 at = ImGuiNET.ImGui.GetCursorScreenPos();
if (open)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Button, RynthTheme.BarButtonOpen);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ButtonHovered, RynthTheme.BarButtonOpenHover);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, RynthTheme.BarButtonOpenBorder);
}
bool clicked = ImGuiNET.ImGui.Button(id, size);
if (open) ImGuiNET.ImGui.PopStyleColor(3);
PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), font, icon, at, size, color);
return clicked;
}
@ -761,17 +798,19 @@ internal static class ImGuiBar
_builtImGuiOnlyMask = mask;
_builtPluginWindows = pluginWindows;
var list = new List<ButtonInfo>();
// An engine panel a plugin window has taken over ("takeOver") has no engine button: the
// window's own (below) stands in when it asks for one.
foreach (var (title, _) in OverlayHost.GetPanels())
if (!LauncherOnly.Contains(title))
if (!LauncherOnly.Contains(title) && !UI.Sections.PluginWindows.TakesOver(title))
{
string icon = IconFor(title, out bool letter);
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title));
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title, BarOpenState.KeyFor(title, null)));
}
foreach (string title in ImGuiOnlyBarPanels)
if (ImGuiOnlyWanted(title) && !LauncherOnly.Contains(title))
if (ImGuiOnlyWanted(title) && !LauncherOnly.Contains(title) && !UI.Sections.PluginWindows.TakesOver(title))
{
string icon = IconFor(title, out bool letter);
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title));
list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title, BarOpenState.KeyFor(title, null)));
}
// Windows plugins draw (their manifests' "windows" with "bar", docs/PLUGIN_WINDOWS.md): the
// icon they name (a Phosphor glyph), else the title's letter; the button toggles the panel.
@ -779,7 +818,8 @@ internal static class ImGuiBar
{
bool letter = false;
string icon = w.Icon.Length > 0 ? w.Icon : IconFor(w.Title, out letter);
list.Add(new ButtonInfo(w.Title, "##bar_pw_" + w.Plugin + "_" + w.Id, icon, letter, w.Title));
list.Add(new ButtonInfo(w.Title, "##bar_pw_" + w.Plugin + "_" + w.Id, icon, letter, w.Title,
BarOpenState.KeyFor(w.Title, null)));
}
// Plugin script windows that asked for a button (RynthSort, Oracle, ...): after the
// engine's own. Only while the plugin is loaded and has submitted the window.
@ -789,7 +829,7 @@ internal static class ImGuiBar
string title = w.Title.Length > 0 ? w.Title : w.Key;
string icon = IconFor(title, out bool letter);
string id = "##bar_sw" + w.Hash.ToString("X8");
list.Add(new ButtonInfo(title, id, icon, letter, title, Window: w));
list.Add(new ButtonInfo(title, id, icon, letter, title, BarOpenState.KeyFor(title, w.PanelKey), Window: w));
}
_buttons = list.ToArray();
_tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar size and rows. Ctrl+wheel over the bar: size.";

View file

@ -9,12 +9,16 @@
// and close; 16 px resize grip, all Phosphor icons), placement restore/persistence shared
// with the Avalonia face through PanelStateStore, and per-panel error isolation.
//
// A plugin window can take an engine panel's place (TakeOver, the manifest's
// "takeOver"): same key, so the saved place, open state and commands carry
// over; the engine's face is kept and comes back on ReleaseTakeOver.
//
// Threads:
// Register engine init.
// RegisterDynamic / Unregister / RequestSize / RequestPos
// RegisterDynamic / Unregister / RequestSize / RequestPos / TakeOver / ReleaseTakeOver
// any thread (script windows, from the plugin pump thread);
// DrawOrder is copy-on-write, removal finishes in DrawAll;
// requests are applied in DrawPanel.
// requests are applied in DrawPanel, face swaps in DrawAll.
// Open / Close any thread (router: game thread / Avalonia UI thread).
// Applied on AC's render thread at the next DrawAll.
// DrawAll AC's render thread, inside the ImGui frame.
@ -146,8 +150,17 @@ internal static class ImGuiPanelHost
public volatile bool HasRequest; // RequestedSize or RequestedPos is set
public int Failures;
public string? Error;
/// <summary>True while a plugin window has this engine panel's place (TakeOver).</summary>
public bool TakenOver;
/// <summary>The engine's own face, kept from the first TakeOver for ReleaseTakeOver.</summary>
public FaceSet? EngineOwn;
/// <summary>A face change waiting for the render thread (ApplyFaceChanges).</summary>
public FaceSet? NextFace;
}
/// <summary>What draws a panel: its spec, its face's factory and its header text.</summary>
private sealed record FaceSet(PanelSpec Spec, Func<IImGuiPanel> Factory, string DisplayTitle);
private static readonly object Sync = new();
private static readonly Dictionary<string, Entry> Entries = new(StringComparer.OrdinalIgnoreCase);
// Copy-on-write under Sync: DrawAll iterates the list it read without holding the lock,
@ -264,6 +277,109 @@ internal static class ImGuiPanelHost
lock (Sync) return Entries.ContainsKey(title);
}
// ── Plugin windows taking over an engine panel (docs/PLUGIN_WINDOWS.md, "takeOver") ──
/// <summary>True when <paramref name="key"/> is an engine panel (Register), taken over or not. Any thread.</summary>
public static bool IsEnginePanel(string key)
{
lock (Sync) return Entries.TryGetValue(key, out Entry? e) && !e.Dynamic;
}
/// <summary>True while a plugin window draws in the engine panel <paramref name="key"/>'s place. Any thread.</summary>
public static bool IsTakenOver(string key)
{
lock (Sync) return Entries.TryGetValue(key, out Entry? e) && e.TakenOver;
}
/// <summary>
/// A plugin window takes the engine panel <paramref name="key"/>'s place: the panel keeps its
/// key (its saved place and size, open state, hotkeys, /rc command and router entry) and is
/// drawn with <paramref name="spec"/> and <paramref name="factory"/>'s face from the next
/// frame; one open now closes and opens again as the new face, where it was (popped out
/// stays popped out). The engine's own face is kept for <see cref="ReleaseTakeOver"/>. Also
/// updates a window already in place. False when <paramref name="key"/> isn't an engine
/// panel. Any thread; applied on AC's render thread.
/// </summary>
public static bool TakeOver(string key, string displayTitle, PanelSpec spec, Func<IImGuiPanel> factory)
{
lock (Sync)
{
if (!Entries.TryGetValue(key, out Entry? e) || e.Dynamic) return false;
// The first takeover finds the engine's face in place; later ones may find a plugin's.
e.EngineOwn ??= new FaceSet(e.Spec, e.Factory, e.DisplayTitle);
e.TakenOver = true;
e.NextFace = new FaceSet(spec, factory, displayTitle);
}
_faceChangePending = true;
return true;
}
/// <summary>
/// The plugin window that took over <paramref name="key"/> went (plugin unloaded, window
/// dropped): the engine's own face comes back in its place, open if the window was open.
/// Any thread; applied on AC's render thread.
/// </summary>
public static void ReleaseTakeOver(string key)
{
lock (Sync)
{
if (!Entries.TryGetValue(key, out Entry? e) || !e.TakenOver || e.EngineOwn == null) return;
e.TakenOver = false;
e.NextFace = e.EngineOwn;
}
_faceChangePending = true;
}
private static volatile bool _faceChangePending;
/// <summary>
/// Swaps in the faces TakeOver / ReleaseTakeOver asked for. A panel shown now closes as its
/// old face and opens as the new one (placement saved and read back as usual), and embedded
/// copies of it are dropped so their hosts draw the new face. AC thread, before the requests.
/// </summary>
private static void ApplyFaceChanges(float placeScale)
{
if (!_faceChangePending) return;
_faceChangePending = false;
List<Entry>? changed = null;
lock (Sync)
foreach (Entry e in DrawOrder)
{
if (e.NextFace is not FaceSet next) continue;
e.NextFace = null;
bool sameFace = e.Factory == next.Factory;
e.Spec = next.Spec;
e.Factory = next.Factory;
e.DisplayTitle = next.DisplayTitle;
if (!sameFace) (changed ??= new List<Entry>()).Add(e);
}
if (changed == null) return;
foreach (Entry e in changed)
{
RynthLog.UI($"ImGuiPanelHost: {e.Title} is drawn by {(e.TakenOver ? "a plugin's window" : "the engine's face again")}.");
DropEmbeddedCopies(e.Title);
if (!e.Shown) continue; // the next open uses the new face
Apply(e.Title, RequestKind.Close, placeScale);
Apply(e.Title, RequestKind.Open, placeScale);
}
}
/// <summary>Hides and drops the embedded copies of <paramref name="title"/> (another face takes its place). AC thread.</summary>
private static void DropEmbeddedCopies(string title)
{
List<string>? gone = null;
foreach (var kv in EmbeddedFaces)
if (kv.Value.Title.Equals(title, StringComparison.OrdinalIgnoreCase)) (gone ??= new List<string>()).Add(kv.Key);
if (gone == null) return;
foreach (string key in gone)
{
EmbeddedFace face = EmbeddedFaces[key];
EmbeddedFaces.Remove(key);
try { face.Instance.OnHidden(); }
catch (Exception ex) { RynthLog.UI($"ImGuiPanelHost: embedded {face.Title}.OnHidden threw {ex.GetType().Name}: {ex.Message}"); }
}
}
public static PanelFace CodeDefault(string title)
{
lock (Sync) return Entries.TryGetValue(title, out Entry? e) ? e.Spec.CodeDefault : PanelFace.Avalonia;
@ -455,6 +571,7 @@ internal static class ImGuiPanelHost
{
_frameScale = uiScale;
float placeScale = PlacementScale();
ApplyFaceChanges(placeScale); // plugin windows taking over (or giving back) engine panels
while (Requests.TryDequeue(out var req))
Apply(req.Title, req.Kind, placeScale);
RemoveUnregistered();

View file

@ -0,0 +1,149 @@
// ============================================================================
// RynthCore.Engine - ImGui/ImGuiStackGuard.cs
// Puts ImGui's stacks back after plugin drawing code (audit 2026-10-21, 02 F4).
// A plugin window's body (PluginWindowFace) is the plugin's own ImGui code; one
// unbalanced PushStyleColor, a BeginChild left open, or an exception between a
// Begin and its End used to carry over into every panel drawn after it that
// frame (soft asserts, so it showed as garbage or a later native fault).
//
// Take() records the stack depths with ImGui's own ErrorRecoveryStoreState
// (exported by our cimgui build); Check() compares a fresh record with it;
// RecoverTo() hands a record back to ErrorRecoveryTryToRecoverState, which ends
// what was left open (windows and child windows, tables, tab bars, tree nodes,
// groups, IDs, disabled blocks, colours, item flags, style vars, fonts, focus
// scopes) down to that record. ImGui's own error report (assert, tooltip, debug
// log) is switched off around that call: the caller logs once instead, and a
// broken plugin can't put an error tooltip on the screen every frame.
//
// Rule from ImGui: a record to recover to must be taken where the current
// window's ID stack is at its base (the start of a window or child body), since
// the recovery pops that window's IDs down to its first.
//
// The record is opaque here (ImGuiStackState reads it for the log). Its size is
// checked on first use; on a mismatch, or with a cimgui.dll without the exports,
// Available is false and callers do as before. AC's render thread, inside an
// ImGui frame and window (StoreState reads the current window).
// ============================================================================
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ImGuiStackGuard
{
/// <summary>Room for one record (ImGui 1.91.6 writes 22 bytes).</summary>
private const int RecordCapacity = 64;
/// <summary>One stack record. Zeroed before ImGui writes it, so two records compare byte for byte.</summary>
[StructLayout(LayoutKind.Sequential, Size = RecordCapacity)]
internal struct Mark
{
private fixed byte _bytes[RecordCapacity];
}
/// <summary>A record's fields (ImGuiStackState.Names), read in place: no allocation.</summary>
private static ReadOnlySpan<short> FieldsOf(in Mark m) =>
MemoryMarshal.Cast<byte, short>(MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.AsRef(in m), 1)))
[..ImGuiStackState.Fields];
private static delegate* unmanaged[Cdecl]<void*, void> _store;
private static delegate* unmanaged[Cdecl]<void*, void> _recover;
private static int _state; // 0 = not resolved, 1 = available, -1 = off
/// <summary>True when the exports exist and the record size checked out. Render thread, inside a window.</summary>
public static bool Available
{
get
{
if (_state == 0) Resolve();
return _state > 0;
}
}
private static void Resolve()
{
_state = -1;
IntPtr module = EntryPoint.ImGuiNativeHandle;
if (module == IntPtr.Zero
|| !NativeLibrary.TryGetExport(module, "igErrorRecoveryStoreState", out IntPtr store)
|| !NativeLibrary.TryGetExport(module, "igErrorRecoveryTryToRecoverState", out IntPtr recover))
{
RynthLog.UI("ImGuiStackGuard: this cimgui.dll has no igErrorRecovery* exports; plugin drawing isn't checked for unbalanced stacks.");
return;
}
_store = (delegate* unmanaged[Cdecl]<void*, void>)store;
_recover = (delegate* unmanaged[Cdecl]<void*, void>)recover;
const byte fill = 0xCC;
byte* probe = stackalloc byte[RecordCapacity];
new Span<byte>(probe, RecordCapacity).Fill(fill);
_store(probe);
if (!ImGuiStackState.WroteExpectedSize(new ReadOnlySpan<byte>(probe, RecordCapacity), fill))
{
RynthLog.UI($"ImGuiStackGuard: ImGui's stack record isn't the {ImGuiStackState.RecordBytes} bytes this engine expects; plugin drawing isn't checked.");
return;
}
_state = 1;
}
/// <summary>The stack depths now. Only when <see cref="Available"/>.</summary>
public static Mark Take()
{
Mark m = default;
_store(&m);
return m;
}
/// <summary>The stack depths now against <paramref name="before"/>; <paramref name="now"/> for the log.</summary>
public static StackCheck Check(in Mark before, out Mark now)
{
now = Take();
return ImGuiStackState.Compare(FieldsOf(before), FieldsOf(now));
}
/// <summary>True when the record was taken with the window's ID stack at its base: one a recovery may go back to.</summary>
public static bool AtWindowBase(in Mark mark) => ImGuiStackState.IdsAtBase(FieldsOf(mark));
/// <summary>What changed between two records, for the log ("colours +2, windows +1").</summary>
public static string Describe(in Mark before, in Mark after) => ImGuiStackState.Describe(FieldsOf(before), FieldsOf(after));
/// <summary>
/// Ends and pops everything above <paramref name="mark"/> (taken where the window's ID stack
/// was at its base). Windows or pops below the mark can't be put back. When windows below it
/// were ended (ImGui's recovery then does nothing), only the colours, style vars and fonts
/// above it are popped, which are the context's and safe from any window.
/// </summary>
public static void RecoverTo(in Mark mark)
{
Mark now = Take();
if (!ImGuiStackState.CanRecover(FieldsOf(mark), FieldsOf(now)))
{
(int colours, int vars, int fonts) = ImGuiStackState.GlobalPops(FieldsOf(mark), FieldsOf(now));
if (colours > 0) ImGuiNET.ImGui.PopStyleColor(colours);
if (vars > 0) ImGuiNET.ImGui.PopStyleVar(vars);
for (int i = 0; i < fonts; i++) ImGuiNET.ImGui.PopFont();
return;
}
ImGuiNET.ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
bool assert = io.ConfigErrorRecoveryEnableAssert, tooltip = io.ConfigErrorRecoveryEnableTooltip;
bool debugLog = io.ConfigErrorRecoveryEnableDebugLog, recovery = io.ConfigErrorRecovery;
io.ConfigErrorRecoveryEnableAssert = false;
io.ConfigErrorRecoveryEnableTooltip = false;
io.ConfigErrorRecoveryEnableDebugLog = false;
io.ConfigErrorRecovery = true;
try
{
fixed (Mark* m = &Unsafe.AsRef(in mark)) _recover(m);
}
finally
{
io.ConfigErrorRecoveryEnableAssert = assert;
io.ConfigErrorRecoveryEnableTooltip = tooltip;
io.ConfigErrorRecoveryEnableDebugLog = debugLog;
io.ConfigErrorRecovery = recovery;
}
}
}

View file

@ -0,0 +1,121 @@
// ============================================================================
// RynthCore.Engine - ImGui/ImGuiStackState.cs
// What a plugin's draw left on ImGui's stacks, from two of Dear ImGui's own
// stack records (ImGuiErrorRecoveryState, taken by ImGuiStackGuard before and
// after the call). Pure: no ImGui calls, so tools/SectionsTests compiles it.
//
// The record is ImGui 1.91.6's ImGuiErrorRecoveryState: 11 shorts in the order
// of Names below (imgui_internal.h; ImGuiSelfTest pins the version). Checked
// against our cimgui.dll in a 32-bit probe on 2026-10-21: 22 bytes written,
// and ImGuiStackGuard re-checks the size before its first use.
// ============================================================================
using System;
using System.Text;
namespace RynthCore.Engine.ImGuiBackend;
/// <summary>How a plugin's draw left ImGui's stacks.</summary>
internal enum StackCheck
{
/// <summary>As it found them.</summary>
Balanced,
/// <summary>It left things open (pushes, a child window, a group...): ImGui can unwind them.</summary>
LeftOpen,
/// <summary>It ended or popped something it didn't begin (the host's window, colours): can't be put back.</summary>
ClosedTooMuch,
}
internal static class ImGuiStackState
{
/// <summary>Shorts in ImGuiErrorRecoveryState (1.91.6).</summary>
public const int Fields = 11;
/// <summary>Bytes ImGui writes for one record.</summary>
public const int RecordBytes = Fields * sizeof(short);
/// <summary>Index of the window stack's depth (Begin / BeginChild).</summary>
public const int WindowStack = 0;
/// <summary>What each field counts, in the record's order.</summary>
public static readonly string[] Names =
{
"windows", "IDs", "tree nodes", "colours", "style vars", "fonts",
"focus scopes", "groups", "item flags", "popups", "disabled",
};
/// <summary>
/// Fields that count the current window's own stacks (its IDs, its tree depth): they compare
/// only at the same window depth. The rest belong to the context.
/// </summary>
public static bool PerWindow(int field) => field is 1 or 2;
/// <summary>The draw's effect: <paramref name="after"/> against <paramref name="before"/>.</summary>
public static StackCheck Compare(ReadOnlySpan<short> before, ReadOnlySpan<short> after)
{
if (after[WindowStack] < before[WindowStack]) return StackCheck.ClosedTooMuch;
bool sameWindow = after[WindowStack] == before[WindowStack];
bool changed = !sameWindow;
for (int i = 0; i < Fields; i++)
{
if (i == WindowStack || (!sameWindow && PerWindow(i))) continue;
if (after[i] < before[i]) return StackCheck.ClosedTooMuch;
if (after[i] != before[i]) changed = true;
}
return changed ? StackCheck.LeftOpen : StackCheck.Balanced;
}
/// <summary>
/// The window's ID stack holds only the window's own ID: a record taken here is one ImGui's
/// recovery can go back to (it pops a window's IDs down to that one).
/// </summary>
public static bool IdsAtBase(ReadOnlySpan<short> record) => record[1] == 1;
/// <summary>Indexes of the context-wide stacks a pop works on from any window.</summary>
public const int Colours = 3, StyleVars = 4, Fonts = 5;
/// <summary>
/// ImGui's recovery can unwind to <paramref name="mark"/> only from the same window depth or
/// deeper; when the draw ended windows below the mark (the host's own), it does nothing.
/// </summary>
public static bool CanRecover(ReadOnlySpan<short> mark, ReadOnlySpan<short> now) => now[WindowStack] >= mark[WindowStack];
/// <summary>
/// When <see cref="CanRecover"/> is false: the colours, style vars and fonts to pop to get back
/// to <paramref name="mark"/> (those stacks belong to the context, not a window). 0 where none.
/// </summary>
public static (int Colours, int StyleVars, int Fonts) GlobalPops(ReadOnlySpan<short> mark, ReadOnlySpan<short> now) =>
(Math.Max(0, now[Colours] - mark[Colours]), Math.Max(0, now[StyleVars] - mark[StyleVars]), Math.Max(0, now[Fonts] - mark[Fonts]));
/// <summary>
/// "windows +1, colours +2, style vars +1": the fields that changed, with the change (a
/// window's own IDs and tree depth only when the window depth is the same).
/// </summary>
public static string Describe(ReadOnlySpan<short> before, ReadOnlySpan<short> after)
{
var sb = new StringBuilder();
bool sameWindow = after[WindowStack] == before[WindowStack];
for (int i = 0; i < Fields; i++)
{
int d = after[i] - before[i];
if (d == 0 || (!sameWindow && PerWindow(i))) continue;
if (sb.Length > 0) sb.Append(", ");
sb.Append(Names[i]).Append(' ').Append(d > 0 ? "+" : "").Append(d);
}
return sb.Length > 0 ? sb.ToString() : "nothing";
}
/// <summary>
/// The size check on first use: <paramref name="record"/> was filled with
/// <paramref name="fill"/> and then written by ImGui. True when exactly the first
/// <see cref="RecordBytes"/> bytes were written (the layout this file expects).
/// </summary>
public static bool WroteExpectedSize(ReadOnlySpan<byte> record, byte fill)
{
int written = 0;
for (int i = 0; i < record.Length; i++)
if (record[i] != fill) written = i + 1;
// A short that happens to equal fill|fill is a value no stack reaches (0xCCCC = -13108).
return written == RecordBytes;
}
}

View file

@ -4,9 +4,13 @@
// the panel host draws the window, this face hands the body to the plugin's
// RynthPluginRenderEmbed(surface, width, height) in the default UI font, under
// an ID scope of its own. Popped out, PluginManager.RenderEmbed adds ":popout"
// to the surface name. An export that throws is switched off (PluginManager
// logs it); the body then says so and asks again every 5 s, so a reloaded
// plugin draws again without the window being reopened.
// to the surface name. An export that throws (or returns -2, "failed") is
// switched off (PluginManager logs it); the body then says so and asks again
// every 5 s, so a reloaded plugin draws again without the window being reopened.
// After every call ImGui's stacks are checked against what they were before it
// (ImGuiStackGuard): whatever the plugin left open (colours, style vars, fonts,
// IDs, groups, child windows, tables...) is ended and popped there, so the
// panels drawn after it start clean; logged once per window, then counted.
// docs/PLUGIN_WINDOWS.md. AC's render thread.
// ============================================================================
@ -44,13 +48,31 @@ internal sealed class PluginWindowFace : IImGuiPanel
int result = PluginManager.EmbedFailed;
if (_failedAtMs < 0 || now - _failedAtMs >= RetryMs)
{
// Two stack records: the body's base (where a recovery goes back to: the panel host
// calls Draw right after its BeginChild, the ID stack at its base) and the depth the
// plugin gets, which it must leave as it found.
bool guarded = ImGuiStackGuard.Available;
ImGuiStackGuard.Mark bodyBase = guarded ? ImGuiStackGuard.Take() : default;
guarded = guarded && ImGuiStackGuard.AtWindowBase(bodyBase); // drawn anywhere else: as before
ImGuiNET.ImGui.PushID(_idScope);
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
ImGuiStackGuard.Mark given = guarded ? ImGuiStackGuard.Take() : default;
try { result = PluginManager.RenderEmbed(_plugin, _surface, avail, out _); }
finally
{
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.PopID();
ImGuiStackGuard.Mark after = default;
StackCheck check = guarded ? ImGuiStackGuard.Check(given, out after) : StackCheck.Balanced;
if (check == StackCheck.Balanced)
{
ImGuiNET.ImGui.PopFont();
ImGuiNET.ImGui.PopID();
}
else
{
// Ends and pops what the plugin left, with this face's ID scope and font.
ImGuiStackGuard.RecoverTo(bodyBase);
NoteUnbalanced(check, ImGuiStackGuard.Describe(given, after));
}
}
if (result == PluginManager.EmbedFailed) _failedAtMs = now;
else if (result == PluginManager.EmbedDrawn) _failedAtMs = -1;
@ -66,4 +88,22 @@ internal sealed class PluginWindowFace : IImGuiPanel
_ => $"Waiting for {_plugin}…",
}, Mute);
}
// Unbalanced draws by plugin + surface: logged the first time, then every RepeatEvery-th.
private static readonly System.Collections.Generic.Dictionary<string, int> Unbalanced = new(StringComparer.Ordinal);
private const int RepeatEvery = 1000;
private void NoteUnbalanced(StackCheck check, string what)
{
string key = _plugin + "/" + _title;
Unbalanced.TryGetValue(key, out int n);
Unbalanced[key] = ++n;
if (n != 1 && n % RepeatEvery != 0) return;
string again = n == 1 ? "" : $" ({n} times so far)";
RynthLog.Warn(check == StackCheck.ClosedTooMuch
? $"PluginWindows: {_plugin} drawing '{_title}' ended or popped what it didn't open ({what}){again}. " +
"What it left open was put back; what it took can't be, so the window may draw wrongly."
: $"PluginWindows: {_plugin} drawing '{_title}' left ImGui's stacks unbalanced ({what}){again}. " +
"Put back after its draw; the panels after it draw as normal.");
}
}

View file

@ -211,6 +211,11 @@ internal static class RynthTheme
public static uint BarBackground => WithAlpha(_t.BarBg, 0xE6);
public const float BarRounding = 4f;
public static uint BarButton => _t.FrameBg;
// A button whose window is open (docked or popped out, BarOpenState): the accent fill
// (Chat's active tab), halfway to the accent under the mouse, and an accent border.
public static uint BarButtonOpen => _t.AccentFill;
public static uint BarButtonOpenHover => _t.WindowBorder;
public static uint BarButtonOpenBorder => _t.Accent;
public static readonly uint BarText = Argb(0xFFFFFFFF);
public static readonly uint RcLabel = Argb(0xFF90EE90); // LightGreen
public static readonly uint ReloadLabel = Argb(0xFFF0E68C); // Khaki

View file

@ -21,7 +21,12 @@
// "miniremote") into the engine's current ImGui
// window on AC's render thread, inside a
// width x height child; reports the size it wants.
// 1 = drawn, 0 = not ready / unknown surface.
// 1 = drawn, 0 = not ready / unknown surface,
// -2 = failed (it caught its own exception): its
// surfaces go off for the session, as for a throw
// (engines before 2026-10-21 read -2 as 0). Leave
// ImGui's stacks as found; the engine puts back
// what a plugin window leaves open, and logs it.
// void RynthPluginOnServerMessage(uint opcode, byte* data, int length)
// — v78, reassembled server messages the plugin
// asked for with SetServerMessageInterestFn

View file

@ -1336,8 +1336,8 @@ internal static partial class PluginManager
/// Render thread only. Returns <see cref="EmbedDrawn"/>, <see cref="EmbedNotReady"/> (the
/// plugin isn't ready: before login, no ImGui context, or too old to draw in a pop-out),
/// <see cref="EmbedNoPlugin"/> (not loaded, or too old to have the export) or
/// <see cref="EmbedFailed"/> (it threw: the export is switched off for this session; the
/// plugin keeps running).
/// <see cref="EmbedFailed"/> (it threw, or returned -2 to say it caught its own exception:
/// the export is switched off for this session; the plugin keeps running).
/// </summary>
internal static unsafe int RenderEmbed(string pluginName, ReadOnlySpan<byte> surfaceUtf8, System.Numerics.Vector2 size, out System.Numerics.Vector2 want)
{
@ -1380,6 +1380,15 @@ internal static partial class PluginManager
fixed (byte* s = surfaceUtf8)
r = ((delegate* unmanaged[Cdecl]<byte*, float, float, float*, float*, int>)fn)(s, size.X, size.Y, &w, &h);
want = new System.Numerics.Vector2(float.IsFinite(w) ? MathF.Max(0, w) : 0, float.IsFinite(h) ? MathF.Max(0, h) : 0);
if (r == EmbedFailed)
{
// The plugin caught its own exception and says so (an exception can't leave a
// managed plugin's [UnmanagedCallersOnly] export, so plugins catch everything; with
// 0 the window would say "Waiting..." for ever): the same as a throw.
p.RenderEmbedPtr = IntPtr.Zero;
RynthLog.Error($"PluginManager: {p.DisplayName} RenderEmbed reported a failure (-2) - embedded surfaces off for this session (plugin keeps running).");
return EmbedFailed;
}
return r == 1 ? EmbedDrawn : EmbedNotReady;
}
catch (Exception ex)
@ -1436,6 +1445,17 @@ internal static partial class PluginManager
public static void ShutdownAll()
{
// A plugin's Shutdown never runs alongside its Tick on the pump thread (audit
// 2026-10-21, 01 #1). EngineLifecycle.Shutdown stops the pump before anything reaches
// here, so this returns at once; a frame still running gets ShutdownWaitMs more, and
// if it outlasts that the plugins are left alone. Nothing below changes then: the
// teardown's defensive ShutdownAll asks again after its other steps.
PluginShutdownGate.Verdict gate = EntryPoint.StopTickPumpForPluginShutdown(PluginShutdownGate.ShutdownWaitMs);
if (!PluginShutdownGate.MayShutDownPlugins(gate))
{
RynthLog.Error(PluginShutdownGate.DescribeRefusal(_plugins.Count, DescribePumpDispatch()));
return;
}
RynthLog.Plugin($"PluginManager: Shutting down {_plugins.Count} plugin(s)...");
UiLifecycleHooks.UiInitialized -= OnUIInitializedObserved;
LoginLifecycleHooks.LoginComplete -= OnLoginCompleteObserved;

View file

@ -1,7 +1,7 @@
// ============================================================================
// RynthCore.Engine - Plugins/PumpGuards.cs
//
// Two small pieces for PluginManager.TickAll and the plugin pump thread.
// Small pieces for PluginManager.TickAll, the plugin pump thread and plugin shutdown.
//
// StepFaultLog: TickAll's own steps (the main-thread freeze check, the delayed
// self-identify, the Nav3D frame clear/commit, dropping failed plugins' script
@ -17,6 +17,9 @@
// the dump, the hang watchdog reports, and this line names the plugin
// (2026-10-13 06:00: RynthAi's tick jumped to address 0).
//
// PluginShutdownGate: plugins are shut down only once the pump has stopped (or
// never ran), so no plugin's Shutdown runs alongside its Tick (audit 2026-10-21).
//
// Pure: no engine state. Compiled into tools\EngineRobustnessTests.
// ============================================================================
@ -82,3 +85,47 @@ internal static class PumpDispatchInfo
return $"inside {plugin} {export ?? "call"} for {ms} ms";
}
}
/// <summary>
/// Whether PluginManager.ShutdownAll may call the plugins' Shutdown now: never while the
/// plugin pump may still be inside a frame on its own thread, or a plugin's Tick and events
/// would run alongside its Shutdown, which frees their threads, textures and handles (a
/// native fault there can't be caught: audit 2026-10-21, 01 #1). EngineLifecycle.Shutdown
/// stops the pump before anything shuts a plugin down; this checks that the stop finished.
/// </summary>
internal static class PluginShutdownGate
{
/// <summary>How long ShutdownAll waits for the pump on top of EngineLifecycle's own join.</summary>
public const int ShutdownWaitMs = 5000;
internal enum Verdict
{
/// <summary>No pump was started in this generation (plugins off, or before login).</summary>
NoPump,
/// <summary>The pump has left its loop: nothing ticks the plugins any more.</summary>
PumpStopped,
/// <summary>Called on the pump thread itself: no frame of it can run alongside.</summary>
OnPumpThread,
/// <summary>The pump is still running (a frame outlasted the wait): leave the plugins alone.</summary>
PumpStillRunning,
}
/// <summary>
/// <paramref name="pumpStarted"/>: a pump thread was started; <paramref name="pumpExited"/>:
/// it has left its loop (after the stop and the wait); <paramref name="onPumpThread"/>: the
/// caller is that thread.
/// </summary>
public static Verdict Decide(bool pumpStarted, bool pumpExited, bool onPumpThread) =>
!pumpStarted ? Verdict.NoPump
: pumpExited ? Verdict.PumpStopped
: onPumpThread ? Verdict.OnPumpThread
: Verdict.PumpStillRunning;
public static bool MayShutDownPlugins(Verdict verdict) => verdict != Verdict.PumpStillRunning;
/// <summary>The log line when ShutdownAll leaves the plugins alone.</summary>
public static string DescribeRefusal(int plugins, string? pumpInside) =>
$"PluginManager: the plugin pump is still running ({pumpInside ?? "no plugin call named"}) - " +
$"{plugins} plugin(s) NOT shut down now, so no Shutdown runs alongside a Tick. " +
"The engine's teardown tries once more after its other steps.";
}

View file

@ -0,0 +1,42 @@
// ============================================================================
// RynthCore.Engine - UI/BarOpenState.cs
// Which toolbar buttons (ImGuiBar) draw as open: a button is highlighted in
// the theme's accent while a window it stands for is open, docked or popped
// out (a popped-out panel stays open in ImGuiPanelHost).
//
// What a button stands for: an engine panel's or a plugin window's button its
// title (a plugin window that took over an engine panel has that panel's
// title), a plugin script window's button that window's panel key ("script:
// ...", not its title); a button that opens a menu of several (ILT, Scripts)
// every window it lists, open while any of them is.
//
// Pure (no ImGui, no engine state): the caller passes the open check
// (ImGuiPanelHost.IsOpen, one set lookup a key). Tests: tools/BarLayoutTests.
// Any thread.
// ============================================================================
using System;
namespace RynthCore.Engine.UI;
internal static class BarOpenState
{
/// <summary>
/// The window a one-window button stands for: a script window's panel key when it is one,
/// else the title (engine panels, ImGui-only panels, plugin windows).
/// </summary>
public static string KeyFor(string title, string? scriptPanelKey) =>
string.IsNullOrEmpty(scriptPanelKey) ? title : scriptPanelKey;
/// <summary>A one-window button is open while its window is (an empty key never is).</summary>
public static bool IsOpen(string key, Func<string, bool> isOpen) =>
!string.IsNullOrEmpty(key) && isOpen(key);
/// <summary>A button for several windows (ILT, Scripts) is open while any of them is; none listed = closed.</summary>
public static bool AnyOpen(ReadOnlySpan<string> keys, Func<string, bool> isOpen)
{
foreach (string key in keys)
if (IsOpen(key, isOpen)) return true;
return false;
}
}

View file

@ -9,12 +9,20 @@
// registers a dynamic panel for each window the manifests ask for (a window
// with "server" only while that server is active) and unregisters the rest.
// The panel key is the window's title, so its saved place, hotkeys and /rc
// commands use the name players see; a title an engine panel has is refused.
// commands use the name players see. A title an engine panel has is refused,
// unless the window declares "takeOver": then it takes that panel's place
// (ImGuiPanelHost.TakeOver: same key, so the saved place and size, open state,
// hotkeys and commands carry over) and the engine's face steps aside, not drawn
// and without its bar button (TakesOver), until the window goes (the plugin
// unloads or stops declaring it): then the engine's face comes back where the
// window was, open if it was open. So a screen can move out of the engine with
// the plugin shipping first and the engine face deleted a release later.
// A window seen for the first time this session opens if it was open when the
// game last closed (Remember Open Windows); one that went with a plugin reload
// opens again when the plugin comes back.
//
// WindowPlan.cs is the pure part (which windows, which are refused and why).
// WindowPlan.cs is the pure part (which windows, which are refused and why,
// which take over an engine panel).
// ============================================================================
using System;
@ -27,13 +35,14 @@ namespace RynthCore.Engine.UI.Sections;
internal static class PluginWindows
{
private sealed record Hosted(SectionWindowDecl Decl, string Signature);
private sealed record Hosted(SectionWindowDecl Decl, string Signature, bool TakesOver);
private static readonly Dictionary<string, Hosted> Live = new(StringComparer.OrdinalIgnoreCase); // render thread
private static readonly HashSet<string> SeenThisSession = new(StringComparer.OrdinalIgnoreCase); // render thread
private static readonly HashSet<string> ReopenWhenBack = new(StringComparer.OrdinalIgnoreCase); // render thread
private static readonly HashSet<string> RefusalsLogged = new(StringComparer.Ordinal); // render thread
private static volatile SectionWindowDecl[] _barWindows = Array.Empty<SectionWindowDecl>();
private static volatile string[] _takenOver = Array.Empty<string>();
private static int _version;
/// <summary>Hosted windows that asked for a bar button, in manifest order. Any thread.</summary>
@ -45,12 +54,23 @@ internal static class PluginWindows
/// <summary>True when <paramref name="title"/> is a plugin window hosted now. Render thread.</summary>
public static bool IsHosted(string title) => Live.ContainsKey(title);
/// <summary>
/// True while a plugin window has taken the place of the engine panel <paramref name="title"/>:
/// the engine's own bar button for it is left out (the window has its own when it asks). Any thread.
/// </summary>
public static bool TakesOver(string title)
{
foreach (string t in _takenOver)
if (t.Equals(title, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
/// <summary>After a SectionRegistry rebuild: register, update and drop the windows' panels. Render thread.</summary>
public static void Sync(IReadOnlyList<SectionManifest> manifests, IReadOnlyList<ServerState> servers)
{
var refused = new List<string>();
Dictionary<string, SectionWindowDecl> want = WindowPlan.Build(manifests, servers,
title => ImGuiPanelHost.HasFace(title) && !Live.ContainsKey(title), refused);
var takeOvers = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, SectionWindowDecl> want = WindowPlan.Build(manifests, servers, Use, refused, takeOvers);
foreach (string r in refused)
if (RefusalsLogged.Add(r)) RynthLog.UI("PluginWindows: " + r + " - not shown.");
@ -60,8 +80,18 @@ internal static class PluginWindows
if (!want.ContainsKey(title)) gone.Add(title);
foreach (string title in gone)
{
if (ImGuiPanelHost.IsOpen(title)) ReopenWhenBack.Add(title);
ImGuiPanelHost.Unregister(title);
Hosted was = Live[title];
if (was.TakesOver)
{
// The engine's face comes back in the window's place (open if it was open).
ImGuiPanelHost.ReleaseTakeOver(title);
RynthLog.UI($"PluginWindows: {was.Decl.Plugin}'s window '{title}' went - the engine's panel is back.");
}
else
{
if (ImGuiPanelHost.IsOpen(title)) ReopenWhenBack.Add(title);
ImGuiPanelHost.Unregister(title);
}
Live.Remove(title);
changed = true;
}
@ -71,9 +101,19 @@ internal static class PluginWindows
string sig = WindowPlan.Signature(w);
if (Live.TryGetValue(title, out Hosted? h) && h.Signature == sig) continue;
SectionWindowDecl decl = w;
ImGuiPanelHost.RegisterDynamic(title, title, Spec(decl), () => new PluginWindowFace(decl.Plugin, decl.Surface, decl.Title));
Func<IImGuiPanel> face = () => new PluginWindowFace(decl.Plugin, decl.Surface, decl.Title);
if (takeOvers.Contains(title))
{
// An engine panel's place: its key, saved place and open state stay; nothing to reopen.
if (!ImGuiPanelHost.TakeOver(title, title, Spec(decl), face)) continue;
if (h == null) RynthLog.UI($"PluginWindows: {decl.Plugin}'s window '{title}' takes the engine panel's place.");
Live[title] = new Hosted(decl, sig, TakesOver: true);
changed = true;
continue;
}
ImGuiPanelHost.RegisterDynamic(title, title, Spec(decl), face);
bool first = h == null;
Live[title] = new Hosted(decl, sig);
Live[title] = new Hosted(decl, sig, TakesOver: false);
changed = true;
if (!first) continue;
bool reopen = ReopenWhenBack.Remove(title);
@ -86,12 +126,26 @@ internal static class PluginWindows
if (!changed) return;
var bar = new List<SectionWindowDecl>();
var taken = new List<string>();
foreach (Hosted h in Live.Values)
{
if (h.Decl.Bar) bar.Add(h.Decl);
if (h.TakesOver) taken.Add(h.Decl.Title);
}
_barWindows = bar.ToArray();
_takenOver = taken.ToArray();
System.Threading.Interlocked.Increment(ref _version);
}
/// <summary>
/// What already uses <paramref name="title"/>: an engine panel (taken over by a window here or
/// not), this sync's own hosted window (free), or another panel such as a script window.
/// </summary>
private static TitleUse Use(string title) =>
ImGuiPanelHost.IsEnginePanel(title) ? TitleUse.EnginePanel
: ImGuiPanelHost.HasFace(title) && !Live.ContainsKey(title) ? TitleUse.Other
: TitleUse.Free;
private static PanelSpec Spec(SectionWindowDecl w) => new(
new Vector2(w.Width, w.Height), new Vector2(w.MinWidth, w.MinHeight),
EdgeToEdge: w.EdgeToEdge, GripInBody: w.EdgeToEdge);

View file

@ -20,7 +20,7 @@
// "windows": [
// { "id": "characters", "title": "Characters", "surface": "window:characters",
// "icon": "\uE68E", "width": 420, "height": 260, "minWidth": 280, "minHeight": 140,
// "bar": true, "edgeToEdge": true, "server": "" } ]
// "bar": true, "edgeToEdge": true, "server": "", "takeOver": false } ]
// }
// servers servers the plugin knows. A built-in id (ilt, aelrynth) keeps the
// engine's own detection; a new id is detected from its lists.
@ -34,7 +34,11 @@
// hosts as panels: header, pop-out, resize, remembered place, a bar
// button when "bar" (the icon: a Phosphor glyph, else the title's
// letter); the body is "surface" through RynthPluginRenderEmbed.
// "title" is the panel key (unique; an engine panel's is refused).
// "title" is the panel key (unique). An engine panel's title is refused,
// unless "takeOver": true (2026-10-21): the window then draws in that
// panel's place (same key: its saved place, open state and commands)
// and the engine's face comes back when the plugin goes. Engines
// before that ignore the key and keep their face (the title refused).
// "server" set: only while that server is active. docs/PLUGIN_WINDOWS.md.
//
// Everything from a plugin is checked here: ids are short lower-case words,
@ -93,7 +97,9 @@ internal sealed record SectionWindowDecl(
float MinHeight,
bool Bar,
bool EdgeToEdge,
string Server)
string Server,
// Takes the place of the engine panel with this title while hosted ("takeOver": true).
bool TakeOver = false)
{
/// <summary>For every world, not one server.</summary>
public bool IsUniversal => Server.Length == 0;
@ -210,7 +216,8 @@ internal static class SectionManifestParser
float minWidth = Math.Min(WindowSize(Size(e, "minWidth"), MinWindowSize), width);
float minHeight = Math.Min(WindowSize(Size(e, "minHeight"), MinWindowSize), height);
windows.Add(new SectionWindowDecl(plugin, id, title, surface, Icon(Str(e, "icon")),
width, height, minWidth, minHeight, Bool(e, "bar", false), Bool(e, "edgeToEdge", false), server));
width, height, minWidth, minHeight, Bool(e, "bar", false), Bool(e, "edgeToEdge", false), server,
Bool(e, "takeOver", false)));
}
return new SectionManifest(plugin, servers.ToArray(), sections.ToArray(), contributions.ToArray())

View file

@ -9,29 +9,49 @@ using System.Collections.Generic;
namespace RynthCore.Engine.UI.Sections;
/// <summary>What already uses a window's title (its panel key).</summary>
internal enum TitleUse
{
/// <summary>Nothing, or this window's own panel (hosted already).</summary>
Free,
/// <summary>An engine panel: a window that declares "takeOver" draws in its place; any other is refused.</summary>
EnginePanel,
/// <summary>Another panel that isn't the engine's (a script window): refused.</summary>
Other,
}
/// <summary>Which plugin windows to host, from the manifests and the servers. Pure.</summary>
internal static class WindowPlan
{
/// <summary>
/// The windows to host, keyed by title, and the ones left out with the reason. A server
/// window counts only while its server is active; the first plugin to claim a title keeps it;
/// <paramref name="isEnginePanel"/> titles are refused.
/// window counts only while its server is active; the first plugin to claim a title keeps it.
/// A title an engine panel has (<paramref name="titleUse"/>) is hosted only when the window
/// declares "takeOver": it then goes in <paramref name="takeOvers"/>, and the engine's face
/// for that title steps aside while the window is hosted. Other used titles are refused.
/// </summary>
public static Dictionary<string, SectionWindowDecl> Build(IReadOnlyList<SectionManifest> manifests,
IReadOnlyList<ServerState> servers, Func<string, bool> isEnginePanel, List<string> refused)
IReadOnlyList<ServerState> servers, Func<string, TitleUse> titleUse, List<string> refused, ISet<string> takeOvers)
{
var want = new Dictionary<string, SectionWindowDecl>(StringComparer.OrdinalIgnoreCase);
foreach (SectionManifest m in manifests)
foreach (SectionWindowDecl w in m.Windows)
{
if (!w.IsUniversal && !ServerActive(servers, w.Server)) continue;
if (isEnginePanel(w.Title)) { refused.Add($"{w.Plugin}'s window '{w.Title}': an engine panel has that title"); continue; }
TitleUse use = titleUse(w.Title);
if (use == TitleUse.Other) { refused.Add($"{w.Plugin}'s window '{w.Title}': another panel has that title"); continue; }
if (use == TitleUse.EnginePanel && !w.TakeOver)
{
refused.Add($"{w.Plugin}'s window '{w.Title}': an engine panel has that title (\"takeOver\": true takes its place)");
continue;
}
if (want.TryGetValue(w.Title, out SectionWindowDecl? first))
{
refused.Add($"{w.Plugin}'s window '{w.Title}': {first.Plugin} has a window with that title");
continue;
}
want[w.Title] = w;
if (use == TitleUse.EnginePanel) takeOvers.Add(w.Title);
}
return want;
}
@ -45,5 +65,5 @@ internal static class WindowPlan
/// <summary>What a hosted window's panel depends on: a change re-registers it.</summary>
public static string Signature(SectionWindowDecl w) =>
string.Join("|", w.Plugin, w.Surface, w.Icon, w.Width, w.Height, w.MinWidth, w.MinHeight, w.Bar, w.EdgeToEdge);
string.Join("|", w.Plugin, w.Surface, w.Icon, w.Width, w.Height, w.MinWidth, w.MinHeight, w.Bar, w.EdgeToEdge, w.TakeOver);
}

View file

@ -7,7 +7,7 @@
1. writes obj\...\rynth-plugin.json from the csproj:
name RynthPluginName (default: AssemblyName without "RynthCore.Plugin.")
version Version (Publish-Update.ps1 passes -p:Version=yyyy.m.d.n)
minEngineApi RynthPluginMinEngineApi
minEngineApi RynthPluginMinEngineApi (raised in release builds; see _RynthPluginEffectiveMinEngineApi)
maxEngineApi RynthPluginMaxEngineApi (optional; leave unset - the table is append-only)
dependencies @(RynthPluginDependency) Include = plugin name, metadata MinVersion, Optional="true"
author RynthPluginAuthor (default: Authors, then Company)
@ -37,9 +37,41 @@
<PropertyGroup>
<!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. -->
<RynthCoreSdkApiVersion>89</RynthCoreSdkApiVersion>
<!-- The first engine API that loads managed plugins and gives them Runtime\PluginShared (2026.10.19.1). -->
<RynthCoreManagedPluginApi>88</RynthCoreManagedPluginApi>
<_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true</_RynthPluginManifestOn>
</PropertyGroup>
<!--
The minEngineApi that goes into the manifest (and the [assembly: RynthPluginManifest] runtime
check): _RynthPluginEffectiveMinEngineApi.
Normally the plugin's own RynthPluginMinEngineApi, as it is.
RynthPluginSharedSdk=true (Publish-Update.ps1's release builds): the plugin ships alone in the
feed and runs against the RynthCore.PluginSdk.dll in Runtime\PluginShared, which reaches a
player only with the core installer of the same release. Its Has* checks guard against an
engine without a function, not against an older PluginShared without an SDK member it calls
(that fails the method, or the load). So:
* a declared minimum at or above RynthCoreManagedPluginApi (88) is the plugin's own checked
claim and is used as it is;
* a lower one (the "66: every newer call is behind its Has* check" of NativeAOT days, when each
plugin carried its own SDK) can't hold for a plugin that needs 88 just to load, so the build
uses RynthCoreSdkApiVersion, the API of the SDK it was compiled against: it may call anything
this SDK has, and the launcher then holds the plugin until the player's core has that API.
A plugin checked against an older PluginShared declares that API (88 or more) to keep running on
older cores. Release builds used to force -p:RynthPluginMinEngineApi=88 on every plugin instead,
so a plugin calling a v89 SDK member was offered to API-88 cores (structural audit 2026-10-21).
-->
<PropertyGroup Condition="'$(_RynthPluginManifestOn)' == 'true'">
<_RynthPluginEffectiveMinEngineApi>$(RynthPluginMinEngineApi.Trim())</_RynthPluginEffectiveMinEngineApi>
<_RynthPluginMinIsNumber>$([System.Text.RegularExpressions.Regex]::IsMatch('$(RynthPluginMinEngineApi.Trim())', '^[0-9]{1,9}$'))</_RynthPluginMinIsNumber>
</PropertyGroup>
<PropertyGroup Condition="'$(_RynthPluginManifestOn)' == 'true' and '$(RynthPluginSharedSdk)' == 'true' and '$(_RynthPluginMinIsNumber)' == 'True'">
<_RynthPluginMinRaised Condition="$(RynthPluginMinEngineApi.Trim()) &lt; $(RynthCoreManagedPluginApi)">true</_RynthPluginMinRaised>
<_RynthPluginEffectiveMinEngineApi Condition="'$(_RynthPluginMinRaised)' == 'true'">$(RynthCoreSdkApiVersion)</_RynthPluginEffectiveMinEngineApi>
</PropertyGroup>
<PropertyGroup Condition="'$(_RynthPluginManifestOn)' == 'true'">
<RynthPluginName Condition="'$(RynthPluginName)' == ''">$([System.Text.RegularExpressions.Regex]::Replace('$(AssemblyName)', '^RynthCore\.Plugin\.', ''))</RynthPluginName>
<RynthPluginAuthor Condition="'$(RynthPluginAuthor)' == '' and '$(Authors)' != '' and '$(Authors)' != '$(AssemblyName)'">$(Authors)</RynthPluginAuthor>
@ -56,7 +88,7 @@
plugin's own check matches its manifest without any code in the plugin. -->
<ItemGroup Condition="'$(_RynthPluginManifestOn)' == 'true'">
<AssemblyAttribute Include="RynthCore.PluginSdk.RynthPluginManifestAttribute">
<_Parameter1>$(RynthPluginMinEngineApi)</_Parameter1>
<_Parameter1>$(_RynthPluginEffectiveMinEngineApi)</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
@ -283,7 +315,9 @@ public class RynthEmbedPluginManifest : Task
<!-- 1 + 2: the JSON and RynthPluginInfo, before compiling (RynthPluginInfo is compiled in). -->
<Target Name="RynthGeneratePluginManifest" BeforeTargets="CoreCompile" Condition="'$(_RynthPluginManifestOn)' == 'true'">
<RynthWritePluginManifest Name="$(RynthPluginName)" Version="$(Version)" MinEngineApi="$(RynthPluginMinEngineApi)"
<Message Importance="high" Condition="'$(_RynthPluginMinRaised)' == 'true'"
Text="$(RynthPluginName): RynthPluginMinEngineApi $(RynthPluginMinEngineApi) is below the managed-plugin API $(RynthCoreManagedPluginApi); this shared-SDK build declares $(_RynthPluginEffectiveMinEngineApi), the API of the SDK it was built with. Declare a checked minimum (at least $(RynthCoreManagedPluginApi)) to run on older cores." />
<RynthWritePluginManifest Name="$(RynthPluginName)" Version="$(Version)" MinEngineApi="$(_RynthPluginEffectiveMinEngineApi)"
MaxEngineApi="$(RynthPluginMaxEngineApi)" SdkApiVersion="$(RynthCoreSdkApiVersion)"
Author="$(RynthPluginAuthor)" Description="$(RynthPluginDescription)"
Homepage="$(RynthPluginHomepage)" License="$(RynthPluginLicense)"