63 KiB
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
- Architecture & Mental Model
- Headers, Building & Linking
- Constants, Data Types & Callback Typedefs
- Application Lifecycle, Windowing & Scaling
- Event Loop, Input, Timers, File Descriptors & Toasts
- Immediate-Mode Hit-Testing
- Drawing Primitives, Typography & Built-In Widgets
- Theming, Colors & Live Reload
- Modal File Open & Save Dialogs
- System, IPC, Subprocess & UTF-8 Utilities
- Real-World Application Recipes
- 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 inpoll()until an X11 event, timer tick, registered file descriptor,SIGUSR1, or toast expiration occurs, and only renders a frame whenneed_redrawis set. - Widgets are drawn and registered per frame. Inside your
on_drawcallback, you compute coordinates, draw controls usinggemui_draw_*(), and pass ahit_id/hit_valpair. On pointer events (on_ptr), you callgemui_hit_test(app, x, y)to find which control was hit, mutate your state, and callgemui_request_redraw(app).
Per-Frame Rendering Pipeline
Whenever a frame is rendered (gemui_render_frame), libgemui executes these exact steps:
- Clears the hit-region table (
gemui_hits_clear(app)). - Fills the entire backbuffer (
0, 0, w, h) withtheme->bg_main. - Invokes
handlers.on_draw(app, cr, w, h, userdata). - If a modal file dialog is open, renders the dimmed backdrop and dialog UI on top (replacing the application's interactive layer until closed).
- If an active toast exists, renders
gemui_draw_toast(app, cr)centered near the bottom edge. - Copies the
CAIRO_FORMAT_RGB24image surface into an X11Pixmapbackbuffer, maps the window on the first frame (for non-override windows), blits viaXCopyArea, and flushes X11.
Logical vs. Physical Coordinates
- Logical pixels are resolution-independent sizes you design against (for example,
42for a header,36for a button,12for padding). - Physical pixels are actual X11 window pixel coordinates.
- Convert logical layout constants with
gemui_scale_px(app, logical_px)orgemui_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 everygemui_rect_tin drawing functions are physical pixels.
Threading & Single-Instance Constraints
libgemuiis not thread-safe. Allgemui_*calls (includinggemui_request_redraw) must run on the thread runninggemui_run().- To wake the UI thread from a worker thread, create a
pipe()or Linuxeventfd(), register the read end withgemui_add_fd(), write a byte from the worker thread, and drain + callgemui_request_redraw()inside thegemui_fd_cb. - Internally,
SIGUSR1delivery uses a process-global self-pipe (g_sig_pipe) and frame rendering temporarily stores the activePangoLayoutin a static pointer. Plan on onegemui_app_tinstance 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 buildinglibgemuiviaMakefile,-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 fromgemui_run()when a registeredfdreportsPOLLIN,POLLHUP, orPOLLERR.gemui_timer_cb: Called repeatedly bygemui_run()when the interval elapses.gemui_close_cb: Called when the window manager sendsWM_DELETE_WINDOW. Returntrueto exitgemui_run()with code0, orfalseto ignore the close request.gemui_file_dialog_cb: Called when the user confirms (accepted == true,pathnon-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 bothXClassHint.res_nameandres_class. PassNULLto default to"anode-app".title: SetsWM_NAMEand_NET_WM_NAME(UTF8_STRING). PassNULLto 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_WORKAREAso panels/docks are respected. - If
w <= 0, uses the full workarea width of that monitor; otherwise clamps scaled width betweenscale_px(260)andworkarea_w - scale_px(24). - If
h <= 0, uses the full workarea height of that monitor; otherwise clamps scaled height betweenscale_px(180)andworkarea_h - scale_px(32). - Centers the window on that monitor's workarea.
- The window is mapped lazily during the first rendered frame (
gemui_run()orgemui_flush_draw()), eliminating initial uninitialized flashes.
- Treated as logical pixels and scaled by
- When
fullscreen_override == true(lockscreen / global overlay):- Creates an
override_redirect = Truewindow spanning the entire virtual X11 desktop (DisplayWidthxDisplayHeight) 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.
- Creates an
- When
- Side effects: Calls
setlocale(LC_CTYPE, ""),XSetLocaleModifiers(""), and installs aSIGUSR1handler withSA_RESTART. - Returns: Newly allocated
gemui_app_t *, orNULLifXOpenDisplay(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 X11Display *(orNULL) andWindow(or0).gemui_theme: Pointer to internalgemui_theme_t(valid for the lifetime ofapp, updated in place on reload;NULLifapp == NULL).gemui_width/gemui_height: Current physical pixel width/height of the window (0ifapp == NULL).
gemui_primary_monitor_rect
gemui_rect_t gemui_primary_monitor_rect(const gemui_app_t *app);
- In
fullscreen_override == truemode, 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:
CLIPBOARDasUTF8_STRINGCLIPBOARDasXA_STRINGXA_PRIMARYasUTF8_STRINGXA_PRIMARYasXA_STRING
- Each selection probe polls the X11 fd for up to 150 ms for
SelectionNotifyand reads up toout_sz - 1bytes. - Returns
trueif non-empty selection bytes were copied intoout;falseotherwise.
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 to1.0ifapp == NULL).gemui_touch_mode:trueif touch mode is enabled viaanode.touchMode/theme.touchMode.gemui_scale_px: Convertslogical_pxto physical pixels viafloor(logical_px * clamp_scale(scale) + 0.5)with a minimum of1(returns0iflogical_px <= 0).gemui_touch_row_px: Identical togemui_scale_px, except multiplies scale by1.18whengemui_touch_mode(app)istrue. 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 blockingpoll()loop untilgemui_quit()is called (orWM_DELETE_WINDOWtriggers an accepted close). Each iteration:- Drains pending X11 events (
XPending/XNextEvent, filtered throughXFilterEventfor XIM). - Clears expired toasts (
toast_until_ms) and requests a redraw. - Fires the repeating timer callback if
timer_ms > 0and due. - Renders a frame if
need_redrawis set. - Computes
poll()timeout from timer & toast deadlines and waits on X11 fd,SIGUSR1self-pipe, and all registered custom fds. - Reloads theme on
SIGUSR1(on_theme+ redraw) and invokes callbacks on ready custom fds.
- Drains pending X11 events (
- Returns
app->exit_code(default0, or1ifapp == NULL). gemui_quit(app, code)recordscodeand setsrunning = false, causinggemui_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 currentgemui_run()iteration (coalescing multiple requests into one redraw).gemui_flush_draw(app)forces an immediate synchronousgemui_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: Registersfd(up toGEMUI_MAX_FDS=16) to be monitored forPOLLIN. Iffdis already registered, updates itscbanduserdatain place.- Returns
0on success,-1ifapp == NULL,fd < 0, or all16slots are full. - Inside
gemui_run(),cb(app, fd, userdata)is invoked wheneverrevents & (POLLIN | POLLHUP | POLLERR). - Important: Always drain non-blocking reads or remove
fdviagemui_del_fd(app, fd)on EOF (read == 0) or error (POLLHUP/POLLERR); otherwisepoll()will wake immediately in a busy spin.
- Returns
gemui_del_fd: Unregistersfd(using swap-with-last removal). Safe to call from insidegemui_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 <= 0orcb == NULLto disable the timer. - Note that the first tick occurs after
interval_msmilliseconds, and subsequent ticks reschedule asnow + 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 callsgemui_quit(app, 0). - If
cb != NULL,cb(app, userdata)decides: returntrueto quit with exit code0, orfalseto 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:
msgis truncated to 255 bytes (toast_msg[256]).- Passing
NULLor""immediately dismisses any active toast. - Passing
duration_ms <= 0uses the default duration of2200ms. 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, callsgemui_flush_draw(app)first (X11 grabs fail on unmapped windows), grabs keyboard (XGrabKeyboard) and confines pointer (XGrabPointer), saves previous focus, sets input focus toapp->win, and returnstrueiffXGrabKeyboardreturnedGrabSuccess.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:
-
on_key(app, ks, state, utf8, ud):ks: X11KeySym(e.g.,XK_Escape,XK_Return,XK_BackSpace,XK_Left,XK_v).state: X11 modifier mask (ControlMask,ShiftMask,Mod1Maskfor Alt).utf8: NUL-terminated UTF-8 string decoded viaXutf8LookupString(withXLookupStringfallback). Control characters (byte < 0x20or0x7f, such asCtrl+C,Backspace,Enter,Tab) are stripped to"", so checkksfor navigation/control keys andutf8[0] != '\0'(when!(state & ControlMask)) for printable text insertion.- Modal dialog note: While
gemui_file_dialog_active(app)istrue, all key events go to the file dialog instead ofon_key.
-
on_ptr(app, type, x, y, btn, ud):GEMUI_PTR_DOWN: Fired onButtonPress(excluding scroll buttonsButton4/Button5);btnisButton1(left),Button2(middle),Button3(right), etc.GEMUI_PTR_MOVE: Coalesces consecutiveMotionNotifyevents and fires only while a mouse button is held down (app->ptr_down == true).btnis0. Passive hover movement without a held button is not delivered.GEMUI_PTR_UP: Fired onButtonRelease(excludingButton4/Button5).GEMUI_PTR_SCROLL_UP/GEMUI_PTR_SCROLL_DOWN: Fired onButton4/Button5press; no correspondingPTR_UPevent is emitted.- Modal dialog note: While
gemui_file_dialog_active(app)istrue, all pointer events go to the file dialog instead ofon_ptr.
-
on_resize(app, w, h, ud):- Fired when
ConfigureNotifychangesapp->worapp->h(or on XRandR / root screen resize infullscreen_overridemode). A redraw is automatically requested immediately afterward.
- Fired when
-
on_theme(app, ud):- Fired after
gemui_theme_reload(app)completes due to rootXA_RESOURCE_MANAGERproperty updates (xrdb) orSIGUSR1. Callinggemui_theme_reload(app)directly from application code does not invokeon_theme.
- Fired after
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 beforeon_drawon 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 onceGEMUI_MAX_HITS(256) slots are full.gemui_hit_test: Scans backwards (num_hits - 1down to0) and returns the most recently added (topmost/overlapping)gemui_hit_tcontaining(x, y), orNULLif none match.- Lifetime: The returned pointer points into
app->hits[]and is only valid until the next frame renders orgemui_hits_clear()is called. Copyidandvalimmediately if needed across frames. - Disabling hit registration: Built-in widgets (
gemui_draw_button,gemui_draw_toggle,gemui_draw_slider,gemui_draw_input) only callgemui_hit_add()whenhit_id >= 0. Pass-1for disabled/decorative controls.
- Lifetime: The returned pointer points into
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: Callscairo_set_source_rgba(cr, c.r, c.g, c.b, c.a).gemui_rounded_rect: Builds a Cairo subpath forrwith cornerradiusclamped tomin(r.w / 2.0, r.h / 2.0). Falls back tocairo_rectangle()ifradius <= 0.0.gemui_fill_rect: Fills axis-aligned rectanglerwith colorc.gemui_fill_round: Fills rounded rectanglerwith colorc.gemui_stroke_round: Strokes rounded rectanglerusing line widthlwand colorc.
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 toicon_font_face. - Pixel font size is
t->base_font_size + llround(pt_delta * t->scale)(defaulting to15 * scaleift == NULL). Effective Pango sizes<= 8fall back to14px, so keep computed sizes>= 9px. - Single-line (
pango_layout_set_single_paragraph_mode(..., True)), ellipsized with...(PANGO_ELLIPSIZE_END) atr.w, vertically centered insider, and clipped to{r.x, r.y - 4, r.w, r.h + 8}. - Returns: Rendered pixel width (
0iftextisNULL/empty, orr.w <= 4, orr.h <= 4).
- Uses Pango family
gemui_draw_icon:- Uses
t->icon_font_facedirectly (non-bold) with the same size calculation, clipping, and return semantics.
- Uses
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:
activeusessel_bg; elseprimaryusesaccent; else usesbg_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:
focusedhighlights withtheme->highlightand thicker border; otherwise usessel_bg(active) orborder. - Hit registration: Registers
rwith(hit_id, hit_val)ifhit_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
labelat top-left, optionalval_text(e.g."75%") at top-right. - A horizontal track near the bottom (
pad_x = gemui_scale_px(app, 10)inset on each side, heightscale_px(8), knob diameterscale_px(16)), clampingnorm_valto[0.0, 1.0]. - Recommended minimum logical row height:
48–56(gemui_touch_row_px(app, 52)). - Registers
rwith(hit_id, hit_val)ifhit_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
textisNULLor empty, displaysplaceholderinfg_muted(note: whenfocused && mask_bullets && emptyandplaceholder == NULL, displays"_"). - When non-empty and
mask_bullets == true, renders up to 48*characters (with trailing_whenfocused). - When non-empty and
mask_bullets == false, appends_whenfocused(truncated to an internal 511-byte display buffer). - Registers
rwith(hit_id, hit_val)ifhit_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). Setsr, g, b,a = 1.0, andargb = 0xffRRGGBB. Returnsfalseif fewer than 6 valid hex digits are found or pointers areNULL.gemui_theme_defaults(t): Fillstwith 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): Initializesoutwithgemui_theme_defaults(out), then reads an Xresources-format file (path) and applies matching keys. Returnsfalseifpath/outisNULLor the file cannot be opened. (Note: unlikegemui_theme_reload, this helper does not query X11 DPI or auto-scalebase_font_size.)gemui_theme_reload(app): Reloadsapp->themein place using the full precedence chain below.
Theme & DPI Resolution Precedence
1. Resource Database Selection
- If
GEMUI_XRESOURCES(or fallbackANODE_XRESOURCES) is set and readable, only that file is loaded. - Otherwise
$HOME/.Xresourcesis loaded (if present), and the live root-windowXA_RESOURCE_MANAGERproperty (xrdb) is queried directly and merged on top (xrdboverrides~/.Xresources). - If neither exists,
<ANODE_PREFIX>/share/anode/themes/Anodized.xthis tried. - Otherwise built-in Anodized defaults are used.
2. DPI, Scale & Touch Mode Resolution
Xft.dpi(48–384, clamped)anode.scale, falling back totheme.scale(0.5–4.0, clamped)anode.touchMode, falling back totheme.touchMode(1/y/tvs.0/n/f)- If neither
Xft.dpinor*.scalewas found in the database:- Checks
GEMUI_SCALE(thenANODE_SCALE), derivingdpi = 96.0 * scale. - Otherwise detects primary screen EDID DPI (
DisplayWidth * 25.4 / DisplayWidthMM); values in[84, 108]snap to96.0, andscale = clamp(dpi / 96.0).
- Checks
- If only
scalewas found,dpi = clamp(96.0 * scale). If onlyXft.dpiwas found,scale = clamp(dpi / 96.0). base_font_size: Iftheme.baseFontSizecame from.Xresources/xrdb/$GEMUI_XRESOURCES(range8–96), it is used directly as physical pixels; otherwise the logical base size (8–28, default15) is multiplied byscale.
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 insideapp. Returnstrueon success,falseifapp == NULLor 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 aroundgemui_file_dialog_open(no_confirm_overwrite = false).gemui_file_dialog_active: Returnstruewhile a modal file dialog is open onapp.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 temporary760x560(logical) GemUI window with classapp_id(default"gemui-file-dialog"), opens the dialog, runs a nestedgemui_run(), writes the chosen path intoout_path(NUL-terminated), destroys the window, and returnstrueiff 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), checksW_OKon existing files or the parent directory for new files, and optionally prompts before overwriting.
- Open mode checks that the path exists (
- Callback safety: Internal dialog memory is freed and
gemui_file_dialog_active(app)becomesfalsebeforecbruns, socbmay safely callgemui_quit()or immediately open another dialog. - String lifetime:
pathpassed tocbis stack-allocated and invalid oncecbreturns; 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 bothstdoutandstderrintoout(up toout_sz - 1bytes, NUL-terminated). - When
timeout_ms > 0and exceeded, kills the entire child process group (kill(-pid, SIGKILL)) and returns124. Passtimeout_ms <= 0to wait indefinitely. - Returns the child's exit code (
WEXITSTATUS),1if killed by an external signal,127ifexecvpfailed, or-1on setup/waitpidfailure. gemui_run_cmd_capture(argv, out, out_sz)is equivalent togemui_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 inon_key,on_ptr,gemui_fd_cb, orgemui_timer_cb; frames never auto-redraw on idle. - Do not rely on
GEMUI_PTR_MOVEfor 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.idand.valimmediately. - Pass
hit_id = -1to 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
pathinsidegemui_file_dialog_cbbefore 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 withgemui_add_fd()over longgemui_run_cmd_timeout()calls. - Keep one
gemui_app_tper process and callgemui_*APIs strictly from the UI loop thread.