1 Embedding the Widget
liquibyte edited this page 2026-11-19 16:23:30 -06:00

Embedding the Widget

The widget is a complete host for an X11 program built on Xtk: one window that shows the terminal, sends it the keys and the mouse, and gives the user selection, search, links and a menu. This page shows a complete program that uses it, explains the calls of its event loop, and describes every function and callback in demo/hosho_widget.h.

1. What the widget is

The widget is written in the form of an Xtk widget. It is one X window, a child of a window of yours, and it holds a terminal (HoshoTerminal) and the pseudoterminal of the program that runs in it. It draws with Xft through an Xtk surface (the double buffer of the DBE extension), and every paint draws the whole view. It has a scrollbar and a menu of Xtk's own.

The widget is not part of libhosho.a. A program compiles demo/hosho_widget.c with its own sources and links Hosho, Xtk and the X11 libraries:

cc -std=gnu17 $(pkg-config --cflags x11 xrender xft fontconfig freetype2 xcursor) \
   -I/usr/include/hosho -Ipath/to/hosho/demo -Ipath/to/xtk/src \
   my_program.c path/to/hosho/demo/hosho_widget.c -o my_program \
   -lhosho path/to/xtk/libxtk.a $(pkg-config --libs x11 xrender xft fontconfig freetype2 xcursor) -lm -lXext -lXpm

2. A complete example

This program opens a window of 24 rows and 80 columns with the user's shell in it, and ends when the shell ends or the window is closed. It compiles with the line above, and it is all a terminal window needs; demo/hosho_demo.c adds the title, links, notifications, the bell and the window functions.

/* terminal_window.c - a window with the Hosho widget, running the user's shell */
#include <X11/Xlib.h>
#include <locale.h>
#include <stdio.h>
#include <sys/select.h>

#include "hosho_widget.h"
#include "xtk_ime.h"
#include "xtk_theme.h"
#include "xtk_worker.h"

static int running = 1;

static void on_program_end(HoshoWidget *widget, int status, void *user_data) {
    (void)widget;
    (void)status;
    (void)user_data;
    running = 0;
}

int main(int argc, char **argv) {
    /* The pictures programs send are taken apart in Xtk's jailed worker */
    hosho_widget_add_worker_jobs();
    if (xtk_worker_is_worker(argc, argv)) return xtk_worker_main();

    setlocale(LC_ALL, "");
    Display *display = XOpenDisplay(NULL);
    if (!display) return 1;
    int screen = DefaultScreen(display);
    XIM input_method = xtk_ime_open(display);
    XtkClipboard *clipboard = xtk_clipboard_create(display);

    /* The Xtk theme: the scrollbar and the menu */
    static XtkConfig config;
    xtk_config_init_defaults(&config);
    XtkTheme *xtk_theme = xtk_theme_new();
    if (xtk_theme && xtk_theme_builtin("Dark", xtk_theme)) xtk_theme_apply(&config, xtk_theme);

    /* The terminal theme */
    static HoshoTheme theme;
    hosho_theme_builtin("Hosho Dark", &theme);

    Window window = XCreateSimpleWindow(display, DefaultRootWindow(display), 0, 0, 800, 480, 0, 0, 0);
    XSelectInput(display, window, StructureNotifyMask | FocusChangeMask);
    Atom delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
    XSetWMProtocols(display, window, &delete_window, 1);
    HoshoWidget *widget = hosho_widget_create(display, screen, window, 0, 0, 800, 480, &config, &theme, clipboard, input_method);
    if (!widget) return 1;
    hosho_widget_set_exit_callback(widget, on_program_end, NULL);

    /* 24 rows of 80 columns */
    int width;
    int height;
    hosho_widget_size_for(widget, 24, 80, &width, &height);
    XResizeWindow(display, window, (unsigned int)width, (unsigned int)height);
    hosho_widget_move_resize(widget, 0, 0, width, height);

    /* The user's shell, with the shell integration of the installed Hosho */
    if (!hosho_widget_start_shell(widget, NULL, "/usr/share/hosho/shell", NULL)) return 1;
    XMapWindow(display, window);

    int display_descriptor = ConnectionNumber(display);
    while (running) {
        while (running && XPending(display)) {
            XEvent event;
            XNextEvent(display, &event);
            if (XFilterEvent(&event, None)) continue; /* the input method's */
            if (event.type == ClientMessage && (Atom)event.xclient.data.l[0] == delete_window) running = 0;
            if (clipboard && xtk_clipboard_handle_event(clipboard, &event)) continue;
            if (hosho_widget_handle_event(widget, &event)) continue;
            if (event.type == ConfigureNotify && event.xany.window == window) {
                hosho_widget_move_resize(widget, 0, 0, event.xconfigure.width, event.xconfigure.height);
            }
            /* The window manager gives the keyboard to the window: it goes on to the terminal */
            if (event.type == FocusIn && event.xany.window == window && event.xfocus.detail != NotifyInferior) {
                XSetInputFocus(display, hosho_widget_get_window(widget), RevertToParent, CurrentTime);
            }
        }
        if (!running) break;
        hosho_widget_tick(widget); /* can call on_program_end */
        if (!running) break;
        XFlush(display);

        fd_set descriptors;
        FD_ZERO(&descriptors);
        FD_SET(display_descriptor, &descriptors);
        int highest = display_descriptor;
        int program = hosho_widget_descriptor(widget);
        if (program >= 0) {
            FD_SET(program, &descriptors);
            if (program > highest) highest = program;
        }
        struct timeval limit = {0, 30000}; /* the cursor's blink needs ticks */
        if (select(highest + 1, &descriptors, NULL, NULL, &limit) > 0 && program >= 0 && FD_ISSET(program, &descriptors)) {
            hosho_widget_read(widget);
        }
    }

    hosho_widget_destroy(widget);
    xtk_theme_free(xtk_theme);
    if (clipboard) xtk_clipboard_destroy(clipboard);
    xtk_ime_close(input_method);
    XCloseDisplay(display);
    return 0;
}

3. The event loop

The widget has no loop of its own: the host's loop calls it. It needs three things, in any order, again and again:

Call When What it does
hosho_widget_handle_event() For each X event. Takes the events of its own window, its scrollbar and its open menu: paint, keys, buttons, motion, focus, the pointer coming in and going out. It returns 1 when the event was the widget's, so the host can skip it, and 0 when it was not.
hosho_widget_read() When hosho_widget_descriptor() can be read. Reads what the program wrote, at most 1 MiB in one call so the window stays live under a flood, and gives it to the terminal. When the program has closed the terminal, the widget notes that it ended.
hosho_widget_tick() Often: the demo waits at most 30 milliseconds between two calls. Sends the bytes the program did not take yet, collects the program's exit status and calls the exit callback, gives the terminal the width of the window again when a program gave back the choice of 80 or 132 columns, makes the cursor and blinking text blink, scrolls while a selection is dragged past the edge, ends the visual bell, writes the log file to disk, and paints when something changed. While a program draws a frame with synchronized output (mode 2026), the paint waits for the frame's end, but at most one second.

Before the widget sees an event, the host gives it to XFilterEvent() when it uses an input method, and to xtk_clipboard_handle_event() when it has a clipboard. When the host's window changes size, it calls hosho_widget_move_resize().

The window manager gives the keyboard to the host's top window. A host whose terminal fills the window passes it on to the widget's window (hosho_widget_get_window()) on FocusIn, as the example does: the input method and the focus reports then work as in a program with more widgets. A host whose window has other widgets can instead give key presses that came to another window to hosho_widget_handle_key(), and say with hosho_widget_set_focused() whether the terminal has the keyboard. A click in the terminal takes the keyboard for the widget's window.

The widget paints only in hosho_widget_tick(). A host that changes the widget while a loop of its own runs (a modal dialog, for example a Preferences window that sets a new theme) calls hosho_widget_tick() after the change, or the change shows only when the main loop runs again.

The exit callback is called from hosho_widget_tick(), and it may destroy the widget: the tick returns at once after it. A host that destroys the widget there must not use it again in the same pass of its loop.

4. Making the widget

hosho_widget_create(display, screen, parent, x, y, width, height, theme, terminal_theme, clipboard, input_method) makes the widget's window as a child of parent and maps it. No program runs yet.

Parameter What it is
display, screen The X connection and the screen number.
parent, x, y, width, height The parent window, and the place and size in it, in pixels.
theme The Xtk theme (XtkConfig): the scrollbar's and the menu's colors and fonts. It must stay valid while the widget is used. It cannot be NULL.
terminal_theme The terminal's theme (see Themes), which is copied. NULL makes the terminal take the text view colors of the Xtk theme (background, text, selection, selection text, cursor), with the fallbacks for the rest, and follow the Xtk theme when it changes.
clipboard The host's clipboard from xtk_clipboard_create(), for copy and paste, PRIMARY and OSC 52. With NULL, nothing can be copied or pasted.
input_method The host's input method from xtk_ime_open(). With NULL, keys are read with XLookupString(), which gives Latin-1 only.

It returns NULL when the font of the theme cannot be opened, the terminal cannot be made, or memory ran out. The terminal's size in characters is what fits the window: the theme's padding on each side, the margin for the shell's marks on the left, and the scrollbar on the right are not part of it. The number of scrollback lines is the theme's scrollback-lines.

hosho_widget_destroy() closes the pseudoterminal, so a program that still runs gets SIGHUP, and collects its exit status if it has ended by then. It switches off the keyboard lights a program switched on, and releases the window and everything else. NULL is permitted.

5. Starting a program

Function What it does
hosho_widget_start(widget, arguments, directory) Starts a program in the terminal. arguments is the program and its arguments with NULL after the last, or NULL for the user's shell ($SHELL, then the password database, then /bin/sh). directory is where it starts, NULL for the current directory. The program gets TERM=xterm-256color, or with the theme's keyboard set to sun, hp, sco, rxvt or linux the terminal description of that keyboard (xterm-sun, xterm-hp, xterm-sco, rxvt-256color or rxvt, linux) when the system has it. Returns 1 when the program runs, 0 when it could not be started or a program runs already.
hosho_widget_start_shell(widget, shell, integration, directory) Starts a shell with Hosho's shell integration, when the shell has one. shell is its path, NULL for the user's shell. integration is the folder with the integration files: the installed /usr/share/hosho/shell or the source's shell/; NULL or "" starts the shell alone. See Shell Integration for each shell.
hosho_widget_is_running() 1 while a program runs, 0 when none does.
hosho_widget_descriptor() The descriptor the host's loop waits on for reading, or -1 when no program runs.
hosho_widget_shell_state() What the shell does, from its marks: HOSHO_SHELL_PROMPT (it waits at a prompt), HOSHO_SHELL_INPUT (text waits at the prompt), HOSHO_SHELL_RUNNING (a command runs), or HOSHO_SHELL_UNKNOWN when no program runs or the shell sends no marks. A host with tabs can show this on a tab that is out of view.
hosho_widget_directory(widget, directory, size) The directory the shell is in: what the shell said (OSC 7), or else the current directory of the program that was started, read from /proc. Returns 1 when it is known. A host uses it to open a file a link names, or to start a new terminal in the same place.

When the program ends, the widget keeps its screen and scrollback, and a new program can be started in it. Starting a program forgets the shell marks of the one before.

6. Size

hosho_widget_move_resize(widget, x, y, width, height) moves and resizes the widget's window. The terminal gets the number of rows and columns that fits, its text is wrapped again for a new width, and the program is told the new size (it gets SIGWINCH). hosho_widget_size_for(widget, rows, columns, &width, &height) gives the size in pixels that shows that many rows and columns; the demo uses it to size its window and to tell the window manager the steps of one character (hosho_widget_size_for() of 0 and of 1 row and column).

A program can ask for a size itself, and the resize callback (hosho_widget_set_resize_callback()) hears of it with the rows and columns: a request in characters (CSI 8 t) and the page size (DECSCPP, DECSLPP, DECSNLS), when the theme has window-ops = 1; and 132 or 80 columns (DECCOLM, which a program can do only after it set mode 40). The callback is also called when a status line comes or goes, with the same size: it takes the row below the screen. The host can make its window fit, as the demo does, or do nothing. While a program may choose 80 or 132 columns, the widget keeps the width it chose and what does not fit the window is not seen; when it gives that back, the width follows the window again.

7. Themes

Function What it does
hosho_widget_set_terminal_theme(widget, terminal_theme) Gives the terminal a theme of its own, which is copied: the font, the margins, every color and style, and the settings. The change shows at once: the fonts are opened again, the size in characters follows the new cell size, and the program is told it. A new scrollback-lines keeps the newest lines and drops the selection and the search's match. NULL goes back to the Xtk theme's text view colors.
hosho_widget_get_terminal_theme() The theme in use, with the font size the user chose with the size keys. A host that changes one key copies it, changes the copy and sets it again.
hosho_widget_set_theme(widget, theme) Takes the Xtk theme again after the host changed it: the scrollbar and the menu, and the terminal's colors when it has no theme of its own.

8. Callbacks

Each callback is set with its function, NULL to remove it, and a user_data pointer that is given back. Each gets the widget first.

Set with Called when
hosho_widget_set_title_callback() The program sets the window title (OSC 0, OSC 2, or a title taken back from the title stack). The title is UTF-8.
hosho_widget_set_icon_name_callback() The program sets the name of the window's icon (OSC 0, OSC 1).
hosho_widget_set_exit_callback() The program ended, one time for each program, with its status as waitpid() gives it. Called from hosho_widget_tick(); it may destroy the widget.
hosho_widget_set_link_callback() The user opens a link: Control and a click, Open Link in the menu, or a letter after Control+Shift+O. The HoshoLink says what it is: HOSHO_LINK_ADDRESS for a hyperlink a program made (explicit_link is 1) or an address found in the text, HOSHO_LINK_FILE for a file name with its line and column (0 when not given). A file name is a guess from the text's form: the host decides whether the file exists, and finds a name with no directory in hosho_widget_directory(). Without this callback, Open Link is grey.
hosho_widget_set_notify_callback() A program asks for the user's attention (OSC 9, OSC 777;notify, OSC 99), with a title that can be NULL and a body. Also when a command of the shell that ran notify-command-seconds or more ends while the terminal does not have the keyboard: the title is "Command done" or "Command failed", and the body says how long it ran and its status.
hosho_widget_set_bell_callback() The program rang the bell, after the widget made the sound or the flash the theme's bell asks for. A host can mark its window, as the demo does with the urgency hint.
hosho_widget_set_progress_callback() A program tells how far a job is (OSC 9;4): state 0 for no job, 1 for a job at percent, 2 for an error, 3 for a job with no known end, 4 for a job that waits. The widget also draws a thin bar at its top.
hosho_widget_set_shell_callback() The shell's state changes (see hosho_widget_shell_state()).
hosho_widget_set_command_callback() A command of the shell ended (shell integration), with its exit status and how many seconds it ran.
hosho_widget_set_resize_callback() The program asks for another size in characters, or a status line comes or goes (see section 6).
hosho_widget_set_window_callbacks(widget, callback, report_callback, user_data) The window functions and reports a program asks for (CSI t), only when the theme has window-ops = 1. callback gets a HoshoWindowFunction (show, iconify, move to x, y, size the text area in pixels, raise, lower, maximize, full screen) and two numbers; the widget repaints for the refresh function itself. report_callback gets a HoshoWindowReport (is the window an icon, its position, the screen's size) and returns 1 when it filled the two numbers. The Host Functions has the numbers of each.

The widget does some host functions itself, with no callback: it answers reports, gives the clipboard to a program when the theme permits it, switches the keyboard lights (DECLL, through the X keyboard extension), changes the pointer's shape (OSC 22), writes the log file, and sends what a program prints to the theme's print-command.

9. Doing things from the host

These functions do what the user can do with keys or the menu, so a host can put them in its own menus and toolbars.

Function What it does
hosho_widget_send(widget, text, length) Types the bytes into the program, as if the user typed them, and shows the screen's last lines.
hosho_widget_paste(widget, text) Pastes UTF-8 text: made safe, and between the paste marks when the program asked for them. A text of more than one line, to a program that does not mark pastes, asks the user first (see The Widget in Use), unless the theme has paste-confirm = 0.
hosho_widget_paste_clipboard() Pastes the clipboard's text, as Control+Shift+V does.
hosho_widget_copy(widget, as_html) Copies the selection to the clipboard: plain text, or with 1 an HTML pre element with the text's colors, bold, italic, underline and strike. A rectangle selection is always plain text.
hosho_widget_selection_text() The selected text, which the caller frees, or NULL when nothing is selected.
hosho_widget_select_all() Selects the scrollback and the screen (only the screen on the alternate screen), and gives it to PRIMARY.
hosho_widget_find() Opens the search bar, empty.
hosho_widget_clear_scrollback() Removes the lines of the scrollback.
hosho_widget_reset() Puts the terminal in the state it had at its start, as RIS does; the scrollback stays.
hosho_widget_show_menu(widget, x, y) Opens the widget's menu as the right mouse button does. The place, in the widget's window, decides which link and which command the menu's items are for.
hosho_widget_handle_key(widget, event) Gives the widget a key press, or a key release, that came to another window of the host. Returns 1 when the widget took the key.
hosho_widget_set_focused(widget, focused) Tells the widget whether it has the keyboard. The cursor then blinks or is hollow, the input method follows, and a program that asked for focus reports gets one. The widget does this by itself from its own window's focus events.
hosho_widget_get_window() The widget's window.
hosho_widget_get_terminal() The terminal, to read its screen, title and modes. The demo prints the last screen with it.

10. The host's items in the menu

The widget's menu (the right mouse button) has the terminal's own items. A host adds its own items after them with hosho_widget_add_menu_item(widget, label, accelerator, callback, user_data): the item's words, the keys the menu shows beside it (for example "Ctrl+Shift+T", or NULL), and the function called when the user chooses it. A label of "" is a separator, and its callback is never called (pass NULL). The host's items come below a separator, in the order they were added; at most 12 can be added, separators with them. The function returns the item's number, from 0, which the callback gets, or -1 when there is no room.

hosho_widget_set_menu_item_enabled(widget, item, enabled) makes an item grey (0) or usable again (1). The accelerator is only shown: the host reads the keys itself. Hanshi adds New Tab, Close Tab and Preferences this way, and the widget's own items do not change for it.

11. Pictures and the jailed worker

What a program sends can be hostile, and taking a picture apart is where a bug lets it in. So the widget never takes a picture apart in the program itself. Every picture goes to Xtk's jailed worker (xtk_worker.h): a process of the program's own that can read no file, write nothing, reach no network, and start or signal nothing. That covers picture files (PNG, JPEG, GIF and BMP, for iTerm2's inline images and kitty's f=100), sixel data, zlib-compressed data (kitty's o=z), and the theme's background picture. Each answer is checked before it is shown; a request that takes more than 5 seconds is given up, and the worker is started again for the next one. Kitty's raw pixels (f=24 and f=32 without o=z) are not a file to take apart: the terminal copies them into a picture itself, after it checked their size.

A program that uses the widget adds the widget's jobs to the worker and starts the worker at the very top of main(), before it does anything else:

hosho_widget_add_worker_jobs();
if (xtk_worker_is_worker(argc, argv)) return xtk_worker_main();

The worker is the same program started again with another name, so both must add the same jobs in the same order: that is why hosho_widget_add_worker_jobs() comes before xtk_worker_is_worker(). Without it the widget shows no sixel picture and no compressed picture; picture files are a job of Xtk's own and need only the worker. The jail needs Linux 5.13 or later with Landlock, on x86-64 or ARM64. Without the jail there is no worker, and the widget shows no picture except Kitty's raw pixels. Pictures has the protocols, and The Host Functions has the three functions the widget gives the terminal for this.

12. Known limitations

  • The keyboard lights a program switches follow only when the X server lets them: a light that shows a lock key's state can stay as the key says.
  • The menu is made the first time it opens, and again after the host adds an item.