Input and focus
Pointer, wheel and keyboard events route through one router that remembers who is hovered, pressed and focused, against the frame the user is looking at.
By the end of this chapter you can bind an accelerator, make a composite one Tab stop, read a drag without remembering where it started, take a dropped file, open a context menu from the keyboard, and know what a custom widget implements to take part.
@Override public void start(Host host) {
host.shortcut(Shortcut.primary(Key.S), this::save); // Cmd+S or Ctrl+S
host.shortcut("Ctrl+Shift+Z", this::redo);
host.window().onFileDrop(drop -> open(drop.first(), drop.at()));
Menus.contextMenus(host, Map.of("rows", rowMenu()));
}
How an event travels
Dispatch is capture, then target, then bubble. A Handles widget sees the
event in onPointerCapture root-first, then the deepest node under the
pointer sees it in onPointer, then each ancestor does. consume() stops it
at any step. The target stays the same through all three phases, so an
ancestor can tell what happened to it from what happened below it.
The router holds what input has to remember between frames against
elements, because a widget is rebuilt constantly and could not remember
any of it. :hover, :active, :focus and :focus-visible are set on
elements by the router, which is why they survive a rebuild.
Hit testing runs against the snapshot taken while painting, not a fresh layout pass. A pointer event is about what the user can see, and that is the last frame drawn. A transform the painter applied is inverted once, from the very matrix the rasterizer used, so a scaled control responds where it is drawn.
Kinds
PointerEvent.Kind | When |
|---|---|
MOVED | the pointer moved with no button change |
PRESSED, RELEASED | a button went down or came up, with button() and clickCount() |
ENTERED, EXITED | synthetic, derived from pointer flow |
CLICKED | synthetic: a press and its release both landed on this node |
WHEEL | the wheel turned or a touchpad scrolled |
A press that is dragged off and let go elsewhere still releases, so the captor can stop looking pressed, and is not a click. Cancelling a click by dragging off is a gesture people rely on.
A secondary or middle press released over the same node without dragging
produces AUX_CLICKED. Read button() to distinguish them. A pinch gesture
reports PINCH, a factor from scale(), and a pinchPhase() of BEGAN,
CHANGED or ENDED. On platforms that report touchpad zoom as wheel input,
the event carries the Control modifier.
Click handlers
Any widget takes a click handler, with no wrapper around it:
new Panel(row).onClick(event -> select(row, event.button(), event.local().fractionX()))
It hears clicks of every button, with the position as a fraction of the
node’s own box. It consumes the click, so an ancestor’s handler does not run
too, and a control inside the node that takes the click keeps it. A node with
only a click handler is not a keyboard control: for one a keyboard must
reach, use pressable or button.
A press captures the pointer
A press takes an implicit capture until the release, so a drag that leaves a
widget still reaches it and :active cannot get stuck. That is what makes a
slider work.
:hover keeps following the pointer regardless: capture decides who is
told, not what is highlighted. router.capturePointer(element) takes a
capture that outlives the release, for the rare widget that needs one.
Gestures: where the drag started
@Override public void onPointer(PointerEvent event) {
if (event.kind() == PointerEvent.Kind.MOVED && !Float.isNaN(event.dragX())) {
var fraction = event.local().fractionX(); // 0..1 along my own box
onChange.accept(min + fraction * (max - min));
}
}
A widget is a value rebuilt every frame and cannot remember where a drag
began. The router can, and reports it on every event of the gesture:
pressX() and pressY() are where the button went down, and dragX() and
dragY() are how far the pointer has travelled since, NaN when no button
is held.
local() is the pointer in the widget’s own box, with fractionX() and
fractionY() clamped to 0..1. A control whose hit target is bigger than
the thing being pointed along, a slider with a readout beside its track, names
the part to measure against with Handles.localPart(). A
control whose drag is a rate rather than a position, a knob, answers
gestureAnchor() once on the press and gets it back as anchor() on every
event after. A canvas reads content() instead of local(): it is
measured from inside the padding, where the painter draws.
A drag held at the edge of a viewport carries the viewport on, and the selection with it.
The wheel is lines
@Override public void onPointer(PointerEvent event) {
if (event.kind() == PointerEvent.Kind.WHEEL) {
scrollBy(event.deltaY() * lineHeight);
event.consume(); // and the page behind does not lurch
}
}
Wheel deltas are in lines, fractional, positive down and right. A touchpad
sends a fraction of a detent per frame and the fraction is preserved in
deltaY(), and a mouse’s whole detents are in ticksY().
Natural scrolling and the windowing layer’s away-from-the-user sign are both
undone at the boundary, so a widget never sees either. --gb-scroll-line in the theme
says how far one line moves a viewport.
Keys and text are different events
A KeyEvent is a key going down or up, with its Key, its Modifiers and
whether it is a repeat. A TextEvent is committed text: what the platform’s
compose and input method produced, which for anything but a Latin keyboard
is not a key at all. One character can take several keystrokes.
A widget that wants what the user typed implements onText, and says so
with wantsTextInput(). That is what turns the platform’s text input on,
and the input method with it; a board that only wants arrow keys leaves it
off. A field that handles a key consumes it, and a key it does not handle
goes on, so Tab still moves focus.
Accelerators
host.shortcut(Mod.CTRL.and(Key.T), actions::toggleTheme); // enums: cannot be misspelled
host.shortcut("Primary+S", this::save); // the desktop's own modifier
host.removeShortcut("Primary+S");
An accelerator is per window and fires after the focused widget has
declined the key, so a text field keeps its own Ctrl+A. The modifiers must
match exactly: Ctrl+S does not fire on Ctrl+Shift+S. A string that names
no key throws at the call.
Primary is the desktop’s own modifier: Cmd on macOS and Ctrl
everywhere else. Shortcut.primary(Key.S) builds it in Java, and Mod,
CmdOrCtrl and Primary all spell it in a string. Nothing else is
translated: a shortcut that says Ctrl means the control key on every
desktop, which is what a terminal or an Emacs-bound editor needs.
-Dgoldberry.input.primary=ctrl or =meta overrides the answer, so a test
can press the same modifier on every desktop.
A widget that binds keys while mounted, a menubar, passes itself as the
owner and gives them back with removeShortcut(shortcut, owner), so an
unmount cannot take a binding somebody else made.
A held key repeats, and an accelerator fires on each repeat unless its
binding says otherwise. A toggle says so, or holding Escape opens and closes
a menu at the platform’s repeat rate:
host.shortcut(Shortcut.of(Key.ESCAPE), menu::toggle, Repeat.IGNORE); // once per press
host.shortcut(Mod.CTRL.and(Key.Z), history::undo); // repeats while held
Repeat.FIRE is what every other form binds. A repeat that an IGNORE
binding declines is still its key: it does not reach focus navigation or the
focused widget. In an offscreen session, session.hold(Key.ESCAPE, 3)
presses the key, repeats it three times and releases it.
Global shortcuts
An accelerator fires while a window has the keyboard. A push-to-talk key, a mute key or a “show the window” key has to work while another application has it, so it is asked of the desktop instead, and the desktop may say no:
var shortcuts = GlobalShortcuts.open();
shortcuts.bind(
List.of(
GlobalShortcut.of("talk", "Push to talk", "Ctrl+Alt+T"),
GlobalShortcut.of("mute", "Mute the microphone", "Ctrl+Alt+M")
),
event -> {
switch (event.id()) {
case "talk" -> microphone.open(event.isPress());
case "mute" -> { if (event.isPress()) microphone.toggleMute(); }
default -> {}
}
}
)
.thenAccept(grants -> grants.forEach(settings::show));
The answer is a Grant per shortcut, in the order asked:
| Grant | Means |
|---|---|
Granted(id, trigger) | its presses and releases will arrive; trigger is the combination in the desktop’s words |
Refused(id, DENIED, …) | the user said no |
Refused(id, TAKEN, …) | another application holds the combination |
Refused(id, UNMAPPABLE, …) | the key has no code here: Menu on a Mac |
Unsupported(id, …) | this desktop has no way to ask |
Show the answer where the shortcut is configured. A shortcut the user turned down, or that another application holds, is not one to tell them to press.
How each desktop is asked:
| Desktop | Asked through | Notes |
|---|---|---|
| Wayland | the desktop’s GlobalShortcuts portal | the desktop shows the user a dialog, and the user may choose another trigger; the trigger granted is the one they chose. The application’s desktop entry id (-Dgoldberry.desktop.id, as for notifications) is the name the desktop lists the shortcuts under |
| X11 | a key grab on the root window | whichever client grabbed the combination first keeps it; Caps Lock and Num Lock do not matter |
| Windows | RegisterHotKey | whichever application registered it first keeps it |
| macOS | Carbon’s RegisterEventHotKey | no Accessibility permission is asked for; open the shortcuts on the UI thread |
A Wayland desktop gives no application the keyboard while another has focus,
so there the portal is the only way, and a desktop whose portal has no global
shortcuts answers Unsupported for each.
Press and release
The listener hears each granted shortcut go down once and come up once. A held key’s repeats are not passed on, so a push-to-talk opens on the press and closes on the release. On Windows the release is noticed within 20 ms, because Windows reports only the press. Binding again, or closing, releases whatever is held first, so the microphone never stays open because its release can no longer come.
bind replaces the shortcuts bound before; an empty list unbinds them all.
Close the shortcuts when the application ends:
@Override public void stop() { shortcuts.close(); }
Opened on the UI thread, the listener and the answer run on the UI thread.
GlobalShortcuts.open(executor) delivers both to an executor of the
application’s choosing.
In tests
GlobalShortcuts.simulated() grants what it is asked, except what the test
refuses, and presses what the test says:
var shortcuts = GlobalShortcuts.simulated().refuse("mute", Grant.Reason.TAKEN);
var call = new Call(shortcuts); // binds "talk" and "mute"
shortcuts.press("talk");
assertTrue(call.microphoneOpen());
shortcuts.release("talk");
assertFalse(call.microphoneOpen());
Focus
One focus owner per window. Focus moves by a press and by Tab and
Shift+Tab in document order, and host.focus(id, fromKeyboard) moves it
from Java: a dialog putting the caret in its first field, a form jumping to
its first error. It is refused when the node cannot take focus, is disabled,
or is outside a modal that is open.
:focus is true however focus arrived. :focus-visible is true only for
keyboard focus, and the ring is drawn on that one, so a button clicked with a
mouse gets no ring. Handles.onFocusChanged(focused, fromKeyboard) tells a
widget the same thing, and onFocusWithin tells a container when focus
enters or leaves its subtree as a whole.
A composite is one Tab stop
@Override public FocusScope focusScope() {
return FocusScope.VERTICAL; // Up and Down rove; Left and Right are mine
}
A radio group, a tab list, a menu or a toolbar is one Tab stop, with the
arrow keys moving focus inside it. The group says
which arrows rove: HORIZONTAL, VERTICAL, or BOTH for a group whose
direction is the stylesheet’s, which is what radio-group answers. Home
and End reach the ends of any scope. Traversal enters at the descendant
matching :checked, or the first one, so the selection is the roving
position and there is no second piece of state to disagree with it.
The cursor
button { cursor: pointer }
.splitter { cursor: ew-resize }
host.window().cursor(Cursor.WAIT); // or decide it yourself
The cursor is a property of the painted rectangle, set from CSS or from
code, and it inherits down the stack of rectangles under the pointer rather
than the element tree. cursor: pointer on a button therefore covers the
label inside it. During a drag the shape stays the one the drag began with,
whatever is under the pointer. The one exception is the box holding the
pointer: when its own cursor changes in a frame painted during the drag,
the pointer takes the new shape. That is how a card that says grab shows
grabbing once it is lifted.
An application can draw its own shapes. Application.cursors() gives a shape
a picture at each size it was drawn, each with its hot spot:
@Override public List<CursorImage> cursors() {
return Stream.of(32, 48, 64, 96)
.map(size -> new CursorImage(Cursor.GRAB,
Image.decode(read("cursors/grab-" + size + ".png")), size * 3 / 8, size / 8))
.toList();
}
The shapes stay CSS’s, so cursor: grab in a stylesheet and a link’s own
pointer show the application’s picture without naming it, and a shape with
no picture is the platform’s. The smallest size is the shape at 100%, and the
toolkit shows the one the display’s scale wants. Without a picture, grab
and grabbing fall back to move.
Dropped files and text
host.window().onFileDrop(drop -> {
for (var path : drop.paths()) { board.add(path, drop.at()); }
});
host.window().onTextDrop(drop -> note.append(drop.lines()));
A desktop reports a drop as a beginning, a position, one event per file and
an end. The toolkit reassembles that into one FileDrop carrying every path
and the point it landed on, in the window’s logical coordinates, because a
board needs to know where. Both
listeners return a Subscription to close when a widget that listened
leaves the tree.
Dragging between widgets
new Card(ticket.title()).draggable(ticket);
new Column(cards).dropTarget(
payload -> payload instanceof Ticket,
drop -> board.move((Ticket) drop.payload(), status)
);
draggable(payload) and dropTarget(accepts, onDrop) are attributes, so any
widget can be either. The router does the rest. A press on a draggable
becomes a drag once the pointer has moved four logical pixels with the button
down, so a press that does not move is still a click. A control inside the
draggable that consumes its press keeps it: a slider in a draggable card drags
its thumb, and the card is picked up from anywhere else.
While the drag lasts, the source’s own box follows the pointer, faded, drawn
over everything and invisible to the hit test. The router looks for a target
under the pointer: the nearest node up the tree that carries a drop target
whose accepts says yes, skipping the source and what is inside it. That
node matches :drag-over. A target that refuses is passed over and gets no
:drag-over. Letting go over an accepting target calls its onDrop with a
Drop: the payload, and the point measured from the corner of the target’s
content box. Letting go anywhere else, or pressing Escape, puts the drag
back. A press that became a drag is not a click wherever it is let go.
DropTarget carries two more hooks for a target that draws where the drop
would land, as a canvas does:
var target = DropTarget.of(payload -> payload instanceof Event, drop -> week.move((Event) drop.payload(), drop.at()))
.whileOver(drop -> week.showSlotAt(drop.at()))
.onLeave(week::hideSlot);
new Canvas(week::paint).dropTarget(target);
whileOver hears every move, and onLeave hears the drag leave, land or be
put back. For a canvas the point is in the painter’s own coordinates.
From the keyboard, Space on a focused draggable picks it up when something
in the window accepts it. The arrow keys and Tab step between the targets
that accept it, in document order, Space or Enter drops it at the centre
of the one it is over, and Escape puts it back. Drop.fromKeyboard() tells
the two apart. Space is taken before the focused widget hears it, so a
draggable pressable is lifted by Space and activated by Enter.
The payload is the object itself and stays in the application. A drag
cannot cross into a popup, and it leaves the window only when the draggable
has a dragOut offer, which the next section is about.
session.drag("card", "done") carries one in a test.
Dragging out of the window
new Card(frame.title())
.draggable(frame)
.dragOut(() -> DragOffer.image(frame::png).withFiles(frame.exportedPath()))
.onDragOutEnd(outcome -> {
switch (outcome) {
case DragOutcome.Delivered _ -> status.show("Sent to another application");
case DragOutcome.Landed _ -> {}
case DragOutcome.Cancelled _ -> status.show("Not sent");
}
});
A draggable that also has a dragOut offer is the desktop’s own drag once
the pointer has moved four logical pixels with the button down. It can be let
go in a file manager, a browser, a mail client or an editor, which take what
the offer carries. The desktop draws the picture under the pointer: the source
as it was painted, faded, held where the press took hold of it, unless the
offer gives one of its own with withPicture.
An offer is any mix of five kinds, each named the way the desktop expects:
| Offer | Carried as |
|---|---|
files(paths) | the files themselves, which must exist when the drag starts |
link(uri) | a link, and its text |
text(string) | text |
image(png) | a PNG image, and the same image as a PNG file for the targets that take only files |
data(mime, bytes) | bytes under a type the application names |
dragOut takes a supplier, asked once when a drag starts, so a widget that
is built often and dragged rarely pays nothing for its offer. Everything but
the paths is a supplier too, asked for when a target takes it: an image that
is never dropped anywhere is never encoded. Suppliers run on the UI thread.
The target picks what to do with the drag from the operations the offer
allows, COPY alone unless allowing says otherwise, and the user steers the
pick with the desktop’s modifier keys. The toolkit never deletes anything: a
source that hears MOVE decides what moving means.
onDragOutEnd hears how it ended, once:
| Outcome | Means |
|---|---|
Delivered(operation) | another application took it; operation is what it says it did, or null where the desktop does not say |
Landed(accepted) | it was let go over one of the application’s own windows; accepted says whether a drop target there took it |
Cancelled() | it was put back: Escape, a release over nothing that takes it, or a target that refused it |
Over the application’s own windows the drag is still an in-app drag. Drop
targets light up with :drag-over and hear whileOver as before, and a drop
there delivers the payload itself, not a FileDrop of the application’s own
files. The window that started the drag keeps painting while it lasts.
A draggable with no offer stays inside its window, and so does every drag
made from the keyboard. Where the desktop will not start a drag, the gesture
goes on as an in-app drag from where the pointer is, and onDragOutEnd hears
nothing. A test session is such a place: session.drag("frame", "bin")
carries a draggable with an offer onto a drop target like any other.
| Desktop | Notes |
|---|---|
| X11 | the pointer keeps its arrow during the drag, and no picture follows it; data larger than the display server takes in one request is refused |
| Wayland | an offer of a type of the application’s own, with no file and no text beside it, is not seen by the application’s own drop targets while it is out |
| Windows | the drag runs inside a loop of the desktop’s; the window’s posted work, timers and frames run in turns inside it |
| macOS | files go as file URLs, everything else is made when a target asks for it |
Context menus
panel id="company" context-menu="rows" {
text "Frodo Baggins"
text "Samwise Gamgee"
}
Menus.contextMenus(host, Map.of("rows", rowMenu()));
context-menu="rows" on any widget names a menu. A right-click, the Menu
key or Shift+F10 on the focused widget finds the name by walking up from
what is under the pointer, and hands it to the one handler the application
registered with the point it happened at. What the name means is the
catalogue’s, which is why Menus.contextMenus is the line that turns a name
into a menu.
Bare F10 is the menu bar’s.
A widget can also have a menu of its own, which it opens without a name:
text-input and text-area open Cut, Copy, Paste and Select all. At each
widget on the walk a name comes first and the widget’s own menu second, so a
field you gave a context-menu= opens yours, and a field inside a panel that
named one opens its own. A custom widget offers one by implementing
ContextMenuOwner; answering false passes the click on to the widgets above.
What a custom widget implements
A widget takes part in input by implementing Handles. Everything on it has
a default, so a widget overrides what it uses.
| Method | For |
|---|---|
onPointerCapture, onPointer | the pointer, root-first and then deepest-first |
onKeyCapture, onKey | keys, the same two phases |
onTextCapture, onText, onPreedit | committed text, and an input method’s composition |
isFocusable() | whether Tab stops here. False by default |
focusScope() | whether the descendants are one Tab stop, and which arrows rove |
onFocusChanged, onFocusWithin | focus arriving at this node, or anywhere in its subtree |
wantsTextInput() | whether the platform’s text input is on while this has focus |
localPart() | the part local() is measured against, as a CSS type name |
gestureAnchor() | a number to remember for the length of a drag |
caretArea(), caretOffsetIn(area) | where the caret is, for the input method’s candidate window |
A canvas takes the same facts through its own Input, with onPointer,
onKey, onText, onPreedit and wantsText(), and it is focusable exactly
when it has one. The whole contract is in
Writing a widget.