Win32 GDI GUI in Rust
For desktop UIs built directly on GDI with no winit/egui/Tauri: laying out a
window, drawing text, and proving it rendered. The recurring failure is
silent — everything looks fine until you look at the pixels.
When to Use
- Writing or debugging a window that draws itself via GDI in Rust
- Text renders nowhere, or only some labels appear
- A window renders pure white, or white boxes over the text
- A window's controls land off-screen or float in the wrong place
- A form's labels are missing even though the fields draw
- A window screenshots as solid black and you cannot tell whether it is broken
- Sibling windows share a title and you keep capturing the wrong one
- GUI unit tests hang, or pass against code you know is wrong
- A tray icon, context menu, or minimise-to-tray that compiles and reports
success but does nothing when clicked
- Building a settings/agent/profile editor: what to model first, and the
serialization rules that keep saved data readable (see
references/settings-editor-model.md)
- Deciding which settings to show, disable or label as unimplemented — the
live / read-only-mirror / inert classification and the CI scan that keeps it
honest (same reference)
- A list of "things not wired up yet" that you suspect is wrong
- Auditing whether a declared surface is consumed at all — settings keys, MCP
tools, IPC commands — and turning the result into a CI gate
(see references/inert-surface-audits.md)
- The UI stutters, or the loop misses its frame target and the average FPS hides
it (see references/render-loop-performance.md)
- Adding a command to the app's control surface, or a client needs to match
replies to requests (see references/local-control-api.md)
Always-on rules
- A window that renders but ignores every click and keystroke has no
message pump. A window proc is only ever invoked by the dispatcher, so if
the main loop never calls
PeekMessage/DispatchMessage (or GetMessage),
the window receives no WM_PAINT, no WM_KEYDOWN/WM_CHAR, no
WM_LBUTTONDOWN and no WM_MOUSEWHEEL — every control is dead no matter how
correctly it is written. Grep the render loop for PeekMessage/DispatchMessage
before diagnosing input handling: an app can have a working pump on one
thread (an overlay) and none on the thread that owns the main window, which
is what makes the window look alive while ignoring everything. Fix:
PeekMessageW(&mut msg, null_mut(), 0, 0, PM_REMOVE) in a while loop at the
top of the frame loop, TranslateMessage + DispatchMessageW each, and break
on WM_QUIT. The tell-tale symptom in a probe: a colour count far too low for
the layout (e.g. 23 where a full UI needs 150+).
PrintWindow flag 1 hangs when the window thread does not pump.
PW_CLIENTONLY (1) sends WM_PRINTCLIENT to the app thread, so it blocks
forever on a window whose thread is not pumping; PW_RENDERFULLCONTENT (2)
reads the DWM redirection surface instead, which returns stale content rather
than hanging. A probe that captures successfully with flag 2 but hangs with
flag 1 is evidence of a missing pump, not a probe bug. Use flag 1 once the pump
exists — it also gives client-area coordinates directly.
- Capture the CLIENT area, or every measured band is shifted by the frame.
GetWindowRect includes the title bar and border, so a band at y=60 in client
coordinates lands on the title bar in a whole-window capture. Use
GetClientRect for dimensions with PrintWindow(hwnd, dc, 1), and measure
bands from the client origin (0, 0).
GetKeyState misses injected, posted and SendMessaged input. It reports
only the physical key state of the calling thread, so a probe (or an
automation tool) that posts Ctrl then F sees GetKeyState(VK_CONTROL) >= 0 and
the shortcut never fires — while real typing works, which makes it look like a
probe-only problem. Track modifiers from the message stream instead:
set a ctrl_down/shift_down flag on WM_KEYDOWN of the modifier and clear
it on WM_KEYUP, then read the flag. This also makes the shortcut unit-testable
without a window.
- A before/after pixel diff beats an ink-vs-modal band when the change is
low-contrast. A search bar whose fill matches the surrounding background
barely moves an ink count, so a band metric reports "no change" for a feature
that plainly rendered. Capture before and after and count differing pixels
directly (>200 is unambiguous); assert the reverse action restores the view
(diff returns to ~0).
CreateWindowExW takes the OUTER size; layout constants are usually the
CLIENT size. Passing WIN_WIDTH/WIN_HEIGHT straight to CreateWindowExW
when the layout is written against those constants leaves the client smaller by
the frame (title bar + borders), so the bottom strip — typically the message
input — lands below the visible edge and looks missing. Compute the outer size
with AdjustWindowRectEx(&mut RECT{right: WIN_WIDTH, bottom: WIN_HEIGHT}, WS_OVERLAPPEDWINDOW, 0, 0) and pass those dimensions. Tell-tale sign in a
capture: the client area is smaller than the layout constants (e.g. 884x600
where the code says 900x640).
- Do not use Escape to reset a probe's state. If the app maps Escape to
"close search, else hide the window", a probe that sends Escape first hides the
window, captures nothing, and reports a render failure that is really a
harness bug. Assert an idempotent pair instead: toggle twice and check that
each transition moves pixels and the third capture matches the first.
- Measure a suspected hot path before restructuring it. An audit note that
"the store saves on every message" is a hypothesis, not a finding. Time the
worst case the caps allow (the test doubles as the regression guard) and let
the number decide: here the write was 8.8ms against a 16.7ms frame budget, so
it was worth batching, but a 0.3ms write would have been left alone. Assert a
generous bound rather than an exact time so the test does not flake.
- A snapshot derived by assignment clobbers keys another writer inserted.
Publishing a store into a shared read-back map with
snapshot = store.clone()
wipes every key a different writer put there — control handlers, caches,
computed fields. The other writer's work silently disappears on the next
publish, and a correct change reads back as missing. Merge per key
(for (k, v) in store.snapshot() { map.insert(k, ...) }) so store values
refresh while foreign keys survive. This is distinct from staleness: the
data was there and the publish deleted it.
- Do not recreate GDI objects per frame. A DIBSection, bitmap or brush that is
deleted and recreated on every present is a full allocation plus a
whole-buffer copy each frame for an object that almost never changes. Create
once, keep the DC's original bitmap, and reallocate only when the size
actually changes. A bitmap selected into a DC must not be freed — restore the
DC's original bitmap with
SelectObject before DeleteObject, or GDI leaks
and eventually fails.
- Sharing a store behind
Arc<Mutex<>> when a consumer holds a raw pointer
is safe only if the allocation never moves. A *mut SettingsUI stored in a
window struct is a borrowed pointer into the store; wrapping the store in
Arc<Mutex<>> for cross-thread sharing keeps the heap allocation stable for
the Arc's lifetime, so the raw pointer stays valid. Moving the store (e.g. into
a Vec that reallocates, or returning it by value from a function) invalidates
every raw pointer into it. This is the standard pattern for a Win32 GDI app
where the render loop owns state and a window holds a borrowed pointer to it.
- A custom-drawn window has no OS tooltip, so each hit target needs one. A hand-rolled GDI window cannot fall back on the OS tooltip: a button whose meaning is not obvious from its label is a dead end. Add a
tooltip: String field to the hit target and fill it from the action in a constructor (HitTarget::new(rect, action)), so a new control cannot ship without one — the compiler enforces it. Store the tooltip text lookup (fn tooltip_for(&UiAction) -> String) next to the action enum so all strings are in one place. In the paint loop, read the hovered index and draw a small box near the cursor. The tooltip is drawn from win.draw_dc (the off-screen DC published for the frame), not from a local dc — draw_ui does not receive the DC directly.
- A modal file dialog blocks forever in a test.
GetSaveFileNameW and
GetOpenFileNameW are modal and wait for user input; calling them from a unit
test hangs the suite indefinitely. Make the path prompt injectable: add a
path_prompt: Option<fn(bool) -> Option<String>> field to the view, default
to None (use the real dialog), and let tests supply a closure that returns
a fixed path. The same applies to any blocking OS dialog (colour picker,
folder browser, print dialog).
- Batch a whole-store write; do not do it per change. A store that
serialises and writes everything on each mutation is O(n) per message. Mark it
dirty and flush at most once a second from the loop, plus once on shutdown.
Keep the immediate path as the default so existing tests and callers are
unchanged, and make turning the mode off flush anything pending so a switch
cannot drop a change. Write to a sibling file and rename, or a crash mid-write
leaves a truncated store and loses everything.
- A theme is not wired until something reads the setting. A
set_theme() that exists and is never called leaves the window permanently on
the default, and the setting screen still shows the control working. Grep for
the setter's call site: if the only hit is its definition, the feature is
inert. Wire it by reading the setting each frame and applying on change, and
apply the saved value before the first frame so a restart honours it.
- Hardcoded colour constants defeat a theme. Replacing them in the panels
but not the message bubbles, sidebar and input leaves a theme switch that
changes most of the window, which reads as a bug. Grep the draw code for the
old constants after introducing a theme; the fill helpers taking a stride
makes this easy to miss because the call sites changed shape at the same time.
WM_LBUTTONDBLCLK never arrives without CS_DBLCLKS on the window class.
Registering with only CS_HREDRAW | CS_VREDRAW means Windows never
synthesises the double-click message, so a double-click feature silently does
nothing however correct its handler is. Add CS_DBLCLKS to WNDCLASSEXW.style
whenever a control responds to a double-click.
- Escape is a shared key: a mode must consume it before the window does. If
Escape both leaves an edit mode and hides the window, pressing it while editing
must cancel the edit and return, not fall through to hide — otherwise a user
correcting a typo loses the window. Give the active mode the first look at the
key and delegate only when no mode is active.
- A keyboard-only user needs focus regions, not just a text box. Tab between
the panes, arrows within a list, Enter activates whatever holds focus — so
Enter's meaning must be region-dependent (send in the input, open in the
sidebar), and text entry must be gated on the focused region or keystrokes
silently edit a draft the user is not looking at. Draw a focus indicator: a
keyboard user cannot otherwise tell what Enter would activate.
- An undo stack must be written by the reversal, not by the recording setter.
Calling the normal setter from
undo() records the undo itself as a new change,
so the history grows on every reversal and redo becomes unreachable. Write the
value directly in undo/redo and move the entry between the two stacks. A
bulk reset must clear the history rather than leave a stack that no longer
describes the state.
- A snapshot mirrored only on write goes stale the moment anything changes the
store by another path. Publishing state into a shared read-back struct inside
the writer leaves every other mutator — undo, a loader, a reset — reporting the
old value, so a correct change looks like it did not take. Derive the snapshot
from the store on a timer instead, and throttle it: cloning it per frame is
wasted work when the only consumer polls.
- Case-insensitive search must take its offsets from the original text.
to_lowercase() can change byte length (some characters expand), so an offset
taken from the lowered string can land mid-character in the original and panic
on the slice that follows. Match against the original, and snap any snippet
window to is_char_boundary before slicing.
- The frame loop must not clone the world every frame. Cloning the whole
transcript, session list or status snapshot just to ask "is anything new?" is
the standard way a loop that should hit 75fps lands at 25fps. Grep the loop for
.to_vec() / .clone() / .list() / .messages(); gate each on a cheap
length or version signature, and throttle any publisher whose only consumer
polls. Measure before and after rather than assuming — see
references/render-loop-performance.md.
- Additive changes to a wire format must not change the shape existing clients
see. Insert the new optional field into the serialised object rather than
adding it to every variant of the response enum, then pin the no-field case with
a test asserting the exact serialised bytes. Details, plus the connection cap and
deferred-persistence patterns a local control surface needs, in
references/local-control-api.md.
- Text and fills must share one surface.
DrawTextW/TextOutW write to a GDI
device context; filling a Vec<u32> writes to your buffer. Different surfaces
means every glyph lands somewhere the app never blits from.
SetBkMode(dc, TRANSPARENT) before every text draw. GDI's default fills an
opaque rectangle behind each string using the current background brush, so a dark
UI gets a white box painted over every label and field — legible only where the
box happens to match. It is per-DC state that resets between DCs, so set it in
the same helper that selects the font, not at each call site.
WM_PAINT must call BeginPaint/EndPaint. Without them the DC is invalid
and GDI silently discards every drawing call — no error, no entry in the
debug output, just an untouched window. This looks identical to a bug in your
draw code.
- Lay out against
GetClientRect, never a height constant. The created window
size includes the frame, so the client area is smaller; adding a guessed frame
constant (WIN_HEIGHT + 80) is worse still, because the guess is wrong on every
DPI setting and theme. Panels and footers anchored to a constant end up cropped
or floating mid-window.
- Paint panels back-to-front, and never draw content at an x a later panel
covers. A sidebar painted after the body erases any body content drawn at the
sidebar's x range, which reads as "the labels never rendered" rather than as an
ordering mistake. Same for a title and a tab strip sharing an origin.
- Never conclude a window is broken from a black screenshot.
GetWindowDC +
GetDIBits returns all-black for a window rendering perfectly. Use
PrintWindow(hwnd, mem_dc, 2).
- Identify windows by class, not title. Sibling windows in one app routinely
share a title, so title matching screenshots the wrong one.
- Prove behaviour with assertions, not eyeballs. Colour count shows something
drew; only looking at it shows the right thing drew. Do both.
- Test UI states that are mutually exclusive separately. When a render path
is
if state_a { draw_x() } else if state_b { draw_y() }, the two controls
never appear together. A test that sets both states and asserts both tooltips
fails on the second one. Split into two tests, each setting only the state that
makes its control appear. The tell-tale failure is left: None, right: Some("...") for the second assertion — the control was never rendered, not
rendered without a tooltip.
- A handler that returns
Ok(()) proves only that it ran. Every OS
registration — tray icon, hotkey, hook, clipboard listener — must be checked by
the OS's own acknowledgement, and start() must propagate that rather than
assuming success. The same applies to any command queued for another thread:
{"queued": true} is the normal response for an accepted control request, so
it distinguishes nothing. Poll for the observable effect it was supposed to
cause — the value in the snapshot, the row in the list, the line in the log —
and treat the ack as merely proof the request was received.
See System tray.
- A
break inside a match inside a for leaves only the match. Loops
driven by event handlers need a flag set in the arm and tested after the loop.
- A config screen that saves is not a feature. Before reporting one done,
grep each field for a reader outside its own definition and the window that
edits it; zero readers means every control is a no-op however well it renders.
Check the two usual shapes by name: a runtime whose config is fixed at
construction (
new() + AgentConfig::default()), and a window holding a
copy of the data instead of a reference to the live store. Details and the
swappable-runtime recipe in
references/settings-editor-model.md.
- Settings must be loaded before being read. A
SettingsUI::new() creates
an empty settings object; calling load() before any read is required to
populate it from disk. Without this, saved settings are never applied at
startup — the default value is always used. This is the most common cause of
"my setting saved but didn't take effect" bugs.
- Window procs have no
self. An unsafe extern "system" fn window proc
cannot use self. Get the state pointer from GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut YourState, null-check it, then use (*ptr).field
for every access. Using self in a window proc is a compile error (E0424).
See references/window-proc-state-access.md
for the full pattern with code examples and common compile errors.
- Adding a new message handler (WM_MOUSEMOVE, WM_LBUTTONDOWN, etc.) to a
window proc follows a strict pattern: get the state pointer from
GetWindowLongPtrW, null-check, use (*ptr).field for every access, and
call InvalidateRect(hwnd, ptr::null_mut(), 0) to trigger a repaint.
Any deviation — using self, forgetting the null check, or not calling
InvalidateRect — causes a compile error or a silent no-op. When adding
a hover state, add a btn_hover: bool field to the struct, initialize it
in new(), update it in WM_MOUSEMOVE, and change the render color
based on it.
- A feature that compiles is not a feature that works. After adding a new
field, function, or message handler, grep for its call site in the render
path. If the only reference is the definition, the feature is inert — it
exists in the binary but never runs. This is the most common failure mode
in a large GUI overhaul: the struct gets the field, the proc gets the match
arm, but nothing calls either. Before reporting a feature done, trace from
the paint loop to the new code and confirm the path is reachable.
- The "field exists but render ignores it" gap is the most common. A field
is added to the state struct, a setter is written, but the render function
never reads the field — it still uses hardcoded values. Examples: a
search_query field that paint_rows() never filters on, a typing bool
that render_chat_window() never checks, a stats_overlay string that is
set but never drawn. Before reporting a feature done, grep the render
function for the field name and confirm it is actually used in a draw call.
- Handle
WM_ERASEBKGND by returning 1. Without this, the window
flickers on resize and repaint. Add WM_ERASEBKGND => 1 to every window proc's
match block — it is a one-liner that prevents visible flicker.
- Hybrid sleep for precise frame pacing.
std::thread::sleep on Windows has
~15ms granularity. For sub-2ms precision, sleep for target_ms - 2 ms, then
busy-wait with std::hint::spin_loop() until the target duration elapses.
Measure the deadline from the START of the frame, not from after the
sleep. Measuring from after the sleep adds the whole target again, so every
frame costs about twice its budget (a 13ms target produces ~30ms frames).
Call timeBeginPeriod(1) at startup and timeEndPeriod(1) at exit so the
sleep honours the requested duration rather than rounding up to ~15.6ms.
This is essential for consistent frame timing in a render loop.
- Register for
TaskbarCreated to recover from Explorer restarts. Call
RegisterWindowMessageW("TaskbarCreated") at startup, then handle the
returned message ID in the tray window proc to re-add the icon via
Shell_NotifyIconW(NIM_ADD, ...). Without this, the tray icon disappears
permanently after an Explorer crash or restart.
- Balloon notifications use
NIM_MODIFY with NIF_INFO. Call
Shell_NotifyIconW(NIM_MODIFY, ...) with uFlags = NIF_INFO and the
szInfoTitle/szInfo fields populated. The NIF_INFO flag must also be set
on the initial NIM_ADD for balloons to work.
- Dynamic context menus need
CreatePopupMenu/AppendMenuW/TrackPopupMenu.
Build the menu each time it is shown based on current state. Use MF_STRING
Use MF_STRING for items, MF_SEPARATOR for dividers, and MFS_CHECKED for toggle state — MFT_CHECKED does not exist in winapi and fails to compile.
TrackPopupMenu returns the chosen item ID — assign it to a variable, don't
discard it.
- Multiple GUI processes block all input. When two instances of a Win32 GUI
app run simultaneously, neither responds to mouse or keyboard — the user sees
windows but clicks do nothing. Before diagnosing input handling, check
tasklist for duplicate PIDs and kill all but one. This is the first thing to
verify when the user reports "I cannot interact with any GUI elements"
despite windows being visible.
- When three defects in a row share a shape, audit for that shape before
implementing anything else. The signal that a surface is inert — renders,
persists, reports success, and is read by nothing — is easy to miss once and
impossible to miss twice. On the third occurrence, stop implementing and
measure the whole class (scan every declared item for readers and writers,
turn the result into a CI gate). Listing your findings as "not wired up yet"
is a claim about code you have not checked, and it is often wrong: check for
written-but-never-read settings before calling anything inert.
- An audit built by parsing source can report PASS while being broken. A
clean audit result is only evidence if the audit found what it claims to look
for, so make the parser prove itself and print the picture it derived. Two
specific traps: slicing a Rust enum up to the next
pub enum swallows
everything between them (so the real variants vanish and a neighbouring enum's
appear instead), and a serde rename_all = "snake_case" wire name never string-
equals the PascalCase variant (nine_router_status != NineRouterStatus), so
every item reads as unknown. Both produced a total false PASS here. Have the
audit print counts and the full name lists per category, and sanity-check them
against something you already know is true before believing a clean run.
- Verify the far end, not the near end. Rendering correctly, persisting
without error, and returning
Ok(())/{"queued": true} are all evidence about
the code you just wrote, not about the feature. For anything that crosses a
boundary — window to store, store to runtime, request to handler — assert on
an observable at the destination (a value in a live readback, a log line, a
pixel), and if the boundary is a queue, poll for the effect rather than
trusting the ack.
- Write the destination probe before reporting the source done. Asking "what
are the optimal next steps?" right after a feature lands will surface whether
anything consumes it, and it is cheaper to find out before the user does. The
probe is also the only thing that survives as a regression test for the
wiring, which unit tests of the producer never are. If a cross-boundary
feature cannot be probed, say so explicitly rather than describing the
boundary as if it were verified.
- "What is next?" asked twice is a command, not a question. Answering it with
a re-ranked list the second time reads as stalling, and it burns the turn the
user spent to find out whether the work is real. When the same question comes
back after you already answered it, pick the highest-value item yourself and
build it; report what changed afterwards. Reserve the list for the first ask.
The same applies to "proceed", "properly proceed with all" and "optimally":
they mean act on the whole scope now, not plan it again.
- When adding
use imports to files with //! doc comments, place them
after all //! lines and after any #![cfg(windows)] inner attributes.
The order is: //! docs → #![...] attrs → use statements. A use line
inserted between //! lines or before #![cfg(windows)] causes an E0753
("expected outer doc comment") or E0753 ("inner attribute is not permitted")
that costs a build cycle to diagnose. When bulk-adding an import to many
files, check each file's first 5 lines before moving on.
- Deleting a dead module requires cleaning up its exclusive dependencies.
A module that is never constructed often pulls in dependencies nothing else
uses (e.g.
wgpu, winit, raw-window-handle, pollster). After deleting
the module, grep the remaining code for each dependency — if zero references,
remove it from Cargo.toml. But first verify no other code references them:
a dependency used only by the dead module is safe to remove, one used
elsewhere (e.g. hardware.rs using wgpu for GPU enumeration) must stay.
The tell-tale sign is a build error naming the removed crate.
- Replacing a GPU-enumeration dependency with Win32 requires more than
swapping the API call. Dropping
wgpu::Instance::enumerate_adapters() for
EnumDisplayDevicesW means rewriting the classification logic (vendor and
device type are no longer provided by the API), updating every consumer of
the old types (GpuDeviceType needs Copy if used by value in a match),
and adding the winuser feature to the winapi dependency in Cargo.toml.
A name-based classifier (classify_gpu_name) is the standard fallback — check
for vendor substrings and known integrated/virtual/software indicators.
- Test-only hooks must not be
#[cfg(test)] in a library used by another
crate's tests. The attribute applies only within its own crate, so the
consuming test binary sees nothing. Use #[doc(hidden)] pub and document it
as not part of the user-facing API, or gate the callers instead.
#[cfg(windows)] on an implementation does not gate its tests or its
imports. Tests calling a cfg-gated helper still compile on every target, so
cargo test --lib fails on Linux/macOS while a Windows build stays green; and
use x::{self, ...} names self on every platform, so a -D warnings build
off Windows fails on an import only the Windows path uses. Gate the tests with
the same attribute as the code they exercise rather than deleting them, and
split the import. A Windows-only dev loop cannot see either failure, so a
green local suite is evidence about Windows only.
Layout
BeginPaint for the DC you will blit to.
- Paint into a
CreateDIBSection (top-down: negative biHeight).
SelectObject the DIB into a memory DC.
- Publish that DC on your window state, then run the layout code.
BitBlt to the paint DC once — drawing direct to the window flickers.
EndPaint.
Read the surface size from GetClientRect and pass it down; full-height fills
guarantee no unpainted band, and it is what makes the footer land on the real
bottom edge.
let buf: &mut [u32] = std::slice::from_raw_parts_mut(raw as *mut u32, total);
win.draw_dc = Some(mem_dc); // text must land here
draw_ui(win, buf);
win.draw_dc = None;
Layout code reads win.draw_dc. Do not open a scratch DC per text call: that
is both wasteful and how the two-surface bug gets introduced.
winapi 0.3.9 signature traps
Grep the bindings rather than guessing — each of these cost real debugging time:
grep -n "pub fn CreateFontW" -A 16 ~/.cargo/registry/src/*/winapi-0.3.*/src/um/wingdi.rs
SelectObject / DeleteObject take *mut c_void. Wrap in one helper rather
than casting at each call site — and check the helper doesn't call itself.
CreateDIBSection's 4th parameter (ppvBits) is *mut *mut c_void, not
&mut *mut c_void. Passing &mut raw where raw: *mut c_void gives a
mismatched-types error. Use &mut raw as *mut _ as *mut _ — not
&raw as *const _ as *mut _, which compiles but creates a shared reference;
the compiler then rejects the later from_raw_parts_mut as UB because the
mutable pointer derives from a shared one. This applies to every
CreateDIBSection call site; grep for them all when one fails.
- A clippy "unused constant" warning does not mean the constant is dead.
Clippy sees only non-test code;
#[cfg(test)] blocks that assert on rendered
colours still reference the constant. Deleting it breaks cargo test while
cargo build and cargo clippy stay green — a failure only the test build
surfaces. Before deleting a constant clippy flags, grep the test modules for
the symbol; if found, keep it under #[cfg(test)] mod test_colors { ... }
with a #[cfg(test)] use re-export, and ensure the values match whatever the
production code (e.g. a theme system) actually renders.
- A temporary collection's
.as_ptr() is a dangling pointer the moment the
statement ends. "json\0".encode_utf16().collect::<Vec<u16>>().as_ptr()
builds a Vec, takes its pointer, then drops the Vec — the pointer is invalid
before the next line runs. Bind the collection to a named let first, then
take the pointer, so the lifetime spans the FFI call that reads it.
CreateFontW's fwWeight is i32; DEFAULT_CHARSET as u32 trips clippy as a
no-op cast.
GetBitmapDimensionEx(hbit: HBITMAP, lpsize: *mut SIZE); see the type-name
section below for which module each handle lives in.
CreateCompatibleBitmap gave a surface reporting 0x0 dimensions on this host,
and DrawTextW clips to the surface — so text silently vanished. Use
CreateDIBSection for any DC you draw text into. Do not assert on
GetBitmapDimensionEx as a size check.
#[allow(dead_code)] silences unused methods on the impl block, not on
the struct.
NOTIFYICONDATAW fields are all u32 — cbSize, uID, uFlags,
uCallbackMessage included. A uID: ICON_ID as usize is a compile error; the
shell rejects nothing here, it just fails to build. The struct is repr(packed)
on x86, so bind it mut and pass &mut data as *mut _ — Shell_NotifyIconW
takes a pointer, not a reference.
NIF_ICON | NIF_MESSAGE | NIF_TIP is already u32; as u32 is a no-op cast
that clippy rejects.
GetFileType(...) == FILE_TYPE_CHAR (not !=) decides whether stdin is a real
terminal. Getting this backwards inverts every prompt-suppression check; it
needs std::os::windows::io::AsRawHandle.
Making a window property a real setting
A style or alpha value hardcoded at CreateWindowExW makes its setting a no-op:
there is no path from the toggle to the existing window. Three rules when a
setting must reach a live window.
- Read the setting where the window is created, not once at startup, and pass
the resulting style in as a parameter. Reading it once and threading it as a
parameter is what makes the call site honest about its dependency.
- One window kind is not another.
replace_all over a duplicated creation
block also rewrites the chat/main window, which legitimately keeps its own
topmost. Patch by unique surrounding context, or scope the edit to the
function, or you will make the other window wrong while fixing this one.
- Cache the last applied value and act only on change. Applying
SetLayeredWindowAttributes or SetWindowPos every frame fights the window
manager and costs needless work; the app also stutters. Compare against a
tracked applied value.
Properties and their calls:
| Setting |
Creation |
Live change |
| always-on-top |
omit WS_EX_TOPMOST from ex_style |
SetWindowPos with HWND_TOPMOST/HWND_NOTOPMOST + SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE |
| transparency |
window must be WS_EX_LAYERED |
SetLayeredWindowAttributes(hwnd, 0, alpha, LWA_ALPHA) |
Give transparency a floor (clamp to something like 0.05): a settings store
that accepts 0 must not be able to make a window the user cannot see.
Handle types for these two calls are a common build-cycle sink: SetWindowPos
and SetLayeredWindowAttributes want *mut HWND__, which DECLARE_HANDLE! puts
in shared::windef, while winuser::HWND is a private alias. A *mut c_void
handle needs as *mut winapi::shared::windef::HWND__, and there is no
dereference — *hwnd as *mut ..., not *hwnd as *mut ... of a deref.
WS_EX_TOPMOST is DWORD from shared::minwindef, and COLORREF is a type
alias, so 0 as COLORREF rather than a tuple-struct call.
Building an editor window
Three tabs beats one long form: a single scrolling list of twenty fields is how
settings screens become unusable. Click-to-cycle suits enum choices; -/+
steppers suit bounded numbers; reserve real text entry for name/model fields.
Show the selected option's description so the choice is informed.
Wire every control the layout draws. A panel that renders but registers no hit
target is the classic dead-control bug, so assert that every tab produces at
least one target, that Save is absent while the form is invalid, and that a
read-only record offers Duplicate but not Delete. Show unsaved state persistently
(a marker plus an enabled Revert) rather than only in a confirm-on-close dialog.
Expose the editor's events to the app rather than letting it mutate state itself:
saves and deletes go through the app's store so the same data is visible over IPC
and MCP afterwards, and there is one implementation of id-uniqueness and
validation.
Asserting on pixels
GDI writes BGRA; SetTextColor takes 0x00BBGGRR. Comparing the DIB's u32
values to your own 0x00BBGGRR constants looks correct and is wrong except for
symmetric colours (0xE8E8EC reads back as 0xECE8E8).
Antialiasing also yields many near-miss values, so match channel-wise with a
tolerance rather than by equality:
let near = |target: u32| {
let d = |shift: u32| (((pixel >> shift) & 0xFF) as i32
- ((target >> shift) & 0xFF) as i32).abs();
d(0) <= 90 && d(8) <= 90 && d(16) <= 90
};
Quick health check on a capture:
| Distinct colours |
Meaning |
| 1 |
nothing rendered |
| 150+ |
backgrounds, borders, antialiased glyphs all present |
A distinct-colour count is a floor, not a pass. “41 distinct colours” is
consistent with a correct window and also with white boxes stamped over every
label. Assert on regions: for each panel you care about, count pixels
differing from that region's modal (background) colour. A label column reading 0%
inked means nothing was drawn there no matter how colourful the window is overall.
A capture that cannot be read proves nothing
Validate the capture file before drawing conclusions from it. A BMP header packed
via a ctypes struct gets padded to 8 bytes, so the offsets silently do not line
up; the resulting "screenshot" decodes to nonsense dimensions and a 100%-white
histogram, which reads exactly like a blank window. Write the headers with
struct.pack and assert the decoded width/height match what you asked for. Also
verify the dominant colours are the palette you specified — if you chose
#141212 for the background and the histogram says #FFFFFF, the window did not
paint, whatever the colour count says.
Let vision, but do not depend on it
Reading a screenshot with a vision model is the best check available, and it gets
rate-limited (HTTP 429) on shared keys. Have a pixel-level fallback ready so
verification degrades instead of stopping: region ink coverage, dominant-colour
comparison, and size assertions. Report which you used, and when vision was
unavailable say the visual assessment is unverified rather than implying you saw it.
Verifying a change that adds a command or setting
A probe that launches the built binary and drives the new control path is worth
more than any unit test, because it proves the wiring between socket, queue and
handler. Two failure modes make such a probe lie to you:
- A stale binary reports the feature as missing. Preferring a fixed path
(
target/release/app.exe) runs yesterday's build, so a newly added handler looks
like it never runs. Select the newest binary by mtime:
max([p for p in candidates if p.exists()], key=lambda p: p.stat().st_mtime).
- Reading state back through a shared snapshot picks up the previous step's
value. Poll for the value you expect to be written (match on its id), not
merely for "something non-empty", or the assertions silently pass against
whatever landed earlier.
Make the probe clean up after itself. Agents and settings created by a probe
persist to the user's real store and make the next run fail on collisions, which
reads as a product bug. Delete created ids on the way out, and sweep leftovers
from prior runs at the start.
Prefer reading the app's own stdout when a probe fails. [Agents] Saved 'x' over IPC distinguishes "the handler never ran" from "the handler ran and the readback
path is wrong" — a distinction that unit tests cannot make.
Unit-testing a GUI with no window
Have the test path use the same surface the window does, and return both the
filled slice and the DIB surface — they hold different things, so asserting on
the wrong one gives a false pass or a false failure.
Two tests that earn their place:
- glyph pixels reach the DIB surface (catches the two-surface bug)
- layout fill colours reach the slice
Then test event semantics, where GUI bugs actually live: Enter sends and
clears the field, blank input sends nothing, whitespace is trimmed, Backspace on
empty is harmless, WM_CHAR control characters are not inserted as text, the
topmost hit target wins over the one beneath it, scroll clamps at both ends.
If a GUI test suite hangs, grep for a helper that calls its own name before
suspecting GDI — self-recursion from a refactor looks exactly like a hang.
System tray lifecycle
A tray implementation that compiles can still be entirely inert, and the failure
is invisible until someone clicks. Four separate things must all be true; any one
missing makes every menu item a no-op while the code reads as complete.
- The icon must actually be registered. Creating a hidden message wi
…(truncated)
1---2name: win32-gui-rendering3description: Build and verify hand-rolled Win32/GDI desktop UIs in Rust.4version: 1.0.05author: Hermes Agent6license: MIT7metadata:8 source: https://skillmd.com/skills/loopyluci/win32-gui-rendering9 hermes:10 tags: [windows, win32, gdi, rust, gui, rendering]11 related_skills: [windows-rust-android-build-env]12---1314# Win32 GDI GUI in Rust1516For desktop UIs built directly on GDI with no winit/egui/Tauri: laying out a17window, drawing text, and **proving it rendered**. The recurring failure is18silent — everything looks fine until you look at the pixels.1920## When to Use2122- Writing or debugging a window that draws itself via GDI in Rust23- Text renders nowhere, or only some labels appear24- A window renders pure white, or white boxes over the text25- A window's controls land off-screen or float in the wrong place26- A form's labels are missing even though the fields draw27- A window screenshots as solid black and you cannot tell whether it is broken28- Sibling windows share a title and you keep capturing the wrong one29- GUI unit tests hang, or pass against code you know is wrong30- A tray icon, context menu, or minimise-to-tray that compiles and reports31 success but does nothing when clicked32- Building a settings/agent/profile editor: what to model first, and the33 serialization rules that keep saved data readable (see34 [references/settings-editor-model.md](references/settings-editor-model.md))35- Deciding which settings to show, disable or label as unimplemented — the36 live / read-only-mirror / inert classification and the CI scan that keeps it37 honest (same reference)38- A list of "things not wired up yet" that you suspect is wrong39- Auditing whether a declared surface is consumed at all — settings keys, MCP40 tools, IPC commands — and turning the result into a CI gate41 (see [references/inert-surface-audits.md](references/inert-surface-audits.md))42- The UI stutters, or the loop misses its frame target and the average FPS hides43 it (see [references/render-loop-performance.md](references/render-loop-performance.md))44- Adding a command to the app's control surface, or a client needs to match45 replies to requests (see [references/local-control-api.md](references/local-control-api.md))4647## Always-on rules4849- **A window that renders but ignores every click and keystroke has no50 message pump.** A window proc is only ever invoked by the dispatcher, so if51 the main loop never calls `PeekMessage`/`DispatchMessage` (or `GetMessage`),52 the window receives no `WM_PAINT`, no `WM_KEYDOWN`/`WM_CHAR`, no53 `WM_LBUTTONDOWN` and no `WM_MOUSEWHEEL` — every control is dead no matter how54 correctly it is written. Grep the render loop for `PeekMessage`/`DispatchMessage`55 before diagnosing input handling: an app can have a working pump on one56 thread (an overlay) and none on the thread that owns the main window, which57 is what makes the window look alive while ignoring everything. Fix:58 `PeekMessageW(&mut msg, null_mut(), 0, 0, PM_REMOVE)` in a `while` loop at the59 top of the frame loop, `TranslateMessage` + `DispatchMessageW` each, and break60 on `WM_QUIT`. The tell-tale symptom in a probe: a colour count far too low for61 the layout (e.g. 23 where a full UI needs 150+).62- **`PrintWindow` flag 1 hangs when the window thread does not pump.**63 `PW_CLIENTONLY` (1) sends `WM_PRINTCLIENT` to the app thread, so it blocks64 forever on a window whose thread is not pumping; `PW_RENDERFULLCONTENT` (2)65 reads the DWM redirection surface instead, which returns *stale* content rather66 than hanging. A probe that captures successfully with flag 2 but hangs with67 flag 1 is evidence of a missing pump, not a probe bug. Use flag 1 once the pump68 exists — it also gives client-area coordinates directly.69- **Capture the CLIENT area, or every measured band is shifted by the frame.**70 `GetWindowRect` includes the title bar and border, so a band at y=60 in client71 coordinates lands on the title bar in a whole-window capture. Use72 `GetClientRect` for dimensions with `PrintWindow(hwnd, dc, 1)`, and measure73 bands from the client origin (0, 0).74- **`GetKeyState` misses injected, posted and `SendMessage`d input.** It reports75 only the *physical* key state of the calling thread, so a probe (or an76 automation tool) that posts Ctrl then F sees `GetKeyState(VK_CONTROL) >= 0` and77 the shortcut never fires — while real typing works, which makes it look like a78 probe-only problem. Track modifiers from the message stream instead:79 set a `ctrl_down`/`shift_down` flag on `WM_KEYDOWN` of the modifier and clear80 it on `WM_KEYUP`, then read the flag. This also makes the shortcut unit-testable81 without a window.82- **A before/after pixel diff beats an ink-vs-modal band when the change is83 low-contrast.** A search bar whose fill matches the surrounding background84 barely moves an ink count, so a band metric reports "no change" for a feature85 that plainly rendered. Capture before and after and count differing pixels86 directly (>200 is unambiguous); assert the reverse action restores the view87 (diff returns to ~0).88- **`CreateWindowExW` takes the OUTER size; layout constants are usually the89 CLIENT size.** Passing `WIN_WIDTH`/`WIN_HEIGHT` straight to `CreateWindowExW`90 when the layout is written against those constants leaves the client smaller by91 the frame (title bar + borders), so the bottom strip — typically the message92 input — lands below the visible edge and looks missing. Compute the outer size93 with `AdjustWindowRectEx(&mut RECT{right: WIN_WIDTH, bottom: WIN_HEIGHT},94 WS_OVERLAPPEDWINDOW, 0, 0)` and pass those dimensions. Tell-tale sign in a95 capture: the client area is smaller than the layout constants (e.g. 884x60096 where the code says 900x640).97- **Do not use Escape to reset a probe's state.** If the app maps Escape to98 "close search, else hide the window", a probe that sends Escape first hides the99 window, captures nothing, and reports a render failure that is really a100 harness bug. Assert an idempotent pair instead: toggle twice and check that101 each transition moves pixels and the third capture matches the first.102- **Measure a suspected hot path before restructuring it.** An audit note that103 "the store saves on every message" is a hypothesis, not a finding. Time the104 worst case the caps allow (the test doubles as the regression guard) and let105 the number decide: here the write was 8.8ms against a 16.7ms frame budget, so106 it was worth batching, but a 0.3ms write would have been left alone. Assert a107 generous bound rather than an exact time so the test does not flake.108- **A snapshot derived by assignment clobbers keys another writer inserted.**109 Publishing a store into a shared read-back map with `snapshot = store.clone()`110 wipes every key a *different* writer put there — control handlers, caches,111 computed fields. The other writer's work silently disappears on the next112 publish, and a correct change reads back as missing. Merge per key113 (`for (k, v) in store.snapshot() { map.insert(k, ...) }`) so store values114 refresh while foreign keys survive. This is distinct from staleness: the115 data was there and the publish deleted it.116- **Do not recreate GDI objects per frame.** A DIBSection, bitmap or brush that is117 deleted and recreated on every present is a full allocation plus a118 whole-buffer copy each frame for an object that almost never changes. Create119 once, keep the DC's original bitmap, and reallocate only when the size120 actually changes. A bitmap selected into a DC must not be freed — restore the121 DC's original bitmap with `SelectObject` before `DeleteObject`, or GDI leaks122 and eventually fails.123- **Sharing a store behind `Arc<Mutex<>>` when a consumer holds a raw pointer124 is safe only if the allocation never moves.** A `*mut SettingsUI` stored in a125 window struct is a borrowed pointer into the store; wrapping the store in126 `Arc<Mutex<>>` for cross-thread sharing keeps the heap allocation stable for127 the Arc's lifetime, so the raw pointer stays valid. Moving the store (e.g. into128 a `Vec` that reallocates, or returning it by value from a function) invalidates129 every raw pointer into it. This is the standard pattern for a Win32 GDI app130 where the render loop owns state and a window holds a borrowed pointer to it.131- **A custom-drawn window has no OS tooltip, so each hit target needs one.** A hand-rolled GDI window cannot fall back on the OS tooltip: a button whose meaning is not obvious from its label is a dead end. Add a `tooltip: String` field to the hit target and fill it from the action in a constructor (`HitTarget::new(rect, action)`), so a new control cannot ship without one — the compiler enforces it. Store the tooltip text lookup (`fn tooltip_for(&UiAction) -> String`) next to the action enum so all strings are in one place. In the paint loop, read the hovered index and draw a small box near the cursor. The tooltip is drawn from `win.draw_dc` (the off-screen DC published for the frame), not from a local `dc` — `draw_ui` does not receive the DC directly.132- **A modal file dialog blocks forever in a test.** `GetSaveFileNameW` and133 `GetOpenFileNameW` are modal and wait for user input; calling them from a unit134 test hangs the suite indefinitely. Make the path prompt injectable: add a135 `path_prompt: Option<fn(bool) -> Option<String>>` field to the view, default136 to `None` (use the real dialog), and let tests supply a closure that returns137 a fixed path. The same applies to any blocking OS dialog (colour picker,138 folder browser, print dialog).139- **Batch a whole-store write; do not do it per change.** A store that140 serialises and writes everything on each mutation is O(n) per message. Mark it141 dirty and flush at most once a second from the loop, plus once on shutdown.142 Keep the immediate path as the default so existing tests and callers are143 unchanged, and make turning the mode off flush anything pending so a switch144 cannot drop a change. Write to a sibling file and rename, or a crash mid-write145 leaves a truncated store and loses everything.146- **A theme is not wired until something reads the setting.** A147 `set_theme()` that exists and is never called leaves the window permanently on148 the default, and the setting screen still shows the control working. Grep for149 the setter's call site: if the only hit is its definition, the feature is150 inert. Wire it by reading the setting each frame and applying on change, and151 apply the saved value before the first frame so a restart honours it.152- **Hardcoded colour constants defeat a theme.** Replacing them in the panels153 but not the message bubbles, sidebar and input leaves a theme switch that154 changes most of the window, which reads as a bug. Grep the draw code for the155 old constants after introducing a theme; the fill helpers taking a stride156 makes this easy to miss because the call sites changed shape at the same time.157- **`WM_LBUTTONDBLCLK` never arrives without `CS_DBLCLKS` on the window class.**158 Registering with only `CS_HREDRAW | CS_VREDRAW` means Windows never159 synthesises the double-click message, so a double-click feature silently does160 nothing however correct its handler is. Add `CS_DBLCLKS` to `WNDCLASSEXW.style`161 whenever a control responds to a double-click.162- **Escape is a shared key: a mode must consume it before the window does.** If163 Escape both leaves an edit mode and hides the window, pressing it while editing164 must cancel the edit and return, not fall through to hide — otherwise a user165 correcting a typo loses the window. Give the active mode the first look at the166 key and delegate only when no mode is active.167- **A keyboard-only user needs focus regions, not just a text box.** Tab between168 the panes, arrows within a list, Enter activates whatever holds focus — so169 Enter's meaning must be region-dependent (send in the input, open in the170 sidebar), and text entry must be gated on the focused region or keystrokes171 silently edit a draft the user is not looking at. Draw a focus indicator: a172 keyboard user cannot otherwise tell what Enter would activate.173- **An undo stack must be written by the reversal, not by the recording setter.**174 Calling the normal setter from `undo()` records the undo itself as a new change,175 so the history grows on every reversal and redo becomes unreachable. Write the176 value directly in `undo`/`redo` and move the entry between the two stacks. A177 bulk reset must clear the history rather than leave a stack that no longer178 describes the state.179- **A snapshot mirrored only on write goes stale the moment anything changes the180 store by another path.** Publishing state into a shared read-back struct inside181 the writer leaves every other mutator — undo, a loader, a reset — reporting the182 old value, so a correct change looks like it did not take. Derive the snapshot183 from the store on a timer instead, and throttle it: cloning it per frame is184 wasted work when the only consumer polls.185- **Case-insensitive search must take its offsets from the original text.**186 `to_lowercase()` can change byte length (some characters expand), so an offset187 taken from the lowered string can land mid-character in the original and panic188 on the slice that follows. Match against the original, and snap any snippet189 window to `is_char_boundary` before slicing.190- **The frame loop must not clone the world every frame.** Cloning the whole191 transcript, session list or status snapshot just to ask "is anything new?" is192 the standard way a loop that should hit 75fps lands at 25fps. Grep the loop for193 `.to_vec()` / `.clone()` / `.list()` / `.messages()`; gate each on a cheap194 length or version signature, and throttle any publisher whose only consumer195 polls. Measure before and after rather than assuming — see196 [references/render-loop-performance.md](references/render-loop-performance.md).197- **Additive changes to a wire format must not change the shape existing clients198 see.** Insert the new optional field into the serialised object rather than199 adding it to every variant of the response enum, then pin the no-field case with200 a test asserting the exact serialised bytes. Details, plus the connection cap and201 deferred-persistence patterns a local control surface needs, in202 [references/local-control-api.md](references/local-control-api.md).203- **Text and fills must share one surface.** `DrawTextW`/`TextOutW` write to a GDI204 device context; filling a `Vec<u32>` writes to your buffer. Different surfaces205 means every glyph lands somewhere the app never blits from.206- **`SetBkMode(dc, TRANSPARENT)` before every text draw.** GDI's default fills an207 opaque rectangle behind each string using the current background brush, so a dark208 UI gets a white box painted over every label and field — legible only where the209 box happens to match. It is per-DC state that resets between DCs, so set it in210 the same helper that selects the font, not at each call site.211- **`WM_PAINT` must call `BeginPaint`/`EndPaint`.** Without them the DC is invalid212 and GDI **silently discards every drawing call** — no error, no entry in the213 debug output, just an untouched window. This looks identical to a bug in your214 draw code.215- **Lay out against `GetClientRect`, never a height constant.** The created window216 size includes the frame, so the client area is smaller; adding a guessed frame217 constant (`WIN_HEIGHT + 80`) is worse still, because the guess is wrong on every218 DPI setting and theme. Panels and footers anchored to a constant end up cropped219 or floating mid-window.220- **Paint panels back-to-front, and never draw content at an x a later panel221 covers.** A sidebar painted *after* the body erases any body content drawn at the222 sidebar's x range, which reads as "the labels never rendered" rather than as an223 ordering mistake. Same for a title and a tab strip sharing an origin.224- **Never conclude a window is broken from a black screenshot.** `GetWindowDC` +225 `GetDIBits` returns all-black for a window rendering perfectly. Use226 `PrintWindow(hwnd, mem_dc, 2)`.227- **Identify windows by class, not title.** Sibling windows in one app routinely228 share a title, so title matching screenshots the wrong one.229- **Prove behaviour with assertions, not eyeballs.** Colour count shows *something*230 drew; only looking at it shows the *right* thing drew. Do both.231- **Test UI states that are mutually exclusive separately.** When a render path232 is `if state_a { draw_x() } else if state_b { draw_y() }`, the two controls233 never appear together. A test that sets both states and asserts both tooltips234 fails on the second one. Split into two tests, each setting only the state that235 makes its control appear. The tell-tale failure is `left: None, right:236 Some("...")` for the second assertion — the control was never rendered, not237 rendered without a tooltip.238- **A handler that returns `Ok(())` proves only that it ran.** Every OS239 registration — tray icon, hotkey, hook, clipboard listener — must be checked by240 the OS's own acknowledgement, and `start()` must propagate that rather than241 assuming success. The same applies to any command queued for another thread:242 `{"queued": true}` is the *normal* response for an accepted control request, so243 it distinguishes nothing. Poll for the observable effect it was supposed to244 cause — the value in the snapshot, the row in the list, the line in the log —245 and treat the ack as merely proof the request was received.246 See [System tray](#system-tray-lifecycle).247- **A `break` inside a `match` inside a `for` leaves only the match.** Loops248 driven by event handlers need a flag set in the arm and tested after the loop.249- **A config screen that saves is not a feature.** Before reporting one done,250 grep each field for a reader outside its own definition and the window that251 edits it; zero readers means every control is a no-op however well it renders.252 Check the two usual shapes by name: a runtime whose config is fixed at253 construction (`new()` + `AgentConfig::default()`), and a window holding a254 *copy* of the data instead of a reference to the live store. Details and the255 swappable-runtime recipe in256 [references/settings-editor-model.md](references/settings-editor-model.md).257- **Settings must be loaded before being read.** A `SettingsUI::new()` creates258 an empty settings object; calling `load()` before any read is required to259 populate it from disk. Without this, saved settings are never applied at260 startup — the default value is always used. This is the most common cause of261 "my setting saved but didn't take effect" bugs.262- **Window procs have no `self`.** An `unsafe extern "system" fn` window proc263 cannot use `self`. Get the state pointer from `GetWindowLongPtrW(hwnd,264 GWLP_USERDATA) as *mut YourState`, null-check it, then use `(*ptr).field`265 for every access. Using `self` in a window proc is a compile error (E0424).266 See [references/window-proc-state-access.md](references/window-proc-state-access.md)267 for the full pattern with code examples and common compile errors.268- **Adding a new message handler (WM_MOUSEMOVE, WM_LBUTTONDOWN, etc.) to a269 window proc follows a strict pattern:** get the state pointer from270 `GetWindowLongPtrW`, null-check, use `(*ptr).field` for every access, and271 call `InvalidateRect(hwnd, ptr::null_mut(), 0)` to trigger a repaint.272 Any deviation — using `self`, forgetting the null check, or not calling273 `InvalidateRect` — causes a compile error or a silent no-op. When adding274 a hover state, add a `btn_hover: bool` field to the struct, initialize it275 in `new()`, update it in `WM_MOUSEMOVE`, and change the render color276 based on it.277- **A feature that compiles is not a feature that works.** After adding a new278 field, function, or message handler, grep for its call site in the render279 path. If the only reference is the definition, the feature is inert — it280 exists in the binary but never runs. This is the most common failure mode281 in a large GUI overhaul: the struct gets the field, the proc gets the match282 arm, but nothing calls either. Before reporting a feature done, trace from283 the paint loop to the new code and confirm the path is reachable.284- **The "field exists but render ignores it" gap is the most common.** A field285 is added to the state struct, a setter is written, but the render function286 never reads the field — it still uses hardcoded values. Examples: a287 `search_query` field that `paint_rows()` never filters on, a `typing` bool288 that `render_chat_window()` never checks, a `stats_overlay` string that is289 set but never drawn. Before reporting a feature done, grep the render290 function for the field name and confirm it is actually used in a draw call.291- **Handle `WM_ERASEBKGND` by returning `1`.** Without this, the window292 flickers on resize and repaint. Add `WM_ERASEBKGND => 1` to every window proc's293 match block — it is a one-liner that prevents visible flicker.294- **Hybrid sleep for precise frame pacing.** `std::thread::sleep` on Windows has295 ~15ms granularity. For sub-2ms precision, sleep for `target_ms - 2` ms, then296 busy-wait with `std::hint::spin_loop()` until the target duration elapses.297 **Measure the deadline from the START of the frame, not from after the298 sleep.** Measuring from after the sleep adds the whole target again, so every299 frame costs about twice its budget (a 13ms target produces ~30ms frames).300 Call `timeBeginPeriod(1)` at startup and `timeEndPeriod(1)` at exit so the301 sleep honours the requested duration rather than rounding up to ~15.6ms.302 This is essential for consistent frame timing in a render loop.303- **Register for `TaskbarCreated` to recover from Explorer restarts.** Call304 `RegisterWindowMessageW("TaskbarCreated")` at startup, then handle the305 returned message ID in the tray window proc to re-add the icon via306 `Shell_NotifyIconW(NIM_ADD, ...)`. Without this, the tray icon disappears307 permanently after an Explorer crash or restart.308- **Balloon notifications use `NIM_MODIFY` with `NIF_INFO`.** Call309 `Shell_NotifyIconW(NIM_MODIFY, ...)` with `uFlags = NIF_INFO` and the310 `szInfoTitle`/`szInfo` fields populated. The `NIF_INFO` flag must also be set311 on the initial `NIM_ADD` for balloons to work.312- **Dynamic context menus need `CreatePopupMenu`/`AppendMenuW`/`TrackPopupMenu`.**313 Build the menu each time it is shown based on current state. Use `MF_STRING`314 Use `MF_STRING` for items, `MF_SEPARATOR` for dividers, and `MFS_CHECKED` for toggle state — `MFT_CHECKED` does not exist in winapi and fails to compile.315 `TrackPopupMenu` returns the chosen item ID — assign it to a variable, don't316 discard it.317- **Multiple GUI processes block all input.** When two instances of a Win32 GUI318 app run simultaneously, neither responds to mouse or keyboard — the user sees319 windows but clicks do nothing. Before diagnosing input handling, check320 `tasklist` for duplicate PIDs and kill all but one. This is the first thing to321 verify when the user reports "I cannot interact with any GUI elements"322 despite windows being visible.323- **When three defects in a row share a shape, audit for that shape before324 implementing anything else.** The signal that a surface is inert — renders,325 persists, reports success, and is read by nothing — is easy to miss once and326 impossible to miss twice. On the third occurrence, stop implementing and327 *measure* the whole class (scan every declared item for readers and writers,328 turn the result into a CI gate). Listing your findings as "not wired up yet"329 is a claim about code you have not checked, and it is often wrong: check for330 written-but-never-read settings before calling anything inert.331- **An audit built by parsing source can report PASS while being broken.** A332 clean audit result is only evidence if the audit found what it claims to look333 for, so make the parser prove itself and print the picture it derived. Two334 specific traps: slicing a Rust enum up to the *next* `pub enum` swallows335 everything between them (so the real variants vanish and a neighbouring enum's336 appear instead), and a serde `rename_all = "snake_case"` wire name never string-337 equals the PascalCase variant (`nine_router_status` != `NineRouterStatus`), so338 every item reads as unknown. Both produced a total false PASS here. Have the339 audit print counts and the full name lists per category, and sanity-check them340 against something you already know is true before believing a clean run.341- **Verify the far end, not the near end.** Rendering correctly, persisting342 without error, and returning `Ok(())`/`{"queued": true}` are all evidence about343 the code you just wrote, not about the feature. For anything that crosses a344 boundary — window to store, store to runtime, request to handler — assert on345 an observable at the destination (a value in a live readback, a log line, a346 pixel), and if the boundary is a queue, poll for the effect rather than347 trusting the ack.348- **Write the destination probe before reporting the source done.** Asking "what349 are the optimal next steps?" right after a feature lands will surface whether350 anything consumes it, and it is cheaper to find out before the user does. The351 probe is also the only thing that survives as a regression test for the352 wiring, which unit tests of the producer never are. If a cross-boundary353 feature cannot be probed, say so explicitly rather than describing the354 boundary as if it were verified.355- **"What is next?" asked twice is a command, not a question.** Answering it with356 a re-ranked list the second time reads as stalling, and it burns the turn the357 user spent to find out whether the work is real. When the same question comes358 back after you already answered it, pick the highest-value item yourself and359 build it; report what changed afterwards. Reserve the list for the first ask.360 The same applies to "proceed", "properly proceed with all" and "optimally":361 they mean act on the whole scope now, not plan it again.362- **When adding `use` imports to files with `//!` doc comments, place them363 after all `//!` lines and after any `#![cfg(windows)]` inner attributes.**364 The order is: `//!` docs → `#![...]` attrs → `use` statements. A `use` line365 inserted between `//!` lines or before `#![cfg(windows)]` causes an E0753366 ("expected outer doc comment") or E0753 ("inner attribute is not permitted")367 that costs a build cycle to diagnose. When bulk-adding an import to many368 files, check each file's first 5 lines before moving on.369- **Deleting a dead module requires cleaning up its exclusive dependencies.**370 A module that is never constructed often pulls in dependencies nothing else371 uses (e.g. `wgpu`, `winit`, `raw-window-handle`, `pollster`). After deleting372 the module, grep the remaining code for each dependency — if zero references,373 remove it from `Cargo.toml`. But first verify no other code references them:374 a dependency used only by the dead module is safe to remove, one used375 elsewhere (e.g. `hardware.rs` using `wgpu` for GPU enumeration) must stay.376 The tell-tale sign is a build error naming the removed crate.377- **Replacing a GPU-enumeration dependency with Win32 requires more than378 swapping the API call.** Dropping `wgpu::Instance::enumerate_adapters()` for379 `EnumDisplayDevicesW` means rewriting the classification logic (vendor and380 device type are no longer provided by the API), updating every consumer of381 the old types (`GpuDeviceType` needs `Copy` if used by value in a `match`),382 and adding the `winuser` feature to the `winapi` dependency in `Cargo.toml`.383 A name-based classifier (`classify_gpu_name`) is the standard fallback — check384 for vendor substrings and known integrated/virtual/software indicators.385- **Test-only hooks must not be `#[cfg(test)]` in a library used by another386 crate's tests.** The attribute applies only within its own crate, so the387 consuming test binary sees nothing. Use `#[doc(hidden)] pub` and document it388 as not part of the user-facing API, or gate the *callers* instead.389- **`#[cfg(windows)]` on an implementation does not gate its tests or its390 imports.** Tests calling a cfg-gated helper still compile on every target, so391 `cargo test --lib` fails on Linux/macOS while a Windows build stays green; and392 `use x::{self, ...}` names `self` on every platform, so a `-D warnings` build393 off Windows fails on an import only the Windows path uses. Gate the tests with394 the same attribute as the code they exercise rather than deleting them, and395 split the import. A Windows-only dev loop cannot see either failure, so a396 green local suite is evidence about Windows only.397398## Layout3994001. `BeginPaint` for the DC you will blit to.4012. Paint into a `CreateDIBSection` (top-down: negative `biHeight`).4023. `SelectObject` the DIB into a memory DC.4034. Publish that DC on your window state, *then* run the layout code.4045. `BitBlt` to the paint DC once — drawing direct to the window flickers.4056. `EndPaint`.406407Read the surface size from `GetClientRect` and pass it down; full-height fills408guarantee no unpainted band, and it is what makes the footer land on the real409bottom edge.410411```rust412let buf: &mut [u32] = std::slice::from_raw_parts_mut(raw as *mut u32, total);413win.draw_dc = Some(mem_dc); // text must land here414draw_ui(win, buf);415win.draw_dc = None;416```417418Layout code reads `win.draw_dc`. Do **not** open a scratch DC per text call: that419is both wasteful and how the two-surface bug gets introduced.420421## winapi 0.3.9 signature traps422423Grep the bindings rather than guessing — each of these cost real debugging time:424425```bash426grep -n "pub fn CreateFontW" -A 16 ~/.cargo/registry/src/*/winapi-0.3.*/src/um/wingdi.rs427```428429- `SelectObject` / `DeleteObject` take `*mut c_void`. Wrap in one helper rather430 than casting at each call site — and check the helper doesn't call itself.431- `CreateDIBSection`'s 4th parameter (`ppvBits`) is `*mut *mut c_void`, not432 `&mut *mut c_void`. Passing `&mut raw` where `raw: *mut c_void` gives a433 mismatched-types error. Use `&mut raw as *mut _ as *mut _` — **not**434 `&raw as *const _ as *mut _`, which compiles but creates a shared reference;435 the compiler then rejects the later `from_raw_parts_mut` as UB because the436 mutable pointer derives from a shared one. This applies to every437 `CreateDIBSection` call site; grep for them all when one fails.438- **A clippy "unused constant" warning does not mean the constant is dead.**439 Clippy sees only non-test code; `#[cfg(test)]` blocks that assert on rendered440 colours still reference the constant. Deleting it breaks `cargo test` while441 `cargo build` and `cargo clippy` stay green — a failure only the test build442 surfaces. Before deleting a constant clippy flags, grep the test modules for443 the symbol; if found, keep it under `#[cfg(test)] mod test_colors { ... }`444 with a `#[cfg(test)] use` re-export, and ensure the values match whatever the445 production code (e.g. a theme system) actually renders.446- **A temporary collection's `.as_ptr()` is a dangling pointer the moment the447 statement ends.** `"json\0".encode_utf16().collect::<Vec<u16>>().as_ptr()`448 builds a Vec, takes its pointer, then drops the Vec — the pointer is invalid449 before the next line runs. Bind the collection to a named `let` first, then450 take the pointer, so the lifetime spans the FFI call that reads it.451- `CreateFontW`'s `fwWeight` is `i32`; `DEFAULT_CHARSET as u32` trips clippy as a452 no-op cast.453- `GetBitmapDimensionEx(hbit: HBITMAP, lpsize: *mut SIZE)`; see the type-name454 section below for which module each handle lives in.455- `CreateCompatibleBitmap` gave a surface reporting 0x0 dimensions on this host,456 and `DrawTextW` clips to the surface — so text silently vanished. Use457 `CreateDIBSection` for any DC you draw text into. Do not assert on458 `GetBitmapDimensionEx` as a size check.459- `#[allow(dead_code)]` silences unused *methods* on the **`impl` block**, not on460 the struct.461- `NOTIFYICONDATAW` fields are all `u32` — `cbSize`, `uID`, `uFlags`,462 `uCallbackMessage` included. A `uID: ICON_ID as usize` is a compile error; the463 shell rejects nothing here, it just fails to build. The struct is `repr(packed)`464 on x86, so bind it `mut` and pass `&mut data as *mut _` — `Shell_NotifyIconW`465 takes a pointer, not a reference.466- `NIF_ICON | NIF_MESSAGE | NIF_TIP` is already `u32`; `as u32` is a no-op cast467 that clippy rejects.468- `GetFileType(...) == FILE_TYPE_CHAR` (not `!=`) decides whether stdin is a real469 terminal. Getting this backwards inverts every prompt-suppression check; it470 needs `std::os::windows::io::AsRawHandle`.471472## Making a window property a real setting473474A style or alpha value hardcoded at `CreateWindowExW` makes its setting a no-op:475there is no path from the toggle to the existing window. Three rules when a476setting must reach a live window.477478- **Read the setting where the window is created**, not once at startup, and pass479 the resulting style in as a parameter. Reading it once and threading it as a480 parameter is what makes the call site honest about its dependency.481- **One window kind is not another.** `replace_all` over a duplicated creation482 block also rewrites the chat/main window, which legitimately keeps its own483 topmost. Patch by unique surrounding context, or scope the edit to the484 function, or you will make the *other* window wrong while fixing this one.485- **Cache the last applied value and act only on change.** Applying486 `SetLayeredWindowAttributes` or `SetWindowPos` every frame fights the window487 manager and costs needless work; the app also stutters. Compare against a488 tracked `applied` value.489490Properties and their calls:491492| Setting | Creation | Live change |493|---|---|---|494| always-on-top | omit `WS_EX_TOPMOST` from `ex_style` | `SetWindowPos` with `HWND_TOPMOST`/`HWND_NOTOPMOST` + `SWP_NOMOVE\|SWP_NOSIZE\|SWP_NOACTIVATE` |495| transparency | window must be `WS_EX_LAYERED` | `SetLayeredWindowAttributes(hwnd, 0, alpha, LWA_ALPHA)` |496497Give transparency a **floor** (clamp to something like `0.05`): a settings store498that accepts `0` must not be able to make a window the user cannot see.499500Handle types for these two calls are a common build-cycle sink: `SetWindowPos`501and `SetLayeredWindowAttributes` want `*mut HWND__`, which `DECLARE_HANDLE!` puts502in `shared::windef`, while `winuser::HWND` is a *private* alias. A `*mut c_void`503handle needs `as *mut winapi::shared::windef::HWND__`, and there is no504dereference — `*hwnd as *mut ...`, not `*hwnd as *mut ...` of a deref.505`WS_EX_TOPMOST` is `DWORD` from `shared::minwindef`, and `COLORREF` is a type506alias, so `0 as COLORREF` rather than a tuple-struct call.507508## Building an editor window509510Three tabs beats one long form: a single scrolling list of twenty fields is how511settings screens become unusable. Click-to-cycle suits enum choices; `-`/`+`512steppers suit bounded numbers; reserve real text entry for name/model fields.513Show the selected option's description so the choice is informed.514515Wire every control the layout draws. A panel that renders but registers no hit516target is the classic dead-control bug, so assert that every tab produces at517least one target, that Save is absent while the form is invalid, and that a518read-only record offers Duplicate but not Delete. Show unsaved state persistently519(a marker plus an enabled Revert) rather than only in a confirm-on-close dialog.520521Expose the editor's events to the app rather than letting it mutate state itself:522saves and deletes go through the app's store so the same data is visible over IPC523and MCP afterwards, and there is one implementation of id-uniqueness and524validation.525526## Asserting on pixels527528GDI writes **BGRA**; `SetTextColor` takes `0x00BBGGRR`. Comparing the DIB's `u32`529values to your own `0x00BBGGRR` constants looks correct and is wrong except for530symmetric colours (`0xE8E8EC` reads back as `0xECE8E8`).531532Antialiasing also yields many near-miss values, so match channel-wise with a533tolerance rather than by equality:534535```rust536let near = |target: u32| {537 let d = |shift: u32| (((pixel >> shift) & 0xFF) as i32538 - ((target >> shift) & 0xFF) as i32).abs();539 d(0) <= 90 && d(8) <= 90 && d(16) <= 90540};541```542543Quick health check on a capture:544545| Distinct colours | Meaning |546|---|---|547| 1 | nothing rendered |548| 150+ | backgrounds, borders, antialiased glyphs all present |549550A distinct-colour count is a *floor*, not a pass. “41 distinct colours” is551consistent with a correct window and also with white boxes stamped over every552label. Assert on **regions**: for each panel you care about, count pixels553differing from that region's modal (background) colour. A label column reading 0%554inked means nothing was drawn there no matter how colourful the window is overall.555556### A capture that cannot be read proves nothing557558Validate the capture file before drawing conclusions from it. A BMP header packed559via a `ctypes` struct gets padded to 8 bytes, so the offsets silently do not line560up; the resulting "screenshot" decodes to nonsense dimensions and a 100%-white561histogram, which reads exactly like a blank window. Write the headers with562`struct.pack` and assert the decoded width/height match what you asked for. Also563verify the dominant colours are the palette you specified — if you chose564`#141212` for the background and the histogram says `#FFFFFF`, the window did not565paint, whatever the colour count says.566567### Let vision, but do not depend on it568569Reading a screenshot with a vision model is the best check available, and it gets570rate-limited (HTTP 429) on shared keys. Have a pixel-level fallback ready so571verification degrades instead of stopping: region ink coverage, dominant-colour572comparison, and size assertions. Report which you used, and when vision was573unavailable say the visual assessment is unverified rather than implying you saw it.574575## Verifying a change that adds a command or setting576577A probe that launches the built binary and drives the new control path is worth578more than any unit test, because it proves the wiring between socket, queue and579handler. Two failure modes make such a probe lie to you:580581- **A stale binary reports the feature as missing.** Preferring a fixed path582 (`target/release/app.exe`) runs yesterday's build, so a newly added handler looks583 like it never runs. Select the **newest** binary by mtime:584 `max([p for p in candidates if p.exists()], key=lambda p: p.stat().st_mtime)`.585- **Reading state back through a shared snapshot picks up the previous step's586 value.** Poll for the value you expect to be written (match on its id), not587 merely for "something non-empty", or the assertions silently pass against588 whatever landed earlier.589590Make the probe clean up after itself. Agents and settings created by a probe591persist to the user's real store and make the *next* run fail on collisions, which592reads as a product bug. Delete created ids on the way out, and sweep leftovers593from prior runs at the start.594595Prefer reading the app's own stdout when a probe fails. `[Agents] Saved 'x' over596IPC` distinguishes "the handler never ran" from "the handler ran and the readback597path is wrong" — a distinction that unit tests cannot make.598599## Unit-testing a GUI with no window600601Have the test path use the same surface the window does, and return **both** the602filled slice and the DIB surface — they hold different things, so asserting on603the wrong one gives a false pass or a false failure.604605Two tests that earn their place:606- glyph pixels reach the DIB surface (catches the two-surface bug)607- layout fill colours reach the slice608609Then test **event semantics**, where GUI bugs actually live: Enter sends and610clears the field, blank input sends nothing, whitespace is trimmed, Backspace on611empty is harmless, `WM_CHAR` control characters are not inserted as text, the612topmost hit target wins over the one beneath it, scroll clamps at both ends.613614If a GUI test suite hangs, grep for a helper that calls its own name before615suspecting GDI — self-recursion from a refactor looks exactly like a hang.616617## System tray lifecycle618619A tray implementation that compiles can still be entirely inert, and the failure620is invisible until someone clicks. Four separate things must all be true; any one621missing makes every menu item a no-op while the code reads as complete.6226231. **The icon must actually be registered.** Creating a hidden message wi624625…(truncated)