1 The Event Loop
liquibyte edited this page 2026-11-19 16:23:20 -06:00
This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

The Event Loop

An Xtk program runs its own event loop and gives each X event to its widgets. This page explains the loop: the order in which the widgets get the events, what they answer, callbacks, the functions to call between events, the keyboard focus, input methods, the clipboard and X errors.

The program owns the loop

Xtk has no main loop and no list of all widgets. The program takes the events from Xlib and passes each one on to the widgets it made. That keeps the toolkit small, and it lets the program mix in its own work: a socket, a pipe to a child process, a timer. The price is that the program must give the events to the widgets in a sensible order, and call a few functions between events for the things that happen over time, such as a blinking caret.

The event loop: wait on the X connection with a time limit, take each event, let the input method filter it, give it to the clipboard, an open menu and the widgets until one takes it, then call the update functions and flush, and wait again

One turn of the loop. The time limit of the wait is what lets the update functions run when no events come.

A loop in that shape:

const int connection = ConnectionNumber(display);
while (running) {
    while (XPending(display)) {
        XEvent event;
        XNextEvent(display, &event);
        if (XFilterEvent(&event, None)) continue;              /* the input method's */
        if (xtk_clipboard_handle_event(clipboard, &event)) continue;
        xtk_tooltip_handle_event(tooltip, &event);              /* sees every event */
        if (xtk_popup_menu_is_visible(menu)) {
            xtk_popup_menu_handle_event(menu, &event);
            continue;
        }
        if (xtk_button_handle_event(ok, &event)) continue;
        if (xtk_entry_handle_event(name, &event)) continue;
        /* ... the other widgets ... */
        xtk_focus_manager_handle_event(focus, &event);
    }
    xtk_entry_update_blink(name);
    xtk_tooltip_update(tooltip);
    xtk_popup_menu_update(menu);
    XFlush(display);
    fd_set ready;
    FD_ZERO(&ready);
    FD_SET(connection, &ready);
    struct timeval wait = {0, 30000};                             /* 30 ms */
    select(connection + 1, &ready, NULL, NULL, &wait);
}

Add the program's own file descriptors to the select() call to wait for them too. A wait of 30 to 50 milliseconds is short enough for every timer in Xtk.

What a widget answers

Every widget has a xtk_widget_handle_event() function. Give it every event, not only the events of its own window: a widget also watches events of other windows (its popup, its parent's resize, a click elsewhere that ends a drag). What it returns says whether to go on:

Return value Meaning What the loop does
0 Not this widget's event, or one that it only watched. Gives the event to the next widget.
1 The widget used the event, for example an Expose of its window, a key while it has the focus, or a press on it. Stops: no other widget gets this event.
2 or more A result that the widget's header names, such as a click on a button (2), a toggle, or a change of value. Stops, and acts on the result if it has no callback for it.
an item, or -1 The menu bar returns XTK_MENUBAR_ACTION(menu, item) for a chosen item and the popup menu the item's index; both return -1 when nothing was chosen. The menu bar returns XTK_MENUBAR_CONSUMED (-2) when Escape only closed its open menu. Tests for >= 0, and stops on XTK_MENUBAR_CONSUMED.

A disabled widget still draws itself on Expose, and returns 0 for every other event. Some widgets act on an event and still return 0 (for example the entry, on a button release or a pointer motion), so 0 does not mean the event was left untouched; it means another widget may have it too.

A rich text view whose right-click menu is open takes every event and returns 1 until the menu closes, so give it the events after the other widgets.

Order. The clipboard comes first, because other programs ask it for the text the user copied. A widget that shows something over the others comes next: an open popup menu or menu bar, and a combo box with its list open, take the pointer (they grab it) and must see the events before the widgets under them. A tooltip watches the pointer, so give it every event without stopping. The focus manager comes last, so that a widget that wants Ctrl+Tab itself gets it first.

Callbacks

Most widgets can also call a function of the program when something happens: a click, a new value, a chosen item, a drop. The function is set with a xtk_widget_set_..._callback() call (sometimes it is a field of a config structure given to the create call, as on_change of XtkEntryConfig). Its first parameter is the widget, its last the user_data pointer given with it. A few callbacks are not given the widget: the spin button's change callback gets only user_data, and the data grid's row callbacks get user_data first. Setting a callback replaces the previous one, and NULL removes it.

A callback runs inside handle_event(), after the widget has changed its state, so the widget already shows the new value when the program reads it. The return value of handle_event() still says what happened, so a program can use either. A callback for a user action may destroy its own widget, unless the header says that it must not where it describes the callback; the widget's handle_event() then returns without touching it again.

Drawing and Expose

A widget draws itself. It repaints its window on Expose, and a call that changes what it shows (xtk_label_set_text(), xtk_slider_set_value() ...) either redraws it at once or sends it an Expose, which the loop then hands back to it. So a program never draws a widget itself, but it must keep giving the events to the widgets. Most widgets draw into a back buffer and show it in one step, so they do not flicker (Drawing).

The program's own windows, such as the main window, are the program's to draw. Give them the theme's window color (config.main.background) as their background, and the widgets on them blend in.

When the main window changes size (ConfigureNotify), the program moves and resizes its widgets itself (each widget has set_position() and a resize call), or lets an XtkGrid do it.

Between events

A few things in Xtk happen over time rather than in answer to an event. The widgets do not run timers of their own: the program calls their update functions each time round the loop, and each one does what is due and returns at once when nothing is.

Function What it does
xtk_entry_update_blink(), xtk_textview_update_blink(), xtk_richtext_update_blink(), xtk_spinbutton_update_blink(), xtk_datagrid_update_blink(), xtk_panel_update_blink(), xtk_filedialog_update_blink() Blink the text caret of the widget that has the focus: in an entry, a spin button, the text view, the rich text view and the cells of a data grid (which are text views), and in the widgets made with entries, every cursor-blink-ms milliseconds of [behavior]; in the hex editor of a panel every 530 milliseconds.
xtk_tooltip_update() Shows a tooltip when the pointer has rested long enough (delay-ms of [tooltip]), and hides one that was asked to hide soon.
xtk_toolbar_update_tooltips() The same for every button of a toolbar, keeps their hover look right, and opens the submenus of their dropdown menus.
xtk_tray_update() The tooltip of the tray icon.
xtk_popup_menu_update(), xtk_menubar_update() Open a submenu once the pointer has rested on its item for a moment.
xtk_spinbutton_update_repeat() Steps the value again and again while a + or − button is held down (after 400 ms, then every 75 ms).
xtk_progressbar_update() Moves the block of a progress bar that pulses (one that shows activity without a known amount).
xtk_colorpicker_update() Blinks the caret of the color picker's hex entry and ends the flash that marks a valid or invalid color.
xtk_dockframe_flush_pending_layout() Finishes a layout change of a dock frame that was put off while a tool window was being undocked.

Each header says whether its widget has such a function. Calling one for a widget that has nothing to do costs almost nothing.

Keyboard focus

The keyboard focus is the X server's input focus. A widget that takes keys (a button, an entry, a list ...) takes the focus itself when it is clicked, draws a focus ring while it has it, and handles its own keys: Space and Enter press a button, the arrow keys move a slider, and Tab is typed into a text view. Many widgets also have a set_focused() call, to give or take the focus from the program, and a get_focus_window() call that says which of their windows takes it.

Moving the focus from widget to widget with the keyboard is the job of the optional focus manager, XtkFocusManager (xtk_focus.h). The program lists its widgets with it, in the order the focus should go, and gives it the events last. Ctrl+Tab then moves the focus to the next widget, and Ctrl+Shift+Tab to the one before; it wraps around at the ends. A widget is skipped when it is disabled or its window is not viewable, so one manager can hold the widgets of every page of a notebook. Plain Tab is left to the widgets.

The manager knows no widget type: for each widget it is given two small functions of the program, one that gives or takes the focus and one that says whether the widget is enabled, and the window that holds the focus:

static void focus_button(void *widget, int focused) { xtk_button_set_focused(widget, focused); }
static int button_enabled(const void *widget) { return xtk_button_get_enabled(widget); }
static void focus_entry(void *widget, int focused) { xtk_entry_focus(widget, focused); }

XtkFocusManager *focus = xtk_focus_manager_create(display);
xtk_focus_manager_register(focus, name, focus_entry, NULL, xtk_entry_get_window(name));
xtk_focus_manager_register(focus, ok, focus_button, button_enabled, xtk_button_get_focus_window(ok));
xtk_focus_manager_focus_first(focus);
/* in the loop, after the widgets: */
xtk_focus_manager_handle_event(focus, &event);
/* at the end: */
xtk_focus_manager_destroy(focus);
Call What it does
xtk_focus_manager_register() Adds a widget at the end of the order: the widget, its focus function, its enabled function (NULL: always enabled), and its focus window. At most XTK_FOCUS_MANAGER_MAX_WIDGETS (128).
xtk_focus_manager_register_composite() The same, for a widget with several windows: one more function says whether a window belongs to the widget.
xtk_focus_manager_unregister() Takes a widget out of the order. Do this before destroying the widget.
xtk_focus_manager_handle_event() Moves the focus on Ctrl+Tab and Ctrl+Shift+Tab, and returns 1 for those keys. It does nothing with fewer than two widgets.
xtk_focus_manager_advance() Moves the focus forward or backward, as those keys do.
xtk_focus_manager_focus_first() Gives the focus to the first widget that can take it.
xtk_focus_manager_owns_window() Whether a window belongs to one of the widgets that can now take the focus.
xtk_focus_manager_set_hint(), xtk_focus_manager_set_hint_callback() A short text for each widget (such as "Space: check or uncheck"), given to the program's callback each time the manager moves the focus there, for a status bar to show. The text is not copied, so it must stay valid; a string literal is the usual choice.

Input methods

To type composed characters (with a dead key or the Compose key) and Chinese, Japanese or Korean text, the text widgets read their keys through an X input method. The program sets it up once:

  1. Call setlocale(LC_ALL, "") before XOpenDisplay(), so that Xlib knows the user's language and character set.
  2. Open the input method with xtk_ime_open(display). It returns NULL when there is none; the widgets then read plain keys.
  3. Give it to each text widget: xtk_entry_set_ime(), xtk_textview_set_ime() or xtk_richtext_set_ime(). NULL is accepted.
  4. In the loop, call XFilterEvent(&event, None) first, and skip the event when it returns True: the input method used it.
  5. At the end, after the widgets are destroyed, close it with xtk_ime_close().

The widgets make their own input contexts from it. xtk_ime_create_input_context() and xtk_ime_destroy_input_context() are there for a program that reads keys in a window of its own.

The clipboard

One XtkClipboard serves the whole program. Make it with xtk_clipboard_create(display), give it to the widgets that copy and paste (the entry, the text view, the rich text view ...), and give it every event first. It owns the text that the program offers to others, and answers when another program asks for it, also in parts for large texts; a large text another program sends in parts is put together before the paste callback gets it.

Call What it does
xtk_clipboard_set_text() Offers a text on the clipboard (SELECTION_CLIPBOARD, pasted with Ctrl+V) or as the primary selection (SELECTION_PRIMARY, pasted with the middle mouse button). NULL gives it up.
xtk_clipboard_request_text() Asks for the text on the clipboard or the primary selection. The answer comes later, through the events: the callback gets the text, or NULL when there is none.
xtk_clipboard_set_rich_text(), xtk_clipboard_request_rich_text() The same with a second, named format next to the plain text, such as Markdown for the rich text view.
xtk_clipboard_handle_event() Returns 1 for an event meant for this clipboard (an answer to its paste, a request for its text, the loss of a selection its window held, a part of a large transfer), 0 for any other event, also one of the same kind meant for another window.
xtk_clipboard_destroy() Frees it, after the widgets that use it.

The text a paste callback gets is valid only during the call: copy it to keep it.

X errors

When the X server reports an error (a window that is gone, a pixmap too large), Xlib calls its error handler, and the default handler prints the error and ends the program. Xtk does not change that. A program that wants to live on sets its own handler with XSetErrorHandler().

For a request that may fail on purpose, such as reading the attributes of a window that may already be gone, Xtk has a trap: xtk_xerror_trap_push(display) before the requests, and xtk_xerror_trap_pop(display) after them. Pop returns the code of the first error between the two (0 when there was none), and no handler sees it. Both wait for the server (XSync()), so do not use them in a fast path. Traps can be nested up to 8 deep.

Menus and popups

Menus, the list of a combo box, tooltips and the file dialog are windows of their own over the program's window. A popup menu (xtk_popup_menu_show()) and the menu bar's menus take the pointer and the keyboard while they are open, so give them the events before the other widgets, as above. The menu bar returns XTK_MENUBAR_ACTION(menu, item) when an item is chosen, and an item of a popup menu can also have a callback of its own (XtkMenuItemCallback). The dialogs (xtk_filedialog, xtk_colorpicker) are top-level windows, centered over the program's window when they open; they take their events through their own handle_event() like any widget. The file dialog's returns 2 when it closes, and the program then reads the outcome (accepted or canceled, and the chosen files).