Files
anode/src/libgemui/gemui.c
T

1414 lines
46 KiB
C
Raw Normal View History

#define _POSIX_C_SOURCE 200809L
#include "gemui.h"
#include "anode_plat.h"
#include "anode_scale.h"
#include <errno.h>
#include <fcntl.h>
#include <locale.h>
#include <math.h>
#include <pango/pangocairo.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <X11/Xatom.h>
#include <X11/Xresource.h>
#include <X11/Xutil.h>
#include <X11/extensions/Xinerama.h>
#include <X11/cursorfont.h>
#include <cairo/cairo-xlib.h>
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
#endif
typedef struct {
int fd;
gemui_fd_cb cb;
void *ud;
} gemui_fd_slot_t;
struct gemui_app {
Display *dpy;
int screen;
Window root;
Window win;
Pixmap backbuf;
cairo_surface_t *img_surf;
cairo_t *img_cr;
cairo_surface_t *xlib_surf;
PangoLayout *pango_layout;
GC gc;
int bw;
int bh;
int w;
int h;
Atom wm_delete;
Atom net_wm_name;
Atom utf8_string;
Atom net_wm_state;
Atom net_wm_state_fs;
XIM xim;
XIC xic;
bool fullscreen_override;
bool mapped;
bool need_redraw;
bool running;
int exit_code;
gemui_theme_t theme;
gemui_handlers_t handlers;
void *userdata;
gemui_hit_t hits[GEMUI_MAX_HITS];
int num_hits;
gemui_fd_slot_t fds[GEMUI_MAX_FDS];
int num_fds;
int timer_ms;
uint64_t next_timer_ms;
gemui_timer_cb timer_cb;
void *timer_ud;
char toast_msg[256];
uint64_t toast_until_ms;
bool ptr_down;
Window prev_focus_win;
int prev_focus_revert;
};
static int g_sig_pipe[2] = {-1, -1};
static PangoLayout *g_active_layout = NULL;
static void gemui_sigusr1_handler(int sig) {
(void)sig;
if (g_sig_pipe[1] >= 0) {
int saved = errno;
char b = 'T';
ssize_t unused = write(g_sig_pipe[1], &b, 1);
(void)unused;
errno = saved;
}
}
static uint64_t gemui_now_ms(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)(ts.tv_nsec / 1000000L);
}
static void gemui_init_sigpipe(void) {
if (g_sig_pipe[0] >= 0) {
return;
}
if (pipe(g_sig_pipe) == 0) {
for (int i = 0; i < 2; i++) {
int fl = fcntl(g_sig_pipe[i], F_GETFL, 0);
if (fl >= 0) {
fcntl(g_sig_pipe[i], F_SETFL, fl | O_NONBLOCK);
}
int fdfl = fcntl(g_sig_pipe[i], F_GETFD, 0);
if (fdfl >= 0) {
fcntl(g_sig_pipe[i], F_SETFD, fdfl | FD_CLOEXEC);
}
}
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = gemui_sigusr1_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sigaction(SIGUSR1, &sa, NULL);
}
}
static int hex_val(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
bool gemui_color_parse(const char *hex, gemui_color_t *out) {
if (!hex || !out) return false;
while (*hex == ' ' || *hex == '\t') hex++;
if (*hex == '#') hex++;
size_t n = strlen(hex);
if (n < 6) return false;
int vals[6];
for (int i = 0; i < 6; i++) {
vals[i] = hex_val(hex[i]);
if (vals[i] < 0) return false;
}
uint8_t r = (uint8_t)((vals[0] << 4) | vals[1]);
uint8_t g = (uint8_t)((vals[2] << 4) | vals[3]);
uint8_t b = (uint8_t)((vals[4] << 4) | vals[5]);
out->r = r / 255.0;
out->g = g / 255.0;
out->b = b / 255.0;
out->a = 1.0;
out->argb = 0xff000000U | ((uint32_t)r << 16) | ((uint32_t)g << 8) | (uint32_t)b;
return true;
}
void gemui_theme_defaults(gemui_theme_t *t) {
memset(t, 0, sizeof(*t));
snprintf(t->name, sizeof(t->name), "AnodeDefault");
snprintf(t->font_face, sizeof(t->font_face), "Fira Code");
snprintf(t->icon_font_face, sizeof(t->icon_font_face), "DejaVuSansM Nerd Font");
t->base_font_size = 15;
t->dpi = 96;
t->scale = 1.0;
t->touch_mode = false;
gemui_color_parse("#11141a", &t->bg_main);
gemui_color_parse("#161b23", &t->bg_bar);
gemui_color_parse("#1b212b", &t->bg_header);
gemui_color_parse("#141922", &t->bg_footer);
gemui_color_parse("#18202c", &t->bg_overlay);
gemui_color_parse("#1a202a", &t->bg_alt_even);
gemui_color_parse("#1e2531", &t->bg_alt_odd);
gemui_color_parse("#212936", &t->bg_input);
gemui_color_parse("#273244", &t->bg_input_focus);
gemui_color_parse("#232b38", &t->bg_button);
gemui_color_parse("#202835", &t->bg_search);
gemui_color_parse("#222b3a", &t->bg_bubble_in);
gemui_color_parse("#1f3a52", &t->bg_bubble_out);
gemui_color_parse("#233044", &t->bg_toast);
gemui_color_parse("#d8dee9", &t->fg_main);
gemui_color_parse("#eceff4", &t->fg_bright);
gemui_color_parse("#8a95a8", &t->fg_muted);
gemui_color_parse("#2f6feb", &t->sel_bg);
gemui_color_parse("#ffffff", &t->sel_fg);
gemui_color_parse("#58a6ff", &t->accent);
gemui_color_parse("#79c0ff", &t->accent_alt);
gemui_color_parse("#d2a8ff", &t->highlight);
gemui_color_parse("#30394a", &t->border);
gemui_color_parse("#262f3e", &t->divider);
gemui_color_parse("#3fb950", &t->success);
gemui_color_parse("#58a6ff", &t->info);
gemui_color_parse("#d29922", &t->warning);
gemui_color_parse("#f85149", &t->danger);
gemui_color_parse("#4d1c20", &t->danger_bg);
}
static void gemui_apply_xrm_db(XrmDatabase db, gemui_theme_t *t) {
if (!db) return;
char *type = NULL;
XrmValue val;
struct {
const char *key;
gemui_color_t *dst;
} colors[] = {
{ "theme.bgMain", &t->bg_main },
{ "theme.bgBar", &t->bg_bar },
{ "theme.bgHeader", &t->bg_header },
{ "theme.bgFooter", &t->bg_footer },
{ "theme.bgOverlay", &t->bg_overlay },
{ "theme.bgAltEven", &t->bg_alt_even },
{ "theme.bgAltOdd", &t->bg_alt_odd },
{ "theme.bgInput", &t->bg_input },
{ "theme.bgInputFocus", &t->bg_input_focus },
{ "theme.bgButton", &t->bg_button },
{ "theme.bgSearch", &t->bg_search },
{ "theme.bgBubbleIn", &t->bg_bubble_in },
{ "theme.bgBubbleOut", &t->bg_bubble_out },
{ "theme.bgToast", &t->bg_toast },
{ "theme.fgMain", &t->fg_main },
{ "theme.fgBright", &t->fg_bright },
{ "theme.fgMuted", &t->fg_muted },
{ "theme.selBg", &t->sel_bg },
{ "theme.selFg", &t->sel_fg },
{ "theme.accent", &t->accent },
{ "theme.accentAlt", &t->accent_alt },
{ "theme.highlight", &t->highlight },
{ "theme.border", &t->border },
{ "theme.divider", &t->divider },
{ "theme.success", &t->success },
{ "theme.info", &t->info },
{ "theme.warning", &t->warning },
{ "theme.danger", &t->danger },
{ "theme.dangerBg", &t->danger_bg },
};
for (size_t i = 0; i < sizeof(colors) / sizeof(colors[0]); i++) {
if (XrmGetResource(db, colors[i].key, "Theme.Color", &type, &val) && val.addr) {
gemui_color_parse(val.addr, colors[i].dst);
}
}
if (XrmGetResource(db, "theme.name", "Theme.Name", &type, &val) && val.addr) {
snprintf(t->name, sizeof(t->name), "%s", val.addr);
}
if (XrmGetResource(db, "theme.fontFace", "Theme.FontFace", &type, &val) && val.addr) {
snprintf(t->font_face, sizeof(t->font_face), "%s", val.addr);
}
if (XrmGetResource(db, "theme.iconFontFace", "Theme.IconFontFace", &type, &val) && val.addr) {
snprintf(t->icon_font_face, sizeof(t->icon_font_face), "%s", val.addr);
}
if (XrmGetResource(db, "theme.baseFontSize", "Theme.BaseFontSize", &type, &val) && val.addr) {
int sz = atoi(val.addr);
if (sz >= 8 && sz <= 96) t->base_font_size = sz;
}
if (XrmGetResource(db, "Xft.dpi", "Xft.Dpi", &type, &val) && val.addr) {
int d = atoi(val.addr);
if (d >= 48 && d <= 384) t->dpi = d;
}
if (XrmGetResource(db, "theme.scale", "Theme.Scale", &type, &val) && val.addr) {
double s = strtod(val.addr, NULL);
if (s > 0.0) t->scale = anode_clamp_scale(s);
}
if (XrmGetResource(db, "theme.touchMode", "Theme.TouchMode", &type, &val) && val.addr) {
t->touch_mode = anode_parse_bool_str(val.addr, t->touch_mode ? 1 : 0) != 0;
}
}
bool gemui_theme_load_file(const char *path, gemui_theme_t *out) {
if (!path || !out) return false;
XrmInitialize();
gemui_theme_defaults(out);
XrmDatabase db = XrmGetFileDatabase(path);
if (!db) return false;
gemui_apply_xrm_db(db, out);
XrmDestroyDatabase(db);
return true;
}
void gemui_theme_reload(gemui_app_t *app) {
if (!app) return;
XrmInitialize();
gemui_theme_defaults(&app->theme);
XrmDatabase db = anode_open_xres_db(app->dpy);
bool from_xres = (db != NULL);
if (!db) {
char xth_path[512];
xth_path[0] = '\0';
anode_default_xth_path(xth_path, sizeof(xth_path));
if (xth_path[0]) {
db = XrmGetFileDatabase(xth_path);
}
}
double dpi_d = 96.0, scale_d = 1.0;
int touch_i = 0;
anode_read_xres_scale_from_db(db, app->dpy, &dpi_d, &scale_d, &touch_i);
bool has_explicit_base_sz = false;
if (db) {
gemui_apply_xrm_db(db, &app->theme);
char *type = NULL;
XrmValue val;
if (from_xres &&
XrmGetResource(db, "theme.baseFontSize", "Theme.BaseFontSize", &type, &val) &&
val.addr && val.addr[0]) {
has_explicit_base_sz = true;
}
XrmDestroyDatabase(db);
}
app->theme.dpi = (int)llround(dpi_d);
app->theme.scale = scale_d;
app->theme.touch_mode = (touch_i != 0);
if (!has_explicit_base_sz) {
int logical_base = app->theme.base_font_size;
if (logical_base < 8 || logical_base > 28) logical_base = 15;
app->theme.base_font_size = anode_scale_px(logical_base, scale_d);
}
}
static void gemui_ensure_backbuf(gemui_app_t *app) {
if (app->w <= 0 || app->h <= 0) return;
if (app->backbuf && app->img_cr && app->xlib_surf &&
app->bw == app->w && app->bh == app->h) {
return;
}
if (app->pango_layout) {
g_object_unref(app->pango_layout);
app->pango_layout = NULL;
}
if (app->img_cr) {
cairo_destroy(app->img_cr);
app->img_cr = NULL;
}
if (app->img_surf) {
cairo_surface_destroy(app->img_surf);
app->img_surf = NULL;
}
if (app->xlib_surf) {
cairo_surface_destroy(app->xlib_surf);
app->xlib_surf = NULL;
}
if (app->backbuf) {
XFreePixmap(app->dpy, app->backbuf);
app->backbuf = 0;
}
app->backbuf = XCreatePixmap(app->dpy, app->win, (unsigned int)app->w,
(unsigned int)app->h,
(unsigned int)DefaultDepth(app->dpy, app->screen));
app->xlib_surf = cairo_xlib_surface_create(app->dpy, app->backbuf,
DefaultVisual(app->dpy, app->screen),
app->w, app->h);
app->img_surf = cairo_image_surface_create(CAIRO_FORMAT_RGB24, app->w, app->h);
app->img_cr = cairo_create(app->img_surf);
app->pango_layout = pango_cairo_create_layout(app->img_cr);
app->bw = app->w;
app->bh = app->h;
if (app->backbuf) {
XSetWindowBackgroundPixmap(app->dpy, app->win, app->backbuf);
}
}
static int gemui_ignore_xerror(Display *dpy, XErrorEvent *ev) {
(void)dpy;
(void)ev;
return 0;
}
static void gemui_save_prev_focus(gemui_app_t *app) {
if (!app || app->prev_focus_win != None) return;
Window cur = None;
int rev = RevertToPointerRoot;
XGetInputFocus(app->dpy, &cur, &rev);
if (cur != None && cur != app->win) {
app->prev_focus_win = cur;
app->prev_focus_revert = rev;
}
}
static void gemui_restore_prev_focus(gemui_app_t *app) {
if (!app || app->prev_focus_win == None || app->prev_focus_win == app->win) return;
XSync(app->dpy, False);
int (*old_handler)(Display *, XErrorEvent *) = XSetErrorHandler(gemui_ignore_xerror);
XSetInputFocus(app->dpy, app->prev_focus_win, app->prev_focus_revert, CurrentTime);
XSync(app->dpy, False);
XSetErrorHandler(old_handler);
app->prev_focus_win = None;
}
gemui_app_t *gemui_create(const char *res_name, const char *title,
int w, int h, bool fullscreen_override) {
setlocale(LC_CTYPE, "");
XSetLocaleModifiers("");
gemui_init_sigpipe();
Display *dpy = XOpenDisplay(NULL);
if (!dpy) {
fprintf(stderr, "gemui: cannot open X11 display\n");
return NULL;
}
gemui_app_t *app = calloc(1, sizeof(*app));
if (!app) {
XCloseDisplay(dpy);
return NULL;
}
app->dpy = dpy;
app->screen = DefaultScreen(dpy);
app->root = RootWindow(dpy, app->screen);
app->fullscreen_override = fullscreen_override;
gemui_theme_reload(app);
int sw = DisplayWidth(dpy, app->screen);
int sh = DisplayHeight(dpy, app->screen);
int mx = 0, my = 0, mw = sw, mh = sh;
/* Pick monitor under pointer via Xinerama if active */
{
int xn = 0;
XineramaScreenInfo *xi = XineramaIsActive(dpy) ? XineramaQueryScreens(dpy, &xn) : NULL;
if (xi && xn > 0) {
Window d_w;
int rx = 0, ry = 0, di = 0;
unsigned int du = 0;
int chosen = 0;
if (XQueryPointer(dpy, app->root, &d_w, &d_w, &rx, &ry, &di, &di, &du)) {
for (int k = 0; k < xn; k++) {
if (rx >= xi[k].x_org && rx < xi[k].x_org + xi[k].width &&
ry >= xi[k].y_org && ry < xi[k].y_org + xi[k].height) {
chosen = k;
break;
}
}
}
mx = xi[chosen].x_org;
my = xi[chosen].y_org;
mw = xi[chosen].width;
mh = xi[chosen].height;
XFree(xi);
}
}
/* Respect _NET_WORKAREA if published by DWM/EWMH */
if (!fullscreen_override) {
Atom workarea_atom = XInternAtom(dpy, "_NET_WORKAREA", False);
Atom da = None;
int di = 0;
unsigned long n = 0, dl = 0;
unsigned char *prop = NULL;
if (XGetWindowProperty(dpy, app->root, workarea_atom, 0L, 4L, False, XA_CARDINAL,
&da, &di, &n, &dl, &prop) == Success && prop) {
if (di == 32 && n >= 4) {
unsigned long *wa = (unsigned long *)prop;
int wx0 = (int)wa[0], wy0 = (int)wa[1], ww0 = (int)wa[2], wh0 = (int)wa[3];
if (ww0 > 64 && wh0 > 64 &&
wx0 < mx + mw && wx0 + ww0 > mx &&
wy0 < my + mh && wy0 + wh0 > my) {
int x1 = (wx0 > mx) ? wx0 : mx;
int y1 = (wy0 > my) ? wy0 : my;
int x2 = (wx0 + ww0 < mx + mw) ? (wx0 + ww0) : (mx + mw);
int y2 = (wy0 + wh0 < my + mh) ? (wy0 + wh0) : (my + mh);
if (x2 - x1 > 64 && y2 - y1 > 64) {
mx = x1; my = y1; mw = x2 - x1; mh = y2 - y1;
}
}
}
XFree(prop);
}
}
if (fullscreen_override || w <= 0) {
w = mw;
} else {
int scaled_w = gemui_scale_px(app, w);
int pad = gemui_scale_px(app, 24);
int max_w = (mw > pad * 2) ? (mw - pad) : mw;
int min_w = gemui_scale_px(app, 260);
if (scaled_w > max_w) scaled_w = max_w;
if (scaled_w < min_w && max_w >= min_w) scaled_w = min_w;
w = scaled_w;
}
if (fullscreen_override || h <= 0) {
h = mh;
} else {
int scaled_h = gemui_scale_px(app, h);
int pad = gemui_scale_px(app, 32);
int max_h = (mh > pad * 2) ? (mh - pad) : mh;
int min_h = gemui_scale_px(app, 180);
if (scaled_h > max_h) scaled_h = max_h;
if (scaled_h < min_h && max_h >= min_h) scaled_h = min_h;
h = scaled_h;
}
app->w = w;
app->h = h;
int wx = fullscreen_override ? 0 : mx + (mw - w) / 2;
int wy = fullscreen_override ? 0 : my + (mh - h) / 2;
if (wx < 0) wx = 0;
if (wy < 0) wy = 0;
XSetWindowAttributes swa;
memset(&swa, 0, sizeof(swa));
swa.background_pixmap = None;
swa.event_mask = ExposureMask | KeyPressMask | ButtonPressMask |
ButtonReleaseMask | PointerMotionMask |
StructureNotifyMask | FocusChangeMask;
if (fullscreen_override) {
swa.override_redirect = True;
swa.event_mask |= VisibilityChangeMask;
}
unsigned long mask = CWBackPixmap | CWEventMask | (fullscreen_override ? CWOverrideRedirect : 0);
app->win = XCreateWindow(dpy, app->root, wx, wy, (unsigned int)w, (unsigned int)h, 0,
CopyFromParent, InputOutput, CopyFromParent, mask, &swa);
{
XSizeHints *shints = XAllocSizeHints();
if (shints) {
shints->flags = PPosition | PSize;
shints->x = wx;
shints->y = wy;
shints->width = w;
shints->height = h;
XSetWMNormalHints(dpy, app->win, shints);
XFree(shints);
}
}
{
Cursor cur = XCreateFontCursor(dpy, XC_left_ptr);
if (cur != None) {
XDefineCursor(dpy, app->win, cur);
XFreeCursor(dpy, cur);
}
}
app->gc = XCreateGC(dpy, app->win, 0, NULL);
XClassHint *ch = XAllocClassHint();
if (ch) {
ch->res_name = (char *)(res_name ? res_name : "anode-app");
ch->res_class = (char *)(res_name ? res_name : "anode-app");
XSetClassHint(dpy, app->win, ch);
XFree(ch);
}
XSelectInput(dpy, app->root,
fullscreen_override ? (PropertyChangeMask | SubstructureNotifyMask)
: PropertyChangeMask);
app->wm_delete = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
app->net_wm_name = XInternAtom(dpy, "_NET_WM_NAME", False);
app->utf8_string = XInternAtom(dpy, "UTF8_STRING", False);
app->net_wm_state = XInternAtom(dpy, "_NET_WM_STATE", False);
app->net_wm_state_fs = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
XSetWMProtocols(dpy, app->win, &app->wm_delete, 1);
if (fullscreen_override) {
XChangeProperty(dpy, app->win, app->net_wm_state, XA_ATOM, 32,
PropModeReplace, (unsigned char *)&app->net_wm_state_fs, 1);
}
gemui_set_title(app, title ? title : "ANODE");
app->xim = XOpenIM(dpy, NULL, NULL, NULL);
if (app->xim) {
app->xic = XCreateIC(app->xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
XNClientWindow, app->win, XNFocusWindow, app->win, NULL);
}
if (fullscreen_override) {
XMapRaised(dpy, app->win);
app->mapped = true;
XMoveResizeWindow(dpy, app->win, mx, my, (unsigned int)mw, (unsigned int)mh);
gemui_save_prev_focus(app);
XSetInputFocus(dpy, app->win, RevertToPointerRoot, CurrentTime);
}
XFlush(dpy);
app->need_redraw = true;
return app;
}
void gemui_destroy(gemui_app_t *app) {
if (!app) return;
gemui_restore_prev_focus(app);
if (app->xic) XDestroyIC(app->xic);
if (app->xim) XCloseIM(app->xim);
if (app->pango_layout) g_object_unref(app->pango_layout);
if (app->img_cr) cairo_destroy(app->img_cr);
if (app->img_surf) cairo_surface_destroy(app->img_surf);
if (app->xlib_surf) cairo_surface_destroy(app->xlib_surf);
if (app->backbuf) XFreePixmap(app->dpy, app->backbuf);
if (app->gc) XFreeGC(app->dpy, app->gc);
if (app->win) XDestroyWindow(app->dpy, app->win);
if (app->dpy) XCloseDisplay(app->dpy);
free(app);
}
void gemui_set_handlers(gemui_app_t *app, const gemui_handlers_t *h, void *userdata) {
if (!app) return;
if (h) app->handlers = *h;
app->userdata = userdata;
}
void gemui_set_title(gemui_app_t *app, const char *title) {
if (!app || !title) return;
XStoreName(app->dpy, app->win, title);
XChangeProperty(app->dpy, app->win, app->net_wm_name, app->utf8_string, 8,
PropModeReplace, (const unsigned char *)title, (int)strlen(title));
}
Display *gemui_display(const gemui_app_t *app) { return app ? app->dpy : NULL; }
Window gemui_window(const gemui_app_t *app) { return app ? app->win : 0; }
const gemui_theme_t *gemui_theme(const gemui_app_t *app) { return app ? &app->theme : NULL; }
int gemui_width(const gemui_app_t *app) { return app ? app->w : 0; }
int gemui_height(const gemui_app_t *app) { return app ? app->h : 0; }
double gemui_scale(const gemui_app_t *app) {
return app ? app->theme.scale : 1.0;
}
bool gemui_touch_mode(const gemui_app_t *app) {
return app ? app->theme.touch_mode : false;
}
int gemui_scale_px(const gemui_app_t *app, int logical_px) {
double s = app ? app->theme.scale : 1.0;
return anode_scale_px(logical_px, s);
}
int gemui_touch_row_px(const gemui_app_t *app, int logical_px) {
double s = app ? app->theme.scale : 1.0;
if (app && app->theme.touch_mode) {
s *= 1.18;
}
return anode_scale_px(logical_px, s);
}
int gemui_add_fd(gemui_app_t *app, int fd, gemui_fd_cb cb, void *userdata) {
if (!app || fd < 0 || app->num_fds >= GEMUI_MAX_FDS) return -1;
for (int i = 0; i < app->num_fds; i++) {
if (app->fds[i].fd == fd) {
app->fds[i].cb = cb;
app->fds[i].ud = userdata;
return 0;
}
}
app->fds[app->num_fds].fd = fd;
app->fds[app->num_fds].cb = cb;
app->fds[app->num_fds].ud = userdata;
app->num_fds++;
return 0;
}
void gemui_del_fd(gemui_app_t *app, int fd) {
if (!app) return;
for (int i = 0; i < app->num_fds; i++) {
if (app->fds[i].fd == fd) {
app->fds[i] = app->fds[app->num_fds - 1];
app->num_fds--;
return;
}
}
}
void gemui_set_timer_ms(gemui_app_t *app, int interval_ms, gemui_timer_cb cb, void *userdata) {
if (!app) return;
app->timer_ms = interval_ms;
app->timer_cb = cb;
app->timer_ud = userdata;
app->next_timer_ms = (interval_ms > 0) ? (gemui_now_ms() + (uint64_t)interval_ms) : 0;
}
void gemui_request_redraw(gemui_app_t *app) {
if (app) app->need_redraw = true;
}
void gemui_show_toast(gemui_app_t *app, const char *msg, int duration_ms) {
if (!app) return;
if (!msg || !msg[0]) {
app->toast_msg[0] = '\0';
app->toast_until_ms = 0;
} else {
snprintf(app->toast_msg, sizeof(app->toast_msg), "%s", msg);
app->toast_until_ms = gemui_now_ms() + (uint64_t)(duration_ms > 0 ? duration_ms : 2200);
}
app->need_redraw = true;
}
void gemui_quit(gemui_app_t *app, int code) {
if (!app) return;
app->exit_code = code;
app->running = false;
}
bool gemui_grab_input(gemui_app_t *app) {
if (!app) return false;
if (!app->mapped) {
gemui_flush_draw(app);
}
bool ok_kbd = XGrabKeyboard(app->dpy, app->win, True, GrabModeAsync,
GrabModeAsync, CurrentTime) == GrabSuccess;
XGrabPointer(app->dpy, app->win, True,
ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
GrabModeAsync, GrabModeAsync, app->win, None, CurrentTime);
gemui_save_prev_focus(app);
if (app->mapped) {
XSetInputFocus(app->dpy, app->win, RevertToPointerRoot, CurrentTime);
}
XFlush(app->dpy);
return ok_kbd;
}
void gemui_ungrab_input(gemui_app_t *app) {
if (!app) return;
XUngrabKeyboard(app->dpy, CurrentTime);
XUngrabPointer(app->dpy, CurrentTime);
gemui_restore_prev_focus(app);
XFlush(app->dpy);
}
void gemui_hits_clear(gemui_app_t *app) {
if (app) app->num_hits = 0;
}
void gemui_hit_add(gemui_app_t *app, gemui_rect_t r, int id, int val) {
if (!app || app->num_hits >= GEMUI_MAX_HITS) return;
app->hits[app->num_hits].r = r;
app->hits[app->num_hits].id = id;
app->hits[app->num_hits].val = val;
app->num_hits++;
}
const gemui_hit_t *gemui_hit_test(const gemui_app_t *app, int x, int y) {
if (!app) return NULL;
for (int i = app->num_hits - 1; i >= 0; i--) {
gemui_rect_t r = app->hits[i].r;
if (x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h) {
return &app->hits[i];
}
}
return NULL;
}
static void gemui_render_frame(gemui_app_t *app) {
if (!app || !app->need_redraw || app->w <= 0 || app->h <= 0) return;
gemui_ensure_backbuf(app);
if (!app->backbuf || !app->img_cr || !app->xlib_surf) return;
cairo_t *cr = app->img_cr;
g_active_layout = app->pango_layout;
gemui_hits_clear(app);
gemui_fill_rect(cr, (gemui_rect_t){0, 0, app->w, app->h}, app->theme.bg_main);
if (app->handlers.on_draw) {
app->handlers.on_draw(app, cr, app->w, app->h, app->userdata);
}
gemui_draw_toast(app, cr);
g_active_layout = NULL;
cairo_surface_flush(app->img_surf);
cairo_t *xcr = cairo_create(app->xlib_surf);
cairo_set_operator(xcr, CAIRO_OPERATOR_SOURCE);
cairo_set_source_surface(xcr, app->img_surf, 0, 0);
cairo_paint(xcr);
cairo_destroy(xcr);
cairo_surface_flush(app->xlib_surf);
if (!app->mapped) {
XSetWindowBackgroundPixmap(app->dpy, app->win, app->backbuf);
XMapRaised(app->dpy, app->win);
app->mapped = true;
}
XCopyArea(app->dpy, app->backbuf, app->win, app->gc, 0, 0,
(unsigned int)app->w, (unsigned int)app->h, 0, 0);
XFlush(app->dpy);
app->need_redraw = false;
}
void gemui_flush_draw(gemui_app_t *app) {
if (!app) return;
app->need_redraw = true;
gemui_render_frame(app);
}
static bool gemui_is_vkbd_win(Display *dpy, Window w) {
if (!dpy || w == None) return false;
int (*old_handler)(Display *, XErrorEvent *) = XSetErrorHandler(gemui_ignore_xerror);
XClassHint ch;
memset(&ch, 0, sizeof(ch));
bool is_vkbd = false;
if (XGetClassHint(dpy, w, &ch)) {
if (ch.res_name && strcmp(ch.res_name, "anode-vkbd") == 0) {
is_vkbd = true;
}
if (ch.res_name) XFree(ch.res_name);
if (ch.res_class) XFree(ch.res_class);
}
XSetErrorHandler(old_handler);
return is_vkbd;
}
static void gemui_keep_fullscreen_on_top(gemui_app_t *app) {
if (!app || !app->fullscreen_override || !app->mapped || !app->dpy || app->win == None) return;
Window root_ret = None, parent_ret = None;
Window *children = NULL;
unsigned int nchildren = 0;
int (*old_handler)(Display *, XErrorEvent *) = XSetErrorHandler(gemui_ignore_xerror);
if (!XQueryTree(app->dpy, app->root, &root_ret, &parent_ret, &children, &nchildren)) {
XSetErrorHandler(old_handler);
return;
}
Window top_non_vkbd = None;
Window top_vkbd = None;
for (int i = (int)nchildren - 1; i >= 0; i--) {
Window cw = children[i];
XWindowAttributes wa;
if (!XGetWindowAttributes(app->dpy, cw, &wa) || wa.map_state != IsViewable) continue;
if (cw == app->win) {
if (top_non_vkbd == None) top_non_vkbd = cw;
break;
}
if (gemui_is_vkbd_win(app->dpy, cw)) {
if (top_vkbd == None) top_vkbd = cw;
} else if (top_non_vkbd == None) {
top_non_vkbd = cw;
}
}
if (top_non_vkbd != app->win) {
XRaiseWindow(app->dpy, app->win);
if (top_vkbd != None) {
XRaiseWindow(app->dpy, top_vkbd);
}
XFlush(app->dpy);
}
if (children) XFree(children);
XSetErrorHandler(old_handler);
}
static void gemui_handle_x_events(gemui_app_t *app) {
while (XPending(app->dpy) > 0 && app->running) {
XEvent ev;
XNextEvent(app->dpy, &ev);
if (XFilterEvent(&ev, None)) continue;
switch (ev.type) {
case Expose:
if (ev.xexpose.count == 0) app->need_redraw = true;
break;
case ConfigureNotify:
if (ev.xconfigure.window == app->win) {
if (ev.xconfigure.width != app->w || ev.xconfigure.height != app->h) {
app->w = ev.xconfigure.width;
app->h = ev.xconfigure.height;
if (app->handlers.on_resize) {
app->handlers.on_resize(app, app->w, app->h, app->userdata);
}
app->need_redraw = true;
}
} else if (app->fullscreen_override && !gemui_is_vkbd_win(app->dpy, ev.xconfigure.window)) {
gemui_keep_fullscreen_on_top(app);
}
break;
case MapNotify:
if (app->fullscreen_override && ev.xmap.window != app->win &&
!gemui_is_vkbd_win(app->dpy, ev.xmap.window)) {
gemui_keep_fullscreen_on_top(app);
}
break;
case VisibilityNotify:
if (app->fullscreen_override && ev.xvisibility.window == app->win &&
ev.xvisibility.state != VisibilityUnobscured) {
gemui_keep_fullscreen_on_top(app);
}
break;
case ClientMessage:
if ((Atom)ev.xclient.data.l[0] == app->wm_delete) {
gemui_quit(app, 0);
}
break;
case KeyPress: {
char buf[64] = {0};
KeySym ks = NoSymbol;
Status st = 0;
int len = 0;
if (app->xic) {
len = Xutf8LookupString(app->xic, &ev.xkey, buf, (int)sizeof(buf) - 1, &ks, &st);
} else {
len = XLookupString(&ev.xkey, buf, (int)sizeof(buf) - 1, &ks, NULL);
}
if (len < 0) len = 0;
buf[len] = '\0';
/* Ignore bare control characters like Ctrl+C/Backspace inside utf8 text buffer */
if (len > 0 && ((unsigned char)buf[0] < 0x20 || buf[0] == 0x7f)) {
buf[0] = '\0';
}
if (app->handlers.on_key) {
app->handlers.on_key(app, ks, ev.xkey.state, buf, app->userdata);
}
break;
}
case ButtonPress:
if (ev.xbutton.button == Button4) {
if (app->handlers.on_ptr) {
app->handlers.on_ptr(app, GEMUI_PTR_SCROLL_UP, ev.xbutton.x, ev.xbutton.y,
ev.xbutton.button, app->userdata);
}
} else if (ev.xbutton.button == Button5) {
if (app->handlers.on_ptr) {
app->handlers.on_ptr(app, GEMUI_PTR_SCROLL_DOWN, ev.xbutton.x, ev.xbutton.y,
ev.xbutton.button, app->userdata);
}
} else {
app->ptr_down = true;
if (app->handlers.on_ptr) {
app->handlers.on_ptr(app, GEMUI_PTR_DOWN, ev.xbutton.x, ev.xbutton.y,
ev.xbutton.button, app->userdata);
}
}
break;
case MotionNotify:
while (XPending(app->dpy) > 0) {
XEvent pev;
XPeekEvent(app->dpy, &pev);
if (pev.type != MotionNotify || pev.xmotion.window != ev.xmotion.window) break;
XNextEvent(app->dpy, &ev);
}
if (app->ptr_down && app->handlers.on_ptr) {
app->handlers.on_ptr(app, GEMUI_PTR_MOVE, ev.xmotion.x, ev.xmotion.y,
0, app->userdata);
}
break;
case ButtonRelease:
if (ev.xbutton.button != Button4 && ev.xbutton.button != Button5) {
app->ptr_down = false;
if (app->handlers.on_ptr) {
app->handlers.on_ptr(app, GEMUI_PTR_UP, ev.xbutton.x, ev.xbutton.y,
ev.xbutton.button, app->userdata);
}
}
break;
case PropertyNotify:
if (ev.xproperty.window == app->root &&
ev.xproperty.atom == XA_RESOURCE_MANAGER &&
ev.xproperty.state != PropertyDelete) {
gemui_theme_reload(app);
if (app->handlers.on_theme) {
app->handlers.on_theme(app, app->userdata);
}
app->need_redraw = true;
}
break;
default:
break;
}
}
}
int gemui_run(gemui_app_t *app) {
if (!app) return 1;
app->running = true;
int xfd = ConnectionNumber(app->dpy);
while (app->running) {
gemui_handle_x_events(app);
if (!app->running) break;
uint64_t now = gemui_now_ms();
if (app->toast_until_ms && now >= app->toast_until_ms) {
app->toast_msg[0] = '\0';
app->toast_until_ms = 0;
app->need_redraw = true;
}
if (app->timer_ms > 0 && app->timer_cb && now >= app->next_timer_ms) {
app->next_timer_ms = now + (uint64_t)app->timer_ms;
app->timer_cb(app, app->timer_ud);
}
if (app->need_redraw) {
gemui_render_frame(app);
}
int timeout_ms = -1;
now = gemui_now_ms();
if (app->timer_ms > 0 && app->timer_cb) {
int rem = (app->next_timer_ms > now) ? (int)(app->next_timer_ms - now) : 0;
timeout_ms = rem;
}
if (app->toast_until_ms > 0) {
int rem = (app->toast_until_ms > now) ? (int)(app->toast_until_ms - now) : 0;
if (timeout_ms < 0 || rem < timeout_ms) timeout_ms = rem;
}
struct pollfd pfds[2 + GEMUI_MAX_FDS];
nfds_t nfds = 0;
pfds[nfds].fd = xfd;
pfds[nfds].events = POLLIN;
pfds[nfds].revents = 0;
nfds++;
int sig_idx = -1;
if (g_sig_pipe[0] >= 0) {
sig_idx = (int)nfds;
pfds[nfds].fd = g_sig_pipe[0];
pfds[nfds].events = POLLIN;
pfds[nfds].revents = 0;
nfds++;
}
int extra_start = (int)nfds;
for (int i = 0; i < app->num_fds; i++) {
pfds[nfds].fd = app->fds[i].fd;
pfds[nfds].events = POLLIN;
pfds[nfds].revents = 0;
nfds++;
}
if (XPending(app->dpy) > 0) continue;
int rc = poll(pfds, nfds, timeout_ms);
if (rc < 0 && errno == EINTR) continue;
if (sig_idx >= 0 && (pfds[sig_idx].revents & POLLIN)) {
char drain[32];
while (read(g_sig_pipe[0], drain, sizeof(drain)) > 0) {}
gemui_theme_reload(app);
if (app->handlers.on_theme) {
app->handlers.on_theme(app, app->userdata);
}
app->need_redraw = true;
}
for (int i = 0; i < app->num_fds; i++) {
int idx = extra_start + i;
if (idx < (int)nfds && (pfds[idx].revents & (POLLIN | POLLHUP | POLLERR))) {
if (app->fds[i].cb) {
app->fds[i].cb(app, app->fds[i].fd, app->fds[i].ud);
}
}
}
}
return app->exit_code;
}
void gemui_set_source(cairo_t *cr, gemui_color_t c) {
cairo_set_source_rgba(cr, c.r, c.g, c.b, c.a);
}
void gemui_rounded_rect(cairo_t *cr, gemui_rect_t r, double rad) {
if (rad <= 0.0) {
cairo_rectangle(cr, r.x, r.y, r.w, r.h);
return;
}
if (rad > r.w / 2.0) rad = r.w / 2.0;
if (rad > r.h / 2.0) rad = r.h / 2.0;
const double pi = 3.14159265358979323846;
cairo_new_sub_path(cr);
cairo_arc(cr, r.x + r.w - rad, r.y + rad, rad, -pi / 2.0, 0.0);
cairo_arc(cr, r.x + r.w - rad, r.y + r.h - rad, rad, 0.0, pi / 2.0);
cairo_arc(cr, r.x + rad, r.y + r.h - rad, rad, pi / 2.0, pi);
cairo_arc(cr, r.x + rad, r.y + rad, rad, pi, 3.0 * pi / 2.0);
cairo_close_path(cr);
}
void gemui_fill_rect(cairo_t *cr, gemui_rect_t r, gemui_color_t c) {
gemui_set_source(cr, c);
cairo_rectangle(cr, r.x, r.y, r.w, r.h);
cairo_fill(cr);
}
void gemui_fill_round(cairo_t *cr, gemui_rect_t r, double radius, gemui_color_t c) {
gemui_set_source(cr, c);
gemui_rounded_rect(cr, r, radius);
cairo_fill(cr);
}
void gemui_stroke_round(cairo_t *cr, gemui_rect_t r, double radius, double lw, gemui_color_t c) {
gemui_set_source(cr, c);
cairo_set_line_width(cr, lw);
gemui_rounded_rect(cr, r, radius);
cairo_stroke(cr);
}
static int gemui_draw_pango(cairo_t *cr, const char *face, int px_size,
gemui_rect_t r, const char *text, bool bold,
int align, gemui_color_t c) {
if (!text || !text[0] || r.w <= 4 || r.h <= 4) return 0;
PangoLayout *layout = g_active_layout ? g_active_layout : pango_cairo_create_layout(cr);
char desc_str[288];
snprintf(desc_str, sizeof(desc_str), "%s%s %dpx",
face && face[0] ? face : "Fira Code",
bold ? " Bold" : "",
px_size > 8 ? px_size : 14);
PangoFontDescription *desc = pango_font_description_from_string(desc_str);
pango_layout_set_attributes(layout, NULL);
pango_layout_set_font_description(layout, desc);
pango_layout_set_width(layout, r.w * PANGO_SCALE);
pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END);
pango_layout_set_single_paragraph_mode(layout, True);
if (align == GEMUI_ALIGN_CENTER) {
pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER);
} else if (align == GEMUI_ALIGN_RIGHT) {
pango_layout_set_alignment(layout, PANGO_ALIGN_RIGHT);
} else {
pango_layout_set_alignment(layout, PANGO_ALIGN_LEFT);
}
pango_layout_set_text(layout, text, -1);
int tw = 0, th = 0;
pango_layout_get_pixel_size(layout, &tw, &th);
int dy = r.y + (r.h - th) / 2;
gemui_set_source(cr, c);
cairo_move_to(cr, r.x, dy);
pango_cairo_show_layout(cr, layout);
pango_font_description_free(desc);
if (!g_active_layout) g_object_unref(layout);
return tw;
}
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) {
double sc = (t && t->scale > 0.0) ? t->scale : 1.0;
int base_px = (t && t->base_font_size > 0) ? t->base_font_size : anode_scale_px(15, sc);
int delta_px = (int)llround((double)pt_delta * sc);
int px = base_px + delta_px;
if (px < 8) px = 8;
char fam[224];
snprintf(fam, sizeof(fam), "%s, %s",
(t && t->font_face[0]) ? t->font_face : "Fira Code",
(t && t->icon_font_face[0]) ? t->icon_font_face : "DejaVuSansM Nerd Font");
return gemui_draw_pango(cr, fam, px, r, text, bold, align, 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) {
double sc = (t && t->scale > 0.0) ? t->scale : 1.0;
int base_px = (t && t->base_font_size > 0) ? t->base_font_size : anode_scale_px(15, sc);
int delta_px = (int)llround((double)pt_delta * sc);
int px = base_px + delta_px;
if (px < 8) px = 8;
const char *iface = (t && t->icon_font_face[0]) ? t->icon_font_face : "DejaVuSansM Nerd Font";
return gemui_draw_pango(cr, iface, px, r, icon_utf8, false, align, c);
}
void gemui_draw_header(gemui_app_t *app, cairo_t *cr, const char *icon,
const char *title, const char *right_badge) {
if (!app) return;
const gemui_theme_t *t = &app->theme;
int hh = gemui_scale_px(app, 42);
int div_h = gemui_scale_px(app, 1);
if (div_h < 1) div_h = 1;
gemui_fill_rect(cr, (gemui_rect_t){0, 0, app->w, hh}, t->bg_header);
gemui_fill_rect(cr, (gemui_rect_t){0, hh - div_h, app->w, div_h}, t->divider);
int x = gemui_scale_px(app, 12);
int vpad = gemui_scale_px(app, 4);
int icon_w = gemui_scale_px(app, 28);
int badge_w = 0;
int badge_pad = gemui_scale_px(app, 10);
if (right_badge && right_badge[0]) {
badge_w = gemui_scale_px(app, 210);
if (badge_w > app->w / 3) badge_w = app->w / 3;
gemui_rect_t br = {
app->w - badge_w - badge_pad,
gemui_scale_px(app, 6),
badge_w,
hh - gemui_scale_px(app, 12)
};
double rad = (double)gemui_scale_px(app, 6);
gemui_fill_round(cr, br, rad, t->bg_overlay);
gemui_stroke_round(cr, br, rad, t->scale >= 1.5 ? 1.5 : 1.0, t->border);
int b_inset = gemui_scale_px(app, 8);
gemui_draw_text(cr, t, (gemui_rect_t){br.x + b_inset, br.y, br.w - b_inset * 2, br.h},
right_badge, -1, false, GEMUI_ALIGN_CENTER, t->fg_main);
}
if (icon && icon[0]) {
gemui_draw_icon(cr, t, (gemui_rect_t){x, vpad, icon_w, hh - vpad * 2},
icon, 3, GEMUI_ALIGN_CENTER, t->accent);
x += icon_w + gemui_scale_px(app, 6);
}
int title_w = app->w - x - (badge_w > 0 ? badge_w + badge_pad * 2 : x);
gemui_draw_text(cr, t, (gemui_rect_t){x, vpad, title_w, hh - vpad * 2},
title ? title : "", 2, true, GEMUI_ALIGN_LEFT, t->fg_bright);
}
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) {
if (!app) return;
const gemui_theme_t *t = &app->theme;
gemui_color_t bg = active ? t->sel_bg : (primary ? t->accent : t->bg_button);
gemui_color_t fg = (active || primary) ? t->sel_fg : t->fg_bright;
gemui_color_t bd = focused ? t->highlight : (active ? t->sel_bg : t->border);
double rad = (double)gemui_scale_px(app, 6);
double lw = focused ? (t->scale >= 1.5 ? 2.5 : 2.0) : (t->scale >= 1.5 ? 1.5 : 1.0);
int pad = gemui_scale_px(app, 6);
gemui_fill_round(cr, r, rad, bg);
gemui_stroke_round(cr, r, rad, lw, bd);
gemui_draw_text(cr, t, (gemui_rect_t){r.x + pad, r.y + 1, r.w - pad * 2, r.h - 2},
label ? label : "", 0, primary || active, GEMUI_ALIGN_CENTER, fg);
if (hit_id >= 0) {
gemui_hit_add(app, r, hit_id, hit_val);
}
}
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) {
if (!app) return;
const gemui_theme_t *t = &app->theme;
double rad = (double)gemui_scale_px(app, 6);
double lw = focused ? (t->scale >= 1.5 ? 2.5 : 2.0) : (t->scale >= 1.5 ? 1.5 : 1.0);
gemui_fill_round(cr, r, rad, t->bg_alt_even);
gemui_stroke_round(cr, r, rad, lw, focused ? t->highlight : t->border);
int pill_w = gemui_scale_px(app, 48);
int pill_h = gemui_scale_px(app, 24);
if (pill_h > r.h - 4) pill_h = r.h - 4;
int pad_x = gemui_scale_px(app, 10);
int k_inset = gemui_scale_px(app, 2);
if (k_inset < 2) k_inset = 2;
int k_sz = pill_h - k_inset * 2;
gemui_draw_text(cr, t, (gemui_rect_t){r.x + pad_x, r.y, r.w - pill_w - pad_x * 3, r.h},
label ? label : "", 0, false, GEMUI_ALIGN_LEFT, t->fg_main);
gemui_rect_t pill = {r.x + r.w - pill_w - pad_x, r.y + (r.h - pill_h) / 2, pill_w, pill_h};
gemui_fill_round(cr, pill, (double)pill_h / 2.0, on ? t->success : t->bg_overlay);
gemui_stroke_round(cr, pill, (double)pill_h / 2.0, lw, on ? t->success : t->border);
gemui_rect_t knob = {on ? (pill.x + pill.w - k_sz - k_inset) : (pill.x + k_inset),
pill.y + k_inset, k_sz, k_sz};
gemui_fill_round(cr, knob, (double)k_sz / 2.0, t->fg_bright);
if (hit_id >= 0) {
gemui_hit_add(app, r, hit_id, hit_val);
}
}
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) {
if (!app) return;
const gemui_theme_t *t = &app->theme;
if (norm_val < 0.0) norm_val = 0.0;
if (norm_val > 1.0) norm_val = 1.0;
double rad = (double)gemui_scale_px(app, 6);
double lw = focused ? (t->scale >= 1.5 ? 2.5 : 2.0) : (t->scale >= 1.5 ? 1.5 : 1.0);
int pad_x = gemui_scale_px(app, 10);
int top_y = r.y + gemui_scale_px(app, 4);
int txt_h = gemui_scale_px(app, 22);
gemui_fill_round(cr, r, rad, t->bg_alt_even);
gemui_stroke_round(cr, r, rad, lw, focused ? t->highlight : t->border);
gemui_draw_text(cr, t, (gemui_rect_t){r.x + pad_x, top_y, r.w / 2, txt_h},
label ? label : "", -1, true, GEMUI_ALIGN_LEFT, t->fg_bright);
if (val_text && val_text[0]) {
gemui_draw_text(cr, t, (gemui_rect_t){r.x + r.w / 2, top_y, r.w / 2 - pad_x, txt_h},
val_text, -1, false, GEMUI_ALIGN_RIGHT, t->accent);
}
int track_h = gemui_scale_px(app, 8);
int knob_d = gemui_scale_px(app, 16);
int track_y = r.y + r.h - gemui_scale_px(app, 14);
gemui_rect_t track = {r.x + pad_x, track_y, r.w - pad_x * 2, track_h};
gemui_fill_round(cr, track, (double)track_h / 2.0, t->bg_overlay);
int fw = (int)(track.w * norm_val);
if (fw > 0) {
gemui_fill_round(cr, (gemui_rect_t){track.x, track.y, fw, track.h},
(double)track_h / 2.0, t->accent);
}
int kx = track.x + fw - knob_d / 2;
if (kx < track.x) kx = track.x;
if (kx > track.x + track.w - knob_d) kx = track.x + track.w - knob_d;
gemui_rect_t knob = {kx, track.y + (track.h - knob_d) / 2, knob_d, knob_d};
gemui_fill_round(cr, knob, (double)knob_d / 2.0, t->fg_bright);
if (hit_id >= 0) {
gemui_hit_add(app, r, hit_id, hit_val);
}
}
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) {
if (!app) return;
const gemui_theme_t *t = &app->theme;
double rad = (double)gemui_scale_px(app, 6);
double lw = focused ? (t->scale >= 1.5 ? 2.5 : 2.0) : (t->scale >= 1.5 ? 1.5 : 1.0);
int pad = gemui_scale_px(app, 8);
gemui_fill_round(cr, r, rad, focused ? t->bg_input_focus : t->bg_input);
gemui_stroke_round(cr, r, rad, lw, focused ? t->accent : t->border);
char display[512];
bool empty = (!text || !text[0]);
if (empty) {
snprintf(display, sizeof(display), "%s", placeholder ? placeholder : "");
} else if (mask_bullets) {
size_t len = strlen(text);
if (len > 48) len = 48;
for (size_t i = 0; i < len; i++) display[i] = '*';
if (focused && len + 1 < sizeof(display)) display[len++] = '_';
display[len] = '\0';
} else {
snprintf(display, sizeof(display), "%s%s", text, focused ? "_" : "");
}
if (empty && focused && mask_bullets) {
snprintf(display, sizeof(display), "%s", placeholder ? placeholder : "_");
}
gemui_draw_text(cr, t, (gemui_rect_t){r.x + pad, r.y + 1, r.w - pad * 2, r.h - 2},
display, 0, false, GEMUI_ALIGN_LEFT, empty ? t->fg_muted : t->fg_bright);
if (hit_id >= 0) {
gemui_hit_add(app, r, hit_id, hit_val);
}
}
void gemui_draw_toast(gemui_app_t *app, cairo_t *cr) {
if (!app || !app->toast_msg[0]) return;
const gemui_theme_t *t = &app->theme;
int tw = gemui_scale_px(app, 420);
int max_w = app->w - gemui_scale_px(app, 40);
if (tw > max_w) tw = max_w;
int th = gemui_scale_px(app, 36);
int ty = app->h - th - gemui_scale_px(app, 18);
gemui_rect_t r = {(app->w - tw) / 2, ty, tw, th};
double rad = (double)gemui_scale_px(app, 6);
gemui_fill_round(cr, r, rad, t->bg_toast);
gemui_stroke_round(cr, r, rad, t->scale >= 1.5 ? 2.0 : 1.5, t->accent);
int pad = gemui_scale_px(app, 10);
gemui_draw_text(cr, t, (gemui_rect_t){r.x + pad, r.y + 2, r.w - pad * 2, r.h - 4},
app->toast_msg, -1, true, GEMUI_ALIGN_CENTER, t->fg_bright);
}
int gemui_unix_cmd(const char *sock_path, const char *cmd, char *resp, size_t resp_sz) {
if (!sock_path || !cmd) return -1;
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) return -1;
struct timeval tv = {1, 0};
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", sock_path);
if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
close(fd);
return -1;
}
size_t len = strlen(cmd);
if (send(fd, cmd, len, MSG_NOSIGNAL) < 0 ||
((len == 0 || cmd[len - 1] != '\n') ? send(fd, "\n", 1, MSG_NOSIGNAL) < 0 : 0)) {
close(fd);
return -1;
}
shutdown(fd, SHUT_WR);
if (resp && resp_sz > 0) {
size_t off = 0;
while (off + 1 < resp_sz) {
ssize_t n = recv(fd, resp + off, resp_sz - 1 - off, 0);
if (n <= 0) break;
off += (size_t)n;
}
resp[off] = '\0';
} else {
char sink[64];
while (recv(fd, sink, sizeof(sink), 0) > 0) {}
}
close(fd);
return 0;
}
int gemui_read_file_line(const char *path, char *buf, size_t sz) {
if (!path || !buf || sz == 0) return -1;
FILE *f = fopen(path, "r");
if (!f) return -1;
if (!fgets(buf, (int)sz, f)) {
fclose(f);
return -1;
}
fclose(f);
size_t n = strlen(buf);
while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) {
buf[--n] = '\0';
}
return 0;
}
int gemui_run_cmd_timeout(const char *const argv[], char *out, size_t out_sz, int timeout_ms) {
return anode_run_cmd_timeout(argv, out, out_sz, timeout_ms);
}
int gemui_run_cmd_capture(const char *const argv[], char *out, size_t out_sz) {
return anode_run_cmd_timeout(argv, out, out_sz, 2500);
}
int gemui_spawn_detached(const char *const argv[]) {
return anode_spawn_detached(argv);
}
void gemui_utf8_pop_char(char *buf) {
if (!buf) return;
size_t len = strlen(buf);
while (len > 0) {
len--;
unsigned char ch = (unsigned char)buf[len];
buf[len] = '\0';
if ((ch & 0xc0) != 0x80) break;
}
}