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 0000000..90b6d58 Binary files /dev/null and b/assets/icon/zigz.ico differ diff --git a/assets/icon/zigz.png b/assets/icon/zigz.png new file mode 100644 index 0000000..efdb989 Binary files /dev/null and b/assets/icon/zigz.png differ diff --git a/assets/icon/zigz.svg b/assets/icon/zigz.svg new file mode 100644 index 0000000..b962eb6 --- /dev/null +++ b/assets/icon/zigz.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/build.zig b/build.zig index 8acc6e5..49a544e 100644 --- a/build.zig +++ b/build.zig @@ -69,25 +69,66 @@ 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 }; + // 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"); + } } -/// Build a runnable example that links the SDL3-backed runtime (`src/app.zig`). -fn addExample( +/// 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. +/// 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 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, - sdl3_prefix: ?[]const u8, - 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`. + sdl: SdlConfig, +) *std.Build.Module { const sdl_c = b.addTranslateC(.{ .root_source_file = b.path("src/sdl_c.h"), .target = target, @@ -102,10 +143,34 @@ 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", .{}); + } + return app_mod; +} + +/// 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, + sdl: SdlConfig, + name: []const u8, + root_path: []const u8, +) void { + 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(.{ @@ -131,6 +196,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 +218,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..22ae99c 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -1,9 +1,15 @@ .{ .name = .zigui, - .version = "0.2.0", + .version = "0.2.2", .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..0641ad0 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,127 @@ 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); + // 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} + \\Icon={s} + \\StartupWMClass={s} + \\Terminal=false + \\Categories=Utility; + \\ + , .{ 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); + std.log.info("zigui: installed {s} (icon {s})", .{ desk_path, icon_path }); + 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 { + 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; +} + +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 +898,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 +972,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 +1027,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 +1060,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 +1770,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/desktop_entry.zig b/src/desktop_entry.zig new file mode 100644 index 0000000..4d9b010 --- /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` writes 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/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/layout/engine.zig b/src/layout/engine.zig index 13dc6a4..3833c77 100644 --- a/src/layout/engine.zig +++ b/src/layout/engine.zig @@ -154,6 +154,33 @@ 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 (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, .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: { + 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 +477,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/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..89c6a48 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| { @@ -1900,16 +1900,24 @@ 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, }; - var size = measure(ctx, req.content, prop) catch Size{}; + // 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 = engine.minWidth(node); + if (least > usual) prop.width = @max(usual, @min(least, root.width - 2 * popover_margin)); + } + 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), @@ -2301,7 +2309,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 +5082,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 new file mode 100644 index 0000000..1a19d74 --- /dev/null +++ b/tools/icon/mkico.py @@ -0,0 +1,123 @@ +"""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; + * 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 +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, for the small sizes + +def supersamples(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()] + 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 + ss = supersamples(size) + 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('