From 9ce117c1d5337db3ab7a465c9b121c18982844a2 Mon Sep 17 00:00:00 2001 From: Brian Pham Date: Wed, 10 Jun 2026 11:49:56 -0700 Subject: [PATCH] osx: keep window construction resilient when no screen contains it When locating the screen that sizes a new window, fall back to a default size if AppKit reports no screens -- or none whose bounds contain the last-known position -- during a display reconfiguration. The window is repositioned on the next ScreenChanged event once the display server settles. See #18895. Co-authored-by: Cursor --- src/Avalonia.Native/WindowImplBase.cs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/Avalonia.Native/WindowImplBase.cs b/src/Avalonia.Native/WindowImplBase.cs index 852317a793..eab3a2e3f9 100644 --- a/src/Avalonia.Native/WindowImplBase.cs +++ b/src/Avalonia.Native/WindowImplBase.cs @@ -51,11 +51,30 @@ namespace Avalonia.Native base.Init(handle); + int defaultWidth = 0, defaultHeight = 0; + + // AppKit can transiently report [NSScreen screens] as empty -- or report screens + // whose bounds don't contain the last-known window position -- during a CGS + // demote/promote race after wake-from-sleep, headless boots, or Spaces + // transitions. FirstOrDefault keeps window construction resilient through that + // window: the window falls back to a default size and is repositioned on the next + // ScreenChanged event once the display server settles, mirroring X11Window. + // See https://github.com/AvaloniaUI/Avalonia/issues/18895 var monitor = this.TryGetFeature()!.AllScreens .OrderBy(x => x.Scaling) - .First(m => m.Bounds.Contains(Position)); + .FirstOrDefault(m => m.Bounds.Contains(Position)); - Resize(new Size(monitor.WorkingArea.Width * 0.75d, monitor.WorkingArea.Height * 0.7d), WindowResizeReason.Layout); + if (monitor != null) + { + // Emulate Windows 7+ default window size behavior. + defaultWidth = (int)(monitor.WorkingArea.Width * 0.75d); + defaultHeight = (int)(monitor.WorkingArea.Height * 0.7d); + } + + defaultWidth = Math.Max(defaultWidth, 300); + defaultHeight = Math.Max(defaultHeight, 200); + + Resize(new Size(defaultWidth, defaultHeight), WindowResizeReason.Layout); } public void Activate()