Writing a Host
How to use the library without the widget: for a terminal in another toolkit, a test that checks what a program draws, or a recorder. This page has a complete example, then explains the event loop, the pseudoterminal, how to read and draw the screen, and the questions a host can ask about the text.
1. A complete example
This program runs the command named on its command line (or the user's shell) in a terminal of 24 rows and 80 columns, and prints the screen the command leaves, as plain text. It needs nothing but the library: cc -std=gnu17 -I/usr/include/hosho screen_text.c -lhosho -o screen_text, then for example ./screen_text ls -l --color.
/* screen_text.c - run a program in a Hosho terminal and print the screen it leaves */
#include <poll.h>
#include <stdio.h>
#include "hosho.h"
/* The terminal answers a report request: the answer goes to the program */
static void host_reply(void *user, const char *bytes, size_t length) {
hosho_pseudoterminal_write(user, bytes, length);
}
int main(int argc, char **argv) {
static const HoshoTerminalHost host = {.reply = host_reply};
HoshoPseudoterminal pseudoterminal;
/* The program named on the command line, or the user's shell */
const char *const *arguments = argc > 1 ? (const char *const *)&argv[1] : NULL;
if (hosho_pseudoterminal_spawn(&pseudoterminal, arguments, NULL, 24, 80) != 0) return 1;
HoshoTerminal *terminal = hosho_terminal_create(24, 80, 1000, &host, &pseudoterminal);
if (!terminal) return 1;
char bytes[65536];
for (;;) {
struct pollfd wait_for = {.fd = pseudoterminal.descriptor, .events = POLLIN};
poll(&wait_for, 1, -1);
ssize_t count = hosho_pseudoterminal_read(&pseudoterminal, bytes, sizeof(bytes));
if (count < 0) break; /* the program ended */
hosho_terminal_feed(terminal, bytes, (size_t)count);
}
int status = 0;
hosho_pseudoterminal_close(&pseudoterminal);
hosho_pseudoterminal_wait(&pseudoterminal, &status, 1);
for (int row = 0; row < terminal->screen.rows; row++) {
char line[2048];
hosho_screen_line_text(&terminal->screen, row, line, sizeof(line));
printf("%s\n", line);
}
hosho_terminal_destroy(terminal);
return 0;
}
Every host has these parts: a pseudoterminal with the program on it, a terminal of the same size, a loop that gives the terminal what the program writes, and at least the reply host function, because programs ask the terminal questions (where is the cursor, what are you) and wait for the answer. A real host adds drawing, keys and the other host functions.
2. The pseudoterminal
| Function | What it does |
|---|---|
hosho_pseudoterminal_spawn(pseudoterminal, arguments, directory, rows, columns) |
Makes a pseudoterminal of that size and starts the program on it, as the controlling terminal of a new session. arguments is the program and its arguments with NULL after the last (the program is looked for in PATH), or NULL for the user's shell. directory is where it starts, NULL for the current directory, which it also gets when it cannot change to that one. Returns 0, or -1 with errno set. A program that cannot be run ends at once with status 127. |
hosho_pseudoterminal_spawn_environment(pseudoterminal, arguments, variables, directory, rows, columns) |
The same, with "NAME=value" entries (NULL after the last) that the program gets in place of the host's variables of those names. |
hosho_pseudoterminal_read(pseudoterminal, bytes, size) |
Reads what the program wrote. It does not block: it returns the number of bytes, 0 when there is nothing to read now, or -1 when the program closed the terminal (it ended) or on an error. |
hosho_pseudoterminal_write(pseudoterminal, bytes, length) |
Writes to the program, as if typed. It does not block, so it can write fewer bytes than asked, or 0 when the program reads nothing now: the host keeps the rest and writes it later. Returns -1 on an error. |
hosho_pseudoterminal_resize(pseudoterminal, rows, columns, pixel_width, pixel_height) |
Tells the program the size of the screen (it gets SIGWINCH). The pixel sizes are those of the text area, 0 when not known; programs that draw pictures read them. |
hosho_pseudoterminal_wait(pseudoterminal, &status, block) |
Collects the program's exit status, as waitpid() gives it: with block 1 it waits until the program ends, with 0 it only looks. Returns 1 when the program ended (now or before), 0 when it still runs, -1 on an error. |
hosho_pseudoterminal_close(pseudoterminal) |
Closes the host's end. The kernel then sends SIGHUP to the program, as when a terminal window closes. The process stays until hosho_pseudoterminal_wait() collects it. |
hosho_pseudoterminal_user_shell() |
The user's shell: $SHELL, then the password database, then /bin/sh. Each of the first two counts only when it is a full path (it starts with /). |
hosho_pseudoterminal_shell_start(shell, folder, &start) |
The arguments and variables that start a shell with Hosho's shell integration and change no file of the user's; see Shell Integration. |
The program gets the host's environment with TERM=xterm-256color and COLORTERM=truecolor, and without the host's COLUMNS, LINES and TERMCAP, which describe another terminal. It gets the default action for each signal and no blocked signal, even when the host ignores or blocks some, and none of the host's open files. The pseudoterminal knows its input is UTF-8, so an erase removes a whole character. HoshoPseudoterminal.descriptor is the host's end, for its poll() or select(); child is the program's process id. The library itself never sends a signal.
3. The event loop
A host waits on the pseudoterminal's descriptor together with its own events (an X connection, a toolkit's loop). When the descriptor can be read, it reads until hosho_pseudoterminal_read() gives 0, and gives each piece to hosho_terminal_feed(). A piece can end in the middle of a character or a sequence: the terminal keeps the start for the next piece. A host that must stay live under a flood reads a limited amount at a time (the widget reads at most 1 MiB) and draws in between.
When the read gives -1, the program has ended. The host closes the pseudoterminal and collects the exit status, and calls hosho_terminal_shell_forget() so that the marks of a shell that ended say nothing about what comes next. The terminal and its screen stay until hosho_terminal_destroy().
The terminal is not safe to use from two threads at once; a host uses each terminal from one thread. hosho_theme_read() reads into a buffer of its own, so it is not to be called from two threads at once either.
4. Making the terminal and changing its size
hosho_terminal_create(rows, columns, scrollback_limit, host, user) makes a terminal: rows and columns are 1 or more, scrollback_limit is the most lines of scrollback (0 for none), host is the host functions (it can be NULL, and must stay valid while the terminal is used), and user is given back to each host function. It returns NULL when memory ran out or a size is not correct. A new terminal has white text (#E5E5E5) on black and xterm's 256 colors until the host gives it a theme (hosho_theme_apply()), and the cell size of a VT340 (10 by 20 pixels) until the host tells its own.
When the window changes size, the host calls hosho_terminal_resize(terminal, rows, columns) and hosho_pseudoterminal_resize() with the same size. A new width wraps the text of the primary screen and the scrollback again, and the cursor stays with its text. When only the height changes, empty lines below the cursor go first, then lines from the top move to the scrollback; a taller screen takes lines back from the scrollback. The alternate screen is cut or padded: the full-screen program on it draws again after SIGWINCH. The scroll region and the margins become the whole screen. The function returns 0, or -1 when a size is less than 1 or memory ran out; the terminal is then still correct, with its size in screen.rows and screen.columns.
hosho_terminal_set_cell_size(terminal, width, height) tells the terminal the size of a cell in pixels: pictures and the size reports use it. A program can also ask for a size itself; the resize host function hears of it (see The Host Functions).
5. Reading the screen
terminal->screen is a HoshoScreen: rows and columns, the buffer in use (alternate_active is 1 for the alternate screen), and the scrollback (scrollback_count lines). Read the fields; change them only through the functions. hosho_screen_line(screen, row) gives a line: rows 0 and up are the screen, -1 is the newest line of the scrollback, -2 the one before, and so on. It returns NULL for a row that does not exist.
HoshoLine field |
What it says |
|---|---|
cells, length |
The cells. A screen line has at least columns cells; a scrollback line has only those up to its last one in use. Take the cells after length as empty. |
dirty |
The line changed since the last hosho_screen_clear_dirty(). A host draws the lines that are dirty, then clears the marks. |
wrapped |
The line was full and its text goes on on the next line. Selection and search join such lines. |
size |
HOSHO_LINE_SINGLE, HOSHO_LINE_DOUBLE_WIDTH, or the top or bottom half of a line of double width and height (HOSHO_LINE_DOUBLE_TOP, HOSHO_LINE_DOUBLE_BOTTOM). A line of double size holds half the columns, each two cells wide. |
mark, status, input_column, folded |
The shell's marks: a prompt or a command's output starts on the line, how the prompt's command ended, where the user's command starts, and whether a display hides the command's output (hosho_screen_set_folded()). See Shell Integration. |
HoshoCell field |
What it says |
|---|---|
character |
A code point; 0 when nothing was written there. With HOSHO_CELL_CLUSTER set, a character with combining marks (or an emoji of more than one code point): hosho_screen_cell_text() gives the cell's text as UTF-8 in a buffer of HOSHO_CELL_TEXT_SIZE bytes, and hosho_screen_cell_codepoints() gives its code points. With HOSHO_CELL_IS_IMAGE() true, the cell shows a part of a picture (see Pictures). |
foreground, background |
A HoshoColor: the default, one of the 256 palette colors, or red, green and blue. hosho_terminal_color(terminal, color, is_background) gives the 0xRRGGBB to draw it with. |
attributes |
HOSHO_ATTRIBUTE_* bits: bold, faint, italic, blink, inverse, invisible, strike, overline; WIDE on the first cell of a wide character and WIDE_TAIL on its second; PROTECTED; UNDERLINE_COLOR when the underline has its own color. |
underline |
HOSHO_UNDERLINE_NONE, SINGLE, DOUBLE, CURLY, DOTTED or DASHED; its color is underline_red, underline_green, underline_blue when HOSHO_ATTRIBUTE_UNDERLINE_COLOR is set. |
link |
The hyperlink the cell is a part of (OSC 8), or 0. hosho_screen_link_address(screen, link) gives its address. |
A wide character fills its cell and the one after it: draw it from the first cell, and skip the cell with WIDE_TAIL. A cell of all zero bits is an empty cell with the default colors.
6. Drawing
hosho_terminal_color() does not exchange the colors of a cell with HOSHO_ATTRIBUTE_INVERSE, and does not follow reverse video (HOSHO_MODE_REVERSE_VIDEO, DECSCNM): the host does that, so it can decide how reverse video looks with its theme. The same is true of faint, invisible and blinking text, and of a theme's styles for the attributes and its rules: they are the display's. The default colors a program can change are terminal->foreground, background and cursor_color.
The terminal marks a line dirty when its cells change, and marks every line when a color the screen uses changes (the palette, the default colors, reverse video). A host that shows old lines while new output scrolls the screen reads screen.scrollback_total, the number of lines that ever went to the scrollback, to keep its view on the same lines.
The cursor is at cursor_row and cursor_column of the screen. cursor_shape is a HoshoCursorShape (block, underline, bar). Draw it when HOSHO_MODE_CURSOR_VISIBLE is set, and make it blink when HOSHO_MODE_CURSOR_BLINK is set. When the cursor stands on the last column after a character was written there, wrap_pending is 1: the next character goes to the next line.
Other modes the display reads with hosho_terminal_mode(): HOSHO_MODE_SYNCHRONIZED_OUTPUT (the program asks the host not to draw until it resets the mode; a host should not wait long), HOSHO_MODE_BIDI_IMPLICIT and HOSHO_MODE_BIDI_AUTODETECT (show right-to-left text in its order: hosho_bidi_order() gives the order of a line's characters), and HOSHO_MODE_ALTERNATE_SCREEN.
hosho_terminal_status_line(terminal, &columns) gives the cells of a status line, or NULL when the program asked for none; status_dirty is 1 when it changed, and the host sets it to 0 after it drew the line. With the terminal's own indicator line (status_type 1), the terminal writes the cursor's position and the modes into it each time it is asked for.
7. Keys, the mouse and paste
A host turns its own key codes into HoshoKey (keys that send a sequence) or into characters, and sends the bytes the input encoder gives: hosho_input_key_event() first, for the Kitty keyboard protocol, then hosho_input_key() or hosho_input_character(). Mouse events go to hosho_input_mouse() when hosho_input_mouse_wanted() says the program asked for them, a change of focus to hosho_input_focus(), and pasted text to hosho_input_paste(). Each function reads the modes the program set and gives 0 bytes when the program asked for nothing. Keyboard, Mouse and Paste has what each one sends.
For shell integration, a host gives what the user types or pastes to hosho_terminal_typed() as well, at the moment it sends it to the program: the terminal does not show these bytes, but learns from them where the user's command starts and, for a shell that cannot tell, that a command starts. With local echo (HOSHO_MODE_LOCAL_ECHO, which a program sets by resetting SRM), the host also feeds the typed bytes to the terminal to show them.
8. Questions about the text
hosho_text.h gives a host more than a grid of cells. A place is a HoshoPosition (a row as for hosho_screen_line(), negative for the scrollback, and a column), and a run of cells is a HoshoTextRange from start to end, both in it.
| Function | What it gives |
|---|---|
hosho_text_range(screen, range, &length) |
The text of a range, as UTF-8 that the caller frees. Lines that continue on the next are joined; other lines end with a line feed; empty cells at a line's end are left out. This is the text of a selection. |
hosho_text_rectangle(screen, range, &length) |
The text of a rectangle: of each row, the columns from the range's first column to its last, with a line feed between the rows. |
hosho_text_range_html(screen, range, color, user, &length) |
The text of a range as an HTML pre element with its colors, bold, italic, underline and strike. color is a function that gives the 0xRRGGBB of a cell's color (a host wraps hosho_terminal_color()). |
hosho_text_search(screen, needle, case_sensitive, from, direction, &found) |
The next match of a text after from (direction 1) or before it (-1), through the screen and the scrollback (on the alternate screen, only the screen). Returns 1 when it found one. Without case_sensitive, only the letters A to Z match their small letters. A cell is compared by its first code point, so combining marks are not part of a match. |
hosho_text_search_pattern() |
The same for a POSIX extended regular expression. Without case_sensitive, the C library ignores case as the locale says. A match is within one line of text (a line that continues on the next row is one line), and a match of no characters is not a match. Returns 0 also for a pattern that is not correct. |
hosho_text_search_row(), hosho_text_search_pattern_row() |
Every match that has a cell on one row, for a display to mark; each can start or end on another row. |
hosho_text_link_at(screen, position, &link) |
The link at a cell: a hyperlink a program made, an address with a scheme and ://, or a file name with an optional line and column (src/main.c:120:8). The HoshoLink has its kind, its text (the address, or the file name without line and column), the line and column, whether a program made it (explicit_link), and its cells. A file name is a guess from the text's form: the host decides whether the file exists. |
hosho_address_at(characters, count, at, &start, &end) |
The web or mail address around one character of a line given as code points, found as hosho_text_link_at() finds one: a scheme and ://, or mailto:; a full stop, comma or closing bracket with no opening one at its end left out. For a host that finds addresses in text of its own, such as an editor. |
hosho_text_block_at(screen, row, &block) |
The command a line is part of, from the shell's marks: the HoshoBlock has the prompt's row, the row where the output starts (more than end_row when there is none), the last row, the command's status, and complete, which is 1 when a later prompt follows. There are no blocks on the alternate screen. |
Search and links read one logical line at a time: lines that continue on the next row are one line of text, so a match or an address can go over the end of a row.
9. Changing the screen from the host
A host does not write cells itself, but a few functions of hosho_screen.h are for the display: hosho_screen_set_folded() hides or shows the output of a prompt's command, hosho_screen_clear_scrollback() removes the scrollback, hosho_screen_set_scrollback_limit() changes how many lines it keeps (the newest stay), and hosho_screen_mark_dirty() marks every line of the buffer in use, after the host changed how it draws. hosho_terminal_reset() puts the terminal in the state it had after hosho_terminal_create(), as RIS does; the scrollback, the defaults the host set and its permissions stay.
Hosho API
The whole library
From bytes to a screen
For the host that shows it
The program