SwAS git · main
SwAS - app switcher for sway (SVG/PNG icons, themeable)
C 97.9% Markdown 1.4%git clone https://git.christianimmanuel.de/sway/SwAS.gitwget https://git.christianimmanuel.de/sway/SwAS/archive/SwAS.tar.gzRemove SDL dep
Makefile | 43 +-- README.md | 28 +- commit_message.txt | 41 ++- config.example | 2 +- sw_draw.h | 984 ++++++++++++++++++++++++++++++++++++++++++++++++++ sw_keymap.h | 1000 ++++++++++++++++++++++++++++++++++++++++++++++++++ sw_wl.h | 1021 ++++++++++++++++++++++++++++++++++++++++++++++++++++ swas.c | 540 +++++++++++---------------- 8 files changed, 3279 insertions(+), 380 deletions(-) diff --git a/Makefile b/Makefile index d43c2e0..7b4b22d 100644 --- a/Makefile +++ b/Makefile @@ -1,24 +1,20 @@ # swas — Makefile # -# make build (SDL3 linked dynamically, via pkg-config) -> ./swas -# make static build with SDL3 baked in (no libSDL3.so needed at runtime) +# make build -> ./swas # make strict build with -Wall -Wextra (for hacking on it) # make run build and run -# make install install to $(PREFIX)/bin (default: /usr) +# make install install to $(PREFIX)/bin (default: /usr) # the example goes to $(PREFIX)/share/swas # make config write a default config to ~/.config/swas/config # make link symlink ~/.config/swas/config at the installed example # make uninstall # make clean # -# Requires: a C compiler, pkg-config, and SDL3 dev files. -# `make static` additionally needs the SDL3 *static* library (libSDL3.a). Distro -# packages don't always ship it; if it's missing, build SDL from source with -# -DSDL_STATIC=ON (see README) or just use the default dynamic `make`. +# Requires: a C compiler and the libwayland-client dev files. Nothing else — +# fonts, icons and SVGs are decoded in-tree, and the window is a Wayland +# layer-shell surface drawn by swas itself. # -# Note: even a "static" build still loads your system's Wayland/X11 libraries at -# runtime (that's how SDL finds a display) — it removes the SDL install -# requirement, not every runtime dependency. +# Written/modified by: Claude Opus 4.1, Claude Sonnet 4.5, Claude Opus 5 CC ?= cc PKG_CONFIG ?= pkg-config @@ -30,32 +26,23 @@ datadir ?= $(PREFIX)/share/swas BUILD := $(shell md5sum swas.c 2>/dev/null | cut -c1-8) SRC := swas.c BIN := swas +HDRS := stb_truetype.h stb_image.h nanosvg.h nanosvgrast.h \ + sw_theme.h sw_draw.h sw_wl.h sw_keymap.h -SDL_CFLAGS := $(shell $(PKG_CONFIG) --cflags sdl3) -SDL_LIBS := $(shell $(PKG_CONFIG) --libs sdl3) -SDL_LDPATH := $(shell $(PKG_CONFIG) --libs-only-L sdl3) -# transitive libs SDL needs when it is linked statically, minus SDL itself: -SDL_STATIC_EXTRA := $(filter-out -lSDL3,$(shell $(PKG_CONFIG) --static --libs sdl3)) +WL_CFLAGS := $(shell $(PKG_CONFIG) --cflags wayland-client 2>/dev/null) +WL_LIBS := $(shell $(PKG_CONFIG) --libs wayland-client 2>/dev/null || echo -lwayland-client) -.PHONY: all static strict run install config link uninstall clean +.PHONY: all strict run install config link uninstall clean all: $(BIN) -$(BIN): $(SRC) stb_truetype.h stb_image.h sw_theme.h - $(CC) $(CFLAGS) -DSWAS_BUILD='"$(BUILD)"' $(SDL_CFLAGS) $(SRC) -o $(BIN) $(SDL_LIBS) -lm +$(BIN): $(SRC) $(HDRS) + $(CC) $(CFLAGS) -DSWAS_BUILD='"$(BUILD)"' $(WL_CFLAGS) $(SRC) -o $(BIN) $(WL_LIBS) -lm @./$(BIN) --version -# Link libSDL3.a statically while keeping system libs dynamic. -static: $(SRC) stb_truetype.h stb_image.h sw_theme.h - $(CC) $(CFLAGS) -DSWAS_BUILD='"$(BUILD)"' $(SDL_CFLAGS) $(SRC) -o $(BIN) \ - $(SDL_LDPATH) -Wl,-Bstatic -lSDL3 -Wl,-Bdynamic $(SDL_STATIC_EXTRA) -lm - @echo "built ./$(BIN) with SDL baked in:"; \ - ldd $(BIN) | grep -qi SDL3 && echo " (warning: still links libSDL3.so)" \ - || echo " no libSDL3.so dependency." - -strict: $(SRC) stb_truetype.h stb_image.h sw_theme.h +strict: $(SRC) $(HDRS) $(CC) -O2 -Wall -Wextra -Wno-misleading-indentation -DSWAS_BUILD='"$(BUILD)"' \ - $(SDL_CFLAGS) $(SRC) -o $(BIN) $(SDL_LIBS) -lm + $(WL_CFLAGS) $(SRC) -o $(BIN) $(WL_LIBS) -lm run: all ./$(BIN) diff --git a/README.md b/README.md index 1ad10e3..43a3f1e 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,10 @@ # swas -Sway App Selector: a radial app launcher, drawn with SDL3. Apps sit in wide slots across the top -arc; point at one and click, or type to filter. Works on Wayland and X11. +Sway App Selector: a radial app launcher for Wayland. Apps sit in wide slots across the top +arc; point at one and click, or type to filter. + +No toolkit. swas draws itself on a layer-shell surface and links only +`libwayland-client`.  @@ -12,21 +15,18 @@ arc; point at one and click, or type to filter. Works on Wayland and X11. Debian trixie and newer: ```sh -sudo apt install build-essential pkg-config libsdl3-dev +sudo apt install build-essential pkg-config libwayland-dev make sudo make install # /usr/bin, examples in /usr/share/swas make config # optional: write a default config to ~/.config/swas/config make link # or: config -> the installed example, kept in sync ``` -`make static` bakes SDL3 into the binary, so it runs without `libSDL3.so`. It -needs `libSDL3.a`, which distro packages do not always ship. - -On bookworm the SDL3 package does not exist yet; build SDL 3.2+ from source and -set `PKG_CONFIG_PATH`. - Needs any TTF font. Icons need a `.desktop` file and an icon theme. +Your compositor must support `wlr-layer-shell` — sway, Hyprland, river, +labwc and the other wlroots compositors do. + ## Use ``` @@ -211,7 +211,6 @@ knowing: | `arc` | degrees of the ring used for apps; the rest is the paging zone | | `radius`, `y_offset` | wheel size and where it sits | | `ui_scale` | scales all text at once | -| `ssaa` | supersampling 1–4 | | `icons`, `icon_px` | `.desktop` icons and their size | | `sort` | `recent` or `alpha` | | `include`, `exclude`, `dirs` | which apps show, and in what order | @@ -246,8 +245,13 @@ that. - The window is mapped and focused before the `.desktop` scan and the font load, so anything typed while it starts is queued by the compositor instead of being lost. -- "Fullscreen" is a borderless window the size of the display, not exclusive - fullscreen: that would make the surface opaque and flicker the mode on close. +- The window is a layer-shell overlay, so it covers the screen without + becoming a real fullscreen window: no mode flicker, and sway keeps the + windows underneath exactly as they were. +- Keyboard layout comes from the compositor's own keymap, so dead keys, AltGr + and non-US layouts type correctly. There is no `libxkbcommon` to install. +- `ssaa` is accepted and ignored. Every shape is antialiased as it is drawn, + so there is nothing left to supersample. - Apps whose `.desktop` file says `Terminal=true` are run inside `terminal=`. - SVG icons are rasterised at the size they are drawn, so they stay sharp at any `icon_px`. diff --git a/commit_message.txt b/commit_message.txt index df02079..fcf6eea 100644 --- a/commit_message.txt +++ b/commit_message.txt @@ -1,17 +1,30 @@ -swas: scale an oversized SVG icon instead of cropping it +shared: bold faces, offscreen canvases and a PNG writer -Icons were rasterised to the width and height the SVG declares, so anything -drawn outside that box was simply not drawn. The box is now the declared -canvas and the shapes' own bounds together: an icon with deliberate padding -keeps it, one whose art overflows its own width/height is scaled down rather -than losing an edge. Stroke width is counted in, since a stroke sits astride -its path. +What swov needed from the layer that swas and swbr already use, added +without changing anything the two of them do. -Checked against a 48x48 icon whose art reaches 88x88: ink running into the -bottom and right edges drops from 54 pixels to 9, and well-formed icons -rasterise byte for byte as before. +sw_draw.h + - sw_fonts_bold() / sw_font_bold(): a second face for headings. Without + one the regular face is emboldened by drawing each glyph twice, a + third of a pixel apart, so bold still reads as bold on a desktop that + ships only one weight. The cache is keyed on size and weight together. + - sw_canvas_new/free/clear and sw_blit_canvas(): an offscreen canvas + that can be scaled, tinted and faded onto another. Shrinking box- + filters; a 1:1 aligned blit is a straight premultiplied-over copy. + This is what swov's backdrop fade and its full -> half -> small blur + chain are made of. + - sw_write_png(): one canvas to a PNG, stored (uncompressed) deflate, + for swov --shot. No zlib, a big file, which is fine for one frame. + - sw_text_width_n() and sw_font_descent(), for measuring part of a + string and centring a line in a box. -Also in this release: dmenu's own flags (-l N, -p PROMPT, -i, ...) now switch -on dmenu mode and are otherwise ignored, so MENU=swas works unchanged in -scripts written for dmenu or bemenu. Blank lines in the input are skipped -rather than becoming empty slices on the wheel. +sw_wl.h + - SwEvent.code carries the raw evdev keycode, so a program can read a + key by its place on the board rather than by what it types. swov's + number row needs that on a layout where the digits take shift. + - sw_win_create() accepts a NULL SwApp: a program that drives its own + frames with sw_win_begin/end has no callbacks to give, and passing + NULL used to dereference it. + +Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> +Claude-Session: https://claude.ai/code/session_01SuAfijAAYjLpcVwhCq3AF4 diff --git a/config.example b/config.example index 3bb176b..fd076cb 100644 --- a/config.example +++ b/config.example @@ -21,7 +21,7 @@ page_ms=110 # base ms per paged step at the SLOW end. Bigger = calmer # zone, fast toward straight-down. # --- rendering --- -ssaa=2 # full-scene supersampling 1..4 (smooths edges). alias: aa +ssaa=2 # ignored: every shape is antialiased as it is drawn. alias: aa animate=1 # subtle settle animation when the search results change anim_ms=90 # its duration (0 or animate=0 to turn it off) icons=1 # show .desktop icons if found (PNG/SVG/JPG/BMP) diff --git a/sw_draw.h b/sw_draw.h new file mode 100644 index 0000000..f9e133e --- /dev/null +++ b/sw_draw.h @@ -0,0 +1,984 @@ +/* sw_draw.h — a software canvas. ARGB8888, premultiplied, which is what + * wl_shm wants. Rounded rectangles come out of a signed distance field, text + * out of stb_truetype with a per-size glyph cache, images out of a box filter. + * + * No GPU and no windowing system: a Canvas is a pixel buffer and a clip + * rectangle, so a whole frame can be drawn and then inspected in a test with + * no compositor anywhere near it. That is the point of doing it this way, as + * much as the short link line. + * + * Lifted out of swbr, which has drawn itself like this all along. + * + * Define SW_DRAW_IMPL in exactly one translation unit before including this. + * stb_truetype.h must be on the include path; this header includes it, and + * emits its implementation unless SW_DRAW_NO_STB_IMPL says otherwise (define + * that when something else in the program already does). + * + * Written/modified by: Claude Opus 5 + */ +#ifndef SW_DRAW_H +#define SW_DRAW_H + +#include <stdbool.h> +#include <stddef.h> +#include <stdint.h> + +/* stb_truetype.h has no re-include guard of its own, so only pull it in when + * the program has not already done so. */ +#ifndef __STB_INCLUDE_STB_TRUETYPE_H__ +#include "stb_truetype.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------------------------------------------------------ types */ + +typedef struct { uint8_t r, g, b, a; } Col; + +typedef struct { + uint32_t *px; /* w*h, ARGB8888 premultiplied */ + int w, h; + int cx0, cy0, cx1, cy1; /* clip rectangle */ +} Canvas; + +typedef struct { + unsigned char *data; + stbtt_fontinfo info; + bool ok; +} FontFile; + +typedef struct { + unsigned cp; /* 0 = free slot */ + int w, h, x0, y0; + float adv; + unsigned char *bmp; +} Glyph; + +typedef struct { + int px; + float sc_pri, sc_alt, sc_bold, ascent, lineh; + Glyph *tab; + int cap, n; + bool used; + bool bold; /* ask the bold face for glyphs */ + bool synth; /* no bold face: embolden by drawing twice */ +} Font; + +/* An image to blit: straight RGBA bytes, as nanosvg and stb_image hand them + * over, not premultiplied. */ +typedef struct { + const unsigned char *rgba; + int w, h, stride; +} Image; + +#define SW_WHITE ((Col){ 255, 255, 255, 255 }) + +/* -------------------------------------------------------------- interface */ + +void sw_parse_color(const char *s, Col *out); +Col sw_col_alpha(Col c, float f); +Col sw_col_mix(Col a, Col b, float t); + +void sw_fonts_init(const char *primary, const char *fallback); +void sw_fonts_free(void); +Font *sw_font(int px); /* cached per pixel size */ +/* An optional bold face. Without one, sw_font_bold emboldens the regular + face by drawing each glyph twice, a third of a pixel apart. */ +void sw_fonts_bold(const char *path); +Font *sw_font_bold(int px); +float sw_text_width(Font *f, const char *s); + +void sw_canvas_clip(Canvas *cv, int x0, int y0, int x1, int y1); +void sw_canvas_clip_all(Canvas *cv); +void sw_canvas_fill(Canvas *cv, Col c); /* the whole clip rectangle */ + +void sw_fill_rect(Canvas *cv, float x, float y, float w, float h, Col c); +void sw_fill_round(Canvas *cv, float x, float y, float w, float h, + float rtl, float rtr, float rbr, float rbl, Col c); +void sw_stroke_round(Canvas *cv, float x, float y, float w, float h, + float rtl, float rtr, float rbr, float rbl, + float t, Col c); +void sw_fill_tri(Canvas *cv, float x0, float y0, float x1, float y1, + float x2, float y2, Col c); +void sw_fill_circle(Canvas *cv, float cx, float cy, float rad, Col c); +void sw_fill_sector(Canvas *cv, float cx, float cy, float r0, float r1, + float a0, float a1, Col c); +void sw_blit(Canvas *cv, Image img, float x, float y, float w, float h, + float alpha); +void sw_text(Canvas *cv, Font *f, float x, float baseline, Col c, const char *s); +float sw_text_width_n(Font *f, const char *s, size_t n); +float sw_font_descent(Font *f); /* positive, below the baseline */ + +/* An offscreen canvas, for a frame that is drawn once and then scaled, + faded or blurred as a whole. Same pixel format as a window's canvas. */ +Canvas *sw_canvas_new(int w, int h); +void sw_canvas_free(Canvas *cv); +void sw_canvas_clear(Canvas *cv); /* to nothing, ignoring the clip */ +/* Scale `src` into `dst`, box-filtered when it shrinks. `tint` multiplies the + colour (use SW_WHITE for none); `alpha` the whole thing. */ +void sw_blit_canvas(Canvas *dst, const Canvas *src, float x, float y, + float w, float h, Col tint, float alpha); + +/* Write a canvas out as a PNG. Stored (uncompressed) deflate: no zlib, and + a big file, which is fine for the one frame a --shot asks for. */ +bool sw_write_png(const char *path, const Canvas *cv); + +#ifdef __cplusplus +} +#endif +#endif /* SW_DRAW_H */ + +/* ===================================================================== */ +#ifdef SW_DRAW_IMPL +#ifndef SW_DRAW_IMPL_ONCE +#define SW_DRAW_IMPL_ONCE + +#include <ctype.h> +#include <math.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +/* One shell call, to ask fontconfig where a family lives. Under -std=c11 the + * libc headers hide popen, and a feature macro set this late would come after + * the program's own includes and do nothing — so declare the two directly. + * Both are POSIX; this is the same declaration unistd would give. */ +#if defined(__STRICT_ANSI__) +FILE *popen(const char *, const char *); +int pclose(FILE *); +#endif + +static float sw_clampf(float v, float lo, float hi) { return v < lo ? lo : (v > hi ? hi : v); } +static int sw_clampi(int v, int lo, int hi) { return v < lo ? lo : (v > hi ? hi : v); } + +void sw_parse_color(const char *s, Col *out) +{ + if (!s || !out) return; + if (*s == '#') s++; + unsigned r, g, b, a = 255; + if (strlen(s) >= 8 && sscanf(s, "%2x%2x%2x%2x", &r, &g, &b, &a) == 4) { } + else if (sscanf(s, "%2x%2x%2x", &r, &g, &b) == 3) { } + else return; + out->r = (uint8_t)r; out->g = (uint8_t)g; out->b = (uint8_t)b; out->a = (uint8_t)a; +} + +Col sw_col_alpha(Col c, float f) +{ + c.a = (uint8_t)sw_clampf((float)c.a * f, 0.0f, 255.0f); + return c; +} + +Col sw_col_mix(Col a, Col b, float t) +{ + t = sw_clampf(t, 0.0f, 1.0f); + Col o; + o.r = (uint8_t)((float)a.r + ((float)b.r - (float)a.r) * t); + o.g = (uint8_t)((float)a.g + ((float)b.g - (float)a.g) * t); + o.b = (uint8_t)((float)a.b + ((float)b.b - (float)a.b) * t); + o.a = (uint8_t)((float)a.a + ((float)b.a - (float)a.a) * t); + return o; +} +#ifndef SW_PATHMAX +#define SW_PATHMAX 4096 +#endif + +/* ------------------------------------------------------------------ fonts */ +/* stb_truetype, rasterised straight into our own ARGB buffer. Glyphs are + * cached per size on first use, so any codepoint works — a status line is + * full of box drawing characters and symbols. */ + +static FontFile sw_font_pri, sw_font_alt, sw_font_bld; + +#define SW_FONT_CACHE 12 +static Font sw_font_cache[SW_FONT_CACHE]; + +static void *sw_xmalloc(size_t n) +{ + void *p = malloc(n); + if (!p) { fprintf(stderr, "sw_draw: out of memory\n"); abort(); } + return p; +} + +static bool sw_file_exists(const char *p) +{ + return p && *p && access(p, R_OK) == 0; +} + +static bool sw_font_file_load(FontFile *ff, const char *path) +{ + memset(ff, 0, sizeof(*ff)); + FILE *f = fopen(path, "rb"); + if (!f) return false; + fseek(f, 0, SEEK_END); + long sz = ftell(f); + fseek(f, 0, SEEK_SET); + if (sz <= 0) { fclose(f); return false; } + ff->data = (unsigned char *)sw_xmalloc((size_t)sz); + if (fread(ff->data, 1, (size_t)sz, f) != (size_t)sz) { + fclose(f); free(ff->data); ff->data = NULL; return false; + } + fclose(f); + if (!stbtt_InitFont(&ff->info, ff->data, stbtt_GetFontOffsetForIndex(ff->data, 0))) { + free(ff->data); ff->data = NULL; return false; + } + ff->ok = true; + return true; +} + +static bool sw_try_font_paths(char *out, size_t n) +{ + const char *cand[] = { + "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", + "/usr/share/fonts/dejavu/DejaVuSansMono.ttf", + "/usr/share/fonts/TTF/DejaVuSansMono.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf", + "/usr/share/fonts/noto/NotoSansMono-Regular.ttf", + "/usr/share/fonts/truetype/freefont/FreeMono.ttf", NULL + }; + for (int i = 0; cand[i]; ++i) + if (sw_file_exists(cand[i])) { snprintf(out, n, "%s", cand[i]); return true; } + return false; +} +static bool sw_fc_match(const char *pattern, char *out, size_t n) +{ + if (!pattern || !*pattern) pattern = "monospace"; + char safe[256]; + size_t j = 0; + for (size_t i = 0; pattern[i] && j < sizeof(safe) - 1; ++i) { + char ch = pattern[i]; + if (ch == '"' || ch == '`' || ch == '$' || ch == '\\' || ch == ';' || + ch == '|' || ch == '&' || ch == '\n' || ch == '\r') continue; + safe[j++] = ch; + } + safe[j] = 0; + char cmd[512]; + snprintf(cmd, sizeof(cmd), "fc-match --format=%%{file} \"%s\" 2>/dev/null", safe); + FILE *p = popen(cmd, "r"); + if (!p) return false; + char buf[SW_PATHMAX]; + size_t r = fread(buf, 1, sizeof(buf) - 1, p); + buf[r] = 0; + pclose(p); + char *s = buf; + while (*s == ' ' || *s == '\n' || *s == '\t') s++; + char *e = s + strlen(s); + while (e > s && (e[-1] == '\n' || e[-1] == '\r' || + e[-1] == ' ' || e[-1] == '\t')) *--e = 0; + if (*s && sw_file_exists(s)) { snprintf(out, n, "%s", s); return true; } + return false; +} + +/* The font cache is keyed on pixel size, so a program can ask for text at any + * size and the glyphs for it are rasterised once. */ +void sw_fonts_init(const char *primary, const char *fallback) +{ + char path[SW_PATHMAX] = ""; + if (primary && *primary) { + snprintf(path, sizeof(path), "%s", primary); + if (!sw_file_exists(path)) sw_fc_match(primary, path, sizeof(path)); + } + if (!sw_file_exists(path)) sw_fc_match("monospace", path, sizeof(path)); + if (!sw_file_exists(path)) sw_try_font_paths(path, sizeof(path)); + if (*path) sw_font_file_load(&sw_font_pri, path); + + char alt[SW_PATHMAX] = ""; + if (fallback && *fallback) { + snprintf(alt, sizeof(alt), "%s", fallback); + if (!sw_file_exists(alt)) sw_fc_match(fallback, alt, sizeof(alt)); + } else if (!sw_fc_match("Noto Sans Symbols 2", alt, sizeof(alt))) { + /* a symbol font if the desktop has one: it covers glyphs a mono font + * usually lacks. Silently skipped when absent. */ + sw_fc_match("Noto Sans Symbols2", alt, sizeof(alt)); + } + if (sw_file_exists(alt) && strcmp(alt, path)) sw_font_file_load(&sw_font_alt, alt); +} + +void sw_fonts_bold(const char *path) +{ + char p[SW_PATHMAX] = ""; + if (!path || !*path) return; + snprintf(p, sizeof(p), "%s", path); + if (!sw_file_exists(p) && !sw_fc_match(path, p, sizeof(p))) return; + if (!sw_file_exists(p)) return; + sw_font_file_load(&sw_font_bld, p); +} + +void sw_fonts_free(void) +{ + for (int i = 0; i < SW_FONT_CACHE; ++i) { + Font *f = &sw_font_cache[i]; + for (int j = 0; j < f->cap; ++j) free(f->tab[j].bmp); + free(f->tab); + f->tab = NULL; + f->cap = f->n = 0; + f->used = false; + } + free(sw_font_pri.data); + free(sw_font_alt.data); + free(sw_font_bld.data); + memset(&sw_font_pri, 0, sizeof(sw_font_pri)); + memset(&sw_font_alt, 0, sizeof(sw_font_alt)); + memset(&sw_font_bld, 0, sizeof(sw_font_bld)); +} + +static void sw_glyph_tab_init(Font *f, int cap) +{ + f->cap = cap; + f->n = 0; + f->tab = (Glyph *)sw_xmalloc((size_t)cap * sizeof(Glyph)); + memset(f->tab, 0, (size_t)cap * sizeof(Glyph)); +} + +static Glyph *glyph_slot(Font *f, unsigned cp) +{ + unsigned h = cp * 2654435761u; + for (;;) { + unsigned i = h & (unsigned)(f->cap - 1); + for (int probe = 0; probe < f->cap; ++probe) { + Glyph *g = &f->tab[(i + (unsigned)probe) & (unsigned)(f->cap - 1)]; + if (g->cp == cp) return g; + if (g->cp == 0) return g; + } + /* full: grow and rehash */ + Glyph *old = f->tab; + int oldcap = f->cap; + sw_glyph_tab_init(f, oldcap * 2); + for (int k = 0; k < oldcap; ++k) { + if (!old[k].cp) continue; + Glyph *g = glyph_slot(f, old[k].cp); + *g = old[k]; + f->n++; + } + free(old); + } +} + +static Glyph *sw_glyph_get(Font *f, unsigned cp) +{ + Glyph *g = glyph_slot(f, cp); + if (g->cp == cp) return g; + + FontFile *ff = (f->bold && sw_font_bld.ok) ? &sw_font_bld : &sw_font_pri; + float sc = (f->bold && sw_font_bld.ok) ? f->sc_bold : f->sc_pri; + int gi = ff->ok ? stbtt_FindGlyphIndex(&ff->info, (int)cp) : 0; + if (!gi && ff != &sw_font_pri && sw_font_pri.ok) { + int gi0 = stbtt_FindGlyphIndex(&sw_font_pri.info, (int)cp); + if (gi0) { ff = &sw_font_pri; sc = f->sc_pri; gi = gi0; } + } + if (!gi && sw_font_alt.ok) { + int gi2 = stbtt_FindGlyphIndex(&sw_font_alt.info, (int)cp); + if (gi2) { ff = &sw_font_alt; sc = f->sc_alt; gi = gi2; } + } + memset(g, 0, sizeof(*g)); + g->cp = cp; + f->n++; + if (!ff->ok || !gi) { + g->adv = (float)f->px * 0.5f; /* missing: leave a blank */ + return g; + } + int aw, lsb; + stbtt_GetGlyphHMetrics(&ff->info, gi, &aw, &lsb); + g->adv = (float)aw * sc; + int x0, y0, x1, y1; + stbtt_GetGlyphBitmapBox(&ff->info, gi, sc, sc, &x0, &y0, &x1, &y1); + int w = x1 - x0, h = y1 - y0; + if (w > 0 && h > 0 && w < 512 && h < 512) { + g->bmp = (unsigned char *)sw_xmalloc((size_t)w * (size_t)h); + stbtt_MakeGlyphBitmap(&ff->info, g->bmp, w, h, w, sc, sc, gi); + g->w = w; g->h = h; g->x0 = x0; g->y0 = y0; + } + return g; +} + +/* One Font per pixel size (and therefore per output scale). */ +static Font *sw_font_get(int px, bool bold) +{ + if (px < 4) px = 4; + for (int i = 0; i < SW_FONT_CACHE; ++i) + if (sw_font_cache[i].used && sw_font_cache[i].px == px && + sw_font_cache[i].bold == bold) return &sw_font_cache[i]; + + int slot = -1; + for (int i = 0; i < SW_FONT_CACHE; ++i) if (!sw_font_cache[i].used) { slot = i; break; } + if (slot < 0) slot = 0; /* recycle the first one */ + Font *f = &sw_font_cache[slot]; + if (f->used) { + for (int k = 0; k < f->cap; ++k) free(f->tab[k].bmp); + free(f->tab); + memset(f, 0, sizeof(*f)); + } + f->used = true; + f->px = px; + f->bold = bold; + f->synth = bold && !sw_font_bld.ok; + f->sc_pri = sw_font_pri.ok ? stbtt_ScaleForPixelHeight(&sw_font_pri.info, (float)px) : 1.0f; + f->sc_alt = sw_font_alt.ok ? stbtt_ScaleForPixelHeight(&sw_font_alt.info, (float)px) : 1.0f; + f->sc_bold = sw_font_bld.ok ? stbtt_ScaleForPixelHeight(&sw_font_bld.info, (float)px) : 1.0f; + { + FontFile *mf = (bold && sw_font_bld.ok) ? &sw_font_bld : &sw_font_pri; + float msc = (bold && sw_font_bld.ok) ? f->sc_bold : f->sc_pri; + int asc = 0, desc = 0, gap = 0; + if (mf->ok) stbtt_GetFontVMetrics(&mf->info, &asc, &desc, &gap); + f->ascent = (float)asc * msc; + f->lineh = (float)(asc - desc) * msc; + } + if (f->ascent <= 0) { f->ascent = (float)px * 0.8f; f->lineh = (float)px; } + sw_glyph_tab_init(f, 256); + return f; +} + +Font *sw_font(int px) { return sw_font_get(px, false); } +Font *sw_font_bold(int px) { return sw_font_get(px, true); } + +static unsigned sw_utf8_next(const char **p) +{ + const unsigned char *s = (const unsigned char *)*p; + unsigned cp; + int n; + if (s[0] < 0x80) { cp = s[0]; n = 1; } + else if ((s[0] & 0xE0) == 0xC0) { cp = s[0] & 0x1Fu; n = 2; } + else if ((s[0] & 0xF0) == 0xE0) { cp = s[0] & 0x0Fu; n = 3; } + else if ((s[0] & 0xF8) == 0xF0) { cp = s[0] & 0x07u; n = 4; } + else { *p = (const char *)(s + 1); return 0xFFFD; } + for (int i = 1; i < n; ++i) { + if ((s[i] & 0xC0) != 0x80) { n = i; break; } + cp = (cp << 6) | (s[i] & 0x3Fu); + } + *p = (const char *)(s + n); + return cp; +} +float sw_text_width(Font *f, const char *s) +{ + float w = 0; + const char *p = s; + while (*p) { + unsigned cp = sw_utf8_next(&p); + if (cp == 0xFE0F || cp == 0x200D) continue; /* variation selectors */ + w += sw_glyph_get(f, cp)->adv + (f->synth ? 0.35f : 0.0f); + } + return w; +} + +void sw_canvas_clip(Canvas *cv, int x0, int y0, int x1, int y1) +{ + cv->cx0 = sw_clampi(x0, 0, cv->w); + cv->cy0 = sw_clampi(y0, 0, cv->h); + cv->cx1 = sw_clampi(x1, 0, cv->w); + cv->cy1 = sw_clampi(y1, 0, cv->h); +} + +void sw_canvas_clip_all(Canvas *cv) { sw_canvas_clip(cv, 0, 0, cv->w, cv->h); } + +static inline void sw_blend(Canvas *cv, int x, int y, Col c, float cov) +{ + if (x < cv->cx0 || x >= cv->cx1 || y < cv->cy0 || y >= cv->cy1) return; + float a = (float)c.a / 255.0f * cov; + if (a <= 0.0f) return; + uint32_t d = cv->px[y * cv->w + x]; + float da = (float)((d >> 24) & 0xff) / 255.0f; + float dr = (float)((d >> 16) & 0xff) / 255.0f; + float dg = (float)((d >> 8) & 0xff) / 255.0f; + float db = (float)(d & 0xff) / 255.0f; + float sr = (float)c.r / 255.0f * a; + float sg = (float)c.g / 255.0f * a; + float sb = (float)c.b / 255.0f * a; + float ia = 1.0f - a; + float orr = sr + dr * ia, og = sg + dg * ia, ob = sb + db * ia, oa = a + da * ia; + cv->px[y * cv->w + x] = + ((uint32_t)(orr * 255.0f + 0.5f) << 16) | + ((uint32_t)(og * 255.0f + 0.5f) << 8) | + ((uint32_t)(ob * 255.0f + 0.5f)) | + ((uint32_t)(oa * 255.0f + 0.5f) << 24); +} + +void sw_fill_rect(Canvas *cv, float x, float y, float w, float h, Col c) +{ + if (w <= 0 || h <= 0 || !c.a) return; + int x0 = (int)floorf(x), y0 = (int)floorf(y); + int x1 = (int)ceilf(x + w), y1 = (int)ceilf(y + h); + for (int yy = y0; yy < y1; ++yy) + for (int xx = x0; xx < x1; ++xx) { + float cxs = sw_clampf(x + w, (float)xx, (float)xx + 1) - sw_clampf(x, (float)xx, (float)xx + 1); + float cys = sw_clampf(y + h, (float)yy, (float)yy + 1) - sw_clampf(y, (float)yy, (float)yy + 1); + sw_blend(cv, xx, yy, c, cxs * cys); + } +} + +/* Rounded box with a radius per corner (tl, tr, br, bl), anti-aliased through + * the usual signed distance trick. A corner radius of 0 is a square corner — + * that is how the bar stays flush with the screen edge. */ +void sw_fill_round(Canvas *cv, float x, float y, float w, float h, + float rtl, float rtr, float rbr, float rbl, Col c) +{ + if (w <= 0 || h <= 0 || !c.a) return; + float hw = w * 0.5f, hh = h * 0.5f; + float ccx = x + hw, ccy = y + hh; + float cap = fminf(hw, hh); + rtl = sw_clampf(rtl, 0, cap); rtr = sw_clampf(rtr, 0, cap); + rbr = sw_clampf(rbr, 0, cap); rbl = sw_clampf(rbl, 0, cap); + + int x0 = (int)floorf(x) - 1, y0 = (int)floorf(y) - 1; + int x1 = (int)ceilf(x + w) + 1, y1 = (int)ceilf(y + h) + 1; + for (int yy = y0; yy < y1; ++yy) { + if (yy < cv->cy0 || yy >= cv->cy1) continue; + for (int xx = x0; xx < x1; ++xx) { + if (xx < cv->cx0 || xx >= cv->cx1) continue; + float px = (float)xx + 0.5f - ccx, py = (float)yy + 0.5f - ccy; + float r = px < 0 ? (py < 0 ? rtl : rbl) : (py < 0 ? rtr : rbr); + float qx = fabsf(px) - (hw - r), qy = fabsf(py) - (hh - r); + float mx = fmaxf(qx, 0.0f), my = fmaxf(qy, 0.0f); + float d = sqrtf(mx * mx + my * my) + fminf(fmaxf(qx, qy), 0.0f) - r; + float cov = sw_clampf(0.5f - d, 0.0f, 1.0f); + if (cov > 0) sw_blend(cv, xx, yy, c, cov); + } + } +} + +/* The same distance field kept to a ring: an outline that follows the corner + * radius and stays inside the box, so a button with no fill still has an edge. */ +void sw_stroke_round(Canvas *cv, float x, float y, float w, float h, + float rtl, float rtr, float rbr, float rbl, + float t, Col c) +{ + if (w <= 0 || h <= 0 || t <= 0 || !c.a) return; + float hw = w * 0.5f, hh = h * 0.5f; + float ccx = x + hw, ccy = y + hh; + float cap = fminf(hw, hh); + rtl = sw_clampf(rtl, 0, cap); rtr = sw_clampf(rtr, 0, cap); + rbr = sw_clampf(rbr, 0, cap); rbl = sw_clampf(rbl, 0, cap); + + int x0 = (int)floorf(x) - 1, y0 = (int)floorf(y) - 1; + int x1 = (int)ceilf(x + w) + 1, y1 = (int)ceilf(y + h) + 1; + for (int yy = y0; yy < y1; ++yy) { + if (yy < cv->cy0 || yy >= cv->cy1) continue; + for (int xx = x0; xx < x1; ++xx) { + if (xx < cv->cx0 || xx >= cv->cx1) continue; + float px = (float)xx + 0.5f - ccx, py = (float)yy + 0.5f - ccy; + float r = px < 0 ? (py < 0 ? rtl : rbl) : (py < 0 ? rtr : rbr); + float qx = fabsf(px) - (hw - r), qy = fabsf(py) - (hh - r); + float mx = fmaxf(qx, 0.0f), my = fmaxf(qy, 0.0f); + float d = sqrtf(mx * mx + my * my) + fminf(fmaxf(qx, qy), 0.0f) - r; + float cov = sw_clampf(0.5f - fabsf(d + t * 0.5f) + t * 0.5f, 0.0f, 1.0f); + if (cov > 0) sw_blend(cv, xx, yy, c, cov); + } + } +} + +void sw_text(Canvas *cv, Font *f, float x, float baseline, Col c, const char *s) +{ + const char *p = s; + float pen = x; + while (*p) { + unsigned cp = sw_utf8_next(&p); + if (cp == 0xFE0F || cp == 0x200D) continue; + Glyph *g = sw_glyph_get(f, cp); + if (g->bmp) { + int gx = (int)lroundf(pen) + g->x0; + int gy = (int)lroundf(baseline) + g->y0; + int pass, passes = f->synth ? 2 : 1; + for (pass = 0; pass < passes; ++pass) { + for (int yy = 0; yy < g->h; ++yy) { + int ty = gy + yy; + if (ty < cv->cy0 || ty >= cv->cy1) continue; + const unsigned char *row = g->bmp + (size_t)yy * (size_t)g->w; + for (int xx = 0; xx < g->w; ++xx) { + unsigned char a = row[xx]; + if (a) sw_blend(cv, gx + pass + xx, ty, c, (float)a / 255.0f); + } + } + } + } + pen += g->adv + (f->synth ? 0.35f : 0.0f); + } +} + + +void sw_canvas_fill(Canvas *cv, Col c) +{ + sw_fill_rect(cv, (float)cv->cx0, (float)cv->cy0, + (float)(cv->cx1 - cv->cx0), (float)(cv->cy1 - cv->cy0), c); +} + +/* A filled triangle, by half-plane tests on a 2x2 grid per pixel. swbr never + * needed one; swas draws its wheel slices and its chevrons out of them. */ +void sw_fill_tri(Canvas *cv, float x0, float y0, float x1, float y1, + float x2, float y2, Col c) +{ + if (!c.a) return; + float minx = fminf(x0, fminf(x1, x2)), maxx = fmaxf(x0, fmaxf(x1, x2)); + float miny = fminf(y0, fminf(y1, y2)), maxy = fmaxf(y0, fmaxf(y1, y2)); + int ix0 = sw_clampi((int)floorf(minx), cv->cx0, cv->cx1); + int iy0 = sw_clampi((int)floorf(miny), cv->cy0, cv->cy1); + int ix1 = sw_clampi((int)ceilf(maxx) + 1, cv->cx0, cv->cx1); + int iy1 = sw_clampi((int)ceilf(maxy) + 1, cv->cy0, cv->cy1); + + float d = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0); + if (fabsf(d) < 1e-6f) return; /* degenerate */ + float inv = 1.0f / d; + + for (int y = iy0; y < iy1; ++y) { + for (int x = ix0; x < ix1; ++x) { + int hits = 0; + for (int sy = 0; sy < 2; ++sy) { + for (int sx = 0; sx < 2; ++sx) { + float px = (float)x + 0.25f + 0.5f * (float)sx; + float py = (float)y + 0.25f + 0.5f * (float)sy; + float l0 = ((x1 - px) * (y2 - py) - (x2 - px) * (y1 - py)) * inv; + float l1 = ((x2 - px) * (y0 - py) - (x0 - px) * (y2 - py)) * inv; + float l2 = 1.0f - l0 - l1; + if (l0 >= 0.0f && l1 >= 0.0f && l2 >= 0.0f) hits++; + } + } + if (hits) sw_blend(cv, x, y, c, (float)hits * 0.25f); + } + } +} + +void sw_fill_circle(Canvas *cv, float cx, float cy, float rad, Col c) +{ + sw_fill_round(cv, cx - rad, cy - rad, rad * 2.0f, rad * 2.0f, + rad, rad, rad, rad, c); +} + +/* A wedge of an annulus: the slice shape a radial menu is made of. Tested + * per pixel against the two radii and the two angles, four samples a pixel so + * the long curved edges do not stair-step. A0 may exceed a1 going the other + * way round; the wedge is always drawn the short way from a0 to a1. */ +void sw_fill_sector(Canvas *cv, float cx, float cy, float r0, float r1, + float a0, float a1, Col c) +{ + if (!c.a || r1 <= 0.0f || r1 <= r0) return; + int ix0 = sw_clampi((int)floorf(cx - r1) - 1, cv->cx0, cv->cx1); + int iy0 = sw_clampi((int)floorf(cy - r1) - 1, cv->cy0, cv->cy1); + int ix1 = sw_clampi((int)ceilf(cx + r1) + 1, cv->cx0, cv->cx1); + int iy1 = sw_clampi((int)ceilf(cy + r1) + 1, cv->cy0, cv->cy1); + + float span = a1 - a0; + while (span < 0.0f) span += 6.283185307f; + while (span > 6.283185307f) span -= 6.283185307f; + float r0s = r0 > 0.0f ? r0 * r0 : -1.0f, r1s = r1 * r1; + + for (int y = iy0; y < iy1; ++y) { + for (int x = ix0; x < ix1; ++x) { + int hits = 0; + for (int sy = 0; sy < 2; ++sy) { + for (int sx = 0; sx < 2; ++sx) { + float dx = (float)x + 0.25f + 0.5f * (float)sx - cx; + float dy = (float)y + 0.25f + 0.5f * (float)sy - cy; + float d2 = dx * dx + dy * dy; + if (d2 < r0s || d2 > r1s) continue; + float da = atan2f(dy, dx) - a0; + while (da < 0.0f) da += 6.283185307f; + while (da > 6.283185307f) da -= 6.283185307f; + if (da <= span) hits++; + } + } + if (hits) sw_blend(cv, x, y, c, (float)hits * 0.25f); + } + } +} + +/* An RGBA image scaled into a box, box-filtered when shrinking so an icon + * rasterised large and drawn small does not come out speckled. The source is + * straight (not premultiplied) RGBA, which is what nanosvg and stb_image give. + */ +void sw_blit(Canvas *cv, Image img, float x, float y, float w, float h, + float alpha) +{ + if (!img.rgba || img.w <= 0 || img.h <= 0 || w <= 0.0f || h <= 0.0f) return; + if (alpha <= 0.0f) return; + int stride = img.stride > 0 ? img.stride : img.w * 4; + + int ix0 = sw_clampi((int)floorf(x), cv->cx0, cv->cx1); + int iy0 = sw_clampi((int)floorf(y), cv->cy0, cv->cy1); + int ix1 = sw_clampi((int)ceilf(x + w), cv->cx0, cv->cx1); + int iy1 = sw_clampi((int)ceilf(y + h), cv->cy0, cv->cy1); + + float sx = (float)img.w / w, sy = (float)img.h / h; + int bx = (int)sx, by = (int)sy; /* box size when shrinking */ + if (bx < 1) bx = 1; + if (by < 1) by = 1; + + for (int dy = iy0; dy < iy1; ++dy) { + for (int dx = ix0; dx < ix1; ++dx) { + float u = ((float)dx + 0.5f - x) * sx; + float v = ((float)dy + 0.5f - y) * sy; + int u0 = (int)u, v0 = (int)v; + if (u0 < 0 || v0 < 0 || u0 >= img.w || v0 >= img.h) continue; + + unsigned rs = 0, gs = 0, bs = 0, as = 0, n = 0; + for (int j = 0; j < by; ++j) { + int vv = v0 + j; + if (vv >= img.h) break; + const unsigned char *row = img.rgba + (size_t)vv * (size_t)stride; + for (int i = 0; i < bx; ++i) { + int uu = u0 + i; + if (uu >= img.w) break; + const unsigned char *p = row + (size_t)uu * 4; + rs += p[0]; gs += p[1]; bs += p[2]; as += p[3]; + n++; + } + } + if (!n || !as) continue; + Col c = { (uint8_t)(rs / n), (uint8_t)(gs / n), (uint8_t)(bs / n), 255 }; + sw_blend(cv, dx, dy, c, (float)(as / n) / 255.0f * alpha); + } + } +} + + +float sw_text_width_n(Font *f, const char *s, size_t n) +{ + char buf[512]; + if (!f || !s || n == 0) return 0.0f; + if (n >= sizeof(buf)) n = sizeof(buf) - 1; + memcpy(buf, s, n); + buf[n] = 0; + return sw_text_width(f, buf); +} + +float sw_font_descent(Font *f) +{ + if (!f) return 0.0f; + float d = f->lineh - f->ascent; + return d > 0.0f ? d : 0.0f; +} + +Canvas *sw_canvas_new(int w, int h) +{ + Canvas *cv; + if (w <= 0 || h <= 0) return NULL; + cv = (Canvas *)calloc(1, sizeof *cv); + if (!cv) return NULL; + cv->px = (uint32_t *)calloc((size_t)w * (size_t)h, 4); + if (!cv->px) { free(cv); return NULL; } + cv->w = w; cv->h = h; + sw_canvas_clip_all(cv); + return cv; +} + +void sw_canvas_free(Canvas *cv) +{ + if (!cv) return; + free(cv->px); + free(cv); +} + +void sw_canvas_clear(Canvas *cv) +{ + if (!cv || !cv->px) return; + memset(cv->px, 0, (size_t)cv->w * (size_t)cv->h * 4); +} + +void sw_blit_canvas(Canvas *dst, const Canvas *src, float x, float y, + float w, float h, Col tint, float alpha) +{ + int ix0, iy0, ix1, iy1, dx, dy, bx, by; + float sx, sy; + if (!dst || !src || !src->px || w <= 0.0f || h <= 0.0f || alpha <= 0.0f) return; + + ix0 = sw_clampi((int)floorf(x), dst->cx0, dst->cx1); + iy0 = sw_clampi((int)floorf(y), dst->cy0, dst->cy1); + ix1 = sw_clampi((int)ceilf(x + w), dst->cx0, dst->cx1); + iy1 = sw_clampi((int)ceilf(y + h), dst->cy0, dst->cy1); + + /* 1:1 and aligned: a straight premultiplied-over copy, no resampling */ + if (tint.r == 255 && tint.g == 255 && tint.b == 255 && + (int)w == src->w && (int)h == src->h && + x == floorf(x) && y == floorf(y)) { + int ox = (int)x, oy = (int)y; + for (dy = iy0; dy < iy1; ++dy) { + const uint32_t *srow; + int sy1 = dy - oy; + if (sy1 < 0 || sy1 >= src->h) continue; + srow = src->px + (size_t)sy1 * (size_t)src->w; + for (dx = ix0; dx < ix1; ++dx) { + uint32_t p; + unsigned av; + Col c; + int sx1 = dx - ox; + if (sx1 < 0 || sx1 >= src->w) continue; + p = srow[sx1]; + av = (p >> 24) & 0xff; + if (!av) continue; + c.r = (uint8_t)sw_clampi((int)((p >> 16 & 0xff) * 255 / av), 0, 255); + c.g = (uint8_t)sw_clampi((int)((p >> 8 & 0xff) * 255 / av), 0, 255); + c.b = (uint8_t)sw_clampi((int)((p & 0xff) * 255 / av), 0, 255); + c.a = 255; + sw_blend(dst, dx, dy, c, (float)av / 255.0f * alpha); + } + } + return; + } + + sx = (float)src->w / w; + sy = (float)src->h / h; + bx = (int)sx; if (bx < 1) bx = 1; + by = (int)sy; if (by < 1) by = 1; + + for (dy = iy0; dy < iy1; ++dy) { + for (dx = ix0; dx < ix1; ++dx) { + float u = ((float)dx + 0.5f - x) * sx; + float v = ((float)dy + 0.5f - y) * sy; + int u0 = (int)u, v0 = (int)v, i, j; + unsigned as = 0, rs = 0, gs = 0, bs = 0, n = 0; + Col c; + float a; + if (u0 < 0 || v0 < 0 || u0 >= src->w || v0 >= src->h) continue; + for (j = 0; j < by; ++j) { + int vv = v0 + j; + const uint32_t *row; + if (vv >= src->h) break; + row = src->px + (size_t)vv * (size_t)src->w; + for (i = 0; i < bx; ++i) { + uint32_t p; + int uu = u0 + i; + if (uu >= src->w) break; + p = row[uu]; + as += (p >> 24) & 0xff; + rs += (p >> 16) & 0xff; + gs += (p >> 8) & 0xff; + bs += p & 0xff; + n++; + } + } + if (!n || !as) continue; + a = (float)(as / n) / 255.0f; + /* the source is premultiplied; sw_blend wants straight colour */ + c.r = (uint8_t)sw_clampi((int)((float)(rs / n) / a + 0.5f), 0, 255); + c.g = (uint8_t)sw_clampi((int)((float)(gs / n) / a + 0.5f), 0, 255); + c.b = (uint8_t)sw_clampi((int)((float)(bs / n) / a + 0.5f), 0, 255); + c.a = 255; + if (tint.r != 255 || tint.g != 255 || tint.b != 255) { + c.r = (uint8_t)(c.r * tint.r / 255); + c.g = (uint8_t)(c.g * tint.g / 255); + c.b = (uint8_t)(c.b * tint.b / 255); + } + sw_blend(dst, dx, dy, c, a * alpha); + } + } +} + +/* ------------------------------------------------------------------ PNG */ + +static uint32_t sw_crc32(const unsigned char *p, size_t n, uint32_t crc) +{ + static uint32_t tab[256]; + static int built = 0; + size_t i; + if (!built) { + uint32_t k, c; + int b; + for (k = 0; k < 256; ++k) { + c = k; + for (b = 0; b < 8; ++b) c = (c & 1) ? 0xedb88320u ^ (c >> 1) : c >> 1; + tab[k] = c; + } + built = 1; + } + crc ^= 0xffffffffu; + for (i = 0; i < n; ++i) crc = tab[(crc ^ p[i]) & 0xff] ^ (crc >> 8); + return crc ^ 0xffffffffu; +} + +static void sw_png_chunk(FILE *f, const char *tag, const unsigned char *d, size_t n) +{ + unsigned char hdr[8]; + uint32_t crc; + unsigned char cb[4]; + hdr[0] = (unsigned char)(n >> 24); hdr[1] = (unsigned char)(n >> 16); + hdr[2] = (unsigned char)(n >> 8); hdr[3] = (unsigned char)n; + memcpy(hdr + 4, tag, 4); + fwrite(hdr, 1, 8, f); + if (n) fwrite(d, 1, n, f); + crc = sw_crc32((const unsigned char *)tag, 4, 0); + if (n) crc = sw_crc32(d, n, crc); + cb[0] = (unsigned char)(crc >> 24); cb[1] = (unsigned char)(crc >> 16); + cb[2] = (unsigned char)(crc >> 8); cb[3] = (unsigned char)crc; + fwrite(cb, 1, 4, f); +} + +bool sw_write_png(const char *path, const Canvas *cv) +{ + FILE *f; + unsigned char ihdr[13]; + unsigned char *raw, *z; + size_t rawn, zn, pos, off; + uint32_t a = 1, b = 0; + int y, x; + static const unsigned char sig[8] = { 137, 80, 78, 71, 13, 10, 26, 10 }; + + if (!path || !cv || !cv->px) return false; + rawn = ((size_t)cv->w * 4 + 1) * (size_t)cv->h; + raw = (unsigned char *)malloc(rawn); + if (!raw) return false; + + /* un-premultiply back to straight RGBA, one filter byte a row */ + pos = 0; + for (y = 0; y < cv->h; ++y) { + raw[pos++] = 0; + for (x = 0; x < cv->w; ++x) { + uint32_t p = cv->px[(size_t)y * (size_t)cv->w + x]; + unsigned av = (p >> 24) & 0xff; + unsigned rv = (p >> 16) & 0xff, gv = (p >> 8) & 0xff, bv = p & 0xff; + if (av && av < 255) { + rv = rv * 255u / av; if (rv > 255) rv = 255; + gv = gv * 255u / av; if (gv > 255) gv = 255; + bv = bv * 255u / av; if (bv > 255) bv = 255; + } + raw[pos++] = (unsigned char)rv; + raw[pos++] = (unsigned char)gv; + raw[pos++] = (unsigned char)bv; + raw[pos++] = (unsigned char)av; + } + } + + /* zlib stream, stored deflate blocks of at most 65535 bytes */ + zn = 2 + 4 + rawn + 5 * ((rawn + 65534) / 65535) + 1; + z = (unsigned char *)malloc(zn); + if (!z) { free(raw); return false; } + pos = 0; + z[pos++] = 0x78; z[pos++] = 0x01; + for (off = 0; off < rawn; ) { + size_t n = rawn - off > 65535 ? 65535 : rawn - off; + z[pos++] = (off + n >= rawn) ? 1 : 0; + z[pos++] = (unsigned char)n; z[pos++] = (unsigned char)(n >> 8); + z[pos++] = (unsigned char)(~n); z[pos++] = (unsigned char)((~n) >> 8); + memcpy(z + pos, raw + off, n); + pos += n; + off += n; + } + for (off = 0; off < rawn; ++off) { /* adler32 */ + a = (a + raw[off]) % 65521u; + b = (b + a) % 65521u; + } + z[pos++] = (unsigned char)(b >> 8); z[pos++] = (unsigned char)b; + z[pos++] = (unsigned char)(a >> 8); z[pos++] = (unsigned char)a; + free(raw); + + f = fopen(path, "wb"); + if (!f) { free(z); return false; } + fwrite(sig, 1, 8, f); + ihdr[0] = (unsigned char)((unsigned)cv->w >> 24); + ihdr[1] = (unsigned char)((unsigned)cv->w >> 16); + ihdr[2] = (unsigned char)((unsigned)cv->w >> 8); + ihdr[3] = (unsigned char)cv->w; + ihdr[4] = (unsigned char)((unsigned)cv->h >> 24); + ihdr[5] = (unsigned char)((unsigned)cv->h >> 16); + ihdr[6] = (unsigned char)((unsigned)cv->h >> 8); + ihdr[7] = (unsigned char)cv->h; + ihdr[8] = 8; ihdr[9] = 6; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0; + sw_png_chunk(f, "IHDR", ihdr, 13); + sw_png_chunk(f, "IDAT", z, pos); + sw_png_chunk(f, "IEND", NULL, 0); + free(z); + fclose(f); + return true; +} + +#endif /* SW_DRAW_IMPL_ONCE */ +#endif /* SW_DRAW_IMPL */ diff --git a/sw_keymap.h b/sw_keymap.h new file mode 100644 index 0000000..a1cb9a7 --- /dev/null +++ b/sw_keymap.h @@ -0,0 +1,1000 @@ +/* sw_keymap.h — keysyms from the keymap the compositor sends, without + * libxkbcommon. + * + * A Wayland client is handed its keymap as XKB text over wl_keyboard.keymap. + * Reading that is the whole job for an app that wants to know what a key + * types: it is the user's real layout, not a guess, so a German keyboard + * types z where z is and ä where ä is. This parser takes the two sections it + * needs — the keycode names and the symbol table — and the four shift levels + * of each key. + * + * What it does not do: dead keys, compose sequences, multiple groups and + * layout switching, and the long tail of keysyms no stock layout uses. A + * search box and a rename field do not need them. If a program ever does, + * that is the point to link libxkbcommon and delete this file. + * + * The keysym name table below was generated from the names the stock us, de, + * fr, es, gb, it, se, no, dk, pl, cz and ru layouts actually use. Checked + * against libxkbcommon on all twelve, every keycode at every modifier + * combination: the characters typed match exactly. Two keysyms differ — + * PrintScreen and Pause, whose second level is selected by Control rather + * than Shift — and neither types anything. + * + * Define SW_KEYMAP_IMPL in exactly one translation unit. + * + * Written/modified by: Claude Opus 5 + */ +#ifndef SW_KEYMAP_H +#define SW_KEYMAP_H + +#include <stdbool.h> +#include <stddef.h> +#include <stdint.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/* X keysyms worth naming, so callers do not need the header they came from */ +enum { + SW_KEY_BACKSPACE = 0xff08, SW_KEY_TAB = 0xff09, SW_KEY_RETURN = 0xff0d, + SW_KEY_ESCAPE = 0xff1b, SW_KEY_HOME = 0xff50, SW_KEY_LEFT = 0xff51, + SW_KEY_UP = 0xff52, SW_KEY_RIGHT = 0xff53, SW_KEY_DOWN = 0xff54, + SW_KEY_PAGE_UP = 0xff55, SW_KEY_PAGE_DOWN = 0xff56, SW_KEY_END = 0xff57, + SW_KEY_INSERT = 0xff63, SW_KEY_KP_ENTER = 0xff8d, SW_KEY_DELETE = 0xffff, + SW_KEY_F1 = 0xffbe, SW_KEY_SPACE = 0x0020 +}; + +#define SW_KEYMAP_MAX 320 /* evdev tops out well below this */ + +typedef struct { + uint32_t sym[SW_KEYMAP_MAX][4]; /* keycode x level: plain, shift, altgr, both */ + uint8_t keypad[SW_KEYMAP_MAX]; /* 1 = its level follows NumLock, not Shift */ + bool ok; +} SwKeymap; + +/* Parse what arrived on wl_keyboard.keymap. Safe to call again on a change. */ +bool sw_keymap_parse(SwKeymap *km, const char *text, size_t len); + +/* The keysym for a keycode under the current modifiers, and what it types. + * utf8 is set to the characters, or "" for a key that types nothing. */ +uint32_t sw_keymap_lookup(const SwKeymap *km, uint32_t keycode, unsigned mods, + char *utf8, size_t n); + +/* The SW_MOD_* bits for a wl_keyboard.modifiers mask. */ +unsigned sw_keymap_mods(const SwKeymap *km, uint32_t depressed); + +/* The codepoint a keysym types, 0 for one that types nothing. */ +uint32_t sw_keysym_to_codepoint(uint32_t sym); + +#ifdef __cplusplus +} +#endif +#endif /* SW_KEYMAP_H */ + +/* ===================================================================== */ +#ifdef SW_KEYMAP_IMPL +#ifndef SW_KEYMAP_IMPL_ONCE +#define SW_KEYMAP_IMPL_ONCE + +#include <ctype.h> +#include <stdlib.h> +#include <string.h> + +/* The modifier bits in a wl_keyboard.modifiers mask are the core X ones, in + * their fixed order, whatever the keymap calls them. */ +enum { SWK_SHIFT = 1u << 0, SWK_LOCK = 1u << 1, SWK_CTRL = 1u << 2, + SWK_MOD1 = 1u << 3, SWK_NUM = 1u << 4, SWK_MOD4 = 1u << 6, + SWK_MOD5 = 1u << 7 }; + +typedef struct { const char *name; uint32_t sym; uint32_t cp; } SwKsEntry; + +/* Generated from the keysym names the stock layouts use. Sorted, so a + * lookup is a binary search. Single ASCII characters are not in here: their + * name is the character and their keysym is its code. */ +static const SwKsEntry SW_KS[] = { + { "0x0100002b", 0x0100002b, 0x002b }, + { "0x010000d7", 0x010000d7, 0x00d7 }, + { "0x010000f7", 0x010000f7, 0x00f7 }, + { "AE", 0x000000c6, 0x00c6 }, + { "Adiaeresis", 0x000000c4, 0x00c4 }, + { "Alt_L", 0x0000ffe9, 0x0000 }, + { "Alt_R", 0x0000ffea, 0x0000 }, + { "Aogonek", 0x000001a1, 0x0104 }, + { "Aring", 0x000000c5, 0x00c5 }, + { "BackSpace", 0x0000ff08, 0x0008 }, + { "Break", 0x0000ff6b, 0x0000 }, + { "Cacute", 0x000001c6, 0x0106 }, + { "Cancel", 0x0000ff69, 0x0000 }, + { "Caps_Lock", 0x0000ffe5, 0x0000 }, + { "Ccedilla", 0x000000c7, 0x00c7 }, + { "Control_L", 0x0000ffe3, 0x0000 }, + { "Control_R", 0x0000ffe4, 0x0000 }, + { "Cyrillic_A", 0x000006e1, 0x0410 }, + { "Cyrillic_BE", 0x000006e2, 0x0411 }, + { "Cyrillic_CHE", 0x000006fe, 0x0427 }, + { "Cyrillic_DE", 0x000006e4, 0x0414 }, + { "Cyrillic_E", 0x000006fc, 0x042d }, + { "Cyrillic_EF", 0x000006e6, 0x0424 }, + { "Cyrillic_EL", 0x000006ec, 0x041b }, + { "Cyrillic_EM", 0x000006ed, 0x041c }, + { "Cyrillic_EN", 0x000006ee, 0x041d }, + { "Cyrillic_ER", 0x000006f2, 0x0420 }, + { "Cyrillic_ES", 0x000006f3, 0x0421 }, + { "Cyrillic_GHE", 0x000006e7, 0x0413 }, + { "Cyrillic_HA", 0x000006e8, 0x0425 }, + { "Cyrillic_HARDSIGN", 0x000006ff, 0x042a }, + { "Cyrillic_I", 0x000006e9, 0x0418 }, + { "Cyrillic_IE", 0x000006e5, 0x0415 }, + { "Cyrillic_IO", 0x000006b3, 0x0401 }, + { "Cyrillic_KA", 0x000006eb, 0x041a }, + { "Cyrillic_O", 0x000006ef, 0x041e }, + { "Cyrillic_PE", 0x000006f0, 0x041f }, + { "Cyrillic_SHA", 0x000006fb, 0x0428 }, + { "Cyrillic_SHCHA", 0x000006fd, 0x0429 }, + { "Cyrillic_SHORTI", 0x000006ea, 0x0419 }, + { "Cyrillic_SOFTSIGN", 0x000006f8, 0x042c }, + { "Cyrillic_TE", 0x000006f4, 0x0422 }, + { "Cyrillic_TSE", 0x000006e3, 0x0426 }, + { "Cyrillic_U", 0x000006f5, 0x0423 }, + { "Cyrillic_VE", 0x000006f7, 0x0412 }, + { "Cyrillic_YA", 0x000006f1, 0x042f }, + { "Cyrillic_YERU", 0x000006f9, 0x042b }, + { "Cyrillic_YU", 0x000006e0, 0x042e }, + { "Cyrillic_ZE", 0x000006fa, 0x0417 }, + { "Cyrillic_ZHE", 0x000006f6, 0x0416 }, + { "Cyrillic_a", 0x000006c1, 0x0430 }, + { "Cyrillic_be", 0x000006c2, 0x0431 }, + { "Cyrillic_che", 0x000006de, 0x0447 }, + { "Cyrillic_de", 0x000006c4, 0x0434 }, + { "Cyrillic_e", 0x000006dc, 0x044d }, + { "Cyrillic_ef", 0x000006c6, 0x0444 }, + { "Cyrillic_el", 0x000006cc, 0x043b }, + { "Cyrillic_em", 0x000006cd, 0x043c }, + { "Cyrillic_en", 0x000006ce, 0x043d }, + { "Cyrillic_er", 0x000006d2, 0x0440 }, + { "Cyrillic_es", 0x000006d3, 0x0441 }, + { "Cyrillic_ghe", 0x000006c7, 0x0433 }, + { "Cyrillic_ha", 0x000006c8, 0x0445 }, + { "Cyrillic_hardsign", 0x000006df, 0x044a }, + { "Cyrillic_i", 0x000006c9, 0x0438 }, + { "Cyrillic_ie", 0x000006c5, 0x0435 }, + { "Cyrillic_io", 0x000006a3, 0x0451 }, + { "Cyrillic_ka", 0x000006cb, 0x043a }, + { "Cyrillic_o", 0x000006cf, 0x043e }, + { "Cyrillic_pe", 0x000006d0, 0x043f }, + { "Cyrillic_sha", 0x000006db, 0x0448 }, + { "Cyrillic_shcha", 0x000006dd, 0x0449 }, + { "Cyrillic_shorti", 0x000006ca, 0x0439 }, + { "Cyrillic_softsign", 0x000006d8, 0x044c }, + { "Cyrillic_te", 0x000006d4, 0x0442 }, + { "Cyrillic_tse", 0x000006c3, 0x0446 }, + { "Cyrillic_u", 0x000006d5, 0x0443 }, + { "Cyrillic_ve", 0x000006d7, 0x0432 }, + { "Cyrillic_ya", 0x000006d1, 0x044f }, + { "Cyrillic_yeru", 0x000006d9, 0x044b }, + { "Cyrillic_yu", 0x000006c0, 0x044e }, + { "Cyrillic_ze", 0x000006da, 0x0437 }, + { "Cyrillic_zhe", 0x000006d6, 0x0436 }, + { "Delete", 0x0000ffff, 0x007f }, + { "Down", 0x0000ff54, 0x0000 }, + { "Dstroke", 0x000001d0, 0x0110 }, + { "ENG", 0x000003bd, 0x014a }, + { "ETH", 0x000000d0, 0x00d0 }, + { "End", 0x0000ff57, 0x0000 }, + { "Eogonek", 0x000001ca, 0x0118 }, + { "Escape", 0x0000ff1b, 0x001b }, + { "EuroSign", 0x000020ac, 0x20ac }, + { "F1", 0x0000ffbe, 0x0000 }, + { "F10", 0x0000ffc7, 0x0000 }, + { "F11", 0x0000ffc8, 0x0000 }, + { "F12", 0x0000ffc9, 0x0000 }, + { "F2", 0x0000ffbf, 0x0000 }, + { "F3", 0x0000ffc0, 0x0000 }, + { "F4", 0x0000ffc1, 0x0000 }, + { "F5", 0x0000ffc2, 0x0000 }, + { "F6", 0x0000ffc3, 0x0000 }, + { "F7", 0x0000ffc4, 0x0000 }, + { "F8", 0x0000ffc5, 0x0000 }, + { "F9", 0x0000ffc6, 0x0000 }, + { "Find", 0x0000ff68, 0x0000 }, + { "Greek_OMEGA", 0x000007d9, 0x03a9 }, + { "Greek_PI", 0x000007d0, 0x03a0 }, + { "Greek_SIGMA", 0x000007d2, 0x03a3 }, + { "Greek_omega", 0x000007f9, 0x03c9 }, + { "Greek_pi", 0x000007f0, 0x03c0 }, + { "Greek_sigma", 0x000007f2, 0x03c3 }, + { "Hangul", 0x0000ff31, 0x0000 }, + { "Hangul_Hanja", 0x0000ff34, 0x0000 }, + { "Help", 0x0000ff6a, 0x0000 }, + { "Henkan_Mode", 0x0000ff23, 0x0000 }, + { "Hiragana", 0x0000ff25, 0x0000 }, + { "Hiragana_Katakana", 0x0000ff27, 0x0000 }, + { "Home", 0x0000ff50, 0x0000 }, + { "Hstroke", 0x000002a1, 0x0126 }, + { "Hyper_L", 0x0000ffed, 0x0000 }, + { "ISO_Left_Tab", 0x0000fe20, 0x0000 }, + { "ISO_Level3_Shift", 0x0000fe03, 0x0000 }, + { "ISO_Level5_Shift", 0x0000fe11, 0x0000 }, + { "ISO_Next_Group", 0x0000fe08, 0x0000 }, + { "Insert", 0x0000ff63, 0x0000 }, + { "KP_0", 0x0000ffb0, 0x0030 }, + { "KP_1", 0x0000ffb1, 0x0031 }, + { "KP_2", 0x0000ffb2, 0x0032 }, + { "KP_3", 0x0000ffb3, 0x0033 }, + { "KP_4", 0x0000ffb4, 0x0034 }, + { "KP_5", 0x0000ffb5, 0x0035 }, + { "KP_6", 0x0000ffb6, 0x0036 }, + { "KP_7", 0x0000ffb7, 0x0037 }, + { "KP_8", 0x0000ffb8, 0x0038 }, + { "KP_9", 0x0000ffb9, 0x0039 }, + { "KP_Add", 0x0000ffab, 0x002b }, + { "KP_Begin", 0x0000ff9d, 0x0000 }, + { "KP_Decimal", 0x0000ffae, 0x002e }, + { "KP_Delete", 0x0000ff9f, 0x0000 }, + { "KP_Divide", 0x0000ffaf, 0x002f }, + { "KP_Down", 0x0000ff99, 0x0000 }, + { "KP_End", 0x0000ff9c, 0x0000 }, + { "KP_Enter", 0x0000ff8d, 0x000d }, + { "KP_Equal", 0x0000ffbd, 0x003d }, + { "KP_Home", 0x0000ff95, 0x0000 }, + { "KP_Insert", 0x0000ff9e, 0x0000 }, + { "KP_Left", 0x0000ff96, 0x0000 }, + { "KP_Multiply", 0x0000ffaa, 0x002a }, + { "KP_Next", 0x0000ff9b, 0x0000 }, + { "KP_Prior", 0x0000ff9a, 0x0000 }, + { "KP_Right", 0x0000ff98, 0x0000 }, + { "KP_Separator", 0x0000ffac, 0x002c }, + { "KP_Subtract", 0x0000ffad, 0x002d }, + { "KP_Up", 0x0000ff97, 0x0000 }, + { "Katakana", 0x0000ff26, 0x0000 }, + { "Left", 0x0000ff51, 0x0000 }, + { "Linefeed", 0x0000ff0a, 0x000a }, + { "Lstroke", 0x000001a3, 0x0141 }, + { "Menu", 0x0000ff67, 0x0000 }, + { "Meta_L", 0x0000ffe7, 0x0000 }, + { "Meta_R", 0x0000ffe8, 0x0000 }, + { "Muhenkan", 0x0000ff22, 0x0000 }, + { "Nacute", 0x000001d1, 0x0143 }, + { "Next", 0x0000ff56, 0x0000 }, + { "Ntilde", 0x000000d1, 0x00d1 }, + { "Num_Lock", 0x0000ff7f, 0x0000 }, + { "OE", 0x000013bc, 0x0152 }, + { "Oacute", 0x000000d3, 0x00d3 }, + { "Odiaeresis", 0x000000d6, 0x00d6 }, + { "Oslash", 0x000000d8, 0x00d8 }, + { "Pause", 0x0000ff13, 0x0000 }, + { "Print", 0x0000ff61, 0x0000 }, + { "Prior", 0x0000ff55, 0x0000 }, + { "Redo", 0x0000ff66, 0x0000 }, + { "Return", 0x0000ff0d, 0x000d }, + { "Right", 0x0000ff53, 0x0000 }, + { "SCHWA", 0x0100018f, 0x018f }, + { "Sacute", 0x000001a6, 0x015a }, + { "Scroll_Lock", 0x0000ff14, 0x0000 }, + { "Shift_L", 0x0000ffe1, 0x0000 }, + { "Shift_R", 0x0000ffe2, 0x0000 }, + { "SunFront", 0x1005ff71, 0x0000 }, + { "SunProps", 0x1005ff70, 0x0000 }, + { "Super_L", 0x0000ffeb, 0x0000 }, + { "Super_R", 0x0000ffec, 0x0000 }, + { "Sys_Req", 0x0000ff15, 0x0000 }, + { "THORN", 0x000000de, 0x00de }, + { "Tab", 0x0000ff09, 0x0009 }, + { "Tslash", 0x000003ac, 0x0166 }, + { "U0001F12F", 0x0101f12f, 0x1f12f }, + { "U017F", 0x0100017f, 0x017f }, + { "U1E9E", 0x01001e9e, 0x1e9e }, + { "U2022", 0x01002022, 0x2022 }, + { "U2026", 0x01002026, 0x2026 }, + { "U202F", 0x0100202f, 0x202f }, + { "U2032", 0x01002032, 0x2032 }, + { "U2033", 0x01002033, 0x2033 }, + { "U2039", 0x01002039, 0x2039 }, + { "U203A", 0x0100203a, 0x203a }, + { "U20BD", 0x010020bd, 0x20bd }, + { "U2194", 0x01002194, 0x2194 }, + { "U2212", 0x01002212, 0x2212 }, + { "U2215", 0x01002215, 0x2215 }, + { "U22C5", 0x010022c5, 0x22c5 }, + { "Udiaeresis", 0x000000dc, 0x00dc }, + { "Undo", 0x0000ff65, 0x0000 }, + { "Up", 0x0000ff52, 0x0000 }, + { "VoidSymbol", 0x00ffffff, 0x0000 }, + { "XF8610ChannelsDown", 0x100811b9, 0x0000 }, + { "XF8610ChannelsUp", 0x100811b8, 0x0000 }, + { "XF863DMode", 0x1008126f, 0x0000 }, + { "XF86ALSToggle", 0x10081230, 0x0000 }, + { "XF86Addressbook", 0x100811ad, 0x0000 }, + { "XF86AppSelect", 0x10081244, 0x0000 }, + { "XF86AspectRatio", 0x10081177, 0x0000 }, + { "XF86Assistant", 0x10081247, 0x0000 }, + { "XF86AttendantOff", 0x1008121c, 0x0000 }, + { "XF86AttendantOn", 0x1008121b, 0x0000 }, + { "XF86AttendantToggle", 0x1008121d, 0x0000 }, + { "XF86Audio", 0x10081188, 0x0000 }, + { "XF86AudioDesc", 0x1008126e, 0x0000 }, + { "XF86AudioForward", 0x1008ff97, 0x0000 }, + { "XF86AudioLowerVolume", 0x1008ff11, 0x0000 }, + { "XF86AudioMedia", 0x1008ff32, 0x0000 }, + { "XF86AudioMicMute", 0x1008ffb2, 0x0000 }, + { "XF86AudioMute", 0x1008ff12, 0x0000 }, + { "XF86AudioNext", 0x1008ff17, 0x0000 }, + { "XF86AudioPause", 0x1008ff31, 0x0000 }, + { "XF86AudioPlay", 0x1008ff14, 0x0000 }, + { "XF86AudioPreset", 0x1008ffb6, 0x0000 }, + { "XF86AudioPrev", 0x1008ff16, 0x0000 }, + { "XF86AudioRaiseVolume", 0x1008ff13, 0x0000 }, + { "XF86AudioRandomPlay", 0x1008ff99, 0x0000 }, + { "XF86AudioRecord", 0x1008ff1c, 0x0000 }, + { "XF86AudioRewind", 0x1008ff3e, 0x0000 }, + { "XF86AudioStop", 0x1008ff15, 0x0000 }, + { "XF86AutopilotEngageToggle", 0x1008127d, 0x0000 }, + { "XF86Back", 0x1008ff26, 0x0000 }, + { "XF86Battery", 0x1008ff93, 0x0000 }, + { "XF86Bluetooth", 0x1008ff94, 0x0000 }, + { "XF86Break", 0x1008119b, 0x0000 }, + { "XF86BrightnessAdjust", 0x1008ff3b, 0x0000 }, + { "XF86BrightnessAuto", 0x100810f4, 0x0000 }, + { "XF86BrightnessMax", 0x10081251, 0x0000 }, + { "XF86BrightnessMin", 0x10081250, 0x0000 }, + { "XF86Buttonconfig", 0x10081240, 0x0000 }, + { "XF86Calculator", 0x1008ff1d, 0x0000 }, + { "XF86Calendar", 0x1008ff20, 0x0000 }, + { "XF86CameraAccessDisable", 0x1008124c, 0x0000 }, + { "XF86CameraAccessEnable", 0x1008124b, 0x0000 }, + { "XF86CameraAccessToggle", 0x1008124d, 0x0000 }, + { "XF86CameraDown", 0x10081218, 0x0000 }, + { "XF86CameraFocus", 0x10081210, 0x0000 }, + { "XF86CameraLeft", 0x10081219, 0x0000 }, + { "XF86CameraRight", 0x1008121a, 0x0000 }, + { "XF86CameraUp", 0x10081217, 0x0000 }, + { "XF86CameraZoomIn", 0x10081215, 0x0000 }, + { "XF86CameraZoomOut", 0x10081216, 0x0000 }, + { "XF86ChannelDown", 0x10081193, 0x0000 }, + { "XF86ChannelUp", 0x10081192, 0x0000 }, + { "XF86ClearGrab", 0x1008fe21, 0x0000 }, + { "XF86ClearvuSonar", 0x10081286, 0x0000 }, + { "XF86Close", 0x1008ff56, 0x0000 }, + { "XF86ContextMenu", 0x100811b6, 0x0000 }, + { "XF86ControlPanel", 0x10081243, 0x0000 }, + { "XF86Copy", 0x1008ff57, 0x0000 }, + { "XF86Cut", 0x1008ff58, 0x0000 }, + { "XF86CycleAngle", 0x1008ff9c, 0x0000 }, + { "XF86DOS", 0x1008ff5a, 0x0000 }, + { "XF86DVD", 0x10081185, 0x0000 }, + { "XF86Data", 0x10081277, 0x0000 }, + { "XF86Database", 0x100811aa, 0x0000 }, + { "XF86Dictate", 0x1008124a, 0x0000 }, + { "XF86Display", 0x1008ff59, 0x0000 }, + { "XF86DisplayOff", 0x100810f5, 0x0000 }, + { "XF86DisplayToggle", 0x100811af, 0x0000 }, + { "XF86Documents", 0x1008ff5b, 0x0000 }, + { "XF86DualRangeRadar", 0x10081283, 0x0000 }, + { "XF86Editor", 0x100811a6, 0x0000 }, + { "XF86Eject", 0x1008ff2c, 0x0000 }, + { "XF86EmojiPicker", 0x10081249, 0x0000 }, + { "XF86Excel", 0x1008ff5c, 0x0000 }, + { "XF86Explorer", 0x1008ff5d, 0x0000 }, + { "XF86FastReverse", 0x10081275, 0x0000 }, + { "XF86Favorites", 0x1008ff30, 0x0000 }, + { "XF86Finance", 0x1008ff3c, 0x0000 }, + { "XF86FishingChart", 0x10081281, 0x0000 }, + { "XF86Fn", 0x100811d0, 0x0000 }, + { "XF86FnRightShift", 0x100811e5, 0x0000 }, + { "XF86Fn_Esc", 0x100811d1, 0x0000 }, + { "XF86Forward", 0x1008ff27, 0x0000 }, + { "XF86FrameBack", 0x1008ff9d, 0x0000 }, + { "XF86FrameForward", 0x1008ff9e, 0x0000 }, + { "XF86FullScreen", 0x1008ffb8, 0x0000 }, + { "XF86Game", 0x1008ff5e, 0x0000 }, + { "XF86Go", 0x1008ff5f, 0x0000 }, + { "XF86GraphicsEditor", 0x100811a8, 0x0000 }, + { "XF86HangupPhone", 0x100811be, 0x0000 }, + { "XF86HomePage", 0x1008ff18, 0x0000 }, + { "XF86Images", 0x100811ba, 0x0000 }, + { "XF86Info", 0x10081166, 0x0000 }, + { "XF86Journal", 0x10081242, 0x0000 }, + { "XF86KbdBrightnessDown", 0x1008ff06, 0x0000 }, + { "XF86KbdBrightnessUp", 0x1008ff05, 0x0000 }, + { "XF86KbdInputAssistAccept", 0x10081264, 0x0000 }, + { "XF86KbdInputAssistCancel", 0x10081265, 0x0000 }, + { "XF86KbdInputAssistNext", 0x10081261, 0x0000 }, + { "XF86KbdInputAssistNextgroup", 0x10081263, 0x0000 }, + { "XF86KbdInputAssistPrev", 0x10081260, 0x0000 }, + { "XF86KbdInputAssistPrevgroup", 0x10081262, 0x0000 }, + { "XF86KbdLcdMenu1", 0x100812b8, 0x0000 }, + { "XF86KbdLcdMenu2", 0x100812b9, 0x0000 }, + { "XF86KbdLcdMenu3", 0x100812ba, 0x0000 }, + { "XF86KbdLcdMenu4", 0x100812bb, 0x0000 }, + { "XF86KbdLcdMenu5", 0x100812bc, 0x0000 }, + { "XF86KbdLightOnOff", 0x1008ff04, 0x0000 }, + { "XF86Keyboard", 0x1008ffb3, 0x0000 }, + { "XF86Launch1", 0x1008ff41, 0x0000 }, + { "XF86Launch2", 0x1008ff42, 0x0000 }, + { "XF86Launch3", 0x1008ff43, 0x0000 }, + { "XF86Launch4", 0x1008ff44, 0x0000 }, + { "XF86Launch5", 0x1008ff45, 0x0000 }, + { "XF86Launch6", 0x1008ff46, 0x0000 }, + { "XF86Launch7", 0x1008ff47, 0x0000 }, + { "XF86Launch8", 0x1008ff48, 0x0000 }, + { "XF86Launch9", 0x1008ff49, 0x0000 }, + { "XF86LaunchA", 0x1008ff4a, 0x0000 }, + { "XF86LaunchB", 0x1008ff4b, 0x0000 }, + { "XF86LeftDown", 0x10081269, 0x0000 }, + { "XF86LeftUp", 0x10081268, 0x0000 }, + { "XF86LightsToggle", 0x1008121e, 0x0000 }, + { "XF86LogOff", 0x1008ff61, 0x0000 }, + { "XF86Macro1", 0x10081290, 0x0000 }, + { "XF86Macro10", 0x10081299, 0x0000 }, + { "XF86Macro11", 0x1008129a, 0x0000 }, + { "XF86Macro12", 0x1008129b, 0x0000 }, + { "XF86Macro13", 0x1008129c, 0x0000 }, + { "XF86Macro14", 0x1008129d, 0x0000 }, + { "XF86Macro15", 0x1008129e, 0x0000 }, + { "XF86Macro16", 0x1008129f, 0x0000 }, + { "XF86Macro17", 0x100812a0, 0x0000 }, + { "XF86Macro18", 0x100812a1, 0x0000 }, + { "XF86Macro19", 0x100812a2, 0x0000 }, + { "XF86Macro2", 0x10081291, 0x0000 }, + { "XF86Macro20", 0x100812a3, 0x0000 }, + { "XF86Macro21", 0x100812a4, 0x0000 }, + { "XF86Macro22", 0x100812a5, 0x0000 }, + { "XF86Macro23", 0x100812a6, 0x0000 }, + { "XF86Macro24", 0x100812a7, 0x0000 }, + { "XF86Macro25", 0x100812a8, 0x0000 }, + { "XF86Macro26", 0x100812a9, 0x0000 }, + { "XF86Macro27", 0x100812aa, 0x0000 }, + { "XF86Macro28", 0x100812ab, 0x0000 }, + { "XF86Macro29", 0x100812ac, 0x0000 }, + { "XF86Macro3", 0x10081292, 0x0000 }, + { "XF86Macro30", 0x100812ad, 0x0000 }, + { "XF86Macro4", 0x10081293, 0x0000 }, + { "XF86Macro5", 0x10081294, 0x0000 }, + { "XF86Macro6", 0x10081295, 0x0000 }, + { "XF86Macro7", 0x10081296, 0x0000 }, + { "XF86Macro8", 0x10081297, 0x0000 }, + { "XF86Macro9", 0x10081298, 0x0000 }, + { "XF86MacroPreset1", 0x100812b3, 0x0000 }, + { "XF86MacroPreset2", 0x100812b4, 0x0000 }, + { "XF86MacroPreset3", 0x100812b5, 0x0000 }, + { "XF86MacroPresetCycle", 0x100812b2, 0x0000 }, + { "XF86MacroRecordStart", 0x100812b0, 0x0000 }, + { "XF86MacroRecordStop", 0x100812b1, 0x0000 }, + { "XF86Mail", 0x1008ff19, 0x0000 }, + { "XF86MailForward", 0x1008ff90, 0x0000 }, + { "XF86MarkWaypoint", 0x1008127e, 0x0000 }, + { "XF86MediaRepeat", 0x100811b7, 0x0000 }, + { "XF86MediaTopMenu", 0x1008126b, 0x0000 }, + { "XF86MenuKB", 0x1008ff65, 0x0000 }, + { "XF86Messenger", 0x1008ff8e, 0x0000 }, + { "XF86MonBrightnessCycle", 0x1008ff07, 0x0000 }, + { "XF86MonBrightnessDown", 0x1008ff03, 0x0000 }, + { "XF86MonBrightnessUp", 0x1008ff02, 0x0000 }, + { "XF86MyComputer", 0x1008ff33, 0x0000 }, + { "XF86NavChart", 0x10081280, 0x0000 }, + { "XF86NavInfo", 0x10081288, 0x0000 }, + { "XF86New", 0x1008ff68, 0x0000 }, + { "XF86News", 0x1008ff69, 0x0000 }, + { "XF86NextElement", 0x1008127b, 0x0000 }, + { "XF86NextFavorite", 0x10081270, 0x0000 }, + { "XF86Next_VMode", 0x1008fe22, 0x0000 }, + { "XF86NotificationCenter", 0x100811bc, 0x0000 }, + { "XF86Numeric0", 0x10081200, 0x0000 }, + { "XF86Numeric1", 0x10081201, 0x0000 }, + { "XF86Numeric11", 0x1008126c, 0x0000 }, + { "XF86Numeric12", 0x1008126d, 0x0000 }, + { "XF86Numeric2", 0x10081202, 0x0000 }, + { "XF86Numeric3", 0x10081203, 0x0000 }, + { "XF86Numeric4", 0x10081204, 0x0000 }, + { "XF86Numeric5", 0x10081205, 0x0000 }, + { "XF86Numeric6", 0x10081206, 0x0000 }, + { "XF86Numeric7", 0x10081207, 0x0000 }, + { "XF86Numeric8", 0x10081208, 0x0000 }, + { "XF86Numeric9", 0x10081209, 0x0000 }, + { "XF86NumericA", 0x1008120c, 0x0000 }, + { "XF86NumericB", 0x1008120d, 0x0000 }, + { "XF86NumericC", 0x1008120e, 0x0000 }, + { "XF86NumericD", 0x1008120f, 0x0000 }, + { "XF86NumericPound", 0x1008120b, 0x0000 }, + { "XF86NumericStar", 0x1008120a, 0x0000 }, + { "XF86OnScreenKeyboard", 0x10081278, 0x0000 }, + { "XF86Open", 0x1008ff6b, 0x0000 }, + { "XF86Paste", 0x1008ff6d, 0x0000 }, + { "XF86PauseRecord", 0x10081272, 0x0000 }, + { "XF86Phone", 0x1008ff6e, 0x0000 }, + { "XF86PickupPhone", 0x100811bd, 0x0000 }, + { "XF86PowerOff", 0x1008ff2a, 0x0000 }, + { "XF86Presentation", 0x100811a9, 0x0000 }, + { "XF86Prev_VMode", 0x1008fe23, 0x0000 }, + { "XF86PreviousElement", 0x1008127c, 0x0000 }, + { "XF86PrivacyScreenToggle", 0x10081279, 0x0000 }, + { "XF86RFKill", 0x1008ffb5, 0x0000 }, + { "XF86RadarOverlay", 0x10081284, 0x0000 }, + { "XF86Reload", 0x1008ff73, 0x0000 }, + { "XF86Reply", 0x1008ff72, 0x0000 }, + { "XF86RightDown", 0x10081267, 0x0000 }, + { "XF86RightUp", 0x10081266, 0x0000 }, + { "XF86RootMenu", 0x1008126a, 0x0000 }, + { "XF86RotateWindows", 0x1008ff74, 0x0000 }, + { "XF86RotationLockToggle", 0x1008ffb7, 0x0000 }, + { "XF86Save", 0x1008ff77, 0x0000 }, + { "XF86ScreenSaver", 0x1008ff2d, 0x0000 }, + { "XF86Screensaver", 0x10081245, 0x0000 }, + { "XF86ScrollDown", 0x1008ff79, 0x0000 }, + { "XF86ScrollUp", 0x1008ff78, 0x0000 }, + { "XF86Search", 0x1008ff1b, 0x0000 }, + { "XF86SelectiveScreenshot", 0x1008127a, 0x0000 }, + { "XF86Send", 0x1008ff7b, 0x0000 }, + { "XF86Shop", 0x1008ff36, 0x0000 }, + { "XF86SidevuSonar", 0x10081287, 0x0000 }, + { "XF86SingleRangeRadar", 0x10081282, 0x0000 }, + { "XF86Sleep", 0x1008ff2f, 0x0000 }, + { "XF86SlowReverse", 0x10081276, 0x0000 }, + { "XF86Sos", 0x1008127f, 0x0000 }, + { "XF86SpellCheck", 0x100811b0, 0x0000 }, + { "XF86StopRecord", 0x10081271, 0x0000 }, + { "XF86Suspend", 0x1008ffa7, 0x0000 }, + { "XF86Switch_VT_1", 0x1008fe01, 0x0000 }, + { "XF86Switch_VT_10", 0x1008fe0a, 0x0000 }, + { "XF86Switch_VT_11", 0x1008fe0b, 0x0000 }, + { "XF86Switch_VT_12", 0x1008fe0c, 0x0000 }, + { "XF86Switch_VT_2", 0x1008fe02, 0x0000 }, + { "XF86Switch_VT_3", 0x1008fe03, 0x0000 }, + { "XF86Switch_VT_4", 0x1008fe04, 0x0000 }, + { "XF86Switch_VT_5", 0x1008fe05, 0x0000 }, + { "XF86Switch_VT_6", 0x1008fe06, 0x0000 }, + { "XF86Switch_VT_7", 0x1008fe07, 0x0000 }, + { "XF86Switch_VT_8", 0x1008fe08, 0x0000 }, + { "XF86Switch_VT_9", 0x1008fe09, 0x0000 }, + { "XF86TaskPane", 0x1008ff7f, 0x0000 }, + { "XF86Taskmanager", 0x10081241, 0x0000 }, + { "XF86Tools", 0x1008ff81, 0x0000 }, + { "XF86TouchpadOff", 0x1008ffb1, 0x0000 }, + { "XF86TouchpadOn", 0x1008ffb0, 0x0000 }, + { "XF86TouchpadToggle", 0x1008ffa9, 0x0000 }, + { "XF86TraditionalSonar", 0x10081285, 0x0000 }, + { "XF86UWB", 0x1008ff96, 0x0000 }, + { "XF86Ungrab", 0x1008fe20, 0x0000 }, + { "XF86Unmute", 0x10081274, 0x0000 }, + { "XF86VOD", 0x10081273, 0x0000 }, + { "XF86Video", 0x1008ff87, 0x0000 }, + { "XF86VideoPhone", 0x100811a0, 0x0000 }, + { "XF86VoiceCommand", 0x10081246, 0x0000 }, + { "XF86Voicemail", 0x100811ac, 0x0000 }, + { "XF86WLAN", 0x1008ff95, 0x0000 }, + { "XF86WPSButton", 0x10081211, 0x0000 }, + { "XF86WWAN", 0x1008ffb4, 0x0000 }, + { "XF86WWW", 0x1008ff2e, 0x0000 }, + { "XF86WakeUp", 0x1008ff2b, 0x0000 }, + { "XF86WebCam", 0x1008ff8f, 0x0000 }, + { "XF86Word", 0x1008ff89, 0x0000 }, + { "XF86Xfer", 0x1008ff8a, 0x0000 }, + { "XF86ZoomIn", 0x1008ff8b, 0x0000 }, + { "XF86ZoomOut", 0x1008ff8c, 0x0000 }, + { "XF86ZoomReset", 0x100811a4, 0x0000 }, + { "Zabovedot", 0x000001af, 0x017b }, + { "Zacute", 0x000001ac, 0x0179 }, + { "aacute", 0x000000e1, 0x00e1 }, + { "acute", 0x000000b4, 0x00b4 }, + { "adiaeresis", 0x000000e4, 0x00e4 }, + { "ae", 0x000000e6, 0x00e6 }, + { "agrave", 0x000000e0, 0x00e0 }, + { "ampersand", 0x00000026, 0x0026 }, + { "aogonek", 0x000001b1, 0x0105 }, + { "apostrophe", 0x00000027, 0x0027 }, + { "approxeq", 0x01002248, 0x2248 }, + { "aring", 0x000000e5, 0x00e5 }, + { "asciicircum", 0x0000005e, 0x005e }, + { "asciitilde", 0x0000007e, 0x007e }, + { "asterisk", 0x0000002a, 0x002a }, + { "at", 0x00000040, 0x0040 }, + { "backslash", 0x0000005c, 0x005c }, + { "bar", 0x0000007c, 0x007c }, + { "braceleft", 0x0000007b, 0x007b }, + { "braceright", 0x0000007d, 0x007d }, + { "bracketleft", 0x0000005b, 0x005b }, + { "bracketright", 0x0000005d, 0x005d }, + { "braille_dot_1", 0x0000fff1, 0x0000 }, + { "braille_dot_2", 0x0000fff2, 0x0000 }, + { "braille_dot_3", 0x0000fff3, 0x0000 }, + { "braille_dot_4", 0x0000fff4, 0x0000 }, + { "braille_dot_5", 0x0000fff5, 0x0000 }, + { "braille_dot_6", 0x0000fff6, 0x0000 }, + { "braille_dot_7", 0x0000fff7, 0x0000 }, + { "braille_dot_8", 0x0000fff8, 0x0000 }, + { "braille_dot_9", 0x0000fff9, 0x0000 }, + { "brokenbar", 0x000000a6, 0x00a6 }, + { "cacute", 0x000001e6, 0x0107 }, + { "ccaron", 0x000001e8, 0x010d }, + { "ccedilla", 0x000000e7, 0x00e7 }, + { "cent", 0x000000a2, 0x00a2 }, + { "colon", 0x0000003a, 0x003a }, + { "comma", 0x0000002c, 0x002c }, + { "copyright", 0x000000a9, 0x00a9 }, + { "currency", 0x000000a4, 0x00a4 }, + { "dagger", 0x00000af1, 0x2020 }, + { "dead_abovedot", 0x0000fe56, 0x0000 }, + { "dead_abovering", 0x0000fe58, 0x0000 }, + { "dead_acute", 0x0000fe51, 0x0000 }, + { "dead_belowdot", 0x0000fe60, 0x0000 }, + { "dead_belowmacron", 0x0000fe68, 0x0000 }, + { "dead_breve", 0x0000fe55, 0x0000 }, + { "dead_caron", 0x0000fe5a, 0x0000 }, + { "dead_cedilla", 0x0000fe5b, 0x0000 }, + { "dead_circumflex", 0x0000fe52, 0x0000 }, + { "dead_diaeresis", 0x0000fe57, 0x0000 }, + { "dead_doubleacute", 0x0000fe59, 0x0000 }, + { "dead_grave", 0x0000fe50, 0x0000 }, + { "dead_hook", 0x0000fe61, 0x0000 }, + { "dead_horn", 0x0000fe62, 0x0000 }, + { "dead_macron", 0x0000fe54, 0x0000 }, + { "dead_ogonek", 0x0000fe5c, 0x0000 }, + { "dead_stroke", 0x0000fe63, 0x0000 }, + { "dead_tilde", 0x0000fe53, 0x0000 }, + { "degree", 0x000000b0, 0x00b0 }, + { "division", 0x000000f7, 0x00f7 }, + { "dollar", 0x00000024, 0x0024 }, + { "doublelowquotemark", 0x00000afe, 0x201e }, + { "downarrow", 0x000008fe, 0x2193 }, + { "dstroke", 0x000001f0, 0x0111 }, + { "eacute", 0x000000e9, 0x00e9 }, + { "ecaron", 0x000001ec, 0x011b }, + { "egrave", 0x000000e8, 0x00e8 }, + { "ellipsis", 0x00000aae, 0x2026 }, + { "emdash", 0x00000aa9, 0x2014 }, + { "endash", 0x00000aaa, 0x2013 }, + { "eng", 0x000003bf, 0x014b }, + { "eogonek", 0x000001ea, 0x0119 }, + { "equal", 0x0000003d, 0x003d }, + { "eth", 0x000000f0, 0x00f0 }, + { "exclam", 0x00000021, 0x0021 }, + { "exclamdown", 0x000000a1, 0x00a1 }, + { "fiveeighths", 0x00000ac5, 0x215d }, + { "grave", 0x00000060, 0x0060 }, + { "greater", 0x0000003e, 0x003e }, + { "greaterthanequal", 0x000008be, 0x2265 }, + { "guillemetleft", 0x000000ab, 0x00ab }, + { "guillemetright", 0x000000bb, 0x00bb }, + { "hstroke", 0x000002b1, 0x0127 }, + { "iacute", 0x000000ed, 0x00ed }, + { "idotless", 0x000002b9, 0x0131 }, + { "igrave", 0x000000ec, 0x00ec }, + { "infinity", 0x000008c2, 0x221e }, + { "kra", 0x000003a2, 0x0138 }, + { "leftarrow", 0x000008fb, 0x2190 }, + { "leftdoublequotemark", 0x00000ad2, 0x201c }, + { "leftsinglequotemark", 0x00000ad0, 0x2018 }, + { "less", 0x0000003c, 0x003c }, + { "lessthanequal", 0x000008bc, 0x2264 }, + { "logicaland", 0x000008de, 0x2227 }, + { "logicalor", 0x000008df, 0x2228 }, + { "lstroke", 0x000001b3, 0x0142 }, + { "macron", 0x000000af, 0x00af }, + { "minus", 0x0000002d, 0x002d }, + { "mu", 0x000000b5, 0x00b5 }, + { "multiply", 0x000000d7, 0x00d7 }, + { "nacute", 0x000001f1, 0x0144 }, + { "nobreakspace", 0x000000a0, 0x00a0 }, + { "notequal", 0x000008bd, 0x2260 }, + { "notsign", 0x000000ac, 0x00ac }, + { "ntilde", 0x000000f1, 0x00f1 }, + { "numbersign", 0x00000023, 0x0023 }, + { "numerosign", 0x000006b0, 0x2116 }, + { "oacute", 0x000000f3, 0x00f3 }, + { "odiaeresis", 0x000000f6, 0x00f6 }, + { "oe", 0x000013bd, 0x0153 }, + { "ograve", 0x000000f2, 0x00f2 }, + { "oneeighth", 0x00000ac3, 0x215b }, + { "onehalf", 0x000000bd, 0x00bd }, + { "onequarter", 0x000000bc, 0x00bc }, + { "onesuperior", 0x000000b9, 0x00b9 }, + { "ordfeminine", 0x000000aa, 0x00aa }, + { "ordmasculine", 0x000000ba, 0x00ba }, + { "oslash", 0x000000f8, 0x00f8 }, + { "paragraph", 0x000000b6, 0x00b6 }, + { "parenleft", 0x00000028, 0x0028 }, + { "parenright", 0x00000029, 0x0029 }, + { "percent", 0x00000025, 0x0025 }, + { "period", 0x0000002e, 0x002e }, + { "periodcentered", 0x000000b7, 0x00b7 }, + { "permille", 0x00000ad5, 0x2030 }, + { "plus", 0x0000002b, 0x002b }, + { "plusminus", 0x000000b1, 0x00b1 }, + { "question", 0x0000003f, 0x003f }, + { "questiondown", 0x000000bf, 0x00bf }, + { "quotedbl", 0x00000022, 0x0022 }, + { "radical", 0x000008d6, 0x221a }, + { "rcaron", 0x000001f8, 0x0159 }, + { "registered", 0x000000ae, 0x00ae }, + { "rightarrow", 0x000008fd, 0x2192 }, + { "rightdoublequotemark", 0x00000ad3, 0x201d }, + { "rightsinglequotemark", 0x00000ad1, 0x2019 }, + { "sacute", 0x000001b6, 0x015b }, + { "scaron", 0x000001b9, 0x0161 }, + { "schwa", 0x01000259, 0x0259 }, + { "section", 0x000000a7, 0x00a7 }, + { "semicolon", 0x0000003b, 0x003b }, + { "seveneighths", 0x00000ac6, 0x215e }, + { "singlelowquotemark", 0x00000afd, 0x201a }, + { "slash", 0x0000002f, 0x002f }, + { "space", 0x00000020, 0x0020 }, + { "ssharp", 0x000000df, 0x00df }, + { "sterling", 0x000000a3, 0x00a3 }, + { "thorn", 0x000000fe, 0x00fe }, + { "threeeighths", 0x00000ac4, 0x215c }, + { "threequarters", 0x000000be, 0x00be }, + { "threesuperior", 0x000000b3, 0x00b3 }, + { "trademark", 0x00000ac9, 0x2122 }, + { "tslash", 0x000003bc, 0x0167 }, + { "twosuperior", 0x000000b2, 0x00b2 }, + { "uacute", 0x000000fa, 0x00fa }, + { "udiaeresis", 0x000000fc, 0x00fc }, + { "ugrave", 0x000000f9, 0x00f9 }, + { "underscore", 0x0000005f, 0x005f }, + { "uparrow", 0x000008fc, 0x2191 }, + { "uring", 0x000001f9, 0x016f }, + { "yacute", 0x000000fd, 0x00fd }, + { "yen", 0x000000a5, 0x00a5 }, + { "zabovedot", 0x000001bf, 0x017c }, + { "zacute", 0x000001bc, 0x017a }, + { "zcaron", 0x000001be, 0x017e }, +}; +#define SW_KS_N ((int)(sizeof(SW_KS) / sizeof(SW_KS[0]))) + +static const SwKsEntry *swk_find(const char *name, size_t len) +{ + int lo = 0, hi = SW_KS_N - 1; + while (lo <= hi) { + int mid = (lo + hi) / 2; + const char *s = SW_KS[mid].name; + int c = strncmp(s, name, len); + if (c == 0) c = (s[len] == 0) ? 0 : 1; + if (c == 0) return &SW_KS[mid]; + if (c < 0) lo = mid + 1; else hi = mid - 1; + } + return NULL; +} + +/* A keysym from its name: one ASCII character stands for itself, UXXXX is a + * codepoint written out, anything else comes from the table. */ +static uint32_t swk_sym_from_name(const char *s, size_t len) +{ + if (len == 0) return 0; + if (len == 1 && (unsigned char)s[0] >= 0x20 && (unsigned char)s[0] < 0x7f) + return (uint32_t)s[0]; + if ((s[0] == 'U' || s[0] == 'u') && len >= 5 && len <= 7) { + uint32_t cp = 0; + size_t i = 1; + for (; i < len; ++i) { + char c = s[i]; + int d = (c >= '0' && c <= '9') ? c - '0' + : (c >= 'a' && c <= 'f') ? c - 'a' + 10 + : (c >= 'A' && c <= 'F') ? c - 'A' + 10 : -1; + if (d < 0) break; + cp = cp * 16u + (uint32_t)d; + } + if (i == len) return cp + 0x1000000u; + } + const SwKsEntry *e = swk_find(s, len); + return e ? e->sym : 0; +} + +uint32_t sw_keysym_to_codepoint(uint32_t sym) +{ + if (sym >= 0x20 && sym <= 0x7e) return sym; + if (sym >= 0xa0 && sym <= 0xff) return sym; + if (sym >= 0x1000020u && sym <= 0x110ffffu) return sym - 0x1000000u; + for (int i = 0; i < SW_KS_N; ++i) /* the named ones */ + if (SW_KS[i].sym == sym) return SW_KS[i].cp; + return 0; +} + +static int swk_utf8(uint32_t cp, char *out, size_t n) +{ + if (!cp || n < 5) { if (n) out[0] = 0; return 0; } + int k = 0; + if (cp < 0x80) { out[k++] = (char)cp; } + else if (cp < 0x800) { out[k++] = (char)(0xC0 | (cp >> 6)); + out[k++] = (char)(0x80 | (cp & 0x3F)); } + else if (cp < 0x10000) { out[k++] = (char)(0xE0 | (cp >> 12)); + out[k++] = (char)(0x80 | ((cp >> 6) & 0x3F)); + out[k++] = (char)(0x80 | (cp & 0x3F)); } + else { out[k++] = (char)(0xF0 | (cp >> 18)); + out[k++] = (char)(0x80 | ((cp >> 12) & 0x3F)); + out[k++] = (char)(0x80 | ((cp >> 6) & 0x3F)); + out[k++] = (char)(0x80 | (cp & 0x3F)); } + out[k] = 0; + return k; +} + +/* ---------------------------------------------------------- the parser */ + +/* Key names are short: <AD01>, <LFSH>, <I252>. One flat table, linear scan — + * a few hundred entries, read once when the keymap arrives. */ +typedef struct { char name[12]; uint32_t code; } SwKcEntry; + +/* The body of a named block, bounded by matching braces. Counting them is + * the only way to find the end: every key line inside xkb_symbols ends in + * "};", so looking for that instead stops at the first key. */ +static const char *swk_section(const char *p, const char *end, const char *what, + const char **body_end) +{ + size_t n = strlen(what); + for (; p + n < end; ++p) { + if (strncmp(p, what, n)) continue; + const char *b = (const char *)memchr(p, '{', (size_t)(end - p)); + if (!b) return NULL; + int depth = 1; + const char *q = b + 1; + for (; q < end && depth; ++q) { + if (*q == '{') depth++; + else if (*q == '}') depth--; + else if (*q == '"') { /* a name can hold a brace */ + while (++q < end && *q != '"') + if (*q == '\\' && q + 1 < end) ++q; + } + } + if (body_end) *body_end = (depth == 0) ? q - 1 : end; + return b + 1; + } + return NULL; +} + +static const char *swk_skip_ws(const char *p, const char *end) +{ + while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) ++p; + return p; +} + +bool sw_keymap_parse(SwKeymap *km, const char *text, size_t len) +{ + if (!km || !text || !len) return false; + memset(km, 0, sizeof(*km)); + const char *end = text + len; + + /* 1. the keycodes block: <NAME> = N; */ + static SwKcEntry kc[768]; + int nkc = 0; + const char *kc_end = end; + const char *p = swk_section(text, end, "xkb_keycodes", &kc_end); + if (!p) return false; + for (; p < kc_end && nkc < (int)(sizeof(kc) / sizeof(kc[0])); ++p) { + if (*p != '<') continue; + const char *gt = (const char *)memchr(p, '>', (size_t)(end - p)); + if (!gt || gt - p > 11) continue; + const char *q = swk_skip_ws(gt + 1, end); + if (q >= end || *q != '=') continue; + q = swk_skip_ws(q + 1, end); + uint32_t v = 0; + bool any = false; + while (q < end && *q >= '0' && *q <= '9') { v = v * 10 + (uint32_t)(*q++ - '0'); any = true; } + if (!any) continue; + size_t nl = (size_t)(gt - p - 1); + memcpy(kc[nkc].name, p + 1, nl); + kc[nkc].name[nl] = 0; + kc[nkc].code = v; + nkc++; + p = q; + } + + /* 2. the symbols block: key <NAME> { [ a, A, ... ] }; — the first bracket + * list is group 1, which is the only group handled. */ + const char *sym_end = end; + p = swk_section(text, end, "xkb_symbols", &sym_end); + if (!p) return false; + end = sym_end; /* stay inside the block from here */ + while (p < end) { + const char *k = NULL; + for (const char *s = p; s + 4 < end; ++s) + if (!strncmp(s, "key ", 4) || !strncmp(s, "key\t", 4)) { k = s + 4; break; } + if (!k) break; + k = swk_skip_ws(k, end); + if (k >= end || *k != '<') { p = k + 1; continue; } + const char *gt = (const char *)memchr(k, '>', (size_t)(end - k)); + if (!gt) break; + size_t nl = (size_t)(gt - k - 1); + + uint32_t code = 0; + for (int i = 0; i < nkc; ++i) + if (strlen(kc[i].name) == nl && !memcmp(kc[i].name, k + 1, nl)) { + code = kc[i].code; + break; + } + + const char *semi = (const char *)memchr(gt, ';', (size_t)(end - gt)); + + /* The symbol list, which is not simply the first bracket: a key may + * carry type[Group1]="FOUR_LEVEL" first, and symbols[Group1]= before + * the list itself. The one we want opens straight after a '{' or an + * '=', where those others follow a name. */ + const char *lb = NULL; + for (const char *s = gt; s < end && (!semi || s < semi); ++s) { + if (*s != '[') continue; + const char *b = s - 1; + while (b > gt && (*b == ' ' || *b == '\t')) --b; + if (*b == '{' || *b == '=') { lb = s; break; } + } + if (!lb) { p = semi ? semi + 1 : gt + 1; continue; } + + + const char *rb = (const char *)memchr(lb, ']', (size_t)(end - lb)); + if (!rb) break; + + if (code && code < SW_KEYMAP_MAX) { + int level = 0; + const char *s = lb + 1; + while (s < rb && level < 4) { + s = swk_skip_ws(s, rb); + const char *e2 = s; + while (e2 < rb && *e2 != ',' && *e2 != ' ' && *e2 != '\t' && + *e2 != '\n' && *e2 != '\r') ++e2; + if (e2 > s) km->sym[code][level++] = swk_sym_from_name(s, (size_t)(e2 - s)); + s = (const char *)memchr(e2, ',', (size_t)(rb - e2)); + if (!s) break; + ++s; + } + + /* The keypad is the one key type worth knowing about: its second + * level is chosen by NumLock where every other key uses Shift, + * and getting that wrong makes the number pad type Home for 7. + * Nothing in the file says so — a keymap leaves the type out when + * it can be told from the symbols, which is exactly what this + * is: both levels in the KP_ block. */ + uint32_t a = km->sym[code][0], b2 = km->sym[code][1]; + km->keypad[code] = (a >= 0xff80 && a <= 0xffbd && + b2 >= 0xff80 && b2 <= 0xffbd) ? 1 : 0; + } + p = rb + 1; + } + + km->ok = true; + return true; +} + +unsigned sw_keymap_mods(const SwKeymap *km, uint32_t depressed) +{ + (void)km; + unsigned m = 0; + if (depressed & SWK_SHIFT) m |= 1u; /* SW_MOD_SHIFT */ + if (depressed & SWK_CTRL) m |= 2u; /* SW_MOD_CTRL */ + if (depressed & SWK_MOD1) m |= 4u; /* SW_MOD_ALT */ + if (depressed & SWK_MOD4) m |= 8u; /* SW_MOD_LOGO */ + if (depressed & SWK_MOD5) m |= 16u; /* AltGr, level 3 */ + if (depressed & SWK_LOCK) m |= 32u; /* caps lock */ + if (depressed & SWK_NUM) m |= 64u; /* num lock */ + return m; +} + +uint32_t sw_keymap_lookup(const SwKeymap *km, uint32_t keycode, unsigned mods, + char *utf8, size_t n) +{ + if (utf8 && n) utf8[0] = 0; + if (!km || !km->ok || keycode >= SW_KEYMAP_MAX) return 0; + + bool shift = (mods & 1u) != 0, altgr = (mods & 16u) != 0, caps = (mods & 32u) != 0; + int level = km->keypad[keycode] ? ((mods & 64u) ? 1 : 0) + : ((shift ? 1 : 0) + (altgr ? 2 : 0)); + uint32_t sym = km->sym[keycode][level]; + if (!sym && level) sym = km->sym[keycode][level & 1]; + if (!sym) sym = km->sym[keycode][0]; + + /* Caps lock is shift, but only for letters — it must not turn 1 into !. */ + if (caps && !shift) { + uint32_t plain = km->sym[keycode][altgr ? 2 : 0]; + uint32_t cp = sw_keysym_to_codepoint(plain); + if (cp && cp < 0x250 && cp == (uint32_t)tolower((int)cp)) { + uint32_t up = km->sym[keycode][(altgr ? 2 : 0) + 1]; + if (up) sym = up; + } + } + + if (utf8 && n) { + /* Control does not type: ctrl+c is a shortcut, not a character. */ + if (!(mods & 2u)) swk_utf8(sw_keysym_to_codepoint(sym), utf8, n); + } + return sym; +} + +#endif /* SW_KEYMAP_IMPL_ONCE */ +#endif /* SW_KEYMAP_IMPL */ diff --git a/sw_wl.h b/sw_wl.h new file mode 100644 index 0000000..8f3b0df --- /dev/null +++ b/sw_wl.h @@ -0,0 +1,1021 @@ +/* sw_wl.h — a Wayland layer-shell window with a software canvas in it. + * + * One surface on a layer (overlay, top, ...), a two-buffer shm pool, pointer + * and keyboard from the seat, and a cursor asked for by name. The program + * gets a Canvas to draw into and callbacks for input; nothing here knows what + * is being drawn. + * + * The protocol glue for wlr-layer-shell-unstable-v1 and cursor-shape-v1 is + * vendored below, the same hand-written marshalling swbr has shipped all + * along, so there is no wayland-scanner step and no generated sources in the + * tree. Only libwayland-client is linked. + * + * Keyboard text comes from the keymap the compositor sends, parsed here — see + * sw_keymap.h. No libxkbcommon. + * + * Define SW_WL_IMPL in exactly one translation unit. sw_draw.h must be + * included (with its implementation) by the same program. + * + * Written/modified by: Claude Opus 5 + */ +#ifndef SW_WL_H +#define SW_WL_H + +#include <stdbool.h> +#include <stdint.h> +#include "sw_draw.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct SwWin SwWin; + +typedef enum { + SW_LAYER_BACKGROUND = 0, SW_LAYER_BOTTOM = 1, + SW_LAYER_TOP = 2, SW_LAYER_OVERLAY = 3 +} SwLayer; + +typedef enum { SW_KBD_NONE = 0, SW_KBD_EXCLUSIVE = 1, SW_KBD_ON_DEMAND = 2 } SwKbd; + +enum { SW_ANCHOR_TOP = 1, SW_ANCHOR_BOTTOM = 2, SW_ANCHOR_LEFT = 4, SW_ANCHOR_RIGHT = 8 }; + +/* the cursor-shape-v1 shapes worth naming */ +enum { SW_CURSOR_DEFAULT = 1, SW_CURSOR_POINTER = 10, SW_CURSOR_TEXT = 6, + SW_CURSOR_GRAB = 11, SW_CURSOR_GRABBING = 12 }; + +enum { SW_MOD_SHIFT = 1, SW_MOD_CTRL = 2, SW_MOD_ALT = 4, SW_MOD_LOGO = 8 }; + +typedef struct { + int w, h; /* 0 on an axis anchored both ways = fill it */ + int anchor; /* SW_ANCHOR_* bits; 0 centres the surface */ + SwLayer layer; + SwKbd keyboard; + int exclusive_zone; /* -1 = sit over everything, do not reserve */ + int margin_top, margin_right, margin_bottom, margin_left; + const char *namespace_; /* what the compositor calls it */ + const char *output; /* connector name, NULL = compositor picks */ +} SwWinOpts; + +/* Input as a queue, for a program with its own loop. The callbacks below + * still fire; this is the same events, kept so an immediate-mode draw loop + * can read them where it already reads everything else. Button numbers are + * the Linux input codes Wayland uses. */ +enum { SW_BTN_LEFT = 0x110, SW_BTN_RIGHT = 0x111, SW_BTN_MIDDLE = 0x112 }; + +typedef enum { + SW_EV_NONE = 0, SW_EV_MOTION, SW_EV_BUTTON, SW_EV_AXIS, SW_EV_KEY, + SW_EV_LEAVE, SW_EV_KB_ENTER, SW_EV_KB_LEAVE, SW_EV_CONFIGURE, SW_EV_CLOSED +} SwEvType; + +typedef struct { + SwEvType type; + float x, y; /* motion, button */ + int button; + bool pressed; /* button, key */ + float ax, ay; /* axis, in surface units */ + uint32_t keysym; /* key */ + uint32_t code; /* key: the raw evdev keycode, for the key's + place on the board rather than what it types */ + unsigned mods; + char text[8]; /* what the key typed, "" for none */ + int w, h; /* configure */ +} SwEvent; + +bool sw_poll(SwEvent *out); /* false when the queue is empty */ + +typedef struct { + void *user; + /* Draw a frame. The canvas is already cleared to nothing. */ + void (*paint)(void *user, Canvas *cv, float scale); + void (*pointer_motion)(void *user, float x, float y); + void (*pointer_button)(void *user, int button, bool pressed, float x, float y); + void (*pointer_axis)(void *user, float dx, float dy); + void (*pointer_leave)(void *user); + /* keysym is an X keysym; utf8 is what the key types, "" when it types + nothing. mods is SW_MOD_* bits. */ + void (*key)(void *user, uint32_t keysym, const char *utf8, unsigned mods, + bool pressed); + void (*keyboard_leave)(void *user); + void (*configured)(void *user, int w, int h, float scale); + void (*closed)(void *user); +} SwApp; + +bool sw_init(void); /* connect and bind; false if no display */ +void sw_shutdown(void); +const char *sw_error(void); + +SwWin *sw_win_create(const SwWinOpts *opts, const SwApp *app); +void sw_win_destroy(SwWin *w); +void sw_win_damage(SwWin *w); /* ask for a repaint */ +void sw_win_resize(SwWin *w, int width, int height); +void sw_win_keyboard(SwWin *w, SwKbd k); +void sw_win_cursor(SwWin *w, unsigned shape); +int sw_win_width(const SwWin *w); +int sw_win_height(const SwWin *w); +float sw_win_scale(const SwWin *w); + +/* For a program that drives its own frames — an animation loop rather than + * a repaint on change. Begin hands back the canvas for the next buffer, or + * NULL when the surface is not ready or both buffers are still on screen; + * end attaches and commits it. Between the two, draw. A program that uses + * these leaves app.paint NULL. */ +Canvas *sw_win_begin(SwWin *w); +void sw_win_end(SwWin *w); + +int sw_fd(void); /* the display fd, for your own poll() */ +bool sw_flush(void); +bool sw_dispatch_pending(void); /* handle what has arrived */ +bool sw_dispatch(int timeout_ms); /* poll, read, dispatch, repaint */ +void sw_run(volatile bool *running); + +#ifdef __cplusplus +} +#endif +#endif /* SW_WL_H */ + +/* ===================================================================== */ +#ifdef SW_WL_IMPL +#ifndef SW_WL_IMPL_ONCE +#define SW_WL_IMPL_ONCE + +#include <errno.h> +#include <fcntl.h> +#include <poll.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/mman.h> +#include <unistd.h> +#include <wayland-client.h> + +#include "sw_keymap.h" + +/* ------------------------------------------- cursor-shape-v1 glue */ +/* Vendored equivalent of what wayland-scanner emits for + * cursor-shape-v1.xml. Two interfaces and two requests: ask the compositor + * for a named cursor over our surface, rather than shipping a cursor theme + * and drawing one ourselves. Absent on an older compositor, in which case + * nothing here runs and the pointer keeps whatever shape it had. */ + +struct wp_cursor_shape_manager_v1; +struct wp_cursor_shape_device_v1; + +extern const struct wl_interface wp_cursor_shape_device_v1_interface; + +static const struct wl_interface *sw_cs_types[] = { + NULL, NULL, + &wp_cursor_shape_device_v1_interface, + &wl_pointer_interface, + NULL, NULL, +}; + +static const struct wl_message wp_cursor_shape_manager_v1_requests[] = { + { "destroy", "", sw_cs_types + 0 }, + { "get_pointer", "no", sw_cs_types + 2 }, + { "get_tablet_tool_v2", "no", sw_cs_types + 4 }, +}; +static const struct wl_interface wp_cursor_shape_manager_v1_interface = { + "wp_cursor_shape_manager_v1", 1, 3, wp_cursor_shape_manager_v1_requests, 0, NULL, +}; + +static const struct wl_message wp_cursor_shape_device_v1_requests[] = { + { "destroy", "", sw_cs_types + 0 }, + { "set_shape", "uu", sw_cs_types + 0 }, +}; +const struct wl_interface wp_cursor_shape_device_v1_interface = { + "wp_cursor_shape_device_v1", 1, 2, wp_cursor_shape_device_v1_requests, 0, NULL, +}; + +enum wp_cursor_shape_device_v1_shape { + WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT = 1, + WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_POINTER = 4, +}; + +static struct wp_cursor_shape_device_v1 * +wp_cursor_shape_manager_v1_get_pointer(struct wp_cursor_shape_manager_v1 *m, + struct wl_pointer *p) +{ + struct wl_proxy *id = wl_proxy_marshal_flags( + (struct wl_proxy *)m, 1, &wp_cursor_shape_device_v1_interface, + wl_proxy_get_version((struct wl_proxy *)m), 0, NULL, p); + return (struct wp_cursor_shape_device_v1 *)id; +} + +static void wp_cursor_shape_device_v1_set_shape(struct wp_cursor_shape_device_v1 *d, + uint32_t serial, uint32_t shape) +{ + wl_proxy_marshal_flags((struct wl_proxy *)d, 1, NULL, + wl_proxy_get_version((struct wl_proxy *)d), 0, + serial, shape); +} + +/* ------------------------------------------------- wlr-layer-shell glue */ +/* Vendored equivalent of what wayland-scanner emits for + * wlr-layer-shell-unstable-v1.xml (Copyright (c) 2017 Drew DeVault, MIT-ish; + * see the protocol file for the full notice). Only the requests and events + * we actually use are wrapped; get_popup is present in the table so the + * opcodes line up, but is never called, hence its NULL type entry. */ + +enum zwlr_layer_shell_v1_layer { + ZWLR_LAYER_SHELL_V1_LAYER_BACKGROUND = 0, + ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM = 1, + ZWLR_LAYER_SHELL_V1_LAYER_TOP = 2, + ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY = 3 +}; +enum zwlr_layer_surface_v1_anchor { + ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP = 1, + ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM = 2, + ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT = 4, + ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT = 8 +}; +enum zwlr_layer_surface_v1_keyboard_interactivity { + ZWLR_LAYER_SURFACE_V1_KEYBOARD_INTERACTIVITY_NONE = 0, + ZWLR_LAYER_SURFACE_V1_KEYBOARD_INTERACTIVITY_EXCLUSIVE = 1, + ZWLR_LAYER_SURFACE_V1_KEYBOARD_INTERACTIVITY_ON_DEMAND = 2 +}; + +struct zwlr_layer_shell_v1; +struct zwlr_layer_surface_v1; + +extern const struct wl_interface zwlr_layer_surface_v1_interface; + +static const struct wl_interface *sw_ls_types[] = { + NULL, NULL, NULL, NULL, + &zwlr_layer_surface_v1_interface, + &wl_surface_interface, + &wl_output_interface, + NULL, NULL, NULL, +}; + +static const struct wl_message zwlr_layer_shell_v1_requests[] = { + { "get_layer_surface", "no?ous", sw_ls_types + 4 }, + { "destroy", "3", sw_ls_types + 0 }, +}; +static const struct wl_interface zwlr_layer_shell_v1_interface = { + "zwlr_layer_shell_v1", 4, 2, zwlr_layer_shell_v1_requests, 0, NULL, +}; + +static const struct wl_message zwlr_layer_surface_v1_requests[] = { + { "set_size", "uu", sw_ls_types + 0 }, + { "set_anchor", "u", sw_ls_types + 0 }, + { "set_exclusive_zone", "i", sw_ls_types + 0 }, + { "set_margin", "iiii", sw_ls_types + 0 }, + { "set_keyboard_interactivity", "u", sw_ls_types + 0 }, + { "get_popup", "o", sw_ls_types + 9 }, + { "ack_configure", "u", sw_ls_types + 0 }, + { "destroy", "", sw_ls_types + 0 }, + { "set_layer", "2u", sw_ls_types + 0 }, +}; +static const struct wl_message zwlr_layer_surface_v1_events[] = { + { "configure", "uuu", sw_ls_types + 0 }, + { "closed", "", sw_ls_types + 0 }, +}; +const struct wl_interface zwlr_layer_surface_v1_interface = { + "zwlr_layer_surface_v1", 4, 9, zwlr_layer_surface_v1_requests, + 2, zwlr_layer_surface_v1_events, +}; + +struct zwlr_layer_surface_v1_listener { + void (*configure)(void *data, struct zwlr_layer_surface_v1 *s, + uint32_t serial, uint32_t width, uint32_t height); + void (*closed)(void *data, struct zwlr_layer_surface_v1 *s); +}; + +#define LS_REQ_SET_SIZE 0 +#define LS_REQ_SET_ANCHOR 1 +#define LS_REQ_SET_EXCLUSIVE 2 +#define LS_REQ_SET_MARGIN 3 +#define LS_REQ_SET_KBD 4 +#define LS_REQ_ACK_CONFIGURE 6 +#define LS_REQ_DESTROY 7 + +static struct zwlr_layer_surface_v1 * +zwlr_layer_shell_v1_get_layer_surface(struct zwlr_layer_shell_v1 *shell, + struct wl_surface *surface, + struct wl_output *output, + uint32_t layer, const char *ns) +{ + struct wl_proxy *id = wl_proxy_marshal_flags( + (struct wl_proxy *)shell, 0, &zwlr_layer_surface_v1_interface, + wl_proxy_get_version((struct wl_proxy *)shell), 0, + NULL, surface, output, layer, ns); + return (struct zwlr_layer_surface_v1 *)id; +} + +static int zwlr_layer_surface_v1_add_listener(struct zwlr_layer_surface_v1 *s, + const struct zwlr_layer_surface_v1_listener *l, + void *data) +{ + return wl_proxy_add_listener((struct wl_proxy *)s, (void (**)(void))l, data); +} + +static void ls_set_size(struct zwlr_layer_surface_v1 *s, uint32_t w, uint32_t h) +{ wl_proxy_marshal_flags((struct wl_proxy *)s, LS_REQ_SET_SIZE, NULL, + wl_proxy_get_version((struct wl_proxy *)s), 0, w, h); } +static void ls_set_anchor(struct zwlr_layer_surface_v1 *s, uint32_t a) +{ wl_proxy_marshal_flags((struct wl_proxy *)s, LS_REQ_SET_ANCHOR, NULL, + wl_proxy_get_version((struct wl_proxy *)s), 0, a); } +static void ls_set_exclusive_zone(struct zwlr_layer_surface_v1 *s, int32_t z) +{ wl_proxy_marshal_flags((struct wl_proxy *)s, LS_REQ_SET_EXCLUSIVE, NULL, + wl_proxy_get_version((struct wl_proxy *)s), 0, z); } +static void ls_set_margin(struct zwlr_layer_surface_v1 *s, int32_t t, int32_t r, + int32_t b, int32_t l) +{ wl_proxy_marshal_flags((struct wl_proxy *)s, LS_REQ_SET_MARGIN, NULL, + wl_proxy_get_version((struct wl_proxy *)s), 0, t, r, b, l); } +static void ls_set_keyboard(struct zwlr_layer_surface_v1 *s, uint32_t k) +{ wl_proxy_marshal_flags((struct wl_proxy *)s, LS_REQ_SET_KBD, NULL, + wl_proxy_get_version((struct wl_proxy *)s), 0, k); } +static void ls_ack_configure(struct zwlr_layer_surface_v1 *s, uint32_t serial) +{ wl_proxy_marshal_flags((struct wl_proxy *)s, LS_REQ_ACK_CONFIGURE, NULL, + wl_proxy_get_version((struct wl_proxy *)s), 0, serial); } +static void ls_destroy(struct zwlr_layer_surface_v1 *s) +{ wl_proxy_marshal_flags((struct wl_proxy *)s, LS_REQ_DESTROY, NULL, + wl_proxy_get_version((struct wl_proxy *)s), + WL_MARSHAL_FLAG_DESTROY); } + + +/* --------------------------------------------------------------- state */ + +/* Under -std=c11 the libc headers hide these, and a feature macro set in a + * header that is included after the program's own would come too late to do + * anything. They are POSIX and Linux; these are their real declarations. */ +#if defined(__STRICT_ANSI__) +int memfd_create(const char *name, unsigned int flags); +int ftruncate(int fd, off_t length); +#ifndef MFD_CLOEXEC +#define MFD_CLOEXEC 0x0001U +#endif +#endif + +static struct wl_display *SWD; +static struct wl_registry *SWREG; +static struct wl_compositor *SWCOMP; +static struct wl_shm *SWSHM; +static struct wl_seat *SWSEAT; +static struct zwlr_layer_shell_v1 *SWSHELL; +static struct wp_cursor_shape_manager_v1 *SWCSM; +static struct wl_pointer *SWPTR; +static struct wl_keyboard *SWKBD; +static struct wp_cursor_shape_device_v1 *SWCSD; +static uint32_t SWPTR_SERIAL; +static char SWERR[256]; + +/* Outputs, only so a window can ask for one by connector name. */ +typedef struct { + struct wl_output *out; + uint32_t name; + char conn[64]; + int32_t scale; +} SwOutput; +static SwOutput SWOUT[8]; +static int SWOUT_N; + +#define SW_MAX_WIN 4 +static SwWin *SWWINS[SW_MAX_WIN]; +static int SWWIN_N; +static SwWin *SW_PTR_WIN; /* the one the pointer is over */ +static SwWin *SW_KBD_WIN; /* the one with keyboard focus */ + +struct SwWin { + struct wl_surface *surf; + struct zwlr_layer_surface_v1 *ls; + SwApp app; + SwWinOpts opts; + + int w, h; /* logical */ + int scale; + bool configured, dirty, closed; + + struct wl_shm_pool *pool; + void *pool_data; + size_t pool_size; + struct wl_buffer *buf[2]; + void *bufmem[2]; + bool busy[2]; + int bw, bh, stride; + + unsigned cursor; + int slot; /* the buffer sw_win_begin handed out */ +}; + +const char *sw_error(void) { return SWERR; } + +/* A ring, deliberately small: these are human-speed events and a frame drains + * it. Dropping the oldest on overflow is better than growing without bound. */ +#define SW_EVQ 128 +static SwEvent SW_Q[SW_EVQ]; +static int SW_QH, SW_QT; + +static void sw_push(const SwEvent *e) +{ + int next = (SW_QT + 1) % SW_EVQ; + if (next == SW_QH) SW_QH = (SW_QH + 1) % SW_EVQ; /* drop the oldest */ + SW_Q[SW_QT] = *e; + SW_QT = next; +} + +bool sw_poll(SwEvent *out) +{ + if (SW_QH == SW_QT) return false; + *out = SW_Q[SW_QH]; + SW_QH = (SW_QH + 1) % SW_EVQ; + return true; +} + +/* -------------------------------------------------------------- buffers */ + +static void sw_buffer_release(void *data, struct wl_buffer *b) +{ + SwWin *w = (SwWin *)data; + for (int i = 0; i < 2; ++i) if (w->buf[i] == b) w->busy[i] = false; +} +static const struct wl_buffer_listener sw_buffer_listener = { sw_buffer_release }; + +static void sw_free_buffers(SwWin *w) +{ + for (int i = 0; i < 2; ++i) { + if (w->buf[i]) wl_buffer_destroy(w->buf[i]); + w->buf[i] = NULL; + w->busy[i] = false; + w->bufmem[i] = NULL; + } + if (w->pool) wl_shm_pool_destroy(w->pool); + w->pool = NULL; + if (w->pool_data) munmap(w->pool_data, w->pool_size); + w->pool_data = NULL; + w->pool_size = 0; +} + +static int sw_anon_shm(size_t size) +{ + int fd = memfd_create("sw_wl", MFD_CLOEXEC); + if (fd < 0) return -1; + if (ftruncate(fd, (off_t)size) < 0) { close(fd); return -1; } + return fd; +} + +/* Two buffers in one pool: one on screen while the next is drawn. */ +static bool sw_alloc(SwWin *w) +{ + int bw = w->w * w->scale, bh = w->h * w->scale; + if (bw <= 0 || bh <= 0) return false; + if (w->pool && w->bw == bw && w->bh == bh) return true; + + sw_free_buffers(w); + w->bw = bw; + w->bh = bh; + w->stride = bw * 4; + size_t one = (size_t)w->stride * (size_t)bh; + size_t total = one * 2; + + int fd = sw_anon_shm(total); + if (fd < 0) return false; + void *mem = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (mem == MAP_FAILED) { close(fd); return false; } + + w->pool_data = mem; + w->pool_size = total; + w->pool = wl_shm_create_pool(SWSHM, fd, (int32_t)total); + close(fd); + for (int i = 0; i < 2; ++i) { + w->buf[i] = wl_shm_pool_create_buffer(w->pool, (int32_t)(one * (size_t)i), + bw, bh, w->stride, + WL_SHM_FORMAT_ARGB8888); + w->bufmem[i] = (char *)mem + one * (size_t)i; + w->busy[i] = false; + wl_buffer_add_listener(w->buf[i], &sw_buffer_listener, w); + } + return true; +} + +/* ---------------------------------------------------------------- paint */ + +static void sw_repaint(SwWin *w) +{ + if (!w->configured || w->closed || !w->app.paint) return; + if (!sw_alloc(w)) return; + + int slot = -1; + for (int i = 0; i < 2; ++i) if (!w->busy[i]) { slot = i; break; } + if (slot < 0) return; /* both in flight; try again */ + + Canvas cv = { (uint32_t *)w->bufmem[slot], w->bw, w->bh, + 0, 0, w->bw, w->bh }; + memset(cv.px, 0, (size_t)w->stride * (size_t)w->bh); + w->app.paint(w->app.user, &cv, (float)w->scale); + + wl_surface_set_buffer_scale(w->surf, w->scale); + wl_surface_attach(w->surf, w->buf[slot], 0, 0); + wl_surface_damage_buffer(w->surf, 0, 0, w->bw, w->bh); + wl_surface_commit(w->surf); + w->busy[slot] = true; + w->dirty = false; +} + +Canvas *sw_win_begin(SwWin *w) +{ + static Canvas cv; + if (!w || !w->configured || w->closed) return NULL; + if (!sw_alloc(w)) return NULL; + int slot = -1; + for (int i = 0; i < 2; ++i) if (!w->busy[i]) { slot = i; break; } + if (slot < 0) return NULL; /* both in flight; skip a frame */ + w->slot = slot; + cv.px = (uint32_t *)w->bufmem[slot]; + cv.w = w->bw; + cv.h = w->bh; + cv.cx0 = 0; cv.cy0 = 0; cv.cx1 = w->bw; cv.cy1 = w->bh; + memset(cv.px, 0, (size_t)w->stride * (size_t)w->bh); + return &cv; +} + +void sw_win_end(SwWin *w) +{ + if (!w || w->slot < 0) return; + wl_surface_set_buffer_scale(w->surf, w->scale); + wl_surface_attach(w->surf, w->buf[w->slot], 0, 0); + wl_surface_damage_buffer(w->surf, 0, 0, w->bw, w->bh); + wl_surface_commit(w->surf); + w->busy[w->slot] = true; + w->slot = -1; + w->dirty = false; +} + +void sw_win_damage(SwWin *w) { if (w) w->dirty = true; } +int sw_win_width(const SwWin *w) { return w ? w->w : 0; } +int sw_win_height(const SwWin *w) { return w ? w->h : 0; } +float sw_win_scale(const SwWin *w) { return w ? (float)w->scale : 1.0f; } + +/* -------------------------------------------------------- layer surface */ + +static void sw_ls_configure(void *data, struct zwlr_layer_surface_v1 *ls, + uint32_t serial, uint32_t width, uint32_t height) +{ + SwWin *w = (SwWin *)data; + ls_ack_configure(ls, serial); + bool changed = (width && (int)width != w->w) || + (height && (int)height != w->h) || !w->configured; + if (width) w->w = (int)width; + if (height) w->h = (int)height; + w->configured = true; + if (!changed) return; + SwEvent e = { .type = SW_EV_CONFIGURE, .w = w->w, .h = w->h }; + sw_push(&e); + if (w->app.configured) w->app.configured(w->app.user, w->w, w->h, (float)w->scale); + w->dirty = true; + sw_repaint(w); +} + +static void sw_ls_closed(void *data, struct zwlr_layer_surface_v1 *ls) +{ + (void)ls; + SwWin *w = (SwWin *)data; + w->closed = true; + SwEvent e = { .type = SW_EV_CLOSED }; + sw_push(&e); + if (w->app.closed) w->app.closed(w->app.user); +} + +static const struct zwlr_layer_surface_v1_listener sw_ls_listener = { + sw_ls_configure, sw_ls_closed +}; + +/* The output's scale reaches us after the surface exists, so a window on a + * HiDPI screen is created at 1x and re-allocated when the real figure lands. */ +static void sw_surf_enter(void *data, struct wl_surface *s, struct wl_output *o) +{ + (void)s; + SwWin *w = (SwWin *)data; + for (int i = 0; i < SWOUT_N; ++i) + if (SWOUT[i].out == o && SWOUT[i].scale > 0 && SWOUT[i].scale != w->scale) { + w->scale = SWOUT[i].scale; + w->dirty = true; + } +} +static void sw_surf_leave(void *data, struct wl_surface *s, struct wl_output *o) +{ (void)data; (void)s; (void)o; } +static const struct wl_surface_listener sw_surf_listener = { + sw_surf_enter, sw_surf_leave, NULL, NULL +}; + +SwWin *sw_win_create(const SwWinOpts *opts, const SwApp *app) +{ + if (!SWCOMP || !SWSHELL || !SWSHM) { + snprintf(SWERR, sizeof(SWERR), "compositor is missing layer-shell or shm"); + return NULL; + } + if (SWWIN_N >= SW_MAX_WIN) return NULL; + + SwWin *w = (SwWin *)calloc(1, sizeof(*w)); + if (!w) return NULL; + w->opts = *opts; + if (app) w->app = *app; /* NULL: the program drives its own frames */ + w->scale = 1; + w->slot = -1; + w->w = opts->w; + w->h = opts->h; + w->cursor = SW_CURSOR_DEFAULT; + + struct wl_output *on = NULL; + if (opts->output && *opts->output) + for (int i = 0; i < SWOUT_N; ++i) + if (!strcmp(SWOUT[i].conn, opts->output)) { on = SWOUT[i].out; break; } + + w->surf = wl_compositor_create_surface(SWCOMP); + wl_surface_add_listener(w->surf, &sw_surf_listener, w); + w->ls = zwlr_layer_shell_v1_get_layer_surface( + SWSHELL, w->surf, on, (uint32_t)opts->layer, + opts->namespace_ ? opts->namespace_ : "sw"); + zwlr_layer_surface_v1_add_listener(w->ls, &sw_ls_listener, w); + ls_set_size(w->ls, (uint32_t)(opts->w > 0 ? opts->w : 0), + (uint32_t)(opts->h > 0 ? opts->h : 0)); + ls_set_anchor(w->ls, (uint32_t)opts->anchor); + ls_set_exclusive_zone(w->ls, opts->exclusive_zone); + ls_set_margin(w->ls, opts->margin_top, opts->margin_right, + opts->margin_bottom, opts->margin_left); + ls_set_keyboard(w->ls, (uint32_t)opts->keyboard); + wl_surface_commit(w->surf); + + SWWINS[SWWIN_N++] = w; + return w; +} + +void sw_win_destroy(SwWin *w) +{ + if (!w) return; + for (int i = 0; i < SWWIN_N; ++i) + if (SWWINS[i] == w) { SWWINS[i] = SWWINS[--SWWIN_N]; break; } + if (SW_PTR_WIN == w) SW_PTR_WIN = NULL; + if (SW_KBD_WIN == w) SW_KBD_WIN = NULL; + sw_free_buffers(w); + if (w->ls) ls_destroy(w->ls); + if (w->surf) wl_surface_destroy(w->surf); + free(w); +} + +void sw_win_resize(SwWin *w, int width, int height) +{ + if (!w || !w->ls) return; + ls_set_size(w->ls, (uint32_t)(width > 0 ? width : 0), + (uint32_t)(height > 0 ? height : 0)); + wl_surface_commit(w->surf); +} + +void sw_win_keyboard(SwWin *w, SwKbd k) +{ + if (!w || !w->ls) return; + ls_set_keyboard(w->ls, (uint32_t)k); + wl_surface_commit(w->surf); +} + +void sw_win_cursor(SwWin *w, unsigned shape) +{ + if (!w) return; + w->cursor = shape; + if (SWCSD && SW_PTR_WIN == w && SWPTR_SERIAL) + wp_cursor_shape_device_v1_set_shape(SWCSD, SWPTR_SERIAL, shape); +} + +/* --------------------------------------------------------------- input */ + +static SwWin *sw_win_of(struct wl_surface *s) +{ + for (int i = 0; i < SWWIN_N; ++i) if (SWWINS[i]->surf == s) return SWWINS[i]; + return NULL; +} + +static double SW_PX, SW_PY; + + + +static void sw_ptr_enter(void *d, struct wl_pointer *p, uint32_t serial, + struct wl_surface *s, wl_fixed_t x, wl_fixed_t y) +{ + (void)d; (void)p; + SwWin *w = sw_win_of(s); + if (!w) return; + SW_PTR_WIN = w; + SWPTR_SERIAL = serial; + SW_PX = wl_fixed_to_double(x); + SW_PY = wl_fixed_to_double(y); + if (SWCSD) wp_cursor_shape_device_v1_set_shape(SWCSD, serial, w->cursor); + SwEvent e = { .type = SW_EV_MOTION, .x = (float)SW_PX, .y = (float)SW_PY }; + sw_push(&e); + if (w->app.pointer_motion) w->app.pointer_motion(w->app.user, (float)SW_PX, (float)SW_PY); +} + +static void sw_ptr_leave(void *d, struct wl_pointer *p, uint32_t serial, + struct wl_surface *s) +{ + (void)d; (void)p; (void)serial; + SwWin *w = sw_win_of(s); + if (!w) return; + /* A leave for a surface we already left, arriving after the enter for + another, must not clear the pointer from the one we are on. */ + if (SW_PTR_WIN == w) SW_PTR_WIN = NULL; + SwEvent e = { .type = SW_EV_LEAVE }; + sw_push(&e); + if (w->app.pointer_leave) w->app.pointer_leave(w->app.user); +} + +static void sw_ptr_motion(void *d, struct wl_pointer *p, uint32_t t, + wl_fixed_t x, wl_fixed_t y) +{ + (void)d; (void)p; (void)t; + SW_PX = wl_fixed_to_double(x); + SW_PY = wl_fixed_to_double(y); + SwWin *w = SW_PTR_WIN; + SwEvent e = { .type = SW_EV_MOTION, .x = (float)SW_PX, .y = (float)SW_PY }; + sw_push(&e); + if (w && w->app.pointer_motion) + w->app.pointer_motion(w->app.user, (float)SW_PX, (float)SW_PY); +} + +static void sw_ptr_button(void *d, struct wl_pointer *p, uint32_t serial, + uint32_t t, uint32_t button, uint32_t state) +{ + (void)d; (void)p; (void)t; + SWPTR_SERIAL = serial; + SwWin *w = SW_PTR_WIN; + SwEvent e = { .type = SW_EV_BUTTON, .x = (float)SW_PX, .y = (float)SW_PY, + .button = (int)button, .pressed = state != 0 }; + sw_push(&e); + if (w && w->app.pointer_button) + w->app.pointer_button(w->app.user, (int)button, state != 0, + (float)SW_PX, (float)SW_PY); +} + +static void sw_ptr_axis(void *d, struct wl_pointer *p, uint32_t t, + uint32_t axis, wl_fixed_t value) +{ + (void)d; (void)p; (void)t; + SwWin *w = SW_PTR_WIN; + double v = wl_fixed_to_double(value); + SwEvent e = { .type = SW_EV_AXIS }; + if (axis == WL_POINTER_AXIS_VERTICAL_SCROLL) e.ay = (float)v; else e.ax = (float)v; + sw_push(&e); + if (!w || !w->app.pointer_axis) return; + if (axis == WL_POINTER_AXIS_VERTICAL_SCROLL) w->app.pointer_axis(w->app.user, 0.0f, (float)v); + else w->app.pointer_axis(w->app.user, (float)v, 0.0f); +} + +static void sw_ptr_frame(void *d, struct wl_pointer *p) { (void)d; (void)p; } +static void sw_ptr_axis_src(void *d, struct wl_pointer *p, uint32_t s) { (void)d; (void)p; (void)s; } +static void sw_ptr_axis_stop(void *d, struct wl_pointer *p, uint32_t t, uint32_t a) +{ (void)d; (void)p; (void)t; (void)a; } +static void sw_ptr_axis_disc(void *d, struct wl_pointer *p, uint32_t a, int32_t v) +{ (void)d; (void)p; (void)a; (void)v; } +static void sw_ptr_axis_v120(void *d, struct wl_pointer *p, uint32_t a, int32_t v) +{ (void)d; (void)p; (void)a; (void)v; } +static void sw_ptr_axis_rel(void *d, struct wl_pointer *p, uint32_t a, uint32_t dir) +{ (void)d; (void)p; (void)a; (void)dir; } + +static const struct wl_pointer_listener sw_ptr_listener = { + sw_ptr_enter, sw_ptr_leave, sw_ptr_motion, sw_ptr_button, sw_ptr_axis, + sw_ptr_frame, sw_ptr_axis_src, sw_ptr_axis_stop, sw_ptr_axis_disc, + sw_ptr_axis_v120, sw_ptr_axis_rel +}; + +/* ------------------------------------------------------------ keyboard */ + +static SwKeymap SW_KEYMAP; +static unsigned SW_MODS; + +static void sw_kbd_keymap(void *d, struct wl_keyboard *k, uint32_t format, + int32_t fd, uint32_t size) +{ + (void)d; (void)k; + if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) { close(fd); return; } + char *text = (char *)mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0); + if (text != MAP_FAILED) { + sw_keymap_parse(&SW_KEYMAP, text, size); + munmap(text, size); + } + close(fd); +} + +static void sw_kbd_enter(void *d, struct wl_keyboard *k, uint32_t serial, + struct wl_surface *s, struct wl_array *keys) +{ + (void)d; (void)k; (void)serial; (void)keys; + SW_KBD_WIN = sw_win_of(s); + SwEvent e = { .type = SW_EV_KB_ENTER }; + sw_push(&e); +} + +static void sw_kbd_leave(void *d, struct wl_keyboard *k, uint32_t serial, + struct wl_surface *s) +{ + (void)d; (void)k; (void)serial; + SwWin *w = sw_win_of(s); + SwEvent e = { .type = SW_EV_KB_LEAVE }; + sw_push(&e); + if (w && w->app.keyboard_leave) w->app.keyboard_leave(w->app.user); + if (SW_KBD_WIN == w) SW_KBD_WIN = NULL; +} + +static void sw_kbd_key(void *d, struct wl_keyboard *k, uint32_t serial, + uint32_t time, uint32_t key, uint32_t state) +{ + (void)d; (void)k; (void)serial; (void)time; + SwWin *w = SW_KBD_WIN; + char utf8[8] = ""; + uint32_t sym = sw_keymap_lookup(&SW_KEYMAP, key + 8, SW_MODS, utf8, sizeof(utf8)); + SwEvent e = { .type = SW_EV_KEY, .keysym = sym, .code = key, .mods = SW_MODS, + .pressed = state != 0 }; + memcpy(e.text, utf8, sizeof(e.text)); + sw_push(&e); + if (!w || !w->app.key) return; + w->app.key(w->app.user, sym, utf8, SW_MODS, state != 0); +} + +static void sw_kbd_mods(void *d, struct wl_keyboard *k, uint32_t serial, + uint32_t dep, uint32_t latched, uint32_t locked, uint32_t group) +{ + (void)d; (void)k; (void)serial; (void)latched; (void)group; + SW_MODS = sw_keymap_mods(&SW_KEYMAP, dep | locked); +} + +static void sw_kbd_rep(void *d, struct wl_keyboard *k, int32_t rate, int32_t delay) +{ (void)d; (void)k; (void)rate; (void)delay; } + +static const struct wl_keyboard_listener sw_kbd_listener = { + sw_kbd_keymap, sw_kbd_enter, sw_kbd_leave, sw_kbd_key, sw_kbd_mods, sw_kbd_rep +}; + +static void sw_seat_caps(void *d, struct wl_seat *seat, uint32_t caps) +{ + (void)d; + if ((caps & WL_SEAT_CAPABILITY_POINTER) && !SWPTR) { + SWPTR = wl_seat_get_pointer(seat); + wl_pointer_add_listener(SWPTR, &sw_ptr_listener, NULL); + if (SWCSM) SWCSD = wp_cursor_shape_manager_v1_get_pointer(SWCSM, SWPTR); + } + if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !SWKBD) { + SWKBD = wl_seat_get_keyboard(seat); + wl_keyboard_add_listener(SWKBD, &sw_kbd_listener, NULL); + } +} +static void sw_seat_name(void *d, struct wl_seat *s, const char *n) +{ (void)d; (void)s; (void)n; } +static const struct wl_seat_listener sw_seat_listener = { sw_seat_caps, sw_seat_name }; + +/* -------------------------------------------------------------- outputs */ + +static void sw_out_geom(void *d, struct wl_output *o, int32_t x, int32_t y, + int32_t pw, int32_t ph, int32_t sub, const char *make, + const char *model, int32_t tr) +{ (void)d; (void)o; (void)x; (void)y; (void)pw; (void)ph; (void)sub; + (void)make; (void)model; (void)tr; } +static void sw_out_mode(void *d, struct wl_output *o, uint32_t f, + int32_t w, int32_t h, int32_t r) +{ (void)d; (void)o; (void)f; (void)w; (void)h; (void)r; } +static void sw_out_done(void *d, struct wl_output *o) { (void)d; (void)o; } +static void sw_out_scale(void *d, struct wl_output *o, int32_t s) +{ + (void)d; + for (int i = 0; i < SWOUT_N; ++i) if (SWOUT[i].out == o) SWOUT[i].scale = s; +} +static void sw_out_name(void *d, struct wl_output *o, const char *name) +{ + (void)d; + for (int i = 0; i < SWOUT_N; ++i) + if (SWOUT[i].out == o) snprintf(SWOUT[i].conn, sizeof(SWOUT[i].conn), "%s", name); +} +static void sw_out_desc(void *d, struct wl_output *o, const char *desc) +{ (void)d; (void)o; (void)desc; } +static const struct wl_output_listener sw_out_listener = { + sw_out_geom, sw_out_mode, sw_out_done, sw_out_scale, sw_out_name, sw_out_desc +}; + +/* ------------------------------------------------------------- registry */ + +static void sw_reg_global(void *d, struct wl_registry *r, uint32_t name, + const char *iface, uint32_t ver) +{ + (void)d; + if (!strcmp(iface, "wl_compositor")) + SWCOMP = (struct wl_compositor *)wl_registry_bind(r, name, &wl_compositor_interface, + ver < 4 ? ver : 4); + else if (!strcmp(iface, "wl_shm")) + SWSHM = (struct wl_shm *)wl_registry_bind(r, name, &wl_shm_interface, 1); + else if (!strcmp(iface, "zwlr_layer_shell_v1")) + SWSHELL = (struct zwlr_layer_shell_v1 *)wl_registry_bind( + r, name, &zwlr_layer_shell_v1_interface, ver < 4 ? ver : 4); + else if (!strcmp(iface, "wp_cursor_shape_manager_v1")) + SWCSM = (struct wp_cursor_shape_manager_v1 *)wl_registry_bind( + r, name, &wp_cursor_shape_manager_v1_interface, 1); + else if (!strcmp(iface, "wl_seat")) { + SWSEAT = (struct wl_seat *)wl_registry_bind(r, name, &wl_seat_interface, + ver < 5 ? ver : 5); + wl_seat_add_listener(SWSEAT, &sw_seat_listener, NULL); + } else if (!strcmp(iface, "wl_output") && SWOUT_N < 8) { + SwOutput *o = &SWOUT[SWOUT_N++]; + memset(o, 0, sizeof(*o)); + o->name = name; + o->scale = 1; + o->out = (struct wl_output *)wl_registry_bind(r, name, &wl_output_interface, + ver < 4 ? ver : 4); + wl_output_add_listener(o->out, &sw_out_listener, NULL); + } +} + +static void sw_reg_remove(void *d, struct wl_registry *r, uint32_t name) +{ + (void)d; (void)r; + for (int i = 0; i < SWOUT_N; ++i) + if (SWOUT[i].name == name) { + wl_output_destroy(SWOUT[i].out); + SWOUT[i] = SWOUT[--SWOUT_N]; + break; + } +} +static const struct wl_registry_listener sw_reg_listener = { sw_reg_global, sw_reg_remove }; + +/* ------------------------------------------------------------ lifecycle */ + +bool sw_init(void) +{ + SWD = wl_display_connect(NULL); + if (!SWD) { + snprintf(SWERR, sizeof(SWERR), + "cannot reach a Wayland compositor (is WAYLAND_DISPLAY set?)"); + return false; + } + SWREG = wl_display_get_registry(SWD); + wl_registry_add_listener(SWREG, &sw_reg_listener, NULL); + wl_display_roundtrip(SWD); /* globals */ + wl_display_roundtrip(SWD); /* and what they send back: seat caps, names */ + + if (!SWCOMP || !SWSHM) { + snprintf(SWERR, sizeof(SWERR), "compositor has no wl_compositor or wl_shm"); + return false; + } + if (!SWSHELL) { + snprintf(SWERR, sizeof(SWERR), + "compositor does not support wlr-layer-shell; sway and the " + "wlroots compositors do"); + return false; + } + return true; +} + +void sw_shutdown(void) +{ + while (SWWIN_N) sw_win_destroy(SWWINS[0]); + if (SWPTR) wl_pointer_destroy(SWPTR); + if (SWKBD) wl_keyboard_destroy(SWKBD); + if (SWD) wl_display_disconnect(SWD); + SWD = NULL; +} + +int sw_fd(void) { return SWD ? wl_display_get_fd(SWD) : -1; } +bool sw_flush(void) { return SWD && wl_display_flush(SWD) != -1; } + +static void sw_paint_dirty(void) +{ + for (int i = 0; i < SWWIN_N; ++i) + if (SWWINS[i]->dirty) sw_repaint(SWWINS[i]); +} + +bool sw_dispatch_pending(void) +{ + if (!SWD) return false; + if (wl_display_dispatch_pending(SWD) < 0) return false; + sw_paint_dirty(); + return wl_display_flush(SWD) != -1; +} + +bool sw_dispatch(int timeout_ms) +{ + if (!SWD) return false; + sw_paint_dirty(); + + while (wl_display_prepare_read(SWD) != 0) + if (wl_display_dispatch_pending(SWD) < 0) return false; + if (wl_display_flush(SWD) < 0 && errno != EAGAIN) { + wl_display_cancel_read(SWD); + return false; + } + + struct pollfd pfd = { wl_display_get_fd(SWD), POLLIN, 0 }; + int n = poll(&pfd, 1, timeout_ms); + if (n > 0 && (pfd.revents & POLLIN)) { + if (wl_display_read_events(SWD) < 0) return false; + } else { + wl_display_cancel_read(SWD); + if (n < 0 && errno != EINTR) return false; + } + if (wl_display_dispatch_pending(SWD) < 0) return false; + sw_paint_dirty(); + return true; +} + +void sw_run(volatile bool *running) +{ + while (*running && sw_dispatch(-1)) { } +} + +#endif /* SW_WL_IMPL_ONCE */ +#endif /* SW_WL_IMPL */ diff --git a/swas.c b/swas.c index e2837d2..7ccdf7f 100644 --- a/swas.c +++ b/swas.c @@ -1,15 +1,19 @@ /* - * swas — Sway App Selector: a radial (weapon-wheel) app launcher, Wayland & X11. + * swas — Sway App Selector: a radial (weapon-wheel) app launcher for Wayland. + * + * Written/modified by: Claude Opus 4.1, Claude Sonnet 4.5, Claude Opus 5 * * Dependencies: - * - SDL3 (the only library you link) + * - libwayland-client (the only library you link) + * - sw_draw.h / sw_wl.h / sw_keymap.h (in-tree: rasteriser, layer-shell + * window, keymap — shared with swbr and swov) * - stb_truetype.h (vendored single-header — smooth fonts) * - stb_image.h (vendored single-header — PNG/JPG/BMP icons) * - nanosvg.h + nanosvgrast.h (vendored single-header — SVG icons) * The vendored *.h files just sit next to this source; nothing to install/link. * * Build: - * cc swas.c -o swas $(pkg-config --cflags --libs sdl3) -lm + * cc swas.c -o swas -lwayland-client -lm * * See --help for every option (all config keys also work on the command line). */ @@ -27,7 +31,8 @@ * 9. main() setup, then the event + render loop * ------------------------------------------------------------------------- */ -#include <SDL3/SDL.h> +#define _POSIX_C_SOURCE 200809L +#define _GNU_SOURCE #define STB_TRUETYPE_IMPLEMENTATION #include "stb_truetype.h" @@ -39,9 +44,20 @@ #include "sw_theme.h" +/* The window, the canvas and the keyboard. swas draws every pixel itself, so + there is no renderer and no GPU: a layer-shell surface with a shared memory + buffer, filled in by hand. */ +#define SW_DRAW_IMPL +#include "sw_draw.h" +typedef struct { float x,y,w,h; } Rect; +#define SW_KEYMAP_IMPL +#include "sw_keymap.h" +#define SW_WL_IMPL +#include "sw_wl.h" + #define APP_ID "swas" /* wayland app_id / X11 WM_CLASS */ -#define SWAS_VERSION "1.2" +#define SWAS_VERSION "1.3" #ifndef SWAS_BUILD /* set by the Makefile: md5 of this file */ #define SWAS_BUILD "unknown" #endif @@ -68,6 +84,7 @@ #include <dirent.h> #include <glob.h> #include <unistd.h> +#include <time.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> @@ -85,8 +102,7 @@ #define ICON_AR (60.0f*(float)DEG) /* bottom-right paging icon */ /* ------------------------------------------------------------------ */ -typedef struct { Uint8 r, g, b, a; } Col; -static SDL_FColor tofc(Col c){ SDL_FColor f={c.r/255.0f,c.g/255.0f,c.b/255.0f,c.a/255.0f}; return f; } +/* Col comes from sw_draw.h — the canvas and this file agree on it. */ static char *xstrdup(const char *s){ char*p=malloc(strlen(s)+1); if(p)strcpy(p,s); return p; } static char *trim(char *s){ while(*s && isspace((unsigned char)*s)) s++; @@ -106,7 +122,7 @@ static void parse_color(const char*s, Col*out){ if(strlen(s)>=8 && sscanf(s,"%2x%2x%2x%2x",&r,&g,&b,&a)==4){} else if(sscanf(s,"%2x%2x%2x",&r,&g,&b)==3){} else return; - out->r=(Uint8)r; out->g=(Uint8)g; out->b=(Uint8)b; out->a=(Uint8)a; + out->r=(uint8_t)r; out->g=(uint8_t)g; out->b=(uint8_t)b; out->a=(uint8_t)a; } static int file_exists(const char*p){ struct stat st; return stat(p,&st)==0 && S_ISREG(st.st_mode); } static float clampf(float v,float lo,float hi){ return v<lo?lo:(v>hi?hi:v); } @@ -287,16 +303,14 @@ static void config_load(Config*c,const char*path){ } /* ------------------------------------------------------------------ */ -/* text: TTF atlas via stb_truetype, with debug-font fallback */ +/* text: sw_draw's glyph cache */ /* ------------------------------------------------------------------ */ -#define GLYPH_LO 32 -#define GLYPH_HI 255 -#define NGLYPH (GLYPH_HI-GLYPH_LO+1) - -typedef struct { - int ok; SDL_Texture *atlas; int px; float baseline; - struct { float u,v,w,h,xoff,yoff,adv; } g[NGLYPH]; -} Font; +/* There used to be an atlas here: every glyph rasterised once at one size + into a texture, then scaled. sw_draw caches per pixel size instead and + rasterises a glyph the first time it is asked for, so text at any size is + sharp rather than a scaled-up copy of one size. What is left is the old + call shape, because a hundred call sites are written against it. */ +typedef struct { int ok; int px; } UiFont; static int try_font_paths(char*out,size_t n){ const char*cand[]={ @@ -333,103 +347,32 @@ static int fc_match(const char*pattern,char*out,size_t n){ return 0; } -static int font_load(Font*ft,SDL_Renderer*ren,const char*path,int px){ - memset(ft,0,sizeof *ft); ft->px=px; - FILE*f=fopen(path,"rb"); if(!f) return 0; - fseek(f,0,SEEK_END); long sz=ftell(f); fseek(f,0,SEEK_SET); - unsigned char*buf=malloc(sz); - if(!buf||fread(buf,1,sz,f)!=(size_t)sz){ fclose(f); free(buf); return 0; } - fclose(f); - stbtt_fontinfo info; - if(!stbtt_InitFont(&info,buf,stbtt_GetFontOffsetForIndex(buf,0))){ free(buf); return 0; } - float sc=stbtt_ScaleForPixelHeight(&info,(float)px); - int asc,desc,gap; stbtt_GetFontVMetrics(&info,&asc,&desc,&gap); ft->baseline=asc*sc; - - int AW=1024, penx=0,peny=0,rowh=0; - for(int cp=GLYPH_LO;cp<=GLYPH_HI;cp++){ - int x0,y0,x1,y1; stbtt_GetCodepointBitmapBox(&info,cp,sc,sc,&x0,&y0,&x1,&y1); - int gw=x1-x0,gh=y1-y0; if(gw<0)gw=0; if(gh<0)gh=0; - if(penx+gw+1>AW){ penx=0; peny+=rowh+1; rowh=0; } - if(gh>rowh)rowh=gh; - penx+=gw+1; - } - int AH=peny+rowh+1; if(AH<1)AH=1; - Uint32*pix=calloc((size_t)AW*AH,4); if(!pix){ free(buf); return 0; } - - penx=0;peny=0;rowh=0; - for(int cp=GLYPH_LO;cp<=GLYPH_HI;cp++){ - int aw,lsb; stbtt_GetCodepointHMetrics(&info,cp,&aw,&lsb); - int x0,y0,x1,y1; stbtt_GetCodepointBitmapBox(&info,cp,sc,sc,&x0,&y0,&x1,&y1); - int gw=x1-x0,gh=y1-y0; if(gw<0)gw=0; if(gh<0)gh=0; - if(penx+gw+1>AW){ penx=0; peny+=rowh+1; rowh=0; } - if(gw&&gh){ - unsigned char*bmp=malloc((size_t)gw*gh); - stbtt_MakeCodepointBitmap(&info,bmp,gw,gh,gw,sc,sc,cp); - for(int yy=0;yy<gh;yy++)for(int xx=0;xx<gw;xx++) - pix[(peny+yy)*AW+(penx+xx)]=((Uint32)bmp[yy*gw+xx]<<24)|0x00FFFFFF; - free(bmp); - } - int gi=cp-GLYPH_LO; - ft->g[gi].u=penx; ft->g[gi].v=peny; ft->g[gi].w=gw; ft->g[gi].h=gh; - ft->g[gi].xoff=x0; ft->g[gi].yoff=y0; ft->g[gi].adv=aw*sc; - if(gh>rowh)rowh=gh; - penx+=gw+1; - } - free(buf); - SDL_Surface*surf=SDL_CreateSurfaceFrom(AW,AH,SDL_PIXELFORMAT_ABGR8888,pix,AW*4); - if(!surf){ free(pix); return 0; } - ft->atlas=SDL_CreateTextureFromSurface(ren,surf); - SDL_DestroySurface(surf); free(pix); - if(!ft->atlas) return 0; - SDL_SetTextureScaleMode(ft->atlas,SDL_SCALEMODE_LINEAR); - SDL_SetTextureBlendMode(ft->atlas,SDL_BLENDMODE_BLEND); - ft->ok=1; return 1; +static int font_load(UiFont*ft,const char*path,int px){ + ft->ok=0; ft->px=px; + sw_fonts_init(path,NULL); + UiFont *probe=ft; /* a font with no glyphs is no font */ + if(sw_text_width(sw_font(px),"M")>0.0f) probe->ok=1; + return ft->ok; } -static unsigned utf8_next(const char**p){ - const unsigned char*s=(const unsigned char*)*p; unsigned cp; int n; - if(s[0]<0x80){cp=s[0];n=1;} - else if((s[0]&0xE0)==0xC0){cp=s[0]&0x1F;n=2;} - else if((s[0]&0xF0)==0xE0){cp=s[0]&0x0F;n=3;} - else if((s[0]&0xF8)==0xF0){cp=s[0]&0x07;n=4;} - else{ *p=(const char*)(s+1); return 0xFFFD; } - for(int i=1;i<n;i++){ if((s[i]&0xC0)!=0x80){n=i;break;} cp=(cp<<6)|(s[i]&0x3F); } - *p=(const char*)(s+n); return cp; -} -static float text_width(Font*ft,float px_h,const char*s){ - if(!ft->ok) return strlen(s)*8.0f*(px_h/8.0f); - float ds=px_h/ft->px,w=0; const char*p=s; - while(*p){ unsigned cp=utf8_next(&p); if(cp<GLYPH_LO||cp>GLYPH_HI)cp='?'; w+=ft->g[cp-GLYPH_LO].adv*ds; } - return w; +/* utf8_next lived here; sw_draw walks the string itself now. */ + +static float text_width(UiFont*ft,float px_h,const char*s){ + (void)ft; + int px=(int)(px_h+0.5f); if(px<4)px=4; + return sw_text_width(sw_font(px),s); } -static void text_draw(SDL_Renderer*r,Font*ft,float x,float y,float px_h,Col c,const char*s){ - if(!ft->ok){ - /* built-in 8x8 font: compose with any active render scale (e.g. SSAA) */ - float k=px_h/8.0f, csx,csy; SDL_GetRenderScale(r,&csx,&csy); - SDL_SetRenderDrawColor(r,c.r,c.g,c.b,c.a); - SDL_SetRenderScale(r,csx*k,csy*k); - SDL_RenderDebugText(r,x/k,y/k,s); - SDL_SetRenderScale(r,csx,csy); - return; - } - float ds=px_h/ft->px; - SDL_SetTextureColorMod(ft->atlas,c.r,c.g,c.b); - SDL_SetTextureAlphaMod(ft->atlas,c.a); - float pen=x; const char*p=s; - while(*p){ unsigned cp=utf8_next(&p); if(cp<GLYPH_LO||cp>GLYPH_HI)cp='?'; - int gi=cp-GLYPH_LO; - if(ft->g[gi].w>0&&ft->g[gi].h>0){ - SDL_FRect src={ft->g[gi].u,ft->g[gi].v,ft->g[gi].w,ft->g[gi].h}; - SDL_FRect dst={pen+ft->g[gi].xoff*ds,y+(ft->baseline+ft->g[gi].yoff)*ds,ft->g[gi].w*ds,ft->g[gi].h*ds}; - SDL_RenderTexture(r,ft->atlas,&src,&dst); - } - pen+=ft->g[gi].adv*ds; - } +/* y is the top of the line, as it always was here; sw_text wants a baseline. */ +static void text_draw(Canvas*cv,UiFont*ft,float x,float y,float px_h,Col c,const char*s){ + (void)ft; + int px=(int)(px_h+0.5f); if(px<4)px=4; + Font *f=sw_font(px); + sw_text(cv,f,x,y+f->ascent,c,s); } -static void text_centered(SDL_Renderer*r,Font*ft,float cx,float cy,float px_h,Col c,const char*s){ - float w=text_width(ft,px_h,s); text_draw(r,ft,cx-w/2,cy-px_h/2,px_h,c,s); +static void text_centered(Canvas*cv,UiFont*ft,float cx,float cy,float px_h,Col c,const char*s){ + float w=text_width(ft,px_h,s); text_draw(cv,ft,cx-w/2,cy-px_h/2,px_h,c,s); } -static void fit_label(Font*ft,float px_h,const char*s,float max_w,char*out,size_t n){ +static void fit_label(UiFont*ft,float px_h,const char*s,float max_w,char*out,size_t n){ if(text_width(ft,px_h,s)<=max_w){ snprintf(out,n,"%s",s); return; } char buf[256]; snprintf(buf,sizeof buf,"%s",s); int len=(int)strlen(buf); while(len>1){ buf[len]='\0'; @@ -445,7 +388,7 @@ static void fit_label(Font*ft,float px_h,const char*s,float max_w,char*out,size_ /* ------------------------------------------------------------------ */ typedef struct { char *id,*name,*exec,*icon; int terminal; - SDL_Texture *tex; int icon_tried; int recent; /* 1 = present in launch history */ + Image tex; int icon_tried; int recent; /* 1 = present in launch history */ } App; typedef struct { App*v; int n,cap; } AppList; @@ -491,7 +434,7 @@ static int parse_desktop(const char*path,const char*id,App*out){ if(ok){ out->id=xstrdup(id); out->name=name; name=NULL; out->exec=strip_field_codes(exec); out->icon=icon; icon=NULL; - out->terminal=terminal; out->tex=NULL; out->icon_tried=0; + out->terminal=terminal; memset(&out->tex,0,sizeof out->tex); out->icon_tried=0; } free(name);free(exec);free(type);free(icon); return ok; @@ -711,15 +654,14 @@ static void resolve_icon(const char*name,char*out,size_t n){ if(file_exists(p)){ snprintf(out,n,"%s",p); return; } } } -static SDL_Texture *load_icon_tex(SDL_Renderer*ren,const char*path){ +/* An icon is now just its pixels: straight RGBA, which is what both stb_image + and nanosvg hand back and what sw_blit takes. */ +static Image load_icon_img(const char*path){ + Image im={0}; int w,h,ch; unsigned char*data=stbi_load(path,&w,&h,&ch,4); - if(!data) return NULL; - SDL_Surface*s=SDL_CreateSurfaceFrom(w,h,SDL_PIXELFORMAT_ABGR8888,data,w*4); - if(!s){ stbi_image_free(data); return NULL; } - SDL_Texture*t=SDL_CreateTextureFromSurface(ren,s); - SDL_DestroySurface(s); stbi_image_free(data); - if(t){ SDL_SetTextureScaleMode(t,SDL_SCALEMODE_LINEAR); SDL_SetTextureBlendMode(t,SDL_BLENDMODE_BLEND); } - return t; + if(!data) return im; + im.rgba=data; im.w=w; im.h=h; im.stride=w*4; + return im; } static int ends_with_ci(const char*s,const char*suf){ size_t ls=strlen(s),lf=strlen(suf); @@ -732,10 +674,11 @@ static int ends_with_ci(const char*s,const char*suf){ here is the declared canvas and the shapes' own bounds together: an icon with deliberate padding keeps it, one that overflows is scaled down instead of losing an edge. */ -static SDL_Texture *load_svg_tex(SDL_Renderer*ren,const char*path,int px){ +static Image load_svg_img(const char*path,int px){ + Image out={0}; if(px<16)px=16; if(px>512)px=512; NSVGimage*img=nsvgParseFromFile(path,"px",96.0f); - if(!img) return NULL; + if(!img) return out; float x0=0,y0=0,x1=img->width,y1=img->height; if(x1<=0||y1<=0){ x0=y0=1e30f; x1=y1=-1e30f; } /* no usable canvas */ for(NSVGshape*s=img->shapes;s;s=s->next){ @@ -747,32 +690,29 @@ static SDL_Texture *load_svg_tex(SDL_Renderer*ren,const char*path,int px){ if(s->bounds[3]+m>y1) y1=s->bounds[3]+m; } float bw=x1-x0, bh=y1-y0; - if(!(bw>0.0f)||!(bh>0.0f)){ nsvgDelete(img); return NULL; } + if(!(bw>0.0f)||!(bh>0.0f)){ nsvgDelete(img); return out; } float sc=(float)px/(bw>bh?bw:bh); int ow=(int)(bw*sc+0.5f), oh=(int)(bh*sc+0.5f); if(ow<1)ow=1; if(oh<1)oh=1; unsigned char*pix=calloc((size_t)ow*oh,4); NSVGrasterizer*r=nsvgCreateRasterizer(); - if(!pix||!r){ free(pix); if(r)nsvgDeleteRasterizer(r); nsvgDelete(img); return NULL; } + if(!pix||!r){ free(pix); if(r)nsvgDeleteRasterizer(r); nsvgDelete(img); return out; } nsvgRasterize(r,img,-x0*sc,-y0*sc,sc,pix,ow,oh,ow*4); nsvgDeleteRasterizer(r); nsvgDelete(img); - SDL_Surface*s=SDL_CreateSurfaceFrom(ow,oh,SDL_PIXELFORMAT_ABGR8888,pix,ow*4); - if(!s){ free(pix); return NULL; } - SDL_Texture*t=SDL_CreateTextureFromSurface(ren,s); - SDL_DestroySurface(s); free(pix); - if(t){ SDL_SetTextureScaleMode(t,SDL_SCALEMODE_LINEAR); SDL_SetTextureBlendMode(t,SDL_BLENDMODE_BLEND); } - return t; + out.rgba=pix; out.w=ow; out.h=oh; out.stride=ow*4; + return out; } -static SDL_Texture *app_icon(SDL_Renderer*ren,App*a,Config*c){ - if(!c->icons) return NULL; +static Image app_icon(App*a,Config*c){ + Image none={0}; + if(!c->icons) return none; if(!a->icon_tried){ a->icon_tried=1; char path[PATH_MAX]; resolve_icon(a->icon,path,sizeof path); if(*path){ if(ends_with_ci(path,".svg")){ int px=(int)(c->icon_px*c->ui_scale*2.0f); if(px<48)px=48; if(px>256)px=256; - a->tex=load_svg_tex(ren,path,px); + a->tex=load_svg_img(path,px); } else { - a->tex=load_icon_tex(ren,path); + a->tex=load_icon_img(path); } } } @@ -967,7 +907,7 @@ static void ov_spawn(Config*c){ } /* whatever it has said since the last frame */ -static void ov_poll(SDL_Window*win){ +static void ov_poll(void){ if(OV_OUT<0) return; static char buf[512]; static int len; @@ -982,7 +922,8 @@ static void ov_poll(SDL_Window*win){ if(OV_LOG) fprintf(stderr,"swas: <- %s\n",start); if(!strcmp(start,"ready")){ OV_READY=1; - SDL_RaiseWindow(win); /* enough on X11 */ + /* On the layer shell we are already above everything, + so there is nothing to raise. */ /* On Wayland a window cannot lift itself, and the backdrop mapped on top of us. swov is talking to sway anyway. */ ov_send("raise " APP_ID); @@ -1072,7 +1013,11 @@ static pid_t WATCH_PID; static double WATCH_AT; static char WATCH_NAME[64]; -static double now_secs_(void){ return (double)SDL_GetTicks()/1000.0; } +static uint64_t now_ms_(void){ + struct timespec ts; clock_gettime(CLOCK_MONOTONIC,&ts); + return (uint64_t)ts.tv_sec*1000u + (uint64_t)(ts.tv_nsec/1000000); +} +static double now_secs_(void){ return (double)now_ms_()/1000.0; } static void err_say(const char*fmt,...){ va_list ap; va_start(ap,fmt); @@ -1154,66 +1099,36 @@ static pid_t launch(App*a,Config*c){ /* ------------------------------------------------------------------ */ /* geometry primitives */ /* ------------------------------------------------------------------ */ -static void fill_circle(SDL_Renderer*r,float cx,float cy,float rad,Col c){ - const int SEG=96; SDL_Vertex v[SEG+2]; SDL_FColor fc=tofc(c); - v[0].position=(SDL_FPoint){cx,cy}; v[0].color=fc; v[0].tex_coord=(SDL_FPoint){0,0}; - for(int i=0;i<=SEG;i++){ float a=(float)(2*M_PI*i/SEG); - v[i+1].position=(SDL_FPoint){cx+rad*cosf(a),cy+rad*sinf(a)}; - v[i+1].color=fc; v[i+1].tex_coord=(SDL_FPoint){0,0}; } - int idx[SEG*3]; for(int i=0;i<SEG;i++){ idx[i*3]=0; idx[i*3+1]=i+1; idx[i*3+2]=i+2; } - SDL_RenderGeometry(r,NULL,v,SEG+2,idx,SEG*3); +/* The shapes the wheel is made of: thin wrappers over sw_draw, antialiased + in software. The signatures are the ones the drawing code below expects. */ +static void fill_circle(Canvas*cv,float cx,float cy,float rad,Col c){ + sw_fill_circle(cv,cx,cy,rad,c); } /* a thin outline circle: the "let go here" hint around the parked wheel */ -static void ring(SDL_Renderer*r,float cx,float cy,float rad,float thick,Col c){ - const int SEG=96; SDL_SetRenderDrawColor(r,c.r,c.g,c.b,c.a); - for(float t=0;t<thick;t+=1.0f) - for(int i=0;i<SEG;i++){ float a=(float)(2*M_PI*i/SEG); - SDL_FRect d={cx+(rad+t)*cosf(a),cy+(rad+t)*sinf(a),1.5f,1.5f}; - SDL_RenderFillRect(r,&d); } +static void ring(Canvas*cv,float cx,float cy,float rad,float thick,Col c){ + sw_stroke_round(cv,cx-rad,cy-rad,rad*2,rad*2,rad,rad,rad,rad,thick,c); } - -static void fill_sector(SDL_Renderer*r,float cx,float cy,float r0,float r1,float a0,float a1,Col c){ - int seg=(int)((a1-a0)/0.04f)+2; if(seg<2)seg=2; if(seg>160)seg=160; - int nv=(seg+1)*2; SDL_Vertex*v=malloc(nv*sizeof*v); SDL_FColor fc=tofc(c); - for(int i=0;i<=seg;i++){ float a=a0+(a1-a0)*i/seg,ca=cosf(a),sa=sinf(a); - v[2*i].position=(SDL_FPoint){cx+r0*ca,cy+r0*sa}; - v[2*i+1].position=(SDL_FPoint){cx+r1*ca,cy+r1*sa}; - v[2*i].color=v[2*i+1].color=fc; v[2*i].tex_coord=v[2*i+1].tex_coord=(SDL_FPoint){0,0}; } - int ni=seg*6,*idx=malloc(ni*sizeof*idx); - for(int i=0;i<seg;i++){ int b=2*i; - idx[i*6]=b;idx[i*6+1]=b+1;idx[i*6+2]=b+2; idx[i*6+3]=b+1;idx[i*6+4]=b+3;idx[i*6+5]=b+2; } - SDL_RenderGeometry(r,NULL,v,nv,idx,ni); free(v); free(idx); +static void fill_sector(Canvas*cv,float cx,float cy,float r0,float r1,float a0,float a1,Col c){ + sw_fill_sector(cv,cx,cy,r0,r1,a0,a1,c); } -static void fill_round_rect(SDL_Renderer*r,float x,float y,float w,float h,float rad,Col c){ - if(rad>w/2)rad=w/2; if(rad>h/2)rad=h/2; - SDL_SetRenderDrawColor(r,c.r,c.g,c.b,c.a); - SDL_FRect mid={x,y+rad,w,h-2*rad}, top={x+rad,y,w-2*rad,rad}, bot={x+rad,y+h-rad,w-2*rad,rad}; - SDL_RenderFillRect(r,&mid); SDL_RenderFillRect(r,&top); SDL_RenderFillRect(r,&bot); - fill_circle(r,x+rad,y+rad,rad,c); fill_circle(r,x+w-rad,y+rad,rad,c); - fill_circle(r,x+rad,y+h-rad,rad,c); fill_circle(r,x+w-rad,y+h-rad,rad,c); +static void fill_round_rect(Canvas*cv,float x,float y,float w,float h,float rad,Col c){ + sw_fill_round(cv,x,y,w,h,rad,rad,rad,rad,c); } - -static void stroke_rect(SDL_Renderer*r,float x,float y,float w,float h,float t,Col c){ - SDL_SetRenderDrawColor(r,c.r,c.g,c.b,c.a); - SDL_FRect e[4]={{x,y,w,t},{x,y+h-t,w,t},{x,y,t,h},{x+w-t,y,t,h}}; - for(int i=0;i<4;i++) SDL_RenderFillRect(r,&e[i]); +static void stroke_rect(Canvas*cv,float x,float y,float w,float h,float t,Col c){ + sw_stroke_round(cv,x,y,w,h,0,0,0,0,t,c); } - -static void fill_tri(SDL_Renderer*r,float x0,float y0,float x1,float y1,float x2,float y2,Col c){ - SDL_FColor fc=tofc(c); - SDL_Vertex v[3]={ {{x0,y0},fc,{0,0}}, {{x1,y1},fc,{0,0}}, {{x2,y2},fc,{0,0}} }; - int idx[3]={0,1,2}; - SDL_RenderGeometry(r,NULL,v,3,idx,3); +static void fill_tri(Canvas*cv,float x0,float y0,float x1,float y1,float x2,float y2,Col c){ + sw_fill_tri(cv,x0,y0,x1,y1,x2,y2,c); } /* stacked arrowheads pointing dir (+1 right / -1 left); count grows with speed */ -static void draw_chevrons(SDL_Renderer*r,float x,float y,int dir,float s,int count,Col c){ +static void draw_chevrons(Canvas*cv,float x,float y,int dir,float s,int count,Col c){ if(count<1)count=1; float gap=s*0.72f, total=(count-1)*gap, start=x-dir*total/2; for(int i=0;i<count;i++){ float ax=start+dir*i*gap; - fill_tri(r, ax+dir*s*0.5f, y, - ax-dir*s*0.5f, y-s*0.62f, - ax-dir*s*0.5f, y+s*0.62f, c); + fill_tri(cv, ax+dir*s*0.5f, y, + ax-dir*s*0.5f, y-s*0.62f, + ax-dir*s*0.5f, y+s*0.62f, c); } } static float norm_ang(float a){ while(a>M_PI)a-=2*M_PI; while(a<=-M_PI)a+=2*M_PI; return a; } @@ -1253,7 +1168,7 @@ static void dump_config(void){ " # zone, fast toward straight-down.\n" "\n" "# --- rendering ---\n" -"ssaa=2 # full-scene supersampling 1..4 (smooths edges). alias: aa\n" +"ssaa=2 # ignored: every shape is antialiased as it is drawn. alias: aa\n" "animate=1 # crossfade app names/icons when results change\n" "anim_ms=90 # its duration (0 or animate=0 to turn it off)\n" "recent_first=1 # bias the best match toward your recently-used apps\n" @@ -1392,7 +1307,7 @@ static void usage(const char*a0){ " swov=swov the binary to ask\n" "\n" "RENDERING\n" -" ssaa=2 full-scene supersampling 1..4 (smooths edges; alias: aa)\n" +" ssaa=2 ignored; every shape is antialiased as it is drawn (alias: aa)\n" " animate=1 anim_ms=90 crossfade names/icons when results change (0 = off)\n" " width=900 height=900 fullscreen=1 close_on_focus_loss=0\n" "\n" @@ -1416,7 +1331,7 @@ static void usage(const char*a0){ "EXAMPLES\n" " swas --list # discover ids\n" " swas include=firefox,code,gimp # a curated wheel, in that order\n" -" swas exclude=htop sort=alpha ssaa=3 # hide htop, A-Z, extra-smooth\n" +" swas exclude=htop sort=alpha # hide htop, list A-Z\n" " swas ui_scale=1.3 icon_px=56 # bigger text and icons\n" "\n" "COLORS (#rrggbb or #rrggbbaa)\n" @@ -1434,7 +1349,7 @@ static void usage(const char*a0){ } /* Load the app/menu list (stdin for dmenu, else scan .desktop dirs). Kept - separate so the SDL window can be created first — see main(). */ + separate so the window can be created first — see main(). */ static void load_apps(AppList*apps, Config*cfg, int dmenu){ if(dmenu){ /* dmenu mode: items come from stdin */ char line[8192]; @@ -1519,47 +1434,37 @@ int main(int argc,char**argv){ return 0; } - /* Identify as swas so the compositor shows the same name everywhere, - Wayland app_id / X11 WM_CLASS so float/center rules match. Before init. */ - SDL_SetAppMetadata(APP_ID,SWAS_VERSION,"org.swas.selector"); - SDL_SetHint(SDL_HINT_APP_ID,APP_ID); - - if(!SDL_Init(SDL_INIT_VIDEO)){ fprintf(stderr,"SDL_Init: %s\n",SDL_GetError()); return 1; } - - /* "Fullscreen" here means a borderless window the size of the display — a - floating overlay, NOT exclusive fullscreen. Exclusive fullscreen makes the - surface opaque (black instead of transparent) and causes a mode-switch - glitch on close, so we avoid it. */ - int winw=cfg.width, winh=cfg.height; - SDL_Rect dbounds; int have_bounds=0; + /* A layer-shell surface on the overlay, the size of the output. Not a + toplevel window: the compositor puts it above everything including a + fullscreen client, it takes the keyboard for as long as it is up, and + there is no float/center rule to write. */ + if(!sw_init()){ fprintf(stderr,"swas: %s\n",sw_error()); return 1; } + + SwWinOpts wo; memset(&wo,0,sizeof wo); + wo.layer = SW_LAYER_OVERLAY; + wo.keyboard = SW_KBD_EXCLUSIVE; + wo.exclusive_zone = -1; + wo.namespace_ = APP_ID; if(cfg.fullscreen){ - SDL_DisplayID d=SDL_GetPrimaryDisplay(); - if(d && SDL_GetDisplayBounds(d,&dbounds)){ winw=dbounds.w; winh=dbounds.h; have_bounds=1; } + wo.anchor = SW_ANCHOR_TOP|SW_ANCHOR_BOTTOM|SW_ANCHOR_LEFT|SW_ANCHOR_RIGHT; + } else { + wo.w = cfg.width; wo.h = cfg.height; } - SDL_WindowFlags wf=SDL_WINDOW_BORDERLESS|SDL_WINDOW_ALWAYS_ON_TOP; - if(cfg.bg.a<255) wf|=SDL_WINDOW_TRANSPARENT; - SDL_Window*win=SDL_CreateWindow(APP_ID,winw,winh,wf); - if(!win){ fprintf(stderr,"CreateWindow: %s\n",SDL_GetError()); return 1; } - if(have_bounds) SDL_SetWindowPosition(win,dbounds.x,dbounds.y); - SDL_Renderer*ren=SDL_CreateRenderer(win,NULL); - if(!ren){ fprintf(stderr,"CreateRenderer: %s\n",SDL_GetError()); return 1; } - SDL_SetRenderDrawBlendMode(ren,SDL_BLENDMODE_BLEND); - SDL_RaiseWindow(win); - SDL_StartTextInput(win); - - /* Get the window mapped & focused NOW, before the (possibly slow, on a busy - machine) .desktop scan and font load — so keystrokes typed during loading - are queued for us by the compositor instead of being lost. */ - SDL_SetRenderDrawColor(ren,cfg.bg.r,cfg.bg.g,cfg.bg.b,cfg.bg.a); - SDL_RenderClear(ren); SDL_RenderPresent(ren); - for(int i=0;i<4;i++){ SDL_PumpEvents(); SDL_Delay(1); } + SwApp wapp; memset(&wapp,0,sizeof wapp); /* we drive our own frames */ + SwWin *win = sw_win_create(&wo,&wapp); + if(!win){ fprintf(stderr,"swas: %s\n",sw_error()); return 1; } + + /* Get the surface configured NOW, before the (possibly slow, on a busy + machine) .desktop scan and font load — so keystrokes typed during + loading are queued for us by the compositor instead of being lost. */ + for(int i=0;i<40 && sw_win_width(win)==0;i++) sw_dispatch(20); load_apps(&apps,&cfg,dmenu); /* slow part; keystrokes queue meanwhile */ if(apps.n==0){ fprintf(stderr,"swas: no %s\n", dmenu?"input on stdin":".desktop applications found"); - SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return 1; } + sw_shutdown(); return 1; } - Font font; memset(&font,0,sizeof font); + UiFont font; memset(&font,0,sizeof font); char fontpath[PATH_MAX]={0}; if(*cfg.font){ /* explicit: a path OR a family name */ if(file_exists(cfg.font)) snprintf(fontpath,sizeof fontpath,"%s",cfg.font); @@ -1568,12 +1473,12 @@ int main(int argc,char**argv){ if(!*fontpath) fc_match("sans-serif",fontpath,sizeof fontpath); /* the desktop default */ if(!*fontpath) try_font_paths(fontpath,sizeof fontpath); /* last-resort known paths */ int atlas_px=(int)(cfg.font_px*cfg.ui_scale); if(atlas_px<10)atlas_px=10; if(atlas_px>200)atlas_px=200; - if(*fontpath) font_load(&font,ren,fontpath,atlas_px); - if(!font.ok) fprintf(stderr,"swas: no usable TTF font found; using built-in font\n"); + if(*fontpath) font_load(&font,fontpath,atlas_px); + if(!font.ok) fprintf(stderr,"swas: no usable TTF font found\n"); int *filt=malloc(apps.n*sizeof*filt); int fn=0; char query[256]={0}; int off=0, selslot=0; /* fixed highlight = off+selslot */ - Uint64 anim0=0; /* time of last filter change (animation) */ + uint64_t anim0=0; /* time of last filter change (animation) */ /* Per-slot crossfade bookkeeping: last_* is the layout drawn last frame; snap_* is frozen at the moment of a results change. A slot only fades if its app+position differ from the snapshot, so anything that stays put @@ -1584,7 +1489,7 @@ int main(int argc,char**argv){ #define REBUILD() do{ \ memcpy(snap_item,last_item,sizeof(int)*last_n); memcpy(snap_ang,last_ang,sizeof(float)*last_n); \ snap_n=last_n; snap_sel=last_sel; \ - fn=build_filter(&apps,query,filt,cfg.slots,cfg.recent_first,cfg.center_first,&off,&selslot); anim0=SDL_GetTicks(); }while(0) + fn=build_filter(&apps,query,filt,cfg.slots,cfg.recent_first,cfg.center_first,&off,&selslot); anim0=now_ms_(); }while(0) REBUILD(); /* --- drag an app out of the wheel and onto a workspace --- @@ -1595,28 +1500,28 @@ int main(int argc,char**argv){ float press_x=0, press_y=0; float wheel_scale=1.0f; /* animated 1 -> drop_shrink */ float corner_t=0.0f; /* 0 = centred, 1 = parked in a corner */ - Uint64 flash_at=0; int flash_ws=-1; /* the tile that just took an app */ - SDL_FRect wsp_rect[24]; + uint64_t flash_at=0; int flash_ws=-1; /* the tile that just took an app */ + Rect wsp_rect[24]; int page_dir=0; float page_speed=0; /* for the paging indicators */ float mx=cfg.width/2.0f,my=cfg.height/2.0f; - Uint64 last_page=0, blink0=SDL_GetTicks(); + uint64_t last_page=0, blink0=now_ms_(); int running=1, had_focus=0, page_armed=0, prev_region=0, chose=0; int ov_started=0; float ov_lx=-1, ov_ly=-1; - /* SDL reports where the pointer already is as soon as the window is up. - That is not the user moving it, and it must not throw away the - selection we opened with. */ + /* The compositor reports where the pointer already is as soon as the + surface is up. That is not the user moving it, and it must not throw + away the selection we opened with. */ int mouse_live=0; float m0x=0, m0y=0; int mouse_seen=0; #define CHOOSE() do{ if(dmenu){ printf("%s\n",apps.v[filt[sel]].name); fflush(stdout); chose=1; } \ else launch(&apps.v[filt[sel]],&cfg); running=0; }while(0) float arc=cfg.arc_deg*(float)DEG; if(arc<60*DEG)arc=60*DEG; if(arc>330*DEG)arc=330*DEG; - SDL_Texture*target=NULL; int tw=0,th=0; float ui=cfg.ui_scale; while(running){ - int w,h; SDL_GetWindowSize(win,&w,&h); - int ss=cfg.ssaa; + if(!sw_dispatch(0)) break; /* the compositor went away */ + int w=sw_win_width(win), h=sw_win_height(win); + if(w<=0||h<=0){ sw_dispatch(16); continue; } { /* ease the wheel down to its dragging size and place, and back. drop_size is a width in pixels, which is what you actually want @@ -1675,7 +1580,7 @@ int main(int argc,char**argv){ tile_h=(float)h*0.135f; if(tile_h>190.0f*cfg.ui_scale) tile_h=190.0f*cfg.ui_scale; tile_y=(float)h*0.035f; for(int i=0;i<NWSP;i++) - wsp_rect[i]=(SDL_FRect){ margin+(tw+gap)*(float)i, tile_y, tw, tile_h }; + wsp_rect[i]=(Rect){ margin+(tw+gap)*(float)i, tile_y, tw, tile_h }; } int searching = query[0]!=0; @@ -1706,10 +1611,10 @@ int main(int argc,char**argv){ float depth=fabsf(dtop)-half_arc, maxd=(float)M_PI-half_arc; page_speed = maxd>0?clampf(depth/maxd,0,1):0; if(fn>vis){ - Uint64 now=SDL_GetTicks(); + uint64_t now=now_ms_(); float t=page_speed*page_speed; /* ease in: gentle start, fast finish */ int iv=(int)(cfg.page_ms*(1.0f-0.82f*t)); if(iv<24)iv=24; - if((Sint64)(now-last_page)>=iv){ + if((int64_t)(now-last_page)>=iv){ off += page_dir; if(off<0)off=0; if(off>maxoff)off=maxoff; @@ -1720,20 +1625,20 @@ int main(int argc,char**argv){ } } - if(OV_OUT>=0) ov_poll(win); + if(OV_OUT>=0) ov_poll(); - SDL_Event ev; - while(SDL_PollEvent(&ev)){ - if(ev.type==SDL_EVENT_QUIT) running=0; - else if(ev.type==SDL_EVENT_WINDOW_FOCUS_GAINED) had_focus=1; - else if(ev.type==SDL_EVENT_WINDOW_FOCUS_LOST){ + SwEvent ev; + while(sw_poll(&ev)){ + if(ev.type==SW_EV_CLOSED) running=0; + else if(ev.type==SW_EV_KB_ENTER) had_focus=1; + else if(ev.type==SW_EV_KB_LEAVE){ /* With the overview up, apps are being started behind us on purpose; each one takes the focus for a moment and that is not a reason to close. */ if(cfg.close_on_focus_loss && had_focus && !OV_READY) running=0; } - else if(ev.type==SDL_EVENT_MOUSE_MOTION){ - mx=ev.motion.x; my=ev.motion.y; + else if(ev.type==SW_EV_MOTION){ + mx=ev.x; my=ev.y; if(!mouse_live){ if(!mouse_seen){ mouse_seen=1; m0x=mx; m0y=my; } @@ -1771,7 +1676,7 @@ int main(int argc,char**argv){ drop_ws=-1; if(!over_wheel) for(int i=0;i<NWSP;i++){ - SDL_FRect t=wsp_rect[i]; + Rect t=wsp_rect[i]; if(mx>=t.x&&mx<t.x+t.w&&my>=t.y&&my<t.y+t.h){ drop_ws=i; break; } } } @@ -1805,28 +1710,29 @@ int main(int argc,char**argv){ else if(region==2 && prev_region==3 && adtop>=icon_dtop) page_armed=1; prev_region=region; } - else if(ev.type==SDL_EVENT_MOUSE_WHEEL){ - int dir=ev.wheel.y>0?-1:(ev.wheel.y<0?1:0); - if(!dir&&ev.wheel.x)dir=ev.wheel.x>0?1:-1; + else if(ev.type==SW_EV_AXIS){ + /* Wayland scrolls in surface units, positive downward. */ + int dir=ev.ay<0?-1:(ev.ay>0?1:0); + if(!dir&&ev.ax)dir=ev.ax>0?1:-1; if(dir){ if(maxoff>0){ off+=dir; if(off<0)off=0; if(off>maxoff)off=maxoff; } else if(vis>0){ selslot+=dir; if(selslot<0)selslot=0; if(selslot>vis-1)selslot=vis-1; } } } - else if(ev.type==SDL_EVENT_MOUSE_BUTTON_DOWN){ - if(ev.button.button==SDL_BUTTON_LEFT&&fn){ - press_down=1; press_x=ev.button.x; press_y=ev.button.y; + else if(ev.type==SW_EV_BUTTON && ev.pressed){ + if(ev.button==SW_BTN_LEFT&&fn){ + press_down=1; press_x=ev.x; press_y=ev.y; /* the bottom zone is for paging; nothing is dragged there */ press_item=(prev_region==2||prev_region==3)?-1:filt[sel]; } - else if(ev.button.button==SDL_BUTTON_RIGHT){ + else if(ev.button==SW_BTN_RIGHT){ if(dragging){ dragging=press_down=0; drop_ws=-1; press_item=-1; if(OV_READY){ ov_send("drag off"); OV_TARGET[0]='\0'; } } else running=0; } } - else if(ev.type==SDL_EVENT_MOUSE_BUTTON_UP){ - if(ev.button.button==SDL_BUTTON_LEFT){ + else if(ev.type==SW_EV_BUTTON && !ev.pressed){ + if(ev.button==SW_BTN_LEFT){ if(dragging){ if(OV_READY){ if(over_wheel) OV_TARGET[0]='\0'; /* changed my mind */ @@ -1852,7 +1758,7 @@ int main(int argc,char**argv){ pid_t p=launch(&apps.v[press_item],&cfg); wsp_adopt(&cfg,p,&WSP[drop_ws]); WSP[drop_ws].exists=1; /* it will be there now */ - flash_ws=drop_ws; flash_at=SDL_GetTicks(); + flash_ws=drop_ws; flash_at=now_ms_(); if(WSP[drop_ws].focused && cfg.drop_close_here) running=0; } /* dropped on the wheel, or nowhere: nothing happens */ @@ -1863,27 +1769,30 @@ int main(int argc,char**argv){ press_down=0; press_item=-1; } } - else if(ev.type==SDL_EVENT_TEXT_INPUT){ - strncat(query,ev.text.text,sizeof query-strlen(query)-1); - REBUILD(); - } - else if(ev.type==SDL_EVENT_KEY_DOWN){ - SDL_Keycode k=ev.key.key; - if(k==SDLK_ESCAPE){ + else if(ev.type==SW_EV_KEY && ev.pressed){ + uint32_t k=ev.keysym; + if(k==SW_KEY_ESCAPE){ if(dragging){ dragging=press_down=0; drop_ws=-1; press_item=-1; if(OV_READY){ ov_send("drag off"); OV_TARGET[0]='\0'; } } else if(query[0]){ query[0]='\0'; REBUILD(); } else running=0; } - else if(k==SDLK_RETURN||k==SDLK_KP_ENTER){ if(fn){ CHOOSE(); } } - else if(k==SDLK_BACKSPACE){ int L=strlen(query); + else if(k==SW_KEY_RETURN||k==SW_KEY_KP_ENTER){ if(fn){ CHOOSE(); } } + else if(k==SW_KEY_BACKSPACE){ int L=strlen(query); if(L>0){ L--; while(L>0&&((unsigned char)query[L]&0xC0)==0x80)L--; query[L]='\0'; REBUILD(); } } - else if(k==SDLK_RIGHT || (k==SDLK_TAB && !(ev.key.mod&SDL_KMOD_SHIFT))){ + else if(k==SW_KEY_RIGHT || (k==SW_KEY_TAB && !(ev.mods&SW_MOD_SHIFT))){ if(vis>0){ if(selslot<vis-1)selslot++; else if(off<maxoff)off++; } } - else if(k==SDLK_LEFT || (k==SDLK_TAB && (ev.key.mod&SDL_KMOD_SHIFT))){ + else if(k==SW_KEY_LEFT || (k==SW_KEY_TAB && (ev.mods&SW_MOD_SHIFT))){ if(vis>0){ if(selslot>0)selslot--; else if(off>0)off--; } } - else if(k==SDLK_DOWN){ if(maxoff>0){ off+=vis; if(off>maxoff)off=maxoff; } } - else if(k==SDLK_UP){ if(maxoff>0){ off-=vis; if(off<0)off=0; } } + else if(k==SW_KEY_DOWN){ if(maxoff>0){ off+=vis; if(off>maxoff)off=maxoff; } } + else if(k==SW_KEY_UP){ if(maxoff>0){ off-=vis; if(off<0)off=0; } } + /* Anything that types a character types into the query. The + keymap says what that is, so a German keyboard puts ä in + the box when ä is pressed. */ + else if(ev.text[0] && (unsigned char)ev.text[0]>=0x20){ + strncat(query,ev.text,sizeof query-strlen(query)-1); + REBUILD(); + } } } if(!running) break; @@ -1902,23 +1811,17 @@ int main(int argc,char**argv){ if(sel>fn-1)sel=fn-1; step = arc/(float)(vis>0?vis:1); - /* -------------------- render (optionally supersampled) ------------- */ - if(ss>1){ - if(!target||tw!=w*ss||th!=h*ss){ - if(target)SDL_DestroyTexture(target); - target=SDL_CreateTexture(ren,SDL_PIXELFORMAT_RGBA8888,SDL_TEXTUREACCESS_TARGET,w*ss,h*ss); - if(target){ SDL_SetTextureScaleMode(target,SDL_SCALEMODE_LINEAR); - SDL_SetTextureBlendMode(target,SDL_BLENDMODE_BLEND); tw=w*ss; th=h*ss; } - } - if(target){ SDL_SetRenderTarget(ren,target); SDL_SetRenderScale(ren,(float)ss,(float)ss); } - else ss=1; - } + /* ------------------------------ render ---------------------------- */ + /* Every primitive is antialiased as it is drawn — the sectors and + triangles sample four times a pixel, the rounded rectangles come + from a distance field, the glyphs from stb_truetype — so the old + supersampled render target is gone and `ssaa` is ignored. */ + Canvas *ren = sw_win_begin(win); + if(!ren){ sw_dispatch(8); continue; } /* both buffers still on screen */ /* With swov behind us it draws its own scrim; a second one over the top only makes the thing you are aiming at harder to see. */ - Col clearc = OV_READY ? (Col){0,0,0,0} : cfg.bg; - SDL_SetRenderDrawColor(ren,clearc.r,clearc.g,clearc.b,clearc.a); - SDL_RenderClear(ren); + if(!OV_READY) sw_canvas_fill(ren,cfg.bg); float slotw=step; /* everything inside the wheel is measured against this, so shrinking @@ -1931,14 +1834,14 @@ int main(int argc,char**argv){ fade back in while the ring sectors (background) stay put — smooths fast typing without delaying anything. */ float af = (cfg.animate && cfg.anim_ms>0) - ? clampf(0.30f + 0.70f*(float)(SDL_GetTicks()-anim0)/(float)cfg.anim_ms, 0.0f, 1.0f) : 1.0f; + ? clampf(0.30f + 0.70f*(float)(now_ms_()-anim0)/(float)cfg.anim_ms, 0.0f, 1.0f) : 1.0f; /* Small, over a busy overview, the wheel had nothing to sit on and read as a handful of loose marks. A disc behind it gives it an edge again — only while it is small, fading in with the shrink. */ if(corner_t>0.0f && cfg.drop_bg.a){ Col d=cfg.drop_bg; - d.a=(Uint8)(d.a*clampf(corner_t,0.0f,1.0f)); + d.a=(uint8_t)(d.a*clampf(corner_t,0.0f,1.0f)); fill_circle(ren,cx,cy,R*1.10f,d); } @@ -1953,23 +1856,22 @@ int main(int argc,char**argv){ /* stationary if this exact app sat at (nearly) this angle before the change */ int stationary=0; for(int k=0;k<snap_n;k++) if(snap_item[k]==item && fabsf(snap_ang[k]-a)<0.02f){ stationary=1; break; } - float sfa = stationary?1.0f:af; Uint8 sfab=(Uint8)(255*sfa); + float sfa = stationary?1.0f:af; uint8_t sfab=(uint8_t)(255*sfa); if(i<SNAPMAX){ last_item[i]=item; last_ang[i]=a; } float lx=cx+rl*cosf(a), ly=cy+rl*sinf(a); - Col tc=hot?cfg.hltext:cfg.text; tc.a=(Uint8)(tc.a*sfa); /* text fades (unless it held still) */ + Col tc=hot?cfg.hltext:cfg.text; tc.a=(uint8_t)(tc.a*sfa); /* text fades (unless it held still) */ float chord=2*rl*sinf(slotw/2)*0.84f; char lbl[160]; fit_label(&font,label_px,apps.v[item].name,chord,lbl,sizeof lbl); - SDL_Texture*ic=app_icon(ren,&apps.v[item],&cfg); - if(ic){ + Image ic=app_icon(&apps.v[item],&cfg); + if(ic.rgba){ float isz=cfg.icon_px*uiw; if(isz>chord)isz=chord; float gap=7.0f*uiw; /* breathing room */ float blockH=isz+gap+label_px; float topy=ly-blockH/2; - SDL_FRect dst={lx-isz/2, topy, isz, isz}; - SDL_SetTextureAlphaMod(ic,sfab); /* icon fades (unless it held still) */ - SDL_RenderTexture(ren,ic,NULL,&dst); + /* the icon fades with the rest, unless it held still */ + sw_blit(ren,ic,lx-isz/2,topy,isz,isz,sfab/255.0f); text_centered(ren,&font,lx, topy+isz+gap+label_px/2, label_px, tc, lbl); } else { text_centered(ren,&font,lx,ly,label_px,tc,lbl); @@ -1998,7 +1900,7 @@ int main(int argc,char**argv){ /* center hub */ fill_circle(ren,cx,cy,rc,cfg.center); - Uint64 now=SDL_GetTicks(); int caret=((now-blink0)/500)%2==0; + uint64_t now=now_ms_(); int caret=((now-blink0)/500)%2==0; char shown[300]; if(query[0]) snprintf(shown,sizeof shown,"%s%s",query,caret?"|":" "); else snprintf(shown,sizeof shown,"type to search"); @@ -2009,10 +1911,10 @@ int main(int argc,char**argv){ int sel_item=filt[sel]; last_sel=sel_item; float caf = (sel_item==snap_sel)?1.0f:af; /* same app in the hub -> no fade */ char nm[200]; fit_label(&font,cfg.title_px*uiw,apps.v[sel_item].name,rc*1.7f,nm,sizeof nm); - Col nmc=cfg.text; nmc.a=(Uint8)(nmc.a*caf); + Col nmc=cfg.text; nmc.a=(uint8_t)(nmc.a*caf); text_centered(ren,&font,cx,cy,cfg.title_px*uiw,nmc,nm); char cnt[64]; snprintf(cnt,sizeof cnt,"%d / %d",sel+1,fn); - Col cc=cfg.dim; cc.a=(Uint8)(cc.a*caf); + Col cc=cfg.dim; cc.a=(uint8_t)(cc.a*caf); text_centered(ren,&font,cx,cy+rc*0.40f,cfg.count_px*uiw,cc,cnt); } else { last_sel=-1; @@ -2020,19 +1922,19 @@ int main(int argc,char**argv){ } /* --- the workspaces, and the app hanging off the pointer --- */ - if(!OV_READY && (dragging || (flash_ws>=0 && SDL_GetTicks()-flash_at<420))){ + if(!OV_READY && (dragging || (flash_ws>=0 && now_ms_()-flash_at<420))){ float rad=10.0f*ui; for(int i=0;i<NWSP;i++){ - SDL_FRect t=wsp_rect[i]; - int hot=(i==drop_ws), lit=(i==flash_ws && SDL_GetTicks()-flash_at<420); + Rect t=wsp_rect[i]; + int hot=(i==drop_ws), lit=(i==flash_ws && now_ms_()-flash_at<420); Col fill=hot||lit?cfg.hl:(WSP[i].exists?cfg.ring:cfg.bg); if(!WSP[i].exists && !hot && !lit) fill.a=0; if(fill.a) fill_round_rect(ren,t.x,t.y,t.w,t.h,rad,fill); if(!WSP[i].exists && !hot && !lit) - stroke_rect(ren,t.x,t.y,t.w,t.h,SDL_max(1.0f,1.5f*ui),cfg.dim); + stroke_rect(ren,t.x,t.y,t.w,t.h,fmaxf(1.0f,1.5f*ui),cfg.dim); else if(WSP[i].focused && !hot && !lit) - stroke_rect(ren,t.x,t.y,t.w,t.h,SDL_max(1.0f,2.0f*ui),cfg.accent); + stroke_rect(ren,t.x,t.y,t.w,t.h,fmaxf(1.0f,2.0f*ui),cfg.accent); Col tc = hot||lit ? cfg.hltext : (WSP[i].exists?cfg.text:cfg.dim); char num[16]; snprintf(num,sizeof num,"%d",WSP[i].num); @@ -2047,14 +1949,13 @@ int main(int argc,char**argv){ } if(over_wheel){ /* the wheel says: let go here to stop */ Col o=cfg.dim; o.a=200; - ring(ren,cx,cy,R*1.12f,SDL_max(2.0f,2.0f*ui),o); + ring(ren,cx,cy,R*1.12f,fmaxf(2.0f,2.0f*ui),o); } if(dragging && press_item>=0){ App*a=&apps.v[press_item]; float isz=cfg.icon_px*ui*1.15f; - SDL_Texture*ic=app_icon(ren,a,&cfg); - if(ic){ SDL_FRect d={mx-isz/2,my-isz/2,isz,isz}; - SDL_SetTextureAlphaMod(ic,235); SDL_RenderTexture(ren,ic,NULL,&d); } + Image ic=app_icon(a,&cfg); + if(ic.rgba) sw_blit(ren,ic,mx-isz/2,my-isz/2,isz,isz,235/255.0f); char cut[160]; fit_label(&font,cfg.label_px*ui,a->name,300.0f*ui,cut,sizeof cut); text_centered(ren,&font,mx,my+isz*0.72f,cfg.label_px*ui,cfg.text,cut); } @@ -2064,29 +1965,21 @@ int main(int argc,char**argv){ if(ERR_TEXT[0] && now_secs_() < ERR_UNTIL){ float a=(float)(ERR_UNTIL-now_secs_()); if(a>1.0f) a=1.0f; - Col ec=cfg.hl; ec.a=(Uint8)(255*a); - Col bgc=cfg.center; bgc.a=(Uint8)(bgc.a*a); + Col ec=cfg.hl; ec.a=(uint8_t)(255*a); + Col bgc=cfg.center; bgc.a=(uint8_t)(bgc.a*a); char cut[200]; fit_label(&font,cfg.label_px*ui,ERR_TEXT,(float)w*0.7f,cut,sizeof cut); float tw=text_width(&font,cfg.label_px*ui,cut); float pad=14.0f*ui, bh=cfg.label_px*ui+pad; - SDL_FRect box={(float)w*0.5f-tw*0.5f-pad, cy+R+40.0f*ui, tw+2*pad, bh}; - SDL_SetRenderDrawColor(ren,bgc.r,bgc.g,bgc.b,bgc.a); - SDL_RenderFillRect(ren,&box); - text_centered(ren,&font,(float)w*0.5f,box.y+bh*0.5f+cfg.label_px*ui*0.35f, + sw_fill_rect(ren,(float)w*0.5f-tw*0.5f-pad, cy+R+40.0f*ui, tw+2*pad, bh, bgc); + float boxy=cy+R+40.0f*ui; + text_centered(ren,&font,(float)w*0.5f,boxy+bh*0.5f+cfg.label_px*ui*0.35f, cfg.label_px*ui,ec,cut); } else if(ERR_TEXT[0] && now_secs_() >= ERR_UNTIL) { ERR_TEXT[0]=0; } - if(ss>1 && target){ - SDL_SetRenderScale(ren,1,1); - SDL_SetRenderTarget(ren,NULL); - SDL_SetRenderDrawColor(ren,0,0,0,0); - SDL_RenderClear(ren); - SDL_RenderTexture(ren,target,NULL,NULL); /* fade is per-element now */ - } - SDL_RenderPresent(ren); + sw_win_end(win); if(!ov_started && cfg.drop){ ov_started=1; /* only now: the wheel is already up */ @@ -2094,14 +1987,11 @@ int main(int argc,char**argv){ one up ourselves, if we were asked to */ if(!ov_adopt() && cfg.overview) ov_spawn(&cfg); } - SDL_Delay(16); + sw_dispatch(16); /* ~60 fps, and the compositor's events */ } ov_stop(); - if(target)SDL_DestroyTexture(target); - SDL_StopTextInput(win); - SDL_DestroyRenderer(ren); - SDL_DestroyWindow(win); - SDL_Quit(); + sw_fonts_free(); + sw_shutdown(); return (dmenu && !chose) ? 1 : 0; /* dmenu convention: non-zero on cancel */ }