Files

63 KiB
Raw Permalink Blame History

libgemui C11 API Reference & Developer Guide

libgemui is a C11 immediate-mode UI toolkit built directly on X11, Cairo, and Pango/HarfBuzz. This document covers the complete public API declared in gemui.h, exact runtime semantics derived from the implementation, theming/scaling behavior, and complete real-world application patterns.


Table of Contents

  1. Architecture & Mental Model
  2. Headers, Building & Linking
  3. Constants, Data Types & Callback Typedefs
  4. Application Lifecycle, Windowing & Scaling
  5. Event Loop, Input, Timers, File Descriptors & Toasts
  6. Immediate-Mode Hit-Testing
  7. Drawing Primitives, Typography & Built-In Widgets
  8. Theming, Colors & Live Reload
  9. Modal File Open & Save Dialogs
  10. System, IPC, Subprocess & UTF-8 Utilities
  11. Real-World Application Recipes
  12. Pitfalls & Best Practices Checklist

1. Architecture & Mental Model

Demand-Driven Immediate Mode

Unlike retained widget trees (GTK/Qt) or continuous 60 FPS game loops, libgemui uses a demand-driven immediate-mode architecture:

  • Your application owns all UI state (input text buffers, toggle booleans, slider values, active focus index, scroll offsets).
  • Nothing redraws unless needed. gemui_run() sleeps in poll() until an X11 event, timer tick, registered file descriptor, SIGUSR1, or toast expiration occurs, and only renders a frame when need_redraw is set.
  • Widgets are drawn and registered per frame. Inside your on_draw callback, you compute coordinates, draw controls using gemui_draw_*(), and pass a hit_id/hit_val pair. On pointer events (on_ptr), you call gemui_hit_test(app, x, y) to find which control was hit, mutate your state, and call gemui_request_redraw(app).

Per-Frame Rendering Pipeline

Whenever a frame is rendered (gemui_render_frame), libgemui executes these exact steps:

  1. Clears the hit-region table (gemui_hits_clear(app)).
  2. Fills the entire backbuffer (0, 0, w, h) with theme->bg_main.
  3. Invokes handlers.on_draw(app, cr, w, h, userdata).
  4. If a modal file dialog is open, renders the dimmed backdrop and dialog UI on top (replacing the application's interactive layer until closed).
  5. If an active toast exists, renders gemui_draw_toast(app, cr) centered near the bottom edge.
  6. Copies the CAIRO_FORMAT_RGB24 image surface into an X11 Pixmap backbuffer, maps the window on the first frame (for non-override windows), blits via XCopyArea, and flushes X11.

Logical vs. Physical Coordinates

  • Logical pixels are resolution-independent sizes you design against (for example, 42 for a header, 36 for a button, 12 for padding).
  • Physical pixels are actual X11 window pixel coordinates.
  • Convert logical layout constants with gemui_scale_px(app, logical_px) or gemui_touch_row_px(app, logical_px).
  • The dimensions passed to on_draw(app, cr, w, h, ud), on_resize(app, w, h, ud), gemui_width(app), gemui_height(app), on_ptr(..., x, y, ...), and every gemui_rect_t in drawing functions are physical pixels.

Threading & Single-Instance Constraints

  • libgemui is not thread-safe. All gemui_* calls (including gemui_request_redraw) must run on the thread running gemui_run().
  • To wake the UI thread from a worker thread, create a pipe() or Linux eventfd(), register the read end with gemui_add_fd(), write a byte from the worker thread, and drain + call gemui_request_redraw() inside the gemui_fd_cb.
  • Internally, SIGUSR1 delivery uses a process-global self-pipe (g_sig_pipe) and frame rendering temporarily stores the active PangoLayout in a static pointer. Plan on one gemui_app_t instance per process.

2. Headers, Building & Linking

Include the single public header:

#include <gemui.h>

gemui.h uses #ifdef __cplusplus extern "C" guards and transitively includes: <stdbool.h>, <stddef.h>, <stdint.h>, <X11/Xlib.h>, <X11/keysym.h>, and <cairo/cairo.h>.

Compiling Against an Installed Library

cc -std=c11 -Wall -Wextra -O2 main.c $(pkg-config --cflags --libs gemui) -o myapp

gemui.pc sets -I${includedir}, -L${libdir}, -Wl,-rpath,${libdir}, -lgemui, and -lm, and lists X11/Cairo/Pango/HarfBuzz/Fontconfig/FreeType2 in Requires.private.

Compiling Against a Vendored Static Archive

make -C third_party/libgemui static
cc -std=c11 -Wall -Wextra -O2 -Ithird_party/libgemui main.c \
  third_party/libgemui/build/libgemui.a \
  $(pkg-config --libs x11 xext xft xinerama xrandr cairo pangocairo pango harfbuzz fontconfig freetype2) \
  -lm -o myapp

Build-time macro ANODE_PREFIX: When building libgemui via Makefile, -DANODE_PREFIX="\"$(ANODE_PREFIX)\"" (defaulting to $(PREFIX), /usr/local) defines the fallback directory searched for <ANODE_PREFIX>/share/anode/themes/Anodized.xth.


3. Constants, Data Types & Callback Typedefs

Constants

Text & Icon Alignment

Constant Value Meaning
GEMUI_ALIGN_LEFT 0 Left-align text inside r
GEMUI_ALIGN_CENTER 1 Horizontally center text inside r
GEMUI_ALIGN_RIGHT 2 Right-align text inside r

(Vertical alignment is always centered inside r.)

Pointer Event Types

Constant Value When Emitted in on_ptr
GEMUI_PTR_DOWN 0 Mouse button pressed (btn = X11 button, e.g. Button1, Button3)
GEMUI_PTR_MOVE 1 Pointer moved while a mouse button is held down (btn is 0)
GEMUI_PTR_UP 2 Mouse button released (btn = X11 button)
GEMUI_PTR_SCROLL_UP 3 Scroll wheel up (Button4, btn is Button4)
GEMUI_PTR_SCROLL_DOWN 4 Scroll wheel down (Button5, btn is Button5)

Capacity Limits

Constant Value Meaning
GEMUI_MAX_HITS 256 Maximum hit regions registered per frame via gemui_hit_add()
GEMUI_MAX_FDS 16 Maximum custom file descriptors registered via gemui_add_fd()

Data Types

gemui_color_t

typedef struct {
  double r;
  double g;
  double b;
  double a;
  uint32_t argb;
} gemui_color_t;

Color channels are normalized [0.0, 1.0] for Cairo, alongside packed 0xAARRGGBB in argb. Construct manually or parse #RRGGBB hex strings with gemui_color_parse().

gemui_rect_t

typedef struct {
  int x;
  int y;
  int w;
  int h;
} gemui_rect_t;

Axis-aligned rectangle in physical pixels. Hit tests check x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h.

gemui_hit_t

typedef struct {
  gemui_rect_t r;
  int id;
  int val;
} gemui_hit_t;

A registered clickable region linking a physical rectangle r to application-defined integers id and val (for example, id = HIT_ROW, val = row_index).

gemui_theme_t

typedef struct {
  char name[64];
  char font_face[96];
  char icon_font_face[96];
  int base_font_size;
  int dpi;
  double scale;
  bool touch_mode;
  gemui_color_t bg_main;
  gemui_color_t bg_bar;
  gemui_color_t bg_header;
  gemui_color_t bg_footer;
  gemui_color_t bg_overlay;
  gemui_color_t bg_alt_even;
  gemui_color_t bg_alt_odd;
  gemui_color_t bg_input;
  gemui_color_t bg_input_focus;
  gemui_color_t bg_button;
  gemui_color_t bg_search;
  gemui_color_t bg_bubble_in;
  gemui_color_t bg_bubble_out;
  gemui_color_t bg_toast;
  gemui_color_t fg_main;
  gemui_color_t fg_bright;
  gemui_color_t fg_muted;
  gemui_color_t sel_bg;
  gemui_color_t sel_fg;
  gemui_color_t accent;
  gemui_color_t accent_alt;
  gemui_color_t highlight;
  gemui_color_t border;
  gemui_color_t divider;
  gemui_color_t success;
  gemui_color_t info;
  gemui_color_t warning;
  gemui_color_t danger;
  gemui_color_t danger_bg;
} gemui_theme_t;

Read-only snapshot accessible via gemui_theme(app). Note that base_font_size holds the resolved pixel font size after DPI scaling (unless overridden explicitly in .Xresources). See Section 8 for every field's .Xresources key and default color.

gemui_app_t

typedef struct gemui_app gemui_app_t;

Opaque handle representing the X11 display connection, window, Cairo/Pango rendering context, theme, event loop state, hit list, file descriptors, timer, and optional modal file dialog.

gemui_handlers_t

typedef struct {
  void (*on_draw)(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud);
  void (*on_key)(gemui_app_t *app, KeySym ks, unsigned int state, const char *utf8, void *ud);
  void (*on_ptr)(gemui_app_t *app, int type, int x, int y, unsigned int btn, void *ud);
  void (*on_theme)(gemui_app_t *app, void *ud);
  void (*on_resize)(gemui_app_t *app, int w, int h, void *ud);
} gemui_handlers_t;

All fields are optional (NULL is safe). Zero-initialize the struct before filling only the handlers you need.

gemui_file_dialog_mode_t & gemui_file_dialog_opts_t

typedef enum {
  GEMUI_FILE_OPEN = 0,
  GEMUI_FILE_SAVE = 1
} gemui_file_dialog_mode_t;

typedef struct {
  gemui_file_dialog_mode_t mode;
  const char *title;            /* optional title ("Open File" / "Save File") */
  const char *initial_dir;      /* optional starting dir (supports ~, else cwd) */
  const char *initial_name;     /* optional initial filename for Save mode */
  const char *filter_exts;      /* optional comma/semicolon list, e.g. ".htab,.csv" */
  const char *default_ext;      /* optional extension appended on Save if missing */
  const char *ok_label;         /* optional confirm button label ("Open" / "Save") */
  bool show_hidden;             /* initial dotfiles visibility (default false) */
  bool no_confirm_overwrite;    /* false (default) prompts before Save overwrite */
} gemui_file_dialog_opts_t;

Callback Typedefs

typedef void (*gemui_fd_cb)(gemui_app_t *app, int fd, void *ud);
typedef void (*gemui_timer_cb)(gemui_app_t *app, void *ud);
typedef bool (*gemui_close_cb)(gemui_app_t *app, void *ud);
typedef void (*gemui_file_dialog_cb)(gemui_app_t *app, bool accepted,
                                     const char *path, void *userdata);
  • gemui_fd_cb: Called from gemui_run() when a registered fd reports POLLIN, POLLHUP, or POLLERR.
  • gemui_timer_cb: Called repeatedly by gemui_run() when the interval elapses.
  • gemui_close_cb: Called when the window manager sends WM_DELETE_WINDOW. Return true to exit gemui_run() with code 0, or false to ignore the close request.
  • gemui_file_dialog_cb: Called when the user confirms (accepted == true, path non-NULL) or cancels (accepted == false, path == NULL) the file dialog.

4. Application Lifecycle, Windowing & Scaling

gemui_create

gemui_app_t *gemui_create(const char *res_name, const char *title,
                          int w, int h, bool fullscreen_override);

Creates the X11 connection, loads theme & DPI settings, creates the window, initializes XIM/XIC UTF-8 input, and configures SIGUSR1 live theme reloading.

  • res_name: Sets both XClassHint.res_name and res_class. Pass NULL to default to "anode-app".
  • title: Sets WM_NAME and _NET_WM_NAME (UTF8_STRING). Pass NULL to default to "ANODE".
  • w, h:
    • When fullscreen_override == false (normal window):
      • Treated as logical pixels and scaled by gemui_scale(app).
      • Picks the Xinerama monitor currently containing the mouse pointer (or screen 0) and intersects it with EWMH _NET_WORKAREA so panels/docks are respected.
      • If w <= 0, uses the full workarea width of that monitor; otherwise clamps scaled width between scale_px(260) and workarea_w - scale_px(24).
      • If h <= 0, uses the full workarea height of that monitor; otherwise clamps scaled height between scale_px(180) and workarea_h - scale_px(32).
      • Centers the window on that monitor's workarea.
      • The window is mapped lazily during the first rendered frame (gemui_run() or gemui_flush_draw()), eliminating initial uninitialized flashes.
    • When fullscreen_override == true (lockscreen / global overlay):
      • Creates an override_redirect = True window spanning the entire virtual X11 desktop (DisplayWidth x DisplayHeight) across all monitors, and sets _NET_WM_STATE_FULLSCREEN.
      • Computes gemui_primary_monitor_rect() via XRandR (XRRGetOutputPrimary, falling back to the pointer monitor/full screen).
      • Subscribes to XRandR screen change and root window stacking/visibility events so it stays raised above normal windows while still allowing an on-screen keyboard (res_name == "anode-vkbd") above it.
      • Maps immediately (XMapRaised), saves the previously focused window, and focuses itself.
  • Side effects: Calls setlocale(LC_CTYPE, ""), XSetLocaleModifiers(""), and installs a SIGUSR1 handler with SA_RESTART.
  • Returns: Newly allocated gemui_app_t *, or NULL if XOpenDisplay(NULL) fails or allocation fails.

gemui_destroy

void gemui_destroy(gemui_app_t *app);

Destroys any active modal file dialog (without invoking its callback), restores previously saved input focus (if fullscreen_override or gemui_grab_input() saved one), destroys XIC/XIM, Pango layout, Cairo surfaces/contexts, backbuffer Pixmap, GC, Window, closes the X11 Display, and frees app. Safe when app == NULL.


gemui_set_handlers

void gemui_set_handlers(gemui_app_t *app, const gemui_handlers_t *h, void *userdata);

Copies *h (if h != NULL) and stores userdata, which is passed to on_draw, on_key, on_ptr, on_theme, and on_resize.


gemui_set_title

void gemui_set_title(gemui_app_t *app, const char *title);

Updates both WM_NAME (XStoreName) and _NET_WM_NAME (UTF8_STRING). No-op if app == NULL or title == NULL.


Accessors

Display *gemui_display(const gemui_app_t *app);
Window gemui_window(const gemui_app_t *app);
const gemui_theme_t *gemui_theme(const gemui_app_t *app);
int gemui_width(const gemui_app_t *app);
int gemui_height(const gemui_app_t *app);
  • gemui_display / gemui_window: Underlying X11 Display * (or NULL) and Window (or 0).
  • gemui_theme: Pointer to internal gemui_theme_t (valid for the lifetime of app, updated in place on reload; NULL if app == NULL).
  • gemui_width / gemui_height: Current physical pixel width/height of the window (0 if app == NULL).

gemui_primary_monitor_rect

gemui_rect_t gemui_primary_monitor_rect(const gemui_app_t *app);
  • In fullscreen_override == true mode, returns the XRandR primary monitor's {x, y, w, h} rectangle within the multi-monitor virtual desktop (great for centering a lockscreen prompt on one screen while blanking all monitors).
  • In normal windowed mode, returns {0, 0, gemui_width(app), gemui_height(app)}.

gemui_clipboard_get

bool gemui_clipboard_get(gemui_app_t *app, char *out, size_t out_sz);

Synchronously retrieves text from X11 selections into out (always NUL-terminated when out && out_sz > 0). Tries in order:

  1. CLIPBOARD as UTF8_STRING
  2. CLIPBOARD as XA_STRING
  3. XA_PRIMARY as UTF8_STRING
  4. XA_PRIMARY as XA_STRING
  • Each selection probe polls the X11 fd for up to 150 ms for SelectionNotify and reads up to out_sz - 1 bytes.
  • Returns true if non-empty selection bytes were copied into out; false otherwise.

Scaling & Touch Helpers

double gemui_scale(const gemui_app_t *app);
bool gemui_touch_mode(const gemui_app_t *app);
int gemui_scale_px(const gemui_app_t *app, int logical_px);
int gemui_touch_row_px(const gemui_app_t *app, int logical_px);
  • gemui_scale: Current scale factor (0.50–4.00, defaults to 1.0 if app == NULL).
  • gemui_touch_mode: true if touch mode is enabled via anode.touchMode / theme.touchMode.
  • gemui_scale_px: Converts logical_px to physical pixels via floor(logical_px * clamp_scale(scale) + 0.5) with a minimum of 1 (returns 0 if logical_px <= 0).
  • gemui_touch_row_px: Identical to gemui_scale_px, except multiplies scale by 1.18 when gemui_touch_mode(app) is true. Recommended for buttons, list rows, toggles, and text inputs.

5. Event Loop, Input, Timers, File Descriptors & Toasts

gemui_run & gemui_quit

int gemui_run(gemui_app_t *app);
void gemui_quit(gemui_app_t *app, int code);
  • gemui_run(app) enters a blocking poll() loop until gemui_quit() is called (or WM_DELETE_WINDOW triggers an accepted close). Each iteration:
    1. Drains pending X11 events (XPending / XNextEvent, filtered through XFilterEvent for XIM).
    2. Clears expired toasts (toast_until_ms) and requests a redraw.
    3. Fires the repeating timer callback if timer_ms > 0 and due.
    4. Renders a frame if need_redraw is set.
    5. Computes poll() timeout from timer & toast deadlines and waits on X11 fd, SIGUSR1 self-pipe, and all registered custom fds.
    6. Reloads theme on SIGUSR1 (on_theme + redraw) and invokes callbacks on ready custom fds.
  • Returns app->exit_code (default 0, or 1 if app == NULL).
  • gemui_quit(app, code) records code and sets running = false, causing gemui_run() to exit cleanly.

gemui_request_redraw & gemui_flush_draw

void gemui_request_redraw(gemui_app_t *app);
void gemui_flush_draw(gemui_app_t *app);
  • gemui_request_redraw(app) marks the window dirty (need_redraw = true); the frame is rendered at the end of the current gemui_run() iteration (coalescing multiple requests into one redraw).
  • gemui_flush_draw(app) forces an immediate synchronous gemui_render_frame(app) right away (useful before grabbing input or before running a blocking operation).

Custom File Descriptors (gemui_add_fd, gemui_del_fd)

int gemui_add_fd(gemui_app_t *app, int fd, gemui_fd_cb cb, void *userdata);
void gemui_del_fd(gemui_app_t *app, int fd);
  • gemui_add_fd: Registers fd (up to GEMUI_MAX_FDS = 16) to be monitored for POLLIN. If fd is already registered, updates its cb and userdata in place.
    • Returns 0 on success, -1 if app == NULL, fd < 0, or all 16 slots are full.
    • Inside gemui_run(), cb(app, fd, userdata) is invoked whenever revents & (POLLIN | POLLHUP | POLLERR).
    • Important: Always drain non-blocking reads or remove fd via gemui_del_fd(app, fd) on EOF (read == 0) or error (POLLHUP/POLLERR); otherwise poll() will wake immediately in a busy spin.
  • gemui_del_fd: Unregisters fd (using swap-with-last removal). Safe to call from inside gemui_fd_cb.

gemui_set_timer_ms

void gemui_set_timer_ms(gemui_app_t *app, int interval_ms, gemui_timer_cb cb, void *userdata);

Configures one repeating monotonic timer on app:

  • Calling again replaces any previous timer.
  • Pass interval_ms <= 0 or cb == NULL to disable the timer.
  • Note that the first tick occurs after interval_ms milliseconds, and subsequent ticks reschedule as now + interval_ms.

gemui_set_close_handler

void gemui_set_close_handler(gemui_app_t *app, gemui_close_cb cb, void *userdata);

Installs an optional handler for window-manager close requests (WM_DELETE_WINDOW).

  • If cb == NULL (default), closing the window immediately calls gemui_quit(app, 0).
  • If cb != NULL, cb(app, userdata) decides: return true to quit with exit code 0, or false to keep the window open (for example, to prompt about unsaved changes).

gemui_show_toast

void gemui_show_toast(gemui_app_t *app, const char *msg, int duration_ms);

Displays a transient pill-shaped notification near the bottom center of the window and requests a redraw:

  • msg is truncated to 255 bytes (toast_msg[256]).
  • Passing NULL or "" immediately dismisses any active toast.
  • Passing duration_ms <= 0 uses the default duration of 2200 ms.
  • gemui_run() automatically clears the toast and redraws once the duration expires.

gemui_grab_input & gemui_ungrab_input

bool gemui_grab_input(gemui_app_t *app);
void gemui_ungrab_input(gemui_app_t *app);
  • gemui_grab_input(app): If the window is not mapped yet, calls gemui_flush_draw(app) first (X11 grabs fail on unmapped windows), grabs keyboard (XGrabKeyboard) and confines pointer (XGrabPointer), saves previous focus, sets input focus to app->win, and returns true iff XGrabKeyboard returned GrabSuccess.
  • gemui_ungrab_input(app): Releases both grabs and restores the previously saved X11 focus.

Handler Callback Semantics

Understanding the exact dispatch rules in gemui.c prevents common bugs:

  1. on_key(app, ks, state, utf8, ud):

    • ks: X11 KeySym (e.g., XK_Escape, XK_Return, XK_BackSpace, XK_Left, XK_v).
    • state: X11 modifier mask (ControlMask, ShiftMask, Mod1Mask for Alt).
    • utf8: NUL-terminated UTF-8 string decoded via Xutf8LookupString (with XLookupString fallback). Control characters (byte < 0x20 or 0x7f, such as Ctrl+C, Backspace, Enter, Tab) are stripped to "", so check ks for navigation/control keys and utf8[0] != '\0' (when !(state & ControlMask)) for printable text insertion.
    • Modal dialog note: While gemui_file_dialog_active(app) is true, all key events go to the file dialog instead of on_key.
  2. on_ptr(app, type, x, y, btn, ud):

    • GEMUI_PTR_DOWN: Fired on ButtonPress (excluding scroll buttons Button4/Button5); btn is Button1 (left), Button2 (middle), Button3 (right), etc.
    • GEMUI_PTR_MOVE: Coalesces consecutive MotionNotify events and fires only while a mouse button is held down (app->ptr_down == true). btn is 0. Passive hover movement without a held button is not delivered.
    • GEMUI_PTR_UP: Fired on ButtonRelease (excluding Button4/Button5).
    • GEMUI_PTR_SCROLL_UP / GEMUI_PTR_SCROLL_DOWN: Fired on Button4 / Button5 press; no corresponding PTR_UP event is emitted.
    • Modal dialog note: While gemui_file_dialog_active(app) is true, all pointer events go to the file dialog instead of on_ptr.
  3. on_resize(app, w, h, ud):

    • Fired when ConfigureNotify changes app->w or app->h (or on XRandR / root screen resize in fullscreen_override mode). A redraw is automatically requested immediately afterward.
  4. on_theme(app, ud):

    • Fired after gemui_theme_reload(app) completes due to root XA_RESOURCE_MANAGER property updates (xrdb) or SIGUSR1. Calling gemui_theme_reload(app) directly from application code does not invoke on_theme.

6. Immediate-Mode Hit-Testing

void gemui_hits_clear(gemui_app_t *app);
void gemui_hit_add(gemui_app_t *app, gemui_rect_t r, int id, int val);
const gemui_hit_t *gemui_hit_test(const gemui_app_t *app, int x, int y);
  • gemui_hits_clear: Clears all hit slots (num_hits = 0). Called automatically before on_draw on every rendered frame; you normally do not need to call it manually.
  • gemui_hit_add: Appends {r, id, val} to the per-frame hit array. Silently drops additions once GEMUI_MAX_HITS (256) slots are full.
  • gemui_hit_test: Scans backwards (num_hits - 1 down to 0) and returns the most recently added (topmost/overlapping) gemui_hit_t containing (x, y), or NULL if none match.
    • Lifetime: The returned pointer points into app->hits[] and is only valid until the next frame renders or gemui_hits_clear() is called. Copy id and val immediately if needed across frames.
    • Disabling hit registration: Built-in widgets (gemui_draw_button, gemui_draw_toggle, gemui_draw_slider, gemui_draw_input) only call gemui_hit_add() when hit_id >= 0. Pass -1 for disabled/decorative controls.

7. Drawing Primitives, Typography & Built-In Widgets

Cairo Geometry Primitives

void gemui_set_source(cairo_t *cr, gemui_color_t c);
void gemui_rounded_rect(cairo_t *cr, gemui_rect_t r, double radius);
void gemui_fill_rect(cairo_t *cr, gemui_rect_t r, gemui_color_t c);
void gemui_fill_round(cairo_t *cr, gemui_rect_t r, double radius, gemui_color_t c);
void gemui_stroke_round(cairo_t *cr, gemui_rect_t r, double radius, double lw, gemui_color_t c);
  • gemui_set_source: Calls cairo_set_source_rgba(cr, c.r, c.g, c.b, c.a).
  • gemui_rounded_rect: Builds a Cairo subpath for r with corner radius clamped to min(r.w / 2.0, r.h / 2.0). Falls back to cairo_rectangle() if radius <= 0.0.
  • gemui_fill_rect: Fills axis-aligned rectangle r with color c.
  • gemui_fill_round: Fills rounded rectangle r with color c.
  • gemui_stroke_round: Strokes rounded rectangle r using line width lw and color c.

Typography & Icons

int gemui_draw_text(cairo_t *cr, const gemui_theme_t *t, gemui_rect_t r,
                    const char *text, int pt_delta, bool bold, int align, gemui_color_t c);
int gemui_draw_icon(cairo_t *cr, const gemui_theme_t *t, gemui_rect_t r,
                    const char *icon_utf8, int pt_delta, int align, gemui_color_t c);
  • gemui_draw_text:
    • Uses Pango family "<font_face>, <icon_font_face>" so Nerd Font / symbol glyphs inside mixed strings automatically fall back to icon_font_face.
    • Pixel font size is t->base_font_size + llround(pt_delta * t->scale) (defaulting to 15 * scale if t == NULL). Effective Pango sizes <= 8 fall back to 14px, so keep computed sizes >= 9px.
    • Single-line (pango_layout_set_single_paragraph_mode(..., True)), ellipsized with ... (PANGO_ELLIPSIZE_END) at r.w, vertically centered inside r, and clipped to {r.x, r.y - 4, r.w, r.h + 8}.
    • Returns: Rendered pixel width (0 if text is NULL/empty, or r.w <= 4, or r.h <= 4).
  • gemui_draw_icon:
    • Uses t->icon_font_face directly (non-bold) with the same size calculation, clipping, and return semantics.

Built-In Widgets

gemui_draw_header

void gemui_draw_header(gemui_app_t *app, cairo_t *cr, const char *icon,
                       const char *title, const char *right_badge);

Draws a full-width top bar across y = 0 .. gemui_scale_px(app, 42) with theme->bg_header, a 1px (scaled) bottom theme->divider line, optional left icon (NULL/empty to omit), bold title (pt_delta = +2), and optional pill right_badge on the right (capped at min(scale_px(app, 210), w / 3)).

Start your main content layout at y >= gemui_scale_px(app, 42).


gemui_draw_button

void gemui_draw_button(gemui_app_t *app, cairo_t *cr, gemui_rect_t r,
                       const char *label, int hit_id, int hit_val,
                       bool primary, bool active, bool focused);

Draws a rounded button (radius = scale_px(6)):

  • Colors: active uses sel_bg; else primary uses accent; else uses bg_button. Label text ink is automatically chosen via perceived luminance (0.299*r + 0.587*g + 0.114*b > 0.58) so bright accent themes still produce dark, high-contrast button text.
  • Border: focused highlights with theme->highlight and thicker border; otherwise uses sel_bg (active) or border.
  • Hit registration: Registers r with (hit_id, hit_val) if hit_id >= 0.

gemui_draw_toggle

void gemui_draw_toggle(gemui_app_t *app, cairo_t *cr, gemui_rect_t r,
                       const char *label, bool on, int hit_id, int hit_val, bool focused);

Draws a rounded row card (bg_alt_even) with left-aligned label and a pill switch on the right (48x24 logical pixels, theme->success when on, theme->bg_overlay when off, white/bright circular knob). Registers the entire r as a hit region if hit_id >= 0.


gemui_draw_slider

void gemui_draw_slider(gemui_app_t *app, cairo_t *cr, gemui_rect_t r,
                       const char *label, double norm_val, const char *val_text,
                       int hit_id, int hit_val, bool focused);

Draws a slider card (bg_alt_even) containing:

  • Bold label at top-left, optional val_text (e.g. "75%") at top-right.
  • A horizontal track near the bottom (pad_x = gemui_scale_px(app, 10) inset on each side, height scale_px(8), knob diameter scale_px(16)), clamping norm_val to [0.0, 1.0].
  • Recommended minimum logical row height: 48–56 (gemui_touch_row_px(app, 52)).
  • Registers r with (hit_id, hit_val) if hit_id >= 0.

Converting pointer x back to norm_val during GEMUI_PTR_DOWN / GEMUI_PTR_MOVE:

static double slider_norm_from_x(const gemui_app_t *app, gemui_rect_t slider_r, int ptr_x) {
  int pad_x = gemui_scale_px(app, 10);
  int track_x = slider_r.x + pad_x;
  int track_w = slider_r.w - pad_x * 2;
  if (track_w <= 0) return 0.0;
  double v = (double)(ptr_x - track_x) / (double)track_w;
  if (v < 0.0) return 0.0;
  if (v > 1.0) return 1.0;
  return v;
}

gemui_draw_input

void gemui_draw_input(gemui_app_t *app, cairo_t *cr, gemui_rect_t r,
                      const char *placeholder, const char *text, bool mask_bullets,
                      bool focused, int hit_id, int hit_val);

Draws a single-line text field (bg_input_focus + accent border when focused, bg_input + border otherwise):

  • When text is NULL or empty, displays placeholder in fg_muted (note: when focused && mask_bullets && empty and placeholder == NULL, displays "_").
  • When non-empty and mask_bullets == true, renders up to 48 * characters (with trailing _ when focused).
  • When non-empty and mask_bullets == false, appends _ when focused (truncated to an internal 511-byte display buffer).
  • Registers r with (hit_id, hit_val) if hit_id >= 0.

gemui_draw_input is display-only; your on_key handler mutates your char buf[] using utf8, gemui_utf8_pop_char() on XK_BackSpace, and gemui_clipboard_get() on Ctrl+V (see Recipe 1).


gemui_draw_toast

void gemui_draw_toast(gemui_app_t *app, cairo_t *cr);

Called automatically at the end of gemui_render_frame() when an active toast message is present (420x36 logical pixels max, clamped to w - scale_px(40), positioned scale_px(18) above the bottom edge). You only need to call this directly if rendering into a custom Cairo context outside gemui_render_frame().


8. Theming, Colors & Live Reload

Color & Theme Functions

bool gemui_color_parse(const char *hex, gemui_color_t *out);
void gemui_theme_defaults(gemui_theme_t *t);
bool gemui_theme_load_file(const char *path, gemui_theme_t *out);
void gemui_theme_reload(gemui_app_t *app);
  • gemui_color_parse(hex, out): Parses 6-digit RGB hex strings ("#1c212a" or "1c212a", optional leading spaces/tabs). Sets r, g, b, a = 1.0, and argb = 0xffRRGGBB. Returns false if fewer than 6 valid hex digits are found or pointers are NULL.
  • gemui_theme_defaults(t): Fills t with the built-in Anodized dark theme (Fira Code, DejaVuSansM Nerd Font, base_font_size = 15, dpi = 96, scale = 1.0, touch_mode = false).
  • gemui_theme_load_file(path, out): Initializes out with gemui_theme_defaults(out), then reads an Xresources-format file (path) and applies matching keys. Returns false if path/out is NULL or the file cannot be opened. (Note: unlike gemui_theme_reload, this helper does not query X11 DPI or auto-scale base_font_size.)
  • gemui_theme_reload(app): Reloads app->theme in place using the full precedence chain below.

Theme & DPI Resolution Precedence

1. Resource Database Selection

  1. If GEMUI_XRESOURCES (or fallback ANODE_XRESOURCES) is set and readable, only that file is loaded.
  2. Otherwise $HOME/.Xresources is loaded (if present), and the live root-window XA_RESOURCE_MANAGER property (xrdb) is queried directly and merged on top (xrdb overrides ~/.Xresources).
  3. If neither exists, <ANODE_PREFIX>/share/anode/themes/Anodized.xth is tried.
  4. Otherwise built-in Anodized defaults are used.

2. DPI, Scale & Touch Mode Resolution

  1. Xft.dpi (48–384, clamped)
  2. anode.scale, falling back to theme.scale (0.5–4.0, clamped)
  3. anode.touchMode, falling back to theme.touchMode (1/y/t vs. 0/n/f)
  4. If neither Xft.dpi nor *.scale was found in the database:
    • Checks GEMUI_SCALE (then ANODE_SCALE), deriving dpi = 96.0 * scale.
    • Otherwise detects primary screen EDID DPI (DisplayWidth * 25.4 / DisplayWidthMM); values in [84, 108] snap to 96.0, and scale = clamp(dpi / 96.0).
  5. If only scale was found, dpi = clamp(96.0 * scale). If only Xft.dpi was found, scale = clamp(dpi / 96.0).
  6. base_font_size: If theme.baseFontSize came from .Xresources / xrdb / $GEMUI_XRESOURCES (range 8–96), it is used directly as physical pixels; otherwise the logical base size (8–28, default 15) is multiplied by scale.

Complete .Xresources / .xth Theme Reference

Metadata & Scaling Keys

gemui_theme_t Field Xresources Key(s) Built-in Default
name[64] theme.name "Anodized"
font_face[96] theme.fontFace "Fira Code"
icon_font_face[96] theme.iconFontFace "DejaVuSansM Nerd Font"
base_font_size theme.baseFontSize 15 (logical, scaled by scale)
dpi Xft.dpi 96
scale anode.scale / theme.scale 1.0
touch_mode anode.touchMode / theme.touchMode false

Color Keys (29 Colors)

gemui_theme_t Field Xresources Key Default Hex Typical Usage
bg_main theme.bgMain #08090b Window background
bg_bar theme.bgBar #0e1014 Toolbar / path bar / alternating file rows
bg_header theme.bgHeader #12151a Header bar fill
bg_footer theme.bgFooter #0b0d11 Footer bar fill
bg_overlay theme.bgOverlay #171b22 Modal surfaces, slider/toggle tracks, badges
bg_alt_even theme.bgAltEven #101318 Even rows, toggle & slider cards
bg_alt_odd theme.bgAltOdd #14181f Odd rows
bg_input theme.bgInput #161a21 Unfocused text input background
bg_input_focus theme.bgInputFocus #1e232c Focused text input background
bg_button theme.bgButton #1c212a Secondary button background
bg_search theme.bgSearch #191e27 Search field background
bg_bubble_in theme.bgBubbleIn #181d25 Incoming chat/card bubble
bg_bubble_out theme.bgBubbleOut #252c38 Outgoing chat/card bubble
bg_toast theme.bgToast #1c222b Toast notification background
fg_main theme.fgMain #e4e8ee Standard body text
fg_bright theme.fgBright #f5f7fa Headings, active labels, toggle knob
fg_muted theme.fgMuted #89929f Placeholders, secondary metadata
sel_bg theme.selBg #38414f Selected row / active button background
sel_fg theme.selFg #f5f7fa Selected text / active button ink
accent theme.accent #cfd6e0 Primary button fill, focused input border, icons
accent_alt theme.accentAlt #e5eaf0 Secondary accent
highlight theme.highlight #e2bc72 Keyboard focus ring, overwrite prompt
border theme.border #2d3440 Default widget border
divider theme.divider #20252f Hairline separators
success theme.success #79cf9c Active toggle pill, positive status
info theme.info #9eb3c8 Informational accents
warning theme.warning #e2bc72 Warning accents
danger theme.danger #e07a7a Error / destructive foreground
danger_bg theme.dangerBg #3f1d20 Destructive container fill

Example .xth / .Xresources Snippet

Xft.dpi: 144
anode.touchMode: false
theme.name: Nord-Compact
theme.fontFace: JetBrains Mono
theme.iconFontFace: Symbols Nerd Font
theme.bgMain: #2e3440
theme.bgHeader: #3b4252
theme.accent: #88c0d0
theme.fgMain: #eceff4

Live reload works automatically via either xrdb -merge mytheme.xth or kill -USR1 <pid>.


9. Modal File Open & Save Dialogs

libgemui includes a full modal directory browser and filename editor in gemui_filedialog.c, usable either as an overlay inside an existing gemui_app_t window or as a one-line blocking dialog window.

API Functions

bool gemui_file_dialog_open(gemui_app_t *app, const gemui_file_dialog_opts_t *opts,
                            gemui_file_dialog_cb cb, void *userdata);
bool gemui_open_file_dialog(gemui_app_t *app, const char *title,
                            const char *initial_dir, const char *filter_exts,
                            gemui_file_dialog_cb cb, void *userdata);
bool gemui_save_file_dialog(gemui_app_t *app, const char *title,
                            const char *initial_dir, const char *initial_name,
                            const char *filter_exts, const char *default_ext,
                            gemui_file_dialog_cb cb, void *userdata);
bool gemui_file_dialog_active(const gemui_app_t *app);
void gemui_file_dialog_close(gemui_app_t *app);
bool gemui_file_dialog_run(const char *app_id, const gemui_file_dialog_opts_t *opts,
                           char *out_path, size_t out_path_sz);
  • gemui_file_dialog_open: Opens the modal overlay inside app. Returns true on success, false if app == NULL or allocation fails. If a dialog is already open, it is destroyed silently (without invoking its callback) before opening the new one.
  • gemui_open_file_dialog / gemui_save_file_dialog: Convenience wrappers around gemui_file_dialog_open (no_confirm_overwrite = false).
  • gemui_file_dialog_active: Returns true while a modal file dialog is open on app.
  • gemui_file_dialog_close: Programmatically cancels an active dialog, frees it, requests a redraw, and invokes its callback with (app, false, NULL, userdata).
  • gemui_file_dialog_run: Creates a temporary 760x560 (logical) GemUI window with class app_id (default "gemui-file-dialog"), opens the dialog, runs a nested gemui_run(), writes the chosen path into out_path (NUL-terminated), destroys the window, and returns true iff accepted.

Options (gemui_file_dialog_opts_t)

Field Max Stored Length Behavior & Defaults
mode — GEMUI_FILE_OPEN (0) or GEMUI_FILE_SAVE (1)
title 127 bytes Defaults to "Open File" / "Save File"
initial_dir PATH_MAX Supports ~ expansion; if an existing file path is passed, opens its parent directory and pre-fills its basename when initial_name is empty. Falls back to getcwd() -> $HOME -> /.
initial_name 255 bytes Pre-fills the filename input (focus starts in the input box if non-empty; otherwise starts in the list in Open mode)
filter_exts 127 bytes Comma/semicolon-separated case-insensitive patterns (e.g. ".csv,.tsv", "*.png;*.jpg", "txt"). * or *.* matches all files. Adds a toolbar toggle to switch between filtered and All (*) views.
default_ext 31 bytes In GEMUI_FILE_SAVE mode, appended automatically (with . if omitted) when the filename's basename has no ..
ok_label 47 bytes Confirm button text (defaults to "Open" / "Save")
show_hidden — Initial dotfile visibility (false by default; toggleable via .* button or Ctrl+H)
no_confirm_overwrite — When false (default) in Save mode, prompts "Overwrite existing file?" if the destination already exists

Lifecycle, Validation & Layout Nuances

  • Validation:
    • Open mode checks that the path exists (stat), is not a directory (typing a directory path navigates into it), and is readable (access(path, R_OK)).
    • Save mode checks that the parent directory exists (stat), checks W_OK on existing files or the parent directory for new files, and optionally prompts before overwriting.
  • Callback safety: Internal dialog memory is freed and gemui_file_dialog_active(app) becomes false before cb runs, so cb may safely call gemui_quit() or immediately open another dialog.
  • String lifetime: path passed to cb is stack-allocated and invalid once cb returns; copy it into your own buffer if needed.
  • Compact screens: Automatically switches to a dense compact layout when window w <= 320 || h <= 360.

Built-In Keyboard & Pointer Shortcuts

Input Action
Esc / Click outside box / Cancel / x Cancel dialog (accepted = false)
Enter / Double-click file row (450 ms) Enter directory (when list focused on dir) or confirm selection
Tab / Shift+Tab Toggle focus between directory list and filename input
Up / Down / PgUp / PgDn Navigate file list
Alt+Up / Alt+Home Go to parent directory / $HOME
Ctrl+H Toggle hidden dotfiles (.*)
Ctrl+U / Ctrl+V / Ctrl+A Clear input / Paste clipboard / Move cursor to end
Left / Right / Home / End / Backspace / Delete UTF-8-aware filename editing
Y / Enter or N / Esc Confirm or back out during overwrite prompt
Mouse Wheel / Scrollbar drag Scroll file list (+-3 rows per wheel tick)

Standalone Quick Example

char chosen[4096];
gemui_file_dialog_opts_t opts = {
  .mode = GEMUI_FILE_OPEN,
  .title = "Choose Config",
  .initial_dir = "~",
  .filter_exts = ".conf,.json",
};
if (gemui_file_dialog_run("my-picker", &opts, chosen, sizeof(chosen))) {
  /* use chosen */
}

10. System, IPC, Subprocess & UTF-8 Utilities

gemui.h bundles six small POSIX helper functions commonly needed by desktop utilities:

gemui_unix_cmd

int gemui_unix_cmd(const char *sock_path, const char *cmd, char *resp, size_t resp_sz);

Connects to an AF_UNIX SOCK_STREAM socket at sock_path with 1-second SO_SNDTIMEO/SO_RCVTIMEO timeouts, sends cmd (appending \n if not already newline-terminated), calls shutdown(fd, SHUT_WR), reads up to resp_sz - 1 bytes into resp (or drains incoming bytes if resp == NULL), NUL-terminates resp, and closes the socket. Returns 0 on success, -1 on invalid args, connect error, or send error.


gemui_read_file_line

int gemui_read_file_line(const char *path, char *buf, size_t sz);

Opens path, reads the first line via fgets(), strips trailing \r and \n, and returns 0. Returns -1 on invalid arguments, open failure, or immediate EOF/read failure. Ideal for reading /sys/... or /proc/... single-line telemetry.


gemui_run_cmd_timeout & gemui_run_cmd_capture

int gemui_run_cmd_timeout(const char *const argv[], char *out, size_t out_sz, int timeout_ms);
int gemui_run_cmd_capture(const char *const argv[], char *out, size_t out_sz);

Forks and runs argv[0] directly via execvp() (no shell) in its own process group (setpgid(0, 0)) with /dev/null on stdin:

  • When out != NULL && out_sz > 0, merges both stdout and stderr into out (up to out_sz - 1 bytes, NUL-terminated).
  • When timeout_ms > 0 and exceeded, kills the entire child process group (kill(-pid, SIGKILL)) and returns 124. Pass timeout_ms <= 0 to wait indefinitely.
  • Returns the child's exit code (WEXITSTATUS), 1 if killed by an external signal, 127 if execvp failed, or -1 on setup/waitpid failure.
  • gemui_run_cmd_capture(argv, out, out_sz) is equivalent to gemui_run_cmd_timeout(argv, out, out_sz, 2500).

Avoid blocking the UI: These functions block the calling thread until the child finishes or times out. Keep timeouts short (e.g., 50–250 ms), or spawn a child pipe manually and watch its read end with gemui_add_fd() (see Recipe 2).


gemui_spawn_detached

int gemui_spawn_detached(const char *const argv[]);

Launches a background command using double-fork() + setsid() with stdin/stdout/stderr redirected to /dev/null, reaping the intermediate child immediately so no zombies remain. Returns 0 once forked (or -1 if argv is invalid or the initial fork() fails; execvp failures in the detached grandchild are not reported).


gemui_utf8_pop_char

void gemui_utf8_pop_char(char *buf);

Removes the last UTF-8 codepoint from a NUL-terminated string buf in place (consuming trailing UTF-8 continuation bytes 0x80..0xBF followed by the leading byte). Safe on NULL or "".


11. Real-World Application Recipes

All three examples below are complete, self-contained C11 programs that compile cleanly with -std=c11 -Wall -Wextra -Werror.

Recipe 1: Interactive Utility Form with Input, Toggle, Slider & File Dialogs

Demonstrates DPI-scaled layout, keyboard focus cycling (Tab), UTF-8 text editing with BackSpace and clipboard paste (Ctrl+V), toggle switch, draggable slider with exact track geometry, integrated Open/Save file dialogs, and unsaved-changes close interception.

#define _POSIX_C_SOURCE 200809L
#include <gemui.h>
#include <stdio.h>
#include <string.h>

enum {
  HIT_INPUT = 1,
  HIT_TOGGLE,
  HIT_SLIDER,
  HIT_OPEN_BTN,
  HIT_SAVE_BTN,
};

enum {
  FOCUS_INPUT = 0,
  FOCUS_TOGGLE,
  FOCUS_SLIDER,
  FOCUS_OPEN,
  FOCUS_SAVE,
  FOCUS_COUNT
};

typedef struct {
  char note[256];
  bool enabled;
  double level;
  int focus;
  bool dragging_slider;
  bool dirty;
  bool close_warned;
  gemui_rect_t slider_rect;
  char current_path[1024];
} utility_state_t;

static double slider_norm_from_x(const gemui_app_t *app, gemui_rect_t r, int x) {
  int pad_x = gemui_scale_px(app, 10);
  int tw = r.w - pad_x * 2;
  if (tw <= 0) return 0.0;
  double v = (double)(x - (r.x + pad_x)) / (double)tw;
  if (v < 0.0) return 0.0;
  if (v > 1.0) return 1.0;
  return v;
}

static void on_open_done(gemui_app_t *app, bool accepted, const char *path, void *ud) {
  utility_state_t *st = (utility_state_t *)ud;
  if (!accepted || !path) {
    gemui_show_toast(app, "Open cancelled", 1200);
    return;
  }
  snprintf(st->current_path, sizeof(st->current_path), "%s", path);
  char line[256];
  if (gemui_read_file_line(path, line, sizeof(line)) == 0) {
    snprintf(st->note, sizeof(st->note), "%s", line);
  }
  st->dirty = false;
  st->close_warned = false;
  gemui_show_toast(app, "Loaded first line from file", 1800);
  gemui_request_redraw(app);
}

static void on_save_done(gemui_app_t *app, bool accepted, const char *path, void *ud) {
  utility_state_t *st = (utility_state_t *)ud;
  if (!accepted || !path) {
    gemui_show_toast(app, "Save cancelled", 1200);
    return;
  }
  FILE *f = fopen(path, "w");
  if (!f) {
    gemui_show_toast(app, "Failed to write file", 2200);
    return;
  }
  fprintf(f, "%s\n# enabled=%d level=%.0f%%\n",
          st->note, st->enabled ? 1 : 0, st->level * 100.0);
  fclose(f);
  snprintf(st->current_path, sizeof(st->current_path), "%s", path);
  st->dirty = false;
  st->close_warned = false;
  gemui_show_toast(app, "Saved successfully", 1800);
  gemui_request_redraw(app);
}

static void trigger_open(gemui_app_t *app, utility_state_t *st) {
  gemui_open_file_dialog(app, "Open Note", "~", ".txt,.md", on_open_done, st);
}

static void trigger_save(gemui_app_t *app, utility_state_t *st) {
  gemui_save_file_dialog(app, "Save Note", "~", "note.txt", ".txt,.md", ".txt",
                         on_save_done, st);
}

static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) {
  utility_state_t *st = (utility_state_t *)ud;
  const gemui_theme_t *t = gemui_theme(app);

  const char *badge = st->dirty ? "Modified" : "Saved";
  gemui_draw_header(app, cr, NULL, "GemUI Utility", badge);

  int pad = gemui_scale_px(app, 14);
  int gap = gemui_scale_px(app, 10);
  int y = gemui_scale_px(app, 42) + pad;
  int iw = w - pad * 2;
  int row_h = gemui_touch_row_px(app, 36);
  int slider_h = gemui_touch_row_px(app, 52);

  gemui_draw_input(app, cr, (gemui_rect_t){pad, y, iw, row_h},
                   "Type note (Ctrl+V paste, Ctrl+U clear)...",
                   st->note, false, st->focus == FOCUS_INPUT, HIT_INPUT, 0);
  y += row_h + gap;

  gemui_draw_toggle(app, cr, (gemui_rect_t){pad, y, iw, row_h},
                    "Enable Feature", st->enabled, HIT_TOGGLE, 0,
                    st->focus == FOCUS_TOGGLE);
  y += row_h + gap;

  char pct[24];
  snprintf(pct, sizeof(pct), "%.0f%%", st->level * 100.0);
  st->slider_rect = (gemui_rect_t){pad, y, iw, slider_h};
  gemui_draw_slider(app, cr, st->slider_rect, "Output Level", st->level, pct,
                    HIT_SLIDER, 0, st->focus == FOCUS_SLIDER);
  y += slider_h + gap;

  if (st->current_path[0]) {
    gemui_draw_text(cr, t, (gemui_rect_t){pad, y, iw, gemui_scale_px(app, 22)},
                    st->current_path, -1, false, GEMUI_ALIGN_LEFT, t->fg_muted);
  }

  int bw = (iw - gap) / 2;
  int by = h - pad - row_h;
  gemui_draw_button(app, cr, (gemui_rect_t){pad, by, bw, row_h},
                    "Open...", HIT_OPEN_BTN, 0, false, false,
                    st->focus == FOCUS_OPEN);
  gemui_draw_button(app, cr, (gemui_rect_t){pad + bw + gap, by, bw, row_h},
                    "Save...", HIT_SAVE_BTN, 0, true, false,
                    st->focus == FOCUS_SAVE);
}

static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, void *ud) {
  utility_state_t *st = (utility_state_t *)ud;

  if (type == GEMUI_PTR_UP) {
    st->dragging_slider = false;
    return;
  }
  if (type == GEMUI_PTR_MOVE) {
    if (st->dragging_slider) {
      st->level = slider_norm_from_x(app, st->slider_rect, x);
      st->dirty = true;
      st->close_warned = false;
      gemui_request_redraw(app);
    }
    return;
  }
  if (type != GEMUI_PTR_DOWN || btn != Button1) return;

  const gemui_hit_t *hit = gemui_hit_test(app, x, y);
  if (!hit) return;

  switch (hit->id) {
    case HIT_INPUT:
      st->focus = FOCUS_INPUT;
      break;
    case HIT_TOGGLE:
      st->focus = FOCUS_TOGGLE;
      st->enabled = !st->enabled;
      st->dirty = true;
      st->close_warned = false;
      break;
    case HIT_SLIDER:
      st->focus = FOCUS_SLIDER;
      st->dragging_slider = true;
      st->level = slider_norm_from_x(app, st->slider_rect, x);
      st->dirty = true;
      st->close_warned = false;
      break;
    case HIT_OPEN_BTN:
      st->focus = FOCUS_OPEN;
      trigger_open(app, st);
      return;
    case HIT_SAVE_BTN:
      st->focus = FOCUS_SAVE;
      trigger_save(app, st);
      return;
    default:
      break;
  }
  gemui_request_redraw(app);
}

static void append_utf8(char *dst, size_t dst_sz, const char *add) {
  if (!add || !add[0]) return;
  size_t cur = strlen(dst);
  size_t rem = (cur + 1 < dst_sz) ? (dst_sz - 1 - cur) : 0;
  size_t alen = strlen(add);
  if (alen > rem) alen = rem;
  if (alen > 0) {
    memcpy(dst + cur, add, alen);
    dst[cur + alen] = '\0';
  }
}

static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char *utf8, void *ud) {
  utility_state_t *st = (utility_state_t *)ud;
  bool ctrl = (state & ControlMask) != 0;

  if (ks == XK_Tab || ks == XK_ISO_Left_Tab) {
    int dir = (state & ShiftMask || ks == XK_ISO_Left_Tab) ? -1 : 1;
    st->focus = (st->focus + dir + FOCUS_COUNT) % FOCUS_COUNT;
    gemui_request_redraw(app);
    return;
  }

  if (st->focus == FOCUS_INPUT) {
    if (ctrl && (ks == XK_u || ks == XK_U)) {
      st->note[0] = '\0';
      st->dirty = true;
      st->close_warned = false;
      gemui_request_redraw(app);
      return;
    }
    if (ctrl && (ks == XK_v || ks == XK_V)) {
      char clip[256];
      if (gemui_clipboard_get(app, clip, sizeof(clip))) {
        append_utf8(st->note, sizeof(st->note), clip);
        st->dirty = true;
        st->close_warned = false;
        gemui_request_redraw(app);
      }
      return;
    }
    if (ks == XK_BackSpace) {
      gemui_utf8_pop_char(st->note);
      st->dirty = true;
      st->close_warned = false;
      gemui_request_redraw(app);
      return;
    }
    if (!ctrl && utf8 && utf8[0]) {
      append_utf8(st->note, sizeof(st->note), utf8);
      st->dirty = true;
      st->close_warned = false;
      gemui_request_redraw(app);
      return;
    }
  } else if (st->focus == FOCUS_SLIDER) {
    if (ks == XK_Left || ks == XK_Right) {
      st->level += (ks == XK_Right) ? 0.05 : -0.05;
      if (st->level < 0.0) st->level = 0.0;
      if (st->level > 1.0) st->level = 1.0;
      st->dirty = true;
      st->close_warned = false;
      gemui_request_redraw(app);
      return;
    }
  }

  if (ks == XK_Return || ks == XK_KP_Enter || (ks == XK_space && st->focus != FOCUS_INPUT)) {
    if (st->focus == FOCUS_TOGGLE) {
      st->enabled = !st->enabled;
      st->dirty = true;
      st->close_warned = false;
    } else if (st->focus == FOCUS_OPEN) {
      trigger_open(app, st);
      return;
    } else if (st->focus == FOCUS_SAVE) {
      trigger_save(app, st);
      return;
    }
    gemui_request_redraw(app);
  }
}

static bool on_close(gemui_app_t *app, void *ud) {
  utility_state_t *st = (utility_state_t *)ud;
  if (!st->dirty || st->close_warned) {
    return true;
  }
  st->close_warned = true;
  gemui_show_toast(app, "Unsaved changes! Click close again to quit.", 2600);
  return false;
}

int main(void) {
  gemui_app_t *app = gemui_create("gemui-utility", "GemUI Utility", 480, 320, false);
  if (!app) return 1;

  utility_state_t st = {
    .enabled = true,
    .level = 0.65,
    .focus = FOCUS_INPUT,
  };
  gemui_handlers_t h = {
    .on_draw = on_draw,
    .on_key  = on_key,
    .on_ptr  = on_ptr,
  };
  gemui_set_handlers(app, &h, &st);
  gemui_set_close_handler(app, on_close, &st);

  int rc = gemui_run(app);
  gemui_destroy(app);
  return rc;
}

Recipe 2: Non-Blocking Background I/O via gemui_add_fd + Timer

Demonstrates streaming stdout from an asynchronous child process via a non-blocking pipe registered with gemui_add_fd(), paired with a 1-second repeating timer (gemui_set_timer_ms()) reading /proc/loadavg via gemui_read_file_line().

#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <fcntl.h>
#include <gemui.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

typedef struct {
  int pipe_fd;
  pid_t child_pid;
  char stream_line[256];
  char load_line[128];
  char partial[256];
  size_t partial_len;
} monitor_state_t;

static void on_pipe_ready(gemui_app_t *app, int fd, void *ud) {
  monitor_state_t *st = (monitor_state_t *)ud;
  char buf[256];

  for (;;) {
    ssize_t n = read(fd, buf, sizeof(buf));
    if (n > 0) {
      for (ssize_t i = 0; i < n; i++) {
        if (buf[i] == '\n') {
          st->partial[st->partial_len] = '\0';
          snprintf(st->stream_line, sizeof(st->stream_line), "%s", st->partial);
          st->partial_len = 0;
        } else if (buf[i] != '\r' && st->partial_len + 1 < sizeof(st->partial)) {
          st->partial[st->partial_len++] = buf[i];
        }
      }
      gemui_request_redraw(app);
    } else if (n == 0) {
      gemui_del_fd(app, fd);
      close(fd);
      st->pipe_fd = -1;
      if (st->child_pid > 0) {
        waitpid(st->child_pid, NULL, WNOHANG);
        st->child_pid = -1;
      }
      snprintf(st->stream_line, sizeof(st->stream_line), "[stream closed]");
      gemui_request_redraw(app);
      break;
    } else {
      if (errno == EINTR) continue;
      if (errno == EAGAIN || errno == EWOULDBLOCK) break;
      gemui_del_fd(app, fd);
      close(fd);
      st->pipe_fd = -1;
      break;
    }
  }
}

static void on_tick(gemui_app_t *app, void *ud) {
  monitor_state_t *st = (monitor_state_t *)ud;
  if (gemui_read_file_line("/proc/loadavg", st->load_line, sizeof(st->load_line)) != 0) {
    snprintf(st->load_line, sizeof(st->load_line), "(unavailable)");
  }
  gemui_request_redraw(app);
}

static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) {
  monitor_state_t *st = (monitor_state_t *)ud;
  const gemui_theme_t *t = gemui_theme(app);
  (void)h;

  gemui_draw_header(app, cr, NULL, "Live Monitor", "1s poll");
  int pad = gemui_scale_px(app, 14);
  int y = gemui_scale_px(app, 42) + pad;
  int row_h = gemui_scale_px(app, 28);

  gemui_draw_text(cr, t, (gemui_rect_t){pad, y, w - pad * 2, row_h},
                  "Stream output:", 0, true, GEMUI_ALIGN_LEFT, t->accent);
  y += row_h;
  gemui_draw_text(cr, t, (gemui_rect_t){pad, y, w - pad * 2, row_h},
                  st->stream_line[0] ? st->stream_line : "Waiting...",
                  0, false, GEMUI_ALIGN_LEFT, t->fg_main);
  y += row_h + pad;

  gemui_draw_text(cr, t, (gemui_rect_t){pad, y, w - pad * 2, row_h},
                  "System loadavg:", 0, true, GEMUI_ALIGN_LEFT, t->accent);
  y += row_h;
  gemui_draw_text(cr, t, (gemui_rect_t){pad, y, w - pad * 2, row_h},
                  st->load_line, 0, false, GEMUI_ALIGN_LEFT, t->fg_bright);
}

static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char *utf8, void *ud) {
  (void)state;
  (void)utf8;
  (void)ud;
  if (ks == XK_Escape || ks == XK_q) gemui_quit(app, 0);
}

int main(void) {
  int pfd[2];
  if (pipe(pfd) != 0) return 1;

  pid_t pid = fork();
  if (pid < 0) {
    close(pfd[0]);
    close(pfd[1]);
    return 1;
  }
  if (pid == 0) {
    close(pfd[0]);
    dup2(pfd[1], STDOUT_FILENO);
    close(pfd[1]);
    char *const argv[] = {"sh", "-c", "while true; do date +%T; sleep 1; done", NULL};
    execvp(argv[0], argv);
    _exit(127);
  }
  close(pfd[1]);

  int fl = fcntl(pfd[0], F_GETFL, 0);
  if (fl >= 0) fcntl(pfd[0], F_SETFL, fl | O_NONBLOCK);
  int fdfl = fcntl(pfd[0], F_GETFD, 0);
  if (fdfl >= 0) fcntl(pfd[0], F_SETFD, fdfl | FD_CLOEXEC);

  gemui_app_t *app = gemui_create("gemui-monitor", "Live Monitor", 440, 200, false);
  if (!app) {
    close(pfd[0]);
    kill(pid, SIGTERM);
    waitpid(pid, NULL, 0);
    return 1;
  }

  monitor_state_t st = {
    .pipe_fd = pfd[0],
    .child_pid = pid,
  };
  on_tick(app, &st);

  gemui_handlers_t h = { .on_draw = on_draw, .on_key = on_key };
  gemui_set_handlers(app, &h, &st);
  gemui_add_fd(app, st.pipe_fd, on_pipe_ready, &st);
  gemui_set_timer_ms(app, 1000, on_tick, &st);

  int rc = gemui_run(app);
  if (st.pipe_fd >= 0) {
    gemui_del_fd(app, st.pipe_fd);
    close(st.pipe_fd);
  }
  if (st.child_pid > 0) {
    kill(st.child_pid, SIGTERM);
    waitpid(st.child_pid, NULL, 0);
  }
  gemui_destroy(app);
  return rc;
}

Recipe 3: Fullscreen Multi-Monitor Overlay / Lockscreen

Demonstrates fullscreen_override = true, using gemui_primary_monitor_rect() to keep interactive UI centered on the primary screen while covering every connected monitor, masked password input, and gemui_grab_input() / gemui_ungrab_input().

#include <gemui.h>
#include <stdio.h>
#include <string.h>

enum {
  HIT_PASS = 1,
  HIT_UNLOCK,
};

typedef struct {
  char pass[64];
  bool wrong;
} lock_state_t;

static void try_unlock(gemui_app_t *app, lock_state_t *st) {
  /* Demo check: replace with PAM/shadow/helper verification in production */
  if (strcmp(st->pass, "unlock") == 0) {
    gemui_quit(app, 0);
    return;
  }
  st->wrong = true;
  st->pass[0] = '\0';
  gemui_show_toast(app, "Incorrect passphrase", 1800);
  gemui_request_redraw(app);
}

static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) {
  lock_state_t *st = (lock_state_t *)ud;
  const gemui_theme_t *t = gemui_theme(app);
  (void)w;
  (void)h;

  gemui_rect_t mon = gemui_primary_monitor_rect(app);
  int cw = gemui_scale_px(app, 360);
  int ch = gemui_scale_px(app, 190);
  if (cw > mon.w - gemui_scale_px(app, 32)) cw = mon.w - gemui_scale_px(app, 32);
  gemui_rect_t card = {mon.x + (mon.w - cw) / 2, mon.y + (mon.h - ch) / 2, cw, ch};

  double rad = (double)gemui_scale_px(app, 8);
  gemui_fill_round(cr, card, rad, t->bg_overlay);
  gemui_stroke_round(cr, card, rad, 1.5, st->wrong ? t->danger : t->accent);

  int pad = gemui_scale_px(app, 16);
  int row_h = gemui_touch_row_px(app, 36);
  int y = card.y + pad;

  gemui_draw_text(cr, t, (gemui_rect_t){card.x + pad, y, cw - pad * 2, gemui_scale_px(app, 28)},
                  "Screen Locked", 2, true, GEMUI_ALIGN_CENTER, t->fg_bright);
  y += gemui_scale_px(app, 38);

  gemui_draw_input(app, cr, (gemui_rect_t){card.x + pad, y, cw - pad * 2, row_h},
                   "Enter passphrase...", st->pass, true, true, HIT_PASS, 0);
  y += row_h + gemui_scale_px(app, 12);

  gemui_draw_button(app, cr, (gemui_rect_t){card.x + pad, y, cw - pad * 2, row_h},
                    "Unlock", HIT_UNLOCK, 0, true, false, false);
}

static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, void *ud) {
  lock_state_t *st = (lock_state_t *)ud;
  if (type != GEMUI_PTR_DOWN || btn != Button1) return;
  const gemui_hit_t *hit = gemui_hit_test(app, x, y);
  if (hit && hit->id == HIT_UNLOCK) {
    try_unlock(app, st);
  }
}

static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char *utf8, void *ud) {
  lock_state_t *st = (lock_state_t *)ud;
  bool ctrl = (state & ControlMask) != 0;

  if (ks == XK_Return || ks == XK_KP_Enter) {
    try_unlock(app, st);
    return;
  }
  if (ks == XK_BackSpace) {
    gemui_utf8_pop_char(st->pass);
    st->wrong = false;
    gemui_request_redraw(app);
    return;
  }
  if (ctrl && (ks == XK_u || ks == XK_U)) {
    st->pass[0] = '\0';
    st->wrong = false;
    gemui_request_redraw(app);
    return;
  }
  if (!ctrl && utf8 && utf8[0]) {
    size_t cur = strlen(st->pass);
    size_t add = strlen(utf8);
    if (cur + add < sizeof(st->pass)) {
      memcpy(st->pass + cur, utf8, add + 1);
      st->wrong = false;
      gemui_request_redraw(app);
    }
  }
}

static void on_resize(gemui_app_t *app, int w, int h, void *ud) {
  (void)w;
  (void)h;
  (void)ud;
  gemui_request_redraw(app);
}

int main(void) {
  gemui_app_t *app = gemui_create("gemui-lock", "Screen Lock", 0, 0, true);
  if (!app) return 1;

  lock_state_t st = {0};
  gemui_handlers_t h = {
    .on_draw   = on_draw,
    .on_key    = on_key,
    .on_ptr    = on_ptr,
    .on_resize = on_resize,
  };
  gemui_set_handlers(app, &h, &st);
  gemui_grab_input(app);

  int rc = gemui_run(app);
  gemui_ungrab_input(app);
  gemui_destroy(app);
  return rc;
}

12. Pitfalls & Best Practices Checklist

  • Always call gemui_request_redraw(app) after changing state in on_key, on_ptr, gemui_fd_cb, or gemui_timer_cb; frames never auto-redraw on idle.
  • Do not rely on GEMUI_PTR_MOVE for hover states — motion events are only dispatched while a mouse button is held down (ptr_down == true).
  • Stay within GEMUI_MAX_HITS (256) per frame; for long scrollable lists, only draw and register the currently visible viewport rows.
  • Do not cache gemui_hit_test() pointers across frames — extract .id and .val immediately.
  • Pass hit_id = -1 to built-in widgets when a button/toggle/slider/input is decorative or disabled so it does not capture clicks.
  • Always scale layout constants via gemui_scale_px() / gemui_touch_row_px(), and start layout below the header bar (gemui_scale_px(app, 42)).
  • Copy path inside gemui_file_dialog_cb before returning; the string lives on the stack inside the dialog completion helper.
  • Remember there is only one repeating timer per gemui_app_t (gemui_set_timer_ms). Multiplex multiple periodic tasks off one base tick if needed.
  • Avoid blocking gemui_run(): prefer non-blocking pipes/sockets with gemui_add_fd() over long gemui_run_cmd_timeout() calls.
  • Keep one gemui_app_t per process and call gemui_* APIs strictly from the UI loop thread.