Private/UI/Initialize-EwWorkbenchMaximizeWorkArea.ps1

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

function Initialize-EwWorkbenchMaximizeWorkArea {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [System.Windows.Window]$Window
    )

    $chrome = [System.Windows.Shell.WindowChrome]::GetWindowChrome($Window)
    if ($null -eq $chrome) {
        throw 'Maximized work-area handling requires WindowChrome.'
    }

    if (-not ('EvergreenUI.WorkbenchMaximizeInterop' -as [type])) {
        Add-Type -TypeDefinition @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
 
namespace EvergreenUI {
    public static class WorkbenchMaximizeInterop {
        [StructLayout(LayoutKind.Sequential)]
        private struct NativePoint {
            public int X;
            public int Y;
        }
 
        [StructLayout(LayoutKind.Sequential)]
        private struct NativeRect {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
 
        [StructLayout(LayoutKind.Sequential)]
        private struct MonitorInfo {
            public int Size;
            public NativeRect Monitor;
            public NativeRect Work;
            public uint Flags;
        }
 
        [StructLayout(LayoutKind.Sequential)]
        private struct MinMaxInfo {
            public NativePoint Reserved;
            public NativePoint MaxSize;
            public NativePoint MaxPosition;
            public NativePoint MinTrackSize;
            public NativePoint MaxTrackSize;
        }
 
        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint flags);
 
        [DllImport("user32.dll", EntryPoint = "GetMonitorInfoW", SetLastError = true)]
        private static extern bool GetMonitorInfo(IntPtr monitor, ref MonitorInfo info);
 
        public static int[] GetMonitorWorkArea(IntPtr hwnd) {
            IntPtr monitor = MonitorFromWindow(hwnd, 2);
            if (monitor == IntPtr.Zero) {
                int error = Marshal.GetLastWin32Error();
                throw new Win32Exception(error == 0 ? 1 : error);
            }
 
            var info = new MonitorInfo { Size = Marshal.SizeOf<MonitorInfo>() };
            if (!GetMonitorInfo(monitor, ref info)) {
                int error = Marshal.GetLastWin32Error();
                throw new Win32Exception(error == 0 ? 1 : error);
            }
 
            return new[] { info.Work.Left, info.Work.Top, info.Work.Right, info.Work.Bottom };
        }
 
        public static int SetMaximizedBounds(IntPtr hwnd, IntPtr minMaxInfoPointer) {
            IntPtr monitor = MonitorFromWindow(hwnd, 2);
            if (monitor == IntPtr.Zero) {
                int error = Marshal.GetLastWin32Error();
                return error == 0 ? 1 : error;
            }
 
            var monitorInfo = new MonitorInfo { Size = Marshal.SizeOf<MonitorInfo>() };
            if (!GetMonitorInfo(monitor, ref monitorInfo)) {
                int error = Marshal.GetLastWin32Error();
                return error == 0 ? 1 : error;
            }
 
            var minMaxInfo = (MinMaxInfo)Marshal.PtrToStructure(
                minMaxInfoPointer, typeof(MinMaxInfo)
            );
            minMaxInfo.MaxPosition.X = monitorInfo.Work.Left - monitorInfo.Monitor.Left;
            minMaxInfo.MaxPosition.Y = monitorInfo.Work.Top - monitorInfo.Monitor.Top;
            minMaxInfo.MaxSize.X = monitorInfo.Work.Right - monitorInfo.Work.Left;
            // Avoid WindowChrome's one-pixel frame overflow when max size equals the work area.
            minMaxInfo.MaxSize.Y = Math.Max(
                1, monitorInfo.Work.Bottom - monitorInfo.Work.Top - 1
            );
            minMaxInfo.MinTrackSize.X = Math.Min(
                minMaxInfo.MinTrackSize.X, minMaxInfo.MaxSize.X
            );
            minMaxInfo.MinTrackSize.Y = Math.Min(
                minMaxInfo.MinTrackSize.Y, minMaxInfo.MaxSize.Y
            );
            Marshal.StructureToPtr(minMaxInfo, minMaxInfoPointer, false);
            return 0;
        }
    }
}
'@
 -ErrorAction Stop
    }

    $state = @{
        Source                  = $null
        Hook                    = $null
        MaximizeRequested       = $Window.WindowState -eq [System.Windows.WindowState]::Maximized
        IsUpdatingMinimums      = $false
        MinimumsAreClamped      = $false
        OriginalMinWidth        = $Window.MinWidth
        OriginalMinHeight       = $Window.MinHeight
        WarningLogged           = $false
        SourceInitializedHandler = $null
        StateChangedHandler     = $null
        ClosedHandler           = $null
    }

    $setMaximizedMinimums = {
        param([IntPtr]$Handle)

        if ($state.IsUpdatingMinimums) {
            return
        }

        $workArea = [EvergreenUI.WorkbenchMaximizeInterop]::GetMonitorWorkArea($Handle)
        $source = [System.Windows.Interop.HwndSource]::FromHwnd($Handle)
        if ($null -eq $source -or $null -eq $source.CompositionTarget) {
            throw 'The maximized Workbench window has no WPF composition target.'
        }

        $workAreaSize = $source.CompositionTarget.TransformFromDevice.Transform(
            [System.Windows.Point]::new(
                [Math]::Max(1, $workArea[2] - $workArea[0] - 1),
                [Math]::Max(1, $workArea[3] - $workArea[1] - 1)
            )
        )

        if (-not $state.MinimumsAreClamped) {
            $state.OriginalMinWidth = $Window.MinWidth
            $state.OriginalMinHeight = $Window.MinHeight
            $state.MinimumsAreClamped = $true
        }

        $state.IsUpdatingMinimums = $true
        try {
            $Window.MinWidth = [Math]::Min($state.OriginalMinWidth, $workAreaSize.X)
            $Window.MinHeight = [Math]::Min($state.OriginalMinHeight, $workAreaSize.Y)
        }
        finally {
            $state.IsUpdatingMinimums = $false
        }
    }.GetNewClosure()

    $restoreMinimums = {
        if (-not $state.MinimumsAreClamped -or $state.IsUpdatingMinimums) {
            return
        }

        $state.IsUpdatingMinimums = $true
        try {
            $Window.MinWidth = $state.OriginalMinWidth
            $Window.MinHeight = $state.OriginalMinHeight
            $state.MinimumsAreClamped = $false
        }
        finally {
            $state.IsUpdatingMinimums = $false
        }
    }.GetNewClosure()

    $state.Hook = [System.Windows.Interop.HwndSourceHook]{
        param($handle, $message, $wParam, $lParam, [ref]$handled)

        try {
            if ($message -eq 0x112) {
                $systemCommand = $wParam.ToInt64() -band 0xFFF0
                if ($systemCommand -eq 0xF030) {
                    $state.MaximizeRequested = $true
                    & $setMaximizedMinimums -Handle $handle
                }
                elseif ($systemCommand -eq 0xF020 -or $systemCommand -eq 0xF120) {
                    $state.MaximizeRequested = $false
                }
            }
            elseif ($message -eq 0x24 -and
                ($state.MaximizeRequested -or $Window.WindowState -eq [System.Windows.WindowState]::Maximized)) {
                & $setMaximizedMinimums -Handle $handle
                $result = [EvergreenUI.WorkbenchMaximizeInterop]::SetMaximizedBounds($handle, $lParam)
                if ($result -eq 0) {
                    $handled.Value = $true
                }
                elseif (-not $state.WarningLogged) {
                    $state.WarningLogged = $true
                    Write-Warning -Message (
                        "EvergreenUI: Could not apply the monitor work area to the maximized Workbench window (Win32 error $result)."
                    )
                }
            }
        }
        catch {
            if (-not $state.WarningLogged) {
                $state.WarningLogged = $true
                Write-Warning -Message (
                    "EvergreenUI: Could not constrain the maximized Workbench window to its monitor work area: $($_.Exception.Message)"
                )
            }
        }

        return [IntPtr]::Zero
    }.GetNewClosure()

    $state.SourceInitializedHandler = {
        $handle = [System.Windows.Interop.WindowInteropHelper]::new($Window).Handle
        $state.Source = [System.Windows.Interop.HwndSource]::FromHwnd($handle)
        if ($null -eq $state.Source) {
            Write-Warning -Message 'EvergreenUI: Could not attach monitor work-area handling to the Workbench window.'
            return
        }

        $state.Source.AddHook($state.Hook)
        if ($Window.WindowState -eq [System.Windows.WindowState]::Maximized) {
            $state.MaximizeRequested = $true
            try {
                & $setMaximizedMinimums -Handle $handle
            }
            catch {
                Write-Warning -Message (
                    "EvergreenUI: Could not prepare the maximized Workbench window for its monitor work area: $($_.Exception.Message)"
                )
            }
        }
    }.GetNewClosure()

    $state.StateChangedHandler = {
        if ($Window.WindowState -eq [System.Windows.WindowState]::Maximized) {
            $state.MaximizeRequested = $true
            $handle = [System.Windows.Interop.WindowInteropHelper]::new($Window).Handle
            if ($handle -ne [IntPtr]::Zero) {
                try {
                    & $setMaximizedMinimums -Handle $handle
                }
                catch {
                    Write-Warning -Message (
                        "EvergreenUI: Could not prepare the maximized Workbench window for its monitor work area: $($_.Exception.Message)"
                    )
                }
            }
        }
        else {
            $state.MaximizeRequested = $false
            & $restoreMinimums
        }
    }.GetNewClosure()

    $state.ClosedHandler = {
        if ($null -ne $state.Source -and $null -ne $state.Hook) {
            $state.Source.RemoveHook($state.Hook)
        }
        $Window.Remove_SourceInitialized($state.SourceInitializedHandler)
        $Window.Remove_StateChanged($state.StateChangedHandler)
        $Window.Remove_Closed($state.ClosedHandler)
    }.GetNewClosure()

    $Window.Add_SourceInitialized($state.SourceInitializedHandler)
    $Window.Add_StateChanged($state.StateChangedHandler)
    $Window.Add_Closed($state.ClosedHandler)
}