hf_repo4 / src /platform /window.cpp
fava21's picture
Backup: patch pack applied + verified on Win11 22000 (d446cc1, ba8617e, dcf5cb8)
2edf277 verified
Raw History Blame Contribute Delete
20.1 kB
// FCS Glass - window.cpp
//
// Implements: W1, W2, W3, W4, W6, W9, E1, E2. (Research notes in window.h.)
#include "platform/window.h"
#include "platform/dpi.h"
namespace fcs {
namespace {
// W3. Caption button geometry in dp. 46x32, flush to the top-right.
constexpr int kCaptionButtonW = 46;
constexpr int kCaptionButtonH = 32;
// W2. The caption strip is 32 dp tall; HTCAPTION except over a control.
constexpr int kCaptionStripH = 32;
} // namespace
// REQ W1 - registers the class shared by both windows.
bool RegisterHostClass(HINSTANCE instance, HBRUSH background, WNDPROC proc,
const wchar_t* class_name) {
WNDCLASSEXW wc = {};
wc.cbSize = sizeof(wc);
wc.style = CS_DBLCLKS; // W9: caption double-click maximize
wc.lpfnWndProc = proc;
wc.hInstance = instance;
wc.hCursor = ::LoadCursorW(nullptr, IDC_ARROW);
wc.hbrBackground = background;
wc.lpszClassName = class_name;
if (::RegisterClassExW(&wc)) return true;
// ERROR_CLASS_ALREADY_EXISTS is success here: the class exists, which is
// all we need.
if (::GetLastError() == ERROR_CLASS_ALREADY_EXISTS) return true;
return false;
}
// REQ W1 - create with the styles the custom frame requires.
bool Window::Create(const wchar_t* class_name, const wchar_t* title, DWORD style,
DWORD ex_style, int x, int y, int w, int h, HWND parent,
HINSTANCE instance) {
// W1: NOREDIRECTIONBITMAP is required for the DComp swap chain;
// WS_OVERLAPPEDWINDOW keeps the OS resize/maximize behaviour.
DWORD ex = ex_style | WS_EX_NOREDIRECTIONBITMAP;
DWORD st = style | WS_THICKFRAME | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
hwnd_ = ::CreateWindowExW(ex, class_name, title, st, x, y, w, h, parent, nullptr,
instance, this);
if (!hwnd_) return false;
// J7: publish the back-pointer the WndProc needs to reach OnNCCalcSize.
// This MUST come after CreateWindowExW: the first WM_NCCALCSIZE fires during
// creation, when the slot is still null. HostWndProc routes WM_NCCALCSIZE to
// Window::NccCalcSizeFor BEFORE it reads GWLP_USERDATA, so that first pass is
// still handled - from the HWND alone - rather than falling through to
// DefWindowProc, which would apply the system frame (BUG-01a).
::SetWindowLongPtrW(hwnd_, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
return true;
}
void Window::Destroy() {
if (hwnd_) {
::DestroyWindow(hwnd_);
hwnd_ = nullptr;
}
}
float Window::dpi_scale() const {
return hwnd_ ? WindowScale(hwnd_) : 1.0f;
}
// W6/BUG-05 - the minimum track size in physical px for the window's
// CURRENT dpi, resolved at WM_GETMINMAXINFO time. A value cached at
// SetMinSizeDp time would be wrong after a monitor DPI hop (E1).
int Window::MinTrackPxX() const {
return DpToPx(static_cast<float>(min_w_dp_), dpi_scale());
}
int Window::MinTrackPxY() const {
return DpToPx(static_cast<float>(min_h_dp_), dpi_scale());
}
// W6/BUG-05 - the WM_GETMINMAXINFO body. The system pre-fills *mmi with
// the defaults before the message is sent; only ptMinTrackSize is
// overridden here, everything else keeps the system value.
void Window::OnGetMinMaxInfo(MINMAXINFO* mmi) const {
if (mmi == nullptr) return;
mmi->ptMinTrackSize.x = MinTrackPxX();
mmi->ptMinTrackSize.y = MinTrackPxY();
}
// REQ E1 / P1, and RV-07.
LRESULT Window::OnDpiChanged(WPARAM wparam, LPARAM lparam) {
(void)wparam;
BeginDpiChange();
// BUG-06: the suggested rect comes from lParam - the official DPI-sample
// pattern. Unpacking width/height out of wParam relies on a packing detail
// those samples deliberately avoid.
if (const RECT* suggested = reinterpret_cast<const RECT*>(lparam)) {
::SetWindowPos(hwnd_, nullptr, suggested->left, suggested->top,
suggested->right - suggested->left,
suggested->bottom - suggested->top,
SWP_NOZORDER | SWP_NOACTIVATE);
}
// RV-07: cleared HERE as well as by the WM_SIZE that SetWindowPos happens to
// provoke. That message is NOT guaranteed - a suggested rect matching the
// current one, a minimized window, or a failed SetWindowPos all skip it - and
// the guard would then stay set for the rest of the session, so a later
// ordinary resize would be treated as DPI-induced and skip its synchronous
// present. Clearing twice is harmless; clearing once, conditionally, is the bug.
EndDpiChange();
return 0;
}
// REQ W1 - sheet of glass. Idempotent: repeated WM_SIZE or
// WM_DWMCOMPOSITIONCHANGED must not clobber a good state.
bool Window::EnableSheetOfGlass() {
if (!hwnd_) return false;
// MARGINS {-1,-1,-1,-1}; W1 states a 1 px margin is wrong.
const MARGINS m = {-1, -1, -1, -1};
const HRESULT hr = ::DwmExtendFrameIntoClientArea(hwnd_, &m);
attrs_.sheet_of_glass = hr;
sheet_of_glass_done_ = SUCCEEDED(hr);
return sheet_of_glass_done_;
}
// REQ W1 - re-apply on composition change.
void Window::OnCompositionChanged() {
if (!hwnd_) return;
(void)EnableSheetOfGlass();
}
// REQ W4 - profile application. Every attribute is annotated with the API it
// maps to, because a mistyped number is the D-7 failure mode.
bool Window::ApplyProfile(bool fluent, bool dark) {
if (!hwnd_) return false;
// DWMWA_USE_IMMERSIVE_DARK_MODE (== 20)
BOOL dark_mode = dark ? TRUE : FALSE;
attrs_.immersive_dark =
::DwmSetWindowAttribute(hwnd_, DWMWA_USE_IMMERSIVE_DARK_MODE, &dark_mode, sizeof(dark_mode));
// DWMWA_WINDOW_CORNER_PREFERENCE (== 33). Fluent rounds, Classic does not.
DWM_WINDOW_CORNER_PREFERENCE corner = fluent ? DWMWCP_ROUND : DWMWCP_DONOTROUND;
attrs_.corner_preference = ::DwmSetWindowAttribute(
hwnd_, DWMWA_WINDOW_CORNER_PREFERENCE, &corner, sizeof(corner));
// DWMWA_BORDER_COLOR (== 34). NONE so our in-app rim is the only edge (G3).
COLORREF border = DWMWA_COLOR_NONE;
attrs_.border_color =
::DwmSetWindowAttribute(hwnd_, DWMWA_BORDER_COLOR, &border, sizeof(border));
// DWMWA_CAPTION_COLOR (== 35). Transparent so the custom caption shows.
COLORREF caption = DWMWA_COLOR_NONE;
attrs_.caption_color =
::DwmSetWindowAttribute(hwnd_, DWMWA_CAPTION_COLOR, &caption, sizeof(caption));
return SUCCEEDED(attrs_.immersive_dark) && SUCCEEDED(attrs_.corner_preference) &&
SUCCEEDED(attrs_.border_color) && SUCCEEDED(attrs_.caption_color);
}
// REQ W2 - resize border in physical px: frame + padded border, both at the
// window's own DPI (research note 6: 4 and 4 at 96 dpi).
int Window::ResizeBorderPx() const {
const float scale = dpi_scale();
int frame = Metric(SM_CXSIZEFRAME, scale);
int padded = Metric(SM_CXPADDEDBORDER, scale);
int total = frame + padded;
if (total < 4) total = 4; // a 0 border makes the window undraggable
return total;
}
// REQ W3 - caption button rect in CLIENT coordinates, flush to the top-right.
RECT Window::CaptionButtonRect(CaptionButton b) const {
const float s = dpi_scale();
const int w = DpToPx(static_cast<float>(kCaptionButtonW), s);
const int h = DpToPx(static_cast<float>(kCaptionButtonH), s);
RECT client = {};
if (hwnd_) ::GetClientRect(hwnd_, &client);
// Right-to-left: Close, Maximize, Minimize.
int index = 0;
switch (b) {
case CaptionButton::Close: index = 0; break;
case CaptionButton::Maximize: index = 1; break;
case CaptionButton::Minimize: index = 2; break;
default: break;
}
RECT r = {};
r.left = client.right - w * (index + 1);
// BUG-33: the button cluster starts BELOW the resize band, not flush at y=0.
// W2 wants a full-perimeter resize and W3 wants the buttons at the top-right,
// and with r.top = 0 those two collide: the band's top few px sit on top of the
// buttons, so one of them has to lose. Giving the BAND the corner is what stock
// Windows does (buttons are inset under the frame there), it keeps W2's
// perimeter whole, and it removes the dead zone that would otherwise sit on top
// of the Close button. When maximized there are no resize zones at all
// (HitTestClient), so the cluster goes flush to the top again.
const int band = (hwnd_ && !::IsZoomed(hwnd_)) ? ResizeBorderPx() : 0;
r.top = band;
r.right = r.left + w;
r.bottom = band + h;
return r;
}
CaptionButton Window::ButtonAtClient(int px, int py) const {
static const CaptionButton kOrder[] = {CaptionButton::Close, CaptionButton::Maximize,
CaptionButton::Minimize};
for (CaptionButton b : kOrder) {
const RECT r = CaptionButtonRect(b);
if (px >= r.left && px < r.right && py >= r.top && py < r.bottom) return b;
}
return CaptionButton::Count;
}
// REQ W2 - client hit test: a 32 dp caption strip plus a full-perimeter resize.
HitRegion Window::HitTestClient(int px, int py) const {
RECT c = {};
if (hwnd_) ::GetClientRect(hwnd_, &c);
if (px < c.left || px >= c.right || py < c.top || py >= c.bottom) return HitRegion::None;
const int b = ResizeBorderPx();
// BUG-33: the caption buttons are inset BELOW the resize band (see
// CaptionButtonRect), so they can no longer collide with a resize zone and
// are resolved first. When maximized the band is zero and there are no resize
// zones at all, so the same order is still correct. Resolving them first is
// what keeps the whole button hit-testable: behind the 32 dp strip test a
// button's lower px would fall through to Client instead.
switch (ButtonAtClient(px, py)) {
case CaptionButton::Minimize: return HitRegion::MinButton;
case CaptionButton::Maximize: return HitRegion::MaxButton;
case CaptionButton::Close: return HitRegion::CloseButton;
default: break;
}
// BUG-33: EVERY resize zone is restored-window-only. When maximized,
// NccCalcSizeFor insets the client back inside the window rect, so the outermost
// b px of the client sit at the very edge of the visible work area. Returning
// HTTOPLEFT/HTLEFT/... there puts a resize cursor on the screen edge of a
// window that CANNOT be resized - unlike every native app - and a drag in that
// band opens an SC_SIZE loop for a size-locked window. BUG-28 special-cased
// only the top edge; the guard belongs around the whole perimeter, because the
// maximized inset is applied to all four sides.
if (!::IsZoomed(hwnd_)) {
// Corners win over the edges they also belong to.
const bool left = px < c.left + b;
const bool right = px >= c.right - b;
const bool top = py < c.top + b;
const bool bottom = py >= c.bottom - b;
if (top && left) return HitRegion::ResizeTopLeft;
if (top && right) return HitRegion::ResizeTopRight;
if (bottom && left) return HitRegion::ResizeBottomLeft;
if (bottom && right) return HitRegion::ResizeBottomRight;
if (left) return HitRegion::ResizeLeft;
if (right) return HitRegion::ResizeRight;
if (bottom) return HitRegion::ResizeBottom;
// BUG-28: the top edge had no zone of its own. `top` was consulted only for
// the corner hits, so everything between them fell through to the caption
// strip: ResizeTop and HTTOP were unreachable dead code and a restored window
// could not be resized from its top edge, so W2's "full-perimeter resize" was
// false. Guarded on `top` - an unconditional return here would make the
// ENTIRE client report HTTOP.
if (top) return HitRegion::ResizeTop;
}
// The remaining top strip is a caption drag region (W9 drag-restore).
if (py < c.top + DpToPx(static_cast<float>(kCaptionStripH), dpi_scale())) {
return HitRegion::Caption;
}
return HitRegion::Client;
}
namespace {
// Maps a region to its HT* code. HTMAXBUTTON over the maximize button is what
// enables the Windows 11 snap-layout flyout (W2, T8).
LRESULT HitToHt(HitRegion r) {
switch (r) {
case HitRegion::Caption: return HTCAPTION;
case HitRegion::MaxButton: return HTMAXBUTTON;
case HitRegion::MinButton: return HTMINBUTTON;
case HitRegion::CloseButton: return HTCLOSE;
case HitRegion::ResizeLeft: return HTLEFT;
case HitRegion::ResizeRight: return HTRIGHT;
case HitRegion::ResizeTop: return HTTOP;
case HitRegion::ResizeBottom: return HTBOTTOM;
case HitRegion::ResizeTopLeft: return HTTOPLEFT;
case HitRegion::ResizeTopRight: return HTTOPRIGHT;
case HitRegion::ResizeBottomLeft: return HTBOTTOMLEFT;
case HitRegion::ResizeBottomRight: return HTBOTTOMRIGHT;
case HitRegion::Client: return HTCLIENT;
// RV-03 (their BUG-32): None means the point is outside the CLIENT rect. For
// a restored window client == window (W1), so it never happens. When
// MAXIMIZED, NccCalcSizeFor insets the client by the resize border, and the
// band between the window rect and the client rect is genuine non-client
// area - the only non-client area this design has. Reporting HTCLIENT there
// made that band phantom client, so cursor tracking and clicks inside it
// lied. HTNOWHERE is the honest answer, and it is the same band RV-01 is
// about: the two are halves of one observation.
case HitRegion::None:
default: return HTNOWHERE;
}
}
} // namespace
// REQ W2 - the ONE place the screen -> client conversion happens. lParam in
// WM_NCHITTEST is SCREEN coordinates; doing this in the caller is how the
// previous build shipped a window draggable only near the screen origin.
LRESULT Window::NCHitTest(POINT screen_pt) const {
if (!hwnd_) return HTCLIENT;
POINT client_pt = screen_pt;
if (!::ScreenToClient(hwnd_, &client_pt)) return HTCLIENT;
return HitToHt(HitTestClient(client_pt.x, client_pt.y));
}
// REQ W2 - hover state from WM_NCMOUSEMOVE. Screen coordinates in, converted
// once here.
void Window::OnNcMouseMove(POINT screen_pt) {
if (!hwnd_) return;
POINT c = screen_pt;
if (!::ScreenToClient(hwnd_, &c)) return;
// BUG-22: WM_NCMOUSELEAVE is only delivered to a window that ASKED for it
// via TrackMouseEvent(TME_LEAVE | TME_NONCLIENT). Nothing ever asked, so
// OnNcMouseLeave was unreachable, and the hovered button plus the HAND
// cursor stayed stuck after the pointer left the window. Re-arm on every
// move: the system cancels the tracking as soon as it fires the leave.
TRACKMOUSEEVENT tme = {};
tme.cbSize = sizeof(tme);
tme.dwFlags = TME_LEAVE | TME_NONCLIENT;
tme.hwndTrack = hwnd_;
::TrackMouseEvent(&tme);
const CaptionButton b = ButtonAtClient(c.x, c.y);
if (caption_.hovered != b) {
caption_.hovered = b;
::SetCursor(::LoadCursorW(nullptr, (b == CaptionButton::Count) ? IDC_ARROW : IDC_HAND));
}
}
void Window::OnNcLButtonDown(CaptionButton b, POINT screen_pt) {
(void)screen_pt;
caption_.pressed = b;
caption_.tracking = true;
}
void Window::OnNcLButtonUp(CaptionButton b, POINT screen_pt) {
(void)screen_pt;
const bool was_pressed = (caption_.pressed == b);
caption_.pressed = CaptionButton::Count;
caption_.tracking = false;
if (!was_pressed || !hwnd_) return;
// The OS already drives HTMIN/HTMAX/HTCLOSE for a normal frame; the
// NOACTIVATE dock window has none, so it is done here.
switch (b) {
case CaptionButton::Minimize:
::ShowWindow(hwnd_, SW_MINIMIZE);
break;
case CaptionButton::Maximize:
if (maximized_) {
::ShowWindow(hwnd_, SW_RESTORE);
maximized_ = false;
} else {
::ShowWindow(hwnd_, SW_MAXIMIZE);
maximized_ = true;
}
break;
case CaptionButton::Close:
::PostMessageW(hwnd_, WM_CLOSE, 0, 0);
break;
default:
break;
}
}
void Window::OnNcMouseLeave() {
caption_.Reset();
}
// REQ E2 - skip rendering when minimized, and never touch a zero-size surface.
bool Window::ShouldRender() const {
if (!hwnd_) return false;
if (::IsIconic(hwnd_)) return false;
RECT r = {};
if (!::GetClientRect(hwnd_, &r)) return false;
if (r.right - r.left <= 0 || r.bottom - r.top <= 0) return false;
return true;
}
// REQ W1 / J7 - the window procedure body for WM_NCCALCSIZE.
//
// D-15: the FIRST WM_NCCALCSIZE for a plain WS_OVERLAPPEDWINDOW arrives with
// wParam == FALSE, so returning 0 only for TRUE lets that pass fall through to
// DefWindowProc. Both cases must return 0.
// D-16: WITHDRAWN. It claimed rgrc[1] was the client rect and rgrc[2] the
// window rect; the real order is rgrc[0] = proposed NEW window rect,
// rgrc[1] = OLD window rect, rgrc[2] = OLD client rect. Copying either of the
// last two into rgrc[0] pins the client to its previous size (BUG-01b), so
// rgrc[0] is the only legal source for making the client fill the frame.
// J7 / X30 (W1): without that inset, content extends past the screen edge.
int Window::ResizeBorderPxFor(HWND hwnd) {
// GetDpiForWindow is Windows 10 1607+, above the 6.2 target floor (HC1),
// so it is resolved at run time by WindowScale (W5/D-13) rather than called.
const float scale = WindowScale(hwnd);
int frame = Metric(SM_CXSIZEFRAME, scale);
int padded = Metric(SM_CXPADDEDBORDER, scale);
int total = frame + padded;
if (total < 4) total = 4;
return total;
}
LRESULT Window::NccCalcSizeFor(HWND hwnd, WPARAM wparam, LPARAM lparam) {
if (hwnd == nullptr) return 0;
// D-15: the FIRST WM_NCCALCSIZE arrives with wParam == FALSE, and on that
// pass lParam is a plain RECT* holding the proposed window rect - NOT an
// NCCALCSIZE_PARAMS. Returning 0 without touching it makes the client the
// whole window. Both passes must return 0.
if (wparam == FALSE) return 0;
{
NCCALCSIZE_PARAMS* p = reinterpret_cast<NCCALCSIZE_PARAMS*>(lparam);
if (p != nullptr) {
// rgrc[] is documented (winuser.h / WM_NCCALCSIZE) as:
// rgrc[0] the NEW WINDOW rect the system is proposing
// rgrc[1] the window rect BEFORE this move/resize
// rgrc[2] the CLIENT rect BEFORE this move/resize
// DefWindowProc writes the default CLIENT rect (window minus the system
// frame) into rgrc[0]; keeping that leaves the frame uncovered, and an
// uncovered margin composites black because the chain is premultiplied.
// So the proposed WINDOW rect is saved, the default is allowed to run,
// and rgrc[0] is restored - the client then equals the CURRENT window
// rect at every size.
//
// BUG-01b: the previous implementation copied rgrc[2] into rgrc[0]. That
// copies the PREVIOUS CLIENT rect, so the client area is pinned to
// whatever size it had last time and never follows a resize. It looked
// correct at creation only because that first pass had just made the
// client equal to the window. Measured: widening the window to 1561x800
// left the client at 1280x800, and the 281 px strip on the right
// composited black with the system caption buttons drawn in it (the
// window still carries WS_CAPTION).
const RECT proposed_window = p->rgrc[0];
::DefWindowProcW(hwnd, WM_NCCALCSIZE, wparam, lparam);
p->rgrc[0] = proposed_window;
RECT& r = p->rgrc[0];
if (::IsZoomed(hwnd)) {
// W1/J7 (X30): when maximized, inset by the frame thickness at this
// window's own DPI so content never runs off-screen or under the taskbar.
const int inset = ResizeBorderPxFor(hwnd);
r.left += inset;
r.top += inset;
r.right -= inset;
r.bottom -= inset;
}
}
}
return 0; // the client area fills the frame
}
LRESULT Window::OnNCCalcSize(WPARAM wparam, LPARAM lparam) {
return NccCalcSizeFor(hwnd_, wparam, lparam);
}
} // namespace fcs