Private/UI/Initialize-EwWorkbenchCaptionButtonCutout.ps1

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

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

    $root = $Window.FindName('WorkbenchRoot')
    if ($root -isnot [System.Windows.Controls.Grid]) {
        throw 'Caption-button handling requires the Workbench root grid.'
    }
    if ($null -eq [System.Windows.Shell.WindowChrome]::GetWindowChrome($Window)) {
        throw 'Caption-button handling requires WindowChrome.'
    }

    if (-not ('EvergreenUI.WorkbenchCaptionCutoutInterop' -as [type])) {
        Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
 
namespace EvergreenUI {
    public static class WorkbenchCaptionCutoutInterop {
        [StructLayout(LayoutKind.Sequential)]
        private struct NativeRect {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
 
        [DllImport("dwmapi.dll")]
        private static extern int DwmGetWindowAttribute(
            IntPtr hwnd, int attribute, out NativeRect value, int size
        );
 
        public static int[] GetCaptionButtonBounds(IntPtr hwnd) {
            var result = DwmGetWindowAttribute(
                hwnd, 5, out NativeRect bounds, Marshal.SizeOf<NativeRect>()
            );
            if (result != 0) {
                Marshal.ThrowExceptionForHR(result);
            }
 
            return new[] { bounds.Left, bounds.Top, bounds.Right, bounds.Bottom };
        }
    }
}
'@
 -ErrorAction Stop
    }

    $state = @{
        Source                    = $null
        Hook                      = $null
        Pending                   = $false
        Closed                    = $false
        WarningLogged             = $false
        SourceInitializedHandler  = $null
        LoadedHandler             = $null
        ContentRenderedHandler    = $null
        SizeChangedHandler        = $null
        StateChangedHandler       = $null
        ClosedHandler             = $null
    }

    $updateCaptionCutout = {
        if ($state.Closed -or $root.ActualWidth -le 0 -or $root.ActualHeight -le 0) {
            return
        }

        $handle = [System.Windows.Interop.WindowInteropHelper]::new($Window).Handle
        if ($handle -eq [IntPtr]::Zero) {
            return
        }

        try {
            $bounds = [EvergreenUI.WorkbenchCaptionCutoutInterop]::GetCaptionButtonBounds($handle)
            if ($bounds[2] -le $bounds[0] -or $bounds[3] -le $bounds[1]) {
                $root.Clip = $null
                return
            }

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

            $transform = $source.CompositionTarget.TransformFromDevice
            $topLeft = $transform.Transform(
                [System.Windows.Point]::new($bounds[0], $bounds[1])
            )
            $bottomRight = $transform.Transform(
                [System.Windows.Point]::new($bounds[2], $bounds[3])
            )
            $buttonRect = [System.Windows.Rect]::new($topLeft, $bottomRight)
            $rootRect = [System.Windows.Rect]::new(0, 0, $root.ActualWidth, $root.ActualHeight)
            if (-not $rootRect.IntersectsWith($buttonRect)) {
                $root.Clip = $null
                return
            }

            $root.Clip = [System.Windows.Media.CombinedGeometry]::new(
                [System.Windows.Media.GeometryCombineMode]::Exclude,
                [System.Windows.Media.RectangleGeometry]::new($rootRect),
                [System.Windows.Media.RectangleGeometry]::new($buttonRect)
            )
        }
        catch {
            $root.Clip = $null
            if (-not $state.WarningLogged) {
                $state.WarningLogged = $true
                Write-Warning -Message (
                    "EvergreenUI: Could not preserve the native caption buttons: $($_.Exception.Message)"
                )
            }
        }
    }.GetNewClosure()

    $applyCaptionCutout = [action]{
        $state.Pending = $false
        & $updateCaptionCutout
    }.GetNewClosure()

    $queueCaptionCutoutUpdate = {
        if ($state.Closed -or $state.Pending -or $Window.Dispatcher.HasShutdownStarted) {
            return
        }

        $state.Pending = $true
        $null = $Window.Dispatcher.InvokeAsync($applyCaptionCutout, [System.Windows.Threading.DispatcherPriority]::Normal)
    }.GetNewClosure()

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

        $null = $handle, $wParam, $lParam, $handled
        if ($message -in 0x0005, 0x0047, 0x02E0, 0x031A, 0x031E, 0x031F, 0x0320) {
            & $queueCaptionCutoutUpdate
        }

        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) {
            if (-not $state.WarningLogged) {
                $state.WarningLogged = $true
                Write-Warning -Message 'EvergreenUI: Could not attach native caption-button handling to the Workbench window.'
            }
            return
        }

        $state.Source.AddHook($state.Hook)
        & $queueCaptionCutoutUpdate
    }.GetNewClosure()

    $state.LoadedHandler = { & $queueCaptionCutoutUpdate }.GetNewClosure()
    $state.ContentRenderedHandler = { & $updateCaptionCutout }.GetNewClosure()
    $state.SizeChangedHandler = { & $updateCaptionCutout }.GetNewClosure()
    $state.StateChangedHandler = { & $queueCaptionCutoutUpdate }.GetNewClosure()
    $state.ClosedHandler = {
        $state.Closed = $true
        if ($null -ne $state.Source -and $null -ne $state.Hook) {
            $state.Source.RemoveHook($state.Hook)
        }
        $Window.Remove_SourceInitialized($state.SourceInitializedHandler)
        $Window.Remove_Loaded($state.LoadedHandler)
        $Window.Remove_ContentRendered($state.ContentRenderedHandler)
        $root.Remove_SizeChanged($state.SizeChangedHandler)
        $Window.Remove_StateChanged($state.StateChangedHandler)
        $Window.Remove_Closed($state.ClosedHandler)
    }.GetNewClosure()

    $Window.Add_SourceInitialized($state.SourceInitializedHandler)
    $Window.Add_Loaded($state.LoadedHandler)
    $Window.Add_ContentRendered($state.ContentRenderedHandler)
    $root.Add_SizeChanged($state.SizeChangedHandler)
    $Window.Add_StateChanged($state.StateChangedHandler)
    $Window.Add_Closed($state.ClosedHandler)
}