diff --git a/App.xaml.cs b/App.xaml.cs index 6106873..4012be9 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -267,6 +267,7 @@ namespace ThreadPilot mainWindow.Show(); if (mainWindow.WindowState != WindowState.Minimized) { + mainWindow.EnsureDashboardVisibleOnScreen(); mainWindow.Activate(); } } diff --git a/Helpers/WindowPlacementHelper.cs b/Helpers/WindowPlacementHelper.cs new file mode 100644 index 0000000..175ea49 --- /dev/null +++ b/Helpers/WindowPlacementHelper.cs @@ -0,0 +1,295 @@ +namespace ThreadPilot.Helpers +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Windows; + using System.Windows.Forms; + using System.Windows.Media; + using DrawingRectangle = System.Drawing.Rectangle; + using WpfPoint = System.Windows.Point; + + public readonly record struct WindowBounds(double Left, double Top, double Width, double Height) + { + public double Right => this.Left + this.Width; + + public double Bottom => this.Top + this.Height; + + public double Area => Math.Max(0, this.Width) * Math.Max(0, this.Height); + } + + public readonly record struct MonitorWorkingArea(double Left, double Top, double Width, double Height, bool IsPrimary) + { + public double Right => this.Left + this.Width; + + public double Bottom => this.Top + this.Height; + + public double Area => Math.Max(0, this.Width) * Math.Max(0, this.Height); + } + + public readonly record struct WindowPlacementCorrection(WindowBounds Bounds, bool WasCorrected); + + public static class WindowPlacementHelper + { + private const double DefaultWindowWidth = 1280; + private const double DefaultWindowHeight = 864; + private const double MinimumVisibleAreaRatio = 0.25; + private const double Epsilon = 0.001; + + public static WindowPlacementCorrection CorrectWindowBounds( + WindowBounds currentBounds, + IReadOnlyCollection workingAreas) + { + var validWorkingAreas = workingAreas + .Where(IsValidWorkingArea) + .ToArray(); + + if (validWorkingAreas.Length == 0) + { + var fallbackBounds = new WindowBounds( + IsFinite(currentBounds.Left) ? currentBounds.Left : 0, + IsFinite(currentBounds.Top) ? currentBounds.Top : 0, + ResolveDimension(currentBounds.Width, DefaultWindowWidth), + ResolveDimension(currentBounds.Height, DefaultWindowHeight)); + + return new WindowPlacementCorrection(fallbackBounds, !BoundsAreEquivalent(currentBounds, fallbackBounds)); + } + + var targetArea = SelectTargetWorkingArea(currentBounds, validWorkingAreas); + var correctedWidth = Math.Min(ResolveDimension(currentBounds.Width, DefaultWindowWidth), targetArea.Width); + var correctedHeight = Math.Min(ResolveDimension(currentBounds.Height, DefaultWindowHeight), targetArea.Height); + var sanitizedBounds = new WindowBounds( + currentBounds.Left, + currentBounds.Top, + correctedWidth, + correctedHeight); + + var hasSufficientIntersection = HasSufficientIntersection(sanitizedBounds, targetArea); + double correctedLeft; + double correctedTop; + + if (!hasSufficientIntersection || !IsFinite(sanitizedBounds.Left) || !IsFinite(sanitizedBounds.Top)) + { + correctedLeft = targetArea.Left + ((targetArea.Width - correctedWidth) / 2); + correctedTop = targetArea.Top + ((targetArea.Height - correctedHeight) / 2); + } + else + { + correctedLeft = Clamp(sanitizedBounds.Left, targetArea.Left, targetArea.Right - correctedWidth); + correctedTop = Clamp(sanitizedBounds.Top, targetArea.Top, targetArea.Bottom - correctedHeight); + } + + var correctedBounds = new WindowBounds( + Math.Round(correctedLeft), + Math.Round(correctedTop), + Math.Round(correctedWidth), + Math.Round(correctedHeight)); + + return new WindowPlacementCorrection(correctedBounds, !BoundsAreEquivalent(currentBounds, correctedBounds)); + } + + public static bool TryCorrectWindowPlacement(Window window) + { + ArgumentNullException.ThrowIfNull(window); + + try + { + if (window.WindowState == WindowState.Maximized) + { + return false; + } + + var workingAreas = GetWorkingAreasInWindowDips(window); + var currentBounds = new WindowBounds( + window.Left, + window.Top, + ResolveWindowDimension(window.ActualWidth, window.Width, DefaultWindowWidth), + ResolveWindowDimension(window.ActualHeight, window.Height, DefaultWindowHeight)); + + var correction = CorrectWindowBounds(currentBounds, workingAreas); + if (!correction.WasCorrected) + { + return false; + } + + window.Width = correction.Bounds.Width; + window.Height = correction.Bounds.Height; + window.Left = correction.Bounds.Left; + window.Top = correction.Bounds.Top; + return true; + } + catch + { + return false; + } + } + + private static MonitorWorkingArea[] GetWorkingAreasInWindowDips(Window window) + { + var transformFromDevice = GetTransformFromDevice(window); + var screens = Screen.AllScreens; + if (screens.Length == 0) + { + return new[] + { + new MonitorWorkingArea( + SystemParameters.WorkArea.Left, + SystemParameters.WorkArea.Top, + SystemParameters.WorkArea.Width, + SystemParameters.WorkArea.Height, + true), + }; + } + + return screens + .Select(screen => ConvertWorkingAreaToDips(screen.WorkingArea, screen.Primary, transformFromDevice)) + .Where(IsValidWorkingArea) + .ToArray(); + } + + private static Matrix GetTransformFromDevice(Window window) + { + try + { + var source = PresentationSource.FromVisual(window); + return source?.CompositionTarget?.TransformFromDevice ?? Matrix.Identity; + } + catch + { + return Matrix.Identity; + } + } + + private static MonitorWorkingArea ConvertWorkingAreaToDips( + DrawingRectangle workingArea, + bool isPrimary, + Matrix transformFromDevice) + { + var topLeft = transformFromDevice.Transform(new WpfPoint(workingArea.Left, workingArea.Top)); + var bottomRight = transformFromDevice.Transform(new WpfPoint(workingArea.Right, workingArea.Bottom)); + + return new MonitorWorkingArea( + topLeft.X, + topLeft.Y, + bottomRight.X - topLeft.X, + bottomRight.Y - topLeft.Y, + isPrimary); + } + + private static MonitorWorkingArea SelectTargetWorkingArea( + WindowBounds currentBounds, + IReadOnlyList workingAreas) + { + var bestIntersection = workingAreas + .Select(area => new + { + Area = area, + IntersectionArea = GetIntersectionArea(currentBounds, area), + }) + .OrderByDescending(candidate => candidate.IntersectionArea) + .ThenByDescending(candidate => candidate.Area.IsPrimary) + .First(); + + if (bestIntersection.IntersectionArea > 0 && HasSufficientIntersection(currentBounds, bestIntersection.Area)) + { + return bestIntersection.Area; + } + + if (!IsFinite(currentBounds.Left) || !IsFinite(currentBounds.Top)) + { + return workingAreas.FirstOrDefault(area => area.IsPrimary, workingAreas[0]); + } + + var centerX = currentBounds.Left + (ResolveDimension(currentBounds.Width, DefaultWindowWidth) / 2); + var centerY = currentBounds.Top + (ResolveDimension(currentBounds.Height, DefaultWindowHeight) / 2); + + return workingAreas + .OrderBy(area => GetSquaredDistanceToArea(centerX, centerY, area)) + .ThenByDescending(area => area.IsPrimary) + .First(); + } + + private static double GetSquaredDistanceToArea(double x, double y, MonitorWorkingArea area) + { + var nearestX = Clamp(x, area.Left, area.Right); + var nearestY = Clamp(y, area.Top, area.Bottom); + var deltaX = x - nearestX; + var deltaY = y - nearestY; + + return (deltaX * deltaX) + (deltaY * deltaY); + } + + private static bool HasSufficientIntersection(WindowBounds bounds, MonitorWorkingArea area) + { + var intersectionArea = GetIntersectionArea(bounds, area); + var boundedWindowArea = Math.Max(1, Math.Min(bounds.Width, area.Width) * Math.Min(bounds.Height, area.Height)); + + return intersectionArea / boundedWindowArea >= MinimumVisibleAreaRatio; + } + + private static double GetIntersectionArea(WindowBounds bounds, MonitorWorkingArea area) + { + if (!IsFinite(bounds.Left) || !IsFinite(bounds.Top) || !IsFinite(bounds.Width) || !IsFinite(bounds.Height)) + { + return 0; + } + + var left = Math.Max(bounds.Left, area.Left); + var top = Math.Max(bounds.Top, area.Top); + var right = Math.Min(bounds.Right, area.Right); + var bottom = Math.Min(bounds.Bottom, area.Bottom); + var width = Math.Max(0, right - left); + var height = Math.Max(0, bottom - top); + + return width * height; + } + + private static bool IsValidWorkingArea(MonitorWorkingArea workingArea) + { + return IsFinite(workingArea.Left) + && IsFinite(workingArea.Top) + && IsFinite(workingArea.Width) + && IsFinite(workingArea.Height) + && workingArea.Width > 0 + && workingArea.Height > 0; + } + + private static double ResolveWindowDimension(double actualValue, double configuredValue, double fallback) + { + if (IsFinite(actualValue) && actualValue > 0) + { + return actualValue; + } + + return ResolveDimension(configuredValue, fallback); + } + + private static double ResolveDimension(double value, double fallback) + { + return IsFinite(value) && value > 0 ? value : fallback; + } + + private static double Clamp(double value, double minimum, double maximum) + { + if (maximum < minimum) + { + return minimum; + } + + return Math.Min(Math.Max(value, minimum), maximum); + } + + private static bool IsFinite(double value) + { + return !double.IsNaN(value) && !double.IsInfinity(value); + } + + private static bool BoundsAreEquivalent(WindowBounds left, WindowBounds right) + { + return Math.Abs(left.Left - right.Left) < Epsilon + && Math.Abs(left.Top - right.Top) < Epsilon + && Math.Abs(left.Width - right.Width) < Epsilon + && Math.Abs(left.Height - right.Height) < Epsilon; + } + } +} diff --git a/MainWindow.Behaviors.partial.cs b/MainWindow.Behaviors.partial.cs index bcf8d1d..fec2c6a 100644 --- a/MainWindow.Behaviors.partial.cs +++ b/MainWindow.Behaviors.partial.cs @@ -1311,6 +1311,7 @@ namespace ThreadPilot else if (this.WindowState == WindowState.Normal || this.WindowState == WindowState.Maximized) { this.ShowInTaskbar = true; + this.EnsureDashboardVisibleOnScreen(); this.ApplyAppRefreshPolicy(this.GetForegroundActivityState()); } @@ -1413,6 +1414,8 @@ namespace ThreadPilot { System.Diagnostics.Debug.WriteLine($"Failed to apply window caption theme: {ex.Message}"); } + + this.EnsureDashboardVisibleOnScreen(); } [System.Diagnostics.Conditional("DEBUG")] @@ -1441,6 +1444,7 @@ namespace ThreadPilot private async Task OnWindowLoadedAsync() { this.Loaded -= this.OnWindowLoaded; + this.EnsureDashboardVisibleOnScreen(); await this.InitializeKeyboardShortcutsAsync(); } @@ -1452,18 +1456,30 @@ namespace ThreadPilot private void ShowWindowFromTray(string? tabTag = null) { this.ShowInTaskbar = true; - this.Visibility = Visibility.Visible; + this.EnsureDashboardVisibleOnScreen(); if (!this.IsVisible) { this.Show(); } + else + { + this.Visibility = Visibility.Visible; + } if (this.WindowState == WindowState.Minimized) { this.WindowState = WindowState.Normal; } + this.EnsureDashboardVisibleOnScreen(); + this.ShowInTaskbar = true; + + if (tabTag != null) + { + this.SelectMainTab(tabTag); + } + // Force foreground restoration when invoked from tray context menu. this.Topmost = true; this.Activate(); @@ -1479,11 +1495,11 @@ namespace ThreadPilot this.ApplyAppRefreshPolicy(processViewWillBeActive ? AppActivityState.ForegroundProcessView : AppActivityState.ForegroundOtherTab); + } - if (tabTag != null) - { - _ = this.Dispatcher.InvokeAsync(() => this.SelectMainTab(tabTag)); - } + internal bool EnsureDashboardVisibleOnScreen() + { + return WindowPlacementHelper.TryCorrectWindowPlacement(this); } private void SelectMainTab(string tag) @@ -1495,9 +1511,6 @@ namespace ThreadPilot this.ApplySectionVisibility(tag); - // Keep NavigationView internal state aligned when possible. - this.RootNavigation.Navigate(tag); - if (string.Equals(tag, "Performance", StringComparison.Ordinal)) { this.TryShowPerformanceIntro(); diff --git a/Tests/ThreadPilot.Core.Tests/WindowPlacementHelperTests.cs b/Tests/ThreadPilot.Core.Tests/WindowPlacementHelperTests.cs new file mode 100644 index 0000000..5abb3bc --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/WindowPlacementHelperTests.cs @@ -0,0 +1,86 @@ +namespace ThreadPilot.Core.Tests +{ + using ThreadPilot.Helpers; + + public sealed class WindowPlacementHelperTests + { + [Fact] + public void CorrectWindowBounds_WhenValuesAreInvalid_CentersDefaultSizeOnPrimaryWorkingArea() + { + var monitors = new[] + { + new MonitorWorkingArea(0, 0, 1024, 768, true), + }; + + var result = WindowPlacementHelper.CorrectWindowBounds( + new WindowBounds(double.NaN, double.NegativeInfinity, 0, double.PositiveInfinity), + monitors); + + Assert.True(result.WasCorrected); + Assert.Equal(0, result.Bounds.Left); + Assert.Equal(0, result.Bounds.Top); + Assert.Equal(1024, result.Bounds.Width); + Assert.Equal(768, result.Bounds.Height); + } + + [Fact] + public void CorrectWindowBounds_WhenMostlyOffScreen_CentersOnNearestWorkingArea() + { + var monitors = new[] + { + new MonitorWorkingArea(0, 0, 1920, 1040, true), + new MonitorWorkingArea(1920, 0, 1280, 984, false), + }; + + var result = WindowPlacementHelper.CorrectWindowBounds( + new WindowBounds(3100, -700, 900, 600), + monitors); + + Assert.True(result.WasCorrected); + Assert.Equal(2110, result.Bounds.Left); + Assert.Equal(192, result.Bounds.Top); + Assert.Equal(900, result.Bounds.Width); + Assert.Equal(600, result.Bounds.Height); + } + + [Fact] + public void CorrectWindowBounds_WhenPartiallyOutside_ClampsInsideIntersectingWorkingArea() + { + var monitors = new[] + { + new MonitorWorkingArea(-1080, 0, 1080, 1880, false), + new MonitorWorkingArea(0, 0, 2560, 1400, true), + }; + + var result = WindowPlacementHelper.CorrectWindowBounds( + new WindowBounds(-100, 120, 1280, 864), + monitors); + + Assert.True(result.WasCorrected); + Assert.Equal(0, result.Bounds.Left); + Assert.Equal(120, result.Bounds.Top); + Assert.Equal(1280, result.Bounds.Width); + Assert.Equal(864, result.Bounds.Height); + } + + [Fact] + public void CorrectWindowBounds_WhenAlreadyVisibleOnSecondaryMonitor_DoesNotMoveWindow() + { + var monitors = new[] + { + new MonitorWorkingArea(0, 0, 1920, 1040, true), + new MonitorWorkingArea(1920, 0, 1280, 984, false), + }; + + var result = WindowPlacementHelper.CorrectWindowBounds( + new WindowBounds(2000, 100, 900, 600), + monitors); + + Assert.False(result.WasCorrected); + Assert.Equal(2000, result.Bounds.Left); + Assert.Equal(100, result.Bounds.Top); + Assert.Equal(900, result.Bounds.Width); + Assert.Equal(600, result.Bounds.Height); + } + } +} diff --git a/ThreadPilot.csproj b/ThreadPilot.csproj index 0aa2a98..23459c2 100644 --- a/ThreadPilot.csproj +++ b/ThreadPilot.csproj @@ -16,10 +16,10 @@ link true CS1998;CS0067;CS0414;WFAC010;IL3000;MVVMTK0034 - 1.1.3 - 1.1.3.0 - 1.1.3.0 - 1.1.3 + 1.1.4 + 1.1.4.0 + 1.1.4.0 + 1.1.4