Input¶
Events¶
from turbodesk.events import Event, Key, KeyPress, Mouse, MouseKind, Paste
def keys(event: Event) -> bool:
match event:
case KeyPress(key=Key.ENTER):
submit()
case KeyPress(key="j"):
move_down()
case KeyPress(key=str() as ch) if ch.isprintable():
type_character(ch)
case _:
return False
return True
ui.on_event(keys)
Event is KeyPress | Mouse | Paste. A Paste holds the whole of a bracketed paste as one event. A marker either side of a key press per character would cost a frame a character, because every layer above re-renders per event. A KeyPress has key (a str for printable characters, or a Key enum member for named keys) and mods, a frozenset of Mod.CTRL, Mod.SHIFT, Mod.META.
Returning True consumes the event. Handlers behind it never see it. Returning False (or None) passes it on.
on_event also works as a decorator:
Focus¶
A widget that owns the keyboard joins the focus ring:
active = ui.focus("search-box") # True if it currently holds the keyboard
if active:
ui.on_event(handle_typing, focused=True)
focused=True handlers run before the app's handlers, whatever order they were registered in. A focused editor eats j wherever your global keymap was set up.
Tab cycles the ring and Shift-Tab goes back. Clicking inside a focusable takes it, provided the widget tagged itself:
Focus order is registration order, not layout order
Whichever focusable is constructed first owns the keyboard by default, even when it is drawn at the bottom of the screen. A filter box built before the table it sits above will swallow the keystrokes meant for the app. The symptom is "this key does nothing", which points nowhere near focus.
Say which one should own it:
Other focus controls: ui.focused (a property), ui.set_focus(key) and ui.focus_next(step), where a negative step moves backwards.
Focus groups¶
One ring for the whole screen is right until two parts of the screen are separately in use. With overlapping windows, Tab should walk the front window's controls and stop at the window's edge. ui.focus_group(key) says where the edge is:
Only Tab is affected. Clicking still reaches any focusable on the screen, which is how the keyboard gets into another group in the first place. Groups nest. A widget belongs to the innermost one it is rendered in; anything drawn outside a group shares the one ring an ungrouped application has always had.
A group of one keeps Tab, the same way a lone focusable does. Without that rule, opening a second window would take Tab away from the first window's editor, because two focusables anywhere on the screen are enough to make Tab mean "move focus".
The modal stack is a separate group underneath all of this, so a dialog's Tab was always confined to the dialog.
Mouse¶
view.on_click(lambda: pick(index))
view.on_click(callback, key=("row", index)) # stable identity
view.on_click_at(lambda ctx: pick_at(ctx.relative))
view.on_right_click(show_menu)
view.on_right_click_at(lambda ctx: popup(ctx.absolute))
Handlers hold their region, translated as the view is composed, so the click lands on whatever ended up at that position. The innermost handler wins.
Pass a key for anything that moves. A row that scrolls between press and release would otherwise hand its click to whatever is now at those coordinates; with a key, a click is matched by identity instead.
The _at variants are handed a ClickContext with relative (inside the view) and absolute (on the screen). absolute is what you want to position a popup at; relative is what you want to know which cell was hit.
Hover¶
Hovering has to be asked for. A terminal reports the pointer moving with no button held only under any-motion tracking, which turbodesk leaves off. It produces an event for each cell the pointer crosses, so an application that draws nothing on hover would re-render for each one. run(app, hover=True) turns it on; without it on_hover never fires.
enter fires when the pointer reaches the view and leave when it goes away, exactly once each. The runtime remembers the last hovered handler and compares by key across frames, because every handler is rebuilt each render; without a key the region is the identity, so a rebuilt element under a stationary pointer would re-enter on every frame.
leave also fires when the hovered element stops being drawn. A menu that closes under a stationary pointer gets no mouse event to say so; the next frame notices instead.
A status line describing the menu item under the pointer is the first caller: menu.pulldown takes an on_hint, shell threads it through, and statusline draws it right-aligned in whatever space the key pairs leave.
Dragging¶
A drag belongs to the runtime, because it outlives the frame it started in. Mark the draggable region with a tag and say what to do with it:
The callback is handed a Drag with phase ("start", "move", "end"), grab, start, pos and delta:
def follow(drag: Drag) -> None:
set_position(Pos(drag.pos.x - drag.grab.x, drag.pos.y - drag.grab.y))
grab is where inside the element the press landed, and start is where on screen. Both are latched when the button goes down and never move. The element is usually following the pointer, so anything measured against where it is compounds its own corrections, one report at a time. A useful sum subtracts from a fixed point. To move something, pos - grab; to drag a corner, pos is the corner.
Marking a region draggable attaches a handler to it, so a press finds its target the same way a click does: innermost and topmost wins, whatever order the targets were registered in. An editor inside a window you drag by its title bar gets the presses inside it, while the window gets the ones on its frame.
Anything drawn over a draggable region takes the press instead. "Over" means a handler that comes first without fitting inside the target. A close box on a window's title bar is part of the window and still raises it. A menu's click-away sheet covers the whole screen, so a press anywhere under an open menu belongs to the menu. That sheet is the existing overlay idiom (a transparent full-screen catcher under the pull-down, so a click outside closes it), which is why one rule is enough.
One edge remains: a region fits inside an identical one, so an overlay exactly the size of the draggable it covers does not block. The overlays here are full-screen catchers over smaller targets, so the case does not arise. If it ever does, mark the overlay draggable under an unregistered tag and the press stops there with no geometry involved.
A press that never moves still produces a start and an end with a zero delta, and on_click on the same region fires as usual: dragging and clicking the same element is the common case, so neither suppresses the other.
The callback is looked up by tag on every report, so it is always the current frame's. A callback captured at press time would close over state that is stale by the second mouse report.
Chords as text¶
turbodesk.keys names a chord in both directions, so a menu label and a binding table cannot drift apart:
from turbodesk import keys
keys.chord("ctrl+alt+f9") # KeyPress(Key.F9, {CTRL, META})
keys.describe(KeyPress("s", CTRL)) # "Ctrl+S"
keys.describe(event, join="-") # "Ctrl-S"
chord raises ValueError on an unknown modifier or key name, which turns a settings file's typo into a message at load time instead of a binding that silently never fires.
Alt on macOS
Terminal.app and iTerm send no Alt modifier by default. The Option key composes characters there, which is what it is for: Option-E then e is é, and Option-2 is ™ on a US layout and something else on a German one.
No application can recover the chord from the character. The character depends on the keyboard layout, so any table is right for one layout and wrong for the rest; and where it is right, reading ≈ as Alt-X means the user can no longer type ≈. Those keys belong to whoever is typing.
The fix is one setting in the terminal:
- Terminal.app: the setting is "Use Option as Meta key", under Settings, Profiles, Keyboard.
- iTerm2: set Left Option key to
Esc+under Settings, Profiles, Keys. - Alacritty, kitty, WezTerm, Ghostty: these already do it by default.
turbodesk parses the resulting Esc-prefixed sequences into Mod.META. An app can offer a second key for everything it puts on Alt, so it works on an unconfigured terminal. Turbo Python, built on turbodesk, ships two complete schemes and picks the Alt-free one on macOS.
Bindings¶
There is no BINDINGS list. A key table is a dict:
ACTIONS = {"q": quit, "r": refresh, Key.ESCAPE: back}
def keys(event: Event) -> bool:
if not isinstance(event, KeyPress):
return False
action = ACTIONS.get(event.key)
if action is None:
return False
action()
return True
A focused text input takes every printable key
If your app has a text box that always holds focus (a console, a search field), d is a character. Give the user a way out that is not a letter: Esc, or a modifier.