window

host

the hwnd, the wndproc, the pumps, input, the dirty box and dpi

mirrored from window/cpp/window.core/host/README.md, which is the only copy of this text. edits made here are overwritten the next time the site builds

the hwnd n the wndproc n window lifetime, the two host kinds (shaped layered n chromed resizable), the three pump entries (pump_once, run, spawn_ui_thread), input, focus n tree hit testing

links into window.core, the lib never owns a thread unless spawn_ui_thread is asked for

filewhat
host.{h,cpp}P1.9, the layered host, hwnd plus wndproc plus lifetime
pump.{h,cpp}P1.10, the three pump entries n the one thread the lib will ever start
input.{h,cpp}P1.11, hover n capture n focus n the tree hit test, plus the P1.21 overlay routing
dirty.hP1.12, the dirty box, the frame plan n the one place a frame is drawn
dpi.hP1.33, process awareness, the monitor a point is on n the logical to device scale
clipboard.hP1.29, the desktop clipboard as utf8 in n utf8 out, header only n user32 only
metrics.hP1.38, the caret blink rate n the double click window, i.e. what a person set
frame.hP1.13, the two host kinds, the chrome metrics n the hit test that pays for eating the frame

what a host owns, n the order it lets go

a host owns three things n hands them to nobody, the window, the presenter that fills it n the renderer that draws into the presenter. that is also the teardown order, renderer first bc it is the one still pointing at the presenters pixels, then the presenter which frees them, then the window

getting that backwards is the access violation on close the ahk lib documented, so it is written once in destroy(), n WM_DESTROY routes through the same order for a window the os closed rather than us

the wndproc is a member, n why that is a criterion

win32 hands you a free function n the usual answer is a global map from hwnd to object, which is a second source of truth that goes stale on every create n destroy. instead the instance pointer rides in on the CREATESTRUCT at WM_NCCREATE n lives in the windows own GWLP_USERDATA, so the window is the map, there is nothing global, n two hosts in one process cannot see each other

two details that are not obvious n both cost a crash if missed

  • the hwnd is passed into on_message, not read off the member. WM_DESTROY clears the member n the messages after it still have a real window to answer for, so reading the member there hands DefWindowProc a null
  • the GWLP_USERDATA link drops at WM_NCDESTROY, the last message a window ever gets. dropping it at WM_DESTROY instead would send everything between the two through the no-instance path

the layered host sizes itself from the present

UpdateLayeredWindow sizes the window as it puts the pixels up, so resize() here resizes the backing store n the window follows on the next frame. sizing the window as well would show one frame at the new size holding the old pixels. the opaque path has no such trick n does get a SetWindowPos

the chromed host, n the frame it eats

host_desc_t::kind picks between the two, P1.13. a popup is the above, shaped n chromeless n out of the taskbar. a chromed one is a real overlapped window that keeps WS_CAPTION n WS_THICKFRAME n both boxes, n eats every pixel of the frame by returning 0 from WM_NCCALCSIZE

the styles are the point n they are not decoration. aero snap, win-arrow, the taskbar button n the minimise animation are all behaviours of those styles, n win32 offers no way to ask for one without the frame that comes with it. so the styles stay, the os carries on running all four off them, n it simply has no pixels left to draw a frame in. the drawn titlebar is then the only chrome there is

the bill for that is WM_NCHITTEST, bc the frame is where the os was getting the resize edges n the caption drag from. frame_hit in frame.h hands them back, n it is a pure function on purpose, a size n a point n three flags in, an HT code out, so every corner of it is drivable with no window anywhere near it. the wndproc side is four lines of unpacking either side of one call

its ordering is the whole of it n none of it is arbitrary

orderwhy
the edges go firsta control flush to the window edge must not eat the resize grip
a maximised window has no edgeselse a grab at the top starts a resize instead of the unsnap drag
a control beats the captiona close button in the titlebar has to be clickable, not only draggable
whats left in the strip is the captionthe os runs the drag, which is where the snap comes back free

the one narrow exception to that order, P1.E.15

frame_t::control_beats_edge is off by default n the table above holds everywhere. turned on, a control INSIDE the caption strip takes the edge off the table, n nowhere else does. the case that asked for it is a close button flush into the top right, which is where it belongs bc that corner is the one target you can throw a cursor at without aiming, n its own top 6 px were a resize grip

it is an exception n never a reversal, the three edges a pane actually sits flush against are untouched by it either way, which is the case the ordering was written for n still gets right. the bill is that a titlebar covered in controls cannot be resized from the top or the two top corners, so it is opt in. host_t reads the field on every hit rather than caching it at create

one measurement, two homes, P1.E.14

frame_t::caption n theme_t::bar_h are the same number n a caller sets both. they do not merge bc frame_t drags <windows.h> in behind it n a theme never may, so one is the token a titlebar paints against n the other is what win32 is told drags the window

they used to disagree out of the box, 32 against 40, which left the bottom 8 px of a default titlebar drawn but not draggable. both are 40 now, matching the ahk lib this is ported from, n a check holds the two defaults together so they cannot drift again

the two sizes come apart here in the OTHER direction

a popup is told a size n the window follows. a chromed one is told by WM_SIZE what size it now is n the store follows, bc a resize drag is the os deciding n not us. so resize() (logical in, window follows) n adopt_size() (device in, store follows) are mirror images, n adopt_size is the only place in the lib that runs dpi_unscaled

adopt_size drops a size it already has, n that is load bearing rather than an optimisation. resize() moves the window itself, which sends a WM_SIZE straight back at us, so without the drop every programmatic resize would rebuild the store twice n fire the reflow callback twice with it

the traps

  • WM_NCCALCSIZE must answer BOTH forms. the wparam says whether the lparam is an NCCALCSIZE_PARAMS (TRUE) or a bare RECT (FALSE), n the one CreateWindowEx sends is the FALSE one. answering only the TRUE form leaves the creation calc to DefWindowProc, so the window comes up with a real frame n every later calc is eaten, which reads as the whole trick not working. the ahk lib gates on the wparam n papers over it with a FRAMECHANGED SetWindowPos right after creation
  • eating the frame breaks maximise on its own, n IT TAKES TWO HALVES TO PUT BACK. the os sizes a maximise as the work area GROWN by the frame it is about to subtract, so a window that never subtracts one hangs over all four edges n covers the taskbar. the POSITION half is frame_max_box filling ptMaxSize n ptMaxPosition in on the MINMAXINFO, n ptMaxPosition is relative to the MONITOR n not the virtual screen, which does nothing wrong on one monitor n puts the window on the wrong screen the moment there are two. the SIZE half is frame_max_inset n frame_max_client in the maximised case of WM_NCCALCSIZE, i.e. the grown rect pulled back in by the border the os expected taken off it
  • for a long time only the first half was here n the comment said both were, P1.E.3. the size half was missing outright n frame.h opened with a block naming frame_max_box as the answer, so the first app built on this lib hit an 8 px overhang on every edge, went looking, read that the case was solved, n ended up writing a wndproc of its own in front of ours. a comment claiming a fix is finished is worse than no comment at all, it stops the next person checking, which is the expensive part n not the bug
  • IsZoomed n never our own m_maximised flag inside that case. WM_NCCALCSIZE arrives DURING the maximise n the flag is set off WM_SIZE, which lands after, so the flag reads false on the one message that needed it true. the os already decided, so the os is what gets asked
  • the inset is asked for AT A DPI. a bare GetSystemMetrics answers for the primary monitor whatever window you meant, so a second screen at another scale gets the first screens border n comes out wrong by the difference, which is another one nobody can see on a single monitor box
  • WM_DPICHANGED applies the dpi BEFORE it moves the window. SetWindowPos sends WM_SIZE back synchronously n a chromed host adopts one as fact, so moving first lands the new size while we still think we are on the old scale, n the store then gets scaled a second time off that answer, i.e. a 150% window comes out at 225%
  • ptMaxTrackSize is deliberately left alone. clamping it to the work area as well stops a drag resize ever crossing onto a second monitor, which is a real thing people do n nothing to do with maximise
  • chromed plus layered is refused at create rather than swapped for something that works. ULW sizes the window as it presents, so it would argue with every resize drag over what size the window is, n that argument reads as a window springing back under the cursor rather than as a mistake anybody can find

input stops at the host

every mouse n key message is translated in the wndproc into a call on the hosts input_router_t, n nothing further in is ever handed a WPARAM. that is what lets the whole of P1.11 be driven headless by the runner, n it is also why the router never calls win32 itself, taking the mouse capture is a callback the host fills in with SetCapture

the router holds four pieces of state n they are not the same piece

statechanges onnotes
hoveredevery movethe target under the cursor
captureda press, until the releasekeeps every move n the release even off its own bounds
focuseda clickwhere keys go, survives the cursor going anywhere
window hoverthe window rect n WM_MOUSELEAVEits own test, see below

the window level hover is not a fold of the control ones. reaching for a corner button leaves the body n every control on the way, so anything that hides itself on a control leave starts hiding exactly as you go to press it. so it is tested against the window rect n cleared only by a real WM_MOUSELEAVE

the modifiers travel WITH the event, P1.E.10

on_press, on_drag n on_release are handed a key_mods_t, last argument on all three. before this a control answering a shift click had to call key_mods_t::current() itself, i.e. read the global keyboard to describe an event it had just been given, which is the one place in this api where the answer depended on when you asked rather than on what arrived

the host reads the keyboard at the wndproc n passes it in, exactly as it already did for key. the router deliberately does not call current() itself, which would have saved every caller a line n made it impossible for any check to drive a shift click without a real key held down

  • each of the three gets its OWN set, n the checks drive them with one modifier each for that reason, bc a router unpacking once n sharing one set reads identical to three correct handovers
  • capture_lost replays the mods the press arrived with, alongside the m_at n m_button it already replayed. nobody let go of anything to cause a stolen capture, so reading the keyboard fresh there would describe the theft rather than the gesture being cancelled
  • mouse_dbl_click takes them too, bc it fires a synthetic mouse_down of its own n the press half would otherwise lose them. on_dbl_click itself does not carry them, the item named three

the cursor hook, P1.E.11

input_target_t::cursor_at(point_t) answers a cursor_t, defaulting to arrow, n the host reads it on WM_SETCURSOR. it takes the POINT bc one control is often several things, a canvas is a crosshair over a port n a grabbing hand over empty space, n asking per point is what makes that one override rather than a control splitting into children to change a pointer

cursor_t is an enum n not the uint32_t holding an IDC_* the finding asked for. every control in the tree implements input_target_t n none of them may see <windows.h>, so host.cpp is the only file that knows an IDC_* exists, the same bargain mouse_button_t already makes

  • the CAPTURED target answers if there is one, only then the hovered. the hover comes off a held target the moment the cursor leaves its bounds, so a hovered-only read loses the cursor during a drag, which is the whole case the hook exists for
  • the decision is on the ROUTER n not in the wndproc, so a check drives it with no window. the wndproc half is four lines round one call, same as frame_hit
  • anything that is not HTCLIENT goes to the default. WM_SETCURSOR fires for the resize edges n the caption too, so answering every one would paint an arrow over a frame about to get a resize cursor

input_target_t is deliberately not control_t, which lands in P1.18. the router needs something to hit test today, so it speaks to an interface of bounds n children n flags, n a control implements it later with the router untouched. bounds are in window coords, not parent relative, same as the ahk lib, which keeps a hit test a containment test rather than a walk accumulating an offset

four things in here that are not obvious n each cost a bug

  • a container defaults to not interactive, so a panel painted over a button does not eat the click, the hit test carries on past it n finds the button underneath
  • WM_LBUTTONDBLCLK arrives INSTEAD of the second WM_LBUTTONDOWN, so the double click path has to press as well as double, else a button clicked twice quickly only fires once
  • a captured drag reports negative client coords, so the lparam is unpacked with GET_X_LPARAM n not LOWORD, which would turn -5 into 65531 n put the cursor miles off to the right
  • WM_CHAR is utf16, so anything past the basic plane arrives as two messages n the halves are joined in the host rather than being passed on as half a character each

TrackMouseEvent is one shot, the os forgets after it fires, so it is re-armed on every move n a flag is what stops that being a syscall per mouse message. it also fires the leave immediately when the cursor is not really over the window, which is why the runner proves the arming by pumping for the message rather than by querying it back

the dirty rect model

dirty.h is the model n host_t is where it lives, bc a window is what owns a dirty box. four calls carry the whole of it

callwhat it does
invalidate()takes the whole window
invalidate(box) / invalidate(target)unions one box, or a controls bounds, into the dirty box
invalidate_move(target, write)invalidates, runs the write, invalidates again
update()draws n presents ONE frame, only if something asked for one

paint() is still there n is the forced full frame, written as an invalidate() plus an update() so there is exactly one place a frame happens n a forced one cannot drift away from a dirty one. show() n a WM_PAINT on the opaque path both take that route

one box, not a list. every invalidate unions into the same rectangle n draws nothing on its own, so a burst of twenty between two messages costs ONE frame. twenty small presents are twenty round trips where one slightly bigger present is one, n the ahk lib arrived at the same answer from the same place

the 70% takeover. past that share of the window a partial frame is paying for a clear n a clip n a present region to save less than it costs, so the whole surface takes over n the frame goes back to being the plain one. it happens at union time, so box() never says one thing while the frame does another, n it is a whole number compare (area * 100 > whole * 70) so a box sitting on the line reads the same on every machine

the two halves of dirty come apart, n they come apart per presenter. this is the part that goes wrong quietly, so the model asks the presenter both questions n assumes neither

questionasked withtrue forfalse for
may we repaint only the box ?keeps_contents()layered, opaquedcomp, a WRITE_DISCARD map
may we present only the box ?partial_proven() plus the switchopaque, dcomp (P1.17)layered (G-window-7)

so a discard path repaints the whole surface every frame n uses the dirty box only to narrow the present, bc a WRITE_DISCARD map hands back undefined memory n there is no older image out there for a partial repaint to sit on top of

the partial present is a separate switch n it defaults off, host_t::set_partial_present. G-window-7 watched a partial layered present lag n drop updates against a real compositor while the headless harness called it fine, so it is unproven rather than merely unwritten. the partial repaint runs either way, which is the whole point of the two halves being separate, the saving that is certain never waits on the one that is not. a path that has proven its own partial present (opaque, a plain sub rect BitBlt) narrows regardless of the switch

the fallback lives inside the presenter n nowhere else. presenter.h says a presenter that cannot do a partial present honestly falls back to a full one on its own rather than reporting a lie, bc a present return code proves nothing visually. so the host never reads a success flag off end(), there isnt one, n the layered presenter falls through to a full UpdateLayeredWindow the moment UpdateLayeredWindowIndirect refuses

the traps

  • keeps_contents() backwards is the miserable one. it shows up as garbage outside the dirty box on the dcomp path ONLY, everything looks perfect on layered n opaque bc a dib really does keep last frame
  • the clip is what makes the saving real. without a push_clip around the repaint box, a paint callback that draws the whole window paints straight over the pixels we deliberately kept, n the frame still LOOKS right while the saving is a lie
  • a move invalidates BEFORE n after the write. doing only the after one looks perfect on the frame you test it on, the old block just sits there lit, n it only shows once the background under it is not flat, so invalidate_move wraps both n the order comes out unwriteable-wrong, same bargain as the renderers single pop()
  • the box is only cleared once the frame carrying it really landed. a refused frame (an invalid surface, a lost device, a minimised window) leaves the invalidate owed, else an update is quietly eaten
  • a float box crosses to px with recti_t::round_out n nothing else. rounding to nearest starts the repaint one px in n leaves the controls left edge stale, which is a fringe that only ever appears on a partial repaint
  • prcDirty does nothing without BOTH pptDst n psize. G-window-7 found that with the pair left null neither block showed, i.e. the ahk libs partial_present := false was hiding a missing argument n not a broken api. that is fixed in presenter_layered.cpp, n the switch is still off bc the animation half of that gate failed on its own

dpi, n the two sizes

dpi.h is header only n user32 only, no project file touched n no lib added. GetDpiForMonitor was the obvious call n it lives in shcore.dll, so it is deliberately not used, GetDpiForWindow answers the same question about the window we actually care about

the process has to declare its awareness before any of it means anything. an undeclared process is UNAWARE, which does not mean the os leaves us alone, it means the os lies, every window is laid out at 96 n then bitmap stretched to whatever the monitor is really on, so a 150% monitor gets a blurry window n every metric we read back is the pretend one. host_t::create calls declare_dpi_v2() beside prewarm() for exactly that reason

a manifest still wins where an exe has one, BUILD.md says where it goes. this is the floor under it, bc window.core is a lib n cannot put a manifest on a host process it did not build. the two agree rather than fight, a process already manifested v2 takes the early return

there are now two sizes n mixing them up is the bug this section exists to stop

sizegetterwhat it is
logicallogical()what the caller asked for, the space the control tree is laid out in, does not move
devicesize()the backbuffer n the window, i.e. logical times the monitor scale

so everything crossing the api in logical px gets scaled on the way in, an invalidate box n a mouse point both do, n the frame pushes the scale as a transform so a paint callback writes plain numbers. at 96 dpi the two are equal n the transform push is skipped outright, so a normal monitor pays nothing

WM_DPICHANGED rebuilds the store at the new scale, marks the whole window, tells whoever set set_dpi_fn n then paints on the spot. the reflow is that callback, bc the lib has no layout of its own until P1.18

the traps

  • the suggested rect on the lparam is not advice. a window that ignores it gets told again, which on a drag between two monitors is a loop you can watch flicker. it is already our logical size times the new scale, i.e. exactly the number we would have worked out ourselves
  • SetProcessDpiAwarenessContext returns FALSE once awareness is set, ERROR_ACCESS_DENIED, while the context is still perfectly v2. so declare_dpi_v2 asks for the context back instead of trusting that bool, else every host after the first reports a failure that never happened
  • the store is rebuilt BEFORE the dpi is committed, so a refused resize leaves the host whole at the old scale rather than claiming a scale its pixels are not at
  • an invalidate is scaled THEN rounded out, in that order. rounding first would round 10.5 down to 10, multiply it to 15 n leave the half pixel that used to be covered stale, i.e. the same one px fringe round_out exists to stop, arrived at from the other side
  • v2 n not v1. v1 leaves the non client area n every common control on the system dpi, n v2 is the one that sends WM_DPICHANGED for a window dragged between monitors rather than only when a monitors own setting changes

the overlay routing, P1.21

the slot itself lives on control_t, scene/control.h, n what is in here is the two virtuals the router reaches it through, overlay() n dismiss_overlay() on input_target_t. the router asks the root for its popup the same way it asks for children, so it never learns what a popup IS

  • hit_test gives the overlay first refusal. it sits in that one function rather than in mouse_down, so the press n the hover n the re-hover after a release all read the same rule from one place. a miss falls straight through to the tree, i.e. an overlay is not modal
  • mouse_wheel puts the overlays path on first, so a scrolling popup over a scrolling page scrolls the popup n hands the wheel back to the page once it has hit its end
  • mouse_down dismisses on a press outside, n outside is measured against the popups box n not against what the hit test found, bc a popup with an inert background hit tests to nothing n a click on its own empty half would otherwise close it. dismiss_overlay hands back whether that press was swallowed, which it is when it landed on the popups owner, else one click on a dropdown header closes the popup n then reaches the header, which reopens it

hit_node also changed for P1.19 n it is worth knowing about here, a node that CONTAINED the point now goes on the path even when nothing interactive was found under it, bc a scrolling container is deliberately not interactive n the wheel still has to reach it over a gap in its content. the return value is untouched, so hover n press n focus route exactly as they always did, only the wheel reads the path

not here yet

focus traversal by tab n the window drag zone are out of P1.11 on purpose, n win10 rounded corners are out of P1.13, square is accepted there

the three pump entries, n why three

three callers want opposite things. a tool with its own loop wants control back every frame (pump_once), an app that IS the window wants to hand control over n be told when it is done (run), n a script that wants a window up while it carries on wants neither (spawn_ui_thread)

the lib spawns no thread unless asked, spawn_ui_thread is the only call anywhere in it that starts one, n the runner proves it by counting process threads across a full create, pump, paint n destroy

the awkward truth under all three is that a window belongs to the thread that created it. win32 delivers its messages there n nowhere else, so a host cannot be handed across to be pumped somewhere else. that is why spawn_ui_thread takes a description n not a host, it has to build the window on the far side rather than adopt one

two details worth keeping

  • run checks closed() after the dispatch, not in the loop condition. the message that closes the window is the one being dispatched, so a condition would send it back into a blocking GetMessage with no window left to ever wake it
  • the ui thread has TWO frame rates n the presenter picks which, P1.17. a path that does not pace itself gets the 16ms timer n lands nearer 30 than 60, bc windows sleep granularity is about 15.6ms, measured at 161 frames over 5 seconds. a path that DOES pace itself (dcomp) gets no timer at all n lands on the refresh, measured at 120 against the timers 32 on the same box. the loop reads paces_frames() once after create, so it has to be a property of the path n never something a presenter switches on halfway through

On this page