From bd517aa050e8991c8cd6f59f98caea276f203196 Mon Sep 17 00:00:00 2001 From: Marc Lavergne Date: Sat, 7 Nov 2026 21:22:25 -0500 Subject: [PATCH 1/3] v0.2.1 SDL3 as a Zig package, cross-builds, D3D12, app icons - SDL3 built from source via lazy castholm/SDL dependency (no system install) - Makefile: demo, windows/linux/linux-arm64/macos-arm64/cross targets, fixed docs serve - -Dmacos-sdk for explicit macOS targets; Windows exes use GUI subsystem (-Dwindows-console opt-out) - Direct3D 12 backend: HLSL shaders compiled at runtime to DXBC, Vulkan/software fallback - App icon: SVG source, generated .ico/.png (tools/icon/mkico.py), Config.icon_png, Windows resource - Linux: installDesktopEntry / --install-desktop; UTF-8 LC_CTYPE fixes X11 title mojibake - Zig 0.17: @intFromEnum -> @backingInt --- .gitignore | 1 + CLAUDE.md | 32 +++++--- Makefile | 161 ++++++++++++++++++++++++++++++++++++ README.md | 20 ++++- assets/icon/zigui.rc | 4 + assets/icon/zigz.ico | Bin 0 -> 8576 bytes assets/icon/zigz.png | Bin 0 -> 3568 bytes assets/icon/zigz.svg | 13 +++ build.zig | 96 +++++++++++++++++----- build.zig.zon | 10 ++- examples/edit/main.zig | 5 ++ examples/showcase/main.zig | 8 +- src/app.zig | 128 ++++++++++++++++++++++++++++- src/gpu/gpu.zig | 164 ++++++++++++++++++++++++++++++++----- src/gpu/shaders/blur.hlsl | 85 +++++++++++++++++++ src/gpu/shaders/compile.sh | 7 +- src/gpu/shaders/prim.hlsl | 119 +++++++++++++++++++++++++++ src/icons.zig | 2 +- src/render/gpu_scene.zig | 14 ++-- src/text/fontset.zig | 6 +- src/view/view.zig | 4 +- tools/icon/mkico.py | 102 +++++++++++++++++++++++ 22 files changed, 910 insertions(+), 71 deletions(-) create mode 100644 Makefile create mode 100644 assets/icon/zigui.rc create mode 100644 assets/icon/zigz.ico create mode 100644 assets/icon/zigz.png create mode 100644 assets/icon/zigz.svg create mode 100644 src/gpu/shaders/blur.hlsl create mode 100644 src/gpu/shaders/prim.hlsl create mode 100644 tools/icon/mkico.py diff --git a/.gitignore b/.gitignore index bd7a2bd..e8e642f 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ zig-out/ *.a .DS_Store tools/parity/refgallery +zig-pkg/ diff --git a/CLAUDE.md b/CLAUDE.md index 3974464..397a95b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,9 @@ implemented. User-facing docs live in [README.md](README.md); design rationale i `zigui` is a SwiftUI-like UI library in **pure Zig 0.17**. The core (geometry, color, state, layout, theme, text, canvas, software rasterizer, GPU scene translation, view layer, components) has **no C dependencies** and is fully -unit-tested headlessly. SDL3 links only into example executables (`src/app.zig` +unit-tested headlessly. SDL3 is a **lazy Zig package** (castholm/SDL in +`build.zig.zon`, built from source and statically linked — no system install; +`-Dsdl3-prefix` overrides) and links only into example executables (`src/app.zig` + `src/gpu/gpu.zig`). On screen, rendering is **GPU-accelerated via SDL_GPU** (Metal on macOS, Vulkan on Linux/Windows) with an automatic fallback to the **CPU software rasterizer** presented through an SDL streaming texture — both @@ -30,6 +32,8 @@ seams each one uses. zig build test --summary all # 169 tests, headless. THIS is the inner loop. zig build showcase edit # build the two examples (does NOT run them) zig build run-showcase # opens a window — blocks on the event loop +make demo # same, ReleaseFast (SDL3 fetched/built by Zig) +make windows|linux|linux-arm64|macos-arm64 # cross-build examples → zig-out//bin docker build -t zigui-test . # run the full suite on Linux # Headless UI iteration (renders one frame to a BMP, no window): @@ -110,7 +114,7 @@ app.zig (SDL3): build → render → (GPU encode | framebuffer upload) → prese | `src/render/canvas.zig` | `DrawCommand` union + `Canvas` builder. The renderer-agnostic seam. | | `src/render/raster.zig` | `Framebuffer` + software rasterizer (SDF AA). Where new draw primitives get pixels. | | `src/render/gpu_scene.zig` | Pure GPU scene translation: `DrawCommand`s → packed `Instance` array + shelf-packed glyph/image `Atlas` + `Step` list (draw runs split at blurs). Headless-tested; no C. | -| `src/gpu/gpu.zig` | The SDL_GPU shell (app layer, links C like `app.zig`): device/pipelines/textures, replays a translated `Scene`, offscreen `renderToRgba` for verification. Shaders in `src/gpu/shaders/` (GLSL→committed SPIR-V via `compile.sh`, plus runtime-compiled MSL twins). | +| `src/gpu/gpu.zig` | The SDL_GPU shell (app layer, links C like `app.zig`): device/pipelines/textures, replays a translated `Scene`, offscreen `renderToRgba` for verification. Shaders in `src/gpu/shaders/` (GLSL→committed SPIR-V via `compile.sh`, plus runtime-compiled MSL and HLSL twins). | | `src/text/*` | `ttf` (parser+rasterizer), `atlas` (`GlyphCache`), `shape` (measure/wrap), `font` (`drawText`). | | `src/theme/theme.zig` | `Theme`, `Palette`, `Metrics`, `Typography`, and the **`Painter`** vtable + `Surface`/`ControlState`/`Role`. The color-scheme/painter vocabulary. | | `src/theme/{macos,win2000,windows10,kde,mui}.zig` | The five built-in theme families: each exports `light`/`dark` `Theme` values and a `Painter` impl drawing that family's chrome (liquid glass / bevels / flat / Breeze / Material). | @@ -179,10 +183,9 @@ exercises nav + tabs + sheet + material + a11y together; `examples/showcase` demos them in a real window. Notes below record *how* each is wired and the deliberate deviations from the original plan, so you can extend safely. -### GPU backend — SDL_GPU (Metal/Vulkan) with software fallback -On-screen rendering now goes through **SDL3's GPU API** (Metal on macOS, Vulkan -on Linux/Windows; D3D12 needs DXIL blobs, a follow-up — Windows uses its Vulkan -driver meanwhile), replacing the framebuffer-upload present path while keeping +### GPU backend — SDL_GPU (Metal/D3D12/Vulkan) with software fallback +On-screen rendering now goes through **SDL3's GPU API** (Metal on macOS, +Direct3D 12 on Windows with Vulkan as its fallback, Vulkan on Linux), replacing the framebuffer-upload present path while keeping it as the automatic fallback (`Config.gpu = false` or `ZIGUI_SOFTWARE=1` forces it; device/swapchain failure falls back silently). No new dependencies: the C surface is `src/gpu/gpu.zig`, owned by `app.zig`, sharing its `@cImport`. @@ -213,11 +216,20 @@ The split keeps the repo's testing philosophy intact: scene texture, then `SDL_BlitGPUTexture` to the swapchain. - **Shaders** in `src/gpu/shaders/`: GLSL sources compiled to **committed SPIR-V blobs** by `compile.sh` (needs `glslc`; only when shaders change) and - hand-written **MSL twins** compiled by Metal at runtime — keep both in sync. + hand-written **MSL twins** compiled by Metal at runtime, and **HLSL twins** + (`prim.hlsl`/`blur.hlsl`) compiled on Windows at runtime to DXBC SM5.1 via + `D3DCompile` from the system's `d3dcompiler_47.dll` (loaded with + `SDL_LoadObject`; no build-time toolchain) — keep all three in sync. SDL_GPU binding conventions: SPIR-V vertex uniforms `set=1`, fragment textures `set=2`, fragment uniforms `set=3`; MSL uses `[[stage_in]]` + - `[[buffer(0)]]`/`[[texture(0)]]`. NDC is +Y-up on **all** backends (SDL - converts for Vulkan), so both sources share the same `-ndc.y` flip. + `[[buffer(0)]]`/`[[texture(0)]]`; HLSL uses vertex inputs `TEXCOORD`, + vertex cbuffer `(b0, space1)`, pixel `t0`/`s0` in `space2`, pixel cbuffer + `(b0, space3)`, and `SampleLevel(…, 0)` (legal in divergent branches/loops). + NDC is +Y-up on **all** backends (SDL converts for Vulkan), so every source + shares the same `-ndc.y` flip. SDL tries Metal → D3D12 → Vulkan; if D3D12's + pipelines fail to build, `Gpu.init` retries without DXBC (Vulkan) before + falling back to software. Verify D3D12 on a Windows box with + `showcase.exe --gpu --screenshot` (cross-build: `make windows`). Output parity: verified pixel-identical to the rasterizer (max 1 LSB/channel) across every showcase section, dark mode, all theme families, sheets/alerts, @@ -597,7 +609,7 @@ Powers `examples/edit` (a TextEdit/gedit-like editor); all headless-tested. - Colors always go through `multiplyAlpha(ctx.opacity)` when painting. - New shapes/effects: add a `DrawCommand` and handle it in **both** backends — the software rasterizer (`render/raster.zig`) and the GPU path - (`render/gpu_scene.zig` + the shaders in `src/gpu/shaders/`, GLSL **and** MSL, + (`render/gpu_scene.zig` + the shaders in `src/gpu/shaders/`, GLSL, MSL **and** HLSL, then re-run `compile.sh`) — keeping command semantics backend-neutral. Verify with `showcase --screenshot --gpu` diffed against the software BMP. - Run `zig build test` after every change; keep it green. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..dd4f8db --- /dev/null +++ b/Makefile @@ -0,0 +1,161 @@ +############################################### +# +# Makefile — zigui +# +# `make validate` is the pre-commit gate; `make build` is the entry point. +# +############################################### + +# Optional include to extend the makefile targets +-include ../styleguide/Makefile.in + +.DEFAULT_GOAL := all + +.PHONY: build dist run demo edit test docs clean windows linux linux-arm64 macos-arm64 cross + +# --------------------------------------------- +# Configuration +# --------------------------------------------- + +# The released version, read from build.zig.zon (the source of truth). +VERSION := $(shell sed -n -E 's/^[[:space:]]*\.version[[:space:]]*=[[:space:]]*"([^"]+)".*/\1/p' build.zig.zon) + +# --------------------------------------------- +# Primary workflows +# --------------------------------------------- + +# Build, format, and test. +all: build format test + @echo "done" + +# --------------------------------------------- +# Build +# --------------------------------------------- + +# Build the library and examples. +build: + zig build + +# Build optimized for release. +dist: + zig build --release=fast + +# --------------------------------------------- +# Cross-platform builds +# --------------------------------------------- + +# Release builds of both examples for each platform, into zig-out//bin. +# SDL3 is compiled from source per target, so no SDL install is needed for any +# of them. Linux binaries load X11/Wayland/GL/Vulkan at runtime. +CROSS = zig build showcase edit -Doptimize=ReleaseFast -Dtarget=$(1) --prefix zig-out/$(1) $(2) + +# The macOS SDK (Xcode or Command Line Tools): an explicit macOS target is a +# cross build to Zig, so SDL needs the SDK's frameworks passed in. +MACOS_SDK = $(shell xcrun --show-sdk-path 2>/dev/null) + +windows: + $(call CROSS,x86_64-windows-gnu) + +linux: + $(call CROSS,x86_64-linux-gnu) + +linux-arm64: + $(call CROSS,aarch64-linux-gnu) + +macos-arm64: + @test -n "$(MACOS_SDK)" || { echo "❌ macOS SDK not found (needs macOS + xcode-select --install)"; exit 1; } + $(call CROSS,aarch64-macos,-Dmacos-sdk=$(MACOS_SDK)) + +# All four platforms. +cross: windows linux linux-arm64 macos-arm64 + +# Build and launch the showcase (the kitchen-sink gallery) in a window. +# SDL3 is fetched and compiled from source by Zig on first use — no Homebrew. +# ReleaseFast because the software rasterizer is ~10x slower in Debug. +demo: + zig build run-showcase -Doptimize=ReleaseFast -- $(ARGS) + +# Build the edit example (the multi-line text editor) into zig-out/bin. +edit: + zig build edit + +# Build and run the showcase in a window. Pass arguments with `make run ARGS="--dark"`. +run: + zig build run-showcase -- $(ARGS) + +# --------------------------------------------- +# Test +# --------------------------------------------- + +# Run the unit test suite. +test: + zig build test --summary all + +# --------------------------------------------- +# Documentation +# --------------------------------------------- + +# Build the API docs and serve them locally (Ctrl-C stops the server). +# The browser opens only once the server answers — opening it first raced the +# server's startup and showed "can't connect". A busy port fails loudly. +# Not 8080: other local tools (e.g. llama.cpp's web UI) leave a service worker +# registered on 127.0.0.1:8080 that keeps serving their app instead of these +# docs. A service worker is per origin, so a dedicated port sidesteps it. +DOCS_PORT ?= 8080 +OPEN ?= open +docs: + zig build docs + @! curl -s -o /dev/null "http://127.0.0.1:$(DOCS_PORT)/" || { echo "❌ port $(DOCS_PORT) is already serving something (an old 'make docs'?) — stop it or use DOCS_PORT=8081"; exit 1; } + @echo "Serving zig-out/docs at http://127.0.0.1:$(DOCS_PORT)/ (Ctrl-C to stop)" + @python3 -m http.server -b 127.0.0.1 $(DOCS_PORT) -d zig-out/docs & pid=$$!; \ + trap 'kill $$pid 2>/dev/null' INT TERM EXIT; \ + until curl -fs -o /dev/null "http://127.0.0.1:$(DOCS_PORT)/"; do \ + kill -0 $$pid 2>/dev/null || { echo "❌ docs server failed to start (port $(DOCS_PORT) in use? try DOCS_PORT=8081)"; exit 1; }; \ + sleep 0.1; \ + done; \ + $(OPEN) "http://127.0.0.1:$(DOCS_PORT)/"; \ + wait $$pid + +# --------------------------------------------- +# Release +# --------------------------------------------- + +# Tag the build.zig.zon version (e.g. 1.0.0) and push it. +tag: + @test -n "$(VERSION)" || { echo "❌ could not read .version from build.zig.zon"; exit 1; } + git tag -a "$(VERSION)" -m "$(VERSION)" + git push + git push --tags + +# --------------------------------------------- +# Environment +# --------------------------------------------- + +# Open the working copy in SourceTree. +st: + open -a SourceTree . + +# Open the project in the editor. +open: + code . + +# Open the repository on GitHub. +github: + open "https://github.com/ddalcu/zigui" + +# Clone a fresh working copy. +clone: + git clone git@github.com:ddalcu/zigui.git + +# Start Claude Code here. +claude: + claude + +# --------------------------------------------- +# Housekeeping +# --------------------------------------------- + +# Remove every build artifact. +clean: + rm -rf .zig-cache + rm -rf zig-out diff --git a/README.md b/README.md index 8d5d766..77ab492 100644 --- a/README.md +++ b/README.md @@ -151,8 +151,9 @@ zig build test --summary all zig build docs # API docs into zig-out/docs ``` -Run the demo apps (require SDL3 — `brew install sdl3` on macOS, -`apt install libsdl3-dev` on Linux): +Run the demo apps. SDL3 is a Zig package dependency (castholm/SDL), fetched and +compiled from source on first build and linked statically — nothing to install +but Zig. (`-Dsdl3-prefix=` links a prebuilt SDL3 instead.) ```sh zig build run-showcase # the kitchen-sink gallery: every component, @@ -165,6 +166,21 @@ zig build showcase edit # build the examples without running them ./zig-out/bin/showcase --screenshot out.bmp [section] [--dark] [--accent N] [--gpu] ``` +The Makefile provides optional convenience targets that wrap `zig build` for each +supported target triple. `zig build` remains the primary build interface. + +```sh +make demo # build (ReleaseFast) + launch the showcase +make windows | linux | linux-arm64 | macos-arm64 # cross-build both examples + # into zig-out//bin (`make cross` = all) + # Windows builds are GUI apps (no console); + # add -Dwindows-console=true to see logs + # App icon: assets/icon/zigz.svg; regenerate the + # .ico/.png with tools/icon/mkico.py + # Linux: run `showcase --install-desktop` once so + # GNOME/Wayland shows the icon (adds a .desktop entry) +``` + > If the software fallback is in use, run with `-Doptimize=ReleaseFast` for > smooth UI — the CPU rasterizer is much slower in the default Debug build. diff --git a/assets/icon/zigui.rc b/assets/icon/zigui.rc new file mode 100644 index 0000000..dd0123a --- /dev/null +++ b/assets/icon/zigui.rc @@ -0,0 +1,4 @@ +// The app icon, embedded into the Windows examples by build.zig +// (addWin32ResourceFile). SDL also picks it up for the window class icon. +// Regenerate zigz.ico with tools/icon/mkico.py after editing zigz.svg. +1 ICON "zigz.ico" diff --git a/assets/icon/zigz.ico b/assets/icon/zigz.ico new file mode 100644 index 0000000000000000000000000000000000000000..90b6d5889aad0aa4e32db7ec8d00782fa1ca510c GIT binary patch literal 8576 zcmai2c{r4B)PBd3eakM)kTrYuvhTaJAjw#gElZTbFqUM?z6_#CQmI6ikYzArEz;tr zWXzxvWkzB!X1;f(Z~NoBzMt!w>wVAlJm=i^xzBkPF91LQ4uGE@0G}{`3;;kG_!AQP zYpX*5AP@YBiT$oi1O)%+_(br%Ko9`3PPo|ea7utP0UmohtCQdpWC-xHgYyCC zZ<-(Yz}Q=vpT7Pnz!%1hfXj}v56+uO+CH`sf#tCfxXcjTnX^&KI&6dkI&++Z*OJMm z{HARF_TH7k$zLw&=|rj0V*n?13fMlfa0+P_`n7(^B@ zIadn3b}*yxKHd@K|6F*l;!viBtf4XLG*ZKQx|>I$VWeCN{gsKytpl2Q_HsxpK)_ws z!7=*_cvl9dkXcXTFT-4z2`oBKvmLdM>*SeNVAHCeit|L9FjoM;5nHOs+%}W|rUKYo zyI4K5@J;`5`mJDKL0Y;Z7B10ZR^E*_qN zxxn54gyUuuXeOHZxtxr1s2M^kb3LGcz2-m)(G~VW=0Z8}zKLeFplWebi7YrdO%3;k4Vb0I|5M~JG(I&XrC0qN{FUem&csm@7P^|oD$g(K+fNu2>nItqGQKT_<;>Js z>+~#x}V6e4&)3hm$iZxG#SaIcX~p}E}wo3!q6GkE|A zeiX}sdoJ$uFKU5(3Wzb(TDWEmb~8lkztw{Lk6ND&v;ddo_~8H{z-+=sEzK~+fH`v= zAR%E%yn{u9p=A(%Hlq&7Otd-A0X*95lI2tUfEj|%UR%o`#}j)t<+^Fs%}E(~?}x>~ zWDeLx#g9?euwTO|qJCPELiN+{?bIgBx&>bo>1s7B{gXHJr}O<$BbH2BjkpQg>t+}z zs}9x`qQ$1m{f(J$DEKA@@IM~(00o5nM^^`5iROSRC;Obu(CLguT)=R6ARILME| z5_YA`x}~{%n2!i$=~jX27I`|A6cBdn;RO_pD)z?{n}JBMeGcZO*2e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Yr_d3+=2gCn`_rxHCzNn2TfD|=rgMKS&MRW5v^93mOK|0(Li?l?i4{<%_KiP4Z>-viaZt@BIgd8~|?s literal 0 HcmV?d00001 diff --git a/assets/icon/zigz.png b/assets/icon/zigz.png new file mode 100644 index 0000000000000000000000000000000000000000..efdb989b1d9b0cc90de0d8881508a88bb030a847 GIT binary patch literal 3568 zcmXX}X+TrQ7QO*-VT*`@s1V8`Mj{cB24sn{2)1gZu2>e4O^O(bmc@jG3K${9h=@T2 zA}R`6L_muaAvAz2p}5c|Ws#7WR48Z?P`E2Gpanuz>AMbA(CkeTVHfB6>iIzPxy zvErPybqPz^Gw3pp_lg&sp7EZaANlO*@&cJ_nh569%?wNo#S);v+>+VP@%FSr^XaY7 z>t({7rR4A{;^<8@y%siXDPQ^J{I7gMr?;mCB$4)a#Vh8PH#dBHQ9cgAMr^9P?p zoPql%-3@e@Bc|>QyOpmOUdzB;TfIF^L?9A2N$uAJC)TZN`wO~`d2v7FYUUUhzwq4I zE8{MQE|3by;XOgH-aY3X8F#b6nwC$OZ)Q%@*3IFzdTX|&RfP!pRDV9HHRxNk!Ar9s zH*B!)koI#Bt#8qW?Qv*zxM;!22M_1cBJV?L6=(46tUGKdbRKDm>I-gpE5EEdm2$G! zF$rWlGNi36e4Dzy@}3EE~?go!i#7 zoH6qH6sPDrb-13GSCRR36*eWXL(OPSXZgCha#KV- zwEEw3*KZ!>@P=lPe?EaKYe<_yxYKLDC&TVgbN*38rF ziyi6$wUq1isIxu_k4lkB9ZN{eU-A5B>vjN)#AR}Z#3ZGfMBgzHhEA#t4Xn7uz82#r zAz=gvMeACFg2ch9BX`~^|1JQG$V3vJYnACCe}x`pN!K1=K#~oBvr9t6=Q?cY_kd+| z)3D)|TOH?SmhJog-@r)SqAsu_dBShpw{wj;yb~-^x=m1gN7m1Es+v(dlx0DIYIf&u zc|G@xz47ZVhUIf%k5+SI3$$j$jgjrUg{BrdFkC`2&cCb9r+IKCPAOhj$938$8Sci& zIQ3eWPTM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- z*k_;P7bZ9Pb~qE!RU+*2g47(K4H7M>2+@=%zO^uvgxRLsnd*QgsP9Y*eRg$-9}I1( z!)e@nrBrLq=2aP2a}c@Vu!06d2QLVPnu=VhGJkqfl^+K^KB@VjpgvfqwO)_gS7LN5 zY?Vl|>Y=H}rDf0ovQ~V5r51<2Tc5L;OKZ!+%+!veC7nApO^P`)efGu4*8S)zK~Zb= zG-CD;*aGe`vRehjS;a2hD6*F8xUxC@$1(FP{H3=rPhVKT_h2@<+;pU^wr*65;bk%oa%6wdL{>= zEp4G|9I|ixWFW1!V`hN&p93XJB`AnY+X#UN)82=d#LEcQO-7?W^Y5uN9cwQwKKb?! WtYf-IcY + + + + + + + + + + + + diff --git a/build.zig b/build.zig index 8acc6e5..27aef0b 100644 --- a/build.zig +++ b/build.zig @@ -69,20 +69,36 @@ pub fn build(b: *std.Build) void { // `showcase` is the kitchen-sink gallery (every component + light/dark and // accent switchers); `edit` is the multi-line text editor. Both support a // headless `--screenshot ` flag for windowless rendering. - // `-Dsdl3-prefix=

` (with `include/` and `lib/`) points at an SDL3 install - // anywhere — the way to build for Windows or against a self-built SDL. + // SDL3 is built from source as a lazy Zig package (see `linkSdl3`); + // `-Dsdl3-prefix=` (with `include/` and `lib/`) links a prebuilt one. + // `-Dmacos-sdk=$(xcrun --show-sdk-path)` is needed whenever macOS is an + // explicit `-Dtarget` (Zig then treats it as a cross build and won't probe + // the host SDK for AppKit/Metal). const sdl3_prefix = b.option([]const u8, "sdl3-prefix", "SDL3 install prefix (include/ and lib/ inside)"); - addExample(b, mod, target, optimize, sdl3_prefix, "showcase", "examples/showcase/main.zig"); - addExample(b, mod, target, optimize, sdl3_prefix, "edit", "examples/edit/main.zig"); + const macos_sdk = b.option([]const u8, "macos-sdk", "macOS SDK path for explicit macOS targets (xcrun --show-sdk-path)"); + // Windows executables are GUI-subsystem by default so launching one + // doesn't open a console window; `-Dwindows-console` keeps the console + // (log output, `--screenshot` messages) for debugging. + const windows_console = b.option(bool, "windows-console", "Build Windows examples as console apps (shows log output)") orelse false; + const sdl: SdlConfig = .{ .prefix = sdl3_prefix, .macos_sdk = macos_sdk, .windows_console = windows_console }; + addExample(b, mod, target, optimize, sdl, "showcase", "examples/showcase/main.zig"); + addExample(b, mod, target, optimize, sdl, "edit", "examples/edit/main.zig"); } +/// Where SDL3 and (for explicit macOS targets) the system SDK come from. +const SdlConfig = struct { + prefix: ?[]const u8, + macos_sdk: ?[]const u8, + windows_console: bool, +}; + /// Build a runnable example that links the SDL3-backed runtime (`src/app.zig`). fn addExample( b: *std.Build, zigui_mod: *std.Build.Module, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, - sdl3_prefix: ?[]const u8, + sdl: SdlConfig, name: []const u8, root_path: []const u8, ) void { @@ -102,10 +118,13 @@ fn addExample( .imports = &.{.{ .name = "zigui", .module = zigui_mod }}, }); app_mod.addImport("sdl_c", sdl_c.createModule()); - linkSdl3(b, app_mod, sdl_c, sdl3_prefix); + linkSdl3(b, app_mod, sdl_c, target, optimize, sdl); // app.zig reaches AppKit (unified titlebar, menu bar, template tray icons) // through the Objective-C runtime. - if (target.result.os.tag == .macos) app_mod.linkSystemLibrary("objc", .{}); + if (target.result.os.tag == .macos) { + if (sdl.macos_sdk) |sdk| addMacosSdk(b, app_mod, sdk); + app_mod.linkSystemLibrary("objc", .{}); + } // libc headers the examples use (stdio/time), via translate-c as `cstdio`. const cstdio = b.addTranslateC(.{ @@ -131,6 +150,15 @@ fn addExample( }, }), }); + // The app icon (assets/icon, generated by tools/icon/mkico.py): the PNG is + // importable as `@embedFile("app_icon")` for `Config.icon_png` (window / + // Dock icon on macOS and Linux); on Windows the multi-size .ico is also + // embedded as a resource for Explorer, the title bar and the taskbar. + exe.root_module.addAnonymousImport("app_icon", .{ .root_source_file = b.path("assets/icon/zigz.png") }); + if (target.result.os.tag == .windows) { + exe.root_module.addWin32ResourceFile(.{ .file = b.path("assets/icon/zigui.rc") }); + if (!sdl.windows_console) exe.subsystem = .windows; + } const install = b.addInstallArtifact(exe, .{}); // `zig build ` builds (and installs) the example. @@ -144,21 +172,51 @@ fn addExample( run_step.dependOn(&run_cmd.step); } -/// Wire up SDL3 headers/libs. On a macOS build host, point at the Homebrew -/// prefix matching the host arch (Apple Silicon → /opt/homebrew, Intel → -/// /usr/local). On Linux the system linker / pkg-config finds SDL3. -/// An explicit `-Dsdl3-prefix` overrides both. -fn linkSdl3(b: *std.Build, m: *std.Build.Module, tc: *std.Build.Step.TranslateC, override: ?[]const u8) void { - const host = @import("builtin"); - const prefix: ?[]const u8 = override orelse if (host.os.tag == .macos) - (if (host.cpu.arch == .aarch64) "/opt/homebrew/opt/sdl3" else "/usr/local/opt/sdl3") - else - null; - if (prefix) |p| { +/// Wire up SDL3. By default SDL3 is built from source as a Zig package +/// (castholm/SDL, pinned in build.zig.zon) and linked statically, so the +/// examples need nothing installed beyond the Zig toolchain. The dependency is +/// lazy: `zig build test` never fetches or compiles it. +/// `-Dsdl3-prefix=` (with `include/` and `lib/`) links a prebuilt SDL3 +/// install instead — e.g. a self-built SDL, or a distro package on Linux. +fn linkSdl3( + b: *std.Build, + m: *std.Build.Module, + tc: *std.Build.Step.TranslateC, + target: std.Build.ResolvedTarget, + optimize: std.builtin.OptimizeMode, + sdl: SdlConfig, +) void { + if (sdl.prefix) |p| { m.addIncludePath(.{ .cwd_relative = b.fmt("{s}/include", .{p}) }); m.addLibraryPath(.{ .cwd_relative = b.fmt("{s}/lib", .{p}) }); m.addRPath(.{ .cwd_relative = b.fmt("{s}/lib", .{p}) }); tc.addIncludePath(.{ .cwd_relative = b.fmt("{s}/include", .{p}) }); + m.linkSystemLibrary("SDL3", .{}); + return; } - m.linkSystemLibrary("SDL3", .{}); + const sdl_dep = if (sdl.macos_sdk) |sdk| b.lazyDependency("sdl", .{ + .target = target, + .optimize = optimize, + .preferred_linkage = .static, + .system_include_path = std.Build.LazyPath{ .cwd_relative = b.fmt("{s}/usr/include", .{sdk}) }, + .system_framework_path = std.Build.LazyPath{ .cwd_relative = b.fmt("{s}/System/Library/Frameworks", .{sdk}) }, + .library_path = std.Build.LazyPath{ .cwd_relative = b.fmt("{s}/usr/lib", .{sdk}) }, + }) else b.lazyDependency("sdl", .{ + .target = target, + .optimize = optimize, + .preferred_linkage = .static, + }); + // First pass: the package is fetched, then build() reruns. + const dep = sdl_dep orelse return; + const sdl_lib = dep.artifact("SDL3"); + m.linkLibrary(sdl_lib); + tc.addIncludePath(sdl_lib.getEmittedIncludeTree()); +} + +/// Point a module at a macOS SDK's headers, frameworks and libraries (the +/// `-Dmacos-sdk` path), which Zig doesn't probe for an explicit macOS target. +fn addMacosSdk(b: *std.Build, m: *std.Build.Module, sdk: []const u8) void { + m.addSystemIncludePath(.{ .cwd_relative = b.fmt("{s}/usr/include", .{sdk}) }); + m.addSystemFrameworkPath(.{ .cwd_relative = b.fmt("{s}/System/Library/Frameworks", .{sdk}) }); + m.addLibraryPath(.{ .cwd_relative = b.fmt("{s}/usr/lib", .{sdk}) }); } diff --git a/build.zig.zon b/build.zig.zon index b71ddad..49747ca 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -1,9 +1,15 @@ .{ .name = .zigui, - .version = "0.2.0", + .version = "0.2.1", .fingerprint = 0x18d03e108d8c3c7e, .minimum_zig_version = "0.17.0", - .dependencies = .{}, + .dependencies = .{ + .sdl = .{ + .url = "git+https://github.com/castholm/SDL.git?ref=v0.6.1+3.4.20#ce475292f172d506468218f939ef607d9be5e083", + .hash = "sdl-0.6.1+3.4.20-SDL--rskqQH3W9l4AJX-kdZ93M9XuhsqLrUsd2fnUE_X", + .lazy = true, + }, + }, .paths = .{ "build.zig", "build.zig.zon", diff --git a/examples/edit/main.zig b/examples/edit/main.zig index 1dc167c..4355c91 100644 --- a/examples/edit/main.zig +++ b/examples/edit/main.zig @@ -587,6 +587,10 @@ pub fn main(init: std.process.Init.Minimal) !void { demo_drag = true; } else if (std.mem.eql(u8, a, "--dark")) { force_dark = true; + } else if (std.mem.eql(u8, a, "--install-desktop")) { + // Linux: add a launcher entry + icon (see app.installDesktopEntry). + if (!app.installDesktopEntry("zigui Editor", @embedFile("app_icon"))) return error.InstallFailed; + return; } else if (!std.mem.startsWith(u8, a, "-")) { open_path = a; } @@ -632,5 +636,6 @@ pub fn main(init: std.process.Init.Minimal) !void { .title = "zigui — Editor", .width = 880, .height = 600, + .icon_png = @embedFile("app_icon"), }, body, null); } diff --git a/examples/showcase/main.zig b/examples/showcase/main.zig index d3bdea3..aad8e2f 100644 --- a/examples/showcase/main.zig +++ b/examples/showcase/main.zig @@ -7,6 +7,7 @@ //! //! Build with `zig build showcase` (run with `zig build run-showcase`). //! Headless: `showcase --screenshot [section]` renders one frame. +//! Linux: `showcase --install-desktop` adds a launcher entry with the icon. const std = @import("std"); const zigui = @import("zigui"); @@ -858,6 +859,11 @@ pub fn main(init: std.process.Init.Minimal) !void { st.show_popover.set(true); } else if (std.mem.eql(u8, a, "--menu")) { st.menu_open.set(true); + } else if (std.mem.eql(u8, a, "--install-desktop")) { + // Linux: add a launcher entry + icon (GNOME/Wayland shows the + // icon only through one). See app.installDesktopEntry. + if (!app.installDesktopEntry("zigui Showcase", @embedFile("app_icon"))) return error.InstallFailed; + return; } else { section = std.fmt.parseInt(i64, a, 10) catch section; } @@ -870,5 +876,5 @@ pub fn main(init: std.process.Init.Minimal) !void { return screenshot(alloc, &st, out, bench, use_gpu); } - try app.run(alloc, AppState, &st, .{ .title = "zigui — Showcase", .width = 980, .height = 660 }, body, null); + try app.run(alloc, AppState, &st, .{ .title = "zigui — Showcase", .width = 980, .height = 660, .icon_png = @embedFile("app_icon") }, body, null); } diff --git a/src/app.zig b/src/app.zig index e0a79cb..c13b928 100644 --- a/src/app.zig +++ b/src/app.zig @@ -43,6 +43,13 @@ pub const Config = struct { /// is created. `rgba` is row-major RGBA8 (`w*h*4` bytes); the surface is /// copied by SDL, so the caller may free `rgba` after `run` sets it. icon: ?WindowIcon = null, + /// Optional window/taskbar icon as PNG bytes (e.g. `@embedFile` of a + /// 256 px PNG), decoded with SDL's built-in loader — the icon on macOS + /// (the Dock) and Linux (X11 / Wayland window icon). On Windows an icon + /// resource embedded in the .exe wins, since it carries every size and + /// SDL already uses it for the window; `icon_png` is the fallback there. + /// Ignored when `icon` is set. + icon_png: ?[]const u8 = null, /// Supersampling factor: the UI is rendered into a framebuffer this many /// times larger per axis, then downscaled on present (SSAA). On a low-DPI /// (100%) display this is what makes text crisp — gamma adds weight, but @@ -689,6 +696,104 @@ fn trayThunk(userdata: ?*anyopaque, entry: ?*c.SDL_TrayEntry) callconv(.c) void /// Build an `SDL_Surface` from row-major RGBA8 pixels (the format zigui's /// `Framebuffer.toRgba8Alloc` produces). Returns null on failure. +/// Give the C library a UTF-8 character-type locale before SDL talks to the +/// display. Unix processes start in the "C" locale, and on X11 (which SDL +/// also picks under GNOME/XWayland) the legacy WM_NAME title goes through +/// Xlib's locale conversion: in "C" the UTF-8 bytes of "zigui — Showcase" are +/// stored as Latin-1 and the title bar shows "zigui â\u{80}\u{94} Showcase". +/// Only LC_CTYPE is touched (as GTK/Qt apps do), so number formatting and +/// collation stay "C". Uses the user's locale, else C.UTF-8. No-op off +/// Linux/BSD. +fn useUtf8Locale() void { + switch (builtin.os.tag) { + .linux, .freebsd, .openbsd, .netbsd, .dragonfly => {}, + else => return, + } + if (std.c.setlocale(.CTYPE, "")) |name| { + const n = std.mem.span(name); + if (std.ascii.findIgnoreCase(n, "utf-8") != null or std.ascii.findIgnoreCase(n, "utf8") != null) return; + } + _ = std.c.setlocale(.CTYPE, "C.UTF-8"); +} + +/// Linux desktop integration: install a freedesktop entry for the running +/// executable — `$XDG_DATA_HOME/applications/.desktop` (default +/// `~/.local/share`) plus the icon at `icons/hicolor/256x256/apps/.png`. +/// +/// Why: on Wayland a runtime window icon (`Config.icon_png`) needs the +/// `xdg_toplevel_icon_v1` protocol, which KDE Plasma supports but GNOME does +/// not; GNOME instead matches the window's app ID — SDL uses the executable +/// name — to a .desktop file and shows *its* icon (Dock, Activities, Alt-Tab). +/// The entry also puts the app in the launcher. Returns false off Linux or on +/// any I/O failure (logged). Re-run after moving the executable. +pub fn installDesktopEntry(name: []const u8, icon_png: []const u8) bool { + if (builtin.os.tag != .linux) return false; + var exe_buf: [4096]u8 = undefined; + const n = std.c.readlink("/proc/self/exe", &exe_buf, exe_buf.len); + if (n <= 0) return false; + const exe = exe_buf[0..@intCast(n)]; + // SDL's default app ID is the executable's basename; match it. + const id = exe[(std.mem.lastIndexOfScalar(u8, exe, '/') orelse return false) + 1 ..]; + + var data_buf: [4096]u8 = undefined; + const data_dir: []const u8 = if (c.SDL_getenv("XDG_DATA_HOME")) |x| + std.mem.span(x) + else if (c.SDL_getenv("HOME")) |h| + std.fmt.bufPrint(&data_buf, "{s}/.local/share", .{std.mem.span(h)}) catch return false + else + return false; + + var path_buf: [4096]u8 = undefined; + var icon_buf: [4096]u8 = undefined; + const icon_dir = std.fmt.bufPrintSentinel(&path_buf, "{s}/icons/hicolor/256x256/apps", .{data_dir}, 0) catch return false; + if (!c.SDL_CreateDirectory(icon_dir.ptr)) return logInstallError(icon_dir); + const icon_path = std.fmt.bufPrintSentinel(&icon_buf, "{s}/{s}.png", .{ icon_dir, id }, 0) catch return false; + if (!c.SDL_SaveFile(icon_path.ptr, icon_png.ptr, icon_png.len)) return logInstallError(icon_path); + + const app_dir = std.fmt.bufPrintSentinel(&path_buf, "{s}/applications", .{data_dir}, 0) catch return false; + if (!c.SDL_CreateDirectory(app_dir.ptr)) return logInstallError(app_dir); + var entry_buf: [8192]u8 = undefined; + // Exec is quoted so paths with spaces work; Icon is the absolute path so + // no icon-theme cache refresh is needed. StartupWMClass ties X11 windows + // to the entry too (Wayland matches by file name = app ID). + const entry = std.fmt.bufPrint(&entry_buf, + \\[Desktop Entry] + \\Type=Application + \\Name={s} + \\Exec="{s}" + \\Icon={s} + \\StartupWMClass={s} + \\Terminal=false + \\Categories=Utility; + \\ + , .{ name, exe, icon_path, id }) catch return false; + var desk_buf: [4096]u8 = undefined; + const desk_path = std.fmt.bufPrintSentinel(&desk_buf, "{s}/{s}.desktop", .{ app_dir, id }, 0) catch return false; + if (!c.SDL_SaveFile(desk_path.ptr, entry.ptr, entry.len)) return logInstallError(desk_path); + std.log.info("zigui: installed {s} (icon {s})", .{ desk_path, icon_path }); + return true; +} + +fn logInstallError(path: []const u8) bool { + std.log.err("zigui: cannot write {s} ({s})", .{ path, c.SDL_GetError() }); + return false; +} + +/// Whether this Windows .exe embeds an icon resource (RT_GROUP_ICON id 1, as +/// assets/icon/zigui.rc declares). SDL registers its window class with that +/// icon at every size, so a single-image `SDL_SetWindowIcon` would only make +/// it worse. Always false elsewhere. +fn hasIconResource() bool { + if (builtin.os.tag != .windows) return false; + const k32 = struct { + // Resource names/types are passed as MAKEINTRESOURCE integers. + extern "kernel32" fn GetModuleHandleW(name: ?[*:0]const u16) callconv(.winapi) ?*anyopaque; + extern "kernel32" fn FindResourceW(module: ?*anyopaque, name: usize, kind: usize) callconv(.winapi) ?*anyopaque; + }; + const rt_group_icon: usize = 14; + return k32.FindResourceW(k32.GetModuleHandleW(null), 1, rt_group_icon) != null; +} + fn makeSurface(rgba: []const u8, w: c_int, h: c_int) ?*c.SDL_Surface { const surf = c.SDL_CreateSurface(w, h, c.SDL_PIXELFORMAT_ABGR8888) orelse return null; const uw: usize = @intCast(w); @@ -770,6 +875,7 @@ pub const Tray = struct { /// initialized if it isn't already (idempotent), so this may be called /// before `run`. pub fn create(gpa: std.mem.Allocator, rgba: []const u8, w: c_int, h: c_int, tooltip: [:0]const u8) !Tray { + useUtf8Locale(); _ = c.SDL_Init(c.SDL_INIT_VIDEO); const surf = makeSurface(rgba, w, h) orelse return Error.TrayInit; const handle = c.SDL_CreateTray(surf, tooltip.ptr) orelse { @@ -843,6 +949,7 @@ pub const Tray = struct { /// macOS the icon shows at half its pixel size in points (36 px → 18 pt, the /// usual menu-bar glyph). pub fn createStatusItem(rgba: []const u8, w: c_int, h: c_int, tooltip: [:0]const u8, on_click: zigui.Callback) bool { + useUtf8Locale(); _ = c.SDL_Init(c.SDL_INIT_VIDEO); switch (builtin.os.tag) { .macos => return cocoa.createStatusItem(rgba, w, h, tooltip, on_click), @@ -897,6 +1004,7 @@ pub fn run( // A hide-to-tray app must not quit when its last visible window is closed: // SDL would send SDL_EVENT_QUIT itself, before our close handler hides it. if (cfg.hide_on_close) _ = c.SDL_SetHint(c.SDL_HINT_QUIT_ON_LAST_WINDOW_CLOSE, "0"); + useUtf8Locale(); if (!c.SDL_Init(c.SDL_INIT_VIDEO)) { std.log.err("SDL_Init failed: {s}", .{c.SDL_GetError()}); return Error.SdlInit; @@ -929,6 +1037,14 @@ pub fn run( _ = c.SDL_SetWindowIcon(window, surf); c.SDL_DestroySurface(surf); } + } else if (cfg.icon_png) |bytes| { + if (!hasIconResource()) { + const io = c.SDL_IOFromConstMem(bytes.ptr, bytes.len); + if (c.SDL_LoadPNG_IO(io, true)) |surf| { + _ = c.SDL_SetWindowIcon(window, surf); + c.SDL_DestroySurface(surf); + } else std.log.info("zigui: icon_png not loaded ({s})", .{c.SDL_GetError()}); + } } // Prefer the GPU backend; when device/swapchain creation fails (no Vulkan @@ -1631,7 +1747,17 @@ const cocoa = struct { return @call(.auto, f, .{ target, sel_registerName("initWithBitmapDataPlanes:pixelsWide:pixelsHigh:bitsPerSample:samplesPerPixel:hasAlpha:isPlanar:colorSpaceName:bitmapFormat:bytesPerRow:bitsPerPixel:"), - planes, w, h, bps, spp, alpha, planar, cs, fmt, bpr, bpp, + planes, + w, + h, + bps, + spp, + alpha, + planar, + cs, + fmt, + bpr, + bpp, }); } diff --git a/src/gpu/gpu.zig b/src/gpu/gpu.zig index 284600e..a5aa159 100644 --- a/src/gpu/gpu.zig +++ b/src/gpu/gpu.zig @@ -1,5 +1,5 @@ //! SDL_GPU backend: renders a `Canvas` command list on the GPU (Metal on -//! macOS, Vulkan on Linux/Windows, D3D12 once DXIL blobs are added) through +//! macOS, Direct3D 12 or Vulkan on Windows, Vulkan on Linux) through //! SDL3's GPU API — no dependencies beyond the SDL3 the runtime already links. //! //! All the interesting decisions are made headlessly in @@ -19,7 +19,9 @@ //! //! The frame is rendered into an offscreen scene texture (so blur can sample //! it) and blitted to the swapchain. Shaders ship as committed SPIR-V blobs -//! (see shaders/compile.sh) plus MSL sources Metal compiles at runtime. +//! (see shaders/compile.sh) plus MSL sources Metal compiles at runtime and +//! HLSL sources compiled at runtime to DXBC for Direct3D 12 (Windows only, +//! via the system's d3dcompiler_47.dll). //! //! Output matches the software rasterizer to within 1 LSB per channel, with //! one caveat: GPU rasterizers snap vertex edges to a fixed subpixel grid @@ -32,6 +34,7 @@ //! never compiled into the core library or its test suite. const std = @import("std"); +const builtin = @import("builtin"); const zigui = @import("zigui"); const scene_mod = zigui.gpu_scene; @@ -48,6 +51,97 @@ const blur_h_frag_spv = @embedFile("shaders/blur_h.frag.spv"); const blur_v_frag_spv = @embedFile("shaders/blur_v.frag.spv"); const prim_msl = @embedFile("shaders/prim.metal"); const blur_msl = @embedFile("shaders/blur.metal"); +const prim_hlsl = @embedFile("shaders/prim.hlsl"); +const blur_hlsl = @embedFile("shaders/blur.hlsl"); + +const is_windows = builtin.os.tag == .windows; +/// COM/Win32 calling convention; plain C elsewhere so the (Windows-only) +/// D3DCompile types still compile on every target. +const winapi: std.builtin.CallingConvention = if (is_windows) .winapi else .c; + +/// The shader formats we can supply. SDL picks the first backend (Metal, +/// then D3D12, then Vulkan) that accepts one of them, so on Windows D3D12 is +/// preferred and Vulkan is the fallback. +const shader_formats: c.SDL_GPUShaderFormat = c.SDL_GPU_SHADERFORMAT_SPIRV | + c.SDL_GPU_SHADERFORMAT_MSL | + (if (is_windows) c.SDL_GPU_SHADERFORMAT_DXBC else 0); + +/// Runtime HLSL → DXBC (shader model 5.1) compiler for SDL's Direct3D 12 +/// backend: `D3DCompile` from d3dcompiler_47.dll, which ships with Windows 10+ +/// — the D3D12 equivalent of Metal compiling the .metal sources at runtime. +/// Loaded dynamically so there is no import-library dependency. +const HlslCompiler = struct { + lib: *c.SDL_SharedObject, + compile: D3DCompileFn, + + /// ID3DBlob: only the IUnknown + buffer accessors we call. + const Blob = extern struct { + vtbl: *const extern struct { + QueryInterface: *const anyopaque, + AddRef: *const fn (*Blob) callconv(winapi) u32, + Release: *const fn (*Blob) callconv(winapi) u32, + GetBufferPointer: *const fn (*Blob) callconv(winapi) [*]const u8, + GetBufferSize: *const fn (*Blob) callconv(winapi) usize, + }, + + fn bytes(self: *Blob) []const u8 { + return self.vtbl.GetBufferPointer(self)[0..self.vtbl.GetBufferSize(self)]; + } + fn release(self: *Blob) void { + _ = self.vtbl.Release(self); + } + }; + + const D3DCompileFn = *const fn ( + src: [*]const u8, + src_len: usize, + source_name: ?[*:0]const u8, + defines: ?*const anyopaque, + include: ?*anyopaque, + entry: [*:0]const u8, + target: [*:0]const u8, + flags1: u32, + flags2: u32, + code: *?*Blob, + errors: *?*Blob, + ) callconv(winapi) i32; + + const D3DCOMPILE_OPTIMIZATION_LEVEL3: u32 = 1 << 15; + + fn load() ?HlslCompiler { + const lib = c.SDL_LoadObject("d3dcompiler_47.dll") orelse { + std.log.info("zigui: d3dcompiler_47.dll not found ({s})", .{c.SDL_GetError()}); + return null; + }; + const f = c.SDL_LoadFunction(lib, "D3DCompile") orelse { + c.SDL_UnloadObject(lib); + return null; + }; + return .{ .lib = lib, .compile = @ptrCast(@alignCast(f)) }; + } + + fn unload(self: HlslCompiler) void { + c.SDL_UnloadObject(self.lib); + } + + /// Compile one entry point; the caller releases the returned blob after + /// handing its bytes to SDL (which copies them). + fn compileEntry(self: HlslCompiler, src: []const u8, entry: [:0]const u8, stage: c.SDL_GPUShaderStage) ?*Blob { + const target: [*:0]const u8 = if (stage == c.SDL_GPU_SHADERSTAGE_VERTEX) "vs_5_1" else "ps_5_1"; + var code: ?*Blob = null; + var errors: ?*Blob = null; + const hr = self.compile(src.ptr, src.len, entry.ptr, null, null, entry.ptr, target, D3DCOMPILE_OPTIMIZATION_LEVEL3, 0, &code, &errors); + if (errors) |e| { + if (hr < 0) std.log.err("zigui: HLSL {s}: {s}", .{ entry, e.bytes() }); + e.release(); + } + if (hr < 0) { + if (code) |b| b.release(); + return null; + } + return code; + } +}; /// Uniform block for both blur fragment shaders; layout must match the `Blur` /// block in blur_h.frag / blur_v.frag / blur.metal (seven float4s, std140). @@ -99,11 +193,19 @@ pub const Gpu = struct { /// suitable GPU backend exists — the caller falls back to the software /// rasterizer. pub fn init(gpa: Allocator, window: ?*c.SDL_Window) ?Gpu { - const device = c.SDL_CreateGPUDevice( - c.SDL_GPU_SHADERFORMAT_SPIRV | c.SDL_GPU_SHADERFORMAT_MSL, - false, - null, - ) orelse { + if (initWith(gpa, window, shader_formats)) |g| return g; + // If D3D12 was chosen but couldn't build its pipelines (say, HLSL + // failed to compile on this machine), try again without DXBC so a + // working Vulkan driver still gets used before the software fallback. + if (is_windows) { + std.log.info("zigui: retrying the GPU backend without Direct3D 12", .{}); + return initWith(gpa, window, shader_formats & ~@as(c.SDL_GPUShaderFormat, c.SDL_GPU_SHADERFORMAT_DXBC)); + } + return null; + } + + fn initWith(gpa: Allocator, window: ?*c.SDL_Window, formats: c.SDL_GPUShaderFormat) ?Gpu { + const device = c.SDL_CreateGPUDevice(formats, false, null) orelse { std.log.info("zigui: no GPU backend ({s}); using the software rasterizer", .{c.SDL_GetError()}); return null; }; @@ -164,13 +266,16 @@ pub const Gpu = struct { const ShaderDesc = struct { spv: []const u8, msl: []const u8, - msl_entry: [:0]const u8, + hlsl: []const u8, + /// The entry point name, shared by the MSL and HLSL sources (SPIR-V + /// always uses "main"). + entry: [:0]const u8, stage: c.SDL_GPUShaderStage, num_samplers: u32 = 0, num_uniform_buffers: u32 = 0, }; - fn createShader(self: *Gpu, desc: ShaderDesc) ?*c.SDL_GPUShader { + fn createShader(self: *Gpu, desc: ShaderDesc, hlsl: ?HlslCompiler) ?*c.SDL_GPUShader { const formats = c.SDL_GetGPUShaderFormats(self.device); var info = c.SDL_GPUShaderCreateInfo{ .stage = desc.stage, @@ -185,11 +290,21 @@ pub const Gpu = struct { info.code = desc.spv.ptr; info.code_size = desc.spv.len; info.entrypoint = "main"; + } else if (formats & c.SDL_GPU_SHADERFORMAT_DXBC != 0) { + const compiler = hlsl orelse return null; + const blob = compiler.compileEntry(desc.hlsl, desc.entry, desc.stage) orelse return null; + defer blob.release(); + const bytes = blob.bytes(); + info.format = c.SDL_GPU_SHADERFORMAT_DXBC; + info.code = bytes.ptr; + info.code_size = bytes.len; + info.entrypoint = desc.entry.ptr; + return c.SDL_CreateGPUShader(self.device, &info); } else { info.format = c.SDL_GPU_SHADERFORMAT_MSL; info.code = desc.msl.ptr; info.code_size = desc.msl.len; - info.entrypoint = desc.msl_entry.ptr; + info.entrypoint = desc.entry.ptr; } return c.SDL_CreateGPUShader(self.device, &info); } @@ -210,47 +325,56 @@ pub const Gpu = struct { fn createPipelines(self: *Gpu) bool { const d = self.device; + // D3D12 only: load the HLSL compiler for the duration of shader setup. + const hlsl: ?HlslCompiler = if (is_windows and + c.SDL_GetGPUShaderFormats(d) & c.SDL_GPU_SHADERFORMAT_DXBC != 0) HlslCompiler.load() else null; + defer if (hlsl) |h| h.unload(); const prim_vert = self.createShader(.{ .spv = prim_vert_spv, .msl = prim_msl, - .msl_entry = "prim_vertex", + .hlsl = prim_hlsl, + .entry = "prim_vertex", .stage = c.SDL_GPU_SHADERSTAGE_VERTEX, .num_uniform_buffers = 1, - }) orelse return false; + }, hlsl) orelse return false; defer c.SDL_ReleaseGPUShader(d, prim_vert); const prim_frag = self.createShader(.{ .spv = prim_frag_spv, .msl = prim_msl, - .msl_entry = "prim_fragment", + .hlsl = prim_hlsl, + .entry = "prim_fragment", .stage = c.SDL_GPU_SHADERSTAGE_FRAGMENT, .num_samplers = 1, - }) orelse return false; + }, hlsl) orelse return false; defer c.SDL_ReleaseGPUShader(d, prim_frag); const quad_vert = self.createShader(.{ .spv = quad_vert_spv, .msl = blur_msl, - .msl_entry = "quad_vertex", + .hlsl = blur_hlsl, + .entry = "quad_vertex", .stage = c.SDL_GPU_SHADERSTAGE_VERTEX, .num_uniform_buffers = 1, - }) orelse return false; + }, hlsl) orelse return false; defer c.SDL_ReleaseGPUShader(d, quad_vert); const blur_h_frag = self.createShader(.{ .spv = blur_h_frag_spv, .msl = blur_msl, - .msl_entry = "blur_h_fragment", + .hlsl = blur_hlsl, + .entry = "blur_h_fragment", .stage = c.SDL_GPU_SHADERSTAGE_FRAGMENT, .num_samplers = 1, .num_uniform_buffers = 1, - }) orelse return false; + }, hlsl) orelse return false; defer c.SDL_ReleaseGPUShader(d, blur_h_frag); const blur_v_frag = self.createShader(.{ .spv = blur_v_frag_spv, .msl = blur_msl, - .msl_entry = "blur_v_fragment", + .hlsl = blur_hlsl, + .entry = "blur_v_fragment", .stage = c.SDL_GPU_SHADERSTAGE_FRAGMENT, .num_samplers = 1, .num_uniform_buffers = 1, - }) orelse return false; + }, hlsl) orelse return false; defer c.SDL_ReleaseGPUShader(d, blur_v_frag); // Nine float4 per-instance attributes; one buffer at instance rate. diff --git a/src/gpu/shaders/blur.hlsl b/src/gpu/shaders/blur.hlsl new file mode 100644 index 0000000..6a8530c --- /dev/null +++ b/src/gpu/shaders/blur.hlsl @@ -0,0 +1,85 @@ +// HLSL twin of quad.vert + blur_h.frag + blur_v.frag (see those files for +// the semantics). Compiled at runtime to DXBC SM5.1 by gpu.zig for SDL's +// Direct3D 12 backend; see prim.hlsl for the binding model. Vertex uniforms +// at (b0, space1); pixel texture/sampler at (t0/s0, space2), pixel uniforms +// at (b0, space3). + +struct Quad { + float4 viewport; // width, height (zw unused) + float4 rect; // x, y, w, h in pixels +}; +ConstantBuffer uq : register(b0, space1); + +struct Blur { + float4 region; // x0, y0, x1, y1 snapshot bounds (px) + float4 texel_br; // 1/tex_w, 1/tex_h, box radius, unused + float4 shape; // blur rect (x, y, w, h) + float4 tint; // straight-alpha tint composited over the blur + float4 clip; // axis-aligned clip intersection + float4 clip_rrect; // innermost rounded clip rect + float4 radii; // shape corner radius, rounded-clip radius +}; +ConstantBuffer u : register(b0, space3); + +Texture2D src : register(t0, space2); +SamplerState smp : register(s0, space2); + +float4 quad_vertex(uint vid : SV_VertexID) : SV_Position { + float2 corner = float2((float)(vid & 1u), (float)((vid >> 1u) & 1u)); + float2 px = uq.rect.xy + corner * uq.rect.zw; + float2 ndc = px / uq.viewport.xy * 2.0 - 1.0; + return float4(ndc.x, -ndc.y, 0.0, 1.0); +} + +float4 blur_h_fragment(float4 pos : SV_Position) : SV_Target0 { + float2 p = pos.xy; + float br = u.texel_br.z; + float4 sum = (float4)0; + float cnt = 0.0; + [loop] + for (float k = -br; k <= br; k += 1.0) { + float sx = p.x + k; + if (sx < u.region.x || sx >= u.region.z) continue; + sum += src.SampleLevel(smp, float2(sx, p.y) * u.texel_br.xy, 0); + cnt += 1.0; + } + return cnt > 0.0 ? sum / max(cnt, 1.0) : (float4)0; +} + +float sdRoundBox(float2 p, float4 rect, float radius) { + float r = min(radius, min(rect.z, rect.w) * 0.5); + float2 center = rect.xy + rect.zw * 0.5; + float2 q = abs(p - center) - (rect.zw * 0.5 - r.xx); + return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r; +} + +float fillCov(float2 p, float4 rect, float radius) { + return saturate(0.5 - sdRoundBox(p, rect, radius)); +} + +float4 blur_v_fragment(float4 pos : SV_Position) : SV_Target0 { + float2 p = pos.xy; + float br = u.texel_br.z; + float4 sum = (float4)0; + float cnt = 0.0; + [loop] + for (float k = -br; k <= br; k += 1.0) { + float sy = p.y + k; + if (sy < u.region.y || sy >= u.region.w) continue; + sum += src.SampleLevel(smp, float2(p.x, sy) * u.texel_br.xy, 0); + cnt += 1.0; + } + float4 blurred = cnt > 0.0 ? sum / max(cnt, 1.0) : (float4)0; + + // tint.over(blurred), straight alpha. + float oa = u.tint.a + blurred.a * (1.0 - u.tint.a); + float3 orgb = oa > 0.0 + ? (u.tint.rgb * u.tint.a + blurred.rgb * blurred.a * (1.0 - u.tint.a)) / max(oa, 1e-30) + : (float3)0; + + float cov = fillCov(p, u.shape, u.radii.x); + cov *= fillCov(p, u.clip, 0.0); + if (u.radii.y > 0.0) cov *= fillCov(p, u.clip_rrect, u.radii.y); + + return float4(orgb, cov); +} diff --git a/src/gpu/shaders/compile.sh b/src/gpu/shaders/compile.sh index 32401ae..50645dc 100755 --- a/src/gpu/shaders/compile.sh +++ b/src/gpu/shaders/compile.sh @@ -1,9 +1,10 @@ #!/bin/sh # Compile the GLSL shaders to the SPIR-V blobs committed next to them (used by # SDL_GPU's Vulkan backend on Linux/Windows; the Metal backend compiles the -# .metal sources at runtime instead). Requires glslc (shaderc), e.g. -# `brew install shaderc` / `apt install glslc`. Run from this directory after -# editing any .vert/.frag, and commit the regenerated .spv files. +# .metal sources and the D3D12 backend the .hlsl sources at runtime instead). +# Requires glslc (shaderc, also in the Vulkan SDK), e.g. `apt install glslc`. +# Run from this directory after editing any .vert/.frag, and commit the +# regenerated .spv files. set -e cd "$(dirname "$0")" for f in prim.vert quad.vert prim.frag blur_h.frag blur_v.frag; do diff --git a/src/gpu/shaders/prim.hlsl b/src/gpu/shaders/prim.hlsl new file mode 100644 index 0000000..324495a --- /dev/null +++ b/src/gpu/shaders/prim.hlsl @@ -0,0 +1,119 @@ +// HLSL twin of prim.vert + prim.frag (see those files for the semantics). +// SDL's Direct3D 12 backend on Windows consumes DXBC; gpu.zig compiles this +// source at runtime with D3DCompile (d3dcompiler_47.dll ships with Windows), +// targeting shader model 5.1, so no offline shader toolchain is needed. +// +// SDL_GPU binding model for DXBC: vertex attributes use semantic TEXCOORD +// where n = attribute location; vertex uniforms at (b0, space1); pixel +// textures/samplers at (t0/s0, space2). Sampling uses SampleLevel(…, 0): the +// atlas has a single mip and nearest filtering, so it is identical to an +// implicit-derivative sample but legal inside non-uniform branches. + +struct Viewport { + float4 size; // viewport width, height in pixels (zw unused) +}; +ConstantBuffer u : register(b0, space1); + +Texture2D atlas : register(t0, space2); +SamplerState smp : register(s0, space2); + +struct VInput { + float4 pos : TEXCOORD0; + float4 shape : TEXCOORD1; + float4 color0 : TEXCOORD2; + float4 color1 : TEXCOORD3; + float4 ab : TEXCOORD4; + float4 uv : TEXCOORD5; + float4 clip : TEXCOORD6; + float4 clip_rrect : TEXCOORD7; + float4 params : TEXCOORD8; + uint vid : SV_VertexID; +}; + +struct VOut { + float4 position : SV_Position; + float2 px : TEXCOORD0; + float2 uv : TEXCOORD1; + nointerpolation float4 shape : TEXCOORD2; + nointerpolation float4 color0 : TEXCOORD3; + nointerpolation float4 color1 : TEXCOORD4; + nointerpolation float4 ab : TEXCOORD5; + nointerpolation float4 clip : TEXCOORD6; + nointerpolation float4 clip_rrect : TEXCOORD7; + nointerpolation float4 params : TEXCOORD8; +}; + +VOut prim_vertex(VInput i) { + // Strip corners: (0,0) (1,0) (0,1) (1,1). + float2 corner = float2((float)(i.vid & 1u), (float)((i.vid >> 1u) & 1u)); + float2 px = i.pos.xy + corner * i.pos.zw; + VOut o; + o.px = px; + o.uv = lerp(i.uv.xy, i.uv.zw, corner); + o.shape = i.shape; + o.color0 = i.color0; + o.color1 = i.color1; + o.ab = i.ab; + o.clip = i.clip; + o.clip_rrect = i.clip_rrect; + o.params = i.params; + float2 ndc = px / u.size.xy * 2.0 - 1.0; + // SDL_GPU NDC is +Y up on every backend; pixel space is +Y down. + o.position = float4(ndc.x, -ndc.y, 0.0, 1.0); + return o; +} + +float sdRoundBox(float2 p, float4 rect, float radius) { + float r = min(radius, min(rect.z, rect.w) * 0.5); + float2 center = rect.xy + rect.zw * 0.5; + float2 q = abs(p - center) - (rect.zw * 0.5 - r.xx); + return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r; +} + +float fillCov(float2 p, float4 rect, float radius) { + return saturate(0.5 - sdRoundBox(p, rect, radius)); +} + +float sdSegment(float2 p, float2 a, float2 b) { + float2 pa = p - a; + float2 ba = b - a; + float len2 = dot(ba, ba); + float h = len2 > 0.0 ? saturate(dot(pa, ba) / len2) : 0.0; + return length(pa - ba * h); +} + +float4 prim_fragment(VOut i) : SV_Target0 { + int kind = (int)i.params.x; + float radius = i.params.y; + float half_w = i.params.z; + float4 color = i.color0; + float cov = 1.0; + + if (kind == 0) { // fill_rrect + cov = fillCov(i.px, i.shape, radius); + } else if (kind == 1) { // stroke_rrect (centered on the edge) + float d = abs(sdRoundBox(i.px, i.shape, radius)) - half_w; + cov = saturate(0.5 - d); + } else if (kind == 2) { // linear_gradient clipped to a rounded rect + cov = fillCov(i.px, i.shape, radius); + float2 dir = i.ab.zw - i.ab.xy; + float len2 = dot(dir, dir); + float t = len2 > 0.0 ? saturate(dot(i.px - i.ab.xy, dir) / len2) : 0.0; + color = lerp(i.color0, i.color1, t); + } else if (kind == 3) { // glyph: coverage in atlas alpha, tinted by color0 + cov = atlas.SampleLevel(smp, i.uv, 0).a; + // Coverage gamma (text contrast) in params.y; see prim.frag. + if (i.params.y != 1.0) cov = pow(abs(cov), i.params.y); + } else if (kind == 4) { // image: RGBA straight from the atlas + color = atlas.SampleLevel(smp, i.uv, 0); + } else { // line segment with round caps + float d = sdSegment(i.px, i.ab.xy, i.ab.zw) - half_w; + cov = saturate(0.5 - d); + } + + // Clip: axis-aligned intersection of the stack + innermost rounded clip. + cov *= fillCov(i.px, i.clip, 0.0); + if (i.params.w > 0.0) cov *= fillCov(i.px, i.clip_rrect, i.params.w); + + return float4(color.rgb, color.a * cov); +} diff --git a/src/icons.zig b/src/icons.zig index 20b42a4..6a88ffb 100644 --- a/src/icons.zig +++ b/src/icons.zig @@ -1881,7 +1881,7 @@ pub const Icon = enum(u21) { zoom_out = 0xE1B7, pub fn codepoint(self: Icon) u21 { - return @intFromEnum(self); + return @backingInt(self); } }; diff --git a/src/render/gpu_scene.zig b/src/render/gpu_scene.zig index b7e2bc5..38b4ce4 100644 --- a/src/render/gpu_scene.zig +++ b/src/render/gpu_scene.zig @@ -293,14 +293,14 @@ pub fn translate( inst.pos = paddedQuad(f.rect, 1); inst.shape = rectArr(f.rect); inst.color0 = colorArr(f.color); - inst.params[0] = @floatFromInt(@intFromEnum(Kind.fill)); + inst.params[0] = @floatFromInt(@backingInt(Kind.fill)); inst.params[1] = f.radius; }, .stroke_rrect => |s| { inst.pos = paddedQuad(s.rect, s.width / 2 + 1); inst.shape = rectArr(s.rect); inst.color0 = colorArr(s.color); - inst.params[0] = @floatFromInt(@intFromEnum(Kind.stroke)); + inst.params[0] = @floatFromInt(@backingInt(Kind.stroke)); inst.params[1] = s.radius; inst.params[2] = s.width / 2; }, @@ -310,7 +310,7 @@ pub fn translate( inst.color0 = colorArr(g.c0); inst.color1 = colorArr(g.c1); inst.ab = .{ g.start.x, g.start.y, g.end.x, g.end.y }; - inst.params[0] = @floatFromInt(@intFromEnum(Kind.gradient)); + inst.params[0] = @floatFromInt(@backingInt(Kind.gradient)); inst.params[1] = g.radius; }, .line => |l| { @@ -323,7 +323,7 @@ pub fn translate( inst.pos = paddedQuad(bb, l.width / 2 + 1); inst.color0 = colorArr(l.color); inst.ab = .{ l.a.x, l.a.y, l.b.x, l.b.y }; - inst.params[0] = @floatFromInt(@intFromEnum(Kind.line)); + inst.params[0] = @floatFromInt(@backingInt(Kind.line)); inst.params[2] = l.width / 2; }, .glyph => |g| { @@ -336,7 +336,7 @@ pub fn translate( g.coverage.height, try coverageToRgba(arena, g.coverage), ); - inst.params[0] = @floatFromInt(@intFromEnum(Kind.glyph)); + inst.params[0] = @floatFromInt(@backingInt(Kind.glyph)); // params[1] (unused by glyphs — no corner radius) carries // the coverage gamma the fragment shader applies, matching // the software rasterizer's `drawGlyph`. @@ -351,7 +351,7 @@ pub fn translate( im.image.height, im.image.pixels, ); - inst.params[0] = @floatFromInt(@intFromEnum(Kind.image)); + inst.params[0] = @floatFromInt(@backingInt(Kind.image)); }, else => unreachable, } @@ -409,7 +409,7 @@ test "gpu_scene: fill becomes one padded instance and one draw step" { const i = scene.instances[0]; try testing.expectEqual([4]f32{ 9, 19, 32, 42 }, i.pos); // padded by 1 try testing.expectEqual([4]f32{ 10, 20, 30, 40 }, i.shape); - try testing.expectEqual(@as(f32, @floatFromInt(@intFromEnum(Kind.fill))), i.params[0]); + try testing.expectEqual(@as(f32, @floatFromInt(@backingInt(Kind.fill))), i.params[0]); try testing.expectEqual(@as(f32, 5), i.params[1]); try testing.expectEqual(@as(usize, 1), scene.steps.len); try testing.expectEqual(@as(u32, 1), scene.steps[0].draw.count); diff --git a/src/text/fontset.zig b/src/text/fontset.zig index 95b1a2c..ffe78d4 100644 --- a/src/text/fontset.zig +++ b/src/text/fontset.zig @@ -54,7 +54,7 @@ pub const FontSet = struct { self.alloc = alloc; for (blobs, 0..) |b, i| self.faces[i] = try ttf.Font.parse(b); // Text faces fall back to the emoji font for codepoints they lack. - const emoji = &self.faces[@intFromEnum(Slot.emoji)]; + const emoji = &self.faces[@backingInt(Slot.emoji)]; for (0..slot_count - 1) |i| self.faces[i].fallback = emoji; for (0..slot_count) |i| self.caches[i] = atlas.GlyphCache.init(alloc, &self.faces[i]); return self; @@ -68,11 +68,11 @@ pub const FontSet = struct { /// Put `face` (e.g. a system CJK font) behind the emoji face, so every style /// reaches it for codepoints the bundled faces lack. It must outlive the set. pub fn setFallback(self: *FontSet, face: *const ttf.Font) void { - self.faces[@intFromEnum(Slot.emoji)].fallback = face; + self.faces[@backingInt(Slot.emoji)].fallback = face; } pub fn cache(self: *FontSet, s: Style) *atlas.GlyphCache { - return &self.caches[@intFromEnum(slotFor(s))]; + return &self.caches[@backingInt(slotFor(s))]; } }; diff --git a/src/view/view.zig b/src/view/view.zig index 2a9698e..bcab5f3 100644 --- a/src/view/view.zig +++ b/src/view/view.zig @@ -885,10 +885,10 @@ fn richCached(arena: Allocator, spans: []const richtext.Span, faces: richtext.Fa var h = std.hash.Wyhash.init(0x51c4); for (spans) |sp| { h.update(sp.text); - const style = [_]u32{ if (sp.weight) |w| @intFromEnum(w) + 1 else 0, @intFromBool(sp.italic), @intFromBool(sp.mono), @bitCast(sp.size_scale), @intCast(sp.text.len) }; + const style = [_]u32{ if (sp.weight) |w| @backingInt(w) + 1 else 0, @intFromBool(sp.italic), @intFromBool(sp.mono), @bitCast(sp.size_scale), @intCast(sp.text.len) }; h.update(std.mem.asBytes(&style)); } - const rest = [_]u32{ @bitCast(px), @bitCast(mult), @intFromFloat(@max(0, @min(1.0e9, @round(max_w)))), @intFromBool(pre), @intFromEnum(faces.base_weight), @intFromBool(faces.fonts != null) }; + const rest = [_]u32{ @bitCast(px), @bitCast(mult), @intFromFloat(@max(0, @min(1.0e9, @round(max_w)))), @intFromBool(pre), @backingInt(faces.base_weight), @intFromBool(faces.fonts != null) }; h.update(std.mem.asBytes(&rest)); const k = h.final(); if (wc.rich.get(k)) |e| { diff --git a/tools/icon/mkico.py b/tools/icon/mkico.py new file mode 100644 index 0000000..e025a76 --- /dev/null +++ b/tools/icon/mkico.py @@ -0,0 +1,102 @@ +"""Build the app icons from a flat SVG — stdlib Python only, no image tools. + + python3 tools/icon/mkico.py assets/icon/zigz.svg + +writes next to the SVG: + * .ico — 16…256 px PNG entries, embedded in the Windows .exe as a + resource (Explorer, title bar, taskbar); see build.zig / zigui.rc; + * .png — 256 px, loaded at runtime via `Config.icon_png` for the + window/Dock icon on macOS and Linux. + +Handles only what the icon uses: elements with absolute M/L/Z commands +and solid #rrggbb fills (polygons, even-odd per path, painted in order), with +16x16 supersampled anti-aliasing. Re-run after editing the SVG and commit the +outputs, so builds never need this step.""" +import re, struct, sys, zlib, os + +SS = 16 # supersamples per axis + +def parse(svg): + vb = [float(v) for v in re.search(r'viewBox="([^"]+)"', svg).group(1).split()] + polys = [] + for m in re.finditer(r']*>', svg): + tag = m.group(0) + fill = re.search(r'fill="#([0-9a-fA-F]{6})"', tag).group(1) + d = re.search(r'\sd="([^"]+)"', tag).group(1) + toks = re.findall(r'[MLZmlz]|-?[\d.]+', d) + assert all(t in 'MLZ' or t[0].isdigit() or t[0] in '-.' for t in toks), d + pts, cur, i = [], None, 0 + while i < len(toks): + t = toks[i] + if t in 'ML': + cur = t; i += 1; continue + if t == 'Z': + i += 1; continue + pts.append((float(toks[i]), float(toks[i + 1]))); i += 2 + polys.append((tuple(int(fill[k:k + 2], 16) for k in (0, 2, 4)), pts)) + return vb, polys + +def render(vb, polys, size): + # Coverage per pixel per fill color (union of polygons sharing a color). + x0, y0, vw, vh = vb + sub = size * SS + sx, sy = sub / vw, sub / vh + colors = {} + for color, pts in polys: + grid = colors.setdefault(color, [bytearray(sub) for _ in range(sub)]) + P = [((x - x0) * sx, (y - y0) * sy) for x, y in pts] + n = len(P) + for r in range(sub): + yc = r + 0.5 + xs = [] + for k in range(n): + (ax, ay), (bx, by) = P[k], P[(k + 1) % n] + if (ay <= yc) != (by <= yc): + xs.append(ax + (yc - ay) * (bx - ax) / (by - ay)) + xs.sort() + row = grid[r] + for a, b in zip(xs[0::2], xs[1::2]): # even-odd within one polygon + lo = max(0, int(a + 0.5)); hi = min(sub, int(b + 0.5)) + if hi > lo: + row[lo:hi] = b'\x01' * (hi - lo) + out = bytearray(size * size * 4) + for color, grid in colors.items(): + for py in range(size): + rows = grid[py * SS:(py + 1) * SS] + for px in range(size): + c = sum(sum(rw[px * SS:(px + 1) * SS]) for rw in rows) + if not c: + continue + a = c / (SS * SS) + o = (py * size + px) * 4 + # straight-alpha "over" onto what's there + da = out[o + 3] / 255 + oa = a + da * (1 - a) + for ch in range(3): + out[o + ch] = round((color[ch] * a + out[o + ch] * da * (1 - a)) / oa) + out[o + 3] = round(oa * 255) + return bytes(out) + +def png(rgba, size): + raw = b''.join(b'\x00' + rgba[y * size * 4:(y + 1) * size * 4] for y in range(size)) + chunk = lambda t, d: struct.pack('>I', len(d)) + t + d + struct.pack('>I', zlib.crc32(t + d) & 0xffffffff) + return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', size, size, 8, 6, 0, 0, 0)) + + chunk(b'IDAT', zlib.compress(raw, 9)) + chunk(b'IEND', b'')) + +def ico(pngs): + hdr = struct.pack(' Date: Sun, 8 Nov 2026 21:38:53 -0500 Subject: [PATCH 2/3] v0.2.2 Icon tooling, zigui as a dependency, overlay clipping, desktop-entry escaping MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - mkico.py: --iconset writes the macOS .iconset (16…1024 px, @1x/@2x); fewer supersamples at large sizes so 1024 px renders in seconds - build.zig: linkApp() exposes the SDL3 runtime (src/app.zig) to dependent packages; examples are built only when zigui is the root build, so a consumer never fetches SDL it doesn't use - Sheets/alerts widen to content that cannot be narrower (e.g. a wide segmented Picker) instead of clipping both edges (new engine.minWidth) - Truncated text keeps its tail when it fits within float rounding - installDesktopEntry escapes Name/Exec/Icon/StartupWMClass per the Desktop Entry Spec (paths with spaces, quotes, $, %, backslashes); refuses control characters Co-Authored-By: Claude Opus 5.5 --- build.zig | 56 ++++++++++++++++++++++- build.zig.zon | 2 +- src/app.zig | 29 +++++++++--- src/desktop_entry.zig | 104 ++++++++++++++++++++++++++++++++++++++++++ src/layout/engine.zig | 42 +++++++++++++++++ src/view/view.zig | 48 ++++++++++++++++++- src/zigui.zig | 3 ++ tools/icon/mkico.py | 32 ++++++++++--- 8 files changed, 299 insertions(+), 17 deletions(-) create mode 100644 src/desktop_entry.zig diff --git a/build.zig b/build.zig index 27aef0b..b5e68a9 100644 --- a/build.zig +++ b/build.zig @@ -81,8 +81,60 @@ pub fn build(b: *std.Build) void { // (log output, `--screenshot` messages) for debugging. const windows_console = b.option(bool, "windows-console", "Build Windows examples as console apps (shows log output)") orelse false; const sdl: SdlConfig = .{ .prefix = sdl3_prefix, .macos_sdk = macos_sdk, .windows_console = windows_console }; - addExample(b, mod, target, optimize, sdl, "showcase", "examples/showcase/main.zig"); - addExample(b, mod, target, optimize, sdl, "edit", "examples/edit/main.zig"); + // The examples only when zigui is the root build: a package that depends + // on zigui reaches SDL through `linkApp` alone, so `b.dependency("zigui")` + // never fetches or builds SDL for a consumer that draws no window. + if (b.dep_prefix.len == 0) { + addExample(b, mod, target, optimize, sdl, "showcase", "examples/showcase/main.zig"); + addExample(b, mod, target, optimize, sdl, "edit", "examples/edit/main.zig"); + } +} + +/// What `linkApp` builds the SDL runtime for. +pub const AppOptions = struct { + target: std.Build.ResolvedTarget, + optimize: std.builtin.OptimizeMode, + /// The macOS SDK root (`xcrun --show-sdk-path`), needed whenever macOS is + /// an explicit `-Dtarget`; null lets Zig probe the host's. + macos_sdk: ?[]const u8 = null, + /// A prebuilt SDL3 (`include/` and `lib/` inside) instead of the package. + sdl3_prefix: ?[]const u8 = null, +}; + +/// The SDL3-backed runtime (`src/app.zig`) for a package that depends on +/// zigui: import the result as `zigui_app` beside `dep.module("zigui")` (the +/// same core module it imports, so the two agree on every type). It links +/// SDL3 (fetched lazily, on first use), libc and, on macOS, the Objective-C +/// runtime. On the first configure SDL may not be fetched yet: the module is +/// returned unlinked and the build reruns once the package is there. +/// +/// const zigui_dep = b.dependency("zigui", .{ .target = target, .optimize = optimize }); +/// const app_mod = @import("zigui").linkApp(zigui_dep, .{ .target = target, .optimize = optimize }); +/// exe.root_module.addImport("zigui", zigui_dep.module("zigui")); +/// exe.root_module.addImport("zigui_app", app_mod); +pub fn linkApp(dep: *std.Build.Dependency, opts: AppOptions) *std.Build.Module { + const b = dep.builder; + const sdl_c = b.addTranslateC(.{ + .root_source_file = b.path("src/sdl_c.h"), + .target = opts.target, + .optimize = opts.optimize, + .link_libc = true, + }); + const app_mod = b.createModule(.{ + .root_source_file = b.path("src/app.zig"), + .target = opts.target, + .optimize = opts.optimize, + .link_libc = true, + .imports = &.{.{ .name = "zigui", .module = dep.module("zigui") }}, + }); + app_mod.addImport("sdl_c", sdl_c.createModule()); + const sdl: SdlConfig = .{ .prefix = opts.sdl3_prefix, .macos_sdk = opts.macos_sdk, .windows_console = false }; + linkSdl3(b, app_mod, sdl_c, opts.target, opts.optimize, sdl); + if (opts.target.result.os.tag == .macos) { + if (opts.macos_sdk) |sdk| addMacosSdk(b, app_mod, sdk); + app_mod.linkSystemLibrary("objc", .{}); + } + return app_mod; } /// Where SDL3 and (for explicit macOS targets) the system SDK come from. diff --git a/build.zig.zon b/build.zig.zon index 49747ca..22ae99c 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -1,6 +1,6 @@ .{ .name = .zigui, - .version = "0.2.1", + .version = "0.2.2", .fingerprint = 0x18d03e108d8c3c7e, .minimum_zig_version = "0.17.0", .dependencies = .{ diff --git a/src/app.zig b/src/app.zig index c13b928..fa3d08c 100644 --- a/src/app.zig +++ b/src/app.zig @@ -752,21 +752,33 @@ pub fn installDesktopEntry(name: []const u8, icon_png: []const u8) bool { const app_dir = std.fmt.bufPrintSentinel(&path_buf, "{s}/applications", .{data_dir}, 0) catch return false; if (!c.SDL_CreateDirectory(app_dir.ptr)) return logInstallError(app_dir); - var entry_buf: [8192]u8 = undefined; - // Exec is quoted so paths with spaces work; Icon is the absolute path so - // no icon-theme cache refresh is needed. StartupWMClass ties X11 windows - // to the entry too (Wayland matches by file name = app ID). + // Each value escaped per the Desktop Entry Specification, so a path with + // spaces, quotes, `$`, `%` or backslashes means what it says (a path that + // cannot be written, with a control character in it, is refused). Exec is + // quoted; Icon is the absolute path so no icon-theme cache refresh is + // needed; StartupWMClass ties X11 windows to the entry too (Wayland + // matches by file name = app ID). Sized for the worst case: every byte of + // a 4096-byte path escaped to four. + var exec_buf: [4 * 4096 + 8]u8 = undefined; + var name_buf: [2 * 256]u8 = undefined; + var icon_value_buf: [2 * 4096]u8 = undefined; + var id_buf: [2 * 4096]u8 = undefined; + const exec = zigui.desktop_entry.execValue(&exec_buf, exe, false) orelse return logUnwritable("executable path", exe); + const name_value = zigui.desktop_entry.stringValue(&name_buf, name) orelse return logUnwritable("name", name); + const icon_value = zigui.desktop_entry.stringValue(&icon_value_buf, icon_path) orelse return logUnwritable("icon path", icon_path); + const id_value = zigui.desktop_entry.stringValue(&id_buf, id) orelse return logUnwritable("app ID", id); + var entry_buf: [exec_buf.len + name_buf.len + icon_value_buf.len + id_buf.len + 256]u8 = undefined; const entry = std.fmt.bufPrint(&entry_buf, \\[Desktop Entry] \\Type=Application \\Name={s} - \\Exec="{s}" + \\Exec={s} \\Icon={s} \\StartupWMClass={s} \\Terminal=false \\Categories=Utility; \\ - , .{ name, exe, icon_path, id }) catch return false; + , .{ name_value, exec, icon_value, id_value }) catch return false; var desk_buf: [4096]u8 = undefined; const desk_path = std.fmt.bufPrintSentinel(&desk_buf, "{s}/{s}.desktop", .{ app_dir, id }, 0) catch return false; if (!c.SDL_SaveFile(desk_path.ptr, entry.ptr, entry.len)) return logInstallError(desk_path); @@ -774,6 +786,11 @@ pub fn installDesktopEntry(name: []const u8, icon_png: []const u8) bool { return true; } +fn logUnwritable(what: []const u8, value: []const u8) bool { + std.log.err("zigui: no desktop entry: its {s} has a control character ({s})", .{ what, value }); + return false; +} + fn logInstallError(path: []const u8) bool { std.log.err("zigui: cannot write {s} ({s})", .{ path, c.SDL_GetError() }); return false; diff --git a/src/desktop_entry.zig b/src/desktop_entry.zig new file mode 100644 index 0000000..92ed2d3 --- /dev/null +++ b/src/desktop_entry.zig @@ -0,0 +1,104 @@ +//! Values for a freedesktop desktop entry (`.desktop` file), escaped per the +//! Desktop Entry Specification, so a path with spaces, quotes, `$`, `%` or +//! backslashes in it means what it says. Pure; `app.zig`'s +//! `installDesktopEntry` and `desktopEntryState` write and read with it. + +const std = @import("std"); + +/// A value of type string: a backslash is written `\\`. Null when `text` holds +/// a control character (a newline would end the line, and the entry with it). +/// +/// - `buf`: where the value is written. +/// - `text`: the raw value (a path, a name). +/// - Returns: the escaped value, in `buf`; null for a control character or +/// when `buf` is too small. +pub fn stringValue(buf: []u8, text: []const u8) ?[]const u8 { + var w = Writer{ .buf = buf }; + for (text) |byte| { + if (byte < 0x20 or byte == 0x7f) return null; + if (byte == '\\') w.put("\\\\") else w.put(&.{byte}); + } + return w.done(); +} + +/// An `Exec` value that runs `program` with one argument, the file opened +/// (`%f`), or none when `with_file` is false. The program is quoted, with +/// the characters the spec reserves inside quotes (`"`, `` ` ``, `$`, `\`) +/// escaped by a backslash, and then the string rule applied on top (each of +/// those backslashes, and a literal one, doubled again: a backslash in the +/// path becomes four). A `%` is written `%%`, so no field code is read in +/// the path. Null when `program` holds a control character, which no +/// escape represents inside quotes. +/// +/// - `buf`: where the value is written. +/// - `program`: the executable's absolute path. +/// - `with_file`: add the `%f` field code, so a file or folder can be opened with it. +/// - Returns: the value, in `buf`; null for a control character or when +/// `buf` is too small. +pub fn execValue(buf: []u8, program: []const u8, with_file: bool) ?[]const u8 { + var w = Writer{ .buf = buf }; + w.put("\""); + for (program) |byte| { + if (byte < 0x20 or byte == 0x7f) return null; + switch (byte) { + // Quoting rule (`\x`), then the string rule doubles the backslash. + '"', '`', '$' => { + w.put("\\\\"); + w.put(&.{byte}); + }, + '\\' => w.put("\\\\\\\\"), + '%' => w.put("%%"), + else => w.put(&.{byte}), + } + } + w.put("\""); + if (with_file) w.put(" %f"); + return w.done(); +} + +/// Appends into a fixed buffer, remembering whether it ran out. +const Writer = struct { + buf: []u8, + len: usize = 0, + full: bool = false, + + fn put(self: *Writer, bytes: []const u8) void { + if (self.full or self.len + bytes.len > self.buf.len) { + self.full = true; + return; + } + @memcpy(self.buf[self.len..][0..bytes.len], bytes); + self.len += bytes.len; + } + + fn done(self: *const Writer) ?[]const u8 { + return if (self.full) null else self.buf[0..self.len]; + } +}; + +test "a plain path is quoted and left alone" { + var buf: [256]u8 = undefined; + try std.testing.expectEqualStrings("\"/opt/My App/bin/app\"", execValue(&buf, "/opt/My App/bin/app", false).?); + try std.testing.expectEqualStrings("\"/usr/bin/app\" %f", execValue(&buf, "/usr/bin/app", true).?); +} + +test "reserved characters are escaped twice, and % is doubled" { + var buf: [256]u8 = undefined; + // In the file: a quote is \\" , a dollar \\$ , a backtick \\` , a backslash + // \\\\ (four), and a percent %%. + try std.testing.expectEqualStrings("\"/a\\\\\"b\\\\$c\\\\`d\\\\\\\\e%%f\"", execValue(&buf, "/a\"b$c`d\\e%f", false).?); +} + +test "a control character or a short buffer is refused" { + var buf: [256]u8 = undefined; + try std.testing.expectEqual(null, execValue(&buf, "/a\nb", false)); + try std.testing.expectEqual(null, stringValue(&buf, "x\ty")); + var tiny: [4]u8 = undefined; + try std.testing.expectEqual(null, execValue(&tiny, "/usr/bin/app", false)); +} + +test "a string value doubles its backslashes" { + var buf: [64]u8 = undefined; + try std.testing.expectEqualStrings("C:\\\\icons\\\\app.png", stringValue(&buf, "C:\\icons\\app.png").?); + try std.testing.expectEqualStrings("/home/me/.local/share/icons/app.png", stringValue(&buf, "/home/me/.local/share/icons/app.png").?); +} diff --git a/src/layout/engine.zig b/src/layout/engine.zig index 13dc6a4..74b0a5c 100644 --- a/src/layout/engine.zig +++ b/src/layout/engine.zig @@ -154,6 +154,34 @@ pub fn measure(node: Node, prop: Proposal) Size { return measureUncached(node, prop); } +/// The narrowest `node` can be laid out without a child overflowing: a leaf's +/// minimum, a horizontal stack's children and gaps summed, the widest child +/// of any other stack, padding added, and a fixed frame's width. A frame that +/// only caps or fills the width does not lower its child's minimum (`arrange` +/// still gives the child that much), and a measured leaf answers for a +/// proposed width of zero (wrapped text: its longest word). +/// +/// - `node`: the tree. +/// - Returns: the width. +pub fn minWidth(node: Node) f32 { + return switch (node) { + .leaf => |h| h.min.width, + .spacer => 0, + .measured => |m| m.measureFn(m.ctx, .{ .width = 0, .height = null }).width, + .padding => |p| minWidth(p.child.*) + p.insets.horizontal(), + .frame => |f| f.width orelse @max(f.min_width orelse 0, minWidth(f.child.*)), + .stack => |s| blk: { + var w: f32 = 0; + for (s.children) |child| { + const cw = if (child == .spacer and s.direction == .horizontal) child.spacer.min_length else minWidth(child); + w = if (s.direction == .horizontal) w + cw else @max(w, cw); + } + if (s.direction == .horizontal and s.children.len > 1) w += s.spacing * @as(f32, @floatFromInt(s.children.len - 1)); + break :blk w; + }, + }; +} + fn measureUncached(node: Node, prop: Proposal) Size { return switch (node) { .leaf => |h| .{ @@ -450,6 +478,20 @@ test "a stack longer than 256 children lays out (heap scratch)" { try std.testing.expectEqual(@as(f32, 600), sz.height); } +test "minWidth: sums a row, takes a column's widest, and sees through a filling frame" { + const wide = leaf(300, 10); + const row_kids = [_]Node{ leaf(50, 10), .{ .spacer = .{} }, leaf(70, 10) }; + const row = Node{ .stack = .{ .direction = .horizontal, .spacing = 10, .children = &row_kids } }; + try std.testing.expectEqual(@as(f32, 140), minWidth(row)); + const filled = Node{ .frame = .{ .max_width = inf, .child = &wide } }; + const col_kids = [_]Node{ row, filled }; + const col = Node{ .stack = .{ .direction = .vertical, .spacing = 8, .children = &col_kids } }; + const padded = Node{ .padding = .{ .insets = .{ .leading = 20, .trailing = 20 }, .child = &col } }; + try std.testing.expectEqual(@as(f32, 340), minWidth(padded)); + // A fixed frame is its width, whatever its child needs. + try std.testing.expectEqual(@as(f32, 120), minWidth(.{ .frame = .{ .width = 120, .child = &wide } })); +} + test "measure: leaf reports ideal when proposal unspecified" { const n = Node{ .leaf = .{ .min = .{ .width = 10, .height = 10 }, diff --git a/src/view/view.zig b/src/view/view.zig index bcab5f3..07e1ecc 100644 --- a/src/view/view.zig +++ b/src/view/view.zig @@ -1900,11 +1900,18 @@ fn drawOverlay(ctx: *const Context, req: OverlayReq, root: Rect, canvas: *Canvas // 3. Measure & position the content. macOS sheets are *centered* window // modals (they don't hug the bottom edge like iOS). - const prop: engine.Proposal = switch (req.style) { + var prop: engine.Proposal = switch (req.style) { .sheet => .{ .width = @min(root.width - 160, 480), .height = null }, .alert => .{ .width = @min(root.width - 80, 320), .height = null }, .popover => .unspecified, }; + // A sheet or alert whose content cannot be narrower than its usual width + // (a wide segmented `Picker`) widens to it, as far as the window allows, + // rather than being clipped at both edges. + if (prop.width) |usual| { + const least = if (buildNode(ctx, req.content)) |node| engine.minWidth(node) else |_| 0; + if (least > usual) prop.width = @max(usual, @min(least, root.width - 2 * popover_margin)); + } var size = measure(ctx, req.content, prop) catch Size{}; // A popover wider than the window is narrowed to fit (its rows truncate), // not pushed past the edge. @@ -2301,7 +2308,9 @@ fn drawTextC(ctx: *const Context, canvas: *Canvas, text: []const u8, px: f32, co /// (returns `str` unchanged when it already fits). The clipped string is built in /// the per-frame arena. Used for `.truncated()` single-line Text. fn truncateToWidth(ctx: *const Context, str: []const u8, px: f32, max_w: f32) []const u8 { - if (shape.measureLineWidth(ctx.cache.face, str, px) <= max_w) return str; + // Layout hands a text exactly its measured width back, give or take float + // rounding, so a tolerance keeps a string that fits from losing its tail. + if (shape.measureLineWidth(ctx.cache.face, str, px) <= max_w + 0.01) return str; const ell = "…"; const ell_w = shape.measureLineWidth(ctx.cache.face, ell, px); if (max_w <= ell_w) return ell; // no room even for the body — just the ellipsis @@ -5072,6 +5081,41 @@ test "view: a Drawing paints into its frame" { try testing.expect(fb.at(35, 10).r > 0.9); } +test "view: an alert widens to content that cannot be narrower" { + var env = TestEnv.init(); + env.setup(); + defer env.deinit(); + var c = env.ctx(); + var ovs: std.ArrayList(OverlayReq) = .empty; + c.overlays = &ovs; + var presented = state.State(bool).init(testing.allocator, true); + defer presented.deinit(); + var choice = state.State(i64).init(testing.allocator, 0); + defer choice.deinit(); + var canvas = Canvas.init(testing.allocator); + defer canvas.deinit(); + const root = Rect{ .x = 0, .y = 0, .width = 900, .height = 400 }; + const options = [_][]const u8{ "A long first option", "A long second option", "A long third option", "Fourth" }; + const picker = Picker(choice.binding(), &options); + const least = try measure(&c, picker, .{ .width = 0, .height = null }); + try testing.expect(least.width > 320); + // A filling picker under a heading, padded: as a settings sheet is built. + const content = VStack(.{ Text("Settings"), picker.frameMaxWidth() }).alignment(.leading).padding(20); + const tree = Rectangle(Color.white).alert(presented.binding(), content); + endBuild(); + try render(&c, tree, root, &canvas); + // The panel holds every segment: none reaches its clip, which is the panel. + var clip: ?Rect = null; + for (canvas.commands.items) |cmd| if (cmd == .push_clip) { + clip = cmd.push_clip.rect; + }; + try testing.expect(clip.?.width >= least.width + 40 - 0.5); + try testing.expect(clip.?.x >= 0 and clip.?.maxX() <= root.width); + for (c.hit_regions.items) |region| if (region.action == .select) { + try testing.expect(region.rect.x >= clip.?.x - 0.5 and region.rect.maxX() <= clip.?.maxX() + 0.5); + }; +} + test "view: popover content is positioned near its (top) anchor" { var env = TestEnv.init(); env.setup(); diff --git a/src/zigui.zig b/src/zigui.zig index 5960c64..0771f7e 100644 --- a/src/zigui.zig +++ b/src/zigui.zig @@ -88,6 +88,8 @@ pub const themeForScheme = theme_registry.forScheme; /// The default theme (macOS light). pub const default_theme = macos.light; +/// Escaped values for a freedesktop desktop entry (`.desktop`). +pub const desktop_entry = @import("desktop_entry.zig"); pub const view = @import("view/view.zig"); pub const View = view.View; pub const Context = view.Context; @@ -222,6 +224,7 @@ pub const Material = view.Material; test { std.testing.refAllDecls(@This()); _ = @import("integration_test.zig"); + _ = @import("desktop_entry.zig"); } test "version is parsed from the package manifest" { diff --git a/tools/icon/mkico.py b/tools/icon/mkico.py index e025a76..a643508 100644 --- a/tools/icon/mkico.py +++ b/tools/icon/mkico.py @@ -6,7 +6,9 @@ * .ico — 16…256 px PNG entries, embedded in the Windows .exe as a resource (Explorer, title bar, taskbar); see build.zig / zigui.rc; * .png — 256 px, loaded at runtime via `Config.icon_png` for the - window/Dock icon on macOS and Linux. + window/Dock icon on macOS and Linux; + * with `--iconset`, also .iconset/ — the 16…1024 px PNGs (@1x and + @2x) a macOS bundle's icon is made of: `iconutil -c icns .iconset`. Handles only what the icon uses: elements with absolute M/L/Z commands and solid #rrggbb fills (polygons, even-odd per path, painted in order), with @@ -14,7 +16,12 @@ outputs, so builds never need this step.""" import re, struct, sys, zlib, os -SS = 16 # supersamples per axis +SS = 16 # supersamples per axis, for the small sizes + +def supersamples(size): + """Fewer samples as the size grows: a 1024 px icon at 16x16 would take + minutes in pure Python, and the larger sizes need less antialiasing.""" + return max(2, min(SS, 2048 // size)) def parse(svg): vb = [float(v) for v in re.search(r'viewBox="([^"]+)"', svg).group(1).split()] @@ -39,7 +46,8 @@ def parse(svg): def render(vb, polys, size): # Coverage per pixel per fill color (union of polygons sharing a color). x0, y0, vw, vh = vb - sub = size * SS + ss = supersamples(size) + sub = size * ss sx, sy = sub / vw, sub / vh colors = {} for color, pts in polys: @@ -62,12 +70,12 @@ def render(vb, polys, size): out = bytearray(size * size * 4) for color, grid in colors.items(): for py in range(size): - rows = grid[py * SS:(py + 1) * SS] + rows = grid[py * ss:(py + 1) * ss] for px in range(size): - c = sum(sum(rw[px * SS:(px + 1) * SS]) for rw in rows) + c = sum(sum(rw[px * ss:(px + 1) * ss]) for rw in rows) if not c: continue - a = c / (SS * SS) + a = c / (ss * ss) o = (py * size + px) * 4 # straight-alpha "over" onto what's there da = out[o + 3] / 255 @@ -94,9 +102,21 @@ def ico(pngs): if __name__ == '__main__': src = sys.argv[1] + iconset = '--iconset' in sys.argv[2:] base = os.path.splitext(src)[0] vb, polys = parse(open(src).read()) pngs = [(s, png(render(vb, polys, s), s)) for s in (16, 20, 24, 32, 40, 48, 64, 128, 256)] open(base + '.ico', 'wb').write(ico(pngs)) open(base + '.png', 'wb').write(pngs[-1][1]) print(f'wrote {base}.ico ({len(pngs)} sizes) and {base}.png (256 px)') + if iconset: + os.makedirs(base + '.iconset', exist_ok=True) + done = {s: blob for s, blob in pngs} + for points in (16, 32, 128, 256, 512): + for scale in (1, 2): + px = points * scale + if px not in done: + done[px] = png(render(vb, polys, px), px) + name = f'icon_{points}x{points}' + ('@2x' if scale == 2 else '') + '.png' + open(os.path.join(base + '.iconset', name), 'wb').write(done[px]) + print(f'wrote {base}.iconset (10 images)') From f8cb5f89df6f76cbe32275b8579c3e3ff5e83e6f Mon Sep 17 00:00:00 2001 From: Marc Lavergne Date: Mon, 9 Nov 2026 11:58:17 -0500 Subject: [PATCH 3/3] Review fixes: overlay sizing work, desktop-entry errors, shared app module - engine.minWidth: a measured leaf (wrapped text) is 0 without wrapping it at width 0; it always came out 0 anyway, after splitting the text a character per line into the wrap cache every frame - drawOverlay lowers sheet/alert/popover content once and measures that node, instead of building it once more per frame - installDesktopEntry: a value refused for length says so (not "control character"), and the log no longer echoes a value holding control characters - build.zig: linkApp and the examples share one appModule(), so the runtime a dependent package gets can't drift from the examples'; linkApp documents that the dependency's target must match - mkico.py keeps 16 samples through 256 px, so the committed .ico/.png regenerate byte-for-byte - desktop_entry.zig header names only its caller in this tree Co-Authored-By: Claude Opus 5.5 --- build.zig | 60 +++++++++++++++++++------------------------ src/app.zig | 8 +++++- src/desktop_entry.zig | 2 +- src/layout/engine.zig | 7 +++-- src/view/view.zig | 7 ++--- tools/icon/mkico.py | 7 ++--- 6 files changed, 46 insertions(+), 45 deletions(-) diff --git a/build.zig b/build.zig index b5e68a9..49a544e 100644 --- a/build.zig +++ b/build.zig @@ -107,31 +107,47 @@ pub const AppOptions = struct { /// SDL3 (fetched lazily, on first use), libc and, on macOS, the Objective-C /// runtime. On the first configure SDL may not be fetched yet: the module is /// returned unlinked and the build reruns once the package is there. +/// Pass `b.dependency("zigui", …)` the same target and optimize mode as +/// `opts`: the core module is built for those, and the runtime for `opts`. /// /// const zigui_dep = b.dependency("zigui", .{ .target = target, .optimize = optimize }); /// const app_mod = @import("zigui").linkApp(zigui_dep, .{ .target = target, .optimize = optimize }); /// exe.root_module.addImport("zigui", zigui_dep.module("zigui")); /// exe.root_module.addImport("zigui_app", app_mod); pub fn linkApp(dep: *std.Build.Dependency, opts: AppOptions) *std.Build.Module { - const b = dep.builder; + const sdl: SdlConfig = .{ .prefix = opts.sdl3_prefix, .macos_sdk = opts.macos_sdk, .windows_console = false }; + return appModule(dep.builder, dep.module("zigui"), opts.target, opts.optimize, sdl); +} + +/// The SDL-linking runtime module (`src/app.zig`) over `zigui_mod`, shared by +/// the examples and `linkApp`. SDL's headers come in through translate-c +/// (`@cImport` is gone in Zig 0.17), importable as `sdl_c`. +fn appModule( + b: *std.Build, + zigui_mod: *std.Build.Module, + target: std.Build.ResolvedTarget, + optimize: std.builtin.OptimizeMode, + sdl: SdlConfig, +) *std.Build.Module { const sdl_c = b.addTranslateC(.{ .root_source_file = b.path("src/sdl_c.h"), - .target = opts.target, - .optimize = opts.optimize, + .target = target, + .optimize = optimize, .link_libc = true, }); const app_mod = b.createModule(.{ .root_source_file = b.path("src/app.zig"), - .target = opts.target, - .optimize = opts.optimize, + .target = target, + .optimize = optimize, .link_libc = true, - .imports = &.{.{ .name = "zigui", .module = dep.module("zigui") }}, + .imports = &.{.{ .name = "zigui", .module = zigui_mod }}, }); app_mod.addImport("sdl_c", sdl_c.createModule()); - const sdl: SdlConfig = .{ .prefix = opts.sdl3_prefix, .macos_sdk = opts.macos_sdk, .windows_console = false }; - linkSdl3(b, app_mod, sdl_c, opts.target, opts.optimize, sdl); - if (opts.target.result.os.tag == .macos) { - if (opts.macos_sdk) |sdk| addMacosSdk(b, app_mod, sdk); + linkSdl3(b, app_mod, sdl_c, target, optimize, sdl); + // app.zig reaches AppKit (unified titlebar, menu bar, template tray icons) + // through the Objective-C runtime. + if (target.result.os.tag == .macos) { + if (sdl.macos_sdk) |sdk| addMacosSdk(b, app_mod, sdk); app_mod.linkSystemLibrary("objc", .{}); } return app_mod; @@ -154,29 +170,7 @@ fn addExample( name: []const u8, root_path: []const u8, ) void { - // The SDL-linking runtime module. SDL's headers come in through translate-c - // (`@cImport` is gone in Zig 0.17), importable as `sdl_c`. - const sdl_c = b.addTranslateC(.{ - .root_source_file = b.path("src/sdl_c.h"), - .target = target, - .optimize = optimize, - .link_libc = true, - }); - const app_mod = b.createModule(.{ - .root_source_file = b.path("src/app.zig"), - .target = target, - .optimize = optimize, - .link_libc = true, - .imports = &.{.{ .name = "zigui", .module = zigui_mod }}, - }); - app_mod.addImport("sdl_c", sdl_c.createModule()); - linkSdl3(b, app_mod, sdl_c, target, optimize, sdl); - // app.zig reaches AppKit (unified titlebar, menu bar, template tray icons) - // through the Objective-C runtime. - if (target.result.os.tag == .macos) { - if (sdl.macos_sdk) |sdk| addMacosSdk(b, app_mod, sdk); - app_mod.linkSystemLibrary("objc", .{}); - } + const app_mod = appModule(b, zigui_mod, target, optimize, sdl); // libc headers the examples use (stdio/time), via translate-c as `cstdio`. const cstdio = b.addTranslateC(.{ diff --git a/src/app.zig b/src/app.zig index fa3d08c..0641ad0 100644 --- a/src/app.zig +++ b/src/app.zig @@ -786,8 +786,14 @@ pub fn installDesktopEntry(name: []const u8, icon_png: []const u8) bool { return true; } +/// Logs why `value` cannot go in a desktop entry. The value itself is left +/// out: a control character in it would be written to the log raw. fn logUnwritable(what: []const u8, value: []const u8) bool { - std.log.err("zigui: no desktop entry: its {s} has a control character ({s})", .{ what, value }); + for (value) |byte| if (byte < 0x20 or byte == 0x7f) { + std.log.err("zigui: no desktop entry: its {s} has a control character", .{what}); + return false; + }; + std.log.err("zigui: no desktop entry: its {s} is too long ({d} bytes)", .{ what, value.len }); return false; } diff --git a/src/desktop_entry.zig b/src/desktop_entry.zig index 92ed2d3..4d9b010 100644 --- a/src/desktop_entry.zig +++ b/src/desktop_entry.zig @@ -1,7 +1,7 @@ //! Values for a freedesktop desktop entry (`.desktop` file), escaped per the //! Desktop Entry Specification, so a path with spaces, quotes, `$`, `%` or //! backslashes in it means what it says. Pure; `app.zig`'s -//! `installDesktopEntry` and `desktopEntryState` write and read with it. +//! `installDesktopEntry` writes with it. const std = @import("std"); diff --git a/src/layout/engine.zig b/src/layout/engine.zig index 74b0a5c..3833c77 100644 --- a/src/layout/engine.zig +++ b/src/layout/engine.zig @@ -158,16 +158,15 @@ pub fn measure(node: Node, prop: Proposal) Size { /// minimum, a horizontal stack's children and gaps summed, the widest child /// of any other stack, padding added, and a fixed frame's width. A frame that /// only caps or fills the width does not lower its child's minimum (`arrange` -/// still gives the child that much), and a measured leaf answers for a -/// proposed width of zero (wrapped text: its longest word). +/// still gives the child that much), and a measured leaf (wrapped text) is +/// zero: it wraps, and reports no wider than it is offered. /// /// - `node`: the tree. /// - Returns: the width. pub fn minWidth(node: Node) f32 { return switch (node) { .leaf => |h| h.min.width, - .spacer => 0, - .measured => |m| m.measureFn(m.ctx, .{ .width = 0, .height = null }).width, + .spacer, .measured => 0, .padding => |p| minWidth(p.child.*) + p.insets.horizontal(), .frame => |f| f.width orelse @max(f.min_width orelse 0, minWidth(f.child.*)), .stack => |s| blk: { diff --git a/src/view/view.zig b/src/view/view.zig index 07e1ecc..89c6a48 100644 --- a/src/view/view.zig +++ b/src/view/view.zig @@ -1908,15 +1908,16 @@ fn drawOverlay(ctx: *const Context, req: OverlayReq, root: Rect, canvas: *Canvas // A sheet or alert whose content cannot be narrower than its usual width // (a wide segmented `Picker`) widens to it, as far as the window allows, // rather than being clipped at both edges. + const node = try buildNode(ctx, req.content); if (prop.width) |usual| { - const least = if (buildNode(ctx, req.content)) |node| engine.minWidth(node) else |_| 0; + const least = engine.minWidth(node); if (least > usual) prop.width = @max(usual, @min(least, root.width - 2 * popover_margin)); } - var size = measure(ctx, req.content, prop) catch Size{}; + var size = engine.measure(node, prop); // A popover wider than the window is narrowed to fit (its rows truncate), // not pushed past the edge. const max_w = root.width - 2 * popover_margin; - if (req.style == .popover and size.width > max_w) size = measure(ctx, req.content, .{ .width = max_w, .height = null }) catch size; + if (req.style == .popover and size.width > max_w) size = engine.measure(node, .{ .width = max_w, .height = null }); const target = switch (req.style) { .sheet, .alert => centerRect(root, size), .popover => anchoredRect(root, req.anchor, size), diff --git a/tools/icon/mkico.py b/tools/icon/mkico.py index a643508..1a19d74 100644 --- a/tools/icon/mkico.py +++ b/tools/icon/mkico.py @@ -19,9 +19,10 @@ SS = 16 # supersamples per axis, for the small sizes def supersamples(size): - """Fewer samples as the size grows: a 1024 px icon at 16x16 would take - minutes in pure Python, and the larger sizes need less antialiasing.""" - return max(2, min(SS, 2048 // size)) + """Fewer samples above 256 px: a 1024 px icon at 16x16 would take minutes + in pure Python, and the larger sizes need less antialiasing. Up to 256 px + (the .ico and .png) it stays at SS, so those outputs don't change.""" + return max(2, min(SS, 4096 // size)) def parse(svg): vb = [float(v) for v in re.search(r'viewBox="([^"]+)"', svg).group(1).split()]