RynthCore as of 2026-11-15 (internal d196196): release 2026.11.15.1

This commit is contained in:
Tom Bohar 2026-11-15 10:51:37 -05:00
commit 7caafc72af
6 changed files with 525 additions and 186 deletions

View file

@ -90,8 +90,12 @@ internal partial class MainWindow : Window
// Last observed window rect per PID — set on first post-login observation,
// used to detect an actual move before we commit anything to appsettings.
private readonly Dictionary<int, (int x, int y, int w, int h)> _baselineWindowRects = [];
// When each client's saved window was put back, and the put-backs since (AcWindowRestoreRule).
private readonly Dictionary<int, (DateTime At, DateTime? Last, int Count)> _windowRestores = [];
// When each client was first seen logged in: the restore waits from then for AC to reach the saved size (AcWindowPlacementRule).
private readonly Dictionary<int, DateTime> _windowLoginSeenUtc = [];
// The window size each client was last seen at and since when (the restore waits for it to hold: RestoreSettle).
private readonly Dictionary<int, (int w, int h, DateTime since)> _windowSizeSinceUtc = [];
// Per client, a new window rect and since when it has held; saved only once it held for StableFor (AcWindowPlacementRule).
private readonly Dictionary<int, AcWindowPlacementRule.Pending?> _windowSavePending = [];
// Serializes prefs-swap launches so two accounts don't race on the live
// UserPreferences.ini. Non-prefs launches don't acquire this and stay
// parallel.
@ -3874,8 +3878,12 @@ internal partial class MainWindow : Window
_everLoggedInPids.RemoveWhere(pid => !activePids.Contains(pid));
foreach (int pid in _baselineWindowRects.Keys.Where(pid => !activePids.Contains(pid)).ToList())
_baselineWindowRects.Remove(pid);
foreach (int pid in _windowRestores.Keys.Where(pid => !activePids.Contains(pid)).ToList())
_windowRestores.Remove(pid);
foreach (int pid in _windowLoginSeenUtc.Keys.Where(pid => !activePids.Contains(pid)).ToList())
_windowLoginSeenUtc.Remove(pid);
foreach (int pid in _windowSavePending.Keys.Where(pid => !activePids.Contains(pid)).ToList())
_windowSavePending.Remove(pid);
foreach (int pid in _windowSizeSinceUtc.Keys.Where(pid => !activePids.Contains(pid)).ToList())
_windowSizeSinceUtc.Remove(pid);
// Latch any PID that's currently reporting IsLoggedIn=true. Once
// latched, the reaper will permanently exempt it — even if some race
@ -4882,6 +4890,49 @@ internal partial class MainWindow : Window
[DllImport("user32.dll")]
private static extern bool IsWindowVisible(IntPtr hWnd);
[StructLayout(LayoutKind.Sequential)]
private struct MonitorInfo
{
public int cbSize;
public WinRect rcMonitor;
public WinRect rcWork;
public uint dwFlags;
}
private delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, IntPtr lprcMonitor, IntPtr dwData);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, MonitorEnumProc lpfnEnum, IntPtr dwData);
[DllImport("user32.dll", EntryPoint = "GetMonitorInfoW")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MonitorInfo lpmi);
/// The work area (screen minus taskbar) of every monitor, for AcWindowPlacementRule.ClampToWorkArea.
/// Empty if the calls fail; the rule then leaves the window where AC put it.
private static List<AcWindowPlacementRule.WorkArea> MonitorWorkAreas()
{
var list = new List<AcWindowPlacementRule.WorkArea>(4);
try
{
EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, (mon, _, _, _) =>
{
var mi = new MonitorInfo { cbSize = Marshal.SizeOf<MonitorInfo>() };
if (GetMonitorInfo(mon, ref mi))
list.Add(new AcWindowPlacementRule.WorkArea(mi.rcWork.Left, mi.rcWork.Top, mi.rcWork.Right, mi.rcWork.Bottom));
return true;
}, IntPtr.Zero);
}
catch
{
list.Clear();
}
return list;
}
// The launcher never resizes an AC window (AcWindowPlacementRule): every SetWindowPos on one carries this.
private const uint SWP_NOSIZE = 0x0001;
private const uint SWP_NOZORDER = 0x0004;
private const uint SWP_NOACTIVATE = 0x0010;
// Posts the move to the client's thread instead of waiting for it: a plain
@ -4923,11 +4974,13 @@ internal partial class MainWindow : Window
}
/// <summary>
/// On the first tick after AC reaches graphics-ready for a tracked client,
/// applies the saved window placement for that account. After that, every
/// tick reads the current rect and persists changes back to the profile so
/// user-initiated moves/resizes survive restart. Idempotent within a tolerance
/// to avoid spamming SaveSettings on DWM-frame fudge.
/// Once a tracked client is logged in, puts the account's saved window
/// position back (position only: AC sizes its own window from its
/// resolution), then saves the window's rect to the profile whenever a new
/// one has held for a while, so the player's own moves survive a restart.
/// The decisions are AcWindowPlacementRule's (2026-11-15, a #rynth-issues
/// report, 2026-11-14: a saved logout-size rect shrank the next login's
/// window and cut the HUD off).
/// </summary>
private void ApplyOrPersistWindowPlacement(
Process process,
@ -4976,8 +5029,11 @@ internal partial class MainWindow : Window
if (hwnd == IntPtr.Zero)
hwnd = FindLargestVisibleWindowForProcess(process.Id);
bool hasSaved = profile.WindowX.HasValue && profile.WindowY.HasValue
&& profile.WindowWidth.HasValue && profile.WindowHeight.HasValue;
AcWindowPlacementRule.Placement? saved =
profile.WindowX.HasValue && profile.WindowY.HasValue && profile.WindowWidth.HasValue && profile.WindowHeight.HasValue
? new AcWindowPlacementRule.Placement(profile.WindowX.Value, profile.WindowY.Value,
profile.WindowWidth.Value, profile.WindowHeight.Value)
: null;
// Only act once AC reports IsLoggedIn — graphicsReady fires while AC
// is still in its small login window, and AC will resize itself again
@ -4987,136 +5043,98 @@ internal partial class MainWindow : Window
// a transient size that gets restored too early next launch.
bool loggedIn = activeSessions.TryGetValue(process.Id, out SessionStateRecord? sess) && sess.IsLoggedIn;
if (!loggedIn)
return;
if (!_windowPositionAppliedPids.Contains(process.Id))
{
_windowPositionAppliedPids.Add(process.Id);
if (hwnd == IntPtr.Zero)
{
LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}@{serverName}): hwnd=0 — cannot restore or capture.");
return;
}
if (hasSaved)
{
SetWindowPos(
hwnd,
IntPtr.Zero,
profile.WindowX!.Value,
profile.WindowY!.Value,
profile.WindowWidth!.Value,
profile.WindowHeight!.Value,
SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS);
_windowRestores[process.Id] = (DateTime.UtcNow, null, 0);
LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}@{serverName}): restored to ({profile.WindowX},{profile.WindowY},{profile.WindowWidth}x{profile.WindowHeight}).");
return;
}
// No saved position — don't capture immediately. The window may still
// be at character-select/login size. Record the baseline on the next
// poll and only persist once the user actually moves or resizes it.
// A rect pending from before the logout must not count its time at
// character select toward StableFor and save itself on the relogin.
_windowSavePending.Remove(process.Id);
return;
}
DateTime nowUtc = DateTime.UtcNow;
if (!_windowLoginSeenUtc.TryGetValue(process.Id, out DateTime loginSeenUtc))
_windowLoginSeenUtc[process.Id] = loginSeenUtc = nowUtc;
if (hwnd == IntPtr.Zero)
{
if (_windowPositionAppliedPids.Add(process.Id))
LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}@{serverName}): hwnd=0 — cannot restore or capture.");
return;
}
if (!GetWindowRect(hwnd, out WinRect rect))
return;
var current = new AcWindowPlacementRule.Placement(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
int x = rect.Left;
int y = rect.Top;
int w = rect.Right - rect.Left;
int h = rect.Bottom - rect.Top;
if (w < 200 || h < 200)
return;
// Reject windows parked off-screen — AC places the window at (-10000,-10000)
// during startup before moving it into view. Multi-monitor setups can have
// negative coords, but never this negative.
if (x < -2000 || y < -2000)
return;
const int Tolerance = 2;
// On first observation with no saved position, record the current rect as
// baseline in memory without persisting. Only save once the window moves
// or resizes away from that baseline — that's user intent, not a transient.
if (!hasSaved)
// ── Restore: position only, once per client ──────────────────────────
// Until it is decided nothing is saved, so the saved spot can't be
// overwritten by AC's placement while the restore still waits for AC
// to reach the saved size.
if (!_windowPositionAppliedPids.Contains(process.Id))
{
if (!_baselineWindowRects.TryGetValue(process.Id, out var baseline))
if (saved is AcWindowPlacementRule.Placement sv)
{
_baselineWindowRects[process.Id] = (x, y, w, h);
return; // wait for the user to move/resize before saving
if (!AcWindowPlacementRule.IsCapturable(current))
return; // parked off-screen / still tiny: look again next tick
if (!_windowSizeSinceUtc.TryGetValue(process.Id, out var size) || size.w != current.Width || size.h != current.Height)
_windowSizeSinceUtc[process.Id] = size = (current.Width, current.Height, nowUtc);
AcWindowPlacementRule.RestoreDecision d = AcWindowPlacementRule.DecideRestore(
sv, current.Width, current.Height, nowUtc - size.since, nowUtc - loginSeenUtc, MonitorWorkAreas());
if (d.Action == AcWindowPlacementRule.RestoreAction.Wait)
return;
_windowPositionAppliedPids.Add(process.Id);
if (d.Action == AcWindowPlacementRule.RestoreAction.Move)
{
// SWP_NOSIZE: the size stays AC's own; it renders at its
// resolution, and a smaller window crops the game and the HUD.
SetWindowPos(hwnd, IntPtr.Zero, d.X, d.Y, 0, 0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS);
LauncherDiag.Info(d.Clamped
? $"WindowPos PID {process.Id} ({accountName}@{serverName}): restored position to ({d.X},{d.Y}), pulled onto the screen from ({sv.X},{sv.Y}); size left to AC ({current.Width}x{current.Height})."
: $"WindowPos PID {process.Id} ({accountName}@{serverName}): restored position to ({d.X},{d.Y}); size left to AC ({current.Width}x{current.Height}).");
return;
}
LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}@{serverName}): saved position ({sv.X},{sv.Y}) not restored ({d.Why}); left where AC put it.");
}
bool movedFromBaseline = Math.Abs(baseline.x - x) > Tolerance
|| Math.Abs(baseline.y - y) > Tolerance
|| Math.Abs(baseline.w - w) > Tolerance
|| Math.Abs(baseline.h - h) > Tolerance;
if (!movedFromBaseline)
return;
}
else
{
bool changed = Math.Abs(profile.WindowX!.Value - x) > Tolerance
|| Math.Abs(profile.WindowY!.Value - y) > Tolerance
|| Math.Abs(profile.WindowWidth!.Value - w) > Tolerance
|| Math.Abs(profile.WindowHeight!.Value - h) > Tolerance;
if (!changed)
return;
}
// ── Reject AC's character-select / login window ──────────────────────
// IsLoggedIn latches true for the whole acclient.exe process: it is set
// once at the first LoginComplete and is deliberately never flipped back
// at char-select (so the stuck-client reaper can't kill a healthy in-game
// client — see SessionStateRegistry). So when the player logs a character
// back out to character-select, AC shrinks its own window to the small
// login/char-select size while this method still sees loggedIn==true and
// would happily persist that tiny rect over the real in-game geometry.
// Next launch then restores the tiny size and the game is unplayable.
//
// AC's char-select/login window is *much* smaller than any window a player
// games in, so treat a capture that collapses the window below half the
// established in-game area as that transient window and skip it. Growth
// and moderate resizes (genuine user intent) still persist; a profile
// whose saved size was already corrupted small self-heals on the first
// resize back up to a real in-game size.
int refW = profile.WindowWidth ?? 0;
int refH = profile.WindowHeight ?? 0;
if ((refW <= 0 || refH <= 0) && _baselineWindowRects.TryGetValue(process.Id, out var refRect))
{
refW = refRect.w;
refH = refRect.h;
}
if (refW > 0 && refH > 0 && (long)w * h * 2L < (long)refW * refH)
{
// Shortly after our restore it is AC shrinking the window back while it brings the character in
// (AcWindowRestoreRule): put the saved window back instead of leaving the game drawn into a small one.
if (hasSaved && _windowRestores.TryGetValue(process.Id, out var rs)
&& AcWindowRestoreRule.ShouldReapply(DateTime.UtcNow, rs.At, rs.Last, rs.Count, sess?.LogoutAtUtc != null,
w, h, profile.WindowWidth!.Value, profile.WindowHeight!.Value))
else
{
SetWindowPos(hwnd, IntPtr.Zero, profile.WindowX!.Value, profile.WindowY!.Value,
profile.WindowWidth!.Value, profile.WindowHeight!.Value,
SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS);
_windowRestores[process.Id] = (rs.At, DateTime.UtcNow, rs.Count + 1);
LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}@{serverName}): AC shrank it to {w}x{h} after the restore: put back to ({profile.WindowX},{profile.WindowY},{profile.WindowWidth}x{profile.WindowHeight}) (#{rs.Count + 1}).");
return;
// No saved position — nothing to put back. The first capturable
// rect becomes the baseline below; only a move away from it
// (the player's) is ever saved.
_windowPositionAppliedPids.Add(process.Id);
}
LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}@{serverName}): ignored char-select/login shrink ({w}x{h}, <50% of in-game {refW}x{refH}).");
}
// ── Save: only a rect that held for StableFor ────────────────────────
if (saved is null && AcWindowPlacementRule.IsCapturable(current) && !_baselineWindowRects.ContainsKey(process.Id))
{
_baselineWindowRects[process.Id] = (current.X, current.Y, current.Width, current.Height);
return;
}
AcWindowPlacementRule.Placement? reference = saved
?? (_baselineWindowRects.TryGetValue(process.Id, out var b)
? new AcWindowPlacementRule.Placement(b.x, b.y, b.w, b.h)
: null);
_baselineWindowRects[process.Id] = (x, y, w, h);
profile.WindowX = x;
profile.WindowY = y;
profile.WindowWidth = w;
profile.WindowHeight = h;
SaveSettings();
LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}@{serverName}): saved ({x},{y},{w}x{h}).");
_windowSavePending.TryGetValue(process.Id, out AcWindowPlacementRule.Pending? pending);
AcWindowPlacementRule.SaveDecision save = AcWindowPlacementRule.DecideSave(current, reference, ref pending, nowUtc);
_windowSavePending[process.Id] = pending;
switch (save.Action)
{
case AcWindowPlacementRule.SaveAction.LoginShrink:
if (save.FirstSeen)
LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}@{serverName}): ignored char-select/login shrink ({current.Width}x{current.Height}, <50% of in-game {reference!.Value.Width}x{reference.Value.Height}).");
return;
case AcWindowPlacementRule.SaveAction.Save:
_baselineWindowRects[process.Id] = (current.X, current.Y, current.Width, current.Height);
profile.WindowX = current.X;
profile.WindowY = current.Y;
profile.WindowWidth = current.Width;
profile.WindowHeight = current.Height;
SaveSettings();
LauncherDiag.Info($"WindowPos PID {process.Id} ({accountName}@{serverName}): saved ({current.X},{current.Y},{current.Width}x{current.Height}), unchanged for {AcWindowPlacementRule.StableFor.TotalSeconds:0} s.");
return;
}
}
/// <summary>

View file

@ -58,7 +58,7 @@
<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\AcWindowRestoreRule.cs" Link="Shared\AcWindowRestoreRule.cs" />
<Compile Include="..\RynthCore.App\AcWindowPlacementRule.cs" Link="Shared\AcWindowPlacementRule.cs" />
<Compile Include="..\RynthCore.App\AcClientLaunchSettingsService.cs" Link="Shared\AcClientLaunchSettingsService.cs" />
<Compile Include="..\RynthCore.App\UserPrefsSwapRecovery.cs" Link="Shared\UserPrefsSwapRecovery.cs" />
<Compile Include="..\RynthCore.App\AcClientLoginAutomationService.cs" Link="Shared\AcClientLoginAutomationService.cs" />

View file

@ -0,0 +1,222 @@
using System;
using System.Collections.Generic;
namespace RynthCore.App;
/// <summary>
/// The launcher's per-account memory of where the AC window sits: what it puts back after the login,
/// and when it writes a new rect to the profile. Pure: MainWindow does the window calls. Checked in
/// tools\LauncherSettingsTests.
///
/// 2026-11-15, a #rynth-issues report, 2026-11-14 ("login changes resolution"): a few seconds after the
/// login the window shrank, half the picture was cut off and the HUD could not be clicked; a second
/// player saw it on mules but not on the main. The launcher had saved 1008x786 at (296,76) six seconds
/// before the client closed (AC's logout / character-select window, 52.6% of the 1608x936 in-game area,
/// so the old "under half" guard let it through), then put that size back on the next login. AC draws
/// at its own resolution whatever the window size, so the smaller window crops the game and leaves the
/// HUD outside the clickable area, and the resolution setting cannot be reached to fix it.
/// So:
/// - Only the position is ever put back. AC sizes its own window from its resolution setting (in the
/// per-account UserPreferences.ini the prefs swap brings in); the launcher never resizes it. This
/// replaces the 2026-10-27 put-back of a shrunk window (AcWindowRestoreRule), which resized it too.
/// - The saved position is used only when the window is about the size it was saved at: a position
/// saved for the small centred login window would put a full-size window half off the screen.
/// It waits for the size to hold (<see cref="RestoreSettle"/>) and, while AC is still at its login
/// size, for it to grow (<see cref="RestoreWatch"/>), then gives up.
/// - The position is pulled onto a monitor's work area at the window's real size.
/// - A new rect is saved only after it held for <see cref="StableFor"/>: the shrink right before
/// the client closes, and AC's own moves at startup and portal-in, never reach the profile.
/// The saved width and height are still written: they are what the size checks compare against.
/// </summary>
internal static class AcWindowPlacementRule
{
/// <summary>A window rect: outer position and size, as GetWindowRect reports it.</summary>
public readonly record struct Placement(int X, int Y, int Width, int Height);
/// <summary>A monitor's work area (the screen minus the taskbar).</summary>
public readonly record struct WorkArea(int Left, int Top, int Right, int Bottom)
{
public int Width => Right - Left;
public int Height => Bottom - Top;
}
/// <summary>
/// How long a new rect must hold before it is saved. AC's own moves (startup, the login window,
/// portal-in) settle within a few seconds; the report's shrink came 6 s before the client closed.
/// 30 s clears both with room, and the cost is small: a window moved and closed within 30 s keeps
/// its old spot.
/// </summary>
public static readonly TimeSpan StableFor = TimeSpan.FromSeconds(30);
/// <summary>How long after the login the restore waits for AC to reach the saved size.</summary>
public static readonly TimeSpan RestoreWatch = TimeSpan.FromSeconds(60);
/// <summary>
/// How long the window's size must hold before the restore is decided: AC may still be growing its
/// window from the login size to its resolution when the login is reported, and a position judged
/// (and pulled onto the screen) at the passing size is wrong for the final one. Two 2 s launcher ticks.
/// </summary>
public static readonly TimeSpan RestoreSettle = TimeSpan.FromSeconds(4);
/// <summary>Pixels of change ignored (DWM frame fudge).</summary>
public const int Tolerance = 2;
/// <summary>
/// How far the outer rect may hang past the work area. Windows 10/11 frames have invisible resize
/// borders (about 7 px at 100% scaling) outside the visible edge, so a window snapped to the screen
/// edge reports (-7, 0); the report's own saves were (-4,1). Within this the spot is left alone.
/// </summary>
public const int EdgeSlack = 16;
/// <summary>The saved size and the window's are this close (each side within a quarter) for the saved position to apply.</summary>
public static bool SizeMatches(int width, int height, int savedWidth, int savedHeight) =>
savedWidth > 0 && savedHeight > 0 && width > 0 && height > 0
&& Math.Abs(width - savedWidth) * 4L <= Math.Max(width, savedWidth)
&& Math.Abs(height - savedHeight) * 4L <= Math.Max(height, savedHeight);
/// <summary>The window collapsed below half the reference in-game area: AC's login / character-select window.</summary>
public static bool IsLoginShrink(int width, int height, int refWidth, int refHeight) =>
refWidth > 0 && refHeight > 0 && (long)width * height * 2L < (long)refWidth * refHeight;
/// <summary>
/// A rect worth looking at: big enough to be the game window, and not AC's startup parking spot at
/// (-10000,-10000) (multi-monitor setups have negative coordinates, never this negative).
/// </summary>
public static bool IsCapturable(Placement p) => p.Width >= 200 && p.Height >= 200 && p.X >= -2000 && p.Y >= -2000;
public static bool Near(Placement a, Placement b) =>
Math.Abs(a.X - b.X) <= Tolerance && Math.Abs(a.Y - b.Y) <= Tolerance
&& Math.Abs(a.Width - b.Width) <= Tolerance && Math.Abs(a.Height - b.Height) <= Tolerance;
// ── Restore ───────────────────────────────────────────────────────────
public enum RestoreAction
{
/// <summary>AC is not at the saved size yet: look again next tick.</summary>
Wait,
/// <summary>Move the window to (X, Y), size untouched.</summary>
Move,
/// <summary>Leave the window where AC put it; the restore is over.</summary>
Skip,
}
public readonly record struct RestoreDecision(RestoreAction Action, int X, int Y, bool Clamped, string Why);
/// <summary>
/// What to do with the saved position, given the window's current size, how long that size has
/// held, the time since the login was first seen, and the monitors' work areas.
/// </summary>
public static RestoreDecision DecideRestore(Placement saved, int width, int height, TimeSpan sizeHeldFor,
TimeSpan sinceLogin, IReadOnlyList<WorkArea> workAreas)
{
if (sizeHeldFor < RestoreSettle && sinceLogin <= RestoreWatch)
return new RestoreDecision(RestoreAction.Wait, 0, 0, false, "window size still changing");
if (!SizeMatches(width, height, saved.Width, saved.Height))
{
return sinceLogin <= RestoreWatch
? new RestoreDecision(RestoreAction.Wait, 0, 0, false, "window not at the saved size yet")
: new RestoreDecision(RestoreAction.Skip, 0, 0, false,
$"window is {width}x{height}, the position was saved for {saved.Width}x{saved.Height}");
}
if (workAreas.Count == 0)
return new RestoreDecision(RestoreAction.Skip, 0, 0, false, "no monitor information");
(int x, int y) = ClampToWorkArea(saved.X, saved.Y, width, height, workAreas);
bool clamped = x != saved.X || y != saved.Y;
return new RestoreDecision(RestoreAction.Move, x, y, clamped, clamped ? "pulled onto the screen" : "saved position");
}
/// <summary>
/// The position nearest (x, y) at which a width x height window lies on a work area (give or take
/// <see cref="EdgeSlack"/>): the area it overlaps most, else the nearest one. A window wider or taller
/// than the area goes to its left / top edge, so the title bar stays reachable.
/// </summary>
public static (int X, int Y) ClampToWorkArea(int x, int y, int width, int height, IReadOnlyList<WorkArea> workAreas)
{
if (workAreas.Count == 0) return (x, y);
WorkArea a = PickArea(x, y, width, height, workAreas);
return (ClampAxis(x, width, a.Left, a.Right), ClampAxis(y, height, a.Top, a.Bottom));
}
private static int ClampAxis(int pos, int size, int lo, int hi)
{
int min = lo - EdgeSlack;
int max = hi - size + EdgeSlack;
if (max < min) return lo; // bigger than the area: pin the leading edge
return Math.Clamp(pos, min, max);
}
private static WorkArea PickArea(int x, int y, int width, int height, IReadOnlyList<WorkArea> areas)
{
WorkArea best = areas[0];
long bestOverlap = -1;
foreach (WorkArea a in areas)
{
long ow = Math.Min(x + width, a.Right) - Math.Max(x, a.Left);
long oh = Math.Min(y + height, a.Bottom) - Math.Max(y, a.Top);
long overlap = ow > 0 && oh > 0 ? ow * oh : 0;
if (overlap > bestOverlap) { bestOverlap = overlap; best = a; }
}
if (bestOverlap > 0) return best;
// Entirely off every monitor: the area nearest the window's centre.
long cx = x + width / 2, cy = y + height / 2;
long bestDist = long.MaxValue;
foreach (WorkArea a in areas)
{
long dx = cx < a.Left ? a.Left - cx : cx > a.Right ? cx - a.Right : 0;
long dy = cy < a.Top ? a.Top - cy : cy > a.Bottom ? cy - a.Bottom : 0;
long d = dx * dx + dy * dy;
if (d < bestDist) { bestDist = d; best = a; }
}
return best;
}
// ── Save ──────────────────────────────────────────────────────────────
/// <summary>A rect that differs from the saved one, and since when it has held.</summary>
public sealed record Pending(Placement Rect, DateTime SinceUtc);
public enum SaveAction
{
/// <summary>Nothing new: not capturable, or the same as the reference.</summary>
None,
/// <summary>A new rect, not held for <see cref="StableFor"/> yet.</summary>
Waiting,
/// <summary>AC's login / character-select window: never saved.</summary>
LoginShrink,
/// <summary>Held long enough: write it to the profile.</summary>
Save,
}
/// <param name="FirstSeen">The rect just changed (for logging once instead of every tick).</param>
public readonly record struct SaveDecision(SaveAction Action, bool FirstSeen);
/// <summary>
/// One tick of the save tracker. <paramref name="reference"/> is the saved rect, else the first rect
/// seen after the login (so AC's own placement is never saved until the player moves the window).
/// <paramref name="pending"/> is the tracker's state, kept per client by the caller.
/// </summary>
public static SaveDecision DecideSave(Placement current, Placement? reference, ref Pending? pending, DateTime nowUtc)
{
if (!IsCapturable(current))
return new SaveDecision(SaveAction.None, false);
if (reference is Placement r && Near(current, r))
{
pending = null; // back where it was: a shrink that came and went is forgotten
return new SaveDecision(SaveAction.None, false);
}
bool firstSeen = pending is null || !Near(pending.Rect, current);
if (firstSeen)
pending = new Pending(current, nowUtc);
if (reference is Placement rr && IsLoginShrink(current.Width, current.Height, rr.Width, rr.Height))
return new SaveDecision(SaveAction.LoginShrink, firstSeen);
if (nowUtc - pending!.SinceUtc < StableFor)
return new SaveDecision(SaveAction.Waiting, firstSeen);
pending = null;
return new SaveDecision(SaveAction.Save, firstSeen);
}
}

View file

@ -1,41 +0,0 @@
using System;
namespace RynthCore.App;
/// <summary>
/// The launcher puts a client's saved window back once, when AC reports the login. AC can still shrink
/// its window to the small login / character-select size afterwards, while it brings the character in,
/// and then draw the game at full size into that small window. Drakkon (2026-10-25 23:04): restored to
/// 1606x929 three seconds after the login, back at 806x629 three seconds later, and left there all
/// night while the game drew 1600x900 into it; the tracker only refused to save that size. For a
/// short while after the restore, a window that collapsed below half the saved area is put back, a few
/// times at most, and never once the client has logged out (that is the real character select).
/// Pure: MainWindow does the window calls. Checked in tools\LauncherSettingsTests.
/// </summary>
internal static class AcWindowRestoreRule
{
/// <summary>How long after the restore a login-size window is put back.</summary>
public static readonly TimeSpan Watch = TimeSpan.FromSeconds(60);
/// <summary>The most times it is put back after one restore.</summary>
public const int MaxReapplies = 5;
/// <summary>The least time between two put-backs (AC may still be resizing).</summary>
public static readonly TimeSpan ReapplyEvery = TimeSpan.FromSeconds(3);
/// <summary>The window collapsed below half the saved in-game area: AC's login / character-select window.</summary>
public static bool IsLoginShrink(int width, int height, int savedWidth, int savedHeight) =>
savedWidth > 0 && savedHeight > 0 && (long)width * height * 2L < (long)savedWidth * savedHeight;
/// <summary>
/// Put the saved window back now: a login-size window within <see cref="Watch"/> of the restore,
/// not logged out, fewer than <see cref="MaxReapplies"/> put-backs, the last one at least
/// <see cref="ReapplyEvery"/> ago.
/// </summary>
public static bool ShouldReapply(DateTime nowUtc, DateTime restoredAtUtc, DateTime? lastReapplyUtc, int reapplies,
bool loggedOut, int width, int height, int savedWidth, int savedHeight)
{
if (loggedOut || reapplies >= MaxReapplies) return false;
if (nowUtc - restoredAtUtc > Watch) return false;
if (lastReapplyUtc is DateTime last && nowUtc - last < ReapplyEvery) return false;
return IsLoginShrink(width, height, savedWidth, savedHeight);
}
}