gpui-cc Course handbook
CHAPTER 04 / STAGE 14COURSE

Traverse focus by stable identity

Move keyboard focus and draw a visible indicator.

focus-traverse
On this page

Learn: the window is active, but a control is focused

There can be an active window with no focused control. Within it, a stable control ID owns the current keyboard focus. When the app rebuilds, the selected node may have a different address or array index. The ID can remain the same; if it is absent or clipped away, it can no longer receive activation.

Run it: find a selection after reordering

Terminal
./build/examples/core-lab stable-selection
C++ · core-lab.cpp
void stable_selection() {
    const std::string_view selected = "save";
    for (const auto items : {std::array<std::string_view, 2>{"open", "save"},
                             std::array<std::string_view, 2>{"save", "open"}}) {
        const auto it = std::find(items.begin(), items.end(), selected);
        if (it != items.end()) std::cout << *it << " at index " << it - items.begin() << '\n';
    }
}

Expect save at index 1, then save at index 0. Try it: remove save from the second list; lookup cannot find it regardless of the previous index.

Build it: store focus separately from the frame

Your challenge: Track focused ID and eligible controls in declaration order. Make focus visible. Implement normalized forward/backward traversal before worrying about X11 keycodes.

Create an ordered list from the current frame’s visible eligible controls. With no selection, forward chooses the first and backward the last. Otherwise advance or wrap. Clicking an eligible control should focus it; blank clicks may preserve focus but do not select a hidden control. Losing window activation hides the outline and cancels pending pointer work. On activation, restore the remembered ID only if still eligible. Draw the focus indicator using the same clipped geometry as the element; a changed outline is a reason to redraw even if the model did not change.

Check it

With A then B: no selection → forward A → forward B → forward A → backward B. Resize while B remains visible: selection stays B. Clip B away: it no longer participates. Reactivate with remembered B gone: no focus. Verify inactive outline hidden and one distinct visual indicator when active. An empty list changes nothing.

Terminal
python3 course/check_core.py focus-traverse

Hints and troubleshooting

Hint: focus jumps after a rebuild or hides the wrong control

Compare stored ID to the current list before walking it. Check whether focus is stored as an array position, node pointer, or ID, and whether your eligibility list uses the clipped area.