RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
rendering lib updates
oxydizer6249042d79a3
diff --git a/src/Server.zig b/src/Server.zigindex ab878d0..15470cd 100644--- a/src/Server.zig+++ b/src/Server.zig@@ -501,6 +501,7 @@ pub const iconRelease = server_icons.iconRelease;pub const iconPrefetch = server_icons.iconPrefetch;pub const iconCancelSpeculative = server_icons.iconCancelSpeculative;pub const iconInvalidateAll = server_icons.iconInvalidateAll;+pub const iconRefreshInstalled = server_icons.iconRefreshInstalled;/// Small direct-mapped memo for resolved icon names, keyed by app_id and/// invalidated wholesale whenever the catalog publishes a new generation.diff --git a/src/firewall_helper/run.zig b/src/firewall_helper/run.zigindex 3fd90b7..49b3878 100644--- a/src/firewall_helper/run.zig+++ b/src/firewall_helper/run.zig@@ -4,6 +4,7 @@//! shell.const std = @import("std");const c = @import("c");+const platform = @import("platform");const Allocator = std.mem.Allocator;pub const Ctx = struct {@@ -14,8 +15,14 @@ pub const Ctx = struct {const dirs = [_][]const u8{ "/usr/sbin", "/sbin", "/usr/bin", "/bin", "/usr/local/sbin", "/usr/local/bin" };-/// `name` in the system directories, or null.+/// `name` in the system directories, or null. Init-aware programs (`systemctl`,+/// `journalctl`) look in `/usr/local/bin` first, where a system without systemd+/// as PID 1 installs its wrappers; see platform/tool.zig.pub fn tool(ctx: Ctx, comptime name: []const u8) ?[]const u8 {+ if (comptime platform.tool.isInitAware(name)) {+ const path = "/usr/local/bin/" ++ name;+ if (std.Io.Dir.accessAbsolute(ctx.io, path, .{ .execute = true })) |_| return path else |_| {}+ }inline for (dirs) |dir| {const path = dir ++ "/" ++ name;if (std.Io.Dir.accessAbsolute(ctx.io, path, .{ .execute = true })) |_| return path else |_| {}diff --git a/src/icon_service.zig b/src/icon_service.zigindex 4a1e983..e0c50f9 100644--- a/src/icon_service.zig+++ b/src/icon_service.zig@@ -68,6 +68,7 @@ const Published = struct {const Job = struct {key: []const u8, // owned by `in_flight` until published; see `enqueue`/`publish`+ epoch: u64 = 0, // `installed_epoch` when queued; see `refreshInstalled`};/// Outcome of one worker-thread decode. `missing` is a resolved, permanent@@ -86,6 +87,7 @@ const Result = struct {key: []const u8,decoded: Decoded,decode_ns: u64, // worker-thread wall time for this job (theme lookup + decode combined)+ epoch: u64 = 0, // copied from the `Job`};pub const IconService = struct {@@ -118,6 +120,7 @@ pub const IconService = struct {owns_config: bool = false,unpinned_bytes: usize = 0, // sum of .bytes over published entries with refcount == 0touch_clock: u64 = 0,+ installed_epoch: u64 = 0, // bumped by `refreshInstalled`pub fn create(allocator: Allocator, cfg: icon_theme.Config, io: Io) !*IconService {const self = try allocator.create(IconService);@@ -340,6 +343,22 @@ pub const IconService = struct {self.freeAllPublished();}+ /// Compositor-thread only. Icons may have been installed or removed+ /// (an application appeared at runtime): forget every cached miss and+ /// have the worker re-read the theme directories on its next lookup.+ /// Found icons, pinned or not, stay published. Never blocks.+ pub fn refreshInstalled(self: *IconService) void {+ icon_theme.invalidateInstalled();+ self.installed_epoch += 1;+ var misses: std.ArrayList([]const u8) = .empty;+ defer misses.deinit(self.allocator);+ var it = self.published.iterator();+ while (it.next()) |e| {+ if (e.value_ptr.entry == null) misses.append(self.allocator, e.key_ptr.*) catch break;+ }+ for (misses.items) |key| self.evictKey(key);+ }+/// Compositor-thread only. Bumps the refcount of a still-published/// entry (a no-op if it's already gone — evicted, or a stale id from/// `invalidateAll`); moves its bytes out of the evictable pool while@@ -400,7 +419,10 @@ pub const IconService = struct {if (res.decoded == .ready) icon_cache.gpa.free(res.decoded.ready.pixels);continue;};- self.publish(removed_entry.key, res.decoded, res.decode_ns);+ // A miss from before `refreshInstalled` may be the very icon that+ // just arrived: don't remember it; the re-request decodes again.+ const decoded: Decoded = if (res.decoded == .missing and res.epoch != self.installed_epoch) .failed else res.decoded;+ self.publish(removed_entry.key, decoded, res.decode_ns);}}@@ -419,7 +441,7 @@ pub const IconService = struct {.essential => &self.job_queue_essential,.speculative => &self.job_queue_speculative,};- queue.append(self.allocator, .{ .key = owned }) catch {+ queue.append(self.allocator, .{ .key = owned, .epoch = self.installed_epoch }) catch {// `owned` stays parked in `in_flight` forever (freed at// `deinit`); allocation failure here is already an exceptional,// low-memory condition, not something to special-case further.@@ -543,7 +565,7 @@ pub const IconService = struct {const decode_ns = stats.nowNs() -% t0;self.lock();- self.result_queue.append(self.allocator, .{ .key = job.key, .decoded = decoded, .decode_ns = decode_ns }) catch |err| {+ self.result_queue.append(self.allocator, .{ .key = job.key, .decoded = decoded, .decode_ns = decode_ns, .epoch = job.epoch }) catch |err| {log.err("run: could not queue icon result: {}", .{err});};self.unlock();diff --git a/src/icon_theme.zig b/src/icon_theme.zigindex 5513130..cd70c62 100644--- a/src/icon_theme.zig+++ b/src/icon_theme.zig@@ -15,6 +15,13 @@ const Io = std.Io;const pthread = std.posix.system;var index_mutex: pthread.pthread_mutex_t = pthread.PTHREAD_MUTEX_INITIALIZER;+/// Bumped by `invalidateInstalled` when icons may have been installed or+/// removed at runtime. `find` compares it, under `index_mutex`, with the+/// generation its indexes were built for and drops them lazily, so the caller+/// (the compositor thread) neither waits for the lock nor re-indexes.+var installed_generation = std.atomic.Value(u64).init(0);+var indexed_generation: u64 = 0; // guarded by index_mutex+pub const Config = struct {theme_name: []const u8,override_root: []const u8 = "",@@ -126,6 +133,11 @@ pub fn find(allocator: Allocator, io: Io, cfg: Config, icon_name: []const u8, taif (try findPack(allocator, io, cfg, icon_name)) |found| return found;_ = pthread.pthread_mutex_lock(&index_mutex);defer _ = pthread.pthread_mutex_unlock(&index_mutex);+ const wanted = installed_generation.load(.acquire);+ if (wanted != indexed_generation) {+ dropIndexesLocked(allocator);+ indexed_generation = wanted;+ }// Every theme-name string this call ever allocates (Inherits= entries),// freed once at the end. `pending`/`visited` below only ever hold slices// borrowed from here or from `cfg.theme_name`, so nothing can dangle.@@ -192,8 +204,9 @@ pub fn find(allocator: Allocator, io: Io, cfg: Config, icon_name: []const u8, ta// dir. Adwaita's index.theme is tens of KB of subdir sections and `find`// walks the whole Inherits chain plus hicolor, so parsing per lookup cost// ~40ms of *render-path* time on every icon-cache miss — that was the start-// menu's stutter as new rows scrolled in. `Config` is resolved once in-// Server.init and never changes, so one parse is good for the process.+// menu's stutter as new rows scrolled in. One parse lasts until the theme+// configuration changes (`forgetParsedThemes`) or icons are installed at+// runtime (`invalidateInstalled`).var parsed_themes: std.StringHashMapUnmanaged(?Theme) = .empty;/// Borrowed from `parsed_themes`; the caller must not deinit the result.@@ -210,11 +223,24 @@ fn themeIndex(allocator: Allocator, io: Io, cfg: Config, theme_name: []const u8)return parsed;}-/// Drop every parsed index. Only needed if the icon theme configuration ever-/// becomes changeable at runtime; nothing calls it today.+/// Drop every parsed index and file index, after the icon theme+/// configuration changed. Blocks while a lookup holds the index lock.pub fn forgetParsedThemes(allocator: Allocator) void {_ = pthread.pthread_mutex_lock(&index_mutex);defer _ = pthread.pthread_mutex_unlock(&index_mutex);+ dropIndexesLocked(allocator);+}++/// Icons may have been installed or removed (an application was added at+/// runtime, with its icons linked into a theme directory): the next `find`+/// re-reads the theme directories. Never blocks; any thread may call it.+pub fn invalidateInstalled() void {+ _ = installed_generation.fetchAdd(1, .release);+}++/// The file indexes hold positions into the parsed indexes' directory lists,+/// so the two are always dropped together. Caller holds `index_mutex`.+fn dropIndexesLocked(allocator: Allocator) void {var it = parsed_themes.iterator();while (it.next()) |entry| {allocator.free(entry.key_ptr.*);@@ -222,6 +248,15 @@ pub fn forgetParsedThemes(allocator: Allocator) void {}parsed_themes.deinit(allocator);parsed_themes = .empty;++ var files_it = theme_files.iterator();+ while (files_it.next()) |entry| {+ allocator.free(entry.key_ptr.*);+ var files = entry.value_ptr.*;+ freeThemeFiles(allocator, &files);+ }+ theme_files.deinit(allocator);+ theme_files = .empty;}fn loadThemeIndex(allocator: Allocator, io: Io, cfg: Config, theme_name: []const u8) !?Theme {@@ -440,8 +475,8 @@ const Candidate = struct {/// hit or miss, into a single one. That was the last of the start menu's/// scroll stutter: every newly revealed row is a fresh icon name.///-/// Same lifetime caveat as `parsed_themes`: valid because the icon config is-/// resolved once at startup and never changes.+/// Same lifetime as `parsed_themes`, and dropped with it: icons installed+/// while the compositor runs appear only after `invalidateInstalled`.const ThemeFiles = std.StringHashMapUnmanaged(std.ArrayListUnmanaged(Candidate));var theme_files: std.StringHashMapUnmanaged(ThemeFiles) = .empty;@@ -496,18 +531,6 @@ fn freeThemeFiles(allocator: Allocator, files: *ThemeFiles) void {files.deinit(allocator);}-/// Counterpart to `forgetParsedThemes`; same caveat, nothing calls it today.-pub fn forgetThemeFiles(allocator: Allocator) void {- var it = theme_files.iterator();- while (it.next()) |entry| {- allocator.free(entry.key_ptr.*);- var files = entry.value_ptr.*;- freeThemeFiles(allocator, &files);- }- theme_files.deinit(allocator);- theme_files = .empty;-}-fn findInTheme(allocator: Allocator, io: Io, cfg: Config, theme: Theme, icon_name: []const u8, target_px: i32) !?Found {const files = try themeIndex_(allocator, io, cfg, theme);const candidates = files.get(icon_name) orelse return null;diff --git a/src/platform/tool.zig b/src/platform/tool.zigindex f1cc63e..4a3993d 100644--- a/src/platform/tool.zig+++ b/src/platform/tool.zig@@ -5,11 +5,30 @@ const std = @import("std");/// The directories searched, in order. Root-owned on every supported system.const system_dirs = [_][]const u8{ "/usr/bin", "/bin", "/usr/local/bin" };+/// Programs a system without systemd as PID 1 replaces. RediOS under redinit+/// installs init-aware wrappers in `/usr/local/bin`, because the real tools+/// refuse to run there ("System has not been booted with systemd"). Under+/// systemd the wrappers hand over to the real tool, so preferring them is safe.+const init_aware = [_][]const u8{ "systemctl", "loginctl", "journalctl" };+const local_first_dirs = [_][]const u8{ "/usr/local/bin", "/usr/bin", "/bin" };++/// Is `name` one of the programs the init system may stand in for?+pub fn isInitAware(comptime name: []const u8) bool {+ inline for (init_aware) |known| if (std.mem.eql(u8, name, known)) return true;+ return false;+}++/// The directories searched for `name`, in order. An init-aware program looks in+/// `/usr/local/bin` first (still a root-owned directory, still never `PATH`).+pub fn searchDirs(comptime name: []const u8) []const []const u8 {+ return if (comptime isInitAware(name)) &local_first_dirs else &system_dirs;+}+/// `name` in the system directories, never on `PATH`: for programs that run/// as root or are handed a secret (`pkexec`, `systemctl`), where a/// user-writable `PATH` entry must not win. Null when none is executable.pub fn system(io: std.Io, comptime name: []const u8) ?[:0]const u8 {- inline for (system_dirs) |dir| {+ inline for (comptime searchDirs(name)) |dir| {const path = dir ++ "/" ++ name;if (std.Io.Dir.accessAbsolute(io, path, .{ .execute = true })) |_| return path else |_| {}}@@ -22,3 +41,18 @@ test "system programs come from the system directories" {try std.testing.expect(std.fs.path.isAbsolute(sh));try std.testing.expectEqual(@as(?[:0]const u8, null), system(std.testing.io, "rediwm-no-such-program"));}++test "init-aware programs prefer the wrapper in /usr/local/bin" {+ // A real systemctl in /usr/bin must never win over the wrapper: under redinit+ // it exits with "System has not been booted with systemd".+ inline for (.{ "systemctl", "loginctl", "journalctl" }) |name| {+ const dirs = searchDirs(name);+ try std.testing.expectEqualStrings("/usr/local/bin", dirs[0]);+ try std.testing.expectEqualStrings("/usr/bin", dirs[1]);+ }+ // Everything else keeps the distribution first, so a port cannot shadow it.+ inline for (.{ "pkexec", "ssh-keygen", "gio" }) |name| {+ try std.testing.expectEqualStrings("/usr/bin", searchDirs(name)[0]);+ try std.testing.expect(!isInitAware(name));+ }+}diff --git a/src/server/icons.zig b/src/server/icons.zigindex e70ccdf..25febde 100644--- a/src/server/icons.zig+++ b/src/server/icons.zig@@ -129,3 +129,9 @@ pub fn iconCancelSpeculative(server: *Server) void {pub fn iconInvalidateAll(server: *Server) void {if (server.icon_service) |svc| svc.invalidateAll();}++/// Applications changed at runtime and may have brought icons: forgets+/// cached misses; see `IconService.refreshInstalled`.+pub fn iconRefreshInstalled(server: *Server) void {+ if (server.icon_service) |svc| svc.refreshInstalled();+}diff --git a/src/server/wallpaper.zig b/src/server/wallpaper.zigindex a71f34b..88fb553 100644--- a/src/server/wallpaper.zig+++ b/src/server/wallpaper.zig@@ -47,6 +47,10 @@ pub fn handleCatalogWake(fd: c_int, mask: wl.EventMask, server: *Server) c_int {_ = fd;_ = mask;if (!server.start_menu_catalog.drainCompletions()) return 0;+ // New entries usually come with icons (a package install, or a launcher+ // sync such as arch-run's linking them into ~/.local/share/icons before+ // moving the entries in), which the cached theme index has not seen.+ server.iconRefreshInstalled();if (server.input.open_control_center) |cc| cc.refresh();var it = server.outputs.iterator(.forward);while (it.next()) |output| {diff --git a/src/start_menu/applications.zig b/src/start_menu/applications.zigindex 42ddeea..15f564c 100644--- a/src/start_menu/applications.zig+++ b/src/start_menu/applications.zig@@ -111,6 +111,13 @@ pub const Catalog = struct {watcher: ?platform.watch.Watcher = null,watch_source: ?*wl.EventSource = null,watched_paths: std.StringHashMapUnmanaged(void) = .empty,+ /// Nearest existing ancestors of application directories that do not+ /// exist yet (a fresh home has no ~/.local/share/applications until+ /// something such as arch-run's launcher sync makes it). Watched only for+ /// new directories, so a later `mkdir -p` is noticed without rescanning on+ /// every unrelated file written next to it.+ parent_paths: std.StringHashMapUnmanaged(platform.watch.Watch) = .empty,+ parent_watches: std.AutoHashMapUnmanaged(platform.watch.Watch, void) = .empty,/// `scan` false leaves the catalog empty and never touches the cache/// (the greeter has no start menu).@@ -167,7 +174,7 @@ pub const Catalog = struct {return;};self.watcher = watcher;- self.syncWatches();+ _ = self.syncWatches();}pub fn deinit(self: *Catalog) void {@@ -182,6 +189,10 @@ pub const Catalog = struct {var it = self.watched_paths.keyIterator();while (it.next()) |k| self.allocator.free(k.*);self.watched_paths.deinit(self.allocator);+ var parents = self.parent_paths.keyIterator();+ while (parents.next()) |k| self.allocator.free(k.*);+ self.parent_paths.deinit(self.allocator);+ self.parent_watches.deinit(self.allocator);if (self.eventfd >= 0) _ = c.close(self.eventfd);if (self.pending) |snap| snap.release();@@ -245,7 +256,7 @@ pub const Catalog = struct {const published = incoming orelse return false;if (old) |prev| prev.release();startup.markCatalogPublished(published.scan_ns, @intCast(published.entries.len), published.provisional, published.generation);- self.syncWatches();+ _ = self.syncWatches();return true;}@@ -391,28 +402,66 @@ pub const Catalog = struct {_ = c.pthread_cond_broadcast(&self.cond);}- fn syncWatches(self: *Catalog) void {- const watcher = self.watcher orelse return;+ /// Returns true when a directory gained a real watch it lacked before.+ fn syncWatches(self: *Catalog) bool {+ const watcher = self.watcher orelse return false;var tmp = std.heap.ArenaAllocator.init(self.allocator);defer tmp.deinit();const a = tmp.allocator();+ var added = false;if (resolveApplicationDirs(a, self.environ)) |dirs| {- for (dirs) |dir| self.addWatch(watcher, dir);+ for (dirs) |dir| {+ if (self.addWatch(watcher, dir)) {+ added = true;+ } else if (!self.watched_paths.contains(dir)) {+ self.watchParentOf(watcher, dir);+ }+ }} else |_| {}// Directories already visited by the scan, without walking the tree again// on the compositor thread.for (self.current.sources) |src| {- if (std.fs.path.dirname(src.path)) |dir| self.addWatch(watcher, dir);+ if (std.fs.path.dirname(src.path)) |dir| {+ if (self.addWatch(watcher, dir)) added = true;+ }}+ return added;}- fn addWatch(self: *Catalog, watcher: platform.watch.Watcher, dir: []const u8) void {- if (self.watched_paths.contains(dir)) return;- _ = watcher.add(dir, .{ .created = true, .deleted = true, .modified = true, .moved_from = true, .moved_to = true, .attrib = true, .written = true }) orelse return;- const owned = self.allocator.dupe(u8, dir) catch return;+ /// Returns true only when `dir` was not watched before and now is.+ fn addWatch(self: *Catalog, watcher: platform.watch.Watcher, dir: []const u8) bool {+ if (self.watched_paths.contains(dir)) return false;+ _ = watcher.add(dir, .{ .created = true, .deleted = true, .modified = true, .moved_from = true, .moved_to = true, .attrib = true, .written = true }) orelse return false;+ // inotify keeps one watch per directory, so a former parent watch on+ // this path has just taken the full interest: stop filtering it.+ if (self.parent_paths.fetchRemove(dir)) |kv| {+ _ = self.parent_watches.remove(kv.value);+ self.allocator.free(kv.key);+ }+ const owned = self.allocator.dupe(u8, dir) catch return true;self.watched_paths.put(self.allocator, owned, {}) catch self.allocator.free(owned);+ return true;+ }++ /// Watches the nearest existing ancestor of the missing `dir` for new+ /// directories; `syncWatches` moves down once each level appears.+ fn watchParentOf(self: *Catalog, watcher: platform.watch.Watcher, dir: []const u8) void {+ var at = dir;+ while (std.fs.path.dirname(at)) |parent| {+ at = parent;+ // A real watch already resyncs on directory creation.+ if (self.watched_paths.contains(at) or self.parent_paths.contains(at)) return;+ const wd = watcher.add(at, .{ .created = true, .moved_to = true }) orelse continue;+ const owned = self.allocator.dupe(u8, at) catch return;+ self.parent_paths.put(self.allocator, owned, wd) catch {+ self.allocator.free(owned);+ return;+ };+ self.parent_watches.put(self.allocator, wd, {}) catch {};+ return;+ }}};@@ -422,9 +471,18 @@ const Changes = struct {fn event(self: *Changes, ev: platform.watch.Event) void {if (!ev.flags.isChange()) return;+ if (self.catalog.parent_watches.contains(ev.watch)) {+ // Only waiting for a missing application directory to appear. Its+ // first files may land before the new watch exists, so rescan when+ // one does.+ if (ev.flags.is_dir and (ev.flags.created or ev.flags.moved_to)) {+ if (self.catalog.syncWatches()) self.saw = true;+ }+ return;+ }self.saw = true;// A new directory may hold applications of its own.- if (ev.flags.created and ev.flags.is_dir) self.catalog.syncWatches();+ if (ev.flags.created and ev.flags.is_dir) _ = self.catalog.syncWatches();}};