Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

Port to Zig 0.17 and drop Python from the install and restart path

oxydizerb26ee5d1c75d
diff --git a/AGENTS.md b/AGENTS.md
index 45a1f60..9aa7b52 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -250,14 +250,19 @@ panel painting. The key rules:
compositor imports). Parsing/persistence is `config/`, applying and reloads
`config_runtime/`, shared raster code (`text`, `anim`, `sdf`, icons) `ui/`.
`memory` owns the process allocator; executables own its shutdown.
-* ReleaseSafe's `_FORTIFY_SOURCE` breaks translate-c on `bits/fcntl2.h`: use
- `std.os.linux` or `@cUndef("_FORTIFY_SOURCE")`. Never `@cInclude`
- glib/gobject/gio/librsvg; hand-declare the ABI. No runtime `parseColor()`
- in comptime defaults.
+* Zig 0.17 has no `@cImport`: the build translates header roots in `src/c/`
+ into modules (`support.cHeaders`): `c` (libc), `c_gfx` (libc, cairo,
+ freetype, harfbuzz, fontconfig, xkbcommon), `c_pulse`, `c_libinput`,
+ `c_png`, `c_archive`. Add a header to its root; a module links nothing, so
+ artifacts link their libraries. The roots undefine `_FORTIFY_SOURCE`
+ (fortified wrappers break translate-c in ReleaseSafe) and define
+ `_GNU_SOURCE`, so socket calls take `.{ .__sockaddr__ = @ptrCast(&addr) }`.
+ Never translate glib/gobject/gio/librsvg; hand-declare the ABI. No runtime
+ `parseColor()` in comptime defaults.
* `std.os.linux.*` return `-errno` in `usize` (`std.os.linux.errno`);
`std.posix.system.*` are libc (`std.posix.errno`).
-* **wlroots bindings** live in `src/wlr/`, backed by one `@cImport` against
- the installed headers; read `src/wlr/AGENTS.md` before extending them.
+* **wlroots bindings** live in `src/wlr/`, backed by one translation of
+ the installed headers (`src/wlr/c.h`, module `wlr_c`); read `src/wlr/AGENTS.md` before extending them.
`ext.*`/`wp.*` Wayland types need their protocol in `build/protocols.zig`.
Nullable outputs/buffers are represented explicitly. Full layout checks
protect embedded input devices, so no extra Pointer padding is needed.
diff --git a/README.md b/README.md
index c7cdda0..c160c37 100644
--- a/README.md
+++ b/README.md
@@ -53,7 +53,7 @@ Installing never replaces your login manager
## Building and running
-Requirements: Zig 0.16, wlroots 0.20, and the development files for Wayland,
+Requirements: Zig 0.17, wlroots 0.20, and the development files for Wayland,
wayland-protocols, xkbcommon, pixman, FreeType, HarfBuzz, Fontconfig,
librsvg/GdkPixbuf, PangoCairo, libinput, PAM, libpulse, libpipewire-0.3, Poppler GLib,
libseccomp, libarchive, libjpeg, libpng, libwebp and GNU Readline. Files embeds
diff --git a/build.zig b/build.zig
index 57314d7..1a47420 100644
--- a/build.zig
+++ b/build.zig
@@ -12,7 +12,6 @@ const data = @import("build/data.zig");
const session_build = @import("build/session.zig");
const tests = @import("build/tests.zig");
const support = @import("build/support.zig");
-const usePrivateWlroots = support.usePrivateWlroots;
const addBass = support.addBass;
const addBassDsp = support.addBassDsp;
const addGlass = support.addGlass;
@@ -24,14 +23,15 @@ const addCatalogInputs = support.addCatalogInputs;
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
- const use_llvm = b.option(bool, "llvm", "Use LLVM and LLD (default for optimized builds)") orelse (optimize != .Debug);
+ const use_llvm = b.option(bool, "llvm", "Use LLVM and LLD (default for optimized builds)") orelse (optimize != .debug);
// Debug aid (TESTING.md): redraw every frame whole and log what the damage missed.
const damage_audit = b.option(bool, "damage-audit", "Compare every frame with a full repaint and log the difference (slow)") orelse false;
// Set by scripts/build-wlroots.sh builds on distros without wlroots 0.20
- // (Debian/Ubuntu). Must be applied before anything runs pkg-config.
- const wlroots_prefix = b.option([]const u8, "wlroots-prefix", "Use wlroots and its bundled dependencies from this private prefix (see scripts/build-wlroots.sh)");
- if (wlroots_prefix) |prefix| usePrivateWlroots(b, prefix);
+ // (Debian/Ubuntu). pkg-config runs in zig build's own environment, so
+ // start it through scripts/with-wlroots.sh to find the prefix.
+ const wlroots_prefix = b.option([]const u8, "wlroots-prefix", "Use wlroots and its bundled dependencies from this private prefix (run through scripts/with-wlroots.sh)");
+ const c_headers = support.cHeaders(b, target, optimize);
const wayland = protocols.module(b);
const xkbcommon = b.dependency("xkbcommon", .{}).module("xkbcommon");
const pixman = b.dependency("pixman", .{}).module("pixman");
@@ -46,6 +46,7 @@ pub fn build(b: *std.Build) void {
wlr_facade.addImport("pixman", pixman);
wlr_facade.addImport("xkbcommon", xkbcommon);
wlr_facade.linkSystemLibrary("wlroots-0.20", .{});
+ const wlr_c = support.cTranslation(b, target, optimize, b.path("src/wlr/c.h"), &.{"wlroots-0.20"});
// These public wlroots headers include protocol headers which wlroots
// does not install. Generate them from the same XML as our Zig bindings.
@@ -53,14 +54,15 @@ pub fn build(b: *std.Build) void {
const run = b.addSystemCommand(&.{ "wayland-scanner", "server-header" });
run.addFileArg(b.path("protocol/" ++ name ++ ".xml"));
const header = run.addOutputFileArg(name ++ "-protocol.h");
- wlr_facade.addIncludePath(header.dirname());
+ wlr_c.addIncludePath(header.dirname());
}
+ wlr_facade.addImport("wlr_c", b.createModule(.{ .root_source_file = wlr_c.getOutput() }));
const wlroots = wlr_facade;
// Module roots enforce one-way dependencies: shared code cannot import Server.
const memory_mod = b.createModule(.{ .root_source_file = b.path("src/memory/allocator.zig"), .target = target, .optimize = optimize });
- const i18n_tool = b.addExecutable(.{ .name = "i18n-tool", .root_module = b.createModule(.{ .root_source_file = b.path("tools/i18n.zig"), .target = b.graph.host, .optimize = .ReleaseSafe }) });
+ const i18n_tool = b.addExecutable(.{ .name = "i18n-tool", .root_module = b.createModule(.{ .root_source_file = b.path("tools/i18n.zig"), .target = b.graph.host, .optimize = .safe }) });
const catalog_compile = b.addRunArtifact(i18n_tool);
catalog_compile.setCwd(b.path("."));
catalog_compile.addArg("compile");
@@ -79,6 +81,7 @@ pub fn build(b: *std.Build) void {
ui_mod.addImport("i18n", i18n_mod);
ui_mod.addImport("memory", memory_mod);
ui_mod.addImport("wayland", wayland);
+ ui_mod.addImport("c_gfx", c_headers.gfx);
ui_mod.linkSystemLibrary("xkbcommon", .{});
addShellUi(b, ui_mod);
ui_mod.addAnonymousImport("theme-rediwm-dark", .{ .root_source_file = b.path("assets/themes/rediwm-dark.toml") });
@@ -142,6 +145,9 @@ pub fn build(b: *std.Build) void {
compositor.root_module.addImport("xkbcommon", xkbcommon);
compositor.root_module.addImport("wlroots", wlroots);
compositor.root_module.addImport("pixman", pixman);
+ compositor.root_module.addImport("c_pulse", c_headers.pulse);
+ compositor.root_module.addImport("c_libinput", c_headers.libinput);
+ compositor.root_module.addImport("c_png", c_headers.png);
compositor.root_module.linkSystemLibrary("wayland-server", .{});
compositor.root_module.linkSystemLibrary("cups", .{});
compositor.root_module.addCSourceFile(.{ .file = b.path("src/printing/direct.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-Wno-deprecated-declarations" } });
@@ -203,6 +209,7 @@ pub fn build(b: *std.Build) void {
.dbus_mod = dbus_mod,
.config_mod = config_mod,
.protocol_mod = protocol_mod,
+ .c = c_headers,
};
const app = apps.add(ctx);
const files = app.files;
@@ -249,6 +256,8 @@ pub fn build(b: *std.Build) void {
module.addImport("i18n", i18n_mod);
module.addImport("config", config_mod);
module.addImport("memory", memory_mod);
+ module.addImport("c", c_headers.libc);
+ module.addImport("c_gfx", c_headers.gfx);
}
inline for (.{ compositor.root_module, ui_tests_module, dbus_tests.root_module, dbus_service.root_module, polkit_service.root_module, session_supervisor.root_module, session_tests.root_module, share_picker_tests.root_module, files_tests.root_module }) |module| {
module.addImport("dbus", dbus_mod);
@@ -256,15 +265,16 @@ pub fn build(b: *std.Build) void {
tests.addC(ctx, zig_tests.test_step);
- const run_cmd = b.addRunArtifact(compositor);
+ // Autostart looks up `rediwm-desktop` / `rediwm-files` on PATH. Run the
+ // cached artifact with the installed bin directory first on PATH.
+ const run_cmd = b.addSystemCommand(&.{ "sh", "-c", "PATH=\"$0:$PATH\" exec \"$@\"" });
+ run_cmd.addDirectoryArg(support.installed(.bin, ""));
+ run_cmd.addArtifactArg(compositor);
// The development run target is always nested in the current Wayland session.
run_cmd.setEnvironmentVariable("WLR_BACKENDS", "wayland");
run_cmd.setEnvironmentVariable("WLR_WL_OUTPUTS", "1");
- // Autostart looks up `rediwm-desktop` / `rediwm-files` on PATH. The run
- // artifact lives in the cache, so install the helpers and expose zig-out/bin.
run_cmd.step.dependOn(b.getInstallStep());
- run_cmd.addPathDir(b.exe_dir);
- if (b.args) |args| run_cmd.addArgs(args);
+ run_cmd.addPassthruArgs();
const run_step = b.step("run", "Run the nested compositor (pass a client command after --)");
run_step.dependOn(&run_cmd.step);
}
diff --git a/build.zig.zon b/build.zig.zon
index 910129c..30ebaec 100644
--- a/build.zig.zon
+++ b/build.zig.zon
@@ -1,7 +1,7 @@
.{
.name = .rediwm,
.version = "0.1.7",
- .minimum_zig_version = "0.16.0",
+ .minimum_zig_version = "0.17.0",
.paths = .{
"build.zig",
"build.zig.zon",
@@ -18,16 +18,16 @@
.hash = "N-V-__8AAFwIBQAS1j3S14ozuJ18ebNtLQ-c5Kl6W4J7PoJt",
},
.pixman = .{
- .url = "https://codeberg.org/ifreund/zig-pixman/archive/v0.3.0.tar.gz",
- .hash = "pixman-0.3.0-LClMnz2VAAAs7QSCGwLimV5VUYx0JFnX5xWU6HwtMuDX",
+ .url = "https://codeberg.org/ifreund/zig-pixman/archive/v0.4.0.tar.gz",
+ .hash = "pixman-0.4.0-LClMn_eWAAAa2zACATDpPwjuI5fWlO5cBp_F_M33hnNZ",
},
.wayland = .{
- .url = "https://codeberg.org/ifreund/zig-wayland/archive/v0.6.0.tar.gz",
- .hash = "wayland-0.6.0-lQa1kqz8AQADQmdNJsNhLoNHcnEGEUjrOaPV-dtEnEmX",
+ .url = "https://codeberg.org/ifreund/zig-wayland/archive/v0.7.0.tar.gz",
+ .hash = "wayland-0.7.0-lQa1kuP8AQD5dW7_o-VKLVD_QbqXe7Zob78r2su7Pyex",
},
.xkbcommon = .{
- .url = "https://codeberg.org/ifreund/zig-xkbcommon/archive/v0.3.0.tar.gz",
- .hash = "xkbcommon-0.3.0-VDqIe3K9AQB2fG5ZeRcMC9i7kfrp5m2rWgLrmdNn9azr",
+ .url = "https://codeberg.org/ifreund/zig-xkbcommon/archive/v0.5.0.tar.gz",
+ .hash = "xkbcommon-0.5.0-VDqIe8y3AgDU-cGL02xZplwABH3WbpTimrrgbgTgD_3g",
},
},
.fingerprint = 0x6c5977b13cbceb1,
diff --git a/build/apps.zig b/build/apps.zig
index 1027881..f307178 100644
--- a/build/apps.zig
+++ b/build/apps.zig
@@ -37,6 +37,7 @@ pub fn add(ctx: Context) Apps {
files.root_module.addImport("wayland", wayland);
inline for (.{ "wayland-client", "wayland-cursor", "xkbcommon", "gio-2.0", "gdk-pixbuf-2.0", "gobject-2.0", "glib-2.0" }) |lib| files.root_module.linkSystemLibrary(lib, .{});
files.root_module.linkSystemLibrary("libarchive", .{});
+ files.root_module.addImport("c_archive", ctx.c.archive);
addThumbCodec(b, files.root_module);
addVolumes(b, files.root_module);
addFilesTerminal(b, files.root_module, false);
@@ -44,11 +45,11 @@ pub fn add(ctx: Context) Apps {
b.getInstallStep().dependOn(&terminal_license.step);
// Use the system C++ ABI, matching the distro's libtorrent-rasterbar.
const torrents = b.addSystemCommand(&.{ "sh", "-c", "exec c++ -std=c++17 -Wall -Wextra -Werror -Wno-deprecated-declarations -Wno-missing-field-initializers $(pkg-config --cflags libtorrent-rasterbar gio-unix-2.0 json-glib-1.0) \"$@\" $(pkg-config --libs libtorrent-rasterbar gio-unix-2.0 json-glib-1.0)", "build-transfers" });
- torrents.addArg(if (optimize == .Debug) "-O0" else "-O2");
+ torrents.addArg(if (optimize == .debug) "-O0" else "-O2");
torrents.addArg("-g");
torrents.addArg("-D_GLIBCXX_ASSERTIONS");
torrents.addArg("-fstack-protector-strong");
- if (optimize != .Debug) torrents.addArg("-D_FORTIFY_SOURCE=3");
+ if (optimize != .debug) torrents.addArg("-D_FORTIFY_SOURCE=3");
inline for (.{ "helper.cpp", "helper_transfers.cpp", "helper_peers.cpp", "helper_tray.cpp" }) |part| torrents.addFileArg(b.path("src/files/torrent/" ++ part));
torrents.addFileInput(b.path("src/files/torrent/helper.hpp"));
torrents.addArg("-o");
@@ -69,9 +70,9 @@ pub fn add(ctx: Context) Apps {
);
b.getInstallStep().dependOn(&install_files.step);
b.getInstallStep().dependOn(&install_files_desktop_entry.step);
- const install_files_icon = b.addSystemCommand(&.{ "install", "-Dm644" });
+ const install_files_icon = b.addSystemCommand(&.{ "install", "-Dm644", "-t" });
+ install_files_icon.addDirectoryArg(support.installed(.prefix, "share/icons/hicolor/256x256/apps"));
install_files_icon.addFileArg(b.path("assets/icons/redi-fm-icon.png"));
- install_files_icon.addArg(b.getInstallPath(.prefix, "share/icons/hicolor/256x256/apps/redi-fm-icon.png"));
b.getInstallStep().dependOn(&install_files_icon.step);
// rediwm-files links neither wlroots-server nor libinput/libpulse, so it
// can be built (and its dependencies checked) without the rest of this
@@ -104,7 +105,7 @@ pub fn add(ctx: Context) Apps {
const bash_hook = b.addLibrary(.{
.name = "rediwm-files-bash",
.linkage = .dynamic,
- .root_module = b.createModule(.{ .target = target, .optimize = .ReleaseFast, .link_libc = true, .sanitize_c = .off }),
+ .root_module = b.createModule(.{ .target = target, .optimize = .fast, .link_libc = true, .sanitize_c = .off }),
});
bash_hook.root_module.addCSourceFile(.{ .file = b.path("src/files/terminal/bash.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
bash_hook.root_module.linkSystemLibrary("readline", .{});
diff --git a/build/context.zig b/build/context.zig
index a081f58..b72261f 100644
--- a/build/context.zig
+++ b/build/context.zig
@@ -2,11 +2,12 @@
//! artifact is assembled from.
const std = @import("std");
+const CHeaders = @import("support.zig").CHeaders;
pub const Context = struct {
b: *std.Build,
target: std.Build.ResolvedTarget,
- optimize: std.builtin.OptimizeMode,
+ optimize: std.lang.Optimize,
use_llvm: bool,
wlroots_prefix: ?[]const u8,
i18n_tool: *std.Build.Step.Compile,
@@ -19,4 +20,5 @@ pub const Context = struct {
dbus_mod: *std.Build.Module,
config_mod: *std.Build.Module,
protocol_mod: *std.Build.Module,
+ c: CHeaders,
};
diff --git a/build/data.zig b/build/data.zig
index de0efa7..8d3b76d 100644
--- a/build/data.zig
+++ b/build/data.zig
@@ -50,7 +50,7 @@ pub fn add(ctx: Context) void {
.root_module = b.createModule(.{
.root_source_file = b.path("src/cursor_theme_gen.zig"),
.target = b.graph.host,
- .optimize = .ReleaseSafe,
+ .optimize = .safe,
.link_libc = true,
}),
.use_llvm = use_llvm,
@@ -58,12 +58,13 @@ pub fn add(ctx: Context) void {
});
cursorgen.root_module.linkSystemLibrary("librsvg-2.0", .{});
cursorgen.root_module.linkSystemLibrary("cairo", .{});
+ cursorgen.root_module.addImport("c_gfx", support.cHeader(b, b.graph.host, .safe, b.path("src/c/gfx.h"), &support.gfx_libs));
const cursorgen_run = b.addRunArtifact(cursorgen);
cursorgen_run.addDirectoryArg(b.path("assets/cursors"));
const cursor_themes = cursorgen_run.addOutputDirectoryArg("icons");
// Cursor aliases are symlinks, which InstallDir drops; cp -a keeps them.
const install_cursors = b.addSystemCommand(&.{ "sh", "-c", "mkdir -p \"$2\" && cp -a -T \"$1\" \"$2\"", "sh" });
install_cursors.addDirectoryArg(cursor_themes);
- install_cursors.addArg(b.getInstallPath(.prefix, "share/icons"));
+ install_cursors.addDirectoryArg(support.installed(.prefix, "share/icons"));
b.getInstallStep().dependOn(&install_cursors.step);
}
diff --git a/build/session.zig b/build/session.zig
index 1ec8991..eb6df68 100644
--- a/build/session.zig
+++ b/build/session.zig
@@ -34,6 +34,19 @@ pub fn add(ctx: Context) Session {
if (wlroots_prefix != null) session_supervisor.root_module.addRPathSpecial("$ORIGIN/../lib/rediwm");
b.installArtifact(session_supervisor);
+ const restart = b.addExecutable(.{
+ .name = "rediwm-restart",
+ .root_module = b.createModule(.{
+ .root_source_file = b.path("src/session_restart.zig"),
+ .target = target,
+ .optimize = optimize,
+ .link_libc = true,
+ }),
+ .use_llvm = use_llvm,
+ .use_lld = use_llvm,
+ });
+ b.installArtifact(restart);
+
const child_set_mod = b.createModule(.{ .root_source_file = b.path("src/child_set.zig"), .target = target, .optimize = optimize });
const dm_ipc_mod = b.createModule(.{
.root_source_file = b.path("src/session/dm_ipc.zig"),
@@ -46,6 +59,9 @@ pub fn add(ctx: Context) Session {
.optimize = optimize,
});
+ dm_ipc_mod.addImport("c", ctx.c.libc);
+ ws_mod.addImport("c", ctx.c.libc);
+
const dm = b.addExecutable(.{
.name = "rediwm-dm",
.root_module = b.createModule(.{
@@ -57,6 +73,7 @@ pub fn add(ctx: Context) Session {
.use_llvm = use_llvm,
.use_lld = use_llvm,
});
+ dm.root_module.addImport("c", ctx.c.libc);
dm.root_module.addImport("child_set", child_set_mod);
dm.root_module.addImport("dm_ipc", dm_ipc_mod);
dm.root_module.addImport("wayland_sessions", ws_mod);
@@ -75,6 +92,7 @@ pub fn add(ctx: Context) Session {
.use_llvm = use_llvm,
.use_lld = use_llvm,
});
+ accounts_helper.root_module.addImport("c", ctx.c.libc);
accounts_helper.root_module.addImport("wayland_sessions", ws_mod);
accounts_helper.root_module.addImport("accounts_validation", b.createModule(.{
.root_source_file = b.path("src/accounts/validation.zig"),
diff --git a/build/support.zig b/build/support.zig
index 7b0a211..303ecbf 100644
--- a/build/support.zig
+++ b/build/support.zig
@@ -1,19 +1,53 @@
-//! Small build helpers: the private wlroots prefix, C sources and assets shared by
+//! Small build helpers: translated C headers, C sources and assets shared by
//! several artifacts, localized data files and the catalog inputs.
const std = @import("std");
-pub fn usePrivateWlroots(b: *std.Build, prefix: []const u8) void {
- prependEnvPath(b, "PKG_CONFIG_PATH", b.fmt("{s}/lib/pkgconfig:{s}/share/pkgconfig", .{ prefix, prefix }));
- // Tests and `zig build run` execute from the cache, where the installed
- // RUNPATH doesn't reach lib/rediwm.
- prependEnvPath(b, "LD_LIBRARY_PATH", b.pathJoin(&.{ prefix, "runtime" }));
+/// C headers as modules: Zig 0.17 has no @cImport. Each translates one header
+/// root under src/c/ (src/wlr/c.h for wlroots). The module is created without
+/// the translation's link objects, so importing one never links its libraries:
+/// artifacts link what they call. pkg-config only supplies include paths.
+pub const CHeaders = struct {
+ /// libc and Linux (`c`).
+ libc: *std.Build.Module,
+ /// libc, cairo, fontconfig, freetype, harfbuzz, xkbcommon (`c_gfx`).
+ gfx: *std.Build.Module,
+ pulse: *std.Build.Module,
+ libinput: *std.Build.Module,
+ png: *std.Build.Module,
+ archive: *std.Build.Module,
+};
+
+pub const gfx_libs = [_][]const u8{ "cairo", "fontconfig", "freetype2", "harfbuzz", "xkbcommon" };
+
+pub fn cHeaders(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize) CHeaders {
+ return .{
+ .libc = cHeader(b, target, optimize, b.path("src/c/libc.h"), &.{}),
+ .gfx = cHeader(b, target, optimize, b.path("src/c/gfx.h"), &gfx_libs),
+ .pulse = cHeader(b, target, optimize, b.path("src/c/pulse.h"), &.{"libpulse"}),
+ .libinput = cHeader(b, target, optimize, b.path("src/c/libinput.h"), &.{"libinput"}),
+ .png = cHeader(b, target, optimize, b.path("src/c/png.h"), &.{"libpng16"}),
+ .archive = cHeader(b, target, optimize, b.path("src/c/archive.h"), &.{"libarchive"}),
+ };
+}
+
+pub fn cHeader(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, header: std.Build.LazyPath, libs: []const []const u8) *std.Build.Module {
+ return b.createModule(.{ .root_source_file = cTranslation(b, target, optimize, header, libs).getOutput() });
+}
+
+pub fn cTranslation(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, header: std.Build.LazyPath, libs: []const []const u8) *std.Build.Step.TranslateC {
+ const translate = b.addTranslateC(.{ .root_source_file = header, .target = target, .optimize = optimize });
+ for (libs) |lib| translate.linkSystemLibrary(lib, .{});
+ return translate;
}
-pub fn prependEnvPath(b: *std.Build, key: []const u8, dirs: []const u8) void {
- const env = &b.graph.environ_map;
- const value = if (env.get(key)) |prev| b.fmt("{s}:{s}", .{ dirs, prev }) else dirs;
- env.put(key, value) catch @panic("OOM");
+/// A directory under the install prefix as a Run argument. The prefix is known
+/// only when the build runs, so it cannot be a string.
+pub fn installed(base: enum { prefix, bin }, sub_path: []const u8) std.Build.LazyPath {
+ return .{ .relative = .{ .base = switch (base) {
+ .prefix => .install_prefix,
+ .bin => .install_bin,
+ }, .sub_path = sub_path } };
}
pub fn addBass(b: *std.Build, module: *std.Build.Module) void {
@@ -29,7 +63,7 @@ pub fn addBassDsp(b: *std.Build, target: std.Build.ResolvedTarget) void {
.linkage = .dynamic,
// Realtime audio code: optimized in every build mode, and no UBSan
// runtime for PipeWire's dlopen to resolve.
- .root_module = b.createModule(.{ .target = target, .optimize = .ReleaseFast, .link_libc = true, .sanitize_c = .off }),
+ .root_module = b.createModule(.{ .target = target, .optimize = .fast, .link_libc = true, .sanitize_c = .off }),
});
dsp.root_module.addCSourceFile(.{ .file = b.path("src/audio/bass_dsp.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra" } });
dsp.root_module.linkSystemLibrary("m", .{});
@@ -70,6 +104,7 @@ pub fn addGlass(b: *std.Build, module: *std.Build.Module, damage_audit: bool) vo
pub fn addThumbCodec(b: *std.Build, module: *std.Build.Module) void {
module.addIncludePath(b.path("src/files"));
module.addCSourceFile(.{ .file = b.path("src/files/thumb_codec.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
+ module.addImport("c_thumb_codec", cHeader(b, module.resolved_target.?, module.optimize.?, b.path("src/files/thumb_codec.h"), &.{}));
inline for (.{ "libjpeg", "libpng16" }) |lib| module.linkSystemLibrary(lib, .{});
}
@@ -82,12 +117,16 @@ pub fn addFilesTerminal(b: *std.Build, module: *std.Build.Module, for_tests: boo
module.addIncludePath(b.path("src/files/terminal"));
const flags: []const []const u8 = if (for_tests) &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-DFT_TEST" } else &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" };
module.addCSourceFile(.{ .file = b.path("src/files/terminal/engine.c"), .flags = flags });
+ const engine = cTranslation(b, module.resolved_target.?, module.optimize.?, b.path("src/files/terminal/engine.h"), &.{});
+ if (for_tests) engine.defineCMacro("FT_TEST", "1");
+ module.addImport("c_terminal", b.createModule(.{ .root_source_file = engine.getOutput() }));
module.linkSystemLibrary("util", .{});
}
pub fn addVolumes(b: *std.Build, module: *std.Build.Module) void {
module.addIncludePath(b.path("src/files"));
module.addCSourceFile(.{ .file = b.path("src/files/volumes.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
+ module.addImport("c_volumes", cHeader(b, module.resolved_target.?, module.optimize.?, b.path("src/files/volumes.h"), &.{}));
inline for (.{ "gio-2.0", "gobject-2.0", "glib-2.0" }) |lib| module.linkSystemLibrary(lib, .{});
}
@@ -124,7 +163,8 @@ pub fn localizedData(b: *std.Build, tool: *std.Build.Step.Compile, path: []const
/// explicitly so edits, review flags and newly added languages invalidate both
/// compiled UI tables and installed desktop/polkit metadata.
pub fn addCatalogInputs(b: *std.Build, run: *std.Build.Step.Run) void {
- var dir = b.build_root.handle.openDir(b.graph.io, "po", .{ .iterate = true }) catch @panic("cannot open po/");
+ b.dependOnDirectoryContents(b.path("po"));
+ var dir = b.root.openDir(b.graph.io, "po", .{ .iterate = true }) catch @panic("cannot open po/");
defer dir.close(b.graph.io);
var paths: std.ArrayList([]const u8) = .empty;
var it = dir.iterate();
diff --git a/build/tests.zig b/build/tests.zig
index 9fea793..e1fb164 100644
--- a/build/tests.zig
+++ b/build/tests.zig
@@ -73,6 +73,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
ui_tests_module.linkSystemLibrary("libinput", .{});
ui_tests_module.linkSystemLibrary("png16", .{});
ui_tests_module.linkSystemLibrary("libpulse", .{});
+ inline for (.{ .{ "c_pulse", ctx.c.pulse }, .{ "c_libinput", ctx.c.libinput }, .{ "c_png", ctx.c.png } }) |entry| ui_tests_module.addImport(entry[0], entry[1]);
ui_tests_module.linkSystemLibrary("xcb", .{});
addBass(b, ui_tests_module);
// Fake PAM is linked only into unit tests; the compositor always uses libpam.
@@ -91,6 +92,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
});
ipc_tests_module.addImport("protocol", protocol_mod);
ipc_tests_module.linkSystemLibrary("png16", .{});
+ ipc_tests_module.addImport("c_png", ctx.c.png);
const ipc_tests = b.addTest(.{ .root_module = ipc_tests_module });
const run_ipc_tests = b.addRunArtifact(ipc_tests);
@@ -111,6 +113,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
.optimize = optimize,
.link_libc = true,
}) });
+ monitor_tests.root_module.addImport("c", ctx.c.libc);
const run_monitor_tests = b.addRunArtifact(monitor_tests);
const monitor_test_step = b.step("test-monitor", "Test System Monitor collection, process identity and model");
monitor_test_step.dependOn(&run_monitor_tests.step);
@@ -121,6 +124,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
.optimize = optimize,
.link_libc = true,
}) });
+ printing_tests.root_module.addImport("c", ctx.c.libc);
printing_tests.root_module.addImport("dbus", dbus_mod);
printing_tests.root_module.addImport("i18n", i18n_mod);
printing_tests.root_module.addImport("wayland", wayland);
@@ -189,7 +193,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
polkit_service.root_module.addCSourceFile(.{ .file = b.path("src/polkit/native.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
polkit_service.root_module.linkSystemLibrary("pthread", .{});
const polkit_manual = b.addRunArtifact(polkit_service);
- if (b.args) |args| polkit_manual.addArgs(args);
+ polkit_manual.addPassthruArgs();
b.step("run-polkit-test-agent", "Run the noninstalled polkit test agent (-- --terminal for manual authentication)").dependOn(&polkit_manual.step);
const polkit_integration = b.addSystemCommand(&.{"python3"});
polkit_integration.addFileArg(b.path("tests/polkit.py"));
@@ -245,6 +249,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
.optimize = optimize,
.link_libc = true,
}) });
+ dm_tests.root_module.addImport("c", ctx.c.libc);
dm_tests.root_module.addImport("child_set", child_set_mod);
dm_tests.root_module.addImport("dm_ipc", dm_ipc_mod);
dm_tests.root_module.addImport("wayland_sessions", ws_mod);
@@ -299,7 +304,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
const run_lock_tests = b.addRunArtifact(lock_tests);
const lock_step = b.step("test-lock", "Test lock isolation, password editing, rendering, PAM outcomes and the rediwm-dm greeter");
lock_step.dependOn(&run_lock_tests.step);
- const auth_tests = b.addExecutable(.{ .name = "auth-tests", .root_module = b.createModule(.{ .target = target, .optimize = .Debug, .link_libc = true }) });
+ const auth_tests = b.addExecutable(.{ .name = "auth-tests", .root_module = b.createModule(.{ .target = target, .optimize = .debug, .link_libc = true }) });
auth_tests.root_module.addCSourceFile(.{ .file = b.path("tests/auth_test.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
const run_auth_tests = b.addRunArtifact(auth_tests);
lock_step.dependOn(&run_auth_tests.step);
@@ -329,15 +334,17 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {
files_tests.root_module.linkSystemLibrary("gio-2.0", .{});
inline for (.{ "gdk-pixbuf-2.0", "gobject-2.0", "glib-2.0" }) |lib| files_tests.root_module.linkSystemLibrary(lib, .{});
files_tests.root_module.linkSystemLibrary("libarchive", .{});
+ files_tests.root_module.addImport("c_archive", ctx.c.archive);
addThumbCodec(b, files_tests.root_module);
addVolumes(b, files_tests.root_module);
addFilesTerminal(b, files_tests.root_module, true);
const run_files_tests = b.addRunArtifact(files_tests);
test_step.dependOn(&run_files_tests.step);
b.step("test-files", "Test Files editing, navigation, transfers and layout").dependOn(&run_files_tests.step);
- const terminal_integration = b.addSystemCommand(&.{"python3"});
+ const terminal_integration = b.addSystemCommand(&.{"env"});
+ terminal_integration.addPrefixedDirectoryArg("REDIWM_TEST_BIN=", support.installed(.bin, ""));
+ terminal_integration.addArg("python3");
terminal_integration.addFileArg(b.path("tests/files_terminal.py"));
- terminal_integration.setEnvironmentVariable("REDIWM_TEST_BIN", b.getInstallPath(.bin, ""));
terminal_integration.step.dependOn(b.getInstallStep());
const terminal_tests = b.step("test-files-terminal", "Test the Files terminal against isolated PTYs and a headless compositor");
terminal_tests.dependOn(&run_files_tests.step);
@@ -360,7 +367,7 @@ pub fn addC(ctx: Context, test_step: *std.Build.Step) void {
const optimize = ctx.optimize;
const gpu_timing_tests = b.addExecutable(.{
.name = "gpu-timing-tests",
- .root_module = b.createModule(.{ .target = target, .optimize = .Debug, .link_libc = true }),
+ .root_module = b.createModule(.{ .target = target, .optimize = .debug, .link_libc = true }),
});
gpu_timing_tests.root_module.addCSourceFile(.{ .file = b.path("src/gpu_timing_test.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
inline for (.{ "wlroots-0.20", "wayland-server", "pixman-1", "egl", "glesv2" }) |lib| {
@@ -372,7 +379,7 @@ pub fn addC(ctx: Context, test_step: *std.Build.Step) void {
const node_tests = b.addExecutable(.{
.name = "node-tests",
- .root_module = b.createModule(.{ .target = target, .optimize = .Debug, .link_libc = true }),
+ .root_module = b.createModule(.{ .target = target, .optimize = .debug, .link_libc = true }),
});
node_tests.root_module.addCSourceFile(.{ .file = b.path("src/node_test.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
node_tests.root_module.addCSourceFile(.{ .file = b.path("src/node.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
@@ -385,7 +392,7 @@ pub fn addC(ctx: Context, test_step: *std.Build.Step) void {
const projection_tests = b.addExecutable(.{
.name = "projection-tests",
- .root_module = b.createModule(.{ .target = target, .optimize = .Debug, .link_libc = true }),
+ .root_module = b.createModule(.{ .target = target, .optimize = .debug, .link_libc = true }),
});
projection_tests.root_module.addCSourceFile(.{ .file = b.path("src/projection_test.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
projection_tests.root_module.addCSourceFile(.{ .file = b.path("src/scene_damage.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
@@ -400,7 +407,7 @@ pub fn addC(ctx: Context, test_step: *std.Build.Step) void {
const glass_tests = b.addExecutable(.{
.name = "glass-tests",
- .root_module = b.createModule(.{ .target = target, .optimize = .Debug, .link_libc = true }),
+ .root_module = b.createModule(.{ .target = target, .optimize = .debug, .link_libc = true }),
});
glass_tests.root_module.addCSourceFile(.{ .file = b.path("src/glass_test.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
inline for (.{ "wlroots-0.20", "wayland-server", "pixman-1", "egl", "glesv2" }) |lib| {
diff --git a/patches/wlroots/README.md b/patches/wlroots/README.md
index 768cbfb..d88fb6e 100644
--- a/patches/wlroots/README.md
+++ b/patches/wlroots/README.md
@@ -14,12 +14,13 @@ including on systems that already package wlroots:
```sh
scripts/build-wlroots.sh "$PWD/zig-out/wlroots"
-zig build -Dwlroots-prefix="$PWD/zig-out/wlroots"
+scripts/with-wlroots.sh "$PWD/zig-out/wlroots" zig build -Dwlroots-prefix="$PWD/zig-out/wlroots"
umask 077
python3 tests/window_titles.py
```
-Keep `-Dwlroots-prefix` on subsequent builds. The resulting binaries bundle
+Keep `-Dwlroots-prefix`, run through `scripts/with-wlroots.sh`, on subsequent
+builds. The resulting binaries bundle
the patched library in `lib/rediwm`; the system wlroots package is unchanged.
Builds without a private prefix retain the system library's title policy.
Release tarballs (`scripts/make-release.sh`) are always built this way, so the
diff --git a/scripts/AGENTS.md b/scripts/AGENTS.md
index 1b0faaf..4e6fe78 100644
--- a/scripts/AGENTS.md
+++ b/scripts/AGENTS.md
@@ -21,7 +21,7 @@
(no network sandbox, no systemd), which are harmless.
* **`DEPENDS` is generated from the built binaries' `NEEDED` libraries**
(`release-build.sh`), never hand-kept; only the extras (Xwayland, portals,
- Python, Mesa drivers) are listed by hand. Libraries bundled in `lib/rediwm`
+ Mesa drivers) are listed by hand. Libraries bundled in `lib/rediwm`
are excluded, and which ones get bundled depends on what the build container
has installed, so never install the distro's own wlroots there.
* **Releases always use the pinned, patched wlroots** from `build-wlroots.sh`,
diff --git a/scripts/install-session.sh b/scripts/install-session.sh
index 90dc2d2..f13a10f 100644
--- a/scripts/install-session.sh
+++ b/scripts/install-session.sh
@@ -37,7 +37,6 @@ done
if [ "$restart" = yes ]; then
echo "This update restarts RediWM and closes connected applications. Save your work first."
fi
-command -v python3 >/dev/null
if [ "$prebuilt" = no ]; then
# Reserve 2 CPU cores for system responsiveness unless overridden by ZIG_JOBS
if [ -z "${ZIG_JOBS:-}" ]; then
@@ -50,15 +49,18 @@ if [ "$prebuilt" = no ]; then
fi
cd "$repo_dir"
# Set by install.sh when it built the private wlroots (see scripts/build-wlroots.sh).
- wlroots_flag=${REDIWM_WLROOTS_PREFIX:+-Dwlroots-prefix=$REDIWM_WLROOTS_PREFIX}
- as_user zig build -Doptimize=ReleaseSafe -j"$ZIG_JOBS" --prefix "$release_dir" $wlroots_flag
+ if [ -n "${REDIWM_WLROOTS_PREFIX:-}" ]; then
+ as_user sh scripts/with-wlroots.sh "$REDIWM_WLROOTS_PREFIX" zig build -Doptimize=ReleaseSafe -j"$ZIG_JOBS" --prefix "$release_dir" -Dwlroots-prefix="$REDIWM_WLROOTS_PREFIX"
+ else
+ as_user zig build -Doptimize=ReleaseSafe -j"$ZIG_JOBS" --prefix "$release_dir"
+ fi
fi
-for binary in rediwm rediwm-msg rediwm-theme rediwm-files rediwm-images rediwm-monitor rediwm-editor rediwm-pdf rediwm-share-picker rediwm-dm rediwm-accounts-helper; do
+for binary in rediwm rediwm-msg rediwm-theme rediwm-files rediwm-images rediwm-monitor rediwm-editor rediwm-pdf rediwm-share-picker rediwm-dm rediwm-accounts-helper rediwm-restart; do
test -x "$release_dir/bin/$binary"
done
as_root sh "$repo_dir/scripts/install-session-root.sh" "$repo_dir" "$release_dir" "$dm_flag"
if [ "$restart" = no ]; then
echo 'Installed ReleaseSafe. Running session left as-is.'
else
- as_user python3 "$repo_dir/scripts/restart-session.py"
+ as_user "$release_dir/bin/rediwm-restart"
fi
diff --git a/scripts/install.sh b/scripts/install.sh
index 6f7bafc..71fecba 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -234,7 +234,7 @@ case "$FAMILY" in
arch)
deps="wayland wayland-protocols pixman libxkbcommon \
freetype2 harfbuzz fontconfig librsvg cairo pango libinput poppler-glib libseccomp \
- libarchive libwebp libpng libjpeg-turbo libpulse pipewire pam libcups mesa pkgconf git python readline gcc boost libtorrent-rasterbar json-glib \
+ libarchive libwebp libpng libjpeg-turbo libpulse pipewire pam libcups mesa pkgconf git readline gcc boost libtorrent-rasterbar json-glib \
xorg-xwayland xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk"
if [ "$PRIVATE_WLROOTS" = no ]; then
deps="wlroots0.20 $deps"
@@ -249,7 +249,7 @@ case "$FAMILY" in
fi
;;
debian)
- deps="build-essential meson ninja-build pkg-config git curl ca-certificates xz-utils python3 \
+ deps="build-essential meson ninja-build pkg-config git curl ca-certificates xz-utils \
bison libexpat1-dev libffi-dev hwdata patchelf \
libwayland-dev wayland-protocols libdrm-dev libxkbcommon-dev xkb-data libpixman-1-dev \
libdisplay-info-dev libegl-dev libgles-dev libgbm-dev libinput-dev libseat-dev libudev-dev liblcms2-dev \
@@ -265,7 +265,7 @@ case "$FAMILY" in
freetype-devel harfbuzz-devel fontconfig-devel librsvg2-devel cairo-devel pango-devel libinput-devel \
libarchive-devel libwebp-devel libpng-devel libjpeg-turbo-devel pulseaudio-libs-devel pipewire-devel pam-devel cups-devel poppler-glib-devel libseccomp-devel \
mesa-libEGL-devel mesa-libGLES-devel glibc-devel readline-devel gcc-c++ json-glib-devel \
- pkgconf-pkg-config git python3 rb_libtorrent-devel \
+ pkgconf-pkg-config git rb_libtorrent-devel \
xorg-x11-server-Xwayland \
xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk"
if [ "$PRIVATE_WLROOTS" = no ]; then
@@ -282,7 +282,7 @@ case "$FAMILY" in
freetype2-devel harfbuzz-devel fontconfig-devel librsvg-devel cairo-devel pango-devel libinput-devel \
libarchive-devel libwebp-devel libpng16-devel libjpeg8-devel libpulse-devel pipewire-devel pam-devel cups-devel libpoppler-glib-devel libseccomp-devel \
Mesa-libEGL-devel Mesa-libGLESv2-devel glibc-devel readline-devel gcc-c++ json-glib-devel \
- pkg-config git python3 libtorrent-rasterbar-devel \
+ pkg-config git libtorrent-rasterbar-devel \
xwayland \
xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk"
;;
@@ -291,7 +291,7 @@ case "$FAMILY" in
media-libs/freetype media-libs/harfbuzz media-libs/fontconfig gnome-base/librsvg x11-libs/cairo x11-libs/pango dev-libs/libinput \
app-arch/libarchive media-libs/libwebp media-libs/libpng media-libs/libjpeg-turbo media-libs/libpulse media-video/pipewire sys-libs/pam net-print/cups \
media-libs/mesa sys-libs/readline net-libs/libtorrent-rasterbar dev-libs/json-glib sys-devel/gcc \
- virtual/pkgconfig dev-vcs/git dev-lang/python \
+ virtual/pkgconfig dev-vcs/git \
x11-base/xwayland \
sys-apps/xdg-desktop-portal gui-libs/xdg-desktop-portal-wlr sys-apps/xdg-desktop-portal-gtk"
;;
diff --git a/scripts/release-build.sh b/scripts/release-build.sh
index a23d942..041f970 100644
--- a/scripts/release-build.sh
+++ b/scripts/release-build.sh
@@ -23,11 +23,11 @@ case "$family" in
# A container image is a snapshot: refresh it so the release links
# what rolling users have today.
pacman -Syu --noconfirm
- extra="xorg-xwayland xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk python mesa squashfs-tools"
+ extra="xorg-xwayland xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk mesa squashfs-tools"
owner() { pacman -Qqo "$1" 2>/dev/null; }
;;
debian|ubuntu)
- extra="xwayland xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk python3 xkb-data libgl1-mesa-dri libegl-mesa0 squashfs-tools"
+ extra="xwayland xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk xkb-data libgl1-mesa-dri libegl-mesa0 squashfs-tools"
# A diverted file (usr-merge) prints "diversion by PKG from: ..." lines
# first; skip them, and keep only the first package of a shared path.
owner() {
@@ -38,7 +38,7 @@ case "$family" in
}
;;
fedora)
- extra="xorg-x11-server-Xwayland xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk python3 mesa-dri-drivers squashfs-tools"
+ extra="xorg-x11-server-Xwayland xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk mesa-dri-drivers squashfs-tools"
owner() { rpm -qf --qf '%{NAME}\n' "$1" 2>/dev/null | head -n 1; }
;;
*) die "unknown family '$family' (arch, debian, ubuntu, fedora)" ;;
@@ -63,7 +63,7 @@ jobs=${ZIG_JOBS:-$((cores > 2 ? cores - 2 : 1))}
log "Building RediWM (ReleaseSafe, x86_64_v2)"
release="$src/zig-out/release-safe"
rm -rf -- "$release"
-zig build -Doptimize=ReleaseSafe -Dcpu=x86_64_v2 -j"$jobs" --prefix "$release" -Dwlroots-prefix="$wlroots"
+sh scripts/with-wlroots.sh "$wlroots" zig build -Doptimize=ReleaseSafe -Dcpu=x86_64_v2 -j"$jobs" --prefix "$release" -Dwlroots-prefix="$wlroots"
# Linking the private wlroots left its build-machine prefix in rediwm's RUNPATH
# (after $ORIGIN/../lib/rediwm, which is all an installed copy needs). A path
@@ -83,7 +83,7 @@ mkdir -p "$stage/zig-out" "$stage/scripts"
cp -a "$release" "$stage/zig-out/release-safe"
cp -a data "$stage/data"
rm -rf -- "$stage/data/__pycache__"
-for f in install-session.sh install-session-root.sh restart-session.py; do
+for f in install-session.sh install-session-root.sh; do
cp "scripts/$f" "$stage/scripts/$f"
done
echo "$version ${REDIWM_REVISION:-unknown}" > "$stage/VERSION"
diff --git a/scripts/restart-session.py b/scripts/restart-session.py
deleted file mode 100644
index 468d29d..0000000
--- a/scripts/restart-session.py
+++ /dev/null
@@ -1,106 +0,0 @@
-#!/usr/bin/env python3
-"""Restart only this user's installed RediWM, never a development/nested instance."""
-import json
-import os
-from pathlib import Path
-import signal
-import socket
-import struct
-import sys
-import time
-
-INSTALLED = Path('/usr/local/bin/rediwm')
-
-
-def connect(path):
- sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- sock.settimeout(3)
- try:
- sock.connect(str(path))
- pid, uid, _ = struct.unpack('3i', sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
- executable = os.readlink(f'/proc/{pid}/exe').removesuffix(' (deleted)')
- if uid != os.getuid() or executable != str(INSTALLED):
- raise ValueError('not this user\'s installed compositor')
- return sock, pid
- except BaseException:
- sock.close()
- raise
-
-
-def request(sock, value):
- sock.sendall(json.dumps(value).encode() + b'\n')
- data = b''
- while b'\n' not in data:
- chunk = sock.recv(65536)
- if not chunk:
- raise ConnectionError('compositor disconnected')
- data += chunk
- return json.loads(data.split(b'\n', 1)[0])
-
-
-def main():
- runtime = Path(os.environ.get('XDG_RUNTIME_DIR', f'/run/user/{os.getuid()}'))
- explicit = os.environ.get('REDIWM_SOCKET')
- display = os.environ.get('WAYLAND_DISPLAY')
- if explicit:
- paths = [Path(explicit)]
- elif display:
- paths = [runtime / f'rediwm-{display}.sock']
- else:
- paths = sorted(runtime.glob('rediwm-*.sock'))
- sessions = []
- for path in paths:
- try:
- sock, pid = connect(path)
- sessions.append((path, sock, pid))
- except (OSError, ValueError):
- continue
- if not sessions:
- print('Installed ReleaseSafe. No installed RediWM session found; select RediWM at login.')
- return
- if len(sessions) != 1:
- for _, sock, _ in sessions:
- sock.close()
- raise RuntimeError('Multiple installed sessions found; set REDIWM_SOCKET to choose one.')
- path, sock, pid = sessions[0]
- with sock:
- # Probe before sending: old versions cannot acquire new restart support
- # merely by replacing their executable on disk.
- capabilities = request(sock, {'query': 'Capabilities'})
- if 'Err' in capabilities:
- raise RuntimeError(f'Cannot inspect session: {capabilities["Err"]}')
- if 'RestartShell' not in capabilities.get('Ok', {}).get('Capabilities', []):
- print('Installed ReleaseSafe. This running version lacks clean restart support. '
- 'Log out and back in once; subsequent installs restart automatically.')
- return
- print('Restarting RediWM; connected applications will close.', flush=True)
- signal.signal(signal.SIGHUP, signal.SIG_IGN)
- try:
- reply = request(sock, {"action": "RestartShell"})
- if "Err" in reply:
- raise RuntimeError(f"Restart rejected: {reply['Err']}")
- except (ConnectionError, socket.timeout):
- pass # Shutdown can close IPC before its buffered reply is flushed.
- expected = INSTALLED.stat()
- deadline = time.monotonic() + 20
- while time.monotonic() < deadline:
- try:
- current = Path(f'/proc/{pid}/exe').stat()
- if (current.st_dev, current.st_ino) == (expected.st_dev, expected.st_ino):
- ready, ready_pid = connect(path)
- with ready:
- if ready_pid == pid and request(ready, {'query': 'Version'}).get('Ok') is not None:
- print('ReleaseSafe restarted successfully.')
- return
- except (OSError, ValueError, ConnectionError):
- pass
- time.sleep(0.2)
- raise RuntimeError('Restart did not become ready within 20 seconds; check the RediWM session log.')
-
-
-if __name__ == '__main__':
- try:
- main()
- except (OSError, ValueError, RuntimeError) as error:
- print(f'Installed, but restart failed: {error}', file=sys.stderr)
- sys.exit(1)
diff --git a/scripts/with-wlroots.sh b/scripts/with-wlroots.sh
new file mode 100755
index 0000000..e72d02a
--- /dev/null
+++ b/scripts/with-wlroots.sh
@@ -0,0 +1,17 @@
+#!/bin/sh
+# Runs a command with the private wlroots prefix from scripts/build-wlroots.sh
+# on its pkg-config and library paths. Zig 0.17 runs pkg-config and the tests
+# in the environment `zig build` was started with, so build.zig can no longer
+# set these for `-Dwlroots-prefix`:
+#
+# scripts/with-wlroots.sh PREFIX zig build -Dwlroots-prefix=PREFIX ...
+set -eu
+
+prefix=$1
+shift
+PKG_CONFIG_PATH="$prefix/lib/pkgconfig:$prefix/share/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}"
+# Tests and `zig build run` execute from the cache, where the installed
+# RUNPATH doesn't reach lib/rediwm.
+LD_LIBRARY_PATH="$prefix/runtime${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
+export PKG_CONFIG_PATH LD_LIBRARY_PATH
+exec "$@"
diff --git a/scripts/zig-bootstrap.sh b/scripts/zig-bootstrap.sh
index 81d8731..7911f1f 100644
--- a/scripts/zig-bootstrap.sh
+++ b/scripts/zig-bootstrap.sh
@@ -46,15 +46,18 @@ target="$zig_arch-linux"
mkdir -p "$ZIG_ROOT"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
-if command -v python3 >/dev/null 2>&1; then
- curl -fsSL https://ziglang.org/download/index.json -o "$tmp/index.json" >&2
- tarball=$(python3 -c "import json;print(json.load(open('$tmp/index.json'))['$ZIG_PIN']['$target']['tarball'])")
- shasum=$(python3 -c "import json;print(json.load(open('$tmp/index.json'))['$ZIG_PIN']['$target']['shasum'])")
-else
- log "python3 not found; guessing the tarball URL and skipping checksum verification"
- tarball="https://ziglang.org/download/$ZIG_PIN/zig-$target-$ZIG_PIN.tar.xz"
- shasum=""
-fi
+curl -fsSL https://ziglang.org/download/index.json -o "$tmp/index.json" >&2
+# index.json is pretty-printed: "<version>": { ... "<target>": { "tarball": ..., "shasum": ... } }
+field() {
+ awk -v ver="\"$ZIG_PIN\"" -v tgt="\"$target\"" -v key="\"$1\"" '
+ /^ "/ { in_ver = ($1 == ver ":") }
+ in_ver && $1 == tgt ":" { in_tgt = 1; next }
+ in_ver && in_tgt && $1 == key ":" { gsub(/[",]/, "", $2); print $2; exit }
+ in_tgt && /}/ { in_tgt = 0 }' "$tmp/index.json"
+}
+tarball=$(field tarball)
+shasum=$(field shasum)
+[ -n "$tarball" ] && [ -n "$shasum" ] || die "zig $ZIG_PIN for $target is not listed in ziglang.org's index.json"
log "Downloading $tarball"
curl -fsSL "$tarball" -o "$tmp/zig.tar.xz" >&2
if [ -n "$shasum" ]; then
diff --git a/src/Keyboard.zig b/src/Keyboard.zig
index aab6d0c..a935c17 100644
--- a/src/Keyboard.zig
+++ b/src/Keyboard.zig
@@ -160,8 +160,9 @@ pub fn switchVt(keyboard: *Keyboard, syms: []const xkb.Keysym) bool {
const session = keyboard.server.session orelse return false;
for (syms) |sym| {
const value = @intFromEnum(sym);
- if (value < xkb.Keysym.XF86Switch_VT_1 or value > xkb.Keysym.XF86Switch_VT_12) continue;
- session.changeVt(value - xkb.Keysym.XF86Switch_VT_1 + 1) catch log.warn("could not switch to VT {d}", .{value - xkb.Keysym.XF86Switch_VT_1 + 1});
+ const first = @intFromEnum(xkb.Keysym.XF86Switch_VT_1);
+ if (value < first or value > @intFromEnum(xkb.Keysym.XF86Switch_VT_12)) continue;
+ session.changeVt(value - first + 1) catch log.warn("could not switch to VT {d}", .{value - first + 1});
return true;
}
return false;
diff --git a/src/Server.zig b/src/Server.zig
index b914293..c8e285c 100644
--- a/src/Server.zig
+++ b/src/Server.zig
@@ -1013,7 +1013,7 @@ pub const IconNameCache = struct {
filled: bool = false,
};
- entries: [capacity]Entry = [_]Entry{.{}} ** capacity,
+ entries: [capacity]Entry = @splat(.{}),
generation: u64 = 0,
primed: bool = false,
diff --git a/src/Taskbar.zig b/src/Taskbar.zig
index e718980..974f605 100644
--- a/src/Taskbar.zig
+++ b/src/Taskbar.zig
@@ -188,8 +188,8 @@ network_presence: taskbar_items.Presence = .{},
blink_timer: ?*wl.EventSource = null,
blink_dim: bool = false,
-clock_time: [16]u8 = [_]u8{0} ** 16,
-clock_date: [128]u8 = [_]u8{0} ** 128,
+clock_time: [16]u8 = @splat(0),
+clock_date: [128]u8 = @splat(0),
clock_locale: c_time.locale_t = null,
clock_minute: c_time.time_t = 0,
// Layout and every tick ask for these; shaping them each time showed up in
@@ -215,7 +215,7 @@ pub const ChipFlat = taskbar_types.ChipFlat;
// `wired` comes last so the IPC tray indices of the other icons stay put.
pub const TrayKind = enum { volume, wifi, power, wired };
-pub const tray_count = std.meta.fields(TrayKind).len;
+pub const tray_count = @typeInfo(TrayKind).@"enum".field_names.len;
pub const AppKind = enum { file_explorer, notes, terminal, settings, text_doc, browser, other };
diff --git a/src/Toplevel.zig b/src/Toplevel.zig
index 4b60ae7..bbfcf14 100644
--- a/src/Toplevel.zig
+++ b/src/Toplevel.zig
@@ -298,7 +298,7 @@ rules_resolved: bool = false,
resolved_before_app_id: bool = false,
open_rules: window_rules.OpenRules = .{},
live_rules: window_rules.LiveRules = .{},
-matched_rules: std.StaticBitSet(window_rules.max_rules) = std.StaticBitSet(window_rules.max_rules).initEmpty(),
+matched_rules: std.StaticBitSet(window_rules.max_rules) = std.StaticBitSet(window_rules.max_rules).empty,
maximize_restore: ?RestoreGeometry = null,
fullscreen_restore: ?RestoreGeometry = null,
maximize_target: ?RestoreGeometry = null,
diff --git a/src/accounts/model.zig b/src/accounts/model.zig
index 06b44e4..8d598cf 100644
--- a/src/accounts/model.zig
+++ b/src/accounts/model.zig
@@ -1,11 +1,7 @@
//! Unprivileged view of login -- accounts and local groups for Settings.
const std = @import("std");
const ws = @import("../session/wayland_sessions.zig");
-const c = @cImport({
- @cInclude("pwd.h");
- @cInclude("grp.h");
- @cInclude("unistd.h");
-});
+const c = @import("c");
pub const User = struct {
name: []const u8,
diff --git a/src/accounts_helper/main.zig b/src/accounts_helper/main.zig
index 12e966d..b98e048 100644
--- a/src/accounts_helper/main.zig
+++ b/src/accounts_helper/main.zig
@@ -4,19 +4,7 @@ const std = @import("std");
const validation = @import("accounts_validation");
const dm_config = @import("dm_config");
const ws = @import("wayland_sessions");
-const c = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- @cDefine("_GNU_SOURCE", "1");
- @cInclude("pwd.h");
- @cInclude("grp.h");
- @cInclude("unistd.h");
- @cInclude("sys/mman.h");
- @cInclude("sys/stat.h");
- @cInclude("fcntl.h");
- @cInclude("errno.h");
- @cInclude("stdio.h");
- @cInclude("stdlib.h");
-});
+const c = @import("c");
const Request = struct {
op: []const u8,
@@ -159,7 +147,7 @@ fn perform(io: std.Io, caller_uid: u32, request: Request) !void {
}
fn lookupUser(name: []const u8) ?struct { uid: u32, gid: u32 } {
- const z = a.dupeZ(u8, name) catch return null;
+ const z = a.dupeSentinel(u8, name, 0) catch return null;
defer a.free(z);
const pw = c.getpwnam(z);
if (pw == null) return null;
@@ -194,7 +182,7 @@ fn adminGroup() ?[]const u8 {
const GroupInfo = struct { gid: u32, members: [*c][*c]u8 };
fn lookupGroup(name: []const u8) ?GroupInfo {
- const z = a.dupeZ(u8, name) catch return null;
+ const z = a.dupeSentinel(u8, name, 0) catch return null;
defer a.free(z);
const group = c.getgrnam(z) orelse return null;
return .{ .gid = group.*.gr_gid, .members = group.*.gr_mem };
@@ -336,7 +324,7 @@ fn localGroup(name: []const u8) bool {
fn findTool(paths: []const []const u8) ![]const u8 {
for (paths) |path| {
- const z = try a.dupeZ(u8, path);
+ const z = try a.dupeSentinel(u8, path, 0);
defer a.free(z);
if (c.access(z, c.X_OK) == 0) return path;
}
diff --git a/src/audio/pipewire.zig b/src/audio/pipewire.zig
index c838f79..fb0931a 100644
--- a/src/audio/pipewire.zig
+++ b/src/audio/pipewire.zig
@@ -24,10 +24,7 @@
const std = @import("std");
const Allocator = std.mem.Allocator;
-const pa = @cImport({
- @cInclude("pulse/pulseaudio.h");
- @cInclude("pulse/rtclock.h");
-});
+const pa = @import("c_pulse");
const log = std.log.scoped(.audio);
const Bass = opaque {};
@@ -562,7 +559,7 @@ pub const AudioManager = struct {
pub fn setDefaultSink(self: *AudioManager, name: []const u8) void {
var buf: [256]u8 = undefined;
- const name_z = std.fmt.bufPrintZ(&buf, "{s}", .{name}) catch return;
+ const name_z = std.fmt.bufPrintSentinel(&buf, "{s}", .{name}, 0) catch return;
self.lock();
defer self.unlock();
if (pa.pa_context_set_default_sink(self.context, name_z, null, null)) |op| pa.pa_operation_unref(op);
@@ -570,7 +567,7 @@ pub const AudioManager = struct {
pub fn setDefaultSource(self: *AudioManager, name: []const u8) void {
var buf: [256]u8 = undefined;
- const name_z = std.fmt.bufPrintZ(&buf, "{s}", .{name}) catch return;
+ const name_z = std.fmt.bufPrintSentinel(&buf, "{s}", .{name}, 0) catch return;
self.lock();
defer self.unlock();
if (pa.pa_context_set_default_source(self.context, name_z, null, null)) |op| pa.pa_operation_unref(op);
diff --git a/src/brightness.zig b/src/brightness.zig
index 57a23f3..2720a70 100644
--- a/src/brightness.zig
+++ b/src/brightness.zig
@@ -4,10 +4,7 @@ const std = @import("std");
const wl = @import("wayland").server.wl;
const Child = @import("session/child.zig");
const Server = @import("Server.zig");
-const c = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- @cInclude("fcntl.h");
-});
+const c = @import("c");
const Brightness = @This();
child: ?std.process.Child = null,
timer: ?*wl.EventSource = null,
diff --git a/src/c/archive.h b/src/c/archive.h
new file mode 100644
index 0000000..8b7219c
--- /dev/null
+++ b/src/c/archive.h
@@ -0,0 +1,3 @@
+/* `c_archive`: Files' archive browsing and extraction. */
+#include <archive.h>
+#include <archive_entry.h>
diff --git a/src/c/gfx.h b/src/c/gfx.h
new file mode 100644
index 0000000..059d98b
--- /dev/null
+++ b/src/c/gfx.h
@@ -0,0 +1,16 @@
+/* libc plus the drawing and keyboard stack (`c_gfx`): what ui/ and the app
+ * clients share, so a cairo_t or xkb_state means one type across them. */
+#include "libc.h"
+
+#include <cairo.h>
+#include <cairo-pdf.h>
+#include <fontconfig/fontconfig.h>
+#include <ft2build.h>
+#include <freetype/freetype.h>
+#include <freetype/ftmm.h>
+#include <freetype/ftsizes.h>
+#include <hb.h>
+#include <hb-ft.h>
+#include <xkbcommon/xkbcommon.h>
+#include <xkbcommon/xkbcommon-compose.h>
+#include <xkbcommon/xkbcommon-keysyms.h>
diff --git a/src/c/libc.h b/src/c/libc.h
new file mode 100644
index 0000000..1bf6b97
--- /dev/null
+++ b/src/c/libc.h
@@ -0,0 +1,37 @@
+/* The libc and Linux headers Zig code uses, translated once into the `c`
+ * module (build/support.zig). Zig 0.17 has no @cImport.
+ *
+ * Translate libc declarations, not glibc's fortified inline wrappers: Zig
+ * rejects their attribute(error) calls in ReleaseSafe. This affects the
+ * translation only; Zig runtime safety and separately compiled C stay on. */
+#undef _FORTIFY_SOURCE
+#define _GNU_SOURCE 1
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <fnmatch.h>
+#include <grp.h>
+#include <langinfo.h>
+#include <linux/netlink.h>
+#include <locale.h>
+#include <monetary.h>
+#include <poll.h>
+#include <pthread.h>
+#include <pwd.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/eventfd.h>
+#include <sys/file.h>
+#include <sys/inotify.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/prctl.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/un.h>
+#include <termios.h>
+#include <time.h>
+#include <unistd.h>
diff --git a/src/c/libinput.h b/src/c/libinput.h
new file mode 100644
index 0000000..4f1187e
--- /dev/null
+++ b/src/c/libinput.h
@@ -0,0 +1,2 @@
+/* `c_libinput`: device configuration for the Input settings. */
+#include <libinput.h>
diff --git a/src/c/png.h b/src/c/png.h
new file mode 100644
index 0000000..77f7ddb
--- /dev/null
+++ b/src/c/png.h
@@ -0,0 +1,2 @@
+/* `c_png`: screenshot encoding. */
+#include <png.h>
diff --git a/src/c/pulse.h b/src/c/pulse.h
new file mode 100644
index 0000000..8ab22de
--- /dev/null
+++ b/src/c/pulse.h
@@ -0,0 +1,3 @@
+/* PipeWire's PulseAudio-compat client API (`c_pulse`, audio/pipewire.zig). */
+#include <pulse/pulseaudio.h>
+#include <pulse/rtclock.h>
diff --git a/src/calculator/client.zig b/src/calculator/client.zig
index 882bada..f6a6a78 100644
--- a/src/calculator/client.zig
+++ b/src/calculator/client.zig
@@ -836,7 +836,7 @@ pub fn run(init: std.process.Init) !void {
self.surface.commit();
if (self.activation) |activation| {
if (init.minimal.environ.getPosix("XDG_ACTIVATION_TOKEN")) |token| {
- const terminated = try a.dupeZ(u8, token);
+ const terminated = try a.dupeSentinel(u8, token, 0);
defer a.free(terminated);
activation.activate(terminated, self.surface);
}
diff --git a/src/calendar.zig b/src/calendar.zig
index be4cae8..7f9df40 100644
--- a/src/calendar.zig
+++ b/src/calendar.zig
@@ -4,11 +4,7 @@ const std = @import("std");
const wlr = @import("wlroots");
const sn = @import("node.zig");
const i18n = @import("i18n");
-const c = @cImport({
- @cInclude("langinfo.h");
- @cInclude("locale.h");
- @cInclude("time.h");
-});
+const c = @import("c");
const Output = @import("Output.zig");
const gpa = @import("main.zig").gpa;
const PanelBuffer = @import("panel_buffer.zig").PanelBuffer;
@@ -195,7 +191,7 @@ fn localNow() c.struct_tm {
return tm;
}
fn timeLocale(allocator: std.mem.Allocator, name: []const u8) c.locale_t {
- const terminated = allocator.dupeZ(u8, name) catch return null;
+ const terminated = allocator.dupeSentinel(u8, name, 0) catch return null;
defer allocator.free(terminated);
// Locale objects are private to this paint. Reloading formats updates an
// already-open calendar without changing libc's process-wide locale.
diff --git a/src/child_set.zig b/src/child_set.zig
index d2b70f7..b43a390 100644
--- a/src/child_set.zig
+++ b/src/child_set.zig
@@ -36,7 +36,7 @@ pub fn next(self: *Set) ?Exit {
_ = self.entries.swapRemove(i);
var status: u32 = 0;
while (true) {
- const result = linux.wait4(entry.pid, &status, linux.W.NOHANG, null);
+ const result = linux.wait4(entry.pid, @ptrCast(&status), linux.W.NOHANG, null);
switch (linux.errno(result)) {
.INTR => continue,
.SUCCESS => return .{ .pid = entry.pid, .status = if (result == entry.pid) status else null },
diff --git a/src/config/keybinds.zig b/src/config/keybinds.zig
index f7f4df9..31dfd5d 100644
--- a/src/config/keybinds.zig
+++ b/src/config/keybinds.zig
@@ -134,31 +134,31 @@ pub fn parseAction(str: []const u8, allocator: Allocator) !Action {
return .poweroff;
}
- inline for (std.meta.fields(Action)) |field| {
- if (std.mem.eql(u8, name, field.name)) {
- return switch (field.type) {
+ inline for (@typeInfo(Action).@"union".field_names) |field_name| {
+ if (std.mem.eql(u8, name, field_name)) {
+ return switch (@FieldType(Action, field_name)) {
void => blk: {
if (arg.len != 0) {
log.warn("unknown action string: '{s}'", .{trimmed});
return error.UnknownAction;
}
- break :blk @unionInit(Action, field.name, {});
+ break :blk @unionInit(Action, field_name, {});
},
[]const u8 => blk: {
if (arg.len == 0) {
- log.warn(field.name ++ " requires " ++ argumentHelp(field.name, "an argument"), .{});
+ log.warn(field_name ++ " requires " ++ argumentHelp(field_name, "an argument"), .{});
return error.UnknownAction;
}
- break :blk @unionInit(Action, field.name, try allocator.dupe(u8, arg));
+ break :blk @unionInit(Action, field_name, try allocator.dupe(u8, arg));
},
u8 => blk: {
const n = std.fmt.parseInt(u8, arg, 10) catch {
- log.warn(field.name ++ " requires " ++ argumentHelp(field.name, "an integer 0-255") ++ ", got '{s}'", .{arg});
+ log.warn(field_name ++ " requires " ++ argumentHelp(field_name, "an integer 0-255") ++ ", got '{s}'", .{arg});
return error.UnknownAction;
};
- break :blk @unionInit(Action, field.name, n);
+ break :blk @unionInit(Action, field_name, n);
},
- else => @compileError("no action parser for " ++ field.name ++ ": " ++ @typeName(field.type)),
+ else => @compileError("no action parser for " ++ field_name ++ ": " ++ @typeName(@FieldType(Action, field_name))),
};
}
}
@@ -241,11 +241,10 @@ pub fn relevantMods(mods: anytype) ModifierMask {
pub fn normalizeSym(sym: xkb.Keysym) xkb.Keysym {
const lower = xkb.Keysym.toLower(sym);
- const raw = @intFromEnum(lower);
- if (raw == xkb.Keysym.plus) return @enumFromInt(xkb.Keysym.equal);
- if (raw == xkb.Keysym.underscore) return @enumFromInt(xkb.Keysym.minus);
- if (raw == xkb.Keysym.ISO_Left_Tab) return @enumFromInt(xkb.Keysym.Tab);
- if (raw == xkb.Keysym.Sys_Req) return @enumFromInt(xkb.Keysym.Print);
+ if (lower == xkb.Keysym.plus) return xkb.Keysym.equal;
+ if (lower == xkb.Keysym.underscore) return xkb.Keysym.minus;
+ if (lower == xkb.Keysym.ISO_Left_Tab) return xkb.Keysym.Tab;
+ if (lower == xkb.Keysym.Sys_Req) return xkb.Keysym.Print;
return lower;
}
@@ -263,13 +262,13 @@ fn argumentHelp(comptime name: []const u8, comptime fallback: []const u8) []cons
pub fn actionEql(a: Action, b: Action) bool {
if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false;
- inline for (std.meta.fields(Action)) |field| {
- if (std.meta.activeTag(a) == @field(std.meta.Tag(Action), field.name)) {
- return switch (field.type) {
+ inline for (@typeInfo(Action).@"union".field_names) |field_name| {
+ if (std.meta.activeTag(a) == @field(std.meta.Tag(Action), field_name)) {
+ return switch (@FieldType(Action, field_name)) {
void => true,
- []const u8 => std.mem.eql(u8, @field(a, field.name), @field(b, field.name)),
- u8 => @field(a, field.name) == @field(b, field.name),
- else => @compileError("no action equality for " ++ field.name),
+ []const u8 => std.mem.eql(u8, @field(a, field_name), @field(b, field_name)),
+ u8 => @field(a, field_name) == @field(b, field_name),
+ else => @compileError("no action equality for " ++ field_name),
};
}
}
@@ -277,13 +276,13 @@ pub fn actionEql(a: Action, b: Action) bool {
}
pub fn describeAction(action: Action, buf: []u8) []const u8 {
- inline for (std.meta.fields(Action)) |field| {
- if (std.meta.activeTag(action) == @field(std.meta.Tag(Action), field.name)) {
- return switch (field.type) {
- void => field.name,
- []const u8 => std.fmt.bufPrint(buf, field.name ++ " {s}", .{@field(action, field.name)}) catch field.name,
- u8 => std.fmt.bufPrint(buf, field.name ++ " {d}", .{@field(action, field.name)}) catch field.name,
- else => @compileError("no action description for " ++ field.name),
+ inline for (@typeInfo(Action).@"union".field_names) |field_name| {
+ if (std.meta.activeTag(action) == @field(std.meta.Tag(Action), field_name)) {
+ return switch (@FieldType(Action, field_name)) {
+ void => field_name,
+ []const u8 => std.fmt.bufPrint(buf, field_name ++ " {s}", .{@field(action, field_name)}) catch field_name,
+ u8 => std.fmt.bufPrint(buf, field_name ++ " {d}", .{@field(action, field_name)}) catch field_name,
+ else => @compileError("no action description for " ++ field_name),
};
}
}
@@ -333,48 +332,48 @@ test "parseKeybind maps modifiers and is case insensitive" {
const a = try parseKeybind("super+t");
try std.testing.expect(a.modifiers.logo);
try std.testing.expect(!a.modifiers.shift);
- try std.testing.expectEqual(@as(u32, xkb.Keysym.t), @intFromEnum(a.sym));
+ try std.testing.expectEqual(@intFromEnum(xkb.Keysym.t), @intFromEnum(a.sym));
const b = try parseKeybind("SUPER+SHIFT+S");
try std.testing.expect(b.modifiers.logo and b.modifiers.shift);
- try std.testing.expectEqual(@as(u32, xkb.Keysym.s), @intFromEnum(b.sym));
+ try std.testing.expectEqual(@intFromEnum(xkb.Keysym.s), @intFromEnum(b.sym));
const c = try parseKeybind("alt+tab");
try std.testing.expect(c.modifiers.alt);
- try std.testing.expectEqual(@as(u32, xkb.Keysym.Tab), @intFromEnum(c.sym));
+ try std.testing.expectEqual(@intFromEnum(xkb.Keysym.Tab), @intFromEnum(c.sym));
const d = try parseKeybind("ctrl+alt+delete");
try std.testing.expect(d.modifiers.ctrl and d.modifiers.alt);
- try std.testing.expectEqual(@as(u32, xkb.Keysym.Delete), @intFromEnum(d.sym));
+ try std.testing.expectEqual(@intFromEnum(xkb.Keysym.Delete), @intFromEnum(d.sym));
const e = try parseKeybind("mod+F1");
try std.testing.expect(e.modifiers.logo);
- try std.testing.expectEqual(@as(u32, xkb.Keysym.F1), @intFromEnum(e.sym));
+ try std.testing.expectEqual(@intFromEnum(xkb.Keysym.F1), @intFromEnum(e.sym));
try std.testing.expectError(error.InvalidKeybind, parseKeybind("super+notakey"));
try std.testing.expectError(error.InvalidKeybind, parseKeybind("hyper+t"));
}
test "every action round trips and compares its payload" {
- inline for (std.meta.fields(Action)) |field| {
- const original = @unionInit(Action, field.name, switch (field.type) {
+ inline for (@typeInfo(Action).@"union".field_names) |field_name| {
+ const original = @unionInit(Action, field_name, switch (@FieldType(Action, field_name)) {
void => {},
[]const u8 => "example with spaces",
u8 => 4,
- else => @compileError("add an action fixture for " ++ field.name),
+ else => @compileError("add an action fixture for " ++ field_name),
});
var buf: [128]u8 = undefined;
const parsed = try parseAction(describeAction(original, &buf), std.testing.allocator);
- defer if (field.type == []const u8) std.testing.allocator.free(@field(parsed, field.name));
+ defer if (@FieldType(Action, field_name) == []const u8) std.testing.allocator.free(@field(parsed, field_name));
try std.testing.expect(actionEql(original, parsed));
var short: [0]u8 = .{};
- try std.testing.expectEqualStrings(field.name, describeAction(original, &short));
- if (field.type != void) {
- const different = @unionInit(Action, field.name, if (field.type == u8) 3 else "different");
+ try std.testing.expectEqualStrings(field_name, describeAction(original, &short));
+ if (@FieldType(Action, field_name) != void) {
+ const different = @unionInit(Action, field_name, if (@FieldType(Action, field_name) == u8) 3 else "different");
try std.testing.expect(!actionEql(original, different));
- try std.testing.expectError(error.UnknownAction, parseAction(field.name, std.testing.allocator));
+ try std.testing.expectError(error.UnknownAction, parseAction(field_name, std.testing.allocator));
} else {
- try std.testing.expectError(error.UnknownAction, parseAction(field.name ++ " extra", std.testing.allocator));
+ try std.testing.expectError(error.UnknownAction, parseAction(field_name ++ " extra", std.testing.allocator));
}
}
try std.testing.expect(!actionEql(.close_window, .quit));
diff --git a/src/config/keymap.zig b/src/config/keymap.zig
index 10b3592..a1eb16a 100644
--- a/src/config/keymap.zig
+++ b/src/config/keymap.zig
@@ -21,7 +21,7 @@ pub fn compile(allocator: std.mem.Allocator, cfg: anytype) !*xkb.Keymap {
fn name(a: std.mem.Allocator, value: []const u8) !?[*:0]const u8 {
if (value.len == 0) return null;
if (std.mem.indexOfScalar(u8, value, 0) != null) return error.InvalidKeymap;
- return (try a.dupeZ(u8, value)).ptr;
+ return (try a.dupeSentinel(u8, value, 0)).ptr;
}
/// Preserve an explicitly bound active-layout symbol before trying layout zero.
@@ -113,12 +113,12 @@ test "configured layouts and layout-zero shortcuts preserve active bindings and
defer state.unref();
_ = state.updateMask(0, 0, 0, 0, 0, 1);
const active = state.keyGetSyms(28); // evdev KEY_T + 8
- try std.testing.expectEqual(@as(u32, xkb.Keysym.Cyrillic_ie), @intFromEnum(active[0]));
+ try std.testing.expectEqual(@intFromEnum(xkb.Keysym.Cyrillic_ie), @intFromEnum(active[0]));
const fallback = bindingSyms(&cfg, state, 28, @import("keybinds.zig").ModifierMask{ .logo = true });
- try std.testing.expectEqual(@as(u32, xkb.Keysym.t), @intFromEnum(fallback[0]));
+ try std.testing.expectEqual(@intFromEnum(xkb.Keysym.t), @intFromEnum(fallback[0]));
_ = state.updateMask(1, 0, 0, 0, 0, 1); // Shift
const shifted = bindingSyms(&cfg, state, 28, @import("keybinds.zig").ModifierMask{ .logo = true, .shift = true });
- try std.testing.expectEqual(@as(u32, xkb.Keysym.T), @intFromEnum(shifted[0]));
+ try std.testing.expectEqual(@intFromEnum(xkb.Keysym.T), @intFromEnum(shifted[0]));
var explicit = try loader.parse(std.testing.allocator,
\\[input]
@@ -130,7 +130,7 @@ test "configured layouts and layout-zero shortcuts preserve active bindings and
defer explicit.deinit();
_ = state.updateMask(0, 0, 0, 0, 0, 1);
const preferred = bindingSyms(&explicit, state, 28, @import("keybinds.zig").ModifierMask{ .logo = true });
- try std.testing.expectEqual(@as(u32, xkb.Keysym.Cyrillic_ie), @intFromEnum(preferred[0]));
+ try std.testing.expectEqual(@intFromEnum(xkb.Keysym.Cyrillic_ie), @intFromEnum(preferred[0]));
}
test "invalid layout rejects config and empty layout compiles" {
@@ -161,12 +161,12 @@ test "Cyrillic-only keymaps keep Latin modifier shortcuts and Cyrillic text" {
defer state.unref();
const key = map.keyByName("AD05");
for ([_]ModifierMask{ .{ .logo = true }, .{ .ctrl = true }, .{ .alt = true } }) |mods| {
- try std.testing.expectEqual(@as(u32, xkb.Keysym.t), @intFromEnum(bindingSyms(&cfg, state, key, mods)[0]));
+ try std.testing.expectEqual(@intFromEnum(xkb.Keysym.t), @intFromEnum(bindingSyms(&cfg, state, key, mods)[0]));
}
- try std.testing.expectEqual(@as(u32, xkb.Keysym.Cyrillic_ie), @intFromEnum(state.keyGetSyms(key)[0]));
- try std.testing.expectEqual(@as(u32, xkb.Keysym.Cyrillic_ie), @intFromEnum(bindingSyms(&cfg, state, key, ModifierMask{})[0]));
+ try std.testing.expectEqual(@intFromEnum(xkb.Keysym.Cyrillic_ie), @intFromEnum(state.keyGetSyms(key)[0]));
+ try std.testing.expectEqual(@intFromEnum(xkb.Keysym.Cyrillic_ie), @intFromEnum(bindingSyms(&cfg, state, key, ModifierMask{})[0]));
_ = state.updateMask(1, 0, 0, 0, 0, 0);
- try std.testing.expectEqual(@as(u32, xkb.Keysym.T), @intFromEnum(bindingSyms(&cfg, state, key, ModifierMask{ .logo = true, .shift = true })[0]));
+ try std.testing.expectEqual(@intFromEnum(xkb.Keysym.T), @intFromEnum(bindingSyms(&cfg, state, key, ModifierMask{ .logo = true, .shift = true })[0]));
}
var explicit = try loader.parse(std.testing.allocator,
\\[input]
@@ -178,5 +178,5 @@ test "Cyrillic-only keymaps keep Latin modifier shortcuts and Cyrillic text" {
defer explicit.deinit();
const state = xkb.State.new(explicit.keyboard_keymap.?) orelse return error.InvalidKeymap;
defer state.unref();
- try std.testing.expectEqual(@as(u32, xkb.Keysym.Cyrillic_ie), @intFromEnum(bindingSyms(&explicit, state, 28, ModifierMask{ .logo = true })[0]));
+ try std.testing.expectEqual(@intFromEnum(xkb.Keysym.Cyrillic_ie), @intFromEnum(bindingSyms(&explicit, state, 28, ModifierMask{ .logo = true })[0]));
}
diff --git a/src/config/loader.zig b/src/config/loader.zig
index 8489060..115dc52 100644
--- a/src/config/loader.zig
+++ b/src/config/loader.zig
@@ -393,8 +393,8 @@ pub const Config = struct {
}
pub fn sandboxAllowGroups(self: *const Config, app_id: ?[]const u8, engine: ?[]const u8) sandbox_allow.GroupSet {
- if (app_id == null) return sandbox_allow.GroupSet.initEmpty();
- var set = sandbox_allow.GroupSet.initEmpty();
+ if (app_id == null) return sandbox_allow.GroupSet.empty;
+ var set = sandbox_allow.GroupSet.empty;
for (self.sandbox_allow) |rule| {
if (rule.app_id.len > 0 and std.mem.eql(u8, rule.app_id, app_id.?)) {
if (rule.engine == null or engine == null or std.mem.eql(u8, rule.engine.?, engine.?)) {
diff --git a/src/config/loader_compare.zig b/src/config/loader_compare.zig
index f861179..4c1442d 100644
--- a/src/config/loader_compare.zig
+++ b/src/config/loader_compare.zig
@@ -49,10 +49,10 @@ pub fn wheelAccel(cfg: InputConfig) ui_wheel.Accel {
}
pub fn inputEql(a: InputConfig, b: InputConfig) bool {
- inline for (std.meta.fields(InputConfig)) |field| {
- const left = @field(a, field.name);
- const right = @field(b, field.name);
- switch (field.type) {
+ inline for (@typeInfo(InputConfig).@"struct".field_names) |field_name| {
+ const left = @field(a, field_name);
+ const right = @field(b, field_name);
+ switch (@FieldType(InputConfig, field_name)) {
[]const u8 => if (!std.mem.eql(u8, left, right)) return false,
[]const []const u8 => {
if (left.len != right.len) return false;
@@ -61,17 +61,17 @@ pub fn inputEql(a: InputConfig, b: InputConfig) bool {
bool, u32, f32 => if (left != right) return false,
AccelProfile, PanModifier => if (left != right) return false,
[2]f32 => if (left[0] != right[0] or left[1] != right[1]) return false,
- else => @compileError("no input equality for " ++ field.name),
+ else => @compileError("no input equality for " ++ field_name),
}
}
return true;
}
pub fn themeEql(a: Theme, b: Theme) bool {
- inline for (std.meta.fields(Theme)) |field| {
- const left = @field(a, field.name);
- const right = @field(b, field.name);
- if (field.type == []const u8) {
+ inline for (@typeInfo(Theme).@"struct".field_names) |field_name| {
+ const left = @field(a, field_name);
+ const right = @field(b, field_name);
+ if (@FieldType(Theme, field_name) == []const u8) {
if (!std.mem.eql(u8, left, right)) return false;
} else if (!std.meta.eql(left, right)) return false;
}
diff --git a/src/config/loader_fields.zig b/src/config/loader_fields.zig
index 4f3a492..e9d8cdf 100644
--- a/src/config/loader_fields.zig
+++ b/src/config/loader_fields.zig
@@ -219,40 +219,40 @@ pub fn enumHint(comptime T: type) []const u8 {
}
pub fn fieldHint(comptime T: type, comptime rules: anytype, key: []const u8) []const u8 {
- inline for (std.meta.fields(T)) |field| {
- if (std.mem.eql(u8, key, field.name)) {
- if (comptime @field(rules, field.name) == .enumeration) return comptime enumHint(field.type);
- return comptime ruleHint(@field(rules, field.name));
+ inline for (@typeInfo(T).@"struct".field_names) |field_name| {
+ if (std.mem.eql(u8, key, field_name)) {
+ if (comptime @field(rules, field_name) == .enumeration) return comptime enumHint(@FieldType(T, field_name));
+ return comptime ruleHint(@field(rules, field_name));
}
}
return "valid";
}
pub fn applyField(target: anytype, allocator: Allocator, comptime rules: anytype, key: []const u8, value: []const u8) !bool {
- inline for (std.meta.fields(@TypeOf(target.*))) |field| {
- const rule = comptime @field(rules, field.name);
- if (rule != .derived and std.mem.eql(u8, key, field.name)) {
+ inline for (@typeInfo(@TypeOf(target.*)).@"struct".field_names) |field_name| {
+ const rule = comptime @field(rules, field_name);
+ if (rule != .derived and std.mem.eql(u8, key, field_name)) {
switch (comptime rule) {
- .taskbar_items => @field(target, field.name) = try TaskbarItems.parse(value),
- .boolean => @field(target, field.name) = try parseBool(value),
- .string => @field(target, field.name) = try parseString(allocator, value),
- .string_list => @field(target, field.name) = try window_rules.parseStringOrArray(allocator, value),
- .json_string_list => @field(target, field.name) = try std.json.parseFromSliceLeaky([]const []const u8, allocator, value, .{ .allocate = .alloc_always }),
- .uint => |range| @field(target, field.name) = try parseU32Range(value, range.min, range.max),
- .int => |range| @field(target, field.name) = try parseI32Range(value, range.min, range.max),
- .output_scale => @field(target, field.name) = try parseOutputScale(value),
- .output_transform => @field(target, field.name) = try output_transform.parse(value),
+ .taskbar_items => @field(target, field_name) = try TaskbarItems.parse(value),
+ .boolean => @field(target, field_name) = try parseBool(value),
+ .string => @field(target, field_name) = try parseString(allocator, value),
+ .string_list => @field(target, field_name) = try window_rules.parseStringOrArray(allocator, value),
+ .json_string_list => @field(target, field_name) = try std.json.parseFromSliceLeaky([]const []const u8, allocator, value, .{ .allocate = .alloc_always }),
+ .uint => |range| @field(target, field_name) = try parseU32Range(value, range.min, range.max),
+ .int => |range| @field(target, field_name) = try parseI32Range(value, range.min, range.max),
+ .output_scale => @field(target, field_name) = try parseOutputScale(value),
+ .output_transform => @field(target, field_name) = try output_transform.parse(value),
.float => |range| {
- const Float = if (@typeInfo(field.type) == .optional) @typeInfo(field.type).optional.child else field.type;
+ const Float = if (@typeInfo(@FieldType(@TypeOf(target.*), field_name)) == .optional) @typeInfo(@FieldType(@TypeOf(target.*), field_name)).optional.child else @FieldType(@TypeOf(target.*), field_name);
const v = try std.fmt.parseFloat(Float, value);
if (!std.math.isFinite(v) or v < range.min or v > range.max or
(range.exclusive_min and v == range.min)) return error.InvalidValue;
- @field(target, field.name) = v;
+ @field(target, field_name) = v;
},
.zoom_steps => try parseZoomSteps(target, value),
- .accel_profile => @field(target, field.name) = try parseAccelProfile(value),
- .accel_point => @field(target, field.name) = try parseVec2(value),
- .enumeration => @field(target, field.name) = try parseEnum(field.type, value),
+ .accel_profile => @field(target, field_name) = try parseAccelProfile(value),
+ .accel_point => @field(target, field_name) = try parseVec2(value),
+ .enumeration => @field(target, field_name) = try parseEnum(@FieldType(@TypeOf(target.*), field_name), value),
.derived => unreachable,
}
return true;
diff --git a/src/config/loader_parse.zig b/src/config/loader_parse.zig
index 175f744..459bebd 100644
--- a/src/config/loader_parse.zig
+++ b/src/config/loader_parse.zig
@@ -60,7 +60,7 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Config
var current_sandbox_allow: SandboxAllowRule = .{};
var have_current_sandbox_allow = false;
var section: Section = .none;
- var target_flags: [anim.Target.count]anim_cfg.TargetFlags = [_]anim_cfg.TargetFlags{.{}} ** anim.Target.count;
+ var target_flags: [anim.Target.count]anim_cfg.TargetFlags = @splat(.{});
var line_no: usize = 0;
var lines = std.mem.splitScalar(u8, bytes, '\n');
diff --git a/src/config/loader_sections_tests.zig b/src/config/loader_sections_tests.zig
index 826236f..44ab25f 100644
--- a/src/config/loader_sections_tests.zig
+++ b/src/config/loader_sections_tests.zig
@@ -229,7 +229,7 @@ test "polkit defaults and strict configuration validation" {
defer std.testing.allocator.free(content);
try std.testing.expectError(error.InvalidConfig, parse(std.testing.allocator, content, "polkit-invalid"));
}
- const long_path = "[polkit]\nhelper_socket = \"/" ++ ("a" ** 107) ++ "\"\n";
+ const long_path = "[polkit]\nhelper_socket = \"/" ++ @as([107]u8, @splat('a')) ++ "\"\n";
try std.testing.expectError(error.InvalidConfig, parse(std.testing.allocator, long_path, "polkit-overlong"));
}
diff --git a/src/config/loader_tests.zig b/src/config/loader_tests.zig
index aede052..568b866 100644
--- a/src/config/loader_tests.zig
+++ b/src/config/loader_tests.zig
@@ -248,15 +248,15 @@ test "idle config parsing and validation" {
test "input and theme reload detect every field and compare strings by content" {
const original_theme = Theme{};
- inline for (std.meta.fields(Theme)) |field| {
+ inline for (@typeInfo(Theme).@"struct".field_names) |field_name| {
var changed = original_theme;
- @field(changed, field.name) = switch (field.type) {
- bool => !@field(original_theme, field.name),
- f32 => @field(original_theme, field.name) + 1,
+ @field(changed, field_name) = switch (@FieldType(Theme, field_name)) {
+ bool => !@field(original_theme, field_name),
+ f32 => @field(original_theme, field_name) + 1,
[]const u8 => "another theme",
[4]f32 => .{ 0.1, 0.2, 0.3, 0.4 },
?[4]f32 => .{ 0.1, 0.2, 0.3, 0.4 },
- else => @compileError("add a theme change fixture for " ++ field.name),
+ else => @compileError("add a theme change fixture for " ++ field_name),
};
try std.testing.expect(!themeEql(original_theme, changed));
try std.testing.expect(!themeEql(changed, original_theme));
@@ -266,23 +266,23 @@ test "input and theme reload detect every field and compare strings by content"
defer std.testing.allocator.free(theme_copy.font);
try std.testing.expect(themeEql(original_theme, theme_copy));
const original = InputConfig{};
- inline for (std.meta.fields(InputConfig)) |field| {
+ inline for (@typeInfo(InputConfig).@"struct".field_names) |field_name| {
var changed = original;
- @field(changed, field.name) = switch (field.type) {
- bool => !@field(original, field.name),
- f32, u32 => @field(original, field.name) + 1,
+ @field(changed, field_name) = switch (@FieldType(InputConfig, field_name)) {
+ bool => !@field(original, field_name),
+ f32, u32 => @field(original, field_name) + 1,
[]const u8 => "another theme",
- []const []const u8 => if (@field(original, field.name).len == 0) &.{"another"} else &.{},
- AccelProfile => switch (@field(original, field.name)) {
+ []const []const u8 => if (@field(original, field_name).len == 0) &.{"another"} else &.{},
+ AccelProfile => switch (@field(original, field_name)) {
.bezier => .flat,
.flat => .bezier,
},
- PanModifier => switch (@field(original, field.name)) {
+ PanModifier => switch (@field(original, field_name)) {
.super => .super_alt,
.super_alt => .super,
},
- [2]f32 => .{ @field(original, field.name)[0] + 0.1, @field(original, field.name)[1] + 0.1 },
- else => @compileError("add an input change fixture for " ++ field.name),
+ [2]f32 => .{ @field(original, field_name)[0] + 0.1, @field(original, field_name)[1] + 0.1 },
+ else => @compileError("add an input change fixture for " ++ field_name),
};
try std.testing.expect(!inputEql(original, changed));
try std.testing.expect(!inputEql(changed, original));
diff --git a/src/config/sandbox_allow.zig b/src/config/sandbox_allow.zig
index 3feff56..6510392 100644
--- a/src/config/sandbox_allow.zig
+++ b/src/config/sandbox_allow.zig
@@ -23,7 +23,7 @@ const log = std.log.scoped(.config);
pub const SandboxAllowRule = struct {
app_id: []const u8 = "",
engine: ?[]const u8 = null,
- allow: GroupSet = GroupSet.initEmpty(),
+ allow: GroupSet = GroupSet.empty,
};
pub fn parseGroup(str: []const u8) ?SandboxGroup {
diff --git a/src/config/taskbar_items.zig b/src/config/taskbar_items.zig
index 2027175..093b11a 100644
--- a/src/config/taskbar_items.zig
+++ b/src/config/taskbar_items.zig
@@ -35,7 +35,7 @@ pub const Item = enum {
return item == .wifi or item == .wired;
}
};
-pub const count = std.meta.fields(Item).len;
+pub const count = @typeInfo(Item).@"enum".field_names.len;
/// What the network hardware offers right now; decides automatic items.
pub const Presence = struct {
@@ -143,7 +143,7 @@ pub const Config = struct {
if (raw.len < 2 or raw[0] != '[' or raw[raw.len - 1] != ']') return error.InvalidValue;
var result: Config = .{};
var order: [count]Item = undefined;
- var seen = [_]bool{false} ** count;
+ var seen = @as([count]bool, @splat(false));
var legacy = true;
var tokens = std.mem.splitScalar(u8, raw[1 .. raw.len - 1], ',');
var index: usize = 0;
diff --git a/src/config/window_rules.zig b/src/config/window_rules.zig
index 6c6b6af..45aae3e 100644
--- a/src/config/window_rules.zig
+++ b/src/config/window_rules.zig
@@ -125,7 +125,7 @@ pub const Resolved = struct {
decorations: ?DecorationMode = null,
skip_taskbar: ?bool = null,
floating: ?bool = null,
- matched_rules: std.StaticBitSet(max_rules) = std.StaticBitSet(max_rules).initEmpty(),
+ matched_rules: std.StaticBitSet(max_rules) = std.StaticBitSet(max_rules).empty,
};
pub const OpenRules = struct {
diff --git a/src/config/workspace_layout.zig b/src/config/workspace_layout.zig
index f3d7adb..1baedc4 100644
--- a/src/config/workspace_layout.zig
+++ b/src/config/workspace_layout.zig
@@ -73,7 +73,7 @@ pub fn parse(a: std.mem.Allocator, bytes: []const u8) !std.json.Parsed(Saved) {
if (s.version != 2) return error.UnsupportedLayoutVersion;
if (s.workspaces.len > 32 or s.windows.len > 4096) return error.InvalidLayout;
if (!std.math.isFinite(s.camera.offset_x) or !std.math.isFinite(s.camera.offset_y)) return error.InvalidLayout;
- inline for (std.meta.fields(Bounds)) |f| if (!std.math.isFinite(@field(s.bounds, f.name))) return error.InvalidLayout;
+ inline for (@typeInfo(Bounds).@"struct".field_names) |name| if (!std.math.isFinite(@field(s.bounds, name))) return error.InvalidLayout;
var seen: [32]bool = @splat(false);
for (s.workspaces) |w| {
if (w.id == 0 or w.id > 32 or seen[w.id - 1] or w.nodes.len > 8191) return error.InvalidLayout;
diff --git a/src/config_runtime/region.zig b/src/config_runtime/region.zig
index 7b38fb5..27c3bb2 100644
--- a/src/config_runtime/region.zig
+++ b/src/config_runtime/region.zig
@@ -1,12 +1,6 @@
//! Apply a personal timezone to libc clocks without changing system files.
const std = @import("std");
-const c = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- @cInclude("stdlib.h");
- @cInclude("time.h");
- @cInclude("fcntl.h");
- @cInclude("unistd.h");
-});
+const c = @import("c");
pub fn applyTimezone(allocator: std.mem.Allocator, zone: []const u8, inherited: ?[]const u8) !void {
if (zone.len != 0) {
@@ -23,7 +17,7 @@ pub fn applyTimezone(allocator: std.mem.Allocator, zone: []const u8, inherited:
}
const value = if (zone.len != 0) zone else inherited;
if (value) |name| {
- const z = try allocator.dupeZ(u8, name);
+ const z = try allocator.dupeSentinel(u8, name, 0);
defer allocator.free(z);
if (c.setenv("TZ", z, 1) != 0) return error.OutOfMemory;
} else if (c.unsetenv("TZ") != 0) return error.OutOfMemory;
diff --git a/src/config_runtime/watcher.zig b/src/config_runtime/watcher.zig
index 0621796..e5b0119 100644
--- a/src/config_runtime/watcher.zig
+++ b/src/config_runtime/watcher.zig
@@ -37,7 +37,7 @@ pub fn init(path: []const u8, server: *Server) !ConfigWatcher {
errdefer allocator.free(owned_path);
const dir = std.fs.path.dirname(path) orelse ".";
- const dir_z = try allocator.dupeZ(u8, dir);
+ const dir_z = try allocator.dupeSentinel(u8, dir, 0);
errdefer allocator.free(dir_z);
const fd = std.c.inotify_init1(linux.IN.NONBLOCK | linux.IN.CLOEXEC);
diff --git a/src/control_center/folder_picker.zig b/src/control_center/folder_picker.zig
index 1f2e80b..358aa3b 100644
--- a/src/control_center/folder_picker.zig
+++ b/src/control_center/folder_picker.zig
@@ -6,13 +6,7 @@ const std = @import("std");
const wl = @import("wayland").server.wl;
const Server = @import("../Server.zig");
const chooser = @import("../files/chooser.zig");
-const c = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- @cDefine("_GNU_SOURCE", "1");
- @cInclude("sys/mman.h");
- @cInclude("unistd.h");
- @cInclude("fcntl.h");
-});
+const c = @import("c");
const a = std.heap.c_allocator;
/// A path in JSON; anything larger is not a result.
diff --git a/src/control_center/sections/appearance.zig b/src/control_center/sections/appearance.zig
index 752d622..1e17d04 100644
--- a/src/control_center/sections/appearance.zig
+++ b/src/control_center/sections/appearance.zig
@@ -600,7 +600,7 @@ pub const Row = enum {
taskbar,
start_menu,
};
-pub const row_count = std.meta.fields(Row).len;
+pub const row_count = @typeInfo(Row).@"enum".field_names.len;
pub const groups = [_]struct { title: ?i18n.Message, rows: []const Row }{
.{ .title = i18n.msg("Themes & colours"), .rows = &.{ .theme, .taskbar_theme, .theme_pack, .icon_theme, .dark_mode, .app_colors } },
@@ -615,7 +615,7 @@ pub const groups = [_]struct { title: ?i18n.Message, rows: []const Row }{
comptime {
// Every row is shown exactly once.
- var seen = [_]bool{false} ** row_count;
+ var seen = @as([row_count]bool, @splat(false));
for (groups) |group| for (group.rows) |row| {
if (seen[@intFromEnum(row)]) @compileError("row in two groups: " ++ @tagName(row));
seen[@intFromEnum(row)] = true;
diff --git a/src/control_center/sections/bluetooth.zig b/src/control_center/sections/bluetooth.zig
index 9573a5f..2ddb089 100644
--- a/src/control_center/sections/bluetooth.zig
+++ b/src/control_center/sections/bluetooth.zig
@@ -162,7 +162,7 @@ fn deviceList(s: *Section, cc: *panel.ControlCenter, a: A, enabled: bool) !W {
var count: usize = 0;
if (m) |manager| for (manager.devices[0..manager.count]) |*d| {
if (!eq(u8, d.adapter.slice(), s.adapter_path.slice()) or (!s.nearby and !d.paired)) continue;
- if (s.search_data.?.value.len > 0 and std.ascii.indexOfIgnoreCase(d.title(), s.search_data.?.value) == null and std.ascii.indexOfIgnoreCase(d.address.slice(), s.search_data.?.value) == null) continue;
+ if (s.search_data.?.value.len > 0 and std.ascii.findIgnoreCase(d.title(), s.search_data.?.value) == null and std.ascii.findIgnoreCase(d.address.slice(), s.search_data.?.value) == null) continue;
const selected = eq(u8, d.path.slice(), s.selected.slice());
s.rows[count] = d.path;
const state = if (d.connected) i18n.tr("Connected") else if (d.blocked) i18n.tr("Blocked") else if (d.paired) i18n.tr("Not connected") else i18n.tr("Ready to pair");
diff --git a/src/control_center/sections/default_apps.zig b/src/control_center/sections/default_apps.zig
index e97db58..d47e82e 100644
--- a/src/control_center/sections/default_apps.zig
+++ b/src/control_center/sections/default_apps.zig
@@ -78,7 +78,7 @@ extern fn g_app_info_reset_type_associations(content_type: [*:0]const u8) void;
extern fn g_object_unref(object: *anyopaque) void;
fn setDirectoryDefault(id: []const u8) !void {
- const terminated = try gpa.dupeZ(u8, if (id.len == 0) "rediwm-files.desktop" else id);
+ const terminated = try gpa.dupeSentinel(u8, if (id.len == 0) "rediwm-files.desktop" else id, 0);
defer gpa.free(terminated);
const app = g_desktop_app_info_new(terminated) orelse return error.ApplicationUnavailable;
defer g_object_unref(app);
diff --git a/src/control_center/sections/printers.zig b/src/control_center/sections/printers.zig
index b1be3b7..eeada1b 100644
--- a/src/control_center/sections/printers.zig
+++ b/src/control_center/sections/printers.zig
@@ -68,7 +68,7 @@ pub const Section = struct {
test_kind: printing.TestKind = .driver,
inches: bool = false,
suggested: ?cups.ipp.Resolution = null,
- expanded: [@typeInfo(Disclosure).@"enum".fields.len]bool = @splat(false),
+ expanded: [@typeInfo(Disclosure).@"enum".field_names.len]bool = @splat(false),
history_limit: usize = 5,
expanded_job: ?i32 = null,
reveal_target: ?[]const u8 = null,
diff --git a/src/control_center/sections/printers_details.zig b/src/control_center/sections/printers_details.zig
index 0e1d4dc..c7e1ddb 100644
--- a/src/control_center/sections/printers_details.zig
+++ b/src/control_center/sections/printers_details.zig
@@ -257,7 +257,7 @@ pub fn printingOptions(self: *Section, cc: *panel.ControlCenter, a: A, state: *c
try options.append(a, panel.sectionTitle(i18n.tr("Printing preferences")));
const groups: []const driver_options.Group = if (std.mem.eql(u8, state.selected, printer.name)) state.groups else &.{};
// Prefer the driver's selectable default over an alias of the same setting.
- var common: [@typeInfo(Preference).@"enum".fields.len]?*const driver_options.Option = @splat(null);
+ var common: [@typeInfo(Preference).@"enum".field_names.len]?*const driver_options.Option = @splat(null);
for (groups) |option_group| for (option_group.options) |*option| {
const kind = preference(option.*) orelse continue;
if (option.choices.len == 0) continue;
diff --git a/src/control_center/sections/region.zig b/src/control_center/sections/region.zig
index 5822048..4c71bf9 100644
--- a/src/control_center/sections/region.zig
+++ b/src/control_center/sections/region.zig
@@ -9,17 +9,7 @@ const gpa = @import("../../main.zig").gpa;
const config = @import("config");
const wl = @import("wayland").server.wl;
const Child = @import("../../session/child.zig");
-const c = @cImport({
- @cDefine("_GNU_SOURCE", "1");
- @cUndef("_FORTIFY_SOURCE");
- @cInclude("locale.h");
- @cInclude("langinfo.h");
- @cInclude("time.h");
- @cInclude("stdio.h");
- @cInclude("monetary.h");
- @cInclude("fcntl.h");
- @cInclude("unistd.h");
-});
+const c = @import("c");
const days = [_]i18n.Message{ i18n.msg("Sunday"), i18n.msg("Monday"), i18n.msg("Tuesday"), i18n.msg("Wednesday"), i18n.msg("Thursday"), i18n.msg("Friday"), i18n.msg("Saturday") };
@@ -114,7 +104,7 @@ fn localeReady(_: c_int, _: wl.EventMask, cc: *panel.ControlCenter) c_int {
while (lines.next()) |line| {
const name = std.mem.trim(u8, line, " \t\r");
if (name.len == 0 or std.mem.eql(u8, name, "POSIX") or std.mem.eql(u8, name, "C") or std.mem.startsWith(u8, name, "C.")) continue;
- const z = a.dupeZ(u8, name) catch continue;
+ const z = a.dupeSentinel(u8, name, 0) catch continue;
const locale = c.newlocale(c.LC_ALL_MASK, z, null) orelse continue;
c.freelocale(locale);
s.locales.append(a, z) catch break;
@@ -184,7 +174,7 @@ fn catalogForLocale(value: []const u8) ?[]const u8 {
fn localeHint(a: std.mem.Allocator, cc: *panel.ControlCenter) ![]const u8 {
const selected = i18n.resolve(cc.server.config.region.language, cc.server.environ);
const canonical = catalogForLocale(selected) orelse return tr("Reopen running apps to use the selected language.");
- const name = try a.dupeZ(u8, if (std.mem.indexOfScalar(u8, selected, '_') != null) selected else canonical);
+ const name = try a.dupeSentinel(u8, if (std.mem.indexOfScalar(u8, selected, '_') != null) selected else canonical, 0);
if (c.newlocale(c.LC_MESSAGES_MASK, name, null)) |locale| {
c.freelocale(locale);
return tr("Reopen running apps to use the selected language.");
@@ -238,7 +228,7 @@ fn localeName(cc: *panel.ControlCenter, category: []const u8) []const u8 {
}
fn localeLabel(a: std.mem.Allocator, name: []const u8, item: c.nl_item) ![]const u8 {
- const name_z = try a.dupeZ(u8, name);
+ const name_z = try a.dupeSentinel(u8, name, 0);
const locale = c.newlocale(c.LC_ALL_MASK, name_z, null) orelse return name;
defer c.freelocale(locale);
const value = std.mem.span(c.nl_langinfo_l(item, locale));
@@ -260,7 +250,7 @@ fn timezone(a: std.mem.Allocator, cc: *panel.ControlCenter) ![]const u8 {
}
fn previews(a: std.mem.Allocator, prefs: config.loader.RegionConfig) !W {
- const name = try a.dupeZ(u8, prefs.formats);
+ const name = try a.dupeSentinel(u8, prefs.formats, 0);
const locale = c.newlocale(c.LC_ALL_MASK, name, null) orelse return text(tr("Regional formats are unavailable for this session."), 12, true);
defer c.freelocale(locale);
// Fixed examples make format changes easy to compare, with no preview timer.
diff --git a/src/control_center/sections/services.zig b/src/control_center/sections/services.zig
index 26a7918..5ba7764 100644
--- a/src/control_center/sections/services.zig
+++ b/src/control_center/sections/services.zig
@@ -330,7 +330,7 @@ fn tryAppend(list: *std.ArrayList(W), a: std.mem.Allocator, widget: W) !void {
try list.append(a, widget);
}
fn matches(unit: systemd.Unit, query: []const u8, filter: Filter) bool {
- if (std.ascii.indexOfIgnoreCase(unit.name, query) == null and std.ascii.indexOfIgnoreCase(unit.description, query) == null) return false;
+ if (std.ascii.findIgnoreCase(unit.name, query) == null and std.ascii.findIgnoreCase(unit.description, query) == null) return false;
return switch (filter) {
.all => true,
.enabled => unit.enabled(),
diff --git a/src/control_center/sections/shortcuts.zig b/src/control_center/sections/shortcuts.zig
index 584518b..52c5491 100644
--- a/src/control_center/sections/shortcuts.zig
+++ b/src/control_center/sections/shortcuts.zig
@@ -50,7 +50,7 @@ pub const Section = struct {
}
pub fn capture(s: *Section, cc: *panel.ControlCenter, keycode: u32, sym: xkb.Keysym, mods: wlr.Keyboard.ModifierMask) void {
- switch (@intFromEnum(sym)) {
+ switch (sym) {
xkb.Keysym.Escape => {
s.cancel();
cc.refresh();
diff --git a/src/control_center/sections/users.zig b/src/control_center/sections/users.zig
index 60aff5c..fc98fbd 100644
--- a/src/control_center/sections/users.zig
+++ b/src/control_center/sections/users.zig
@@ -8,11 +8,7 @@ const validation = @import("../../accounts/validation.zig");
const ui = @import("ui");
const W = ui.layout.Widget;
const gpa = @import("../../main.zig").gpa;
-const c = @cImport({
- @cDefine("_GNU_SOURCE", "1");
- @cInclude("sys/socket.h");
- @cInclude("unistd.h");
-});
+const c = @import("c");
const secret_input = ui.widgets.secret_input;
extern fn rediwm_polkit_secret_new() ?*anyopaque;
extern fn rediwm_polkit_secret_free(*anyopaque) void;
diff --git a/src/control_center/welcome.zig b/src/control_center/welcome.zig
index 8b0996f..368d794 100644
--- a/src/control_center/welcome.zig
+++ b/src/control_center/welcome.zig
@@ -212,7 +212,7 @@ fn saveApp(cc: *panel.ControlCenter, browser: bool, index: usize) !void {
const value = values[index];
if (browser) {
if (value.len == 0) return;
- const id = try gpa.dupeZ(u8, value);
+ const id = try gpa.dupeSentinel(u8, value, 0);
defer gpa.free(id);
const app = g_desktop_app_info_new(id) orelse return error.ApplicationUnavailable;
defer g_object_unref(app);
diff --git a/src/cursor_theme_gen.zig b/src/cursor_theme_gen.zig
index cb46f75..f92606a 100644
--- a/src/cursor_theme_gen.zig
+++ b/src/cursor_theme_gen.zig
@@ -11,12 +11,7 @@
//! and libXcursor animate.
const std = @import("std");
const Io = std.Io;
-const c = @cImport({
- @cInclude("cairo.h");
- @cInclude("stdio.h");
- @cInclude("sys/stat.h");
- @cInclude("unistd.h");
-});
+const c = @import("c_gfx");
const Handle = opaque {};
const GError = opaque {};
@@ -282,7 +277,7 @@ fn writeFile(allocator: std.mem.Allocator, dir: []const u8, name: []const u8, by
fn link(allocator: std.mem.Allocator, dir: []const u8, target: []const u8, alias: []const u8) !void {
if (std.mem.eql(u8, target, alias)) return;
const path = try std.fmt.allocPrintSentinel(allocator, "{s}/{s}", .{ dir, alias }, 0);
- const to = try allocator.dupeZ(u8, target);
+ const to = try allocator.dupeSentinel(u8, target, 0);
_ = c.unlink(path.ptr);
if (c.symlink(to.ptr, path.ptr) != 0) return error.LinkFailed;
}
@@ -291,7 +286,7 @@ fn mkdirs(allocator: std.mem.Allocator, path: []const u8) !void {
var i: usize = 1;
while (i <= path.len) : (i += 1) {
if (i != path.len and path[i] != '/') continue;
- const part = try allocator.dupeZ(u8, path[0..i]);
+ const part = try allocator.dupeSentinel(u8, path[0..i], 0);
if (c.mkdir(part.ptr, 0o755) != 0 and std.c._errno().* != @intFromEnum(std.posix.E.EXIST)) return error.MkdirFailed;
}
}
diff --git a/src/dbus/wire.zig b/src/dbus/wire.zig
index b654b4a..5f71864 100644
--- a/src/dbus/wire.zig
+++ b/src/dbus/wire.zig
@@ -8,7 +8,7 @@ pub const Kind = enum(u8) { method_call = 1, method_return = 2, error_reply = 3,
pub const Writer = struct {
allocator: std.mem.Allocator,
bytes: std.ArrayList(u8) = .empty,
- endian: std.builtin.Endian = .little,
+ endian: std.lang.Endian = .little,
pub fn deinit(self: *Writer) void {
self.bytes.deinit(self.allocator);
}
@@ -17,7 +17,7 @@ pub const Writer = struct {
try self.bytes.appendSlice(self.allocator, data);
}
pub fn alignTo(self: *Writer, n: usize) !void {
- const zeros = [_]u8{0} ** 8;
+ const zeros = @as([8]u8, @splat(0));
try self.raw(zeros[0..padding(self.bytes.items.len, n)]);
}
pub fn byte(self: *Writer, value: u8) !void {
@@ -84,7 +84,7 @@ pub const Reader = struct {
fds: []const std.posix.fd_t = &.{},
bytes: []const u8,
offset: usize = 0,
- endian: std.builtin.Endian = .little,
+ endian: std.lang.Endian = .little,
pub fn take(self: *Reader, n: usize) Error![]const u8 {
if (self.offset > self.bytes.len or n > self.bytes.len - self.offset) return error.Truncated;
const value = self.bytes[self.offset..][0..n];
@@ -318,7 +318,7 @@ pub fn decodeWithFds(bytes: []const u8, fds: []const std.posix.fd_t) Error!Messa
var fields = try r.array(8);
var h: Headers = .{};
var fd_count: u32 = 0;
- var seen = [_]bool{false} ** 256;
+ var seen = @as([256]bool, @splat(false));
while (fields.offset < fields.bytes.len) {
try fields.alignTo(8);
const code = try fields.byte();
@@ -421,7 +421,7 @@ pub fn encode(allocator: std.mem.Allocator, kind: Kind, flags: u8, serial: u32,
}
test "primitive round trips in both byte orders and string alignment" {
- for ([_]std.builtin.Endian{ .little, .big }) |endian| {
+ for ([_]std.lang.Endian{ .little, .big }) |endian| {
var w: Writer = .{ .allocator = std.testing.allocator, .endian = endian };
defer w.deinit();
try w.byte(7);
diff --git a/src/desktop/app_actions.zig b/src/desktop/app_actions.zig
index 2aeb482..9fabb1d 100644
--- a/src/desktop/app_actions.zig
+++ b/src/desktop/app_actions.zig
@@ -266,7 +266,7 @@ pub fn finishEdit(self: *App) void {
pub fn choiceEntry(self: *App, index: usize) ?@import("dotdesktop.zig").parser.AppEntry {
var n: usize = 0;
for (self.catalog) |entry| {
- if (self.edit_text.items.len > 0 and std.ascii.indexOfIgnoreCase(entry.name, self.edit_text.items) == null) continue;
+ if (self.edit_text.items.len > 0 and std.ascii.findIgnoreCase(entry.name, self.edit_text.items) == null) continue;
if (n == index) return entry;
n += 1;
}
diff --git a/src/desktop/app_tests.zig b/src/desktop/app_tests.zig
index c414d89..b2ded2b 100644
--- a/src/desktop/app_tests.zig
+++ b/src/desktop/app_tests.zig
@@ -60,7 +60,7 @@ test "desktop shortcut picker searches, confirms separately and cancels without
test "desktop pointer motion repaints only when visible state changes" {
var icons = [_]Icon{.{ .item = .{ .path = "", .name = "", .icon = null }, .cell = .{}, .born = 0 }};
- var app = App{ .worker = undefined, .icons = .{ .items = &icons, .capacity = icons.len }, .dirty = false };
+ var app = App{ .worker = undefined, .icons = .fromOwnedSlice(&icons), .dirty = false };
app.motion(200, 200);
app.motion(300, 250);
try std.testing.expect(!app.dirty);
@@ -198,7 +198,7 @@ test "icon group cache matches fresh pixels after visual and content changes" {
icons[0].name_cache.deinit();
icons[0].raster.deinit();
}
- var app = App{ .worker = undefined, .geometry = .{ .w = 200, .h = 240 }, .icons = .{ .items = &icons, .capacity = icons.len } };
+ var app = App{ .worker = undefined, .geometry = .{ .w = 200, .h = 240 }, .icons = .fromOwnedSlice(&icons) };
defer app.edit_text.deinit(a);
defer app.rename_editor.deinit();
const ic = &icons[0];
@@ -230,8 +230,8 @@ test "icon group cache matches fresh pixels after visual and content changes" {
try expectFreshIconPixels(&app, 200, 240, 1, 0, 1, 0, 1000);
ic.replaceItem(try copyItem(.{ .path = "", .name = "Beta icon", .icon = null }));
try expectFreshIconPixels(&app, 200, 240, 1, 0, 1, 0, 1000);
- const blue = [_]u32{0xff2040e0} ** 4;
- const red = [_]u32{0xffe04020} ** 4;
+ const blue = @as([4]u32, @splat(0xff2040e0));
+ const red = @as([4]u32, @splat(0xffe04020));
for ([_]?@import("../icon_cache.zig").Entry{ .{ .pixels = &blue, .size = 2 }, .{ .pixels = &red, .size = 2 }, null }) |icon| {
ic.replaceItem(try copyItem(.{ .path = "", .name = "Beta icon", .icon = icon }));
try expectFreshIconPixels(&app, 200, 240, 1, 0, 1, 0, 1000);
diff --git a/src/desktop/c.zig b/src/desktop/c.zig
index e579b85..cde6b9a 100644
--- a/src/desktop/c.zig
+++ b/src/desktop/c.zig
@@ -1,18 +1 @@
-pub const api = @cImport({
- // Translate libc declarations, not glibc's fortified inline wrappers: Zig
- // 0.16 rejects their attribute(error) calls in ReleaseSafe. This affects
- // this import only; Zig runtime safety and separately compiled C stay on.
- @cUndef("_FORTIFY_SOURCE");
- @cDefine("_GNU_SOURCE", "1");
- @cInclude("cairo.h");
- @cInclude("sys/inotify.h");
- @cInclude("sys/eventfd.h");
- @cInclude("sys/stat.h");
- @cInclude("poll.h");
- @cInclude("unistd.h");
- @cInclude("fcntl.h");
- @cInclude("pthread.h");
- @cInclude("time.h");
- @cInclude("stdlib.h");
- @cInclude("xkbcommon/xkbcommon.h");
-});
+pub const api = @import("c_gfx");
diff --git a/src/desktop/embedded.zig b/src/desktop/embedded.zig
index 44407ff..208a25c 100644
--- a/src/desktop/embedded.zig
+++ b/src/desktop/embedded.zig
@@ -654,7 +654,7 @@ pub const Desktop = struct {
_ = @import("../session/child.zig").watch(a, self.server.wl_server.getEventLoop(), launch.pid, null, null) catch {
_ = std.os.linux.kill(launch.pid, .KILL);
var status: u32 = 0;
- while (std.os.linux.errno(std.os.linux.wait4(launch.pid, &status, 0, null)) == .INTR) {}
+ while (std.os.linux.errno(std.os.linux.wait4(launch.pid, @ptrCast(&status), 0, null)) == .INTR) {}
};
}
}
diff --git a/src/desktop/wallpaper.zig b/src/desktop/wallpaper.zig
index 194d284..40af6cf 100644
--- a/src/desktop/wallpaper.zig
+++ b/src/desktop/wallpaper.zig
@@ -14,7 +14,7 @@ extern fn g_error_free(*GError) void;
pub const Mode = enum { fill, fit, stretch, center, tile };
pub const Image = struct { pixels: []u32, w: i32, h: i32, mode: Mode };
pub fn load(a: std.mem.Allocator, path: []const u8, mode: Mode) !Image {
- const z = try a.dupeZ(u8, path);
+ const z = try a.dupeSentinel(u8, path, 0);
defer a.free(z);
var err: ?*GError = null;
const pixbuf = gdk_pixbuf_new_from_file(z, &err) orelse {
diff --git a/src/desktop/watcher.zig b/src/desktop/watcher.zig
index 00f2d93..91e1f0b 100644
--- a/src/desktop/watcher.zig
+++ b/src/desktop/watcher.zig
@@ -139,7 +139,7 @@ pub const Worker = struct {
self.stopAndJoin();
for (self.started[0..self.started_len]) |launch| {
var status: u32 = 0;
- _ = std.os.linux.wait4(launch.pid, &status, std.os.linux.W.NOHANG, null);
+ _ = std.os.linux.wait4(launch.pid, @ptrCast(&status), std.os.linux.W.NOHANG, null);
}
if (self.wake_worker >= 0) _ = c.close(self.wake_worker);
if (self.wake_main >= 0) _ = c.close(self.wake_main);
@@ -386,7 +386,7 @@ pub const Worker = struct {
defer c.free(real);
const target = std.mem.span(real);
for (app_dirs) |dir| {
- const zdir = mem.dupeZ(u8, dir) catch continue;
+ const zdir = mem.dupeSentinel(u8, dir, 0) catch continue;
const canonical = c.realpath(zdir, null) orelse continue;
defer c.free(canonical);
const prefix = std.mem.span(canonical);
@@ -410,7 +410,7 @@ pub const Worker = struct {
std.log.err("desktop directory: {}", .{err});
return;
};
- const zdir = a.dupeZ(u8, self.dir) catch return;
+ const zdir = a.dupeSentinel(u8, self.dir, 0) catch return;
defer a.free(zdir);
const fd = c.inotify_init1(c.IN_NONBLOCK | c.IN_CLOEXEC);
defer if (fd >= 0) {
@@ -628,7 +628,7 @@ pub const Worker = struct {
.folder => {
var suffix: usize = 1;
while (true) : (suffix += 1) {
- const path = if (suffix == 1) try a.dupeZ(u8, cmd.path) else try std.fmt.allocPrintSentinel(a, "{s} ({d})", .{ cmd.path, suffix }, 0);
+ const path = if (suffix == 1) try a.dupeSentinel(u8, cmd.path, 0) else try std.fmt.allocPrintSentinel(a, "{s} ({d})", .{ cmd.path, suffix }, 0);
const result = c.mkdir(path, 0o755);
if (result == 0) {
if (self.created_folder) |previous| a.free(previous.path);
@@ -641,30 +641,30 @@ pub const Worker = struct {
}
},
.trust => { // Allow Launching: the user's own `chmod u+x`.
- const p = try a.dupeZ(u8, cmd.path);
+ const p = try a.dupeSentinel(u8, cmd.path, 0);
defer a.free(p);
var stat: c.struct_stat = undefined;
if (c.stat(p, &stat) != 0 or stat.st_mode & c.S_IFMT != c.S_IFREG or stat.st_uid != c.getuid()) return error.NotYourFile;
if (c.chmod(p, (stat.st_mode & 0o7777) | c.S_IXUSR) != 0) return error.PermissionChangeFailed;
},
.file => {
- const p = try a.dupeZ(u8, cmd.path);
+ const p = try a.dupeSentinel(u8, cmd.path, 0);
defer a.free(p);
const fd = c.open(p, c.O_WRONLY | c.O_CREAT | c.O_EXCL | c.O_CLOEXEC, @as(c_uint, 0o644));
if (fd < 0) return error.CreateFailed;
_ = c.close(fd);
},
.rename, .move => { // No overwriting another desktop item.
- const from = try a.dupeZ(u8, cmd.path);
+ const from = try a.dupeSentinel(u8, cmd.path, 0);
defer a.free(from);
- const to = try a.dupeZ(u8, cmd.value);
+ const to = try a.dupeSentinel(u8, cmd.value, 0);
defer a.free(to);
if (c.renameat2(c.AT_FDCWD, from, c.AT_FDCWD, to, 1) != 0) return error.RenameFailed;
},
.link => {
- const from = try a.dupeZ(u8, cmd.path);
+ const from = try a.dupeSentinel(u8, cmd.path, 0);
defer a.free(from);
- const to = try a.dupeZ(u8, cmd.value);
+ const to = try a.dupeSentinel(u8, cmd.value, 0);
defer a.free(to);
if (c.symlink(from, to) != 0) return error.LinkFailed;
},
@@ -690,7 +690,7 @@ fn executable(env: std.process.Environ, name: []const u8) bool {
var paths = std.mem.splitScalar(u8, env.getPosix("PATH") orelse "", ':');
while (paths.next()) |p| {
var buf: [4096]u8 = undefined;
- const z = std.fmt.bufPrintZ(&buf, "{s}/{s}", .{ p, name }) catch continue;
+ const z = std.fmt.bufPrintSentinel(&buf, "{s}/{s}", .{ p, name }, 0) catch continue;
if (c.access(z, c.X_OK) == 0) return true;
}
return false;
diff --git a/src/dm/appearance.zig b/src/dm/appearance.zig
index 0d1c562..06099e9 100644
--- a/src/dm/appearance.zig
+++ b/src/dm/appearance.zig
@@ -1,13 +1,7 @@
//! Login appearance lives outside private/encrypted homes. Root creates only
//! directories; it never opens or parses the account's appearance files.
const std = @import("std");
-const c = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- @cInclude("fcntl.h");
- @cInclude("sys/stat.h");
- @cInclude("unistd.h");
- @cInclude("errno.h");
-});
+const c = @import("c");
pub const root = "/var/lib/rediwm-appearance";
@@ -25,7 +19,7 @@ pub fn provision(uid: u32, gid: u32) !void {
fn provisionAt(parent: c_int, uid: u32, gid: u32) !void {
var buf: [16]u8 = undefined;
- const name = try std.fmt.bufPrintZ(&buf, "{d}", .{uid});
+ const name = try std.fmt.bufPrintSentinel(&buf, "{d}", .{uid}, 0);
const created = c.mkdirat(parent, name, 0o755) == 0;
if (!created and std.posix.errno(-1) != .EXIST) return error.CreateDirectoryFailed;
const fd = c.openat(parent, name, c.O_RDONLY | c.O_DIRECTORY | c.O_NOFOLLOW | c.O_CLOEXEC);
@@ -47,7 +41,7 @@ test "login appearance provisioning is per uid and refuses symlinks" {
try provisionAt(tmp.dir.handle, uid, c.getgid());
try provisionAt(tmp.dir.handle, uid, c.getgid());
var name_buf: [16]u8 = undefined;
- const name = try std.fmt.bufPrintZ(&name_buf, "{d}", .{uid});
+ const name = try std.fmt.bufPrintSentinel(&name_buf, "{d}", .{uid}, 0);
var stat: c.struct_stat = undefined;
try std.testing.expectEqual(@as(c_int, 0), c.fstatat(tmp.dir.handle, name, &stat, c.AT_SYMLINK_NOFOLLOW));
try std.testing.expectEqual(uid, stat.st_uid);
diff --git a/src/dm/daemon.zig b/src/dm/daemon.zig
index ea5f2d4..961773b 100644
--- a/src/dm/daemon.zig
+++ b/src/dm/daemon.zig
@@ -14,10 +14,7 @@ const proto = @import("proto.zig");
const dm_ipc = @import("dm_ipc");
const ws = @import("wayland_sessions");
-const c = @cImport({
- @cInclude("pwd.h");
- @cInclude("sys/mman.h");
-});
+const c = @import("c");
const log = std.log.scoped(.rediwm_dm);
@@ -39,7 +36,7 @@ fn defaultUserValidator(user: []const u8, range: ws.UidRange) bool {
var pw: c.struct_passwd = undefined;
var res: ?*c.struct_passwd = null;
var name_buf: [256:0]u8 = undefined;
- const name_z = std.fmt.bufPrintZ(&name_buf, "{s}", .{user}) catch return false;
+ const name_z = std.fmt.bufPrintSentinel(&name_buf, "{s}", .{user}, 0) catch return false;
if (c.getpwnam_r(name_z.ptr, &pw, &buf, buf.len, &res) != 0 or res == null) return false;
const shell = if (pw.pw_shell) |s| std.mem.span(s) else "";
return ws.loginAccount(range, pw.pw_uid, shell);
@@ -226,7 +223,7 @@ pub const Daemon = struct {
self.children.add(self.gpa, pid) catch |err| {
_ = linux.kill(pid, .KILL);
var status: u32 = 0;
- while (linux.errno(linux.wait4(pid, &status, 0, null)) == .INTR) {}
+ while (linux.errno(linux.wait4(pid, @ptrCast(&status), 0, null)) == .INTR) {}
reaped = true;
return err;
};
@@ -279,19 +276,19 @@ pub const Daemon = struct {
for ([_]?[*:0]const u8{
"rediwm-dm",
"--worker",
- (std.fmt.bufPrintZ(&ctrl_buf, "{d}", .{ctrl_fd}) catch linux.exit_group(1)).ptr,
+ (std.fmt.bufPrintSentinel(&ctrl_buf, "{d}", .{ctrl_fd}, 0) catch linux.exit_group(1)).ptr,
}) |arg| {
args[n] = arg;
n += 1;
}
if (greeter_fd >= 0) {
args[n] = "--greeter-fd";
- args[n + 1] = (std.fmt.bufPrintZ(&greeter_buf, "{d}", .{greeter_fd}) catch linux.exit_group(1)).ptr;
+ args[n + 1] = (std.fmt.bufPrintSentinel(&greeter_buf, "{d}", .{greeter_fd}, 0) catch linux.exit_group(1)).ptr;
n += 2;
}
if (self.confdir) |dir| {
args[n] = "--confdir";
- args[n + 1] = (std.fmt.bufPrintZ(&confdir_buf, "{s}", .{dir}) catch linux.exit_group(1)).ptr;
+ args[n + 1] = (std.fmt.bufPrintSentinel(&confdir_buf, "{s}", .{dir}, 0) catch linux.exit_group(1)).ptr;
n += 2;
}
if (self.is_test) args[n] = "--test";
diff --git a/src/dm/main.zig b/src/dm/main.zig
index 41898e3..b7b1d38 100644
--- a/src/dm/main.zig
+++ b/src/dm/main.zig
@@ -24,7 +24,7 @@ fn printUsage() void {
\\ --marker <PATH> Custom path for autologin marker file
\\
;
- const c = @cImport({ @cInclude("unistd.h"); });
+ const c = @import("c");
_ = c.write(1, usage.ptr, usage.len);
}
diff --git a/src/dm/proto.zig b/src/dm/proto.zig
index 05cd1e0..e587988 100644
--- a/src/dm/proto.zig
+++ b/src/dm/proto.zig
@@ -132,7 +132,7 @@ pub fn sanitizeText(out: []u8, text: []const u8) []const u8 {
}
test "dm frames round-trip and refuse oversized payloads" {
- const c = @cImport(@cInclude("sys/socket.h"));
+ const c = @import("c");
var fds: [2]c_int = undefined;
try std.testing.expectEqual(@as(c_int, 0), c.socketpair(c.AF_UNIX, c.SOCK_STREAM | c.SOCK_CLOEXEC, 0, &fds));
defer _ = linux.close(fds[0]);
diff --git a/src/dm/tests.zig b/src/dm/tests.zig
index af6e997..3b3a5b1 100644
--- a/src/dm/tests.zig
+++ b/src/dm/tests.zig
@@ -6,10 +6,7 @@ const proto = @import("proto.zig");
const dm_ipc = @import("dm_ipc");
const ws = @import("wayland_sessions");
-const c = @cImport({
- @cInclude("sys/socket.h");
- @cInclude("unistd.h");
-});
+const c = @import("c");
test {
_ = proto;
diff --git a/src/dm/vt.zig b/src/dm/vt.zig
index 4e15da5..8797398 100644
--- a/src/dm/vt.zig
+++ b/src/dm/vt.zig
@@ -42,7 +42,7 @@ pub fn activate(vtnr: u32) !void {
/// hidden text buffer, so this can run ahead of the switch.
pub fn blank(vtnr: u32) !void {
var path_buf: [32]u8 = undefined;
- const path = try std.fmt.bufPrintZ(&path_buf, "/dev/tty{d}", .{vtnr});
+ const path = try std.fmt.bufPrintSentinel(&path_buf, "/dev/tty{d}", .{vtnr}, 0);
const rc = linux.open(path.ptr, .{ .ACCMODE = .WRONLY, .NOCTTY = true, .CLOEXEC = true, .NONBLOCK = true }, 0);
if (linux.errno(rc) != .SUCCESS) return error.OpenTtyFailed;
const fd: i32 = @intCast(rc);
diff --git a/src/dm/worker.zig b/src/dm/worker.zig
index c997791..74b5043 100644
--- a/src/dm/worker.zig
+++ b/src/dm/worker.zig
@@ -8,13 +8,7 @@ const std = @import("std");
const linux = std.os.linux;
const proto = @import("proto.zig");
-const c = @cImport({
- @cInclude("pwd.h");
- @cInclude("grp.h");
- @cInclude("unistd.h");
- @cInclude("sys/ioctl.h");
- @cInclude("sys/prctl.h");
-});
+const c = @import("c");
pub const pam_handle_t = opaque {};
@@ -51,10 +45,10 @@ pub fn runWorker(ctrl_fd: c_int, greeter_fd: c_int, confdir: ?[]const u8, is_tes
var frame_buf: [proto.max_frame]u8 = undefined;
const init = try std.json.parseFromSliceLeaky(proto.Init, a, try proto.readFrame(ctrl_fd, &frame_buf), .{ .allocate = .alloc_always });
const is_greeter = std.mem.eql(u8, init.class, "greeter");
- const user_z = try a.dupeZ(u8, init.user);
- const confdir_z: ?[*:0]const u8 = if (confdir) |cd| (try a.dupeZ(u8, cd)).ptr else null;
+ const user_z = try a.dupeSentinel(u8, init.user, 0);
+ const confdir_z: ?[*:0]const u8 = if (confdir) |cd| (try a.dupeSentinel(u8, cd, 0)).ptr else null;
- const pamh = rediwm_pam_start((try a.dupeZ(u8, init.service)).ptr, user_z.ptr, confdir_z, ctrl_fd) orelse {
+ const pamh = rediwm_pam_start((try a.dupeSentinel(u8, init.service, 0)).ptr, user_z.ptr, confdir_z, ctrl_fd) orelse {
report(ctrl_fd, .failed, "pam_start failed");
return 1;
};
@@ -158,7 +152,7 @@ fn supervise(pid: linux.pid_t, signal_fd: i32) u32 {
}
}
var status: u32 = 0;
- while (linux.errno(linux.waitpid(pid, &status, 0)) == .INTR) {}
+ while (linux.errno(linux.waitpid(pid, @ptrCast(&status), 0)) == .INTR) {}
return status;
}
@@ -185,8 +179,8 @@ fn account(a: std.mem.Allocator, user_z: [:0]const u8) Account {
const home = if (pw.pw_dir) |d| std.mem.span(d) else "/";
const shell = if (pw.pw_shell) |s| std.mem.span(s) else "";
return .{
- .home = a.dupeZ(u8, home) catch "/",
- .shell = a.dupeZ(u8, if (shell.len > 0) shell else "/bin/sh") catch "/bin/sh",
+ .home = a.dupeSentinel(u8, home, 0) catch "/",
+ .shell = a.dupeSentinel(u8, if (shell.len > 0) shell else "/bin/sh", 0) catch "/bin/sh",
.uid = pw.pw_uid,
.gid = pw.pw_gid,
.found = true,
@@ -196,7 +190,7 @@ fn account(a: std.mem.Allocator, user_z: [:0]const u8) Account {
/// The child's environment: PAM's (XDG_RUNTIME_DIR, XDG_SESSION_ID...) plus
/// the account's identity. Keys we set ourselves are never taken from PAM.
fn sessionEnv(a: std.mem.Allocator, pamh: *pam_handle_t, user: []const u8, desktops: []const u8, greeter: bool, login_started_ns: u64) ![:null]?[*:0]const u8 {
- const user_z = try a.dupeZ(u8, user);
+ const user_z = try a.dupeSentinel(u8, user, 0);
const acct = account(a, user_z);
const owned = [_][]const u8{ "HOME", "USER", "LOGNAME", "SHELL", "XDG_CURRENT_DESKTOP", "REDIWM_GREETER_FD", "REDIWM_LOGIN_STARTED_NS" };
var list: std.ArrayList(?[*:0]const u8) = .empty;
@@ -282,7 +276,7 @@ fn execSession(
// ask logind over D-Bus), so no setuid/file-capability exec may.
// User sessions keep them for sudo and pkexec.
if (c.prctl(c.PR_SET_NO_NEW_PRIVS, @as(c_ulong, 1), @as(c_ulong, 0), @as(c_ulong, 0), @as(c_ulong, 0)) != 0) linux.exit_group(1);
- const cmd = a.dupeZ(u8, exec) catch linux.exit_group(1);
+ const cmd = a.dupeSentinel(u8, exec, 0) catch linux.exit_group(1);
const argv = [_:null]?[*:0]const u8{ "/bin/sh", "-c", cmd.ptr };
_ = linux.execve("/bin/sh", &argv, env.ptr);
} else {
diff --git a/src/dock/paint.zig b/src/dock/paint.zig
index 1d49008..da13d06 100644
--- a/src/dock/paint.zig
+++ b/src/dock/paint.zig
@@ -19,7 +19,7 @@ pub fn hashValue(hasher: *std.hash.Wyhash, value: anytype) void {
hasher.update(&.{1});
hashValue(hasher, v);
} else hasher.update(&.{0}),
- .@"struct" => |info| inline for (info.fields) |field| hashValue(hasher, @field(value, field.name)),
+ .@"struct" => |info| inline for (info.field_names) |name| hashValue(hasher, @field(value, name)),
.pointer => {
hasher.update(std.mem.asBytes(&value.len));
hasher.update(std.mem.sliceAsBytes(value));
diff --git a/src/editor/app_files.zig b/src/editor/app_files.zig
index fea98f4..3b7a2ca 100644
--- a/src/editor/app_files.zig
+++ b/src/editor/app_files.zig
@@ -38,7 +38,7 @@ pub fn open(self: *App, path: []const u8) void {
return;
}
};
- const owned = a.dupeZ(u8, path) catch return;
+ const owned = a.dupeSentinel(u8, path, 0) catch return;
self.queue.append(a, owned) catch {
a.free(owned);
return;
@@ -72,7 +72,7 @@ pub fn sync(self: *App) void {
};
if (self.current().path != null or self.current().doc.text.items.len > 0 or self.current().doc.modified()) self.newTab() catch return;
const t = self.current();
- const path = a.dupeZ(u8, job.path) catch return;
+ const path = a.dupeSentinel(u8, job.path, 0) catch return;
t.doc.deinit();
t.doc = job.document.?;
job.document = null;
@@ -86,7 +86,7 @@ pub fn sync(self: *App) void {
},
.save => if (self.findTab(job.tab_id)) |i| {
const t = self.tabs.items[i];
- const path = a.dupeZ(u8, job.path) catch return;
+ const path = a.dupeSentinel(u8, job.path, 0) catch return;
if (t.path) |old| a.free(old);
t.path = path;
t.stamp = job.stamp;
diff --git a/src/editor/instance.zig b/src/editor/instance.zig
index 9eb31d5..e339887 100644
--- a/src/editor/instance.zig
+++ b/src/editor/instance.zig
@@ -1,14 +1,6 @@
//! One editor per Wayland display. A private runtime socket receives open requests.
const std = @import("std");
-const c = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- @cInclude("sys/socket.h");
- @cInclude("sys/un.h");
- @cInclude("sys/file.h");
- @cInclude("sys/stat.h");
- @cInclude("unistd.h");
- @cInclude("fcntl.h");
-});
+const c = @import("c");
const a = std.heap.c_allocator;
pub const Request = struct { path: []const u8 = "", token: []const u8 = "" };
pub const Instance = struct {
@@ -17,7 +9,7 @@ pub const Instance = struct {
primary: bool,
pub fn init(environ: std.process.Environ) !Instance {
const runtime = environ.getPosix("XDG_RUNTIME_DIR") orelse return error.NoRuntimeDirectory;
- const dir = try a.dupeZ(u8, runtime);
+ const dir = try a.dupeSentinel(u8, runtime, 0);
defer a.free(dir);
var st: c.struct_stat = undefined;
if (c.lstat(dir, &st) != 0 or st.st_mode & c.S_IFMT != c.S_IFDIR or st.st_uid != c.getuid() or st.st_mode & 0o077 != 0) return error.RuntimeDirectoryNotPrivate;
@@ -38,11 +30,11 @@ pub const Instance = struct {
const fd = c.socket(c.AF_UNIX, c.SOCK_DGRAM | c.SOCK_CLOEXEC | c.SOCK_NONBLOCK, 0);
if (fd < 0) return error.SocketFailed;
errdefer _ = c.close(fd);
- if (c.connect(fd, @ptrCast(&address), @sizeOf(c.struct_sockaddr_un)) == 0) return .{ .fd = fd, .path = path, .primary = false };
+ if (c.connect(fd, .{ .__sockaddr__ = @ptrCast(&address) }, @sizeOf(c.struct_sockaddr_un)) == 0) return .{ .fd = fd, .path = path, .primary = false };
const err = std.posix.errno(@as(c_int, -1));
if (err != .NOENT and err != .CONNREFUSED) return error.ConnectFailed;
_ = c.unlink(path);
- if (c.bind(fd, @ptrCast(&address), @sizeOf(c.struct_sockaddr_un)) != 0) return error.BindFailed;
+ if (c.bind(fd, .{ .__sockaddr__ = @ptrCast(&address) }, @sizeOf(c.struct_sockaddr_un)) != 0) return error.BindFailed;
_ = c.chmod(path, 0o600);
return .{ .fd = fd, .path = path, .primary = true };
}
diff --git a/src/editor/lines.zig b/src/editor/lines.zig
index 8440538..40f2b72 100644
--- a/src/editor/lines.zig
+++ b/src/editor/lines.zig
@@ -232,7 +232,11 @@ test "a huge single line folds into bounded pieces without scanning it all" {
test "a folded paragraph breaks after a space when one is near" {
// No word is longer than the 8 bytes looked back at this cut, so every
// piece can end after a space.
- const text = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau " ** 3;
+ const text = comptime blk: {
+ var repeated: []const u8 = "";
+ for (0..3) |_| repeated = repeated ++ "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau ";
+ break :blk repeated;
+ };
var seg = at(text, 0, 64);
var pieces: usize = 0;
while (true) : (pieces += 1) {
diff --git a/src/editor/main.zig b/src/editor/main.zig
index 1e74769..665589c 100644
--- a/src/editor/main.zig
+++ b/src/editor/main.zig
@@ -268,7 +268,7 @@ pub fn run(init: std.process.Init, paths: []const [:0]const u8, instance: *@impo
// Initial commit to start xdg configuration sequence
self.surface.commit();
- var pending_token = try a.dupeZ(u8, initial_token);
+ var pending_token = try a.dupeSentinel(u8, initial_token, 0);
defer a.free(pending_token);
while (self.running) {
self.app.sync();
@@ -299,7 +299,7 @@ pub fn run(init: std.process.Init, paths: []const [:0]const u8, instance: *@impo
if (self.configured and self.applied_scale > 0 and pending_token.len > 0) {
if (self.activation) |activation| activation.activate(pending_token, self.surface);
a.free(pending_token);
- pending_token = try a.dupeZ(u8, "");
+ pending_token = try a.dupeSentinel(u8, "", 0);
}
while (!display.prepareRead()) {
@@ -340,7 +340,7 @@ pub fn run(init: std.process.Init, paths: []const [:0]const u8, instance: *@impo
const req = parsed.value;
if (req.path.len == 0) self.app.newTab() catch {} else if (std.fs.path.isAbsolute(req.path) and std.mem.indexOfScalar(u8, req.path, 0) == null) self.app.open(req.path);
if (req.token.len > 0 and std.mem.indexOfScalar(u8, req.token, 0) == null) {
- const owned = try a.dupeZ(u8, req.token);
+ const owned = try a.dupeSentinel(u8, req.token, 0);
a.free(pending_token);
pending_token = owned;
}
diff --git a/src/editor/operation.zig b/src/editor/operation.zig
index dea75ea..ff9f22d 100644
--- a/src/editor/operation.zig
+++ b/src/editor/operation.zig
@@ -130,7 +130,7 @@ pub fn executable(buf: []u8, name: []const u8) []const u8 {
const n = c.readlink("/proc/self/exe", &path, path.len);
if (n > 0 and n < path.len) {
if (std.fs.path.dirname(path[0..@intCast(n)])) |dir| {
- const sibling = std.fmt.bufPrintZ(buf, "{s}/{s}", .{ dir, name }) catch return name;
+ const sibling = std.fmt.bufPrintSentinel(buf, "{s}/{s}", .{ dir, name }, 0) catch return name;
if (c.access(sibling, c.X_OK) == 0) return sibling;
}
}
@@ -169,7 +169,7 @@ pub const Operation = struct {
errdefer if (owns) a.free(data);
const self = try a.create(Operation);
errdefer a.destroy(self);
- const owned = try a.dupeZ(u8, path);
+ const owned = try a.dupeSentinel(u8, path, 0);
errdefer a.free(owned);
const fd = c.eventfd(0, c.EFD_CLOEXEC | c.EFD_NONBLOCK);
if (fd < 0) return error.EventFailed;
@@ -197,7 +197,7 @@ pub const Operation = struct {
fn canonical(self: *Operation) !void {
const path = c.realpath(self.path, null) orelse return error.OpenFailed;
defer c.free(path);
- const owned = try a.dupeZ(u8, std.mem.span(path));
+ const owned = try a.dupeSentinel(u8, std.mem.span(path), 0);
a.free(self.path);
self.path = owned;
}
@@ -273,7 +273,7 @@ pub const Operation = struct {
} else if (c.renameat2(c.AT_FDCWD, temp, c.AT_FDCWD, self.path, c.RENAME_NOREPLACE) != 0) return error.FileChanged;
if (c.stat(self.path, &st) != 0) return error.WriteFailed;
self.stamp = Stamp.of(st);
- const parent_z = try a.dupeZ(u8, parent);
+ const parent_z = try a.dupeSentinel(u8, parent, 0);
defer a.free(parent_z);
const dir = c.open(parent_z, c.O_RDONLY | c.O_DIRECTORY | c.O_CLOEXEC);
if (dir >= 0) {
@@ -317,7 +317,7 @@ pub const Operation = struct {
}
const chosen = parsed.value.paths[0];
if (!std.fs.path.isAbsolute(chosen) or std.mem.indexOfScalar(u8, chosen, 0) != null) return error.InvalidPath;
- const owned = try a.dupeZ(u8, chosen);
+ const owned = try a.dupeSentinel(u8, chosen, 0);
a.free(self.path);
self.path = owned;
// Capture the destination the user just approved, before returning to the UI.
@@ -331,7 +331,7 @@ pub const Operation = struct {
test "atomic saves preserve permissions, reject stale files and follow symlink targets" {
var template: [64:0]u8 = @splat(0);
- _ = try std.fmt.bufPrintZ(&template, "/tmp/rediwm-editor-XXXXXX", .{});
+ _ = try std.fmt.bufPrintSentinel(&template, "/tmp/rediwm-editor-XXXXXX", .{}, 0);
const dir = c.mkdtemp(&template) orelse return error.CreateFailed;
defer _ = c.rmdir(dir);
const path = try std.fmt.allocPrintSentinel(a, "{s}/note.txt", .{std.mem.span(dir)}, 0);
@@ -340,7 +340,7 @@ test "atomic saves preserve permissions, reject stale files and follow symlink t
const link = try std.fmt.allocPrintSentinel(a, "{s}/link.txt", .{std.mem.span(dir)}, 0);
defer a.free(link);
defer _ = c.unlink(link);
- var job: Operation = .{ .kind = .save, .tab_id = 1, .path = try a.dupeZ(u8, path), .bytes = try a.dupe(u8, "original"), .expected = null, .io = undefined, .fd = -1 };
+ var job: Operation = .{ .kind = .save, .tab_id = 1, .path = try a.dupeSentinel(u8, path, 0), .bytes = try a.dupe(u8, "original"), .expected = null, .io = undefined, .fd = -1 };
defer a.free(job.path);
defer a.free(job.bytes);
try job.work();
@@ -358,7 +358,7 @@ test "atomic saves preserve permissions, reject stale files and follow symlink t
try std.testing.expect(c.symlink(path, link) == 0);
job.expected = Stamp.of(st);
a.free(job.path);
- job.path = try a.dupeZ(u8, link);
+ job.path = try a.dupeSentinel(u8, link, 0);
try job.work();
try std.testing.expect(c.lstat(link, &st) == 0 and st.st_mode & c.S_IFMT == c.S_IFLNK);
const fd = c.open(path, c.O_RDONLY);
@@ -374,7 +374,7 @@ test "atomic saves preserve permissions, reject stale files and follow symlink t
test "loading reads one buffer, keeps the BOM aside and refuses binary data early" {
var template: [64:0]u8 = @splat(0);
- _ = try std.fmt.bufPrintZ(&template, "/tmp/rediwm-editor-XXXXXX", .{});
+ _ = try std.fmt.bufPrintSentinel(&template, "/tmp/rediwm-editor-XXXXXX", .{}, 0);
const dir = c.mkdtemp(&template) orelse return error.CreateFailed;
defer _ = c.rmdir(dir);
const path = try std.fmt.allocPrintSentinel(a, "{s}/big.txt", .{std.mem.span(dir)}, 0);
@@ -388,7 +388,7 @@ test "loading reads one buffer, keeps the BOM aside and refuses binary data earl
try std.testing.expect(fd >= 0);
try writeAll(fd, body.items);
_ = c.close(fd);
- var job: Operation = .{ .kind = .load, .tab_id = 1, .path = try a.dupeZ(u8, path), .bytes = "", .owns_bytes = false, .expected = null, .io = undefined, .fd = -1 };
+ var job: Operation = .{ .kind = .load, .tab_id = 1, .path = try a.dupeSentinel(u8, path, 0), .bytes = "", .owns_bytes = false, .expected = null, .io = undefined, .fd = -1 };
defer a.free(job.path);
defer if (job.document) |*d| d.deinit();
try job.work();
diff --git a/src/editor/view.zig b/src/editor/view.zig
index a148e79..0457295 100644
--- a/src/editor/view.zig
+++ b/src/editor/view.zig
@@ -90,7 +90,7 @@ pub const Layouts = struct {
l.width = width;
l.scale = scale;
var buf: [256:0]u8 = undefined;
- const name = std.fmt.bufPrintZ(&buf, "{s}", .{family}) catch "monospace";
+ const name = std.fmt.bufPrintSentinel(&buf, "{s}", .{family}, 0) catch "monospace";
if (l.font) |f| p.pango_font_description_free(f);
l.font = p.pango_font_description_from_string(name);
if (l.font) |f| p.pango_font_description_set_absolute_size(f, size * 1024);
diff --git a/src/files/app.zig b/src/files/app.zig
index 53a0e2d..226d467 100644
--- a/src/files/app.zig
+++ b/src/files/app.zig
@@ -270,7 +270,7 @@ pub const App = struct {
// Title notification
title_changed: bool = true,
- title_z: [256:0]u8 = [1:0]u8{0} ** 256,
+ title_z: [256:0]u8 = @splat(0),
pub fn init(
allocator: Allocator,
diff --git a/src/files/app_chooser.zig b/src/files/app_chooser.zig
index 0dcfacd..4fa52e3 100644
--- a/src/files/app_chooser.zig
+++ b/src/files/app_chooser.zig
@@ -218,7 +218,7 @@ pub fn collectChooser(self: *App) !void {
return error.NoSelection;
} else try std.fs.path.join(self.allocator, &.{ self.history.current, name });
defer self.allocator.free(path);
- const zpath = try self.allocator.dupeZ(u8, path);
+ const zpath = try self.allocator.dupeSentinel(u8, path, 0);
defer self.allocator.free(zpath);
var stat: c.struct_stat = undefined;
const exists = c.stat(zpath, &stat) == 0;
@@ -228,7 +228,7 @@ pub fn collectChooser(self: *App) !void {
}
if (opts.mode == .open and (!exists or c.access(zpath, c.R_OK) != 0)) return error.Inaccessible;
if (opts.mode == .save) {
- const parent = try self.allocator.dupeZ(u8, self.history.current);
+ const parent = try self.allocator.dupeSentinel(u8, self.history.current, 0);
defer self.allocator.free(parent);
if (c.access(parent, c.W_OK | c.X_OK) != 0) return error.Inaccessible;
}
@@ -241,7 +241,7 @@ pub fn collectChooser(self: *App) !void {
} else {
for (self.items.items) |item| {
if (!item.selected or item.is_broken or item.is_dir != (opts.mode == .folder)) continue;
- const zpath = try self.allocator.dupeZ(u8, item.path);
+ const zpath = try self.allocator.dupeSentinel(u8, item.path, 0);
defer self.allocator.free(zpath);
var stat: c.struct_stat = undefined;
if (c.stat(zpath, &stat) != 0 or c.access(zpath, c.R_OK) != 0 or (stat.st_mode & c.S_IFMT == c.S_IFDIR) != (opts.mode == .folder)) return error.Inaccessible;
@@ -265,7 +265,7 @@ pub fn collectChooser(self: *App) !void {
while (true) : (index += 1) {
if (index > 10000) return error.TooManyFiles;
const path = if (index == 0) try std.fs.path.join(self.allocator, &.{ folder, name }) else try std.fmt.allocPrint(self.allocator, "{s}/{s}.{d}", .{ folder, name, index });
- const zpath = try self.allocator.dupeZ(u8, path);
+ const zpath = try self.allocator.dupeSentinel(u8, path, 0);
defer self.allocator.free(zpath);
var stat: c.struct_stat = undefined;
var exists = c.lstat(zpath, &stat) == 0;
diff --git a/src/files/app_opening.zig b/src/files/app_opening.zig
index 4309b74..6ba2b16 100644
--- a/src/files/app_opening.zig
+++ b/src/files/app_opening.zig
@@ -42,7 +42,7 @@ pub fn previewSelected(self: *App) void {
}
if (!formats.candidate(item.path)) {
if (!@import("../editor/formats.zig").candidate(item.path)) return;
- if (self.editor_path == null) self.editor_path = self.allocator.dupeZ(u8, item.path) catch null;
+ if (self.editor_path == null) self.editor_path = self.allocator.dupeSentinel(u8, item.path, 0) catch null;
return;
}
if (self.preview_return_fd != null) return;
@@ -99,7 +99,7 @@ pub fn launchImageList(self: *App, fd: c_int, index: usize) !void {
const n = c.readlink("/proc/self/exe", &exe_buf, exe_buf.len);
if (n > 0 and n < exe_buf.len) {
if (std.fs.path.dirname(exe_buf[0..@intCast(n)])) |dir| {
- const sibling = try std.fmt.bufPrintZ(&sibling_buf, "{s}/rediwm-images", .{dir});
+ const sibling = try std.fmt.bufPrintSentinel(&sibling_buf, "{s}/rediwm-images", .{dir}, 0);
if (c.access(sibling, c.X_OK) == 0) executable = sibling;
}
}
@@ -159,7 +159,7 @@ pub fn openFile(self: *App, path: []const u8) void {
const n = c.readlink("/proc/self/exe", &exe_buf, exe_buf.len);
if (n > 0 and n < exe_buf.len) {
if (std.fs.path.dirname(exe_buf[0..@intCast(n)])) |dir| {
- if (std.fmt.bufPrintZ(&sibling_buf, "{s}/rediwm-pdf", .{dir})) |sibling| {
+ if (std.fmt.bufPrintSentinel(&sibling_buf, "{s}/rediwm-pdf", .{dir}, 0)) |sibling| {
if (c.access(sibling, c.X_OK) == 0) executable = sibling;
} else |_| {}
}
@@ -213,7 +213,7 @@ pub fn openExtracted(self: *App, path: []const u8, preview: bool) void {
if (preview and image_formats.candidate(path)) {
self.previewExtracted(path) catch self.setStatusNotice(tr("Could not open image viewer"), true);
} else if (preview and @import("../editor/formats.zig").candidate(path)) {
- if (self.editor_path == null) self.editor_path = self.allocator.dupeZ(u8, path) catch null;
+ if (self.editor_path == null) self.editor_path = self.allocator.dupeSentinel(u8, path, 0) catch null;
} else if (!preview or isPdf(path)) self.openFile(path);
}
diff --git a/src/files/app_terminal.zig b/src/files/app_terminal.zig
index 63637e2..58936e8 100644
--- a/src/files/app_terminal.zig
+++ b/src/files/app_terminal.zig
@@ -116,7 +116,7 @@ fn rememberDirectory(self: *App) void {
const current = self.history.current;
if (std.mem.eql(u8, current, trash) or (std.mem.startsWith(u8, current, trash) and current.len > trash.len and current[trash.len] == '/')) return;
}
- const path_z = self.allocator.dupeZ(u8, self.history.current) catch return;
+ const path_z = self.allocator.dupeSentinel(u8, self.history.current, 0) catch return;
defer self.allocator.free(path_z);
var path_buf: [4096]u8 = undefined;
const real = c.realpath(path_z, &path_buf) orelse return;
@@ -124,7 +124,7 @@ fn rememberDirectory(self: *App) void {
if (c.stat(real, &stat) != 0 or stat.st_mode & c.S_IFMT != c.S_IFDIR) return;
const resolved = std.mem.span(real);
if (self.terminal.directory) |old| if (std.mem.eql(u8, old, resolved)) return;
- const owned = self.allocator.dupeZ(u8, resolved) catch return;
+ const owned = self.allocator.dupeSentinel(u8, resolved, 0) catch return;
if (self.terminal.directory) |old| self.allocator.free(old);
self.terminal.directory = owned;
if (self.terminal.session) |session| _ = tc.ft_follow(session, owned);
@@ -147,7 +147,7 @@ pub fn terminalHelper(self: *App, name: []const u8, buffer: []u8) ![:0]u8 {
const n = c.readlink("/proc/self/exe", &executable, executable.len);
if (n <= 0 or n >= executable.len) return error.NoExecutable;
const directory = std.fs.path.dirname(executable[0..@intCast(n)]) orelse return error.NoExecutable;
- return std.fmt.bufPrintZ(buffer, "{s}/{s}", .{ directory, name });
+ return std.fmt.bufPrintSentinel(buffer, "{s}/{s}", .{ directory, name }, 0);
}
pub fn terminalStart(self: *App) void {
if (self.chooser != null or self.terminal.close_at != null) return;
@@ -167,7 +167,7 @@ pub fn terminalStart(self: *App) void {
self.terminal.session = session;
self.terminal.generation = std.math.maxInt(u64);
rememberDirectory(self);
- const directory = self.terminal.directory orelse self.allocator.dupeZ(u8, self.home_dir) catch {
+ const directory = self.terminal.directory orelse self.allocator.dupeSentinel(u8, self.home_dir, 0) catch {
self.terminal.error_message = tr("No terminal directory");
return;
};
diff --git a/src/files/app_tests.zig b/src/files/app_tests.zig
index dd44dde..2550703 100644
--- a/src/files/app_tests.zig
+++ b/src/files/app_tests.zig
@@ -43,7 +43,7 @@ test "grid hit testing respects gutters, scrolling and responsive columns" {
app.list_view = false;
app.scroll_y = 0;
var items: [20]ViewItem = undefined;
- app.items = .{ .items = &items, .capacity = items.len };
+ app.items = .fromOwnedSlice(&items);
try std.testing.expectEqual(@as(i32, 3), app.columns());
try std.testing.expectEqual(@as(?usize, 0), app.itemAt(250, 158));
try std.testing.expectEqual(@as(?usize, 1), app.itemAt(490, 158));
diff --git a/src/files/app_views_tests.zig b/src/files/app_views_tests.zig
index 6456c39..38342f0 100644
--- a/src/files/app_views_tests.zig
+++ b/src/files/app_views_tests.zig
@@ -98,7 +98,7 @@ test "Transfers uses list geometry and isolates file actions while preserving th
// while the transfer pane is active.
var files: [32]ViewItem = undefined;
var transfers: [32]@import("torrents.zig").Transfer = undefined;
- app.items = .{ .items = &files, .capacity = files.len };
+ app.items = .fromOwnedSlice(&files);
app.torrents.snapshot = .{ .arena = undefined, .value = .{ .transfers = &transfers } };
app.list_view = false;
app.transfer_view = .{ .active = true, .folder_scroll = 77, .folder_search_visible = true };
diff --git a/src/files/appimage.zig b/src/files/appimage.zig
index 56a7c9c..9750558 100644
--- a/src/files/appimage.zig
+++ b/src/files/appimage.zig
@@ -109,7 +109,7 @@ fn get(file: *anyopaque, key: [*:0]const u8) ?[*:0]u8 {
}
fn set(a: Allocator, file: *anyopaque, key: [*:0]const u8, value: []const u8) !void {
- const z = try a.dupeZ(u8, value);
+ const z = try a.dupeSentinel(u8, value, 0);
defer a.free(z);
g_key_file_set_string(file, "Desktop Entry", key, z);
}
@@ -207,7 +207,7 @@ fn atomicWrite(a: Allocator, io: std.Io, path: []const u8, bytes: []const u8) !v
/// The caller owns an arena. No files are extracted from the image to disk;
/// only bounded launcher/icon bytes are published to the user's XDG data dir.
pub fn install(a: Allocator, io: std.Io, environ: std.process.Environ, path: []const u8) !void {
- const zpath = try a.dupeZ(u8, path);
+ const zpath = try a.dupeSentinel(u8, path, 0);
const canonical = c.realpath(zpath, null) orelse return error.ReadFailed;
defer c.free(canonical);
const image_path = std.mem.span(canonical);
@@ -283,7 +283,7 @@ pub fn install(a: Allocator, io: std.Io, environ: std.process.Environ, path: []c
while (entries.next()) |entry| {
if (entry.len == 0) continue;
if (entry.len > 255 or std.mem.indexOfScalar(u8, entry, '/') == null or std.mem.indexOfAny(u8, entry, " \t\r\n\\") != null) continue;
- const mime = try a.dupeZ(u8, entry);
+ const mime = try a.dupeSentinel(u8, entry, 0);
if (g_app_info_add_supports_type(app, mime, null) == 0) failed = true;
// Claim unhandled URL schemes (including Unity's sign-in callback),
// preserving an existing user choice and all file-type defaults.
diff --git a/src/files/archive.zig b/src/files/archive.zig
index 476d341..89f2d7c 100644
--- a/src/files/archive.zig
+++ b/src/files/archive.zig
@@ -3,10 +3,7 @@
const std = @import("std");
const tr = @import("i18n").tr;
const c = @import("c.zig").api;
-const a = @cImport({
- @cInclude("archive.h");
- @cInclude("archive_entry.h");
-});
+const a = @import("c_archive");
const Allocator = std.mem.Allocator;
pub const Cancel = std.atomic.Value(bool);
@@ -95,7 +92,7 @@ const Reader = struct {
_ = a.archive_read_support_format_zip(handle);
_ = a.archive_read_support_format_tar(handle);
_ = a.archive_read_support_format_7zip(handle);
- const zpath = try mem.dupeZ(u8, path);
+ const zpath = try mem.dupeSentinel(u8, path, 0);
defer mem.free(zpath);
const fd = c.open(zpath, c.O_RDONLY | c.O_NONBLOCK | c.O_CLOEXEC);
if (fd < 0) return error.OpenArchiveFailed;
@@ -208,7 +205,7 @@ fn openDirectory(root: c_int, path: []const u8) !c_int {
while (parts.next()) |part| {
if (part.len == 0) continue;
var buf: [4096]u8 = undefined;
- const name = try std.fmt.bufPrintZ(&buf, "{s}", .{part});
+ const name = try std.fmt.bufPrintSentinel(&buf, "{s}", .{part}, 0);
if (c.mkdirat(fd, name, @as(c_uint, 0o700)) != 0 and std.c._errno().* != c.EEXIST) return error.WriteFailed;
const next = c.openat(fd, name, c.O_RDONLY | c.O_DIRECTORY | c.O_NOFOLLOW | c.O_CLOEXEC);
if (next < 0) return error.UnsafeArchivePath;
@@ -250,7 +247,7 @@ fn resolveLink(mem: Allocator, links: *const Links, path: []const u8, resolved:
pub fn extract(mem: Allocator, path: []const u8, destination: []const u8, member: ?[]const u8, cancel: *const Cancel) !void {
const reader = try Reader.open(mem, path, cancel);
defer reader.close();
- const zdest = try mem.dupeZ(u8, destination);
+ const zdest = try mem.dupeSentinel(u8, destination, 0);
defer mem.free(zdest);
const root = c.open(zdest, c.O_RDONLY | c.O_DIRECTORY | c.O_NOFOLLOW | c.O_CLOEXEC);
if (root < 0) return error.WriteFailed;
@@ -284,7 +281,7 @@ pub fn extract(mem: Allocator, path: []const u8, destination: []const u8, member
const parent = try openDirectory(root, if (kind == c.S_IFDIR) name else std.fs.path.dirname(name) orelse "");
defer _ = c.close(parent);
if (kind == c.S_IFDIR) continue;
- const zname = try mem.dupeZ(u8, std.fs.path.basename(name));
+ const zname = try mem.dupeSentinel(u8, std.fs.path.basename(name), 0);
defer mem.free(zname);
const fd = c.openat(parent, zname, c.O_WRONLY | c.O_CREAT | c.O_EXCL | c.O_NOFOLLOW | c.O_CLOEXEC, @as(c_uint, 0o600));
if (fd < 0) return error.WriteFailed;
@@ -327,9 +324,9 @@ pub fn extract(mem: Allocator, path: []const u8, destination: []const u8, member
try check(cancel);
const parent = try openDirectory(root, std.fs.path.dirname(link.key_ptr.*) orelse "");
defer _ = c.close(parent);
- const name = try mem.dupeZ(u8, std.fs.path.basename(link.key_ptr.*));
+ const name = try mem.dupeSentinel(u8, std.fs.path.basename(link.key_ptr.*), 0);
defer mem.free(name);
- const target = try mem.dupeZ(u8, link.value_ptr.*);
+ const target = try mem.dupeSentinel(u8, link.value_ptr.*, 0);
defer mem.free(target);
if (c.symlinkat(target, parent, name) != 0) return error.WriteFailed;
}
diff --git a/src/files/archive_tests.zig b/src/files/archive_tests.zig
index 432a8f6..6cdd24e 100644
--- a/src/files/archive_tests.zig
+++ b/src/files/archive_tests.zig
@@ -59,10 +59,7 @@ pub fn writeArchiveFixture(path: []const u8, names: []const [:0]const u8) !void
pub const ArchiveLinkFixture = struct { name: [:0]const u8, target: [:0]const u8 };
pub fn writeArchiveFixtureLinks(path: []const u8, names: []const [:0]const u8, links: []const ArchiveLinkFixture) !void {
- const api = @cImport({
- @cInclude("archive.h");
- @cInclude("archive_entry.h");
- });
+ const api = @import("c_archive");
const writer = api.archive_write_new() orelse return error.OutOfMemory;
defer _ = api.archive_write_free(writer);
if (std.mem.endsWith(u8, path, ".zip")) {
@@ -71,7 +68,7 @@ pub fn writeArchiveFixtureLinks(path: []const u8, names: []const [:0]const u8, l
try std.testing.expectEqual(@as(c_int, 0), api.archive_write_set_format_pax_restricted(writer));
try std.testing.expectEqual(@as(c_int, 0), api.archive_write_add_filter_gzip(writer));
}
- const zpath = try std.testing.allocator.dupeZ(u8, path);
+ const zpath = try std.testing.allocator.dupeSentinel(u8, path, 0);
defer std.testing.allocator.free(zpath);
try std.testing.expectEqual(@as(c_int, 0), api.archive_write_open_filename(writer, zpath));
for (names) |name| {
diff --git a/src/files/associations.zig b/src/files/associations.zig
index 9e39bdf..970d6a4 100644
--- a/src/files/associations.zig
+++ b/src/files/associations.zig
@@ -155,9 +155,9 @@ pub const Applications = struct {
const a = self.arena.allocator();
const owned = try a.alloc([:0]const u8, paths.len);
for (paths, 0..) |path, i| {
- owned[i] = try a.dupeZ(u8, path);
+ owned[i] = try a.dupeSentinel(u8, path, 0);
const kind = mime_db.guess(owned[i]);
- if (i == 0) self.content_type = try a.dupeZ(u8, kind) else if (!std.mem.eql(u8, self.content_type, kind)) self.same_type = false;
+ if (i == 0) self.content_type = try a.dupeSentinel(u8, kind, 0) else if (!std.mem.eql(u8, self.content_type, kind)) self.same_type = false;
}
self.paths = owned;
const default = if (self.same_type) g_app_info_get_default_for_type(self.content_type, 0) else null;
@@ -252,7 +252,7 @@ extern fn g_app_info_get_id(app: *anyopaque) ?[*:0]const u8;
/// Launch through the same MIME default that Open With displays. A URI-based
/// launch can pick the handler for file:// instead of the file's content type.
pub fn launchDefault(path: []const u8) !void {
- const filename = try std.heap.c_allocator.dupeZ(u8, path);
+ const filename = try std.heap.c_allocator.dupeSentinel(u8, path, 0);
defer std.heap.c_allocator.free(filename);
var kind: TypeZ = undefined;
const content_type = kind.set(mime_db.guess(filename)) orelse return error.NoDefaultApplication;
@@ -266,7 +266,7 @@ pub fn launchDefault(path: []const u8) !void {
/// Keep the bundled PDF viewer fallback, but honor an explicit alternative.
pub fn hasAlternativeDefault(path: []const u8, bundled_id: []const u8) bool {
- const filename = std.heap.c_allocator.dupeZ(u8, path) catch return false;
+ const filename = std.heap.c_allocator.dupeSentinel(u8, path, 0) catch return false;
defer std.heap.c_allocator.free(filename);
var kind: TypeZ = undefined;
const content_type = kind.set(mime_db.guess(filename)) orelse return false;
diff --git a/src/files/c.zig b/src/files/c.zig
index d6e4b35..cde6b9a 100644
--- a/src/files/c.zig
+++ b/src/files/c.zig
@@ -1,26 +1 @@
-pub const api = @cImport({
- // Translate libc declarations, not glibc's fortified inline wrappers: Zig
- // 0.16 rejects their attribute(error) calls in ReleaseSafe. This affects
- // this import only; Zig runtime safety and separately compiled C stay on.
- @cUndef("_FORTIFY_SOURCE");
- @cDefine("_GNU_SOURCE", "1");
- @cInclude("cairo.h");
- @cInclude("sys/mman.h");
- @cInclude("sys/inotify.h");
- @cInclude("sys/eventfd.h");
- @cInclude("sys/stat.h");
- @cInclude("poll.h");
- @cInclude("unistd.h");
- @cInclude("pwd.h");
- @cInclude("grp.h");
- @cInclude("fcntl.h");
- @cInclude("pthread.h");
- @cInclude("time.h");
- @cInclude("stdlib.h");
- @cInclude("errno.h");
- @cInclude("dirent.h");
- @cInclude("stdio.h");
- @cInclude("signal.h");
- @cInclude("xkbcommon/xkbcommon.h");
- @cInclude("xkbcommon/xkbcommon-keysyms.h");
-});
+pub const api = @import("c_gfx");
diff --git a/src/files/chooser.zig b/src/files/chooser.zig
index f02bbbb..e727edc 100644
--- a/src/files/chooser.zig
+++ b/src/files/chooser.zig
@@ -1,9 +1,7 @@
//! Shared contract between the portal backend and Files' chooser mode.
const std = @import("std");
const mime_db = @import("../mime_db.zig");
-const c = @cImport({
- @cInclude("fnmatch.h");
-});
+const c = @import("c");
pub const Mode = enum { open, save, folder };
pub const Rule = struct { kind: u32, value: []const u8 };
@@ -31,10 +29,10 @@ pub const Result = struct {
pub fn matches(filter: Filter, name: []const u8) bool {
var name_buf: [4096]u8 = undefined;
- const zname = std.fmt.bufPrintZ(&name_buf, "{s}", .{name}) catch return false;
+ const zname = std.fmt.bufPrintSentinel(&name_buf, "{s}", .{name}, 0) catch return false;
for (filter.rules) |rule| {
var buf: [4096]u8 = undefined;
- const pattern = std.fmt.bufPrintZ(&buf, "{s}", .{rule.value}) catch continue;
+ const pattern = std.fmt.bufPrintSentinel(&buf, "{s}", .{rule.value}, 0) catch continue;
if (rule.kind == 0) {
if (c.fnmatch(pattern, zname, 0) == 0) return true;
} else if (rule.kind == 1) {
diff --git a/src/files/client_dnd.zig b/src/files/client_dnd.zig
index 76c372f..3601a58 100644
--- a/src/files/client_dnd.zig
+++ b/src/files/client_dnd.zig
@@ -135,7 +135,7 @@ pub fn startDropReceive(self: *Client, offer: *Offer, slot: ?usize, target: []co
}
pub fn canonicalPath(path: []const u8) ![]u8 {
- const terminated = try a.dupeZ(u8, path);
+ const terminated = try a.dupeSentinel(u8, path, 0);
defer a.free(terminated);
var buffer: [4096]u8 = undefined;
const resolved = c.realpath(terminated, &buffer) orelse return error.InvalidPath;
diff --git a/src/files/collation.zig b/src/files/collation.zig
index 6385d4f..f32e334 100644
--- a/src/files/collation.zig
+++ b/src/files/collation.zig
@@ -1,12 +1,7 @@
//! Private name collation. Keys are frozen with each listing so UI sorting
//! never calls libc, changes the process locale or races a worker update.
const std = @import("std");
-const c = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- @cDefine("_GNU_SOURCE", "1");
- @cInclude("locale.h");
- @cInclude("string.h");
-});
+const c = @import("c");
pub const Locale = struct {
handle: c.locale_t,
@@ -50,7 +45,7 @@ pub const Locale = struct {
// key instead of passing malformed multibyte sequences to libc.
if (!std.unicode.utf8ValidateSlice(text) or std.mem.indexOfScalar(u8, text, 0) != null) return allocator.dupe(u8, text);
var source_buffer: [1024]u8 = undefined;
- const owned_source = if (text.len >= source_buffer.len) try allocator.dupeZ(u8, text) else null;
+ const owned_source = if (text.len >= source_buffer.len) try allocator.dupeSentinel(u8, text, 0) else null;
defer if (owned_source) |owned| allocator.free(owned);
const ztext: [:0]const u8 = owned_source orelse blk: {
@memcpy(source_buffer[0..text.len], text);
diff --git a/src/files/dirsize.zig b/src/files/dirsize.zig
index e43ba84..8066845 100644
--- a/src/files/dirsize.zig
+++ b/src/files/dirsize.zig
@@ -212,7 +212,7 @@ pub const Pool = struct {
pub fn startJob(self: *Pool, path: []const u8) !*Job {
var path_buf: [4096]u8 = undefined;
- const path_z = try std.fmt.bufPrintZ(&path_buf, "{s}", .{path});
+ const path_z = try std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0);
const root_fd = c.open(path_z, c.O_RDONLY | c.O_DIRECTORY | c.O_NOFOLLOW | c.O_CLOEXEC);
if (root_fd < 0) {
@@ -334,7 +334,7 @@ fn walkDirectory(pool: *Pool, ctx: *WorkerContext, job: *Job, dir_fd: c_int, dep
while (true) {
if (job.cancelled.load(.acquire)) return;
- const rc = linux.getdents64(dir_fd, buf.ptr, buf.len);
+ const rc = linux.getdents64(dir_fd, buf.ptr, @intCast(buf.len));
const err = linux.errno(rc);
if (err != .SUCCESS) {
if (err != .NOENT and err != .BADF) {
diff --git a/src/files/dirsize_tests.zig b/src/files/dirsize_tests.zig
index 49f6c29..e26e798 100644
--- a/src/files/dirsize_tests.zig
+++ b/src/files/dirsize_tests.zig
@@ -95,11 +95,11 @@ test "dirsize: a hardlink pair is counted once" {
defer a.free(f1);
try writeTestFile(f1, "hardlink payload");
- const f1_z = try a.dupeZ(u8, f1);
+ const f1_z = try a.dupeSentinel(u8, f1, 0);
defer a.free(f1_z);
const f2 = try std.fmt.allocPrint(a, "{s}/file2_hardlink.txt", .{tmp});
defer a.free(f2);
- const f2_z = try a.dupeZ(u8, f2);
+ const f2_z = try a.dupeSentinel(u8, f2, 0);
defer a.free(f2_z);
try std.testing.expect(c.link(f1_z, f2_z) == 0);
diff --git a/src/files/git.zig b/src/files/git.zig
index c696110..ec766cc 100644
--- a/src/files/git.zig
+++ b/src/files/git.zig
@@ -307,7 +307,7 @@ pub fn switchBranch(mem: Allocator, io: std.Io, environ: std.process.Environ, di
pub fn scan(mem: Allocator, io: std.Io, environ: std.process.Environ, dir: []const u8) !?Repository {
var canonical: [std.fs.max_path_bytes]u8 = undefined;
- const zdir = try mem.dupeZ(u8, dir);
+ const zdir = try mem.dupeSentinel(u8, dir, 0);
defer mem.free(zdir);
if (c.realpath(zdir, &canonical) == null) return null;
const directory = try mem.dupe(u8, std.mem.sliceTo(&canonical, 0));
diff --git a/src/files/ops.zig b/src/files/ops.zig
index ba4196c..4216e9d 100644
--- a/src/files/ops.zig
+++ b/src/files/ops.zig
@@ -99,7 +99,7 @@ pub fn renameItem(allocator: Allocator, old_path: []const u8, new_name: []const
const new_path = try std.fmt.allocPrintSentinel(allocator, "{s}/{s}", .{ parent, new_name }, 0);
defer allocator.free(new_path);
- const old_z = try allocator.dupeZ(u8, old_path);
+ const old_z = try allocator.dupeSentinel(u8, old_path, 0);
defer allocator.free(old_z);
if (c.renameat2(c.AT_FDCWD, old_z, c.AT_FDCWD, new_path, 1) != 0) {
@@ -159,8 +159,8 @@ pub fn isDescendantOrSame(src: []const u8, dst: []const u8) bool {
var src_buf: [4096]u8 = undefined;
var dst_buf: [4096]u8 = undefined;
- const src_z = std.fmt.bufPrintZ(&src_buf, "{s}", .{src}) catch return false;
- const dst_z = std.fmt.bufPrintZ(&dst_buf, "{s}", .{dst}) catch return false;
+ const src_z = std.fmt.bufPrintSentinel(&src_buf, "{s}", .{src}, 0) catch return false;
+ const dst_z = std.fmt.bufPrintSentinel(&dst_buf, "{s}", .{dst}, 0) catch return false;
var src_st: c.struct_stat = undefined;
var dst_st: c.struct_stat = undefined;
@@ -173,7 +173,7 @@ pub fn isDescendantOrSame(src: []const u8, dst: []const u8) bool {
while (std.fs.path.dirname(cur)) |p| {
if (std.mem.eql(u8, p, cur)) break;
var p_buf: [4096]u8 = undefined;
- const p_z = std.fmt.bufPrintZ(&p_buf, "{s}", .{p}) catch break;
+ const p_z = std.fmt.bufPrintSentinel(&p_buf, "{s}", .{p}, 0) catch break;
var p_st: c.struct_stat = undefined;
if (c.stat(p_z, &p_st) == 0) {
if (p_st.st_dev == src_st.st_dev and p_st.st_ino == src_st.st_ino) return true;
@@ -185,7 +185,7 @@ pub fn isDescendantOrSame(src: []const u8, dst: []const u8) bool {
pub fn generateUniqueName(allocator: Allocator, dest_dir: []const u8, original_name: []const u8) ![]u8 {
var path_buf: [4096]u8 = undefined;
- const initial_z = try std.fmt.bufPrintZ(&path_buf, "{s}/{s}", .{ dest_dir, original_name });
+ const initial_z = try std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ dest_dir, original_name }, 0);
var st: c.struct_stat = undefined;
if (c.lstat(initial_z, &st) != 0) {
return try allocator.dupe(u8, original_name);
@@ -205,7 +205,7 @@ pub fn generateUniqueName(allocator: Allocator, dest_dir: []const u8, original_n
var count: usize = 1;
while (count < 10000) : (count += 1) {
const candidate = try std.fmt.allocPrint(allocator, "{s} ({d}){s}", .{ stem, count, ext });
- const cand_z = std.fmt.bufPrintZ(&path_buf, "{s}/{s}", .{ dest_dir, candidate }) catch {
+ const cand_z = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ dest_dir, candidate }, 0) catch {
allocator.free(candidate);
return error.PathTooLong;
};
@@ -218,9 +218,9 @@ pub fn generateUniqueName(allocator: Allocator, dest_dir: []const u8, original_n
}
pub fn copyFileContents(allocator: Allocator, src_path: []const u8, dst_path: []const u8, cancel: ?*std.atomic.Value(bool)) !void {
- const src_z = try allocator.dupeZ(u8, src_path);
+ const src_z = try allocator.dupeSentinel(u8, src_path, 0);
defer allocator.free(src_z);
- const dst_z = try allocator.dupeZ(u8, dst_path);
+ const dst_z = try allocator.dupeSentinel(u8, dst_path, 0);
defer allocator.free(dst_z);
const src_fd = c.open(src_z, c.O_RDONLY | c.O_CLOEXEC);
@@ -263,9 +263,9 @@ pub fn copyFileContents(allocator: Allocator, src_path: []const u8, dst_path: []
}
pub fn copySymlink(allocator: Allocator, src_path: []const u8, dst_path: []const u8) !void {
- const src_z = try allocator.dupeZ(u8, src_path);
+ const src_z = try allocator.dupeSentinel(u8, src_path, 0);
defer allocator.free(src_z);
- const dst_z = try allocator.dupeZ(u8, dst_path);
+ const dst_z = try allocator.dupeSentinel(u8, dst_path, 0);
defer allocator.free(dst_z);
var target_buf: [4096]u8 = undefined;
@@ -279,7 +279,7 @@ pub fn copySymlink(allocator: Allocator, src_path: []const u8, dst_path: []const
pub fn copyRecursive(allocator: Allocator, src: []const u8, dst: []const u8, cancel: ?*std.atomic.Value(bool)) !void {
if (cancel != null and cancel.?.load(.acquire)) return error.Cancelled;
- const src_z = try allocator.dupeZ(u8, src);
+ const src_z = try allocator.dupeSentinel(u8, src, 0);
defer allocator.free(src_z);
var st: c.struct_stat = undefined;
@@ -289,7 +289,7 @@ pub fn copyRecursive(allocator: Allocator, src: []const u8, dst: []const u8, can
if (fmt == c.S_IFLNK) {
return copySymlink(allocator, src, dst);
} else if (fmt == c.S_IFDIR) {
- const dst_z = try allocator.dupeZ(u8, dst);
+ const dst_z = try allocator.dupeSentinel(u8, dst, 0);
defer allocator.free(dst_z);
if (c.mkdir(dst_z, @as(c_uint, @intCast(st.st_mode & 0o7777))) != 0) return error.CreateDirectoryFailed;
@@ -322,7 +322,7 @@ pub fn copyRecursive(allocator: Allocator, src: []const u8, dst: []const u8, can
}
pub fn deleteRecursive(allocator: Allocator, path: []const u8) !void {
- const path_z = try allocator.dupeZ(u8, path);
+ const path_z = try allocator.dupeSentinel(u8, path, 0);
defer allocator.free(path_z);
var st: c.struct_stat = undefined;
@@ -372,9 +372,9 @@ pub fn moveItem(allocator: Allocator, src: []const u8, dst: []const u8, cancel:
if (isDescendantOrSame(src, dst)) return error.CannotMoveIntoDescendant;
if (std.mem.eql(u8, src, dst)) return;
- const src_z = try allocator.dupeZ(u8, src);
+ const src_z = try allocator.dupeSentinel(u8, src, 0);
defer allocator.free(src_z);
- const dst_z = try allocator.dupeZ(u8, dst);
+ const dst_z = try allocator.dupeSentinel(u8, dst, 0);
defer allocator.free(dst_z);
if (c.renameat2(c.AT_FDCWD, src_z, c.AT_FDCWD, dst_z, 1) == 0) {
@@ -602,7 +602,7 @@ pub const JobRunner = struct {
var target = try std.fmt.allocPrint(self.allocator, "{s}/{s}", .{ self.dest_dir, name });
defer self.allocator.free(target);
var buf: [4096]u8 = undefined;
- const target_z = try std.fmt.bufPrintZ(&buf, "{s}", .{target});
+ const target_z = try std.fmt.bufPrintSentinel(&buf, "{s}", .{target}, 0);
var st: c.struct_stat = undefined;
if (c.lstat(target_z, &st) == 0) {
var action = self.default_conflict;
@@ -661,7 +661,7 @@ pub const JobRunner = struct {
self.result_path = path;
return .success;
}
- const zstage = try self.allocator.dupeZ(u8, stage);
+ const zstage = try self.allocator.dupeSentinel(u8, stage, 0);
defer self.allocator.free(zstage);
const dir = c.opendir(zstage) orelse return error.OpenDirectoryFailed;
defer _ = c.closedir(dir);
diff --git a/src/files/ops_tests.zig b/src/files/ops_tests.zig
index 6be678e..54a1934 100644
--- a/src/files/ops_tests.zig
+++ b/src/files/ops_tests.zig
@@ -9,7 +9,7 @@ const makeTestDir = files_tests.makeTestDir;
pub fn writeTestFile(path: []const u8, content: []const u8) !void {
var path_buf: [4096]u8 = undefined;
- const path_z = try std.fmt.bufPrintZ(&path_buf, "{s}", .{path});
+ const path_z = try std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0);
const fd = c.open(path_z, c.O_WRONLY | c.O_CREAT | c.O_TRUNC | c.O_CLOEXEC, @as(c_uint, 0o644));
if (fd < 0) return error.WriteFileFailed;
defer _ = c.close(fd);
@@ -23,7 +23,7 @@ pub fn writeTestFile(path: []const u8, content: []const u8) !void {
pub fn readTestFile(path: []const u8, buf: []u8) ![]u8 {
var path_buf: [4096]u8 = undefined;
- const path_z = try std.fmt.bufPrintZ(&path_buf, "{s}", .{path});
+ const path_z = try std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0);
const fd = c.open(path_z, c.O_RDONLY | c.O_CLOEXEC);
if (fd < 0) return error.OpenFileFailed;
defer _ = c.close(fd);
@@ -34,7 +34,7 @@ pub fn readTestFile(path: []const u8, buf: []u8) ![]u8 {
pub fn testFileExists(path: []const u8) bool {
var path_buf: [4096]u8 = undefined;
- const path_z = std.fmt.bufPrintZ(&path_buf, "{s}", .{path}) catch return false;
+ const path_z = std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0) catch return false;
var st: c.struct_stat = undefined;
return c.stat(path_z, &st) == 0;
}
@@ -72,7 +72,7 @@ test "copyRecursive and copySymlink" {
// Create symlink inside sub
const link_src = try std.fmt.allocPrint(allocator, "{s}/link_to_file1", .{sub_dir});
defer allocator.free(link_src);
- const link_src_z = try allocator.dupeZ(u8, link_src);
+ const link_src_z = try allocator.dupeSentinel(u8, link_src, 0);
defer allocator.free(link_src_z);
_ = c.symlink("../file1.txt", link_src_z);
@@ -98,7 +98,7 @@ test "copyRecursive and copySymlink" {
// Verify symlink target was preserved
const dst_link = try std.fmt.allocPrint(allocator, "{s}/sub/link_to_file1", .{dst_dir});
defer allocator.free(dst_link);
- const dst_link_z = try allocator.dupeZ(u8, dst_link);
+ const dst_link_z = try allocator.dupeSentinel(u8, dst_link, 0);
defer allocator.free(dst_link_z);
var target_buf: [256]u8 = undefined;
const link_len = c.readlink(dst_link_z, &target_buf, target_buf.len);
diff --git a/src/files/properties.zig b/src/files/properties.zig
index 9f00e40..a3901b8 100644
--- a/src/files/properties.zig
+++ b/src/files/properties.zig
@@ -83,7 +83,7 @@ pub const State = struct {
}
pub fn init(a: std.mem.Allocator, path: []const u8, preview: ?icons.Entry) !State {
- const owned = try a.dupeZ(u8, path);
+ const owned = try a.dupeSentinel(u8, path, 0);
errdefer a.free(owned);
// O_PATH pins the inode without reading a file, opening a device or
// blocking on a FIFO. A symlink describes the link itself.
@@ -131,7 +131,7 @@ pub const State = struct {
return;
}
var buf: [64]u8 = undefined;
- const pinned = std.fmt.bufPrintZ(&buf, "/proc/self/fd/{d}", .{self.fd}) catch unreachable;
+ const pinned = std.fmt.bufPrintSentinel(&buf, "/proc/self/fd/{d}", .{self.fd}, 0) catch unreachable;
if (c.chmod(pinned, (self.stat.st_mode & 0o7777) ^ permissionBit(index)) != 0) {
self.message = tr("Could not change permissions");
return;
diff --git a/src/files/recent.zig b/src/files/recent.zig
index 92c9949..5624181 100644
--- a/src/files/recent.zig
+++ b/src/files/recent.zig
@@ -71,7 +71,7 @@ pub fn read(a: Allocator, io: std.Io, env: std.process.Environ) ![]Entry {
defer a.free(decoded);
const date = g_bookmark_file_get_visited_date_time(bookmark, uri, null) orelse
g_bookmark_file_get_modified_date_time(bookmark, uri, null);
- const owned = try a.dupeZ(u8, decoded);
+ const owned = try a.dupeSentinel(u8, decoded, 0);
errdefer a.free(owned);
// Bookmark date getters return borrowed values.
try entries.append(a, .{ .path = owned, .opened = if (date) |d| g_date_time_to_unix(d) else 0 });
@@ -88,9 +88,9 @@ pub fn record(a: Allocator, io: std.Io, env: std.process.Environ, opened: []cons
defer g_bookmark_file_free(bookmark);
const raw_uri = try clipboard.encodeLocalUri(a, opened);
defer a.free(raw_uri);
- const uri = try a.dupeZ(u8, raw_uri);
+ const uri = try a.dupeSentinel(u8, raw_uri, 0);
defer a.free(uri);
- const mime = try a.dupeZ(u8, mime_db.guess(opened));
+ const mime = try a.dupeSentinel(u8, mime_db.guess(opened), 0);
defer a.free(mime);
g_bookmark_file_set_mime_type(bookmark, uri, mime);
g_bookmark_file_add_application(bookmark, uri, "RediWM Files", "rediwm-files %f");
diff --git a/src/files/settings.zig b/src/files/settings.zig
index b9f6975..d4e9be1 100644
--- a/src/files/settings.zig
+++ b/src/files/settings.zig
@@ -99,8 +99,8 @@ pub const Settings = struct {
defer if (path) |p| a.free(p);
var self: Settings = .{ .env = env };
errdefer self.deinit(a);
- if (path) |p| self.config_path = try a.dupeZ(u8, p);
- if (theme.resolvePath(env)) |p| self.theme_path = try a.dupeZ(u8, p);
+ if (path) |p| self.config_path = try a.dupeSentinel(u8, p, 0);
+ if (theme.resolvePath(env)) |p| self.theme_path = try a.dupeSentinel(u8, p, 0);
return self;
}
@@ -118,7 +118,7 @@ pub const Settings = struct {
var parent = std.fs.path.dirname(maybe_path orelse continue) orelse continue;
while (true) {
var buf: [4096]u8 = undefined;
- const path = std.fmt.bufPrintZ(&buf, "{s}", .{parent}) catch break;
+ const path = std.fmt.bufPrintSentinel(&buf, "{s}", .{parent}, 0) catch break;
if (c.inotify_add_watch(fd, path, c.IN_CLOSE_WRITE | c.IN_MOVED_TO | c.IN_CREATE | c.IN_DELETE | c.IN_DELETE_SELF | c.IN_MOVE_SELF) >= 0) break;
parent = std.fs.path.dirname(parent) orelse break;
}
diff --git a/src/files/terminal/model.zig b/src/files/terminal/model.zig
index 83a4bf0..7dc9a93 100644
--- a/src/files/terminal/model.zig
+++ b/src/files/terminal/model.zig
@@ -1,11 +1,7 @@
//! Session and drawer state, owned by one Files window.
const std = @import("std");
const ui = @import("ui");
-pub const c = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- if (@import("builtin").is_test) @cDefine("FT_TEST", "1");
- @cInclude("engine.h");
-});
+pub const c = @import("c_terminal");
pub const Point = struct { line: i64, col: i32 };
pub const Selection = struct {
anchor: Point,
diff --git a/src/files/thumb_decode.zig b/src/files/thumb_decode.zig
index 1711619..8824784 100644
--- a/src/files/thumb_decode.zig
+++ b/src/files/thumb_decode.zig
@@ -5,9 +5,7 @@
const std = @import("std");
const c = @import("c.zig").api;
const decode = @import("../images/decode.zig");
-const tc = @cImport({
- @cInclude("thumb_codec.h");
-});
+const tc = @import("c_thumb_codec");
const a = std.heap.c_allocator;
@@ -224,7 +222,7 @@ pub fn uriHash(uri: []const u8) [32]u8 {
/// A cached thumbnail's path: `<cache>/thumbnails/<size>/<md5>.png`.
fn sharedPath(buf: []u8, ctx: Context, size_dir: []const u8, hash: *const [32]u8) ?[:0]u8 {
const root = ctx.cache_dir orelse return null;
- return std.fmt.bufPrintZ(buf, "{s}/thumbnails/{s}/{s}.png", .{ root, size_dir, hash }) catch null;
+ return std.fmt.bufPrintSentinel(buf, "{s}/thumbnails/{s}/{s}.png", .{ root, size_dir, hash }, 0) catch null;
}
fn readShared(ctx: Context, path: []const u8, mtime: i64, size: i64) ?Decoded {
@@ -262,7 +260,7 @@ pub fn writeShared(ctx: Context, path: []const u8, decoded: Decoded) void {
var uri: std.ArrayList(u8) = .empty;
defer uri.deinit(a);
fileUri(&uri, a, path) catch return;
- const uri_z = a.dupeZ(u8, uri.items) catch return;
+ const uri_z = a.dupeSentinel(u8, uri.items, 0) catch return;
defer a.free(uri_z);
const hash = uriHash(uri.items);
@@ -272,7 +270,7 @@ pub fn writeShared(ctx: Context, path: []const u8, decoded: Decoded) void {
var final_buf: [std.fs.max_path_bytes]u8 = undefined;
const final = sharedPath(&final_buf, ctx, "normal", &hash) orelse return;
var tmp_buf: [std.fs.max_path_bytes]u8 = undefined;
- const tmp = std.fmt.bufPrintZ(&tmp_buf, "{s}/thumbnails/normal/{s}.{d}.tmp", .{ root, &hash, c.getpid() }) catch return;
+ const tmp = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/thumbnails/normal/{s}.{d}.tmp", .{ root, &hash, c.getpid() }, 0) catch return;
_ = c.unlink(tmp.ptr);
if (tc.tc_png_write(tmp.ptr, decoded.pixels.ptr, decoded.w, decoded.h, uri_z.ptr, decoded.file_mtime, decoded.file_size) != 0) return;
if (c.rename(tmp.ptr, final.ptr) != 0) _ = c.unlink(tmp.ptr);
diff --git a/src/files/thumbs.zig b/src/files/thumbs.zig
index 17849b4..23f203f 100644
--- a/src/files/thumbs.zig
+++ b/src/files/thumbs.zig
@@ -178,7 +178,7 @@ pub const Service = struct {
self.queue.clearRetainingCapacity();
for (wants) |want| {
if (self.resolved(want) or self.inFlight(want)) continue;
- const path = a.dupeZ(u8, want.path) catch continue;
+ const path = a.dupeSentinel(u8, want.path, 0) catch continue;
self.queue.append(a, .{ .path = path, .mtime = want.mtime, .bytes = want.bytes, .is_symlink = want.is_symlink }) catch {
a.free(path);
continue;
@@ -380,7 +380,7 @@ const TestDir = struct {
fn init() !TestDir {
var template = "/tmp/rediwm-thumbs-XXXXXX".*;
const made = c.mkdtemp(&template) orelse return error.TmpDirFailed;
- return .{ .path = try std.testing.allocator.dupeZ(u8, std.mem.span(made)) };
+ return .{ .path = try std.testing.allocator.dupeSentinel(u8, std.mem.span(made), 0) };
}
fn file(self: TestDir, name: []const u8) ![:0]u8 {
@@ -389,7 +389,7 @@ const TestDir = struct {
fn deinit(self: TestDir) void {
var cmd: [256]u8 = undefined;
- const text = std.fmt.bufPrintZ(&cmd, "rm -rf '{s}'", .{self.path}) catch unreachable;
+ const text = std.fmt.bufPrintSentinel(&cmd, "rm -rf '{s}'", .{self.path}, 0) catch unreachable;
_ = c.system(text.ptr);
std.testing.allocator.free(self.path);
}
@@ -552,7 +552,7 @@ test "least recently used rasters are evicted first" {
defer service.deinit();
const names = [_][]const u8{ "/x/a.png", "/x/b.png", "/x/c.png" };
for (names) |name| {
- const key = try a.dupeZ(u8, name);
+ const key = try a.dupeSentinel(u8, name, 0);
const pixels = try a.alloc(u32, 4);
@memset(pixels, 0xff00ff00);
try service.entries.put(a, key, .{ .pixels = pixels, .w = 2, .h = 2, .mtime = 1, .bytes = 1, .tick = service.nextTick() });
@@ -563,7 +563,7 @@ test "least recently used rasters are evicted first" {
// 40 bytes under the budget, leaving the three small ones 8 bytes over it.
const big = try a.alloc(u32, (max_bytes - 40) / 4);
@memset(big, 0);
- try service.entries.put(a, try a.dupeZ(u8, "/x/big.png"), .{ .pixels = big, .w = 1, .h = 1, .mtime = 1, .bytes = 1, .tick = service.nextTick() });
+ try service.entries.put(a, try a.dupeSentinel(u8, "/x/big.png", 0), .{ .pixels = big, .w = 1, .h = 1, .mtime = 1, .bytes = 1, .tick = service.nextTick() });
service.bytes += big.len * 4;
service.evict();
try std.testing.expect(service.bytes <= max_bytes);
diff --git a/src/files/torrents.zig b/src/files/torrents.zig
index 41a6a80..129952f 100644
--- a/src/files/torrents.zig
+++ b/src/files/torrents.zig
@@ -1,13 +1,7 @@
//! Bounded, nonblocking client for the per-user transfer helper.
const std = @import("std");
const tr = @import("i18n").tr;
-const c = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- @cDefine("_GNU_SOURCE", "1");
- @cInclude("sys/socket.h");
- @cInclude("sys/un.h");
- @cInclude("unistd.h");
-});
+const c = @import("c");
pub const File = struct { index: usize, path: []const u8, size: i64 };
pub const Transfer = struct {
source: []const u8 = "",
@@ -66,7 +60,7 @@ pub const Client = struct {
pub fn connect(self: *Client, runtime: []const u8) bool {
var address: c.struct_sockaddr_un = std.mem.zeroes(c.struct_sockaddr_un);
address.sun_family = c.AF_UNIX;
- _ = std.fmt.bufPrintZ(@ptrCast(&address.sun_path), "{s}/files-transfers.sock", .{runtime}) catch return false;
+ _ = std.fmt.bufPrintSentinel(@ptrCast(&address.sun_path), "{s}/files-transfers.sock", .{runtime}, 0) catch return false;
const fd = c.socket(c.AF_UNIX, c.SOCK_SEQPACKET | c.SOCK_NONBLOCK | c.SOCK_CLOEXEC, 0);
if (fd < 0) return false;
if (c.connect(fd, .{ .__sockaddr__ = @ptrCast(&address) }, @sizeOf(@TypeOf(address))) != 0) {
diff --git a/src/files/volumes.zig b/src/files/volumes.zig
index 2ff5257..c404805 100644
--- a/src/files/volumes.zig
+++ b/src/files/volumes.zig
@@ -6,9 +6,7 @@
const std = @import("std");
const i18n = @import("i18n");
const tr = i18n.tr;
-const c = @cImport({
- @cInclude("volumes.h");
-});
+const c = @import("c_volumes");
pub const Kind = enum {
/// Flash media: USB sticks and memory cards.
diff --git a/src/files/worker.zig b/src/files/worker.zig
index daee6c1..ff607df 100644
--- a/src/files/worker.zig
+++ b/src/files/worker.zig
@@ -385,7 +385,7 @@ pub const Worker = struct {
defer if (recent_path) |p| self.allocator.free(p);
var watch_path = if (recent_path) |p| std.fs.path.dirname(p).? else if (cur_archive_len > 0) std.fs.path.dirname(cur_dir[0..cur_archive_len]) orelse "/" else watched_dir.?;
while (true) {
- const zp = std.fmt.bufPrintZ(&zpath_buf, "{s}", .{watch_path}) catch break;
+ const zp = std.fmt.bufPrintSentinel(&zpath_buf, "{s}", .{watch_path}, 0) catch break;
inotify_wd = c.inotify_add_watch(
inotify_fd,
zp,
@@ -413,7 +413,7 @@ pub const Worker = struct {
if (inotify_fd >= 0) {
if (snap.repository) |repo| {
for (repo.watch_paths, 0..) |path, i| {
- const zp = snap.arena.allocator().dupeZ(u8, path) catch continue;
+ const zp = snap.arena.allocator().dupeSentinel(u8, path, 0) catch continue;
next_watches[i] = c.inotify_add_watch(inotify_fd, zp, c.IN_CREATE | c.IN_DELETE | c.IN_MOVED_FROM | c.IN_MOVED_TO | c.IN_CLOSE_WRITE | c.IN_DELETE_SELF | c.IN_MOVE_SELF);
}
}
@@ -506,7 +506,7 @@ pub const Worker = struct {
const mem = snap.arena.allocator();
snap.dir = try mem.dupe(u8, path);
const source = path[0..archive_len];
- const zsource = try mem.dupeZ(u8, source);
+ const zsource = try mem.dupeSentinel(u8, source, 0);
var stat: c.struct_stat = undefined;
if (c.stat(zsource, &stat) != 0) return error.OpenArchiveFailed;
if (cache.path == null or !std.mem.eql(u8, cache.path.?, source) or
diff --git a/src/files_main.zig b/src/files_main.zig
index 31a0856..9c35a39 100644
--- a/src/files_main.zig
+++ b/src/files_main.zig
@@ -69,7 +69,7 @@ fn resolveTarget(allocator: std.mem.Allocator, environ: std.process.Environ, tar
errdefer allocator.free(resolved);
var zpath_buf: [4096]u8 = undefined;
- const zpath = std.fmt.bufPrintZ(&zpath_buf, "{s}", .{resolved}) catch return error.NameTooLong;
+ const zpath = std.fmt.bufPrintSentinel(&zpath_buf, "{s}", .{resolved}, 0) catch return error.NameTooLong;
var stat_buf: c.struct_stat = undefined;
if (c.stat(zpath, &stat_buf) != 0) {
@@ -133,7 +133,7 @@ pub fn main(init: std.process.Init) void {
extern fn g_filename_from_uri([*:0]const u8, ?*?[*:0]u8, ?*anyopaque) ?[*:0]u8;
extern fn g_free(?*anyopaque) void;
};
- const raw = Gio.g_filename_from_uri(a.dupeZ(u8, source) catch return, null, null) orelse return;
+ const raw = Gio.g_filename_from_uri(a.dupeSentinel(u8, source, 0) catch return, null, null) orelse return;
defer Gio.g_free(raw);
torrent_source = a.dupe(u8, std.mem.span(raw)) catch return;
} else if (!std.mem.startsWith(u8, source, "magnet:?")) torrent_source = std.fs.path.resolve(a, &.{source}) catch return;
diff --git a/src/global_filter.zig b/src/global_filter.zig
index de8f0c0..beda2a0 100644
--- a/src/global_filter.zig
+++ b/src/global_filter.zig
@@ -50,9 +50,9 @@ pub fn sandboxed(server: *const Server, client: *const wl.Client) bool {
}
pub fn clientAllowedGroups(server: *const Server, client: *const wl.Client) GroupSet {
- const mgr = server.security_context orelse return GroupSet.initEmpty();
- const state = mgr.lookupClient(client) orelse return GroupSet.initEmpty();
- const app_id = if (state.app_id) |s| std.mem.span(s) else return GroupSet.initEmpty();
+ const mgr = server.security_context orelse return GroupSet.empty;
+ const state = mgr.lookupClient(client) orelse return GroupSet.empty;
+ const app_id = if (state.app_id) |s| std.mem.span(s) else return GroupSet.empty;
const engine = if (state.sandbox_engine) |s| std.mem.span(s) else null;
return server.config.sandboxAllowGroups(app_id, engine);
}
@@ -138,7 +138,7 @@ test "privileged table names match generated protocol interface names where avai
}
test "pure filter decision logic" {
- const empty_groups = GroupSet.initEmpty();
+ const empty_groups = GroupSet.empty;
// 1. Un-sandboxed, normal client: sees everything except when Xwayland denies
try std.testing.expect(pureFilterDecision(null, false, empty_groups, "wl_compositor"));
@@ -165,7 +165,7 @@ test "pure filter decision logic" {
try std.testing.expect(!pureFilterDecision(null, true, empty_groups, "xwayland_shell_v1"));
// 4. Sandboxed client with clipboard allowance:
- var clipboard_only = GroupSet.initEmpty();
+ var clipboard_only = GroupSet.empty;
clipboard_only.insert(.clipboard);
try std.testing.expect(pureFilterDecision(null, true, clipboard_only, "zwlr_data_control_manager_v1"));
@@ -174,7 +174,7 @@ test "pure filter decision logic" {
try std.testing.expect(!pureFilterDecision(null, true, clipboard_only, "ext_session_lock_manager_v1"));
// 5. wp_security_context_manager_v1 and xwayland_shell_v1 can never be granted
- const all_groups = GroupSet.initFull();
+ const all_groups = GroupSet.full;
try std.testing.expect(!pureFilterDecision(null, true, all_groups, "wp_security_context_manager_v1"));
try std.testing.expect(!pureFilterDecision(null, true, all_groups, "xwayland_shell_v1"));
}
diff --git a/src/i18n/mod.zig b/src/i18n/mod.zig
index dfccedd..9302eb0 100644
--- a/src/i18n/mod.zig
+++ b/src/i18n/mod.zig
@@ -200,13 +200,13 @@ fn format(writer: *std.Io.Writer, pattern: []const u8, args: anytype) FormatErro
const end = std.mem.indexOfScalarPos(u8, pattern, i + 1, '}') orelse return error.InvalidFormat;
const name = pattern[i + 1 .. end];
var found = false;
- inline for (std.meta.fields(@TypeOf(args))) |field| {
- if (std.mem.eql(u8, name, field.name)) {
- const value = @field(args, field.name);
- switch (@typeInfo(field.type)) {
+ inline for (@typeInfo(@TypeOf(args)).@"struct".field_names) |field_name| {
+ if (std.mem.eql(u8, name, field_name)) {
+ const value = @field(args, field_name);
+ switch (@typeInfo(@FieldType(@TypeOf(args), field_name))) {
.int, .comptime_int, .float, .comptime_float => writer.print("{d}", .{value}) catch return error.NoSpaceLeft,
.pointer, .array => writer.print("{s}", .{value}) catch return error.NoSpaceLeft,
- else => @compileError("i18n argument " ++ field.name ++ " must be string or integer, got " ++ @typeName(field.type)),
+ else => @compileError("i18n argument " ++ field_name ++ " must be string or integer, got " ++ @typeName(@FieldType(@TypeOf(args), field_name))),
}
found = true;
}
diff --git a/src/icon_cache.zig b/src/icon_cache.zig
index 2eafe79..3cd86f3 100644
--- a/src/icon_cache.zig
+++ b/src/icon_cache.zig
@@ -20,10 +20,8 @@ const Io = std.Io;
// file scope, which zig's translate-c cannot parse, and it cascades into
// thousands of unrelated errors. Since only a handful of stable, ABI-frozen
// rsvg/glib/gobject symbols are needed, they're hand-declared below instead
-// of pulled in through @cInclude.
-const c = @cImport({
- @cInclude("cairo.h");
-});
+// of translated from their headers.
+const c = @import("c_gfx");
const GError = opaque {};
const RsvgHandle = opaque {};
@@ -117,13 +115,13 @@ fn lookupScoped(cfg: icon_theme.Config, io: Io, icon_name: []const u8, size_px:
const is_svg = std.mem.endsWith(u8, icon_name, ".svg");
const is_png = std.mem.endsWith(u8, icon_name, ".png");
if (is_svg) {
- const zpath = gpa.dupeZ(u8, icon_name) catch return null;
+ const zpath = gpa.dupeSentinel(u8, icon_name, 0) catch return null;
defer gpa.free(zpath);
const in_pack = cfg.override_root.len > 0 and std.mem.startsWith(u8, icon_name, cfg.override_root) and icon_name.len > cfg.override_root.len and icon_name[cfg.override_root.len] == '/';
const pixels = (if (in_pack) rasterizePackSvg(zpath, io, size_px) else rasterizeSvg(zpath, size_px)) orelse return null;
return Entry{ .pixels = pixels, .size = size_px };
} else if (is_png) {
- const zpath = gpa.dupeZ(u8, icon_name) catch return null;
+ const zpath = gpa.dupeSentinel(u8, icon_name, 0) catch return null;
defer gpa.free(zpath);
if (try loadPng(zpath, io, size_px)) |pixels| {
return Entry{ .pixels = pixels, .size = size_px };
@@ -132,13 +130,13 @@ fn lookupScoped(cfg: icon_theme.Config, io: Io, icon_name: []const u8, size_px:
} else {
var buf: [512]u8 = undefined;
if (std.fmt.bufPrint(&buf, "{s}.svg", .{icon_name})) |svg_path| {
- const zpath = gpa.dupeZ(u8, svg_path) catch return null;
+ const zpath = gpa.dupeSentinel(u8, svg_path, 0) catch return null;
defer gpa.free(zpath);
if (rasterizeSvg(zpath, size_px)) |pixels| {
return Entry{ .pixels = pixels, .size = size_px };
}
} else |_| {}
- if (std.fmt.bufPrintZ(&buf, "{s}.png", .{icon_name})) |png_path| {
+ if (std.fmt.bufPrintSentinel(&buf, "{s}.png", .{icon_name}, 0)) |png_path| {
if (try loadPng(png_path, io, size_px)) |pixels| {
return Entry{ .pixels = pixels, .size = size_px };
}
@@ -418,7 +416,7 @@ test "rectangular PNG icons keep their proportions" {
}
test "shrinking an icon preserves fine detail across each pixel footprint" {
- var src = [_]u32{0} ** 64;
+ var src = @as([64]u32, @splat(0));
src[0] = 0x80800000;
const pixels = try resample(&src, 8, 8, 2);
defer gpa.free(pixels);
diff --git a/src/icon_theme.zig b/src/icon_theme.zig
index b31b7ad..5513130 100644
--- a/src/icon_theme.zig
+++ b/src/icon_theme.zig
@@ -113,7 +113,7 @@ pub fn findPack(allocator: Allocator, io: Io, cfg: Config, icon_name: []const u8
defer allocator.free(rel);
if (@import("config").theme_pack.asset(allocator, io, cfg.override_root, rel)) |path| {
defer allocator.free(path);
- return .{ .path = try allocator.dupeZ(u8, path), .svg = std.mem.eql(u8, ext, "svg"), .pack = true };
+ return .{ .path = try allocator.dupeSentinel(u8, path, 0), .svg = std.mem.eql(u8, ext, "svg"), .pack = true };
} else |_| {}
}
}
diff --git a/src/images/app_dialogs.zig b/src/images/app_dialogs.zig
index 0212a35..2221119 100644
--- a/src/images/app_dialogs.zig
+++ b/src/images/app_dialogs.zig
@@ -41,7 +41,7 @@ pub fn openSave(self: *App) void {
var suggested = false;
for (0..10000) |n| {
const name = if (n == 0) std.fmt.bufPrint(&name_buf, "{s}-edited.png", .{base}) catch "edited.png" else std.fmt.bufPrint(&name_buf, "{s}-edited-{d}.png", .{ base, n }) catch "edited.png";
- const dest = std.fmt.bufPrintZ(&buf, "{s}/{s}", .{ dir, name }) catch {
+ const dest = std.fmt.bufPrintSentinel(&buf, "{s}/{s}", .{ dir, name }, 0) catch {
self.message(tr("The filename is too long."));
return;
};
@@ -100,7 +100,7 @@ pub fn confirmDialog(self: *App) void {
self.message(tr("Enter a filename or an absolute path."));
return;
};
- const path = if (std.fs.path.isAbsolute(name)) a.dupeZ(u8, name) catch return else std.fmt.allocPrintSentinel(a, "{s}/{s}", .{ std.fs.path.dirname(self.paths[self.selected]) orelse ".", name }, 0) catch return;
+ const path = if (std.fs.path.isAbsolute(name)) a.dupeSentinel(u8, name, 0) catch return else std.fmt.allocPrintSentinel(a, "{s}/{s}", .{ std.fs.path.dirname(self.paths[self.selected]) orelse ".", name }, 0) catch return;
defer a.free(path);
self.operation = edit.Operation.start(.save, self.io, path, self.image, null) catch {
self.message(tr("Could not start saving."));
diff --git a/src/images/edit.zig b/src/images/edit.zig
index d9044e8..d58cafd 100644
--- a/src/images/edit.zig
+++ b/src/images/edit.zig
@@ -69,7 +69,7 @@ pub const Operation = struct {
pub fn start(kind: Kind, io: std.Io, path: []const u8, im: ?Image, stamp: ?Stamp) !*Operation {
const self = try a.create(Operation);
errdefer a.destroy(self);
- self.* = .{ .kind = kind, .path = try a.dupeZ(u8, path), .io = io, .stamp = stamp };
+ self.* = .{ .kind = kind, .path = try a.dupeSentinel(u8, path, 0), .io = io, .stamp = stamp };
errdefer a.free(self.path);
if (im) |image| self.image = .{ .pixels = try a.dupe(u32, image.pixels), .w = image.w, .h = image.h };
errdefer if (self.image) |image| image.deinit();
diff --git a/src/images_main.zig b/src/images_main.zig
index 617395f..5b82117 100644
--- a/src/images_main.zig
+++ b/src/images_main.zig
@@ -45,7 +45,7 @@ fn run(init: std.process.Init) !void {
var it = std.mem.splitScalar(u8, bytes.items[0 .. bytes.items.len - 1], 0);
while (it.next()) |p| {
if (p.len == 0 or !std.fs.path.isAbsolute(p)) return error.InvalidList;
- try paths.append(a, try a.dupeZ(u8, p));
+ try paths.append(a, try a.dupeSentinel(u8, p, 0));
}
} else {
var first: usize = 1;
@@ -53,12 +53,12 @@ fn run(init: std.process.Init) !void {
for (args[first..]) |arg| {
const real = c.realpath(arg, null) orelse return error.FileNotFound;
defer c.free(real);
- try paths.append(a, try a.dupeZ(u8, std.mem.span(real)));
+ try paths.append(a, try a.dupeSentinel(u8, std.mem.span(real), 0));
}
if (paths.items.len == 1) {
- const target = try a.dupeZ(u8, paths.items[0]);
+ const target = try a.dupeSentinel(u8, paths.items[0], 0);
defer a.free(target);
- const dir = try a.dupeZ(u8, std.fs.path.dirname(target).?);
+ const dir = try a.dupeSentinel(u8, std.fs.path.dirname(target).?, 0);
defer a.free(dir);
if (c.opendir(dir)) |directory| {
defer _ = c.closedir(directory);
diff --git a/src/images_tests.zig b/src/images_tests.zig
index c5d7924..52c5641 100644
--- a/src/images_tests.zig
+++ b/src/images_tests.zig
@@ -65,7 +65,7 @@ test "streaming decoder enforces dimensions before full raster allocation" {
// PPM exposes dimensions in its header, before any pixel data arrives.
const header = "P6\n32769 1\n255\n";
try std.testing.expectEqual(@as(isize, header.len), c.write(fd, header.ptr, header.len));
- const raster = [_]u8{0} ** (32769 * 3);
+ const raster = @as([32769 * 3]u8, @splat(0));
try std.testing.expectEqual(@as(isize, raster.len), c.write(fd, &raster, raster.len));
try std.testing.expectError(error.ImageTooLarge, loader.load(std.mem.sliceTo(&path, 0), false));
}
diff --git a/src/input/cursor.zig b/src/input/cursor.zig
index 543fd6a..db0546a 100644
--- a/src/input/cursor.zig
+++ b/src/input/cursor.zig
@@ -9,7 +9,7 @@ const log = std.log.scoped(.input);
pub fn createCursorManager(theme: []const u8, size: u32) ?*wlr.XcursorManager {
var buf: [128]u8 = undefined;
const name: ?[*:0]const u8 = if (cursor_theme.managerTheme(theme)) |t|
- (std.fmt.bufPrintZ(&buf, "{s}", .{t}) catch return null).ptr
+ (std.fmt.bufPrintSentinel(&buf, "{s}", .{t}, 0) catch return null).ptr
else
null;
return wlr.XcursorManager.create(name, size) catch null;
diff --git a/src/input/repeat_keys.zig b/src/input/repeat_keys.zig
index ce22df3..3900ad3 100644
--- a/src/input/repeat_keys.zig
+++ b/src/input/repeat_keys.zig
@@ -7,7 +7,7 @@ const xkb = @import("xkbcommon");
/// Text and caret keys: printable characters, Backspace, Delete, Left, Right.
pub fn editing(sym: xkb.Keysym, utf8: []const u8) bool {
- return switch (@intFromEnum(sym)) {
+ return switch (sym) {
xkb.Keysym.BackSpace, xkb.Keysym.Delete, xkb.Keysym.Left, xkb.Keysym.Right => true,
else => printable(utf8),
};
@@ -15,7 +15,7 @@ pub fn editing(sym: xkb.Keysym, utf8: []const u8) bool {
/// List navigation: Up, Down, Page Up, Page Down.
pub fn navigation(sym: xkb.Keysym) bool {
- return switch (@intFromEnum(sym)) {
+ return switch (sym) {
xkb.Keysym.Up, xkb.Keysym.Down, xkb.Keysym.Page_Up, xkb.Keysym.Page_Down => true,
else => false,
};
@@ -28,20 +28,15 @@ fn printable(utf8: []const u8) bool {
test "text and caret keys repeat; action keys do not" {
const std = @import("std");
- const sym = struct {
- fn of(value: u32) xkb.Keysym {
- return @enumFromInt(value);
- }
- }.of;
- try std.testing.expect(editing(sym(xkb.Keysym.a), "a"));
- try std.testing.expect(editing(sym(xkb.Keysym.space), " "));
- try std.testing.expect(editing(sym(xkb.Keysym.eacute), "é"));
- try std.testing.expect(editing(sym(xkb.Keysym.BackSpace), "\x08"));
- try std.testing.expect(editing(sym(xkb.Keysym.Left), ""));
- try std.testing.expect(!editing(sym(xkb.Keysym.Return), "\r"));
- try std.testing.expect(!editing(sym(xkb.Keysym.Tab), "\t"));
- try std.testing.expect(!editing(sym(xkb.Keysym.Escape), "\x1b"));
- try std.testing.expect(!editing(sym(xkb.Keysym.Home), ""));
- try std.testing.expect(navigation(sym(xkb.Keysym.Page_Down)));
- try std.testing.expect(!navigation(sym(xkb.Keysym.Left)));
+ try std.testing.expect(editing(xkb.Keysym.a, "a"));
+ try std.testing.expect(editing(xkb.Keysym.space, " "));
+ try std.testing.expect(editing(xkb.Keysym.eacute, "é"));
+ try std.testing.expect(editing(xkb.Keysym.BackSpace, "\x08"));
+ try std.testing.expect(editing(xkb.Keysym.Left, ""));
+ try std.testing.expect(!editing(xkb.Keysym.Return, "\r"));
+ try std.testing.expect(!editing(xkb.Keysym.Tab, "\t"));
+ try std.testing.expect(!editing(xkb.Keysym.Escape, "\x1b"));
+ try std.testing.expect(!editing(xkb.Keysym.Home, ""));
+ try std.testing.expect(navigation(xkb.Keysym.Page_Down));
+ try std.testing.expect(!navigation(xkb.Keysym.Left));
}
diff --git a/src/ipc/commands.zig b/src/ipc/commands.zig
index cd3c24e..b2320b3 100644
--- a/src/ipc/commands.zig
+++ b/src/ipc/commands.zig
@@ -7,13 +7,13 @@ pub const CommandId = blk: {
@setEvalBranchQuota(100_000);
var names: []const []const u8 = &.{};
for (.{ protocol.Request, protocol.Action }) |T| {
- for (std.meta.fields(T)) |field| {
- if (T == protocol.Request and isInternalRequest(field.name)) continue;
+ for (@typeInfo(T).@"union".field_names) |field_name| {
+ if (T == protocol.Request and isInternalRequest(field_name)) continue;
var exists = false;
- for (names) |name| if (std.mem.eql(u8, name, field.name)) {
+ for (names) |name| if (std.mem.eql(u8, name, field_name)) {
exists = true;
};
- if (!exists) names = names ++ .{field.name};
+ if (!exists) names = names ++ .{field_name};
}
}
break :blk @Enum(u16, .exhaustive, names, &std.simd.iota(u16, names.len));
diff --git a/src/ipc/events.zig b/src/ipc/events.zig
index 2206b92..befe5d3 100644
--- a/src/ipc/events.zig
+++ b/src/ipc/events.zig
@@ -165,7 +165,7 @@ fn hashWindowValue(hasher: *std.hash.Wyhash, value: anytype) void {
hasher.update(&.{1});
hashWindowValue(hasher, v);
} else hasher.update(&.{0}),
- .@"struct" => |info| inline for (info.fields) |field| hashWindowValue(hasher, @field(value, field.name)),
+ .@"struct" => |info| inline for (info.field_names) |name| hashWindowValue(hasher, @field(value, name)),
.pointer => {
std.hash.autoHash(hasher, value.len);
hasher.update(value);
diff --git a/src/ipc/processes.zig b/src/ipc/processes.zig
index eb1b619..5ab4c89 100644
--- a/src/ipc/processes.zig
+++ b/src/ipc/processes.zig
@@ -6,13 +6,7 @@ const protocol = @import("protocol.zig");
const Client = @import("server.zig").Client;
const Server = @import("../Server.zig");
const gpa = @import("../main.zig").gpa;
-const c = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- @cInclude("sys/eventfd.h");
- @cInclude("fcntl.h");
- @cInclude("unistd.h");
- @cInclude("time.h");
-});
+const c = @import("c");
pub const Job = struct {
arena: std.heap.ArenaAllocator,
diff --git a/src/ipc/protocol_stringify_tests.zig b/src/ipc/protocol_stringify_tests.zig
index e3346b6..123242b 100644
--- a/src/ipc/protocol_stringify_tests.zig
+++ b/src/ipc/protocol_stringify_tests.zig
@@ -273,18 +273,18 @@ test "response serializers preserve baseline fields rounding and omissions" {
@setEvalBranchQuota(200_000);
const fixtures = @import("../ipc_serializer_fixtures.zig");
var lines = std.mem.splitScalar(u8, @embedFile("../ipc_serializers.jsonl"), '\n');
- inline for (std.meta.fields(protocol.ResponsePayload)) |field| {
+ inline for (@typeInfo(protocol.ResponsePayload).@"union".field_names) |field_name| {
inline for (.{ false, true }) |populated| {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
- const payload = @unionInit(protocol.ResponsePayload, field.name, fixtures.sample(field.type, populated));
+ const payload = @unionInit(protocol.ResponsePayload, field_name, fixtures.sample(@FieldType(protocol.ResponsePayload, field_name), populated));
var list: std.ArrayList(u8) = .empty;
try protocol.stringifyResponse(.{ .ok = payload }, protocol.BufferWriter{ .list = &list, .allocator = a });
const actual = try std.json.parseFromSlice(std.json.Value, a, list.items, .{});
const expected = try std.json.parseFromSlice(std.json.Value, a, lines.next().?, .{});
expectJsonEqual(expected.value, actual.value) catch |err| {
- std.debug.print("serializer {s}, populated={}\n", .{ field.name, populated });
+ std.debug.print("serializer {s}, populated={}\n", .{ field_name, populated });
return err;
};
}
diff --git a/src/ipc/protocol_wait.zig b/src/ipc/protocol_wait.zig
index d6e5cd6..fe228f3 100644
--- a/src/ipc/protocol_wait.zig
+++ b/src/ipc/protocol_wait.zig
@@ -20,12 +20,12 @@ pub fn waitNames(comptime name: []const u8) []const []const u8 {
comptime {
@setEvalBranchQuota(20_000);
- for (std.meta.fields(@TypeOf(wait_aliases))) |f| {
- if (!@hasField(WaitCondition, f.name)) @compileError("unknown wait alias target: " ++ f.name);
+ for (@typeInfo(@TypeOf(wait_aliases)).@"struct".field_names) |name| {
+ if (!@hasField(WaitCondition, name)) @compileError("unknown wait alias target: " ++ name);
}
var names: []const []const u8 = &.{};
- for (std.meta.fields(WaitCondition)) |field| {
- for (waitNames(field.name)) |name| {
+ for (@typeInfo(WaitCondition).@"union".field_names) |field_name| {
+ for (waitNames(field_name)) |name| {
for (names) |previous| {
if (std.mem.eql(u8, previous, name)) @compileError("duplicate wait name: " ++ name);
}
@@ -55,10 +55,10 @@ pub fn parseWaitCondition(allocator: std.mem.Allocator, val: std.json.Value) Par
var value: std.json.Value = .null;
switch (val) {
.string => |s| {
- inline for (std.meta.fields(WaitCondition)) |field| {
- if (field.type == void) {
- inline for (comptime waitNames(field.name)) |name| {
- if (std.mem.eql(u8, s, name)) return @unionInit(WaitCondition, field.name, {});
+ inline for (@typeInfo(WaitCondition).@"union".field_names) |field_name| {
+ if (@FieldType(WaitCondition, field_name) == void) {
+ inline for (comptime waitNames(field_name)) |name| {
+ if (std.mem.eql(u8, s, name)) return @unionInit(WaitCondition, field_name, {});
}
}
}
@@ -68,12 +68,12 @@ pub fn parseWaitCondition(allocator: std.mem.Allocator, val: std.json.Value) Par
// Historically all no-payload conditions take precedence over
// payload conditions, independently of object insertion order.
inline for (.{ true, false }) |no_payload| {
- inline for (std.meta.fields(WaitCondition)) |field| {
- if ((field.type == void) == no_payload) {
- inline for (comptime waitNames(field.name)) |name| {
+ inline for (@typeInfo(WaitCondition).@"union".field_names) |field_name| {
+ if ((@FieldType(WaitCondition, field_name) == void) == no_payload) {
+ inline for (comptime waitNames(field_name)) |name| {
if (selected == null) {
if (obj.get(name)) |v| {
- selected = @field(Tag, field.name);
+ selected = @field(Tag, field_name);
value = v;
}
}
diff --git a/src/ipc/server.zig b/src/ipc/server.zig
index 55bb69a..4bf167e 100644
--- a/src/ipc/server.zig
+++ b/src/ipc/server.zig
@@ -372,7 +372,7 @@ fn detectSandbox(pid: i32, client_fd: c_int, allocator: std.mem.Allocator) ?Sand
defer if (pidfd >= 0) closeFd(pidfd);
var proc_buf: [64]u8 = undefined;
- const proc_path = std.fmt.bufPrintZ(&proc_buf, "/proc/{d}", .{pid}) catch return null;
+ const proc_path = std.fmt.bufPrintSentinel(&proc_buf, "/proc/{d}", .{pid}, 0) catch return null;
const proc_fd = c.open(proc_path.ptr, .{ .ACCMODE = .RDONLY, .DIRECTORY = true, .CLOEXEC = true });
if (proc_fd < 0) return null;
diff --git a/src/ipc/settings.zig b/src/ipc/settings.zig
index 726587f..c2d8983 100644
--- a/src/ipc/settings.zig
+++ b/src/ipc/settings.zig
@@ -78,12 +78,13 @@ pub fn setNightLight(server: *Server, enabled: ?bool, temperature: ?u16, persist
}
pub fn getTheme(server: *Server, a: std.mem.Allocator) !protocol.Response {
- const fields = std.meta.fields(theme.Theme);
- const entries = try a.alloc(protocol.ThemeToken, fields.len);
- inline for (fields, 0..) |field, i| {
- entries[i] = .{ .name = field.name };
- const value = @field(theme.global, field.name);
- if (field.type == [4]f32 or field.type == ?[4]f32) entries[i].color = value else if (field.type == []const u8) entries[i].text = value else if (field.type == bool) entries[i].boolean = value else if (@typeInfo(field.type) == .float) entries[i].number = value else @compileError("unhandled theme token " ++ field.name);
+ const names = @typeInfo(theme.Theme).@"struct".field_names;
+ const entries = try a.alloc(protocol.ThemeToken, names.len);
+ inline for (names, 0..) |name, i| {
+ entries[i] = .{ .name = name };
+ const value = @field(theme.global, name);
+ const T = @FieldType(theme.Theme, name);
+ if (T == [4]f32 or T == ?[4]f32) entries[i].color = value else if (T == []const u8) entries[i].text = value else if (T == bool) entries[i].boolean = value else if (@typeInfo(T) == .float) entries[i].number = value else @compileError("unhandled theme token " ++ name);
}
return .{ .ok = .{ .theme = .{ .tokens = .{ .entries = entries }, .path = server.theme_path, .dark_mode = server.config.compositor.dark_mode } } };
}
diff --git a/src/ipc_serializer_fixtures.zig b/src/ipc_serializer_fixtures.zig
index 5016669..313054a 100644
--- a/src/ipc_serializer_fixtures.zig
+++ b/src/ipc_serializer_fixtures.zig
@@ -10,18 +10,18 @@ pub fn sample(comptime T: type, comptime populated: bool) T {
.float => if (populated) 1.23456 else 0,
.optional => |o| if (populated) sample(o.child, populated) else null,
.@"enum" => std.meta.tags(T)[0],
- .array => |a| [_]a.child{sample(a.child, populated)} ** a.len,
+ .array => |a| @as([a.len]a.child, @splat(sample(a.child, populated))),
.pointer => |p| if (p.size == .slice)
(if (p.child == u8) "text \"quoted\"\n\\" else &[_]p.child{sample(p.child, populated)})
else
@compileError("add pointer fixture for " ++ @typeName(T)),
.@"struct" => blk: {
var value: T = undefined;
- for (std.meta.fields(T)) |f| {
- if (std.mem.eql(u8, f.name, "placeholder") or std.mem.eql(u8, f.name, "tab_group") or (@hasField(T, "tab_group") and (std.mem.eql(u8, f.name, "tag") or std.mem.eql(u8, f.name, "description") or std.mem.eql(u8, f.name, "content_type")))) {
- @field(value, f.name) = null;
+ for (@typeInfo(T).@"struct".field_names) |name| {
+ if (std.mem.eql(u8, name, "placeholder") or std.mem.eql(u8, name, "tab_group") or (@hasField(T, "tab_group") and (std.mem.eql(u8, name, "tag") or std.mem.eql(u8, name, "description") or std.mem.eql(u8, name, "content_type")))) {
+ @field(value, name) = null;
} else {
- @field(value, f.name) = sample(f.type, populated);
+ @field(value, name) = sample(@FieldType(T, name), populated);
}
}
break :blk value;
diff --git a/src/ipc_tests.zig b/src/ipc_tests.zig
index 27dbdc9..e915c98 100644
--- a/src/ipc_tests.zig
+++ b/src/ipc_tests.zig
@@ -239,11 +239,11 @@ test "IPC registry covers public variants and all routes" {
@setEvalBranchQuota(200_000);
const registry = protocol.commands;
inline for (.{ protocol.Request, protocol.Action }) |T| {
- inline for (std.meta.fields(T)) |field| {
- if (comptime T == protocol.Request and registry.isInternalRequest(field.name)) continue;
+ inline for (@typeInfo(T).@"union".field_names) |field_name| {
+ if (comptime T == protocol.Request and registry.isInternalRequest(field_name)) continue;
var count: usize = 0;
inline for (registry.specs) |s| {
- if (comptime std.mem.eql(u8, @tagName(s.id), field.name)) count += 1;
+ if (comptime std.mem.eql(u8, @tagName(s.id), field_name)) count += 1;
}
try std.testing.expectEqual(@as(usize, 1), count);
}
@@ -297,7 +297,7 @@ test "every v1 command parses" {
}
fn encodeWithFailingAllocator(allocator: std.mem.Allocator) !void {
- const pixels = [_]u32{0xff123456} ** 16;
+ const pixels = @as([16]u32, @splat(0xff123456));
const bytes = try @import("screenshot/encode.zig").encodePng(allocator, 4, 4, &pixels, 4);
defer allocator.free(bytes);
try std.testing.expect(bytes.len > 20);
diff --git a/src/keyboard/process.zig b/src/keyboard/process.zig
index 792320d..46f6865 100644
--- a/src/keyboard/process.zig
+++ b/src/keyboard/process.zig
@@ -171,7 +171,7 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state
if (keyboard.server.screenshot_selector.output != null and state == .pressed) {
if (event_keycode < keyboard.screenshot_consumed.len) keyboard.screenshot_consumed[event_keycode] = true;
for (xkb_state.keyGetSyms(keycode)) |sym| {
- if (@intFromEnum(sym) == xkb.Keysym.Escape) keyboard.server.screenshot_selector.cancel();
+ if (sym == xkb.Keysym.Escape) keyboard.server.screenshot_selector.cancel();
}
return;
}
@@ -230,8 +230,8 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state
}
if (keyboard.server.switcher.active()) {
keyboard.stopSwitcherRepeat();
- if (@intFromEnum(sym) == xkb.Keysym.Escape) keyboard.server.switcher.cancel();
- if (@intFromEnum(sym) == xkb.Keysym.Return) keyboard.server.switcher.accept(keyboard.server);
+ if (sym == xkb.Keysym.Escape) keyboard.server.switcher.cancel();
+ if (sym == xkb.Keysym.Return) keyboard.server.switcher.accept(keyboard.server);
if (event_keycode < keyboard.switcher_consumed.len) keyboard.switcher_consumed[event_keycode] = true;
return;
}
@@ -254,14 +254,14 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state
// keyboard; its release is ours too.
if (state == .pressed and keyboard.server.input.dock_drag.reordering()) {
for (xkb_state.keyGetSyms(keycode)) |sym| {
- if (@intFromEnum(sym) != xkb.Keysym.Escape) continue;
+ if (sym != xkb.Keysym.Escape) continue;
_ = keyboard.server.input.cancelDrag();
keyboard.consuming_escape = true;
return;
}
} else if (state == .released and keyboard.consuming_escape) {
for (xkb_state.keyGetSyms(keycode)) |sym| {
- if (@intFromEnum(sym) != xkb.Keysym.Escape) continue;
+ if (sym != xkb.Keysym.Escape) continue;
keyboard.consuming_escape = false;
return;
}
@@ -295,7 +295,7 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state
if (state == .pressed) {
if (event_keycode < keyboard.battery_consumed.len) keyboard.battery_consumed[event_keycode] = true;
for (xkb_state.keyGetSyms(keycode)) |sym| {
- switch (@intFromEnum(sym)) {
+ switch (sym) {
xkb.Keysym.Escape => {
popup.output.closeBattery();
return;
@@ -312,7 +312,7 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state
if (keyboard.server.input.open_calendar) |calendar| {
if (state == .pressed) {
for (xkb_state.keyGetSyms(keycode)) |sym| {
- switch (@intFromEnum(sym)) {
+ switch (sym) {
xkb.Keysym.Escape => {
calendar.output.closeCalendar();
return;
@@ -329,7 +329,7 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state
if (keyboard.server.input.open_power_menu) |pm| {
if (state == .pressed) {
for (xkb_state.keyGetSyms(keycode)) |sym| {
- switch (@intFromEnum(sym)) {
+ switch (sym) {
xkb.Keysym.Escape => if (Output.fromWlr(pm.wlr_output)) |output| output.closePowerMenu(),
xkb.Keysym.Left => pm.navigate(false),
xkb.Keysym.Right => pm.navigate(true),
@@ -365,7 +365,7 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state
if (keyboard.server.input.open_start_menu) |sm| {
// Escape abandons an application dragged out of the menu, not the menu.
if (state == .pressed and keyboard.server.input.dock_drag.active()) for (xkb_state.keyGetSyms(keycode)) |sym| {
- if (@intFromEnum(sym) == xkb.Keysym.Escape) {
+ if (sym == xkb.Keysym.Escape) {
_ = keyboard.server.input.cancelDrag();
keyboard.consuming_escape = true;
return;
@@ -411,7 +411,7 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state
// inhibits it until the trigger is released. Either way the release is ours.
if (state == .pressed) {
for (xkb_state.keyGetSyms(keycode)) |sym| {
- if (@intFromEnum(sym) == xkb.Keysym.Escape) {
+ if (sym == xkb.Keysym.Escape) {
const input = &keyboard.server.input;
if (input.cancelDrag()) {
keyboard.consuming_escape = true;
@@ -438,7 +438,7 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state
} else if (state == .released) {
if (keyboard.consuming_escape) {
for (xkb_state.keyGetSyms(keycode)) |sym| {
- if (@intFromEnum(sym) == xkb.Keysym.Escape) {
+ if (sym == xkb.Keysym.Escape) {
keyboard.consuming_escape = false;
return;
}
diff --git a/src/keyboard/shell.zig b/src/keyboard/shell.zig
index 3bfd623..fcedebd 100644
--- a/src/keyboard/shell.zig
+++ b/src/keyboard/shell.zig
@@ -165,11 +165,11 @@ pub fn deliverShell(keyboard: *Keyboard, target: ShellTarget, event_keycode: u32
.polkit => if (server.polkit_dialog) |dialog| if (syms.len > 0) dialog.key(syms[0], utf8, mods),
.lock => if (server.locker) |lock| if (syms.len > 0) lock.key(syms[0], utf8, mods),
.control_center => |cc| for (syms) |sym| {
- if (mods.ctrl and !mods.alt and !mods.logo and (@intFromEnum(sym) == xkb.Keysym.f or @intFromEnum(sym) == xkb.Keysym.F)) {
+ if (mods.ctrl and !mods.alt and !mods.logo and (sym == xkb.Keysym.f or sym == xkb.Keysym.F)) {
cc.focusSearch();
break;
}
- const key: ?@import("ui").input.Key = switch (@intFromEnum(sym)) {
+ const key: ?@import("ui").input.Key = switch (sym) {
xkb.Keysym.Escape => .escape,
xkb.Keysym.Return, xkb.Keysym.KP_Enter => .enter,
xkb.Keysym.BackSpace => .backspace,
@@ -183,7 +183,7 @@ pub fn deliverShell(keyboard: *Keyboard, target: ShellTarget, event_keycode: u32
xkb.Keysym.Page_Up => .page_up,
xkb.Keysym.Page_Down => .page_down,
xkb.Keysym.Tab, xkb.Keysym.ISO_Left_Tab => .tab,
- else => if (mods.ctrl and (@intFromEnum(sym) == xkb.Keysym.a or @intFromEnum(sym) == xkb.Keysym.A)) .select_all else if (mods.ctrl and (@intFromEnum(sym) == xkb.Keysym.c or @intFromEnum(sym) == xkb.Keysym.C or @intFromEnum(sym) == xkb.Keysym.x or @intFromEnum(sym) == xkb.Keysym.X or @intFromEnum(sym) == xkb.Keysym.v or @intFromEnum(sym) == xkb.Keysym.V)) null else if (utf8.len > 0) .{ .char = utf8 } else null,
+ else => if (mods.ctrl and (sym == xkb.Keysym.a or sym == xkb.Keysym.A)) .select_all else if (mods.ctrl and (sym == xkb.Keysym.c or sym == xkb.Keysym.C or sym == xkb.Keysym.x or sym == xkb.Keysym.X or sym == xkb.Keysym.v or sym == xkb.Keysym.V)) null else if (utf8.len > 0) .{ .char = utf8 } else null,
};
if (key) |k| _ = cc.selectKey(k, mods.shift);
},
diff --git a/src/libinput.zig b/src/libinput.zig
index beb6f88..03bb5b8 100644
--- a/src/libinput.zig
+++ b/src/libinput.zig
@@ -1,16 +1,14 @@
// Thin wrapper around the subset of libinput's device-config API the control
// center's Input section needs (pointer accel speed, natural scroll,
// tap-to-click). libinput.h is a clean, glib-free C API (unlike librsvg, see
-// AGENTS.md, "Build and platform gotchas") so it's @cInclude'd directly rather than hand-declared.
+// AGENTS.md, "Build and platform gotchas") so it's translated directly rather than hand-declared.
//
// `wlr.InputDevice.getLibinputDevice()` returns a pointer to an opaque type
// from the wlroots facade's C import; since it carries no fields on either
// side, a plain `@ptrCast` onto libinput.h's own `struct libinput_device*`
// is safe and avoids needing to name that private type at all.
const wlr = @import("wlroots");
-const c = @cImport({
- @cInclude("libinput.h");
-});
+const c = @import("c_libinput");
fn handle(device: *wlr.InputDevice) ?*c.libinput_device {
const raw = device.getLibinputDevice() orelse return null;
diff --git a/src/main.zig b/src/main.zig
index 8bcde6b..387cbe2 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -40,7 +40,7 @@ pub fn main(init: std.process.Init) void {
@import("session/activation.zig").setSessionFdInheritance(init.minimal.environ, false);
wlr.log.init(.debug, null);
// Runs last, on a normal exit only: restarts exec and fatal paths exit.
- defer if (@import("builtin").mode == .Debug) {
+ defer if (@import("builtin").mode == .debug) {
if (@import("memory").deinit()) log.err("memory leaks reported above", .{});
};
diff --git a/src/memory/allocator.zig b/src/memory/allocator.zig
index acac569..f4670b8 100644
--- a/src/memory/allocator.zig
+++ b/src/memory/allocator.zig
@@ -1,7 +1,7 @@
const std = @import("std");
/// Shared process allocator. The executable owns shutdown and leak reporting.
var debug_allocator: std.heap.DebugAllocator(.{}) = .init;
-pub const gpa = if (@import("builtin").mode == .Debug) debug_allocator.allocator() else std.heap.c_allocator;
+pub const gpa = if (@import("builtin").mode == .debug) debug_allocator.allocator() else std.heap.c_allocator;
pub fn deinit() bool {
- return if (@import("builtin").mode == .Debug) debug_allocator.deinit() == .leak else false;
+ return if (@import("builtin").mode == .debug) debug_allocator.deinit() == .leak else false;
}
diff --git a/src/mime_db.zig b/src/mime_db.zig
index cf1f3a3..b28c949 100644
--- a/src/mime_db.zig
+++ b/src/mime_db.zig
@@ -104,7 +104,7 @@ pub const Db = struct {
} else if (key[0] == '*' and std.mem.indexOfAny(u8, key[1..], "*?[\\") == null) {
try self.putGlob(&self.suffixes, &self.suffixes_ci, key[1..], pattern[1..], glob, case_sensitive);
} else {
- try self.patterns.append(a, .{ .glob = glob, .pattern = try a.dupeZ(u8, key), .case_sensitive = case_sensitive });
+ try self.patterns.append(a, .{ .glob = glob, .pattern = try a.dupeSentinel(u8, key, 0), .case_sensitive = case_sensitive });
}
}
}
diff --git a/src/msg/msg_cli.zig b/src/msg/msg_cli.zig
index 449c8c4..6fcbe55 100644
--- a/src/msg/msg_cli.zig
+++ b/src/msg/msg_cli.zig
@@ -123,26 +123,27 @@ pub const FlagParser = struct {
/// `?T` when some payload field has neither a default nor a preset; null
/// then means a required flag was missing or unparsable.
pub fn Result(comptime T: type, comptime Preset: type) type {
- for (std.meta.fields(T)) |f| {
- if (f.default_value_ptr == null and !@hasField(Preset, f.name)) return ?T;
+ const info = @typeInfo(T).@"struct";
+ for (info.field_names, info.field_attrs) |name, attrs| {
+ if (attrs.default_value_ptr == null and !@hasField(Preset, name)) return ?T;
}
return T;
}
pub fn parse(p: FlagParser, comptime T: type, comptime spec: anytype, preset: anytype) Result(T, @TypeOf(preset)) {
- const fields = std.meta.fields(T);
- comptime for (fields) |f| {
- if (f.default_value_ptr == null and !@hasField(@TypeOf(preset), f.name) and !hasEntry(spec, f.name))
- @compileError("required field '" ++ f.name ++ "' of " ++ @typeName(T) ++ " has no flag or preset");
+ const info = @typeInfo(T).@"struct";
+ comptime for (info.field_names, info.field_attrs) |name, attrs| {
+ if (attrs.default_value_ptr == null and !@hasField(@TypeOf(preset), name) and !hasEntry(spec, name))
+ @compileError("required field '" ++ name ++ "' of " ++ @typeName(T) ++ " has no flag or preset");
};
var out: T = undefined;
- var given = std.StaticBitSet(fields.len).initEmpty();
- inline for (fields, 0..) |f, i| {
- if (@hasField(@TypeOf(preset), f.name)) {
- @field(out, f.name) = @field(preset, f.name);
+ var given = std.StaticBitSet(info.field_names.len).empty;
+ inline for (info.field_names, info.field_types, info.field_attrs, 0..) |name, FieldType, attrs, i| {
+ if (@hasField(@TypeOf(preset), name)) {
+ @field(out, name) = @field(preset, name);
given.set(i);
- } else if (f.defaultValue()) |d| @field(out, f.name) = d;
+ } else if (attrs.defaultValue(FieldType)) |d| @field(out, name) = d;
}
args: while (p.idx.* < p.args.len) : (p.idx.* += 1) {
@@ -166,11 +167,11 @@ pub const FlagParser = struct {
if (p.value(entry, @FieldType(CliOptions, name), text)) |v| @field(p.opts, name) = v;
} else {
const i = comptime fieldIndex(T, name);
- if (p.value(entry, fields[i].type, text)) |v| {
+ if (p.value(entry, info.field_types[i], text)) |v| {
@field(out, name) = v;
given.set(i);
} else {
- if (fields[i].defaultValue()) |d| @field(out, name) = d;
+ if (info.field_attrs[i].defaultValue(info.field_types[i])) |d| @field(out, name) = d;
given.unset(i);
}
}
@@ -182,8 +183,8 @@ pub const FlagParser = struct {
if (comptime entryFlag(entry, "bare")) {
const i = comptime fieldIndex(T, entryField(entry));
if (!given.isSet(i)) {
- if (p.value(entry, fields[i].type, a)) |v| {
- @field(out, fields[i].name) = v;
+ if (p.value(entry, info.field_types[i], a)) |v| {
+ @field(out, info.field_names[i]) = v;
given.set(i);
}
}
@@ -192,8 +193,8 @@ pub const FlagParser = struct {
}
if (Result(T, @TypeOf(preset)) != T) {
- inline for (fields, 0..) |f, i| {
- if (f.default_value_ptr == null and !given.isSet(i)) return null;
+ inline for (info.field_attrs, 0..) |attrs, i| {
+ if (attrs.default_value_ptr == null and !given.isSet(i)) return null;
}
}
return out;
diff --git a/src/msg/msg_usage.zig b/src/msg/msg_usage.zig
index 7434dc8..457ef11 100644
--- a/src/msg/msg_usage.zig
+++ b/src/msg/msg_usage.zig
@@ -13,25 +13,25 @@ pub const TopCommandTag = blk: {
@setEvalBranchQuota(20_000);
for (protocol.commands.specs) |s| {
if (s.cli) |cli| {
- for (std.meta.fields(@TypeOf(local_commands))) |field| {
+ for (@typeInfo(@TypeOf(local_commands)).@"struct".field_names) |local| {
for (&[_][]const u8{cli.name} ++ cli.aliases) |name| {
- if (std.mem.eql(u8, field.name, name)) @compileError("CLI name shadows local command: " ++ name);
+ if (std.mem.eql(u8, local, name)) @compileError("CLI name shadows local command: " ++ name);
}
}
}
}
var names: []const []const u8 = &.{};
- for (std.meta.fields(@TypeOf(local_commands))) |field| names = names ++ .{field.name};
- for (std.meta.fields(protocol.commands.CliTag(false))) |field| names = names ++ .{field.name};
+ for (@typeInfo(@TypeOf(local_commands)).@"struct".field_names) |name| names = names ++ .{name};
+ for (@typeInfo(protocol.commands.CliTag(false)).@"enum".field_names) |name| names = names ++ .{name};
break :blk @Enum(u8, .exhaustive, names, &std.simd.iota(u8, names.len));
};
pub fn lookupTopCommand(name: []const u8) ?TopCommandTag {
- inline for (std.meta.fields(@TypeOf(local_commands))) |field| {
- if (std.mem.eql(u8, name, field.name)) return @field(TopCommandTag, field.name);
+ inline for (@typeInfo(@TypeOf(local_commands)).@"struct".field_names) |local| {
+ if (std.mem.eql(u8, name, local)) return @field(TopCommandTag, local);
}
const tag = protocol.commands.lookupCli(false, name) orelse return null;
- return @enumFromInt(@intFromEnum(tag) + std.meta.fields(@TypeOf(local_commands)).len);
+ return @enumFromInt(@intFromEnum(tag) + @typeInfo(@TypeOf(local_commands)).@"struct".field_names.len);
}
pub fn printUsage() void {
@@ -50,9 +50,9 @@ pub fn printUsage() void {
\\Commands:
\\
, .{});
- inline for (std.meta.fields(@TypeOf(local_commands))) |field| {
- const c = @field(local_commands, field.name);
- std.debug.print(" {s} {s} {s}\n", .{ field.name, c.synopsis, c.description });
+ inline for (@typeInfo(@TypeOf(local_commands)).@"struct".field_names) |name| {
+ const c = @field(local_commands, name);
+ std.debug.print(" {s} {s} {s}\n", .{ name, c.synopsis, c.description });
}
inline for (protocol.commands.specs) |s| {
if (comptime s.cli) |cli| printCommandHelp("", cli, s.description);
diff --git a/src/network/popup.zig b/src/network/popup.zig
index 230e456..3d50e34 100644
--- a/src/network/popup.zig
+++ b/src/network/popup.zig
@@ -385,26 +385,25 @@ pub const Popup = struct {
}
pub fn keyRepeats(self: *Popup, sym: xkb.Keysym, utf8: []const u8) bool {
if (self.focus != .password and self.focus != .ssid) return false;
- return switch (@intFromEnum(sym)) {
+ return switch (sym) {
xkb.Keysym.BackSpace, xkb.Keysym.Delete, xkb.Keysym.Left, xkb.Keysym.Right => true,
- else => utf8.len > 0 and @intFromEnum(sym) != xkb.Keysym.Return and @intFromEnum(sym) != xkb.Keysym.Tab and @intFromEnum(sym) != xkb.Keysym.Escape,
+ else => utf8.len > 0 and sym != xkb.Keysym.Return and sym != xkb.Keysym.Tab and sym != xkb.Keysym.Escape,
};
}
pub fn key(self: *Popup, sym: xkb.Keysym, utf8: []const u8, mods: wlr.Keyboard.ModifierMask) void {
- const code = @intFromEnum(sym);
- if (self.focus == .settings and (code == xkb.Keysym.Return or code == xkb.Keysym.KP_Enter or code == xkb.Keysym.space)) {
+ if (self.focus == .settings and (sym == xkb.Keysym.Return or sym == xkb.Keysym.KP_Enter or sym == xkb.Keysym.space)) {
self.openSettings();
return;
}
- if (code == xkb.Keysym.Escape) {
+ if (sym == xkb.Keysym.Escape) {
self.output.closeWifi();
return;
}
- if (code == xkb.Keysym.Tab or code == xkb.Keysym.ISO_Left_Tab) {
- self.navigate(mods.shift or code == xkb.Keysym.ISO_Left_Tab);
+ if (sym == xkb.Keysym.Tab or sym == xkb.Keysym.ISO_Left_Tab) {
+ self.navigate(mods.shift or sym == xkb.Keysym.ISO_Left_Tab);
return;
}
- if (code == xkb.Keysym.Return or code == xkb.Keysym.KP_Enter) {
+ if (sym == xkb.Keysym.Return or sym == xkb.Keysym.KP_Enter) {
if (self.focus == .password or self.focus == .ssid) {
if (self.canUse()) self.join();
} else self.activate();
@@ -417,8 +416,8 @@ pub const Popup = struct {
if (!self.canUse()) return;
const input = if (self.focus == .password) &self.password else &self.name;
if (mods.ctrl) {
- if (code == xkb.Keysym.u) input.clear();
- } else if (!mods.alt and !mods.logo) switch (code) {
+ if (sym == xkb.Keysym.u) input.clear();
+ } else if (!mods.alt and !mods.logo) switch (sym) {
xkb.Keysym.BackSpace => input.backspace(),
xkb.Keysym.Delete => input.delete(),
xkb.Keysym.Left => input.left(),
@@ -434,11 +433,11 @@ pub const Popup = struct {
self.refresh();
return;
}
- if (code == xkb.Keysym.Up or code == xkb.Keysym.Down) {
- self.navigate(code == xkb.Keysym.Up);
+ if (sym == xkb.Keysym.Up or sym == xkb.Keysym.Down) {
+ self.navigate(sym == xkb.Keysym.Up);
return;
}
- if (code == xkb.Keysym.space) {
+ if (sym == xkb.Keysym.space) {
self.activate();
self.refresh();
self.ensureFormVisible();
diff --git a/src/night_light/NightLight.zig b/src/night_light/NightLight.zig
index 195da4a..2c0744a 100644
--- a/src/night_light/NightLight.zig
+++ b/src/night_light/NightLight.zig
@@ -13,9 +13,7 @@ const protocol = @import("../ipc/protocol.zig");
const log = std.log.scoped(.night_light);
-const c_time = @cImport({
- @cInclude("time.h");
-});
+const c_time = @import("c");
pub const NightLight = struct {
server: ?*Server = null,
diff --git a/src/output_management.zig b/src/output_management.zig
index e03d199..f7198d9 100644
--- a/src/output_management.zig
+++ b/src/output_management.zig
@@ -190,8 +190,9 @@ fn diff(server: *Server, output: *Output, state: *const wlr.OutputHeadV1.State)
comptime {
// `diff` converts transforms by value.
- for (@typeInfo(output_transform.Transform).@"enum".fields) |field| {
- const wl_value = @intFromEnum(@field(wl.Output.Transform, field.name));
- if (wl_value != field.value) @compileError("output_transform.Transform must match wl_output.transform");
+ const info = @typeInfo(output_transform.Transform).@"enum";
+ for (info.field_names, info.field_values) |name, value| {
+ const wl_value = @intFromEnum(@field(wl.Output.Transform, name));
+ if (wl_value != value) @compileError("output_transform.Transform must match wl_output.transform");
}
}
diff --git a/src/pdf/app.zig b/src/pdf/app.zig
index 47dc165..1889400 100644
--- a/src/pdf/app.zig
+++ b/src/pdf/app.zig
@@ -236,7 +236,7 @@ pub const App = struct {
errdefer std.heap.page_allocator.destroy(secret);
if (c.api.mlock(secret, secret.len) != 0) return error.PasswordMemoryFailed;
errdefer _ = c.api.munlock(secret, secret.len);
- const path = try a.dupeZ(u8, initial_path);
+ const path = try a.dupeSentinel(u8, initial_path, 0);
errdefer a.free(path);
var self = App{
diff --git a/src/pdf/app_keyboard.zig b/src/pdf/app_keyboard.zig
index 66e8e45..5904788 100644
--- a/src/pdf/app_keyboard.zig
+++ b/src/pdf/app_keyboard.zig
@@ -157,7 +157,7 @@ pub fn handleKey(self: *App, sym: u32, utf8: []const u8) void {
'c', 'C' => {
if (if (self.selection_active) self.selected_text else null) |txt| {
if (self.clipboard_text) |c_prev| a.free(c_prev);
- self.clipboard_text = a.dupeZ(u8, txt) catch null;
+ self.clipboard_text = a.dupeSentinel(u8, txt, 0) catch null;
self.clipboard_request = true;
}
},
diff --git a/src/pdf/app_pointer.zig b/src/pdf/app_pointer.zig
index 1baca25..17597cc 100644
--- a/src/pdf/app_pointer.zig
+++ b/src/pdf/app_pointer.zig
@@ -171,7 +171,7 @@ pub fn handleButton(self: *App, button: u32, pressed: bool) void {
.goto_page => |target| self.goToPage(target),
.uri => |u| {
if (!std.mem.startsWith(u8, u, "http://") and !std.mem.startsWith(u8, u, "https://")) return;
- const copy = a.dupeZ(u8, u) catch return;
+ const copy = a.dupeSentinel(u8, u, 0) catch return;
if (self.clipboard_text) |old| a.free(old);
self.clipboard_text = copy;
self.clipboard_request = true;
@@ -244,7 +244,7 @@ pub fn updateSelection(self: *App) void {
const text = content.text orelse return;
const selected = range.text(text);
if (selected.len == 0) return;
- self.selected_text = a.dupeZ(u8, selected) catch return;
+ self.selected_text = a.dupeSentinel(u8, selected, 0) catch return;
self.selection_range = range;
self.selection_active = true;
self.dirty = true;
diff --git a/src/pdf/app_scroll.zig b/src/pdf/app_scroll.zig
index 1bb4841..2296c97 100644
--- a/src/pdf/app_scroll.zig
+++ b/src/pdf/app_scroll.zig
@@ -75,7 +75,7 @@ pub fn executeSearch(self: *App) void {
return;
}
- const qz = a.dupeZ(u8, query) catch return;
+ const qz = a.dupeSentinel(u8, query, 0) catch return;
defer a.free(qz);
for (0..self.n_pages) |p| {
diff --git a/src/pdf/c.zig b/src/pdf/c.zig
index b3c6408..aef6033 100644
--- a/src/pdf/c.zig
+++ b/src/pdf/c.zig
@@ -1,29 +1,6 @@
//! C ABI bindings for Poppler, GLib and libc/Cairo.
-//! GLib/GObject headers are intentionally hand-declared (no @cInclude per AGENTS.md).
-pub const api = @cImport({
- // Translate libc declarations, not glibc's fortified inline wrappers: Zig
- // 0.16 rejects their attribute(error) calls in ReleaseSafe.
- @cUndef("_FORTIFY_SOURCE");
- @cDefine("_GNU_SOURCE", "1");
- @cInclude("cairo.h");
- @cInclude("cairo-pdf.h");
- @cInclude("sys/mman.h");
- @cInclude("sys/eventfd.h");
- @cInclude("sys/stat.h");
- @cInclude("sys/socket.h");
- @cInclude("sys/un.h");
- @cInclude("poll.h");
- @cInclude("unistd.h");
- @cInclude("fcntl.h");
- @cInclude("pthread.h");
- @cInclude("time.h");
- @cInclude("stdlib.h");
- @cInclude("errno.h");
- @cInclude("stdio.h");
- @cInclude("signal.h");
- @cInclude("xkbcommon/xkbcommon.h");
- @cInclude("xkbcommon/xkbcommon-keysyms.h");
-});
+//! GLib/GObject headers are intentionally hand-declared (never translated, per AGENTS.md).
+pub const api = @import("c_gfx");
pub extern fn rediwm_pdf_open_document(path: [*:0]const u8) c_int;
/// `print_fd` is the print helper's socket or -1; it stays open in the sandbox.
@@ -32,7 +9,7 @@ pub extern fn rediwm_pdf_sandbox_enter(document_fd: c_int, display_fd: c_int, pr
/// its socket, or -1.
pub extern fn rediwm_pdf_print_start(document_fd: c_int, path: [*:0]const u8) c_int;
-// GLib & Poppler types declared by hand without @cInclude.
+// GLib & Poppler types declared by hand, not translated.
pub const PopplerDocument = opaque {};
pub const PopplerPage = opaque {};
pub const GBytes = opaque {};
diff --git a/src/pdf/client_print.zig b/src/pdf/client_print.zig
index b9e925b..ecc02d6 100644
--- a/src/pdf/client_print.zig
+++ b/src/pdf/client_print.zig
@@ -50,7 +50,7 @@ pub fn publishClipboard(self: *Client) void {
clip.* = .{
.client = self,
.proxy = source,
- .text = a.dupeZ(u8, text) catch return,
+ .text = a.dupeSentinel(u8, text, 0) catch return,
};
source.setListener(*ClipboardSource, ClipboardSource.event, clip);
source.offer("text/plain;charset=utf-8");
diff --git a/src/pdf/connection.zig b/src/pdf/connection.zig
index e3da44e..0cf0def 100644
--- a/src/pdf/connection.zig
+++ b/src/pdf/connection.zig
@@ -34,7 +34,7 @@ pub fn connect() !*wl.Display {
if (c.mkdtemp(&directory) == null) return error.SocketFailed;
defer _ = c.rmdir(&directory);
var path_storage: [108]u8 = undefined;
- const path = try std.fmt.bufPrintZ(&path_storage, "{s}/wayland", .{directory});
+ const path = try std.fmt.bufPrintSentinel(&path_storage, "{s}/wayland", .{directory}, 0);
var address: c.struct_sockaddr_un = std.mem.zeroes(c.struct_sockaddr_un);
address.sun_family = c.AF_UNIX;
@memcpy(@as([*]u8, @ptrCast(&address.sun_path))[0..path.len], path);
diff --git a/src/pdf/document.zig b/src/pdf/document.zig
index 2c9a499..e6dbcc5 100644
--- a/src/pdf/document.zig
+++ b/src/pdf/document.zig
@@ -273,7 +273,7 @@ pub const Document = struct {
if (text_ptr == null) return null;
defer c.g_free(text_ptr);
- return try allocator.dupeZ(u8, std.mem.span(text_ptr.?));
+ return try allocator.dupeSentinel(u8, std.mem.span(text_ptr.?), 0);
}
/// One rectangle per Unicode character, in top-left page coordinates.
@@ -367,7 +367,7 @@ pub const Document = struct {
if (any_action.type == c.POPPLER_ACTION_URI) {
const uri_action: *c.PopplerActionUri = @ptrCast(@alignCast(action_raw));
if (uri_action.uri) |uri_ptr| {
- const uri_str = try allocator.dupeZ(u8, std.mem.span(uri_ptr));
+ const uri_str = try allocator.dupeSentinel(u8, std.mem.span(uri_ptr), 0);
try results.append(allocator, .{ .area = area, .target = .{ .uri = uri_str } });
}
} else if (any_action.type == c.POPPLER_ACTION_GOTO_DEST) {
@@ -415,7 +415,7 @@ pub const Document = struct {
if (action_raw) |act| {
defer c.poppler_action_free(act);
const any_act: *c.PopplerActionAny = @ptrCast(@alignCast(act));
- const title = if (any_act.title) |t| try allocator.dupeZ(u8, std.mem.span(t)) else try allocator.dupeZ(u8, "");
+ const title = if (any_act.title) |t| try allocator.dupeSentinel(u8, std.mem.span(t), 0) else try allocator.dupeSentinel(u8, "", 0);
var page_target: ?usize = null;
if (any_act.type == c.POPPLER_ACTION_GOTO_DEST) {
diff --git a/src/pdf/main.zig b/src/pdf/main.zig
index a532897..6002814 100644
--- a/src/pdf/main.zig
+++ b/src/pdf/main.zig
@@ -244,7 +244,7 @@ pub fn run(init: std.process.Init.Minimal) !void {
return error.ExpectedDocument;
}
const raw = std.mem.span(args[i]);
- const initial_path = try a.dupeZ(u8, raw);
+ const initial_path = try a.dupeSentinel(u8, raw, 0);
defer a.free(initial_path);
const document_fd = c.rediwm_pdf_open_document(initial_path.ptr);
if (document_fd < 0) return error.CannotOpenRegularFile;
diff --git a/src/pdf/worker.zig b/src/pdf/worker.zig
index a44c7b5..459429c 100644
--- a/src/pdf/worker.zig
+++ b/src/pdf/worker.zig
@@ -223,7 +223,7 @@ pub const Worker = struct {
self.clearPendingLocked();
const dup_pass = if (password) |p| blk: {
- const copy = try std.heap.page_allocator.dupeZ(u8, p);
+ const copy = try std.heap.page_allocator.dupeSentinel(u8, p, 0);
if (c.api.mlock(copy.ptr, copy.len + 1) != 0) {
std.crypto.secureZero(u8, copy);
std.heap.page_allocator.free(copy);
@@ -297,7 +297,7 @@ pub const Worker = struct {
if (generation != self.generation or self.job_count >= self.jobs.len) return;
- const q = try a.dupeZ(u8, query);
+ const q = try a.dupeSentinel(u8, query, 0);
self.jobs[self.job_count] = .{
.kind = .search,
.priority = 4,
diff --git a/src/placeholder_match.zig b/src/placeholder_match.zig
index d173ad4..c56b785 100644
--- a/src/placeholder_match.zig
+++ b/src/placeholder_match.zig
@@ -30,7 +30,7 @@ pub fn matchesPidChain(client_pid: i32, target_pid: i32) bool {
var depth: usize = 0;
while (depth < 5) : (depth += 1) {
var path_buf: [64:0]u8 = undefined;
- const path = std.fmt.bufPrintZ(&path_buf, "/proc/{d}/stat", .{cur_pid}) catch break;
+ const path = std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/stat", .{cur_pid}, 0) catch break;
const fd = std.posix.openat(std.posix.AT.FDCWD, path, .{
.ACCMODE = .RDONLY,
.CLOEXEC = true,
diff --git a/src/polkit/dialog.zig b/src/polkit/dialog.zig
index 080bc7a..0d0202b 100644
--- a/src/polkit/dialog.zig
+++ b/src/polkit/dialog.zig
@@ -202,9 +202,8 @@ pub const Dialog = struct {
return self.focus == .input and !self.waiting and @import("../input/repeat_keys.zig").editing(keysym, utf8);
}
- pub fn key(self: *Dialog, keysym: xkb.Keysym, utf8: []const u8, mods: wlr.Keyboard.ModifierMask) void {
+ pub fn key(self: *Dialog, sym: xkb.Keysym, utf8: []const u8, mods: wlr.Keyboard.ModifierMask) void {
self.caret_edit_ms = anim.nowMs();
- const sym = @intFromEnum(keysym);
if (sym == xkb.Keysym.Escape) return self.cancel();
if (sym == xkb.Keysym.Tab or sym == xkb.Keysym.ISO_Left_Tab) {
self.focus = @enumFromInt((@as(usize, @intFromEnum(self.focus)) + (if (mods.shift or sym == xkb.Keysym.ISO_Left_Tab) @as(usize, 3) else 1)) % 4);
diff --git a/src/polkit/helper.zig b/src/polkit/helper.zig
index 48efdc7..2bb6907 100644
--- a/src/polkit/helper.zig
+++ b/src/polkit/helper.zig
@@ -2,11 +2,7 @@
//! may respond/cancel, but must not destroy this object or dispatch the loop.
const std = @import("std");
const wl = @import("wayland").server.wl;
-const c = @cImport({
- @cInclude("sys/socket.h");
- @cInclude("sys/un.h");
- @cInclude("unistd.h");
-});
+const c = @import("c");
const Child = @import("../session/child.zig");
extern fn rediwm_polkit_spawn([*:0]const u8, *std.posix.pid_t) c_int;
extern fn rediwm_polkit_secret_new() ?*anyopaque;
@@ -68,7 +64,7 @@ pub const Helper = struct {
self.fd = c.socket(c.AF_UNIX, c.SOCK_STREAM | c.SOCK_NONBLOCK | c.SOCK_CLOEXEC, 0);
if (self.fd < 0) return error.SocketFailed;
var spawned = false;
- if (c.connect(self.fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))) < 0) {
+ if (c.connect(self.fd, .{ .__sockaddr__ = @ptrCast(&addr) }, @sizeOf(@TypeOf(addr))) < 0) {
switch (std.posix.errno(@as(c_int, -1))) {
.INPROGRESS => self.connecting = true,
.NOENT, .CONNREFUSED => {
@@ -83,7 +79,7 @@ pub const Helper = struct {
self.child = Child.watch(allocator, loop, pid, self, childExited) catch |err| {
_ = std.os.linux.kill(pid, .KILL);
var status: u32 = 0;
- while (std.os.linux.errno(std.os.linux.wait4(pid, &status, 0, null)) == .INTR) {}
+ while (std.os.linux.errno(std.os.linux.wait4(pid, @ptrCast(&status), 0, null)) == .INTR) {}
return err;
};
spawned = true;
@@ -361,7 +357,7 @@ test "socketpair helper frames split/coalesced reads and wipes sent responses" {
// Maximum accepted response includes its newline in a single fgets buffer.
events.automatic = false;
helper.awaiting_response = true;
- const maximum = [_]u8{'x'} ** max_response;
+ const maximum = @as([max_response]u8, @splat('x'));
try helper.respond(&maximum);
try loop.dispatch(100);
const maximum_n = c.read(fds[1], &response, response.len);
@@ -392,7 +388,7 @@ test "helper bounds responses before copying and wipes every terminal path" {
defer helper.cancel();
// Rejected input never needs an event source and never reaches the buffer.
helper.awaiting_response = true;
- const oversized = [_]u8{'x'} ** 511;
+ const oversized = @as([511]u8, @splat('x'));
try std.testing.expectError(error.ResponseTooLong, helper.respond(&oversized));
for ([_][]const u8{ "a\nb", "a\rb", "a\x00b" }) |bad| try std.testing.expectError(error.InvalidLine, helper.respond(bad));
try std.testing.expect(std.mem.allEqual(u8, secret, 0));
@@ -413,7 +409,7 @@ test "helper bounds responses before copying and wipes every terminal path" {
try std.testing.expect(std.mem.allEqual(u8, secret, 0));
helper.finished = false;
try std.testing.expectError(error.InvalidHelperLine, helper.feed("SUCCESSx\n"));
- const huge = [_]u8{'x'} ** (max_line + 1);
+ const huge = @as([max_line + 1]u8, @splat('x'));
try std.testing.expectError(error.LineTooLong, helper.feed(&huge));
}
@@ -433,7 +429,7 @@ test "helper preserves a backpressured response until cancellation erases it" {
helper.timer = try loop.addTimer(*Helper, Helper.onTimeout, &helper);
const size: c_int = 4096;
try std.testing.expectEqual(0, c.setsockopt(helper.fd, c.SOL_SOCKET, c.SO_SNDBUF, &size, @sizeOf(c_int)));
- const padding = [_]u8{0} ** 4096;
+ const padding = @as([4096]u8, @splat(0));
var full = false;
for (0..16) |_| {
const n = c.send(helper.fd, &padding, padding.len, c.MSG_NOSIGNAL);
diff --git a/src/polkit_test_terminal.zig b/src/polkit_test_terminal.zig
index a771efb..da95ac2 100644
--- a/src/polkit_test_terminal.zig
+++ b/src/polkit_test_terminal.zig
@@ -4,11 +4,7 @@ const std = @import("std");
const wl = @import("wayland").server.wl;
const Agent = @import("polkit/agent.zig").Agent;
const helper = @import("polkit/helper.zig");
-const c = @cImport({
- @cInclude("unistd.h");
- @cInclude("fcntl.h");
- @cInclude("termios.h");
-});
+const c = @import("c");
extern fn rediwm_polkit_secret_new() ?*anyopaque;
extern fn rediwm_polkit_secret_free(*anyopaque) void;
extern fn rediwm_polkit_clear(*anyopaque, usize) void;
diff --git a/src/power_profiles.zig b/src/power_profiles.zig
index 9ad0109..e304039 100644
--- a/src/power_profiles.zig
+++ b/src/power_profiles.zig
@@ -31,8 +31,8 @@ pub const Profile = enum {
performance,
pub fn parse(text: []const u8) ?Profile {
- inline for (std.meta.fields(Profile)) |field| {
- if (std.mem.eql(u8, text, wireName(@enumFromInt(field.value)))) return @enumFromInt(field.value);
+ for (std.meta.tags(Profile)) |profile| {
+ if (std.mem.eql(u8, text, wireName(profile))) return profile;
}
return null;
}
@@ -58,10 +58,10 @@ pub const Profile = enum {
/// daemon offers at least balanced and power-saver; an empty set means the
/// Profiles list has not arrived, so all three are assumed.
pub fn next(active: Profile, available: std.EnumSet(Profile)) Profile {
- const choices = if (available.count() == 0) std.EnumSet(Profile).initFull() else available;
+ const choices = if (available.count() == 0) std.EnumSet(Profile).full else available;
var candidate = active;
- for (0..std.meta.fields(Profile).len) |_| {
- candidate = @enumFromInt((@intFromEnum(candidate) + 1) % std.meta.fields(Profile).len);
+ for (0..@typeInfo(Profile).@"enum".field_names.len) |_| {
+ candidate = @enumFromInt((@intFromEnum(candidate) + 1) % @typeInfo(Profile).@"enum".field_names.len);
if (choices.contains(candidate)) return candidate;
}
return active;
@@ -79,7 +79,7 @@ pub const Manager = struct {
/// forged PropertiesChanged cannot move the OSD.
service_owner: ?[]u8 = null,
active: ?Profile = null,
- available: std.EnumSet(Profile) = .initEmpty(),
+ available: std.EnumSet(Profile) = .empty,
closing: bool = false,
pub fn create(server: *Server, allocator: std.mem.Allocator) !*Manager {
@@ -274,7 +274,7 @@ pub const Manager = struct {
if (self.service_owner) |old| self.allocator.free(old);
self.service_owner = null;
self.active = null;
- self.available = .initEmpty();
+ self.available = .empty;
const name = unique orelse return;
self.service_owner = self.allocator.dupe(u8, name) catch null;
}
@@ -386,7 +386,7 @@ fn parseProperties(reader: *wire.Reader) !Update {
if (std.mem.eql(u8, name, "ActiveProfile") and std.mem.eql(u8, sig, "s")) {
update.active = Profile.parse(try entries.string());
} else if (std.mem.eql(u8, name, "Profiles") and std.mem.eql(u8, sig, "aa{sv}")) {
- var set: std.EnumSet(Profile) = .initEmpty();
+ var set: std.EnumSet(Profile) = .empty;
var profiles = try entries.array(4);
while (profiles.offset < profiles.bytes.len) {
var fields = try profiles.array(8);
@@ -413,13 +413,13 @@ test "profiles round-trip their wire names" {
}
test "cycling wraps and skips profiles the daemon lacks" {
- var all: std.EnumSet(Profile) = .initFull();
+ var all: std.EnumSet(Profile) = .full;
try std.testing.expectEqual(Profile.balanced, next(.power_saver, all));
try std.testing.expectEqual(Profile.performance, next(.balanced, all));
try std.testing.expectEqual(Profile.power_saver, next(.performance, all));
all.remove(.performance);
try std.testing.expectEqual(Profile.power_saver, next(.balanced, all));
- try std.testing.expectEqual(Profile.performance, next(.balanced, .initEmpty()));
+ try std.testing.expectEqual(Profile.performance, next(.balanced, .empty));
}
test "properties parse the active profile and the offered set" {
diff --git a/src/printing/admin.zig b/src/printing/admin.zig
index 2bcc834..714b975 100644
--- a/src/printing/admin.zig
+++ b/src/printing/admin.zig
@@ -799,7 +799,7 @@ test "discovery owns complete identities and rejects unsafe backend addresses" {
try writer.string(field[0]);
try writer.string(field[1]);
}
- const long_id = "MFG:Acme;" ++ "X" ** 600 ++ ";MDL:Label;";
+ const long_id = "MFG:Acme;" ++ @as([600]u8, @splat('X')) ++ ";MDL:Label;";
try writer.alignTo(8);
try writer.string("device-id:0");
try writer.string(long_id);
diff --git a/src/printing/client.zig b/src/printing/client.zig
index 077cc44..c0369f6 100644
--- a/src/printing/client.zig
+++ b/src/printing/client.zig
@@ -444,7 +444,7 @@ fn ueventSocket() c_int {
var addr = std.mem.zeroes(c.struct_sockaddr_nl);
addr.nl_family = c.AF_NETLINK;
addr.nl_groups = 1;
- if (c.bind(fd, @ptrCast(&addr), @sizeOf(c.struct_sockaddr_nl)) != 0) {
+ if (c.bind(fd, .{ .__sockaddr__ = @ptrCast(&addr) }, @sizeOf(c.struct_sockaddr_nl)) != 0) {
_ = c.close(fd);
return -1;
}
@@ -456,7 +456,7 @@ fn drainUevents(fd: c_int) bool {
var bytes: [8192]u8 = undefined;
var sender: c.struct_sockaddr_nl = undefined;
var len: c.socklen_t = @sizeOf(c.struct_sockaddr_nl);
- const n = c.recvfrom(fd, &bytes, bytes.len, 0, @ptrCast(&sender), &len);
+ const n = c.recvfrom(fd, &bytes, bytes.len, 0, .{ .__sockaddr__ = @ptrCast(&sender) }, &len);
if (n <= 0) break;
if (sender.nl_pid != 0) continue;
var words = std.mem.splitScalar(u8, bytes[0..@intCast(n)], 0);
diff --git a/src/printing/daemon_watch.zig b/src/printing/daemon_watch.zig
index c0e6360..9e7cf0d 100644
--- a/src/printing/daemon_watch.zig
+++ b/src/printing/daemon_watch.zig
@@ -2,11 +2,7 @@
//! before sending an IPP notification. This watcher never opens the socket.
const std = @import("std");
const endpoint = @import("endpoint.zig");
-const c = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- @cInclude("sys/inotify.h");
- @cInclude("unistd.h");
-});
+const c = @import("c");
const A = std.mem.Allocator;
pub const Watch = struct {
@@ -24,7 +20,7 @@ pub const Watch = struct {
if (name.len == 0 or std.mem.eql(u8, name, "/")) return null;
const basename = try a.dupe(u8, name);
errdefer a.free(basename);
- const directory = try a.dupeZ(u8, parent);
+ const directory = try a.dupeSentinel(u8, parent, 0);
defer a.free(directory);
const fd = c.inotify_init1(c.IN_CLOEXEC | c.IN_NONBLOCK);
if (fd < 0) {
diff --git a/src/printing/direct.zig b/src/printing/direct.zig
index f38ee10..99bc172 100644
--- a/src/printing/direct.zig
+++ b/src/printing/direct.zig
@@ -60,7 +60,7 @@ pub const Worker = struct {
if (user.len == 0 or user.len > 255 or password.len >= 4096) return error.InvalidCredentials;
for (user) |ch| if (ch < 0x21 or ch == 0x7f) return error.InvalidCredentials;
if (std.mem.indexOfScalar(u8, password, 0) != null) return error.InvalidCredentials;
- const name = try a.dupeZ(u8, user);
+ const name = try a.dupeSentinel(u8, user, 0);
defer a.free(name);
rediwm_cups_credentials(self.native, name, password.ptr, password.len);
}
@@ -74,19 +74,19 @@ pub const Worker = struct {
if (!self.discovery) {
var i: usize = 0;
while (i < signature.len) : (i += 1) switch (signature[i]) {
- 's' => try args.append(mem, try mem.dupeZ(u8, try reader.string())),
+ 's' => try args.append(mem, try mem.dupeSentinel(u8, try reader.string(), 0)),
'b' => try args.append(mem, if (try reader.boolean()) "true" else "false"),
'a' => {
i += 1;
if (i >= signature.len or signature[i] != 's') return error.InvalidSignature;
var values = try reader.array(4);
- while (values.offset < values.bytes.len) try args.append(mem, try mem.dupeZ(u8, try values.string()));
+ while (values.offset < values.bytes.len) try args.append(mem, try mem.dupeSentinel(u8, try values.string(), 0));
},
else => return error.InvalidSignature,
};
try reader.done();
}
- if (rediwm_cups_submit(self.native, try mem.dupeZ(u8, method), @intCast(args.items.len), args.items.ptr, @intFromBool(reset)) != 0) return error.OutOfMemory;
+ if (rediwm_cups_submit(self.native, try mem.dupeSentinel(u8, method, 0), @intCast(args.items.len), args.items.ptr, @intFromBool(reset)) != 0) return error.OutOfMemory;
}
pub fn devices(self: *Worker, writer: *wire.Writer) !void {
const dict = try writer.beginArray(8);
diff --git a/src/printing/http.zig b/src/printing/http.zig
index c1b8875..fc3dfcd 100644
--- a/src/printing/http.zig
+++ b/src/printing/http.zig
@@ -175,7 +175,7 @@ pub fn sendNoWait(server: []const u8, resource: []const u8, body: []const u8) !v
var addr: c.struct_sockaddr_un = std.mem.zeroes(c.struct_sockaddr_un);
addr.sun_family = c.AF_UNIX;
@memcpy(addr.sun_path[0..socket.len], socket);
- if (c.connect(fd, @ptrCast(&addr), @intCast(@offsetOf(c.struct_sockaddr_un, "sun_path") + socket.len + 1)) != 0) return error.ConnectionFailed;
+ if (c.connect(fd, .{ .__sockaddr__ = @ptrCast(&addr) }, @intCast(@offsetOf(c.struct_sockaddr_un, "sun_path") + socket.len + 1)) != 0) return error.ConnectionFailed;
var packet: [2048]u8 = undefined;
const headers = std.fmt.bufPrint(&packet, "POST {s} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/ipp\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n", .{ resource, body.len }) catch return error.RequestTooLarge;
if (headers.len + body.len > packet.len) return error.RequestTooLarge;
@@ -204,7 +204,7 @@ fn connectUnix(socket: []const u8, cancel: c_int, deadline: i64) !c_int {
var addr: c.struct_sockaddr_un = std.mem.zeroes(c.struct_sockaddr_un);
addr.sun_family = c.AF_UNIX;
@memcpy(addr.sun_path[0..socket.len], socket);
- const result = c.connect(fd, @ptrCast(&addr), @intCast(@offsetOf(c.struct_sockaddr_un, "sun_path") + socket.len + 1));
+ const result = c.connect(fd, .{ .__sockaddr__ = @ptrCast(&addr) }, @intCast(@offsetOf(c.struct_sockaddr_un, "sun_path") + socket.len + 1));
if (result < 0) {
const e = std.posix.errno(result);
if (e == .NOENT or e == .CONNREFUSED) return error.CupsUnavailable;
@@ -274,11 +274,11 @@ fn connectTcp(io: ?std.Io, target: endpoint.Endpoint, cancel: c_int, deadline: i
const result = switch (address) {
.ip4 => |ip| blk: {
var addr: std.os.linux.sockaddr.in = .{ .port = std.mem.nativeToBig(u16, ip.port), .addr = @bitCast(ip.bytes) };
- break :blk c.connect(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr)));
+ break :blk c.connect(fd, .{ .__sockaddr__ = @ptrCast(&addr) }, @sizeOf(@TypeOf(addr)));
},
.ip6 => |ip| blk: {
var addr: std.os.linux.sockaddr.in6 = .{ .port = std.mem.nativeToBig(u16, ip.port), .flowinfo = ip.flow, .addr = ip.bytes, .scope_id = ip.interface.index };
- break :blk c.connect(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr)));
+ break :blk c.connect(fd, .{ .__sockaddr__ = @ptrCast(&addr) }, @sizeOf(@TypeOf(addr)));
},
};
if (result == 0) return fd;
@@ -356,17 +356,17 @@ test "remote loopback HTTP preserves authority, resource and body" {
try t.expect(listener >= 0);
defer _ = c.close(listener);
var address: std.os.linux.sockaddr.in = .{ .port = 0, .addr = @bitCast([4]u8{ 127, 0, 0, 1 }) };
- try t.expectEqual(@as(c_int, 0), c.bind(listener, @ptrCast(&address), @sizeOf(@TypeOf(address))));
+ try t.expectEqual(@as(c_int, 0), c.bind(listener, .{ .__sockaddr__ = @ptrCast(&address) }, @sizeOf(@TypeOf(address))));
try t.expectEqual(@as(c_int, 0), c.listen(listener, 1));
var length: c.socklen_t = @sizeOf(@TypeOf(address));
- try t.expectEqual(@as(c_int, 0), c.getsockname(listener, @ptrCast(&address), &length));
+ try t.expectEqual(@as(c_int, 0), c.getsockname(listener, .{ .__sockaddr__ = @ptrCast(&address) }, &length));
const Fixture = struct {
listener: c_int,
bytes: [4096]u8 = undefined,
count: usize = 0,
fn run(self: *@This()) void {
ready(self.listener, c.POLLIN, -1, nowMs() + 3000) catch return;
- const fd = c.accept(self.listener, null, null);
+ const fd = c.accept(self.listener, .{ .__sockaddr__ = null }, null);
if (fd < 0) return;
defer _ = c.close(fd);
while (self.count < self.bytes.len) {
diff --git a/src/printing/native.zig b/src/printing/native.zig
index 1fe2a48..a068e46 100644
--- a/src/printing/native.zig
+++ b/src/printing/native.zig
@@ -1,12 +1 @@
-pub const c = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- @cInclude("sys/socket.h");
- @cInclude("sys/un.h");
- @cInclude("sys/eventfd.h");
- @cInclude("linux/netlink.h");
- @cInclude("poll.h");
- @cInclude("unistd.h");
- @cInclude("pthread.h");
- @cInclude("time.h");
- @cInclude("pwd.h");
-});
+pub const c = @import("c");
diff --git a/src/screenshot/encode.zig b/src/screenshot/encode.zig
index 072752b..84fdbe0 100644
--- a/src/screenshot/encode.zig
+++ b/src/screenshot/encode.zig
@@ -1,8 +1,6 @@
const std = @import("std");
-const c = @cImport({
- @cInclude("png.h");
-});
+const c = @import("c_png");
const PngWriteCtx = struct {
list: *std.ArrayList(u8),
diff --git a/src/screenshot/save.zig b/src/screenshot/save.zig
index 3fa4f10..102bd26 100644
--- a/src/screenshot/save.zig
+++ b/src/screenshot/save.zig
@@ -1,22 +1,14 @@
//! Publish only complete PNGs: file browsers may inspect a path at IN_CREATE.
//! All I/O runs on the capture worker, never on the compositor event loop.
const std = @import("std");
-const c = @cImport({
- // Match files/c.zig: Zig 0.16 cannot translate fortified libc wrappers.
- @cUndef("_FORTIFY_SOURCE");
- @cDefine("_GNU_SOURCE", "1");
- @cInclude("stdlib.h");
- @cInclude("unistd.h");
- @cInclude("fcntl.h");
- @cInclude("stdio.h");
-});
+const c = @import("c");
pub fn writePngFile(path: []const u8, bytes: []const u8) !void {
if (bytes.len < 8 or !std.mem.eql(u8, bytes[0..8], "\x89PNG\r\n\x1a\n")) return error.InvalidPng;
var path_buf: [4096]u8 = undefined;
- const destination = try std.fmt.bufPrintZ(&path_buf, "{s}", .{path});
+ const destination = try std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0);
var temporary_buf: [4096]u8 = undefined;
- const temporary = try std.fmt.bufPrintZ(&temporary_buf, "{s}/.rediwm-screenshot-XXXXXX", .{std.fs.path.dirname(path) orelse "."});
+ const temporary = try std.fmt.bufPrintSentinel(&temporary_buf, "{s}/.rediwm-screenshot-XXXXXX", .{std.fs.path.dirname(path) orelse "."}, 0);
const fd = c.mkostemp(temporary.ptr, c.O_CLOEXEC);
if (fd < 0) return error.CreateFailed;
var closed = false;
diff --git a/src/session/app_scope.zig b/src/session/app_scope.zig
index abeea7b..660863a 100644
--- a/src/session/app_scope.zig
+++ b/src/session/app_scope.zig
@@ -210,10 +210,10 @@ test "unit names escape like systemd and stay under the limit" {
try std.testing.expectEqualStrings("app-rediwm-org.gnome.Nautilus-42.scope", unitName(42, "org.gnome.Nautilus").name());
try std.testing.expectEqualStrings("app-rediwm-brave\\x2dbrowser-7.scope", unitName(7, "brave-browser").name());
try std.testing.expectEqualStrings("app-rediwm-app-1.scope", unitName(1, "").name());
- const long = unitName(2147483647, "x" ** 300);
+ const long = unitName(2147483647, &@as([300]u8, @splat('x')));
try std.testing.expect(long.len <= max_unit);
try std.testing.expect(std.mem.endsWith(u8, long.name(), "-2147483647.scope"));
- const escaped = unitName(5, "-" ** 100);
+ const escaped = unitName(5, &@as([100]u8, @splat('-')));
try std.testing.expect(escaped.len <= max_unit);
try std.testing.expect(std.mem.endsWith(u8, escaped.name(), "\\x2d-5.scope"));
}
diff --git a/src/session/child.zig b/src/session/child.zig
index 783cd6b..4d79e74 100644
--- a/src/session/child.zig
+++ b/src/session/child.zig
@@ -54,7 +54,7 @@ pub fn dispatch(self: *Child) bool {
fn reap(self: *Child) ?u32 {
var status: u32 = 0;
while (true) {
- const rc = linux.wait4(self.pid, &status, linux.W.NOHANG, null);
+ const rc = linux.wait4(self.pid, @ptrCast(&status), linux.W.NOHANG, null);
switch (linux.errno(rc)) {
.INTR => continue,
.SUCCESS => return if (rc == self.pid) status else null,
diff --git a/src/session/dm_ipc.zig b/src/session/dm_ipc.zig
index 617d20f..89fa2eb 100644
--- a/src/session/dm_ipc.zig
+++ b/src/session/dm_ipc.zig
@@ -3,12 +3,7 @@
//! one response. Requests that carry a secret are encoded into a caller-owned
//! buffer that is wiped after sending, so no heap copy of a password ever exists.
const std = @import("std");
-const c = @cImport({
- @cInclude("sys/socket.h");
- @cInclude("sys/un.h");
- @cInclude("unistd.h");
- @cInclude("errno.h");
-});
+const c = @import("c");
/// Protocol frames are small; anything larger is a protocol violation.
pub const max_frame = 64 * 1024;
@@ -230,7 +225,7 @@ test "dm requests are framed JSON in native byte order" {
(try encodeRequest(&out, .cancel))[4..],
);
// The largest password the UI accepts still fits after worst-case escaping.
- const control = [_]u8{1} ** 511;
+ const control = @as([511]u8, @splat(1));
_ = try encodeRequest(&out, .{ .answer = &control });
}
diff --git a/src/session/file_chooser.zig b/src/session/file_chooser.zig
index bd64a11..d7b4c62 100644
--- a/src/session/file_chooser.zig
+++ b/src/session/file_chooser.zig
@@ -9,14 +9,7 @@ const Server = @import("../Server.zig");
const model = @import("../files/chooser.zig");
const protocol = @import("file_chooser_protocol.zig");
const settings = @import("settings_portal.zig");
-const c = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- @cDefine("_GNU_SOURCE", "1");
- @cInclude("sys/mman.h");
- @cInclude("unistd.h");
- @cInclude("fcntl.h");
- @cInclude("signal.h");
-});
+const c = @import("c");
const a = std.heap.c_allocator;
const interface = "org.freedesktop.impl.portal.FileChooser";
const Request = struct {
diff --git a/src/session/greeter.zig b/src/session/greeter.zig
index 2ee088e..7d47194 100644
--- a/src/session/greeter.zig
+++ b/src/session/greeter.zig
@@ -7,11 +7,7 @@ const std = @import("std");
const wl = @import("wayland").server.wl;
const dm_ipc = @import("dm_ipc.zig");
const ws = @import("wayland_sessions.zig");
-const c = @cImport({
- @cInclude("pwd.h");
- @cInclude("unistd.h");
- @cInclude("sys/mman.h");
-});
+const c = @import("c");
extern fn rediwm_secret_clear([*]u8, usize) void;
diff --git a/src/session/lock.zig b/src/session/lock.zig
index 7114eae..0aa25e5 100644
--- a/src/session/lock.zig
+++ b/src/session/lock.zig
@@ -31,12 +31,7 @@ const ImageBuffer = @import("../ImageBuffer.zig");
const lock_account = @import("lock_account.zig");
const lock_events = @import("lock_events.zig");
const lock_input = @import("lock_input.zig");
-pub const c = @cImport({
- @cInclude("time.h");
- @cInclude("unistd.h");
- @cInclude("sys/mman.h");
- @cInclude("sys/prctl.h");
-});
+pub const c = @import("c");
const text_field = ui.widgets.field;
const SecretInput = ui.widgets.secret_input.Input;
const Auth = opaque {};
diff --git a/src/session/lock_input.zig b/src/session/lock_input.zig
index a1d697a..fb32c5a 100644
--- a/src/session/lock_input.zig
+++ b/src/session/lock_input.zig
@@ -145,8 +145,7 @@ pub fn keyRepeats(self: *const Lock, sym: xkb.Keysym, utf8: []const u8) bool {
if (self.busy()) return false;
if (self.focus == 0) return @import("../input/repeat_keys.zig").editing(sym, utf8);
if (self.focus == focus_account or self.focus == focus_session) {
- const value = @intFromEnum(sym);
- return value == xkb.Keysym.Left or value == xkb.Keysym.Right;
+ return sym == xkb.Keysym.Left or sym == xkb.Keysym.Right;
}
return false;
}
@@ -155,8 +154,7 @@ pub fn key(self: *Lock, sym: xkb.Keysym, utf8: []const u8, mods: wlr.Keyboard.Mo
self.caps = mods.caps;
self.caret_edit_ms = anim.nowMs();
defer self.changed();
- const value = @intFromEnum(sym);
- if (value == xkb.Keysym.Escape) {
+ if (sym == xkb.Keysym.Escape) {
self.clear();
self.confirm = null;
self.focus = 0;
@@ -167,13 +165,13 @@ pub fn key(self: *Lock, sym: xkb.Keysym, utf8: []const u8, mods: wlr.Keyboard.Mo
return;
}
if (self.busy()) return;
- switch (value) {
- xkb.Keysym.Tab, xkb.Keysym.ISO_Left_Tab => self.moveFocus(mods.shift or value == xkb.Keysym.ISO_Left_Tab),
- xkb.Keysym.Up, xkb.Keysym.Down => if (!self.prompting()) self.choose(focus_account, if (value == xkb.Keysym.Up) -1 else 1),
+ switch (sym) {
+ xkb.Keysym.Tab, xkb.Keysym.ISO_Left_Tab => self.moveFocus(mods.shift or sym == xkb.Keysym.ISO_Left_Tab),
+ xkb.Keysym.Up, xkb.Keysym.Down => if (!self.prompting()) self.choose(focus_account, if (sym == xkb.Keysym.Up) -1 else 1),
xkb.Keysym.Left, xkb.Keysym.Right => if (self.focus == focus_account or self.focus == focus_session)
- self.choose(self.focus, if (value == xkb.Keysym.Left) -1 else 1)
+ self.choose(self.focus, if (sym == xkb.Keysym.Left) -1 else 1)
else if (self.focus == 0) {
- if (value == xkb.Keysym.Left) self.field().left() else self.field().right();
+ if (sym == xkb.Keysym.Left) self.field().left() else self.field().right();
},
xkb.Keysym.Home => if (self.focus == 0) {
self.input.cursor = 0;
diff --git a/src/session/lock_tests.zig b/src/session/lock_tests.zig
index 56aa600..ef69c55 100644
--- a/src/session/lock_tests.zig
+++ b/src/session/lock_tests.zig
@@ -36,17 +36,17 @@ test "lock password editing clears complete UTF-8 characters and Escape never un
lock.key(@enumFromInt('a'), "a", .{});
lock.key(@enumFromInt('e'), "é", .{});
try std.testing.expectEqualStrings("aé", lock.field().value());
- lock.key(@enumFromInt(xkb.Keysym.BackSpace), "", .{});
+ lock.key(xkb.Keysym.BackSpace, "", .{});
try std.testing.expectEqualStrings("a", lock.field().value());
try std.testing.expectEqual(@as(u8, 0), lock.password[2]);
lock.reveal = true;
- lock.key(@enumFromInt(xkb.Keysym.Escape), "", .{});
+ lock.key(xkb.Keysym.Escape, "", .{});
try std.testing.expect(server.locker == &lock);
try std.testing.expect(!lock.reveal);
try std.testing.expectEqual(@as(usize, 0), lock.input.len);
for (lock.password) |byte| try std.testing.expectEqual(@as(u8, 0), byte);
// Oversized input must not produce a partial UTF-8 sequence or overrun.
- const full = [_]u8{'a'} ** 511;
+ const full = @as([511]u8, @splat('a'));
lock.key(@enumFromInt('a'), &full, .{});
lock.key(@enumFromInt('e'), "é", .{});
try std.testing.expectEqual(@as(usize, 511), lock.input.len);
@@ -146,9 +146,7 @@ test "lock raster scales to small outputs and renders a solid accent unlock butt
try std.testing.expectApproxEqAbs(ui.theme.shellPalette().accent[channel] * 255, got, 1);
}
if (size[0] == 1672) {
- const env = @cImport({
- @cInclude("stdlib.h");
- });
+ const env = @import("c");
if (env.getenv("REDIWM_LOCK_PREVIEW")) |path| {
const bytes = try @import("../screenshot/encode.zig").encodePng(std.testing.allocator, @intCast(buf.width), @intCast(buf.height), buf.pixels, @intCast(buf.width));
defer std.testing.allocator.free(bytes);
@@ -266,10 +264,7 @@ test "lock covers new outputs and follows layout and mode changes without UI" {
}
test "greeter signs in through rediwm-dm and exits only once the session starts" {
- const sock = @cImport({
- @cInclude("sys/socket.h");
- @cInclude("unistd.h");
- });
+ const sock = @import("c");
const peer = struct {
fd: c_int,
buf: [4096]u8 = undefined,
@@ -330,24 +325,24 @@ test "greeter signs in through rediwm-dm and exits only once the session starts"
try std.testing.expectEqualStrings("rediwm-test-a", std.mem.sliceTo(&lock.user, 0));
// Account and session choice.
- lock.key(@enumFromInt(xkb.Keysym.Down), "", .{});
+ lock.key(xkb.Keysym.Down, "", .{});
try std.testing.expectEqualStrings("rediwm-test-b", std.mem.sliceTo(&lock.user, 0));
- lock.key(@enumFromInt(xkb.Keysym.Up), "", .{});
+ lock.key(xkb.Keysym.Up, "", .{});
try std.testing.expectEqualStrings("Test A", std.mem.sliceTo(&lock.name, 0));
- lock.key(@enumFromInt(xkb.Keysym.ISO_Left_Tab), "", .{ .shift = true });
+ lock.key(xkb.Keysym.ISO_Left_Tab, "", .{ .shift = true });
try std.testing.expectEqual(focus_account, lock.focus);
- lock.key(@enumFromInt(xkb.Keysym.Tab), "", .{});
+ lock.key(xkb.Keysym.Tab, "", .{});
try std.testing.expectEqual(@as(u8, 0), lock.focus);
- for (0..3) |_| lock.key(@enumFromInt(xkb.Keysym.Tab), "", .{});
+ for (0..3) |_| lock.key(xkb.Keysym.Tab, "", .{});
try std.testing.expectEqual(focus_session, lock.focus);
- lock.key(@enumFromInt(xkb.Keysym.Right), "", .{});
+ lock.key(xkb.Keysym.Right, "", .{});
try std.testing.expectEqualStrings("sway", greeter.selectedSession().?.id);
- lock.key(@enumFromInt(xkb.Keysym.Left), "", .{});
+ lock.key(xkb.Keysym.Left, "", .{});
lock.focus = 0;
// The password typed up front answers dm's first question.
for ("pw") |ch| lock.key(@enumFromInt(ch), &.{ch}, .{});
- lock.key(@enumFromInt(xkb.Keysym.Return), "", .{});
+ lock.key(xkb.Keysym.Return, "", .{});
try std.testing.expectEqualStrings("{\"type\":\"login\",\"user\":\"rediwm-test-a\"}", try daemon.read());
try std.testing.expectEqual(@as(usize, 0), lock.input.len);
lock.key(@enumFromInt('x'), "x", .{});
@@ -369,7 +364,7 @@ test "greeter signs in through rediwm-dm and exits only once the session starts"
try std.testing.expect(lock.prompting() and lock.reveal and !lock.busy());
for ("123") |ch| lock.key(@enumFromInt(ch), &.{ch}, .{});
try std.testing.expectEqualStrings("Code:", lock.status);
- lock.key(@enumFromInt(xkb.Keysym.Return), "", .{});
+ lock.key(xkb.Keysym.Return, "", .{});
try std.testing.expectEqualStrings("{\"type\":\"answer\",\"response\":\"123\"}", try daemon.read());
// Wrong answers cancel the attempt and never start a session.
@@ -385,14 +380,14 @@ test "greeter signs in through rediwm-dm and exits only once the session starts"
// Escape abandons a question.
lock.retry_at = 0;
for ("pw") |ch| lock.key(@enumFromInt(ch), &.{ch}, .{});
- lock.key(@enumFromInt(xkb.Keysym.Return), "", .{});
+ lock.key(xkb.Keysym.Return, "", .{});
_ = try daemon.read();
daemon.write("{\"type\":\"question\",\"kind\":\"secret\",\"text\":\"Password:\"}");
greeter.pump();
_ = try daemon.read();
daemon.write("{\"type\":\"question\",\"kind\":\"secret\",\"text\":\"New password:\"}");
greeter.pump();
- lock.key(@enumFromInt(xkb.Keysym.Escape), "", .{});
+ lock.key(xkb.Keysym.Escape, "", .{});
try std.testing.expectEqualStrings("{\"type\":\"cancel\"}", try daemon.read());
daemon.write("{\"type\":\"ok\"}");
greeter.pump();
@@ -401,7 +396,7 @@ test "greeter signs in through rediwm-dm and exits only once the session starts"
// Success starts the chosen session with its desktop identity, and the
// greeter exits only after dm accepts it.
for ("pw") |ch| lock.key(@enumFromInt(ch), &.{ch}, .{});
- lock.key(@enumFromInt(xkb.Keysym.Return), "", .{});
+ lock.key(xkb.Keysym.Return, "", .{});
_ = try daemon.read();
daemon.write("{\"type\":\"ok\"}");
greeter.pump();
@@ -411,7 +406,7 @@ test "greeter signs in through rediwm-dm and exits only once the session starts"
);
for (greeter.pending) |byte| try std.testing.expectEqual(@as(u8, 0), byte);
try std.testing.expect(!server.shutting_down);
- lock.key(@enumFromInt(xkb.Keysym.Down), "", .{});
+ lock.key(xkb.Keysym.Down, "", .{});
try std.testing.expectEqualStrings("rediwm-test-a", std.mem.sliceTo(&lock.user, 0));
daemon.write("{\"type\":\"ok\"}");
greeter.pump();
@@ -420,10 +415,7 @@ test "greeter signs in through rediwm-dm and exits only once the session starts"
}
test "greeter reports a lost login service and exits to be replaced" {
- const sock = @cImport({
- @cInclude("sys/socket.h");
- @cInclude("unistd.h");
- });
+ const sock = @import("c");
const display = try wl.Server.create();
defer display.destroy();
var server: Server = undefined;
@@ -445,7 +437,7 @@ test "greeter reports a lost login service and exits to be replaced" {
}
// No REDIWM_GREETER_FD: a clear message, not a crash or an unlock.
for ("pw") |ch| lock.key(@enumFromInt(ch), &.{ch}, .{});
- lock.key(@enumFromInt(xkb.Keysym.Return), "", .{});
+ lock.key(xkb.Keysym.Return, "", .{});
try std.testing.expectEqualStrings("No login service", lock.status);
try std.testing.expectEqual(@as(usize, 0), lock.input.len);
try std.testing.expectEqual(greeter_mod.Phase.idle, greeter.phase);
@@ -454,7 +446,7 @@ test "greeter reports a lost login service and exits to be replaced" {
try std.testing.expectEqual(@as(c_int, 0), sock.socketpair(sock.AF_UNIX, sock.SOCK_STREAM | sock.SOCK_CLOEXEC, 0, &fds));
try greeter.adopt(fds[0]);
for ("pw") |ch| lock.key(@enumFromInt(ch), &.{ch}, .{});
- lock.key(@enumFromInt(xkb.Keysym.Return), "", .{});
+ lock.key(xkb.Keysym.Return, "", .{});
try std.testing.expect(lock.busy());
_ = sock.close(fds[1]);
greeter.pump();
@@ -502,9 +494,7 @@ test "greeter raster shows account arrows and the session chooser" {
};
try std.testing.expect(lit.any(buf, 30 * geo.s, height - 90 * geo.s, 120 * geo.s, height - 60 * geo.s));
try std.testing.expect(lit.any(buf, width / 2 - 130 * geo.s, geo.top + 244 * geo.s, width / 2 - 90 * geo.s, geo.top + 304 * geo.s));
- const env = @cImport({
- @cInclude("stdlib.h");
- });
+ const env = @import("c");
if (env.getenv("REDIWM_GREETER_PREVIEW")) |path| {
const bytes = try @import("../screenshot/encode.zig").encodePng(std.testing.allocator, @intCast(buf.width), @intCast(buf.height), buf.pixels, @intCast(buf.width));
defer std.testing.allocator.free(bytes);
diff --git a/src/session/lock_view.zig b/src/session/lock_view.zig
index adaed9f..7b1fea1 100644
--- a/src/session/lock_view.zig
+++ b/src/session/lock_view.zig
@@ -236,7 +236,7 @@ pub fn paint(r: *ui.paint.Renderer, lock: *Lock, w: f32, h: f32, clock_24h: bool
var date_buf: [96]u8 = @splat(0);
var period: [16]u8 = @splat(0);
var pattern: [256]u8 = undefined;
- const date_pattern = std.fmt.bufPrintZ(&pattern, "{s}", .{i18n.trc("date", "%A, %B %-d")}) catch "%A, %B %-d";
+ const date_pattern = std.fmt.bufPrintSentinel(&pattern, "{s}", .{i18n.trc("date", "%A, %B %-d")}, 0) catch "%A, %B %-d";
if (c.localtime_r(&raw, &tm) != null) {
_ = c.strftime(&time_buf, time_buf.len, if (clock_24h) "%H:%M" else "%l:%M", &tm);
if (!clock_24h) _ = c.strftime(&period, period.len, "%p", &tm);
diff --git a/src/session/login_appearance.zig b/src/session/login_appearance.zig
index 155782a..fc0a257 100644
--- a/src/session/login_appearance.zig
+++ b/src/session/login_appearance.zig
@@ -4,13 +4,7 @@ const std = @import("std");
const theme = @import("ui").theme;
const png = @import("../png.zig");
const wallpapers = @import("../wallpapers.zig");
-const c = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- @cInclude("fcntl.h");
- @cInclude("sys/stat.h");
- @cInclude("unistd.h");
- @cInclude("stdio.h");
-});
+const c = @import("c");
pub const root = @import("../dm/appearance.zig").root;
const max_theme_bytes = 64 * 1024;
const max_edge = 1920;
@@ -35,7 +29,7 @@ pub fn writableDirectory(a: std.mem.Allocator) ?[]u8 {
fn openDirectory(path: []const u8, uid: u32) !c_int {
var buf: [std.fs.max_path_bytes]u8 = undefined;
- const z = try std.fmt.bufPrintZ(&buf, "{s}", .{path});
+ const z = try std.fmt.bufPrintSentinel(&buf, "{s}", .{path}, 0);
const fd = c.open(z, c.O_RDONLY | c.O_DIRECTORY | c.O_NOFOLLOW | c.O_CLOEXEC);
if (fd < 0) return error.OpenDirectoryFailed;
errdefer _ = c.close(fd);
@@ -75,7 +69,7 @@ fn writeAtomic(path: []const u8, name: [:0]const u8, parts: []const []const u8)
const dir = try openDirectory(path, c.getuid());
defer _ = c.close(dir);
var buf: [100]u8 = undefined;
- const temp = try std.fmt.bufPrintZ(&buf, ".{s}.{d}.{d}", .{ name, c.getpid(), serial.fetchAdd(1, .monotonic) });
+ const temp = try std.fmt.bufPrintSentinel(&buf, ".{s}.{d}.{d}", .{ name, c.getpid(), serial.fetchAdd(1, .monotonic) }, 0);
const fd = c.openat(dir, temp, c.O_WRONLY | c.O_CREAT | c.O_EXCL | c.O_CLOEXEC | c.O_NOFOLLOW, @as(c_uint, 0o600));
if (fd < 0) return error.CreateFileFailed;
defer _ = c.close(fd);
diff --git a/src/session/login_bus.zig b/src/session/login_bus.zig
index 5dc535b..f55c966 100644
--- a/src/session/login_bus.zig
+++ b/src/session/login_bus.zig
@@ -244,7 +244,7 @@ const Reply = struct {
error_text: ?[]u8 = null,
signature: []u8 = &.{},
body: []u8 = &.{},
- endian: std.builtin.Endian = .little,
+ endian: std.lang.Endian = .little,
fn callback(owner: ?*anyopaque, _: *Connection, result: Connection.Failure!wire.Message) void {
const self: *Reply = @ptrCast(@alignCast(owner.?));
diff --git a/src/session/services.zig b/src/session/services.zig
index 952f278..e57aecd 100644
--- a/src/session/services.zig
+++ b/src/session/services.zig
@@ -268,7 +268,7 @@ test "session helper tracking and bounded shutdown" {
child.id = null; // ownership was transferred to the watcher
try mgr.loop.dispatch(1000);
var status: u32 = 0;
- try std.testing.expectEqual(std.os.linux.E.CHILD, std.os.linux.errno(std.os.linux.wait4(pid, &status, std.os.linux.W.NOHANG, null)));
+ try std.testing.expectEqual(std.os.linux.E.CHILD, std.os.linux.errno(std.os.linux.wait4(pid, @ptrCast(&status), std.os.linux.W.NOHANG, null)));
// Immediate exits are readable even if they occur before registration.
var quick = try std.process.spawn(std.testing.io, .{ .argv = &.{ "/bin/sh", "-c", "exit 7" } });
@@ -278,5 +278,5 @@ test "session helper tracking and bounded shutdown" {
quick.id = null;
try mgr.loop.dispatch(1000);
try std.testing.expectEqual(@as(usize, 0), mgr.countTracked());
- try std.testing.expectEqual(std.os.linux.E.CHILD, std.os.linux.errno(std.os.linux.wait4(quick_pid, &status, std.os.linux.W.NOHANG, null)));
+ try std.testing.expectEqual(std.os.linux.E.CHILD, std.os.linux.errno(std.os.linux.wait4(quick_pid, @ptrCast(&status), std.os.linux.W.NOHANG, null)));
}
diff --git a/src/session/supervisor.zig b/src/session/supervisor.zig
index a4bb0cf..e13be5d 100644
--- a/src/session/supervisor.zig
+++ b/src/session/supervisor.zig
@@ -261,7 +261,7 @@ fn descendants(allocator: std.mem.Allocator, root: Pid) !PidSet {
var path_buf: [64]u8 = undefined;
var dirents: [4096]u8 align(8) = undefined;
while (pending.pop()) |pid| {
- const task_path = try std.fmt.bufPrintZ(&path_buf, "/proc/{d}/task", .{pid});
+ const task_path = try std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/task", .{pid}, 0);
const dir = sys.openZ(task_path, .{ .ACCMODE = .RDONLY, .DIRECTORY = true, .CLOEXEC = true }, 0) catch continue;
defer sys.close(dir);
while (true) {
@@ -274,7 +274,7 @@ fn descendants(allocator: std.mem.Allocator, root: Pid) !PidSet {
const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&entry.name)), 0);
if (name[0] == '.') continue;
var children_path: [96]u8 = undefined;
- const file = std.fmt.bufPrintZ(&children_path, "/proc/{d}/task/{s}/children", .{ pid, name }) catch continue;
+ const file = std.fmt.bufPrintSentinel(&children_path, "/proc/{d}/task/{s}/children", .{ pid, name }, 0) catch continue;
const fd = sys.openZ(file, .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, 0) catch continue;
defer sys.close(fd);
const text = sys.readAll(allocator, fd) catch continue;
@@ -309,10 +309,10 @@ fn stopGroup(allocator: std.mem.Allocator, compositor: Pid, compositor_fd: i32,
awaitExit(allocator, &handles, compositor_fd, 2000);
var status: u32 = 0;
- const reaped = sys.retry(linux.wait4, .{ compositor, &status, linux.W.NOHANG, null }) catch 0;
+ const reaped = sys.retry(linux.wait4, .{ compositor, @as(*i32, @ptrCast(&status)), linux.W.NOHANG, null }) catch 0;
for (handles.keys()) |pid| {
var ignored: u32 = 0;
- _ = linux.wait4(pid, &ignored, linux.W.NOHANG, null);
+ _ = linux.wait4(pid, @ptrCast(&ignored), linux.W.NOHANG, null);
}
if (reaped != compositor) {
sys.diagnostic("killed compositor remains in kernel I/O; leaving it to logind teardown", .{});
diff --git a/src/session/wayland_sessions.zig b/src/session/wayland_sessions.zig
index 3c9a0a6..dfce692 100644
--- a/src/session/wayland_sessions.zig
+++ b/src/session/wayland_sessions.zig
@@ -99,9 +99,7 @@ pub fn desktopList(a: std.mem.Allocator, names: []const u8) ![]const u8 {
return out;
}
-const c = @cImport({
- @cInclude("unistd.h");
-});
+const c = @import("c");
fn isExecutable(path_z: [:0]const u8) bool {
return c.access(path_z.ptr, c.X_OK) == 0;
@@ -110,12 +108,12 @@ fn isExecutable(path_z: [:0]const u8) bool {
pub fn executable(program: []const u8, search: []const u8) bool {
var buf: [std.fs.max_path_bytes + 1]u8 = undefined;
if (std.mem.indexOfScalar(u8, program, '/') != null) {
- const z = std.fmt.bufPrintZ(&buf, "{s}", .{program}) catch return false;
+ const z = std.fmt.bufPrintSentinel(&buf, "{s}", .{program}, 0) catch return false;
return isExecutable(z);
}
var dirs = std.mem.tokenizeScalar(u8, search, ':');
while (dirs.next()) |dir| {
- const z = std.fmt.bufPrintZ(&buf, "{s}/{s}", .{ dir, program }) catch continue;
+ const z = std.fmt.bufPrintSentinel(&buf, "{s}/{s}", .{ dir, program }, 0) catch continue;
if (isExecutable(z)) return true;
}
return false;
diff --git a/src/session_main.zig b/src/session_main.zig
index 5c2346d..08af812 100644
--- a/src/session_main.zig
+++ b/src/session_main.zig
@@ -89,7 +89,7 @@ pub fn main(init: std.process.Init) !u8 {
fn loginSession(arena: std.mem.Allocator, bus: *login_bus.Bus, runtime_env: ?[]const u8, env: *std.process.Environ.Map, lease: *?Publication) !void {
const session = try bus.login(arena);
const runtime = runtime_env orelse return error.NoRuntimeDir;
- const runtime_z = try arena.dupeZ(u8, runtime);
+ const runtime_z = try arena.dupeSentinel(u8, runtime, 0);
var info: linux.Statx = undefined;
_ = try sys.check(linux.statx(linux.AT.FDCWD, runtime_z, 0, .{ .UID = true, .MODE = true }, &info));
if (info.uid != linux.getuid() or info.mode & 0o077 != 0) {
@@ -112,7 +112,7 @@ fn makePath(arena: std.mem.Allocator, path: []const u8) !void {
var end: usize = 1;
while (end <= path.len) : (end += 1) {
if (end != path.len and path[end] != '/') continue;
- const partial = try arena.dupeZ(u8, path[0..end]);
+ const partial = try arena.dupeSentinel(u8, path[0..end], 0);
switch (linux.errno(linux.mkdirat(linux.AT.FDCWD, partial, 0o700))) {
.SUCCESS, .EXIST => {},
else => |err| return sys.errnoError(err),
diff --git a/src/session_restart.zig b/src/session_restart.zig
new file mode 100644
index 0000000..3b950ec
--- /dev/null
+++ b/src/session_restart.zig
@@ -0,0 +1,261 @@
+//! rediwm-restart: restart this user's installed RediWM after an update, never
+//! a development or nested instance.
+//!
+//! Run by install-session.sh as the login user. It finds the IPC socket, checks
+//! through SO_PEERCRED that the listener is this user's process running the
+//! installed executable, asks it to restart, then waits until the same PID
+//! answers again from the new executable. Usage:
+//! `rediwm-restart [installed [socket]]` (default /usr/local/bin/rediwm). The
+//! socket is an argument, never `REDIWM_SOCKET`: a shell started from the live
+//! session inherits that variable, and a stray run would restart the desktop.
+const std = @import("std");
+const linux = std.os.linux;
+const c = std.posix.system;
+
+const default_installed = "/usr/local/bin/rediwm";
+const io_timeout_s = 3;
+const ready_timeout_ms = 20_000;
+const poll_interval_ms = 200;
+
+const Ucred = extern struct { pid: i32, uid: u32, gid: u32 };
+
+const Session = struct {
+ path: []const u8,
+ fd: c_int,
+ pid: i32,
+};
+
+const RequestError = error{ Disconnected, TimedOut, BadReply, OutOfMemory };
+
+pub fn main(init: std.process.Init) u8 {
+ const allocator = std.heap.c_allocator;
+ const args = init.minimal.args.vector;
+ const installed: []const u8 = if (args.len > 1) std.mem.span(args[1]) else default_installed;
+ const socket: ?[]const u8 = if (args.len > 2) std.mem.span(args[2]) else null;
+ run(allocator, init.minimal.environ, installed, socket) catch |err| {
+ std.debug.print("Installed, but restart failed: {s}\n", .{errorText(err)});
+ return 1;
+ };
+ return 0;
+}
+
+fn errorText(err: anyerror) []const u8 {
+ return switch (err) {
+ error.MultipleSessions => "Multiple installed sessions found; pass the socket path as the second argument to choose one.",
+ error.NotReady => "Restart did not become ready within 20 seconds; check the RediWM session log.",
+ error.Rejected => "Restart rejected by the compositor",
+ else => @errorName(err),
+ };
+}
+
+fn run(allocator: std.mem.Allocator, environ: std.process.Environ, installed: []const u8, socket: ?[]const u8) !void {
+ var arena_state: std.heap.ArenaAllocator = .init(allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ const paths = try socketPaths(arena, environ, socket);
+ var found: std.ArrayList(Session) = .empty;
+ for (paths) |path| {
+ const session = connect(arena, path, installed) orelse continue;
+ try found.append(arena, session);
+ }
+ if (found.items.len == 0) {
+ say("Installed ReleaseSafe. No installed RediWM session found; select RediWM at login.\n");
+ return;
+ }
+ if (found.items.len != 1) {
+ for (found.items) |s| closeFd(s.fd);
+ return error.MultipleSessions;
+ }
+ const session = found.items[0];
+
+ {
+ defer closeFd(session.fd);
+ // Probe before sending: old versions cannot acquire new restart support
+ // merely by replacing their executable on disk.
+ const capabilities = try request(arena, session.fd, "{\"version\":1,\"command\":\"capabilities\"}\n");
+ if (!hasCapability(capabilities, "restart_shell")) {
+ say("Installed ReleaseSafe. This running version lacks clean restart support. " ++
+ "Log out and back in once; subsequent installs restart automatically.\n");
+ return;
+ }
+ say("Restarting RediWM; connected applications will close.\n");
+ const ignore: std.posix.Sigaction = .{
+ .handler = .{ .handler = std.posix.SIG.IGN },
+ .mask = std.posix.sigemptyset(),
+ .flags = 0,
+ };
+ std.posix.sigaction(.HUP, &ignore, null);
+ if (request(arena, session.fd, "{\"version\":1,\"command\":\"restart_shell\"}\n")) |reply| {
+ if (reply.get("Err") != null) return error.Rejected;
+ } else |err| switch (err) {
+ // Shutdown can close IPC before its buffered reply is flushed.
+ error.Disconnected, error.TimedOut => {},
+ else => |e| return e,
+ }
+ }
+ try waitReady(arena, session, installed);
+}
+
+/// The sockets to try: an explicit one, this display's, or every session's.
+fn socketPaths(arena: std.mem.Allocator, environ: std.process.Environ, socket: ?[]const u8) ![]const []const u8 {
+ if (socket) |explicit| return try arena.dupe([]const u8, &.{explicit});
+ const runtime = environ.getPosix("XDG_RUNTIME_DIR") orelse
+ try std.fmt.allocPrint(arena, "/run/user/{d}", .{c.getuid()});
+ if (environ.getPosix("WAYLAND_DISPLAY")) |display| {
+ return try arena.dupe([]const u8, &.{try std.fmt.allocPrint(arena, "{s}/rediwm-{s}.sock", .{ runtime, display })});
+ }
+ var list: std.ArrayList([]const u8) = .empty;
+ const dir_path = try std.fmt.allocPrintSentinel(arena, "{s}", .{runtime}, 0);
+ const dir = std.c.opendir(dir_path) orelse return list.items;
+ defer _ = std.c.closedir(dir);
+ while (std.c.readdir(dir)) |entry| {
+ const name = std.mem.sliceTo(&entry.name, 0);
+ if (!std.mem.startsWith(u8, name, "rediwm-") or !std.mem.endsWith(u8, name, ".sock")) continue;
+ try list.append(arena, try std.fmt.allocPrint(arena, "{s}/{s}", .{ runtime, name }));
+ }
+ std.mem.sort([]const u8, list.items, {}, struct {
+ fn less(_: void, a: []const u8, b: []const u8) bool {
+ return std.mem.lessThan(u8, a, b);
+ }
+ }.less);
+ return list.items;
+}
+
+/// Connects and accepts only this user's process running `installed`.
+fn connect(arena: std.mem.Allocator, path: []const u8, installed: []const u8) ?Session {
+ if (path.len >= 107) return null;
+ const fd = c.socket(std.posix.AF.UNIX, std.posix.SOCK.STREAM | std.posix.SOCK.CLOEXEC, 0);
+ if (fd < 0) return null;
+ errdefer closeFd(fd);
+ const tv: std.posix.timeval = .{ .sec = io_timeout_s, .usec = 0 };
+ _ = c.setsockopt(fd, std.posix.SOL.SOCKET, std.posix.SO.RCVTIMEO, @ptrCast(&tv), @sizeOf(std.posix.timeval));
+ _ = c.setsockopt(fd, std.posix.SOL.SOCKET, std.posix.SO.SNDTIMEO, @ptrCast(&tv), @sizeOf(std.posix.timeval));
+
+ var addr: std.posix.sockaddr.un = .{ .family = std.posix.AF.UNIX, .path = undefined };
+ @memset(&addr.path, 0);
+ @memcpy(addr.path[0..path.len], path);
+ const addr_len: std.posix.socklen_t = @intCast(@offsetOf(std.posix.sockaddr.un, "path") + path.len + 1);
+ if (c.connect(fd, @ptrCast(&addr), addr_len) < 0) {
+ closeFd(fd);
+ return null;
+ }
+
+ var cred: Ucred = undefined;
+ var cred_len: std.posix.socklen_t = @sizeOf(Ucred);
+ if (c.getsockopt(fd, std.posix.SOL.SOCKET, std.posix.SO.PEERCRED, @ptrCast(&cred), &cred_len) < 0 or
+ cred.uid != c.getuid() or
+ !runsInstalled(arena, cred.pid, installed))
+ {
+ closeFd(fd);
+ return null;
+ }
+ return .{ .path = path, .fd = fd, .pid = cred.pid };
+}
+
+fn runsInstalled(arena: std.mem.Allocator, pid: i32, installed: []const u8) bool {
+ const link = std.fmt.allocPrintSentinel(arena, "/proc/{d}/exe", .{pid}, 0) catch return false;
+ var buf: [std.posix.PATH_MAX]u8 = undefined;
+ const n = c.readlink(link, &buf, buf.len);
+ if (n <= 0) return false;
+ const deleted = " (deleted)";
+ var exe: []const u8 = buf[0..@intCast(n)];
+ if (std.mem.endsWith(u8, exe, deleted)) exe = exe[0 .. exe.len - deleted.len];
+ return std.mem.eql(u8, exe, installed);
+}
+
+/// Sends one request line and returns the reply's top-level object.
+fn request(arena: std.mem.Allocator, fd: c_int, line: []const u8) RequestError!std.json.ObjectMap {
+ var sent: usize = 0;
+ while (sent < line.len) {
+ const n = c.write(fd, line.ptr + sent, line.len - sent);
+ if (n < 0) return failure(std.posix.errno(n));
+ sent += @intCast(n);
+ }
+ var data: std.ArrayList(u8) = .empty;
+ var chunk: [4096]u8 = undefined;
+ while (std.mem.indexOfScalar(u8, data.items, '\n') == null) {
+ const n = c.read(fd, &chunk, chunk.len);
+ if (n < 0) return failure(std.posix.errno(n));
+ if (n == 0) return error.Disconnected;
+ try data.appendSlice(arena, chunk[0..@intCast(n)]);
+ }
+ const first = data.items[0..std.mem.indexOfScalar(u8, data.items, '\n').?];
+ const value = std.json.parseFromSliceLeaky(std.json.Value, arena, first, .{}) catch return error.BadReply;
+ return switch (value) {
+ .object => |o| o,
+ else => error.BadReply,
+ };
+}
+
+fn failure(err: std.posix.E) RequestError {
+ return switch (err) {
+ .AGAIN => error.TimedOut,
+ else => error.Disconnected,
+ };
+}
+
+fn hasCapability(reply: std.json.ObjectMap, name: []const u8) bool {
+ const ok = switch (reply.get("Ok") orelse return false) {
+ .object => |o| o,
+ else => return false,
+ };
+ const list = switch (ok.get("Capabilities") orelse return false) {
+ .array => |a| a,
+ else => return false,
+ };
+ for (list.items) |item| switch (item) {
+ .string => |s| if (std.mem.eql(u8, s, name)) return true,
+ else => {},
+ };
+ return false;
+}
+
+/// Waits until the same PID runs the new executable and answers `Version`.
+fn waitReady(arena: std.mem.Allocator, session: Session, installed: []const u8) !void {
+ const installed_z = try std.fmt.allocPrintSentinel(arena, "{s}", .{installed}, 0);
+ const exe_z = try std.fmt.allocPrintSentinel(arena, "/proc/{d}/exe", .{session.pid}, 0);
+ const expected = fileId(installed_z) orelse return error.NotReady;
+ const deadline = nowMs() + ready_timeout_ms;
+ while (nowMs() < deadline) : (sleepMs(poll_interval_ms)) {
+ const current = fileId(exe_z) orelse continue;
+ if (!std.meta.eql(current, expected)) continue;
+ const ready = connect(arena, session.path, installed) orelse continue;
+ defer closeFd(ready.fd);
+ if (ready.pid != session.pid) continue;
+ const reply = request(arena, ready.fd, "{\"version\":1,\"command\":\"version\"}\n") catch continue;
+ if (reply.get("Ok") == null) continue;
+ say("ReleaseSafe restarted successfully.\n");
+ return;
+ }
+ return error.NotReady;
+}
+
+const FileId = struct { dev_major: u32, dev_minor: u32, ino: u64 };
+
+fn fileId(path: [*:0]const u8) ?FileId {
+ var stx: linux.Statx = undefined;
+ const rc = linux.statx(linux.AT.FDCWD, path, 0, .{ .INO = true }, &stx);
+ if (linux.errno(rc) != .SUCCESS) return null;
+ return .{ .dev_major = stx.dev_major, .dev_minor = stx.dev_minor, .ino = stx.ino };
+}
+
+fn nowMs() i64 {
+ var ts: std.posix.timespec = undefined;
+ if (std.posix.errno(c.clock_gettime(std.posix.CLOCK.MONOTONIC, &ts)) != .SUCCESS) return 0;
+ return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);
+}
+
+fn sleepMs(ms: u32) void {
+ var ts: std.posix.timespec = .{ .sec = 0, .nsec = @as(isize, ms) * 1_000_000 };
+ _ = c.nanosleep(&ts, null);
+}
+
+/// Progress goes to stdout; only the final failure line uses stderr.
+fn say(comptime text: []const u8) void {
+ _ = c.write(std.posix.STDOUT_FILENO, text.ptr, text.len);
+}
+
+fn closeFd(fd: c_int) void {
+ _ = c.close(fd);
+}
diff --git a/src/share_picker/c.zig b/src/share_picker/c.zig
index b2d5f82..cde6b9a 100644
--- a/src/share_picker/c.zig
+++ b/src/share_picker/c.zig
@@ -1,13 +1 @@
-pub const api = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- @cDefine("_GNU_SOURCE", "1");
- @cInclude("cairo.h");
- @cInclude("sys/mman.h");
- @cInclude("poll.h");
- @cInclude("unistd.h");
- @cInclude("fcntl.h");
- @cInclude("time.h");
- @cInclude("signal.h");
- @cInclude("xkbcommon/xkbcommon.h");
- @cInclude("xkbcommon/xkbcommon-keysyms.h");
-});
+pub const api = @import("c_gfx");
diff --git a/src/share_picker/client.zig b/src/share_picker/client.zig
index 85a0bac..24cb972 100644
--- a/src/share_picker/client.zig
+++ b/src/share_picker/client.zig
@@ -515,7 +515,7 @@ pub fn run(labels: []const []const u8) !sources.Decision {
self.xdg_toplevel.setListener(*Client, Client.xdgToplevelEvent, &self);
self.xdg_toplevel.setAppId("rediwm-share-picker");
var title: [256]u8 = undefined;
- self.xdg_toplevel.setTitle(std.fmt.bufPrintZ(&title, "{s}", .{i18n.tr("Share screen")}) catch "Share screen");
+ self.xdg_toplevel.setTitle(std.fmt.bufPrintSentinel(&title, "{s}", .{i18n.tr("Share screen")}, 0) catch "Share screen");
self.xdg_toplevel.setMinSize(320, 200 + CSD_TITLEBAR_H);
if (self.decoration_manager) |mgr| {
diff --git a/src/snap.zig b/src/snap.zig
index 0a74fee..bfe8f0d 100644
--- a/src/snap.zig
+++ b/src/snap.zig
@@ -285,8 +285,8 @@ test "tiles share their splits and keep the gap" {
test "a huge gap leaves every tile at least a pixel" {
const tiny: wlr.Box = .{ .x = 0, .y = 0, .width = 20, .height = 11 };
- inline for (std.meta.fields(Tile)) |field| {
- const rect = tileRect(tiny, @field(Tile, field.name), 512);
+ inline for (@typeInfo(Tile).@"enum".field_names) |field_name| {
+ const rect = tileRect(tiny, @field(Tile, field_name), 512);
try testing.expect(rect.width >= 1 and rect.height >= 1);
}
}
diff --git a/src/start_menu/applications.zig b/src/start_menu/applications.zig
index 40e04cc..7c5faed 100644
--- a/src/start_menu/applications.zig
+++ b/src/start_menu/applications.zig
@@ -418,7 +418,7 @@ pub const Catalog = struct {
fn addWatch(self: *Catalog, dir: []const u8, mask: u32) void {
if (self.watched_paths.contains(dir)) return;
var zbuf: [std.posix.PATH_MAX]u8 = undefined;
- const zdir = std.fmt.bufPrintZ(&zbuf, "{s}", .{dir}) catch return;
+ const zdir = std.fmt.bufPrintSentinel(&zbuf, "{s}", .{dir}, 0) catch return;
const wd = std.c.inotify_add_watch(self.watch_fd, zdir.ptr, mask);
if (wd < 0) return;
const owned = self.allocator.dupe(u8, dir) catch return;
diff --git a/src/start_menu/desktop_file.zig b/src/start_menu/desktop_file.zig
index 572725c..55d9b12 100644
--- a/src/start_menu/desktop_file.zig
+++ b/src/start_menu/desktop_file.zig
@@ -229,7 +229,7 @@ pub fn checkTryExec(try_exec: []const u8, environ: std.process.Environ) bool {
while (it.next()) |dir| {
if (dir.len == 0) continue;
var buf: [std.posix.PATH_MAX]u8 = undefined;
- const candidate = std.fmt.bufPrintZ(&buf, "{s}/{s}", .{ dir, try_exec }) catch continue;
+ const candidate = std.fmt.bufPrintSentinel(&buf, "{s}/{s}", .{ dir, try_exec }, 0) catch continue;
if (c.access(candidate.ptr, c.X_OK) == 0) return true;
}
return false;
diff --git a/src/start_menu/launch.zig b/src/start_menu/launch.zig
index 73ac2ea..21a757d 100644
--- a/src/start_menu/launch.zig
+++ b/src/start_menu/launch.zig
@@ -449,10 +449,10 @@ fn launchDbusActivatable(server: *Server, entry: *const AppEntry, uris: []const
errdefer arena.deinit();
const a = arena.allocator();
var owned = entry.*;
- inline for (@typeInfo(AppEntry).@"struct".fields) |field| {
- if (field.type == []const u8) @field(owned, field.name) = try a.dupe(u8, @field(entry, field.name));
- if (field.type == ?[]const u8) {
- if (@field(entry, field.name)) |value| @field(owned, field.name) = try a.dupe(u8, value);
+ inline for (@typeInfo(AppEntry).@"struct".field_names) |field_name| {
+ if (@FieldType(AppEntry, field_name) == []const u8) @field(owned, field_name) = try a.dupe(u8, @field(entry, field_name));
+ if (@FieldType(AppEntry, field_name) == ?[]const u8) {
+ if (@field(entry, field_name)) |value| @field(owned, field_name) = try a.dupe(u8, value);
}
}
const owned_uris = try a.alloc([]const u8, uris.len);
diff --git a/src/start_menu/menu_keys.zig b/src/start_menu/menu_keys.zig
index dac5b6a..05d594b 100644
--- a/src/start_menu/menu_keys.zig
+++ b/src/start_menu/menu_keys.zig
@@ -70,15 +70,15 @@ pub fn handleKey(
// Left/right navigate the quick-launch strip; typing returns to search.
if (menu.card_selection) |selected| {
- if (@intFromEnum(keysym) == xkb.Keysym.Left or @intFromEnum(keysym) == xkb.Keysym.Right) {
- menu.card_selection = if (@intFromEnum(keysym) == xkb.Keysym.Left) selected -| 1 else @min(selected + 1, menu.card_count - 1);
+ if (keysym == xkb.Keysym.Left or keysym == xkb.Keysym.Right) {
+ menu.card_selection = if (keysym == xkb.Keysym.Left) selected -| 1 else @min(selected + 1, menu.card_count - 1);
menu.buildTree();
menu.requestRepaint();
return true;
}
}
// Pressed:
- switch (@intFromEnum(keysym)) {
+ switch (keysym) {
xkb.Keysym.Escape => {
if (Output.fromWlr(menu.wlr_output)) |output| output.closeStartMenu();
return true;
@@ -131,7 +131,7 @@ pub fn handleKey(
// Match on the *unshifted* keysym so Ctrl+Shift+A is still
// select-all, and accept both cases for layouts that
// report them differently.
- switch (@intFromEnum(keysym)) {
+ switch (keysym) {
xkb.Keysym.a, xkb.Keysym.A => return menu.editKey(.select_all, edit_mods),
xkb.Keysym.c, xkb.Keysym.C => return menu.editKey(.copy, edit_mods),
xkb.Keysym.x, xkb.Keysym.X => return menu.editKey(.cut, edit_mods),
diff --git a/src/start_menu/search.zig b/src/start_menu/search.zig
index 3212542..fdd227c 100644
--- a/src/start_menu/search.zig
+++ b/src/start_menu/search.zig
@@ -265,7 +265,11 @@ test "search word prefix in name" {
}
test "search folds translated names aliases and arbitrarily long fields" {
- const long_prefix = "Long " ** 80;
+ const long_prefix = comptime blk: {
+ var repeated: []const u8 = "";
+ for (0..80) |_| repeated = repeated ++ "Long ";
+ break :blk repeated;
+ };
const apps = [_]AppEntry{
.{ .id = "camera", .desktop_file_path = "", .name = "Cámara", .exec = "camera" },
.{ .id = "terminal", .desktop_file_path = "", .name = "Терминал", .exec = "terminal" },
diff --git a/src/system_monitor/actions.zig b/src/system_monitor/actions.zig
index 24377df..72aa0f8 100644
--- a/src/system_monitor/actions.zig
+++ b/src/system_monitor/actions.zig
@@ -23,7 +23,7 @@ pub fn execute(identity: proc.Identity, kind: Kind) !void {
// fdinfo identifies the task referred to by THIS pidfd, not whichever task
// currently occupies /proc/PID. An exited pidfd reports Pid: -1.
var path_buf: [64]u8 = undefined;
- const path = try std.fmt.bufPrintZ(&path_buf, "/proc/self/fdinfo/{d}", .{pidfd});
+ const path = try std.fmt.bufPrintSentinel(&path_buf, "/proc/self/fdinfo/{d}", .{pidfd}, 0);
var info_buf: [4096]u8 = undefined;
const info = try proc.readAt(c.AT_FDCWD, path, &info_buf);
var lines = std.mem.splitScalar(u8, info, '\n');
diff --git a/src/system_monitor/model.zig b/src/system_monitor/model.zig
index ff50e0b..d6db2f9 100644
--- a/src/system_monitor/model.zig
+++ b/src/system_monitor/model.zig
@@ -31,7 +31,7 @@ pub const Model = struct {
if (self.query.len > 0) {
var pid_buf: [32]u8 = undefined;
const pid = std.fmt.bufPrint(&pid_buf, "{d}", .{row.identity.pid}) catch unreachable;
- if (std.ascii.indexOfIgnoreCase(row.name, self.query) == null and std.ascii.indexOfIgnoreCase(row.user, self.query) == null and std.mem.indexOf(u8, pid, self.query) == null) continue;
+ if (std.ascii.findIgnoreCase(row.name, self.query) == null and std.ascii.findIgnoreCase(row.user, self.query) == null and std.mem.indexOf(u8, pid, self.query) == null) continue;
}
try self.rows.append(self.allocator, i);
}
diff --git a/src/system_monitor/proc.zig b/src/system_monitor/proc.zig
index fedca66..cb1f1b6 100644
--- a/src/system_monitor/proc.zig
+++ b/src/system_monitor/proc.zig
@@ -1,16 +1,6 @@
//! Bounded Linux proc readers. No compositor, Wayland or UI dependencies.
const std = @import("std");
-pub const c = @cImport({
- @cUndef("_FORTIFY_SOURCE");
- @cDefine("_GNU_SOURCE", "1");
- @cInclude("unistd.h");
- @cInclude("fcntl.h");
- @cInclude("dirent.h");
- @cInclude("pwd.h");
- @cInclude("poll.h");
- @cInclude("sys/eventfd.h");
- @cInclude("time.h");
-});
+pub const c = @import("c");
pub const Identity = struct {
pid: i32,
@@ -69,7 +59,7 @@ pub fn readAt(dir: c_int, path: [*:0]const u8, buf: []u8) ![]const u8 {
pub fn openProcess(pid: i32) !c_int {
if (pid <= 0) return error.ProcessExited;
var buf: [64]u8 = undefined;
- const path = try std.fmt.bufPrintZ(&buf, "/proc/{d}", .{pid});
+ const path = try std.fmt.bufPrintSentinel(&buf, "/proc/{d}", .{pid}, 0);
const fd = c.open(path, c.O_DIRECTORY | c.O_RDONLY | c.O_CLOEXEC | c.O_NOFOLLOW);
if (fd < 0) return switch (std.posix.errno(fd)) {
.ACCES, .PERM => error.PermissionDenied,
diff --git a/src/systemd/bus.zig b/src/systemd/bus.zig
index d6d9694..ae8175c 100644
--- a/src/systemd/bus.zig
+++ b/src/systemd/bus.zig
@@ -176,7 +176,7 @@ pub fn propertiesChanged(self: *Client, object: []const u8, body: *wire.Reader)
const snap = self.fresh();
const unit = snap.at(object) orelse return;
var touched = false;
- var delivered: std.EnumSet(Prop) = .initEmpty();
+ var delivered: std.EnumSet(Prop) = .empty;
var values = try body.array(8);
while (values.offset < values.bytes.len) {
try values.alignTo(8);
diff --git a/src/systemd_edit.zig b/src/systemd_edit.zig
index 62bad50..e5c9df6 100644
--- a/src/systemd_edit.zig
+++ b/src/systemd_edit.zig
@@ -4,10 +4,7 @@ const std = @import("std");
const systemd = @import("systemd.zig");
const gpa = @import("main.zig").gpa;
const Child = @import("session/child.zig");
-const c = @cImport({
- @cInclude("sys/socket.h");
- @cInclude("unistd.h");
-});
+const c = @import("c");
pub const Request = struct {
client: *systemd.Client,
diff --git a/src/taskbar/c_time.zig b/src/taskbar/c_time.zig
index 25cf681..0e2e5be 100644
--- a/src/taskbar/c_time.zig
+++ b/src/taskbar/c_time.zig
@@ -1,6 +1,3 @@
//! The C time and locale declarations the taskbar clock shares across its files.
-pub const c = @cImport({
- @cInclude("locale.h");
- @cInclude("time.h");
-});
+pub const c = @import("c");
diff --git a/src/taskbar/clock.zig b/src/taskbar/clock.zig
index 48456e3..589ca1b 100644
--- a/src/taskbar/clock.zig
+++ b/src/taskbar/clock.zig
@@ -36,7 +36,7 @@ pub fn scheduleClockTick(bar: *Taskbar) void {
}
pub fn updateClockLocale(bar: *Taskbar) void {
- const name = gpa.dupeZ(u8, bar.server.config.region.formats) catch return;
+ const name = gpa.dupeSentinel(u8, bar.server.config.region.formats, 0) catch return;
defer gpa.free(name);
// Keep a private locale: changing the process locale would affect workers.
const locale = c_time.newlocale(c_time.LC_TIME_MASK, name, null);
diff --git a/src/theme_main.zig b/src/theme_main.zig
index 4220c13..d04e6f2 100644
--- a/src/theme_main.zig
+++ b/src/theme_main.zig
@@ -28,7 +28,7 @@ fn native(rc: c_int) !void {
return error.PackValidationFailed;
}
fn z(path: []const u8) ![:0]u8 {
- return a.dupeZ(u8, path);
+ return a.dupeSentinel(u8, path, 0);
}
fn validate(io: std.Io, root: []const u8, id: []const u8) !packs.Pack {
const path = try std.fs.path.join(a, &.{ root, "theme.toml" });
@@ -132,7 +132,7 @@ fn run(init: std.process.Init) !void {
command = try terminal.argv(a, raw, palette, opacity, modern);
}
const argv = try a.allocSentinel(?[*:0]const u8, command.len, null);
- for (argv, command) |*dest, arg| dest.* = (try a.dupeZ(u8, arg)).ptr;
+ for (argv, command) |*dest, arg| dest.* = (try a.dupeSentinel(u8, arg, 0)).ptr;
_ = execvp(argv[0].?, argv.ptr);
return error.TerminalExecFailed;
}
diff --git a/src/toplevel/create.zig b/src/toplevel/create.zig
index f0bb12a..79fe94c 100644
--- a/src/toplevel/create.zig
+++ b/src/toplevel/create.zig
@@ -257,17 +257,17 @@ pub fn createPlaceholder(
const body_color = col.Straight.fromRgba(theme.global.window_bg).premultiply();
const body_rect = try col.createRect(nodes.content_tree, init_w, init_h, body_color);
- const desktop_id = try gpa.dupeZ(u8, entry.id);
+ const desktop_id = try gpa.dupeSentinel(u8, entry.id, 0);
errdefer gpa.free(desktop_id);
- const name = try gpa.dupeZ(u8, entry.name);
+ const name = try gpa.dupeSentinel(u8, entry.name, 0);
errdefer gpa.free(name);
- const app_id = try gpa.dupeZ(u8, if (entry.startup_wm_class) |wmc| wmc else entry.id);
+ const app_id = try gpa.dupeSentinel(u8, if (entry.startup_wm_class) |wmc| wmc else entry.id, 0);
errdefer gpa.free(app_id);
- const startup_wm_class = if (entry.startup_wm_class) |wmc| try gpa.dupeZ(u8, wmc) else null;
+ const startup_wm_class = if (entry.startup_wm_class) |wmc| try gpa.dupeSentinel(u8, wmc, 0) else null;
errdefer if (startup_wm_class) |wmc| gpa.free(wmc);
- const icon = if (entry.icon) |ico| try gpa.dupeZ(u8, ico) else null;
+ const icon = if (entry.icon) |ico| try gpa.dupeSentinel(u8, ico, 0) else null;
errdefer if (icon) |ico| gpa.free(ico);
- const token = if (token_str) |tok| try gpa.dupeZ(u8, tok) else null;
+ const token = if (token_str) |tok| try gpa.dupeSentinel(u8, tok, 0) else null;
errdefer if (token) |tok| gpa.free(tok);
toplevel.* = .{
diff --git a/src/ui/cairo.zig b/src/ui/cairo.zig
index b031faa..a139289 100644
--- a/src/ui/cairo.zig
+++ b/src/ui/cairo.zig
@@ -2,10 +2,9 @@
// share picker, the desktop): text through text.zig instead of Cairo's toy
// font API, and the shared components (paint.zig, widgets/) through an
// offscreen layer composited by Cairo, so its clip and transform still apply.
-// Each app has its own `@cImport` of cairo.h, so contexts cross as
-// `*anyopaque`.
+// Contexts cross as `*anyopaque`, keeping cairo types out of the interface.
const std = @import("std");
-const c = @cImport(@cInclude("cairo.h"));
+const c = @import("c_gfx");
const paint = @import("paint.zig");
const theme = @import("theme.zig");
const text = @import("text.zig");
@@ -364,7 +363,7 @@ test "a scrollbar thumb paints its look through cairo" {
var hot = scrollbar.look(g, .{ .wide = 1, .accent = 1, .shine = 1 }, 8, palette);
drawScrollbar(cr, hot);
c.cairo_surface_flush(surface);
- var expected = [_]u32{0} ** (40 * 60);
+ var expected = @as([40 * 60]u32, @splat(0));
var renderer = paint.Renderer.init(&expected, 40, 60, 1.5);
hot.rect.x += 0.25;
hot.rect.y += 0.5;
diff --git a/src/ui/compose.zig b/src/ui/compose.zig
index 08ccba4..c590b27 100644
--- a/src/ui/compose.zig
+++ b/src/ui/compose.zig
@@ -12,9 +12,7 @@
//! presses a dead key never loads one, and one table is shared by every
//! `Compose` in the process.
const std = @import("std");
-const c = @cImport({
- @cInclude("xkbcommon/xkbcommon-compose.h");
-});
+const c = @import("c_gfx");
/// Longest normalized locale name kept (`ll_CC.UTF-8` plus slack).
const max_locale = 48;
@@ -207,7 +205,7 @@ test "locale names get a UTF-8 encoding and lose their modifier" {
try std.testing.expectEqualStrings(fallback_locale, normalizeLocale(&buf, "C"));
try std.testing.expectEqualStrings(fallback_locale, normalizeLocale(&buf, "POSIX"));
try std.testing.expectEqualStrings(fallback_locale, normalizeLocale(&buf, "C.UTF-8"));
- try std.testing.expectEqualStrings(fallback_locale, normalizeLocale(&buf, "x" ** 60));
+ try std.testing.expectEqualStrings(fallback_locale, normalizeLocale(&buf, &@as([60]u8, @splat('x'))));
}
test "ordinary keys pass through without loading a table" {
diff --git a/src/ui/context_menu.zig b/src/ui/context_menu.zig
index 70a7e01..66671e4 100644
--- a/src/ui/context_menu.zig
+++ b/src/ui/context_menu.zig
@@ -1,6 +1,6 @@
//! Shared context-menu appearance for Files, Editor and the desktop.
const std = @import("std");
-const c = @cImport(@cInclude("cairo.h"));
+const c = @import("c_gfx");
const ui = @import("cairo.zig");
const theme = @import("theme.zig");
const IconId = @import("layout.zig").IconId;
diff --git a/src/ui/fold.zig b/src/ui/fold.zig
index 3403035..e9b0cf8 100644
--- a/src/ui/fold.zig
+++ b/src/ui/fold.zig
@@ -208,6 +208,10 @@ test "fold matching maps expansion and decomposed accent offsets" {
try std.testing.expect(startsWith("Æsir", "ae", .{}));
try std.testing.expect(eql("ÉLAN", "e\u{301}lan", .{}));
try std.testing.expectEqual(std.math.Order.lt, order("Äpfel", "Zebra", .{}));
- const long = "Préfixe " ** 100;
+ const long = comptime blk: {
+ var repeated: []const u8 = "";
+ for (0..100) |_| repeated = repeated ++ "Préfixe ";
+ break :blk repeated;
+ };
try std.testing.expect(contains(long ++ "Терминал", "терм", .{}));
}
diff --git a/src/ui/font_fallback.zig b/src/ui/font_fallback.zig
index 3e2a420..784b8ba 100644
--- a/src/ui/font_fallback.zig
+++ b/src/ui/font_fallback.zig
@@ -2,13 +2,11 @@
// text.zig; this module answers "which installed file covers this character
// or family?" so fallback does not hardcode paths.
//
-// fontconfig.h is a clean C API (no glib), so it @cInclude's unlike rsvg.
+// fontconfig.h is a clean C API (no glib), so it is translated, unlike rsvg.
const std = @import("std");
const Allocator = std.mem.Allocator;
-const c = @cImport({
- @cInclude("fontconfig/fontconfig.h");
-});
+const c = @import("c_gfx");
const log = std.log.scoped(.fontconfig);
@@ -211,7 +209,7 @@ fn candidateFromPattern(allocator: Allocator, font: *c.FcPattern) ?Candidate {
var cs: ?*c.FcCharSet = null;
if (c.FcPatternGetCharSet(font, c.FC_CHARSET, 0, &cs) != c.FcResultMatch) return null;
const copied = c.FcCharSetCopy(cs orelse return null) orelse return null;
- const path = allocator.dupeZ(u8, file) catch {
+ const path = allocator.dupeSentinel(u8, file, 0) catch {
c.FcCharSetDestroy(copied);
return null;
};
diff --git a/src/ui/paint_tests.zig b/src/ui/paint_tests.zig
index 4c8c17d..13dbe75 100644
--- a/src/ui/paint_tests.zig
+++ b/src/ui/paint_tests.zig
@@ -33,7 +33,7 @@ test "scroll underlay paints beneath rows, which skip their own fill when told t
r.fillRect(scroll.computed_x, scroll.computed_y, scroll.computed_width, 10, .{ .color = .{ 1, 0, 0, 1 } });
}
};
- var pixels = [_]u32{0} ** (20 * 20);
+ var pixels = @as([20 * 20]u32, @splat(0));
var r = Renderer.init(&pixels, 20, 20, 1);
var row = Widget{
.kind = .{ .row = .{ .selected = true, .underlay = true } },
@@ -73,7 +73,7 @@ test "scroll underlay paints beneath rows, which skip their own fill when told t
}
test "fillRect paints solid color inside a device-pixel buffer" {
- var pixels = [_]u32{0} ** (10 * 10);
+ var pixels = @as([10 * 10]u32, @splat(0));
var r = Renderer.init(&pixels, 10, 10, 1);
r.fillRect(1, 1, 4, 4, .{ .color = .{ 1, 0, 0, 1 } });
// Center of the fill should be fully opaque red; a corner outside it stays clear.
@@ -82,7 +82,7 @@ test "fillRect paints solid color inside a device-pixel buffer" {
}
test "fillRect respects the active clip rect" {
- var pixels = [_]u32{0} ** (10 * 10);
+ var pixels = @as([10 * 10]u32, @splat(0));
var r = Renderer.init(&pixels, 10, 10, 1);
r.clip = .{ .x = 0, .y = 0, .w = 5, .h = 10 };
r.fillRect(0, 0, 10, 10, .{ .color = .{ 1, 1, 1, 1 } });
@@ -92,7 +92,7 @@ test "fillRect respects the active clip rect" {
test "replacement fills preserve alpha, rounded corners and damage clips" {
for ([_]f32{ 1, 1.5 }) |scale| {
- var pixels = [_]u32{0xffeeeeee} ** (30 * 30);
+ var pixels = @as([30 * 30]u32, @splat(0xffeeeeee));
var r = Renderer.init(&pixels, 30, 30, scale);
const style: RectStyle = .{ .color = .{ 0.4, 0.2, 0.1, 0.5 }, .radius = 4, .replace = true };
r.fillRect(2, 2, 16, 16, style);
@@ -185,7 +185,7 @@ test "prototype button states retain neutral premultiplied fills" {
const saved = theme.global;
defer theme.global = saved;
theme.global = .{};
- var pixels = [_]u32{0} ** (30 * 30);
+ var pixels = @as([30 * 30]u32, @splat(0));
var renderer = Renderer.init(&pixels, 30, 30, 1);
const Callback = struct {
fn call(_: ?*anyopaque, _: usize) void {}
@@ -382,12 +382,12 @@ test "smooth image sampling is exact at one to one, blends between pixels and sh
// Shrinking a flat translucent image by 1.3 keeps its premultiplied colour,
// also at the edge, where the footprint leaves the image.
- const flat = [_]u32{0x80402010} ** 16;
+ const flat = @as([16]u32, @splat(0x80402010));
const small: Image = .{ .pixels = &flat, .width = 4, .height = 4 };
for ([_]f32{ 0.1, 0.5, 2, 3.9 }) |at| try std.testing.expectEqual(@as(u32, 0x80402010), boxSample(small, at, at, 1.3));
// Placed 1:1 on a pixel boundary it reproduces the image.
- var pixels = [_]u32{0} ** 16;
+ var pixels = @as([16]u32, @splat(0));
var r = Renderer.init(&pixels, 4, 4, 1);
r.drawImageSmooth(1, 1, 2, 2, 0, image);
try std.testing.expectEqual(black, pixels[1 * 4 + 1]);
diff --git a/src/ui/shell_icons.zig b/src/ui/shell_icons.zig
index 3bcc3e0..2497477 100644
--- a/src/ui/shell_icons.zig
+++ b/src/ui/shell_icons.zig
@@ -2,9 +2,7 @@
//! tinting happens at paint time, so hover/selection never rerasterizes SVGs.
const std = @import("std");
const IconId = @import("layout.zig").IconId;
-const c = @cImport({
- @cInclude("cairo.h");
-});
+const c = @import("c_gfx");
/// The start-button logo; not an `IconId` glyph because it keeps its own colours.
pub const redi_logo = @embedFile("redi-logo");
/// The Settings app's colour icon (`settings_icon_name`), for when neither the
@@ -43,7 +41,7 @@ const Entry = struct { id: IconId, mask: Mask };
var cache: [64]?Entry = @splat(null);
var next: usize = 0;
-var overrides: [std.meta.fields(IconId).len]?[]u8 = @splat(null);
+var overrides: [@typeInfo(IconId).@"enum".field_names.len]?[]u8 = @splat(null);
var pack_root: []const u8 = "";
var source_mutex: std.posix.system.pthread_mutex_t = .{};
diff --git a/src/ui/text.zig b/src/ui/text.zig
index 7e6dd3d..8080e28 100644
--- a/src/ui/text.zig
+++ b/src/ui/text.zig
@@ -7,14 +7,7 @@
const std = @import("std");
const gpa = @import("memory").gpa;
const font_fallback = @import("font_fallback.zig");
-pub const c = @cImport({
- @cInclude("ft2build.h");
- @cInclude("freetype/freetype.h");
- @cInclude("freetype/ftmm.h");
- @cInclude("freetype/ftsizes.h");
- @cInclude("hb.h");
- @cInclude("hb-ft.h");
-});
+pub const c = @import("c_gfx");
const log = std.log.scoped(.text);
@@ -79,7 +72,7 @@ pub const color_load_flags: c_int = c.FT_LOAD_DEFAULT | c.FT_LOAD_COLOR;
pub var ft_library: c.FT_Library = null;
pub var faces: std.ArrayListUnmanaged(Face) = .empty;
pub var chains: [font_count]std.ArrayListUnmanaged(u32) = @splat(.empty);
-pub const font_count = std.meta.fields(Font).len;
+pub const font_count = @typeInfo(Font).@"enum".field_names.len;
pub var coverage: std.AutoHashMapUnmanaged(u64, u32) = .empty;
pub const no_face = std.math.maxInt(u32);
diff --git a/src/ui/theme.zig b/src/ui/theme.zig
index d666a73..fe9718d 100644
--- a/src/ui/theme.zig
+++ b/src/ui/theme.zig
@@ -490,7 +490,7 @@ pub fn taskbar(comptime token: TaskbarToken) @FieldType(Theme, @tagName(token))
/// holds, so nothing else of `t` (its strings in particular) is kept.
pub fn taskbarTokens(t: Theme) Theme {
var out: Theme = .{};
- inline for (std.meta.fields(TaskbarToken)) |field| @field(out, field.name) = @field(t, field.name);
+ inline for (@typeInfo(TaskbarToken).@"enum".field_names) |field_name| @field(out, field_name) = @field(t, field_name);
return out;
}
@@ -498,8 +498,8 @@ pub fn taskbarTokens(t: Theme) Theme {
/// compare as `writeTaskbarInto` stores them, so a saved and reloaded theme
/// still equals the preset it came from.
pub fn taskbarTokensEql(a: Theme, b: Theme) bool {
- inline for (std.meta.fields(TaskbarToken)) |field| {
- if (!sameWritten(@field(a, field.name), @field(b, field.name))) return false;
+ inline for (@typeInfo(TaskbarToken).@"enum".field_names) |field_name| {
+ if (!sameWritten(@field(a, field_name), @field(b, field_name))) return false;
}
return true;
}
@@ -535,19 +535,19 @@ pub const RadiusPreset = enum { sharp, default, round };
/// Whether a token is one the Sharp/Default/Round presets rescale. The
/// taskbar's corner radius is a shape of its own (its square default has
/// nothing to scale), so a preset must neither reset nor be undone by it.
-fn presetRadius(comptime field: std.builtin.Type.StructField) bool {
- if (field.type != f32) return false;
- if (!std.mem.startsWith(u8, field.name, "radius") and !std.mem.endsWith(u8, field.name, "_radius")) return false;
- return !std.mem.eql(u8, field.name, "taskbar_radius");
+fn presetRadius(comptime name: []const u8) bool {
+ if (@FieldType(Theme, name) != f32) return false;
+ if (!std.mem.startsWith(u8, name, "radius") and !std.mem.endsWith(u8, name, "_radius")) return false;
+ return !std.mem.eql(u8, name, "taskbar_radius");
}
pub fn applyRadiusPreset(t: *Theme, preset: RadiusPreset) void {
@setEvalBranchQuota(10000);
const defaults: Theme = .{};
- inline for (std.meta.fields(Theme)) |field| {
- if (comptime presetRadius(field)) {
- const base = @field(defaults, field.name);
- @field(t, field.name) = switch (preset) {
+ inline for (@typeInfo(Theme).@"struct".field_names) |field_name| {
+ if (comptime presetRadius(field_name)) {
+ const base = @field(defaults, field_name);
+ @field(t, field_name) = switch (preset) {
.sharp => @min(base, 4),
.default => base,
.round => base * 1.3,
@@ -564,9 +564,9 @@ pub fn radiusPreset(t: Theme) ?RadiusPreset {
var candidate: Theme = .{};
applyRadiusPreset(&candidate, preset);
var matches = true;
- inline for (std.meta.fields(Theme)) |field| {
- if (comptime presetRadius(field)) {
- if (@abs(@field(t, field.name) - @field(candidate, field.name)) > 0.001) matches = false;
+ inline for (@typeInfo(Theme).@"struct".field_names) |field_name| {
+ if (comptime presetRadius(field_name)) {
+ if (@abs(@field(t, field_name) - @field(candidate, field_name)) > 0.001) matches = false;
}
}
if (matches) return preset;
diff --git a/src/ui/theme_file.zig b/src/ui/theme_file.zig
index eff0da5..6ae0779 100644
--- a/src/ui/theme_file.zig
+++ b/src/ui/theme_file.zig
@@ -37,14 +37,14 @@ pub fn load(allocator: Allocator, io: Io, path: []const u8) !Theme {
pub fn keysOf(comptime T: type) []const []const u8 {
const keys = comptime blk: {
var count: usize = 0;
- for (std.meta.fields(Theme)) |field| if (field.type == T) {
+ for (@typeInfo(Theme).@"struct".field_names) |field_name| if (@FieldType(Theme, field_name) == T) {
count += 1;
};
var names: [count][]const u8 = undefined;
var i: usize = 0;
- for (std.meta.fields(Theme)) |field| {
- if (field.type == T) {
- names[i] = field.name;
+ for (@typeInfo(Theme).@"struct".field_names) |field_name| {
+ if (@FieldType(Theme, field_name) == T) {
+ names[i] = field_name;
i += 1;
}
}
@@ -230,7 +230,7 @@ pub fn appendColor(allocator: Allocator, buf: *std.ArrayList(u8), key: []const u
}
pub fn knownKey(key: []const u8) bool {
- inline for (std.meta.fields(Theme)) |field| if (std.mem.eql(u8, key, field.name)) return true;
+ inline for (@typeInfo(Theme).@"struct".field_names) |field_name| if (std.mem.eql(u8, key, field_name)) return true;
return std.mem.eql(u8, key, "taskbar_height");
}
@@ -292,14 +292,14 @@ pub fn writeDiff(allocator: Allocator, buf: *std.ArrayList(u8), t: Theme, defaul
pub fn writeTaskbarInto(allocator: Allocator, buf: *std.ArrayList(u8), t: Theme) !void {
const defaults: Theme = .{};
try buf.appendSlice(allocator, "[taskbar_theme]\n");
- inline for (std.meta.fields(TaskbarToken)) |field| {
- const value = @field(t, field.name);
+ inline for (@typeInfo(TaskbarToken).@"enum".field_names) |field_name| {
+ const value = @field(t, field_name);
if (comptime @TypeOf(value) == bool) {
- if (value != @field(defaults, field.name)) try appendLine(allocator, buf, "{s} = {}\n", .{ field.name, value });
+ if (value != @field(defaults, field_name)) try appendLine(allocator, buf, "{s} = {}\n", .{ field_name, value });
} else if (comptime @TypeOf(value) == ?[4]f32) {
- if (value) |color| try appendColor(allocator, buf, field.name, color);
- } else if (!std.meta.eql(quantize(value), quantize(@field(defaults, field.name)))) {
- try appendColor(allocator, buf, field.name, value);
+ if (value) |color| try appendColor(allocator, buf, field_name, color);
+ } else if (!std.meta.eql(quantize(value), quantize(@field(defaults, field_name)))) {
+ try appendColor(allocator, buf, field_name, value);
}
}
}
diff --git a/src/wlr/AGENTS.md b/src/wlr/AGENTS.md
index 871f391..1cccc02 100644
--- a/src/wlr/AGENTS.md
+++ b/src/wlr/AGENTS.md
@@ -6,9 +6,10 @@ were adapted from that project; keep `LICENSE.zig-wlroots` and attribution.
## Boundary and layouts
-* `c.zig` owns the single `@cImport`. Add headers there; separate imports
- create incompatible C type identities. `_FORTIFY_SOURCE` is undefined for
- translate-c compatibility in ReleaseSafe. The two uninstalled protocol C
+* `c.h` lists every wlroots header; the build translates it once into
+ `wlr_c`, which `c.zig` re-exports. Add headers there; separate
+ translations create incompatible C type identities. `_FORTIFY_SOURCE` is
+ undefined for translate-c compatibility in ReleaseSafe. The two uninstalled protocol C
headers are generated by `wayland-scanner` in `build.zig`.
* Prefer raw C types where callers need no Zig methods or typed events.
Otherwise declare a small `extern struct`, retyping Wayland fields as
diff --git a/src/wlr/abi.zig b/src/wlr/abi.zig
index bc6be21..dcb287b 100644
--- a/src/wlr/abi.zig
+++ b/src/wlr/abi.zig
@@ -6,7 +6,7 @@ pub fn bind(comptime F: type, comptime function: anytype) F {
@setEvalBranchQuota(100000);
comptime assertFunction(F, @TypeOf(function));
const signature = @typeInfo(F).@"fn";
- const params = signature.params;
+ const params = signature.param_types;
const Return = signature.return_type.?;
// Actual function declarations preserve Zig's method-call syntax. A cast
// function pointer alone would require a second implicit dereference.
@@ -17,62 +17,62 @@ pub fn bind(comptime F: type, comptime function: anytype) F {
}
}.call,
1 => struct {
- fn call(a0: params[0].type.?) callconv(.c) Return {
+ fn call(a0: params[0].?) callconv(.c) Return {
return @as(*const F, @ptrCast(&function))(a0);
}
}.call,
2 => struct {
- fn call(a0: params[0].type.?, a1: params[1].type.?) callconv(.c) Return {
+ fn call(a0: params[0].?, a1: params[1].?) callconv(.c) Return {
return @as(*const F, @ptrCast(&function))(a0, a1);
}
}.call,
3 => struct {
- fn call(a0: params[0].type.?, a1: params[1].type.?, a2: params[2].type.?) callconv(.c) Return {
+ fn call(a0: params[0].?, a1: params[1].?, a2: params[2].?) callconv(.c) Return {
return @as(*const F, @ptrCast(&function))(a0, a1, a2);
}
}.call,
4 => struct {
- fn call(a0: params[0].type.?, a1: params[1].type.?, a2: params[2].type.?, a3: params[3].type.?) callconv(.c) Return {
+ fn call(a0: params[0].?, a1: params[1].?, a2: params[2].?, a3: params[3].?) callconv(.c) Return {
return @as(*const F, @ptrCast(&function))(a0, a1, a2, a3);
}
}.call,
5 => struct {
- fn call(a0: params[0].type.?, a1: params[1].type.?, a2: params[2].type.?, a3: params[3].type.?, a4: params[4].type.?) callconv(.c) Return {
+ fn call(a0: params[0].?, a1: params[1].?, a2: params[2].?, a3: params[3].?, a4: params[4].?) callconv(.c) Return {
return @as(*const F, @ptrCast(&function))(a0, a1, a2, a3, a4);
}
}.call,
6 => struct {
- fn call(a0: params[0].type.?, a1: params[1].type.?, a2: params[2].type.?, a3: params[3].type.?, a4: params[4].type.?, a5: params[5].type.?) callconv(.c) Return {
+ fn call(a0: params[0].?, a1: params[1].?, a2: params[2].?, a3: params[3].?, a4: params[4].?, a5: params[5].?) callconv(.c) Return {
return @as(*const F, @ptrCast(&function))(a0, a1, a2, a3, a4, a5);
}
}.call,
7 => struct {
- fn call(a0: params[0].type.?, a1: params[1].type.?, a2: params[2].type.?, a3: params[3].type.?, a4: params[4].type.?, a5: params[5].type.?, a6: params[6].type.?) callconv(.c) Return {
+ fn call(a0: params[0].?, a1: params[1].?, a2: params[2].?, a3: params[3].?, a4: params[4].?, a5: params[5].?, a6: params[6].?) callconv(.c) Return {
return @as(*const F, @ptrCast(&function))(a0, a1, a2, a3, a4, a5, a6);
}
}.call,
8 => struct {
- fn call(a0: params[0].type.?, a1: params[1].type.?, a2: params[2].type.?, a3: params[3].type.?, a4: params[4].type.?, a5: params[5].type.?, a6: params[6].type.?, a7: params[7].type.?) callconv(.c) Return {
+ fn call(a0: params[0].?, a1: params[1].?, a2: params[2].?, a3: params[3].?, a4: params[4].?, a5: params[5].?, a6: params[6].?, a7: params[7].?) callconv(.c) Return {
return @as(*const F, @ptrCast(&function))(a0, a1, a2, a3, a4, a5, a6, a7);
}
}.call,
9 => struct {
- fn call(a0: params[0].type.?, a1: params[1].type.?, a2: params[2].type.?, a3: params[3].type.?, a4: params[4].type.?, a5: params[5].type.?, a6: params[6].type.?, a7: params[7].type.?, a8: params[8].type.?) callconv(.c) Return {
+ fn call(a0: params[0].?, a1: params[1].?, a2: params[2].?, a3: params[3].?, a4: params[4].?, a5: params[5].?, a6: params[6].?, a7: params[7].?, a8: params[8].?) callconv(.c) Return {
return @as(*const F, @ptrCast(&function))(a0, a1, a2, a3, a4, a5, a6, a7, a8);
}
}.call,
10 => struct {
- fn call(a0: params[0].type.?, a1: params[1].type.?, a2: params[2].type.?, a3: params[3].type.?, a4: params[4].type.?, a5: params[5].type.?, a6: params[6].type.?, a7: params[7].type.?, a8: params[8].type.?, a9: params[9].type.?) callconv(.c) Return {
+ fn call(a0: params[0].?, a1: params[1].?, a2: params[2].?, a3: params[3].?, a4: params[4].?, a5: params[5].?, a6: params[6].?, a7: params[7].?, a8: params[8].?, a9: params[9].?) callconv(.c) Return {
return @as(*const F, @ptrCast(&function))(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
}
}.call,
11 => struct {
- fn call(a0: params[0].type.?, a1: params[1].type.?, a2: params[2].type.?, a3: params[3].type.?, a4: params[4].type.?, a5: params[5].type.?, a6: params[6].type.?, a7: params[7].type.?, a8: params[8].type.?, a9: params[9].type.?, a10: params[10].type.?) callconv(.c) Return {
+ fn call(a0: params[0].?, a1: params[1].?, a2: params[2].?, a3: params[3].?, a4: params[4].?, a5: params[5].?, a6: params[6].?, a7: params[7].?, a8: params[8].?, a9: params[9].?, a10: params[10].type.?) callconv(.c) Return {
return @as(*const F, @ptrCast(&function))(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10);
}
}.call,
12 => struct {
- fn call(a0: params[0].type.?, a1: params[1].type.?, a2: params[2].type.?, a3: params[3].type.?, a4: params[4].type.?, a5: params[5].type.?, a6: params[6].type.?, a7: params[7].type.?, a8: params[8].type.?, a9: params[9].type.?, a10: params[10].type.?, a11: params[11].type.?) callconv(.c) Return {
+ fn call(a0: params[0].?, a1: params[1].?, a2: params[2].?, a3: params[3].?, a4: params[4].?, a5: params[5].?, a6: params[6].?, a7: params[7].?, a8: params[8].?, a9: params[9].?, a10: params[10].type.?, a11: params[11].type.?) callconv(.c) Return {
return @as(*const F, @ptrCast(&function))(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11);
}
}.call,
@@ -83,10 +83,9 @@ pub fn bind(comptime F: type, comptime function: anytype) F {
fn assertFunction(comptime A: type, comptime B: type) void {
const a = @typeInfo(A).@"fn";
const b = @typeInfo(B).@"fn";
- if (!std.meta.eql(a.calling_convention, b.calling_convention) or
- a.is_var_args != b.is_var_args or a.params.len != b.params.len)
+ if (!std.meta.eql(a.attrs, b.attrs) or a.param_types.len != b.param_types.len)
@compileError("C function signature changed: " ++ @typeName(A) ++ " / " ++ @typeName(B));
- for (a.params, b.params) |ap, bp| assertValue(ap.type.?, bp.type.?);
+ for (a.param_types, b.param_types) |ap, bp| assertValue(ap.?, bp.?);
assertValue(a.return_type.?, b.return_type.?);
}
@@ -155,21 +154,21 @@ fn assertSize(comptime A: type, comptime B: type) void {
/// objects allocated or passed by value by the compositor.
pub fn assertFields(comptime A: type, comptime B: type) void {
@setEvalBranchQuota(100000);
- const fields = @typeInfo(A).@"struct".fields;
+ const info = @typeInfo(A).@"struct";
// zig-wayland wraps wl_list in a typed Head with one embedded Link.
- if (fields.len == 1 and std.mem.eql(u8, fields[0].name, "link") and
+ if (info.field_names.len == 1 and std.mem.eql(u8, info.field_names[0], "link") and
@hasField(B, "prev") and @hasField(B, "next"))
{
if (@offsetOf(A, "link") != 0) @compileError("Wayland list wrapper moved");
- assertValue(fields[0].type, B);
+ assertValue(info.field_types[0], B);
return;
}
- for (fields) |field| {
- if (!@hasField(B, field.name))
- @compileError("C field missing: " ++ @typeName(B) ++ "." ++ field.name);
- if (@offsetOf(A, field.name) != @offsetOf(B, field.name))
- @compileError("C field offset changed: " ++ @typeName(A) ++ "." ++ field.name);
- assertValue(field.type, @FieldType(B, field.name));
+ for (info.field_names, info.field_types) |name, FieldType| {
+ if (!@hasField(B, name))
+ @compileError("C field missing: " ++ @typeName(B) ++ "." ++ name);
+ if (@offsetOf(A, name) != @offsetOf(B, name))
+ @compileError("C field offset changed: " ++ @typeName(A) ++ "." ++ name);
+ assertValue(FieldType, @FieldType(B, name));
}
}
diff --git a/src/wlr/allocator.zig b/src/wlr/allocator.zig
index fd39598..0ddf0fa 100644
--- a/src/wlr/allocator.zig
+++ b/src/wlr/allocator.zig
@@ -26,9 +26,9 @@ pub const Allocator = extern struct {
comptime {
const Real = c.wlr_allocator;
assertSameLayout(Allocator, Real);
- for (@typeInfo(Allocator).@"struct".fields) |field| {
- assertFieldOffset(Allocator, Real, field.name);
- assertSameLayout(field.type, @FieldType(Real, field.name));
+ for (@typeInfo(Allocator).@"struct".field_names) |field_name| {
+ assertFieldOffset(Allocator, Real, field_name);
+ assertSameLayout(@FieldType(Allocator, field_name), @FieldType(Real, field_name));
}
const Events = @FieldType(Allocator, "events");
assertFieldOffset(Events, @FieldType(Real, "events"), "destroy");
diff --git a/src/wlr/bindings_tests.zig b/src/wlr/bindings_tests.zig
index 243e1e5..5ebfeb9 100644
--- a/src/wlr/bindings_tests.zig
+++ b/src/wlr/bindings_tests.zig
@@ -6,15 +6,15 @@ test "all exported bindings match the installed headers" {
}
fn refAllDeclsRecursive(comptime T: type) void {
- inline for (comptime std.meta.declarations(T)) |decl| {
- const value = @field(T, decl.name);
+ inline for (comptime std.meta.declarations(T)) |decl_name| {
+ const value = @field(T, decl_name);
if (@TypeOf(value) == type) {
switch (@typeInfo(value)) {
.@"struct", .@"enum", .@"union", .@"opaque" => refAllDeclsRecursive(value),
else => {},
}
}
- _ = &@field(T, decl.name);
+ _ = &@field(T, decl_name);
}
}
diff --git a/src/wlr/box.zig b/src/wlr/box.zig
index 086eeb6..e1788d0 100644
--- a/src/wlr/box.zig
+++ b/src/wlr/box.zig
@@ -1,7 +1,7 @@
-//! wlr.Box / wlr.FBox, backed by @cImport against wlr/util/box.h instead
+//! wlr.Box / wlr.FBox, backed by translate-c against wlr/util/box.h instead
//! of a hand-mirrored extern struct. The four fields are redeclared here
//! only so Zig's method-call sugar works on them (an alias to the
-//! @cImport type directly can't carry extra pub fns); the comptime
+//! translate-c type directly can't carry extra pub fns); the comptime
//! asserts below keep that redeclaration honest against the real header.
const c = @import("c.zig").c;
const assertFieldOffset = @import("signal.zig").assertFieldOffset;
diff --git a/src/wlr/c.h b/src/wlr/c.h
new file mode 100644
index 0000000..f3cd981
--- /dev/null
+++ b/src/wlr/c.h
@@ -0,0 +1,95 @@
+/* Every wlroots header the facade in this directory needs, translated once
+ * into the `wlr_c` module (build.zig) so generated type identities stay
+ * consistent across files. Add one #include per header as a subsystem
+ * migrates; never translate a wlroots header a second time elsewhere. */
+#define WLR_USE_UNSTABLE
+#undef _FORTIFY_SOURCE
+
+#include <wlr/util/box.h>
+#include <wlr/util/edges.h>
+#include <wlr/types/wlr_output_power_management_v1.h>
+#include <wlr/types/wlr_idle_notify_v1.h>
+#include <wlr/types/wlr_idle_inhibit_v1.h>
+#include <wlr/types/wlr_keyboard_shortcuts_inhibit_v1.h>
+#include <wlr/types/wlr_security_context_v1.h>
+#include <wlr/types/wlr_fractional_scale_v1.h>
+#include <wlr/types/wlr_relative_pointer_v1.h>
+#include <wlr/types/wlr_pointer_constraints_v1.h>
+#include <wlr/types/wlr_output.h>
+#include <wlr/types/wlr_output_layout.h>
+#include <wlr/types/wlr_output_management_v1.h>
+#include <wlr/types/wlr_xdg_output_v1.h>
+#include <wlr/backend.h>
+#include <wlr/backend/multi.h>
+#include <wlr/backend/libinput.h>
+#include <wlr/backend/session.h>
+#include <wlr/types/wlr_presentation_time.h>
+#include <wlr/render/wlr_renderer.h>
+#include <wlr/render/allocator.h>
+#include <wlr/render/gles2.h>
+#include <wlr/render/pixman.h>
+#include <wlr/render/pass.h>
+#include <wlr/render/wlr_texture.h>
+#include <wlr/render/drm_format_set.h>
+#include <wlr/backend/drm.h>
+#include <wlr/backend/headless.h>
+#include <wlr/backend/wayland.h>
+#include <wlr/backend/x11.h>
+#include <wlr/config.h>
+#include <wlr/version.h>
+#include <wlr/render/color.h>
+#include <wlr/render/dmabuf.h>
+#include <wlr/render/drm_syncobj.h>
+#include <wlr/render/swapchain.h>
+#include <wlr/types/wlr_buffer.h>
+#include <wlr/util/addon.h>
+#include <wlr/util/log.h>
+#include <wlr/util/region.h>
+#include <wlr/types/wlr_compositor.h>
+#include <wlr/types/wlr_subcompositor.h>
+#include <wlr/types/wlr_scene.h>
+#include <wlr/types/wlr_xdg_shell.h>
+#include <wlr/types/wlr_xdg_activation_v1.h>
+#include <wlr/types/wlr_xdg_decoration_v1.h>
+#include <wlr/types/wlr_layer_shell_v1.h>
+#include <wlr/xwayland.h>
+#include <wlr/types/wlr_data_device.h>
+#include <wlr/types/wlr_data_control_v1.h>
+#include <wlr/types/wlr_ext_data_control_v1.h>
+#include <wlr/types/wlr_primary_selection.h>
+#include <wlr/types/wlr_primary_selection_v1.h>
+#include <wlr/types/wlr_ext_foreign_toplevel_list_v1.h>
+#include <wlr/types/wlr_foreign_toplevel_management_v1.h>
+#include <wlr/types/wlr_ext_image_capture_source_v1.h>
+#include <wlr/types/wlr_ext_image_copy_capture_v1.h>
+#include <wlr/types/wlr_session_lock_v1.h>
+#include <wlr/types/wlr_screencopy_v1.h>
+#include <wlr/types/wlr_linux_dmabuf_v1.h>
+#include <wlr/types/wlr_linux_drm_syncobj_v1.h>
+#include <wlr/types/wlr_single_pixel_buffer_v1.h>
+#include <wlr/types/wlr_viewporter.h>
+#include <wlr/interfaces/wlr_ext_image_capture_source_v1.h>
+#include <wlr/interfaces/wlr_buffer.h>
+#include <wlr/xwayland/shell.h>
+#include <wlr/xwayland/server.h>
+#include <wlr/types/wlr_seat.h>
+#include <wlr/types/wlr_cursor.h>
+#include <wlr/types/wlr_input_device.h>
+#include <wlr/types/wlr_keyboard.h>
+#include <wlr/types/wlr_pointer.h>
+#include <wlr/types/wlr_touch.h>
+#include <wlr/types/wlr_switch.h>
+#include <wlr/types/wlr_tablet_tool.h>
+#include <wlr/types/wlr_tablet_pad.h>
+#include <wlr/types/wlr_tablet_v2.h>
+#include <wlr/types/wlr_virtual_keyboard_v1.h>
+#include <wlr/types/wlr_virtual_pointer_v1.h>
+#include <wlr/types/wlr_pointer_gestures_v1.h>
+#include <wlr/types/wlr_cursor_shape_v1.h>
+#include <wlr/types/wlr_text_input_v3.h>
+#include <wlr/types/wlr_input_method_v2.h>
+#include <wlr/types/wlr_xcursor_manager.h>
+#include <wlr/types/wlr_keyboard_group.h>
+#include <wlr/xcursor.h>
+#include <wlr/interfaces/wlr_keyboard.h>
+#include <wlr/interfaces/wlr_pointer.h>
diff --git a/src/wlr/c.zig b/src/wlr/c.zig
index 70b6860..705af74 100644
--- a/src/wlr/c.zig
+++ b/src/wlr/c.zig
@@ -1,99 +1,3 @@
-//! The single @cImport boundary for every wlroots C header the facade in
-//! this directory needs. One pass keeps translate-c's generated type
-//! identities consistent across files, mirroring zig-wlroots's own
-//! single-root `wlroots.zig` import. Add one @cInclude per header as a
-//! subsystem migrates; never @cImport a header a second time elsewhere.
-pub const c = @cImport({
- @cDefine("WLR_USE_UNSTABLE", {});
- @cUndef("_FORTIFY_SOURCE");
- @cInclude("wlr/util/box.h");
- @cInclude("wlr/util/edges.h");
- @cInclude("wlr/types/wlr_output_power_management_v1.h");
- @cInclude("wlr/types/wlr_idle_notify_v1.h");
- @cInclude("wlr/types/wlr_idle_inhibit_v1.h");
- @cInclude("wlr/types/wlr_keyboard_shortcuts_inhibit_v1.h");
- @cInclude("wlr/types/wlr_security_context_v1.h");
- @cInclude("wlr/types/wlr_fractional_scale_v1.h");
- @cInclude("wlr/types/wlr_relative_pointer_v1.h");
- @cInclude("wlr/types/wlr_pointer_constraints_v1.h");
- @cInclude("wlr/types/wlr_output.h");
- @cInclude("wlr/types/wlr_output_layout.h");
- @cInclude("wlr/types/wlr_output_management_v1.h");
- @cInclude("wlr/types/wlr_xdg_output_v1.h");
- @cInclude("wlr/backend.h");
- @cInclude("wlr/backend/multi.h");
- @cInclude("wlr/backend/libinput.h");
- @cInclude("wlr/backend/session.h");
- @cInclude("wlr/types/wlr_presentation_time.h");
- @cInclude("wlr/render/wlr_renderer.h");
- @cInclude("wlr/render/allocator.h");
- @cInclude("wlr/render/gles2.h");
- @cInclude("wlr/render/pixman.h");
- @cInclude("wlr/render/pass.h");
- @cInclude("wlr/render/wlr_texture.h");
- @cInclude("wlr/render/drm_format_set.h");
- // isDrm/isWl/isX11/isHeadless are backend-specific predicates, declared
- // in each backend's own header rather than wlr_output.h.
- @cInclude("wlr/backend/drm.h");
- @cInclude("wlr/backend/headless.h");
- @cInclude("wlr/backend/wayland.h");
- @cInclude("wlr/backend/x11.h");
- @cInclude("wlr/config.h");
- @cInclude("wlr/version.h");
- @cInclude("wlr/render/color.h");
- @cInclude("wlr/render/dmabuf.h");
- @cInclude("wlr/render/drm_syncobj.h");
- @cInclude("wlr/render/swapchain.h");
- @cInclude("wlr/types/wlr_buffer.h");
- @cInclude("wlr/util/addon.h");
- @cInclude("wlr/util/log.h");
- @cInclude("wlr/util/region.h");
- @cInclude("wlr/types/wlr_compositor.h");
- @cInclude("wlr/types/wlr_subcompositor.h");
- @cInclude("wlr/types/wlr_scene.h");
- @cInclude("wlr/types/wlr_xdg_shell.h");
- @cInclude("wlr/types/wlr_xdg_activation_v1.h");
- @cInclude("wlr/types/wlr_xdg_decoration_v1.h");
- @cInclude("wlr/types/wlr_layer_shell_v1.h");
- @cInclude("wlr/xwayland.h");
- @cInclude("wlr/types/wlr_data_device.h");
- @cInclude("wlr/types/wlr_data_control_v1.h");
- @cInclude("wlr/types/wlr_ext_data_control_v1.h");
- @cInclude("wlr/types/wlr_primary_selection.h");
- @cInclude("wlr/types/wlr_primary_selection_v1.h");
- @cInclude("wlr/types/wlr_ext_foreign_toplevel_list_v1.h");
- @cInclude("wlr/types/wlr_foreign_toplevel_management_v1.h");
- @cInclude("wlr/types/wlr_ext_image_capture_source_v1.h");
- @cInclude("wlr/types/wlr_ext_image_copy_capture_v1.h");
- @cInclude("wlr/types/wlr_session_lock_v1.h");
- @cInclude("wlr/types/wlr_screencopy_v1.h");
- @cInclude("wlr/types/wlr_linux_dmabuf_v1.h");
- @cInclude("wlr/types/wlr_linux_drm_syncobj_v1.h");
- @cInclude("wlr/types/wlr_single_pixel_buffer_v1.h");
- @cInclude("wlr/types/wlr_viewporter.h");
- @cInclude("wlr/interfaces/wlr_ext_image_capture_source_v1.h");
- @cInclude("wlr/interfaces/wlr_buffer.h");
- @cInclude("wlr/xwayland/shell.h");
- @cInclude("wlr/xwayland/server.h");
- @cInclude("wlr/types/wlr_seat.h");
- @cInclude("wlr/types/wlr_cursor.h");
- @cInclude("wlr/types/wlr_input_device.h");
- @cInclude("wlr/types/wlr_keyboard.h");
- @cInclude("wlr/types/wlr_pointer.h");
- @cInclude("wlr/types/wlr_touch.h");
- @cInclude("wlr/types/wlr_switch.h");
- @cInclude("wlr/types/wlr_tablet_tool.h");
- @cInclude("wlr/types/wlr_tablet_pad.h");
- @cInclude("wlr/types/wlr_tablet_v2.h");
- @cInclude("wlr/types/wlr_virtual_keyboard_v1.h");
- @cInclude("wlr/types/wlr_virtual_pointer_v1.h");
- @cInclude("wlr/types/wlr_pointer_gestures_v1.h");
- @cInclude("wlr/types/wlr_cursor_shape_v1.h");
- @cInclude("wlr/types/wlr_text_input_v3.h");
- @cInclude("wlr/types/wlr_input_method_v2.h");
- @cInclude("wlr/types/wlr_xcursor_manager.h");
- @cInclude("wlr/types/wlr_keyboard_group.h");
- @cInclude("wlr/xcursor.h");
- @cInclude("wlr/interfaces/wlr_keyboard.h");
- @cInclude("wlr/interfaces/wlr_pointer.h");
-});
+//! The wlroots C declarations, translated from c.h by the build (`wlr_c`).
+//! Add headers there; never translate a wlroots header a second time.
+pub const c = @import("wlr_c");
diff --git a/src/wlr/edges.zig b/src/wlr/edges.zig
index a446a3f..5ae4db1 100644
--- a/src/wlr/edges.zig
+++ b/src/wlr/edges.zig
@@ -1,6 +1,6 @@
//! wlr.Edges: `enum wlr_edges` (wlr/util/edges.h) is a plain bitmask
//! (WLR_EDGE_TOP = 1<<0, ...), not a C bitfield, so this is pure
-//! ergonomic sugar over a u32 -- no @cImport struct to stay in sync with,
+//! ergonomic sugar over a u32 -- no translate-c struct to stay in sync with,
//! just the four bit positions the header defines.
pub const Edges = packed struct(u32) {
top: bool = false,
diff --git a/src/wlr/fractional_scale.zig b/src/wlr/fractional_scale.zig
index ff1b553..0c0ae00 100644
--- a/src/wlr/fractional_scale.zig
+++ b/src/wlr/fractional_scale.zig
@@ -1,4 +1,4 @@
-//! wlr.FractionalScaleManagerV1, backed by @cImport against
+//! wlr.FractionalScaleManagerV1, backed by translate-c against
//! wlr/types/wlr_fractional_scale_v1.h.
const wl = @import("wayland").server.wl;
const c = @import("c.zig").c;
diff --git a/src/wlr/idle_inhibit.zig b/src/wlr/idle_inhibit.zig
index 7ecba25..454b3f1 100644
--- a/src/wlr/idle_inhibit.zig
+++ b/src/wlr/idle_inhibit.zig
@@ -1,4 +1,4 @@
-//! wlr.IdleInhibitManagerV1 / wlr.IdleInhibitorV1, backed by @cImport
+//! wlr.IdleInhibitManagerV1 / wlr.IdleInhibitorV1, backed by translate-c
//! against wlr/types/wlr_idle_inhibit_v1.h. `events.destroy` on the
//! inhibitor type carries the surface, not the inhibitor itself (see
//! wlr-protocols) -- that's not a mistake, wlroots really does type it
diff --git a/src/wlr/idle_notify.zig b/src/wlr/idle_notify.zig
index 203a81c..e922f4e 100644
--- a/src/wlr/idle_notify.zig
+++ b/src/wlr/idle_notify.zig
@@ -1,4 +1,4 @@
-//! wlr.IdleNotifierV1, backed by @cImport against
+//! wlr.IdleNotifierV1, backed by translate-c against
//! wlr/types/wlr_idle_notify_v1.h. Every field but `global` is
//! WLR_PRIVATE in the real struct, so there's nothing else to redeclare
//! or assert beyond it -- `global` is the struct's first field, so its
diff --git a/src/wlr/keyboard_shortcuts_inhibit.zig b/src/wlr/keyboard_shortcuts_inhibit.zig
index 947044e..5f1dd07 100644
--- a/src/wlr/keyboard_shortcuts_inhibit.zig
+++ b/src/wlr/keyboard_shortcuts_inhibit.zig
@@ -1,5 +1,5 @@
//! wlr.KeyboardShortcutsInhibitManagerV1 / wlr.KeyboardShortcutsInhibitorV1,
-//! backed by @cImport against wlr/types/wlr_keyboard_shortcuts_inhibit_v1.h.
+//! backed by translate-c against wlr/types/wlr_keyboard_shortcuts_inhibit_v1.h.
const wl = @import("wayland").server.wl;
const c = @import("c.zig").c;
const assertSameLayout = @import("signal.zig").assertSameLayout;
diff --git a/src/wlr/log.zig b/src/wlr/log.zig
index 3b3b324..4418f59 100644
--- a/src/wlr/log.zig
+++ b/src/wlr/log.zig
@@ -14,7 +14,7 @@ pub const Importance = enum(c_int) {
const wlr_log_init = abi.bind(fn (
verbosity: Importance,
- callback: ?*const fn (importance: Importance, fmt: [*:0]const u8, args: *std.builtin.VaList) callconv(.c) void,
+ callback: ?*const fn (importance: Importance, fmt: [*:0]const u8, args: *std.lang.VaList) callconv(.c) void,
) callconv(.c) void, c.wlr_log_init);
pub const init = wlr_log_init;
diff --git a/src/wlr/output.zig b/src/wlr/output.zig
index 8b09e1e..fe79521 100644
--- a/src/wlr/output.zig
+++ b/src/wlr/output.zig
@@ -1,4 +1,4 @@
-//! wlr.Output / wlr.OutputCursor, backed by @cImport against
+//! wlr.Output / wlr.OutputCursor, backed by translate-c against
//! wlr/types/wlr_output.h. The single biggest type in the facade so far:
//! see src/wlr/AGENTS.md for the general pattern and the top-level
//! AGENTS.md's rendering/damage notes before changing anything here.
diff --git a/src/wlr/output_layout.zig b/src/wlr/output_layout.zig
index 89d4075..b340d2f 100644
--- a/src/wlr/output_layout.zig
+++ b/src/wlr/output_layout.zig
@@ -1,4 +1,4 @@
-//! wlr.OutputLayout, backed by @cImport against
+//! wlr.OutputLayout, backed by translate-c against
//! wlr/types/wlr_output_layout.h. `OutputLayout.Output` (the per-output
//! layout entry) is declared only far enough to be a valid
//! `wl.list.Head` element -- RediWM never calls `.get()` or walks
diff --git a/src/wlr/output_management.zig b/src/wlr/output_management.zig
index 6911f99..a0e7bc3 100644
--- a/src/wlr/output_management.zig
+++ b/src/wlr/output_management.zig
@@ -74,9 +74,9 @@ pub fn Types(comptime Output: type) type {
comptime {
const Real = c.wlr_output_head_v1_state;
assertSameLayout(State, Real);
- for (@typeInfo(State).@"struct".fields) |field| {
- assertFieldOffset(State, Real, field.name);
- assertSameLayout(field.type, @FieldType(Real, field.name));
+ for (@typeInfo(State).@"struct".field_names) |field_name| {
+ assertFieldOffset(State, Real, field_name);
+ assertSameLayout(@FieldType(State, field_name), @FieldType(Real, field_name));
}
}
};
@@ -89,9 +89,9 @@ pub fn Types(comptime Output: type) type {
comptime {
const Real = c.wlr_output_head_v1;
- for (@typeInfo(OutputHeadV1).@"struct".fields) |field| {
- assertFieldOffset(OutputHeadV1, Real, field.name);
- assertSameLayout(field.type, @FieldType(Real, field.name));
+ for (@typeInfo(OutputHeadV1).@"struct".field_names) |field_name| {
+ assertFieldOffset(OutputHeadV1, Real, field_name);
+ assertSameLayout(@FieldType(OutputHeadV1, field_name), @FieldType(Real, field_name));
}
}
};
@@ -110,9 +110,9 @@ pub fn Types(comptime Output: type) type {
comptime {
const Real = c.wlr_output_configuration_head_v1;
- for (@typeInfo(Head).@"struct".fields) |field| {
- assertFieldOffset(Head, Real, field.name);
- assertSameLayout(field.type, @FieldType(Real, field.name));
+ for (@typeInfo(Head).@"struct".field_names) |field_name| {
+ assertFieldOffset(Head, Real, field_name);
+ assertSameLayout(@FieldType(Head, field_name), @FieldType(Real, field_name));
}
}
};
@@ -144,9 +144,9 @@ pub fn Types(comptime Output: type) type {
comptime {
const Real = c.wlr_output_configuration_v1;
assertSameLayout(OutputConfigurationV1, Real);
- for (@typeInfo(OutputConfigurationV1).@"struct".fields) |field| {
- assertFieldOffset(OutputConfigurationV1, Real, field.name);
- assertSameLayout(field.type, @FieldType(Real, field.name));
+ for (@typeInfo(OutputConfigurationV1).@"struct".field_names) |field_name| {
+ assertFieldOffset(OutputConfigurationV1, Real, field_name);
+ assertSameLayout(@FieldType(OutputConfigurationV1, field_name), @FieldType(Real, field_name));
}
}
};
diff --git a/src/wlr/output_power.zig b/src/wlr/output_power.zig
index e93bfea..077a3c5 100644
--- a/src/wlr/output_power.zig
+++ b/src/wlr/output_power.zig
@@ -1,13 +1,13 @@
-//! wlr.OutputPowerManagerV1 / wlr.OutputPowerV1, backed by @cImport
+//! wlr.OutputPowerManagerV1 / wlr.OutputPowerV1, backed by translate-c
//! against wlr/types/wlr_output_power_management_v1.h.
//!
//! The struct bodies are hand-redeclared (unlike most future subsystems,
-//! which can usually alias the @cImport type directly) only because
+//! which can usually alias the translate-c type directly) only because
//! `events.*` needs to be retyped from the real `wl_signal` to
//! zig-wayland's `wl.Signal(T)` to get `.add()`/`.get()`/`.emit()` for
//! consumers -- the same reason zig-wlroots hand-declared this struct.
//! The comptime block below is the difference: it checks every
-//! redeclared field's offset against the real @cImport'd struct, so a
+//! redeclared field's offset against the real translated struct, so a
//! future wlroots release that reorders or inserts a field fails the
//! build instead of silently corrupting memory.
//!
diff --git a/src/wlr/pointer_constraints.zig b/src/wlr/pointer_constraints.zig
index 6fc62f4..a1f354d 100644
--- a/src/wlr/pointer_constraints.zig
+++ b/src/wlr/pointer_constraints.zig
@@ -1,5 +1,5 @@
//! wlr.PointerConstraintsV1 / wlr.PointerConstraintV1, backed by
-//! @cImport against wlr/types/wlr_pointer_constraints_v1.h.
+//! translate-c against wlr/types/wlr_pointer_constraints_v1.h.
const std = @import("std");
const wl = @import("wayland").server.wl;
const zwp = @import("wayland").server.zwp;
diff --git a/src/wlr/relative_pointer.zig b/src/wlr/relative_pointer.zig
index c46c6f7..7b08ad3 100644
--- a/src/wlr/relative_pointer.zig
+++ b/src/wlr/relative_pointer.zig
@@ -1,5 +1,5 @@
//! wlr.RelativePointerManagerV1 / wlr.RelativePointerV1, backed by
-//! @cImport against wlr/types/wlr_relative_pointer_v1.h.
+//! translate-c against wlr/types/wlr_relative_pointer_v1.h.
//! RelativePointerV1 is not referenced by name anywhere in RediWM, but
//! its layout still has to be right: the manager's `relative_pointers`
//! list and `events.new_relative_pointer` signal are typed in terms of
diff --git a/src/wlr/render_pass.zig b/src/wlr/render_pass.zig
index 3c10e24..5583c04 100644
--- a/src/wlr/render_pass.zig
+++ b/src/wlr/render_pass.zig
@@ -40,9 +40,9 @@ pub const RenderPass = opaque {
comptime {
const Real = c.wlr_render_texture_options;
assertSameLayout(TextureOptions, Real);
- for (@typeInfo(TextureOptions).@"struct".fields) |field| {
- assertFieldOffset(TextureOptions, Real, field.name);
- assertSameLayout(field.type, @FieldType(Real, field.name));
+ for (@typeInfo(TextureOptions).@"struct".field_names) |field_name| {
+ assertFieldOffset(TextureOptions, Real, field_name);
+ assertSameLayout(@FieldType(TextureOptions, field_name), @FieldType(Real, field_name));
}
}
};
@@ -56,9 +56,9 @@ pub const RenderPass = opaque {
comptime {
const Real = c.wlr_render_rect_options;
assertSameLayout(RectOptions, Real);
- for (@typeInfo(RectOptions).@"struct".fields) |field| {
- assertFieldOffset(RectOptions, Real, field.name);
- assertSameLayout(field.type, @FieldType(Real, field.name));
+ for (@typeInfo(RectOptions).@"struct".field_names) |field_name| {
+ assertFieldOffset(RectOptions, Real, field_name);
+ assertSameLayout(@FieldType(RectOptions, field_name), @FieldType(Real, field_name));
}
}
};
diff --git a/src/wlr/renderer.zig b/src/wlr/renderer.zig
index 6385649..b1e0a09 100644
--- a/src/wlr/renderer.zig
+++ b/src/wlr/renderer.zig
@@ -16,9 +16,9 @@ pub const Renderer = extern struct {
comptime {
const Real = c.wlr_buffer_pass_options;
assertSameLayout(BufferPassOptions, Real);
- for (@typeInfo(BufferPassOptions).@"struct".fields) |field| {
- assertFieldOffset(BufferPassOptions, Real, field.name);
- assertSameLayout(field.type, @FieldType(Real, field.name));
+ for (@typeInfo(BufferPassOptions).@"struct".field_names) |field_name| {
+ assertFieldOffset(BufferPassOptions, Real, field_name);
+ assertSameLayout(@FieldType(BufferPassOptions, field_name), @FieldType(Real, field_name));
}
}
};
@@ -68,23 +68,23 @@ pub const Renderer = extern struct {
comptime {
const Real = c.wlr_renderer;
- for (@typeInfo(Renderer).@"struct".fields) |field| {
- assertFieldOffset(Renderer, Real, field.name);
- assertSameLayout(field.type, @FieldType(Real, field.name));
+ for (@typeInfo(Renderer).@"struct".field_names) |field_name| {
+ assertFieldOffset(Renderer, Real, field_name);
+ assertSameLayout(@FieldType(Renderer, field_name), @FieldType(Real, field_name));
}
const Events = @FieldType(Renderer, "events");
const RealEvents = @FieldType(Real, "events");
- for (@typeInfo(Events).@"struct".fields) |field| {
- assertFieldOffset(Events, RealEvents, field.name);
- assertSameLayout(field.type, c.wl_signal);
+ for (@typeInfo(Events).@"struct".field_names) |field_name| {
+ assertFieldOffset(Events, RealEvents, field_name);
+ assertSameLayout(@FieldType(Events, field_name), c.wl_signal);
}
const Features = @FieldType(Renderer, "features");
const RealFeatures = @FieldType(Real, "features");
- for (@typeInfo(Features).@"struct".fields) |field| {
- assertFieldOffset(Features, RealFeatures, field.name);
- assertSameLayout(field.type, @FieldType(RealFeatures, field.name));
+ for (@typeInfo(Features).@"struct".field_names) |field_name| {
+ assertFieldOffset(Features, RealFeatures, field_name);
+ assertSameLayout(@FieldType(Features, field_name), @FieldType(RealFeatures, field_name));
}
}
};
diff --git a/src/wlr/security_context.zig b/src/wlr/security_context.zig
index a4a805d..f6a7708 100644
--- a/src/wlr/security_context.zig
+++ b/src/wlr/security_context.zig
@@ -1,5 +1,5 @@
//! wlr.SecurityContextManagerV1 / wlr.SecurityContextV1State, backed by
-//! @cImport against wlr/types/wlr_security_context_v1.h. Read
+//! translate-c against wlr/types/wlr_security_context_v1.h. Read
//! src/global_filter.zig and the top-level AGENTS.md's security-context
//! note before changing this: it's what hides privileged globals from
//! sandboxed clients.
diff --git a/src/wlr/signal.zig b/src/wlr/signal.zig
index 26ccb0f..0c1af21 100644
--- a/src/wlr/signal.zig
+++ b/src/wlr/signal.zig
@@ -1,6 +1,6 @@
//! Safety net for the facade's one necessary hand-declared shape: the
//! `events` block of a wlr struct, where a field has to be retyped from
-//! @cImport's raw `wl_signal` to zig-wayland's `wl.Signal(T)` to get
+//! translate-c's raw `wl_signal` to zig-wayland's `wl.Signal(T)` to get
//! `.add()`/`.get()`/`.emit()` for free. That retyping is safe only
//! because `struct wl_signal` is just one `wl_list` (two pointers) and
//! always will be -- these asserts turn any future drift (a struct
diff --git a/src/wlr/texture.zig b/src/wlr/texture.zig
index d93171f..7b4fa38 100644
--- a/src/wlr/texture.zig
+++ b/src/wlr/texture.zig
@@ -17,9 +17,9 @@ pub const Texture = extern struct {
comptime {
const Real = c.wlr_texture_read_pixels_options;
assertSameLayout(ReadPixelsOptions, Real);
- for (@typeInfo(ReadPixelsOptions).@"struct".fields) |field| {
- assertFieldOffset(ReadPixelsOptions, Real, field.name);
- assertSameLayout(field.type, @FieldType(Real, field.name));
+ for (@typeInfo(ReadPixelsOptions).@"struct".field_names) |field_name| {
+ assertFieldOffset(ReadPixelsOptions, Real, field_name);
+ assertSameLayout(@FieldType(ReadPixelsOptions, field_name), @FieldType(Real, field_name));
}
}
};
@@ -48,9 +48,9 @@ pub const Texture = extern struct {
comptime {
const Real = c.wlr_texture;
assertSameLayout(Texture, Real);
- for (@typeInfo(Texture).@"struct".fields) |field| {
- assertFieldOffset(Texture, Real, field.name);
- assertSameLayout(field.type, @FieldType(Real, field.name));
+ for (@typeInfo(Texture).@"struct".field_names) |field_name| {
+ assertFieldOffset(Texture, Real, field_name);
+ assertSameLayout(@FieldType(Texture, field_name), @FieldType(Real, field_name));
}
}
};
diff --git a/src/wlr/xdg_output.zig b/src/wlr/xdg_output.zig
index b5fc466..187f2c8 100644
--- a/src/wlr/xdg_output.zig
+++ b/src/wlr/xdg_output.zig
@@ -18,9 +18,9 @@ pub fn Types(comptime OutputLayout: type) type {
height: i32,
comptime {
- for (@typeInfo(XdgOutputV1).@"struct".fields) |field| {
- assertFieldOffset(XdgOutputV1, c.wlr_xdg_output_v1, field.name);
- assertSameLayout(field.type, @FieldType(c.wlr_xdg_output_v1, field.name));
+ for (@typeInfo(XdgOutputV1).@"struct".field_names) |field_name| {
+ assertFieldOffset(XdgOutputV1, c.wlr_xdg_output_v1, field_name);
+ assertSameLayout(@FieldType(XdgOutputV1, field_name), @FieldType(c.wlr_xdg_output_v1, field_name));
}
}
};
@@ -40,9 +40,9 @@ pub fn Types(comptime OutputLayout: type) type {
comptime {
const Real = c.wlr_xdg_output_manager_v1;
- for (@typeInfo(XdgOutputManagerV1).@"struct".fields) |field| {
- assertFieldOffset(XdgOutputManagerV1, Real, field.name);
- assertSameLayout(field.type, @FieldType(Real, field.name));
+ for (@typeInfo(XdgOutputManagerV1).@"struct".field_names) |field_name| {
+ assertFieldOffset(XdgOutputManagerV1, Real, field_name);
+ assertSameLayout(@FieldType(XdgOutputManagerV1, field_name), @FieldType(Real, field_name));
}
const Events = @FieldType(XdgOutputManagerV1, "events");
assertFieldOffset(Events, @FieldType(Real, "events"), "destroy");
diff --git a/src/wlr/xdg_shell.zig b/src/wlr/xdg_shell.zig
index fc772e7..b173b17 100644
--- a/src/wlr/xdg_shell.zig
+++ b/src/wlr/xdg_shell.zig
@@ -432,19 +432,20 @@ pub const XdgSurface = extern struct {
/// translate-c gives anonymous unions generated field names. Match these by
/// position and validate each alternative instead of baking that name in.
fn assertWithAnonymousUnion(comptime T: type, comptime C: type) void {
- const real = @typeInfo(C).@"struct".fields;
- for (@typeInfo(T).@"struct".fields, 0..) |field, index| {
- const actual = real[index];
- if (@offsetOf(T, field.name) != @offsetOf(C, actual.name))
- @compileError("XDG field offset changed: " ++ @typeName(T) ++ "." ++ field.name);
- abi.assertValue(field.type, actual.type);
- if (@typeInfo(field.type) == .@"union") {
- const fields = @typeInfo(field.type).@"union".fields;
- const alternatives = @typeInfo(actual.type).@"union".fields;
- if (fields.len != alternatives.len) @compileError("XDG union alternatives changed");
- for (fields, alternatives) |ours, theirs| abi.assertValue(ours.type, theirs.type);
- } else if (!@import("std").mem.eql(u8, field.name, actual.name)) {
- @compileError("XDG field changed: " ++ field.name);
+ const real = @typeInfo(C).@"struct";
+ for (@typeInfo(T).@"struct".field_names, @typeInfo(T).@"struct".field_types, 0..) |name, FieldType, index| {
+ const actual_name = real.field_names[index];
+ const Actual = real.field_types[index];
+ if (@offsetOf(T, name) != @offsetOf(C, actual_name))
+ @compileError("XDG field offset changed: " ++ @typeName(T) ++ "." ++ name);
+ abi.assertValue(FieldType, Actual);
+ if (@typeInfo(FieldType) == .@"union") {
+ const ours = @typeInfo(FieldType).@"union".field_types;
+ const theirs = @typeInfo(Actual).@"union".field_types;
+ if (ours.len != theirs.len) @compileError("XDG union alternatives changed");
+ for (ours, theirs) |Ours, Theirs| abi.assertValue(Ours, Theirs);
+ } else if (!@import("std").mem.eql(u8, name, actual_name)) {
+ @compileError("XDG field changed: " ++ name);
}
}
}
diff --git a/tests/session_restart.py b/tests/session_restart.py
index a2e153e..4e88218 100644
--- a/tests/session_restart.py
+++ b/tests/session_restart.py
@@ -1,21 +1,17 @@
#!/usr/bin/env python3
"""Replace a live executable and restart twice, preserving PID and renewing IPC."""
-import importlib.util
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import time
-from unittest.mock import patch
from ipc_client import ROOT, IPCClient, stop_process
def run():
- spec = importlib.util.spec_from_file_location('restart_session', ROOT / 'scripts/restart-session.py')
- restart = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(restart)
+ restart = ROOT / 'zig-out/release-safe/bin/rediwm-restart'
with tempfile.TemporaryDirectory(prefix='rediwm-restart-') as directory:
tmp = Path(directory)
binary = tmp / 'rediwm'
@@ -36,20 +32,21 @@ def run():
assert proc.poll() is None, 'compositor exited at startup'
assert time.monotonic() < deadline, 'IPC not ready'
time.sleep(.05)
- with patch.object(restart, 'INSTALLED', binary), patch.dict(os.environ, env, clear=True):
- for _ in range(2):
- with IPCClient(env['REDIWM_SOCKET']) as previous:
- assert previous.request(query='version')
- staged = tmp / 'replacement'
- shutil.copy2(source, staged)
- staged.replace(binary)
- assert os.readlink(f'/proc/{proc.pid}/exe').endswith(' (deleted)')
- restart.main()
- assert proc.poll() is None, 'login process exited'
- assert Path(f'/proc/{proc.pid}/exe').stat().st_ino == binary.stat().st_ino
- assert previous.sock.recv(1) == b'', 'old client connection survived restart'
- with IPCClient(env['REDIWM_SOCKET']) as ipc:
- assert ipc.request(query='outputs'), 'output missing after restart'
+ for _ in range(2):
+ with IPCClient(env['REDIWM_SOCKET']) as previous:
+ assert previous.request(query='version')
+ staged = tmp / 'replacement'
+ shutil.copy2(source, staged)
+ staged.replace(binary)
+ assert os.readlink(f'/proc/{proc.pid}/exe').endswith(' (deleted)')
+ result = subprocess.run([str(restart), str(binary), env['REDIWM_SOCKET']], env=env, capture_output=True, text=True, timeout=40)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert 'restarted successfully' in result.stdout, result.stdout
+ assert proc.poll() is None, 'login process exited'
+ assert Path(f'/proc/{proc.pid}/exe').stat().st_ino == binary.stat().st_ino
+ assert previous.sock.recv(1) == b'', 'old client connection survived restart'
+ with IPCClient(env['REDIWM_SOCKET']) as ipc:
+ assert ipc.request(query='outputs'), 'output missing after restart'
print('PASS: two atomic executable replacements; PID preserved, IPC renewed, output available')
except BaseException:
log.flush()
diff --git a/tools/i18n.zig b/tools/i18n.zig
index 49aceab..dc5bac8 100644
--- a/tools/i18n.zig
+++ b/tools/i18n.zig
@@ -110,8 +110,8 @@ fn scan(path: []const u8, list: *List) anyerror!void {
}
fn extract(path: []const u8, list: *List) !void {
- const source = try A.dupeZ(u8, try read(path));
- var tree = try std.zig.Ast.parse(A, source, .zig);
+ const source = try A.dupeSentinel(u8, try read(path), 0);
+ var tree = try std.zig.Ast.parse(A, source, .{});
defer tree.deinit(A);
const tags = tree.tokens.items(.tag);
var i: u32 = 0;
@@ -549,8 +549,8 @@ fn generateData(tags: []const []const u8, source: []const u8, output: []const u8
try write(output, out.written());
}
fn lint(path: []const u8) !void {
- const source = try A.dupeZ(u8, try read(path));
- var tree = try std.zig.Ast.parse(A, source, .zig);
+ const source = try A.dupeSentinel(u8, try read(path), 0);
+ var tree = try std.zig.Ast.parse(A, source, .{});
defer tree.deinit(A);
const tags = tree.tokens.items(.tag);
var test_depth: usize = 0;