using System.Runtime.InteropServices;
using Agent.Screen;
using static Agent.Banner.NativeMethods;
namespace Agent.Banner;
///
/// The Being Viewed banner: a small always-on-top strip at the top centre of the
/// screen, one row per Remote View session ("Being Viewed by Ann · Control" and Stop).
/// Plain Win32: a topmost tool window that never activates (WS_EX_NOACTIVATE, every
/// SetWindowPos with SWP_NOACTIVATE, MA_NOACTIVATE on clicks), a STATIC per caption
/// (screen readers read it; clicks fall through to the window, which drags) and an
/// owner-drawn BUTTON per Stop (named for the session, invokable by assistive tech
/// and Space). It follows the DPI of its monitor (PerMonitorV2, WM_DPICHANGED), the
/// user's light or dark app theme and high contrast (WM_SETTINGCHANGE).
/// One per process, on the thread that runs .
///
internal sealed unsafe class BannerWindow
{
private const string ClassName = "ExecuteR.Banner";
private const string Title = "ExecuteR Remote View";
private const uint WM_APP_SHOW = WM_APP + 1;
private const uint WM_APP_END = WM_APP + 2;
private const int CaptionId = 100;
private const int ButtonId = 200;
private const int Rows = ScreenBannerProtocol.MaxItems;
private const double FontPoints = 9.75;
private const uint ICC_TAB_CLASSES = 0x0008;
private const uint ICC_STANDARD_CLASSES = 0x4000;
// The icon group csc writes for ApplicationIcon, which Native AOT copies into the exe.
private const int IconResource = 32512;
private static BannerWindow? current;
private readonly Action stop;
private readonly bool? forcedDark;
private readonly BannerRows rows = new();
private readonly Lock pending = new();
private readonly nint[] captions = new nint[Rows];
private readonly nint[] buttons = new nint[Rows];
private readonly bool[] hot = new bool[Rows];
private readonly bool[] pressed = new bool[Rows];
private readonly nint instance;
private readonly nint hand;
private IReadOnlyList? next;
private nint window;
private nint tooltip;
private nint icon;
private nint captionFont;
private nint buttonFont;
private nint backBrush;
private nint borderBrush;
private BannerLayout? layout;
private BannerPalette palette;
private int dpi = 96;
private bool dark;
private bool moved;
private BannerWindow(Action stop, bool? forcedDark)
{
this.stop = stop;
this.forcedDark = forcedDark;
instance = GetModuleHandleW(null);
hand = LoadCursorW(0, IDC_HAND);
}
///
/// Creates the (hidden) banner; runs on this thread when
/// Stop is pressed for a session. overrides the
/// theme (the Debug preview only).
///
public static BannerWindow Create(Action stop, bool? forcedDark = null)
{
var banner = new BannerWindow(stop, forcedDark);
current = banner;
banner.CreateWindows();
return banner;
}
/// Shows these sessions from any thread (hides on none); the latest call wins.
public void Post(IReadOnlyList items)
{
lock (pending)
{
next = items;
}
PostMessageW(window, WM_APP_SHOW, 0, 0);
}
/// Closes the banner from any thread; then returns.
public void PostEnd() => PostMessageW(window, WM_APP_END, 0, 0);
/// Shows these sessions (on the window's thread).
public void Show(IReadOnlyList items)
{
rows.Show(items);
Relayout();
}
/// Runs the message loop until the banner closes; the process's exit code.
public int Run()
{
MSG message;
while (GetMessageW(&message, 0, 0, 0) > 0)
{
if (!IsDialogMessageW(window, &message))
{
TranslateMessage(&message);
DispatchMessageW(&message);
}
}
DeleteResources();
return 0;
}
private void CreateWindows()
{
var init = new INITCOMMONCONTROLSEX { dwSize = (uint)sizeof(INITCOMMONCONTROLSEX), dwICC = ICC_STANDARD_CLASSES | ICC_TAB_CLASSES };
InitCommonControlsEx(&init);
fixed (char* name = ClassName)
{
var windowClass = new WNDCLASSEXW
{
cbSize = (uint)sizeof(WNDCLASSEXW),
style = CS_HREDRAW | CS_VREDRAW,
lpfnWndProc = &WindowProc,
hInstance = instance,
hCursor = LoadCursorW(0, IDC_ARROW),
lpszClassName = name,
};
if (RegisterClassExW(&windowClass) == 0)
{
throw new InvalidOperationException($"RegisterClassEx failed ({Marshal.GetLastPInvokeError()}).");
}
}
// Created on the primary monitor, where it is shown, so it starts at that DPI.
var work = PrimaryWorkArea();
window = CreateWindowExW(
WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, ClassName, Title, WS_POPUP | WS_CLIPCHILDREN,
work.Left, work.Top, 1, 1, 0, 0, instance, 0);
if (window == 0)
{
throw new InvalidOperationException($"CreateWindowEx failed ({Marshal.GetLastPInvokeError()}).");
}
dpi = (int)GetDpiForWindow(window);
tooltip = CreateWindowExW(
WS_EX_TOPMOST, "tooltips_class32", null, WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX,
0, 0, 0, 0, window, 0, instance, 0);
SendMessageW(tooltip, TTM_SETDELAYTIME, TTDT_INITIAL, 400);
for (var row = 0; row < Rows; row++)
{
captions[row] = CreateWindowExW(
0, "STATIC", null, WS_CHILD | SS_LEFTNOWORDWRAP | SS_NOPREFIX | SS_CENTERIMAGE,
0, 0, 0, 0, window, CaptionId + row, instance, 0);
buttons[row] = CreateWindowExW(
0, "BUTTON", null, WS_CHILD | WS_TABSTOP | BS_OWNERDRAW,
0, 0, 0, 0, window, ButtonId + row, instance, 0);
SetWindowSubclass(buttons[row], &ButtonProc, 1, (nuint)row);
}
ApplyTheme();
CreateResources();
}
/// Measures, sizes, places, and shows or hides the banner for the current rows.
private void Relayout()
{
var count = rows.Count;
var captionSizes = new TextSize[count];
var buttonSizes = new TextSize[count];
var dc = GetDC(window);
var old = SelectObject(dc, captionFont);
for (var row = 0; row < count; row++)
{
captionSizes[row] = Measure(dc, BannerRows.Caption(rows.Items[row]));
}
SelectObject(dc, buttonFont);
for (var row = 0; row < count; row++)
{
buttonSizes[row] = Measure(dc, BannerRows.StopText(rows.IsStopping(row)));
}
SelectObject(dc, old);
ReleaseDC(window, dc);
layout = BannerLayout.Compute(dpi, captionSizes, buttonSizes);
UpdateTools(clear: true);
for (var row = 0; row < Rows; row++)
{
if (row >= count)
{
ShowWindow(captions[row], SW_HIDE);
ShowWindow(buttons[row], SW_HIDE);
continue;
}
var item = rows.Items[row];
var caption = layout.Captions[row];
var pad = BannerLayout.CaptionPad(caption.Height);
SetWindowTextW(captions[row], BannerRows.Caption(item));
SetWindowPos(captions[row], 0, caption.Left + pad, caption.Top, caption.Width - pad, caption.Height, SWP_NOZORDER | SWP_NOACTIVATE | SWP_SHOWWINDOW);
var button = layout.Buttons[row];
var stopping = rows.IsStopping(row);
if (stopping)
{
hot[row] = false;
}
SetWindowTextW(buttons[row], BannerRows.StopName(item));
EnableWindow(buttons[row], !stopping);
SetWindowPos(buttons[row], 0, button.Left, button.Top, button.Width, button.Height, SWP_NOZORDER | SWP_NOACTIVATE | SWP_SHOWWINDOW);
InvalidateRect(buttons[row], null, false);
InvalidateRect(captions[row], null, true);
}
UpdateTools(clear: false);
if (count == 0)
{
ShowWindow(window, SW_HIDE);
return;
}
Place();
InvalidateRect(window, null, true);
}
private static TextSize Measure(nint dc, string text)
{
SIZE size;
fixed (char* chars = text)
{
GetTextExtentPoint32W(dc, chars, text.Length, &size);
}
return new TextSize(size.cx, size.cy);
}
/// Top centre of the primary work area, unless the user dragged it somewhere still on a screen.
private void Place()
{
if (layout is null)
{
return;
}
RECT bounds;
GetWindowRect(window, &bounds);
if (moved && !OnAnyScreen(bounds))
{
// Dragged off every screen (a monitor went away): back to the top centre.
moved = false;
}
var size = layout.Window;
var target = moved
? new Box(bounds.left, bounds.top, size.Width, size.Height)
: BannerLayout.Place(PrimaryWorkArea(), size, dpi);
var show = rows.Count > 0 ? SWP_SHOWWINDOW : 0;
SetWindowPos(window, HWND_TOPMOST, target.Left, target.Top, target.Width, target.Height, SWP_NOACTIVATE | show);
}
private static bool OnAnyScreen(RECT bounds)
{
var monitor = MonitorFromRect(&bounds, MONITOR_DEFAULTTONULL);
var info = new MONITORINFO { cbSize = (uint)sizeof(MONITORINFO) };
return monitor != 0 && GetMonitorInfoW(monitor, &info) && info.rcWork.ToBox().IntersectsWith(bounds.ToBox());
}
private static Box PrimaryWorkArea()
{
var monitor = MonitorFromPoint(default, MONITOR_DEFAULTTOPRIMARY);
var info = new MONITORINFO { cbSize = (uint)sizeof(MONITORINFO) };
return GetMonitorInfoW(monitor, &info) ? info.rcWork.ToBox() : new Box(0, 0, 1024, 768);
}
/// Removes () or adds the tooltips: each caption's rectangle and each Stop button.
private void UpdateTools(bool clear)
{
for (var row = 0; row < Rows; row++)
{
var captionTool = new TTTOOLINFOW { cbSize = (uint)sizeof(TTTOOLINFOW), uFlags = TTF_SUBCLASS, hwnd = window, uId = (nuint)(CaptionId + row) };
var buttonTool = new TTTOOLINFOW { cbSize = (uint)sizeof(TTTOOLINFOW), uFlags = TTF_IDISHWND | TTF_SUBCLASS, hwnd = window, uId = (nuint)buttons[row] };
if (clear)
{
SendMessageW(tooltip, TTM_DELTOOLW, 0, (nint)(&captionTool));
SendMessageW(tooltip, TTM_DELTOOLW, 0, (nint)(&buttonTool));
continue;
}
if (layout is null || row >= rows.Count)
{
continue;
}
// The tooltip copies the text.
fixed (char* captionTip = BannerRows.CaptionTip(rows.Items[row]))
fixed (char* stopTip = BannerRows.StopTip)
{
captionTool.rect = RECT.From(layout.Captions[row]);
captionTool.lpszText = captionTip;
SendMessageW(tooltip, TTM_ADDTOOLW, 0, (nint)(&captionTool));
buttonTool.lpszText = stopTip;
SendMessageW(tooltip, TTM_ADDTOOLW, 0, (nint)(&buttonTool));
}
}
}
/// The user's app theme (Settings › Personalisation › Colours), or the high-contrast colours.
private void ApplyTheme()
{
dark = forcedDark ?? AppsUseDarkTheme();
palette = BannerPalette.For(dark, HighContrast(), GetSysColor);
Replace(ref backBrush, CreateSolidBrush(palette.Back));
Replace(ref borderBrush, CreateSolidBrush(palette.Border));
StyleWindow(window, dark);
InvalidateRect(window, null, true);
for (var row = 0; row < Rows; row++)
{
InvalidateRect(captions[row], null, true);
InvalidateRect(buttons[row], null, false);
}
}
/// The fonts (the message font's face at 9.75 pt, bold for captions) and the icon, for the current DPI.
private void CreateResources()
{
var metrics = new NONCLIENTMETRICSW { cbSize = (uint)sizeof(NONCLIENTMETRICSW) };
LOGFONTW font = default;
if (SystemParametersInfoForDpi(SPI_GETNONCLIENTMETRICS, metrics.cbSize, &metrics, 0, (uint)dpi) != 0)
{
font = metrics.lfMessageFont;
}
else
{
"Segoe UI".AsSpan().CopyTo(new Span(font.lfFaceName, 32));
}
// Rounded up, as WinForms turns points into GDI pixels (13 px at 96 DPI, 17 at 120).
font.lfHeight = -(int)Math.Ceiling(FontPoints * dpi / 72);
font.lfWidth = 0;
font.lfItalic = 0;
font.lfUnderline = 0;
font.lfStrikeOut = 0;
font.lfWeight = FW_NORMAL;
Replace(ref buttonFont, CreateFontIndirectW(&font));
font.lfWeight = FW_BOLD;
Replace(ref captionFont, CreateFontIndirectW(&font));
for (var row = 0; row < Rows; row++)
{
SendMessageW(captions[row], WM_SETFONT, captionFont, 0);
}
var size = BannerLayout.Scale(BannerLayout.IconSize, dpi);
nint loaded = 0;
if (LoadIconWithScaleDown(instance, IconResource, size, size, &loaded) < 0)
{
loaded = 0;
}
if (icon != 0)
{
DestroyIcon(icon);
}
icon = loaded;
}
private void DeleteResources()
{
Replace(ref captionFont, 0);
Replace(ref buttonFont, 0);
Replace(ref backBrush, 0);
Replace(ref borderBrush, 0);
if (icon != 0)
{
DestroyIcon(icon);
icon = 0;
}
}
private static void Replace(ref nint gdiObject, nint replacement)
{
if (gdiObject != 0)
{
DeleteObject(gdiObject);
}
gdiObject = replacement;
}
private void Paint()
{
PAINTSTRUCT paint;
var dc = BeginPaint(window, &paint);
RECT client;
GetClientRect(window, &client);
FillRect(dc, &client, backBrush);
FrameRect(dc, &client, borderBrush);
if (layout is not null && rows.Count > 0 && icon != 0)
{
DrawIconEx(dc, layout.Icon.Left, layout.Icon.Top, icon, layout.Icon.Width, layout.Icon.Height, 0, 0, DI_NORMAL);
}
EndPaint(window, &paint);
}
private void DrawButton(DRAWITEMSTRUCT* item)
{
var row = (int)item->CtlID - ButtonId;
if (row is < 0 or >= Rows)
{
return;
}
var disabled = (item->itemState & ODS_DISABLED) != 0;
var lit = !disabled && (hot[row] || pressed[row] || (item->itemState & ODS_SELECTED) != 0);
var back = lit ? palette.ButtonHot : palette.Button;
var fore = disabled ? palette.ButtonDisabledText : lit ? palette.ButtonHotText : palette.ButtonText;
var dc = item->hDC;
var rect = item->rcItem;
var brush = CreateSolidBrush(back);
FillRect(dc, &rect, brush);
DeleteObject(brush);
if (palette.ButtonFramed)
{
var frame = CreateSolidBrush(fore);
FrameRect(dc, &rect, frame);
DeleteObject(frame);
}
var old = SelectObject(dc, buttonFont);
SetBkMode(dc, TRANSPARENT);
SetTextColor(dc, fore);
var text = BannerRows.StopText(rows.IsStopping(row));
fixed (char* chars = text)
{
DrawTextW(dc, chars, text.Length, &rect, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX);
}
SelectObject(dc, old);
if ((item->itemState & ODS_FOCUS) != 0 && (item->itemState & ODS_NOFOCUSRECT) == 0)
{
var inset = BannerLayout.Scale(2, dpi);
var focus = new RECT { left = rect.left + inset, top = rect.top + inset, right = rect.right - inset, bottom = rect.bottom - inset };
SetTextColor(dc, fore);
DrawFocusRect(dc, &focus);
}
}
/// Stop pressed (mouse, Space, or an assistive technology's invoke): ask once, then show "Stopping…".
private void Pressed(int row)
{
if (rows.Press(row) is { } sessionId)
{
stop(sessionId);
Relayout();
}
}
private nint OnMessage(uint message, nint wParam, nint lParam)
{
switch (message)
{
case WM_APP_SHOW:
IReadOnlyList? items;
lock (pending)
{
items = next;
next = null;
}
if (items is not null)
{
Show(items);
}
return 0;
case WM_APP_END:
case WM_CLOSE:
DestroyWindow(window);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_MOUSEACTIVATE:
// Clicking it (or its buttons) leaves the user's focus where it was.
return MA_NOACTIVATE;
case WM_LBUTTONDOWN:
// Anywhere but a button drags the banner.
moved = true;
ReleaseCapture();
SendMessageW(window, WM_NCLBUTTONDOWN, HTCAPTION, 0);
return 0;
case WM_ERASEBKGND:
return 1;
case WM_PAINT:
Paint();
return 0;
case WM_CTLCOLORSTATIC:
SetTextColor(wParam, palette.Fore);
SetBkColor(wParam, palette.Back);
return backBrush;
case WM_DRAWITEM:
DrawButton((DRAWITEMSTRUCT*)lParam);
return 1;
case WM_COMMAND:
var id = LowWord(wParam);
if (HighWord(wParam) == BN_CLICKED && id >= ButtonId && id < ButtonId + Rows)
{
Pressed(id - ButtonId);
}
return 0;
case WM_DPICHANGED:
dpi = LowWord(wParam);
CreateResources();
var suggested = *(RECT*)lParam;
SetWindowPos(window, 0, suggested.left, suggested.top, suggested.right - suggested.left, suggested.bottom - suggested.top, SWP_NOZORDER | SWP_NOACTIVATE);
Relayout();
return 0;
case WM_SETTINGCHANGE:
case WM_SYSCOLORCHANGE:
case WM_THEMECHANGED:
// App theme (ImmersiveColorSet), high contrast, fonts, the work area.
ApplyTheme();
CreateResources();
Relayout();
break;
case WM_DISPLAYCHANGE:
Place();
break;
}
return DefWindowProcW(window, message, wParam, lParam);
}
private nint OnButtonMessage(nint button, int row, uint message, nint wParam, nint lParam)
{
switch (message)
{
// The mouse is handled here, not by BUTTON, which would take the focus and so
// activate the banner.
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
if (IsWindowEnabled(button))
{
SetCapture(button);
pressed[row] = true;
InvalidateRect(button, null, false);
}
return 0;
case WM_LBUTTONUP:
if (pressed[row])
{
pressed[row] = false;
ReleaseCapture();
InvalidateRect(button, null, false);
if (Inside(button, lParam) && IsWindowEnabled(button))
{
Pressed(row);
}
}
return 0;
case WM_CAPTURECHANGED:
if (pressed[row])
{
pressed[row] = false;
InvalidateRect(button, null, false);
}
break;
case WM_MOUSEMOVE:
var inside = Inside(button, lParam);
if (!hot[row] && inside)
{
var track = new TRACKMOUSEEVENT { cbSize = (uint)sizeof(TRACKMOUSEEVENT), dwFlags = TME_LEAVE, hwndTrack = button };
TrackMouseEvent(&track);
}
if (hot[row] != inside)
{
hot[row] = inside;
InvalidateRect(button, null, false);
}
break;
case WM_MOUSELEAVE:
if (hot[row])
{
hot[row] = false;
InvalidateRect(button, null, false);
}
break;
case BM_CLICK:
// What assistive technology sends to invoke a button; BUTTON's own would
// need the banner active first.
if (IsWindowEnabled(button))
{
Pressed(row);
}
return 0;
case WM_SETCURSOR:
SetCursor(hand);
return 1;
case WM_NCDESTROY:
RemoveWindowSubclass(button, &ButtonProc, 1);
break;
}
return DefSubclassProc(button, message, wParam, lParam);
}
private static bool Inside(nint control, nint lParam)
{
RECT client;
GetClientRect(control, &client);
int x = SignedLowWord(lParam), y = SignedHighWord(lParam);
return x >= client.left && x < client.right && y >= client.top && y < client.bottom;
}
[UnmanagedCallersOnly]
private static nint WindowProc(nint hwnd, uint message, nint wParam, nint lParam)
=> current is { } banner && banner.window == hwnd
? banner.OnMessage(message, wParam, lParam)
: DefWindowProcW(hwnd, message, wParam, lParam);
[UnmanagedCallersOnly]
private static nint ButtonProc(nint hwnd, uint message, nint wParam, nint lParam, nuint id, nuint data)
=> current is { } banner
? banner.OnButtonMessage(hwnd, (int)data, message, wParam, lParam)
: DefSubclassProc(hwnd, message, wParam, lParam);
}