From ec7474c9afee8db18d1251c13ad8f8b9d85d5be0 Mon Sep 17 00:00:00 2001 From: Ben Buhse Date: Sun, 8 Feb 2026 16:17:28 -0600 Subject: [PATCH] Implement some simple flags and runtime log-levels I used flags.zig from Isaac Freund for parsing basic CLI arguments, I don't need much else since most configuration is in Kdl. https://codeberg.org/river/river/src/commit/e967499fb12b6074ebb93d98d7fc3e5eefb438ab/common/flags.zig I also removed some of the duplicated bits for the exe_check step since I realized I can just use the beansprout executable for all of it. --- LICENSES/0BSD.txt | 5 +++ LICENSES/HPND.txt | 7 +++ LICENSES/ISC.txt | 8 ---- LICENSES/MIT.txt | 18 ++++++++ README.md | 2 +- build.zig | 112 +++++++++++++++++++++++----------------------- src/flags.zig | 97 +++++++++++++++++++++++++++++++++++++++ src/main.zig | 93 +++++++++++++++++++++++++++++++++++++- 8 files changed, 277 insertions(+), 65 deletions(-) create mode 100644 LICENSES/0BSD.txt create mode 100644 LICENSES/HPND.txt delete mode 100644 LICENSES/ISC.txt create mode 100644 LICENSES/MIT.txt create mode 100644 src/flags.zig diff --git a/LICENSES/0BSD.txt b/LICENSES/0BSD.txt new file mode 100644 index 0000000..0b8ae76 --- /dev/null +++ b/LICENSES/0BSD.txt @@ -0,0 +1,5 @@ +Copyright (C) YEAR by AUTHOR EMAIL + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/LICENSES/HPND.txt b/LICENSES/HPND.txt new file mode 100644 index 0000000..ff9ae1b --- /dev/null +++ b/LICENSES/HPND.txt @@ -0,0 +1,7 @@ +Historical Permission Notice and Disclaimer + +Copyright + +Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies, and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of or not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. + + DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,. IN NO EVENT SHALL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/LICENSES/ISC.txt b/LICENSES/ISC.txt deleted file mode 100644 index b9c199c..0000000 --- a/LICENSES/ISC.txt +++ /dev/null @@ -1,8 +0,0 @@ -ISC License: - -Copyright (c) 2004-2010 by Internet Systems Consortium, Inc. ("ISC") -Copyright (c) 1995-2003 by Internet Software Consortium - -Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt new file mode 100644 index 0000000..d817195 --- /dev/null +++ b/LICENSES/MIT.txt @@ -0,0 +1,18 @@ +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 08abbe7..e296ec8 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,6 @@ These are in rough order of my priority, though no promises I do them in this or - [ ] Support per-host config using properties (maybe also per-output?) - [ ] Add input configuration, i.e. pointer acceleration and that type of thing - [ ] Support a basic bar -- [ ] Implement runtime log levels - [ ] Support starting programs at WM launch - [ ] Support overriding config location - [ ] Add support for multimedia/brightness keys (this might not be neccesary) @@ -25,5 +24,6 @@ These are in rough order of my priority, though no promises I do them in this or - [x] Support floating windows - [x] Support wallpapers - [x] Make "orelse return" bits into errors; handle gracefully +- [x] Implement runtime log levels - [ ] Switch all structs to idiomatic Zig init/deinit pattern (init returns value, caller decides stack/heap) - I'm not sure I really need this diff --git a/build.zig b/build.zig index 2707d47..6751489 100644 --- a/build.zig +++ b/build.zig @@ -36,7 +36,10 @@ pub fn build(b: *std.Build) void { scanner.generate("river_layer_shell_v1", 1); scanner.generate("zwlr_layer_shell_v1", 3); - const exe = b.addExecutable(.{ + const options = b.addOptions(); + options.addOption([]const u8, "version", version); + + const beansprout = b.addExecutable(.{ .name = "beansprout", .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), @@ -45,42 +48,26 @@ pub fn build(b: *std.Build) void { .strip = strip, }), }); - exe.pie = pie; + beansprout.pie = pie; - // Make sure to also add new imports to the exe_check step - exe.root_module.addImport("wayland", wayland); - exe.root_module.addImport("kdl", kdl); - exe.root_module.addImport("known_folders", known_folders); - exe.root_module.addImport("pixman", pixman); - exe.root_module.addImport("xkbcommon", xkbcommon); - exe.root_module.addImport("zigimg", zigimg); + beansprout.root_module.addOptions("build_options", options); - exe.linkLibC(); - exe.linkSystemLibrary("wayland-client"); - exe.linkSystemLibrary("pixman-1"); - exe.linkSystemLibrary("xkbcommon"); + beansprout.root_module.addImport("wayland", wayland); + beansprout.root_module.addImport("kdl", kdl); + beansprout.root_module.addImport("known_folders", known_folders); + beansprout.root_module.addImport("pixman", pixman); + beansprout.root_module.addImport("xkbcommon", xkbcommon); + beansprout.root_module.addImport("zigimg", zigimg); - b.installArtifact(exe); + beansprout.linkLibC(); + beansprout.linkSystemLibrary("wayland-client"); + beansprout.linkSystemLibrary("pixman-1"); + beansprout.linkSystemLibrary("xkbcommon"); - const run_cmd = b.addRunArtifact(exe); - - // By making the run step depend on the install step, it will be run from the - // installation directory rather than directly from within the cache directory. - // This is not necessary, however, if the application depends on other installed - // files, this ensures they will be present and in the expected location. - run_cmd.step.dependOn(b.getInstallStep()); - - // This allows the user to pass arguments to the application in the build - // command itself, like this: `zig build run -- arg1 arg2 etc` - if (b.args) |args| { - run_cmd.addArgs(args); - } - - const run_step = b.step("run", "Run beansprout"); - run_step.dependOn(&run_cmd.step); + b.installArtifact(beansprout); const exe_unit_tests = b.addTest(.{ - .root_module = exe.root_module, + .root_module = beansprout.root_module, }); const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests); @@ -88,29 +75,44 @@ pub fn build(b: *std.Build) void { const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&run_exe_unit_tests.step); - // check step used for zls to give comptime info - const exe_check = b.addExecutable(.{ - .name = "beansprout", - .root_module = b.createModule(.{ - .root_source_file = b.path("src/main.zig"), - .target = target, - .optimize = optimize, - .strip = strip, - }), - }); - - exe_check.root_module.addImport("wayland", wayland); - exe_check.root_module.addImport("kdl", kdl); - exe_check.root_module.addImport("known_folders", known_folders); - exe_check.root_module.addImport("pixman", pixman); - exe_check.root_module.addImport("xkbcommon", xkbcommon); - exe_check.root_module.addImport("zigimg", zigimg); - - exe_check.linkLibC(); - exe_check.linkSystemLibrary("wayland-client"); - exe_check.linkSystemLibrary("pixman-1"); - exe_check.linkSystemLibrary("xkbcommon"); - + // Use by zls to get inline compilation errors const check = b.step("check", "Check if beansprout compiles"); - check.dependOn(&exe_check.step); + check.dependOn(&beansprout.step); } + +const version = manifest.version; +/// Needed until https://github.com/ziglang/zig/issues/22775 +/// is addressed. +const manifest: struct { + name: @Type(.enum_literal), + version: []const u8, + fingerprint: u64, + minimum_zig_version: []const u8, + dependencies: struct { + wayland: struct { + url: []const u8, + hash: []const u8, + }, + xkbcommon: struct { + url: []const u8, + hash: []const u8, + }, + kdl: struct { + url: []const u8, + hash: []const u8, + }, + known_folders: struct { + url: []const u8, + hash: []const u8, + }, + pixman: struct { + url: []const u8, + hash: []const u8, + }, + zigimg: struct { + url: []const u8, + hash: []const u8, + }, + }, + paths: []const []const u8, +} = @import("build.zig.zon"); diff --git a/src/flags.zig b/src/flags.zig new file mode 100644 index 0000000..f7f9536 --- /dev/null +++ b/src/flags.zig @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: © 2023 Isaac Freund +// SPDX-License-Identifier: 0BSD + +//! Zero allocation argument parsing for unix-like systems. + +const std = @import("std"); +const mem = std.mem; + +pub const Flag = struct { + name: [:0]const u8, + kind: enum { boolean, arg }, +}; + +pub fn parser(comptime Arg: type, comptime flags: []const Flag) type { + switch (Arg) { + // TODO consider allowing []const u8 + [:0]const u8, [*:0]const u8 => {}, // ok + else => @compileError("invalid argument type: " ++ @typeName(Arg)), + } + return struct { + pub const Result = struct { + /// Remaining args after the recognized flags + args: []const Arg, + /// Data obtained from parsed flags + flags: Flags, + + pub const Flags = flags_type: { + var fields: []const std.builtin.Type.StructField = &.{}; + for (flags) |flag| { + const field: std.builtin.Type.StructField = switch (flag.kind) { + .boolean => .{ + .name = flag.name, + .type = bool, + .default_value_ptr = &false, + .is_comptime = false, + .alignment = @alignOf(bool), + }, + .arg => .{ + .name = flag.name, + .type = ?[:0]const u8, + .default_value_ptr = &@as(?[:0]const u8, null), + .is_comptime = false, + .alignment = @alignOf(?[:0]const u8), + }, + }; + fields = fields ++ [_]std.builtin.Type.StructField{field}; + } + break :flags_type @Type(.{ .@"struct" = .{ + .layout = .auto, + .fields = fields, + .decls = &.{}, + .is_tuple = false, + } }); + }; + }; + + pub fn parse(args: []const Arg) !Result { + var result_flags: Result.Flags = .{}; + + var i: usize = 0; + outer: while (i < args.len) : (i += 1) { + const arg = switch (Arg) { + [*:0]const u8 => mem.sliceTo(args[i], 0), + [:0]const u8 => args[i], + else => unreachable, + }; + inline for (flags) |flag| { + if (mem.eql(u8, "-" ++ flag.name, arg)) { + switch (flag.kind) { + .boolean => @field(result_flags, flag.name) = true, + .arg => { + i += 1; + if (i == args.len) { + std.log.err("option '-" ++ flag.name ++ + "' requires an argument but none was provided!", .{}); + return error.MissingFlagArgument; + } + @field(result_flags, flag.name) = switch (Arg) { + [*:0]const u8 => mem.sliceTo(args[i], 0), + [:0]const u8 => args[i], + else => unreachable, + }; + }, + } + continue :outer; + } + } + break; + } + + return Result{ + .args = args[i..], + .flags = result_flags, + }; + } + }; +} diff --git a/src/main.zig b/src/main.zig index f373b2e..0ea7b46 100644 --- a/src/main.zig +++ b/src/main.zig @@ -23,7 +23,57 @@ const Globals = struct { } }; +const usage: []const u8 = + \\usage: beansprout [options] + \\ + \\ -h Print this help message and exit. + \\ -version Print the version number and exit. + \\ -log-level Set the log level to error, warning, info, or debug. + \\ +; + pub fn main() !void { + const result = flags.parser([*:0]const u8, &.{ + .{ .name = "h", .kind = .boolean }, + .{ .name = "version", .kind = .boolean }, + .{ .name = "log-level", .kind = .arg }, + }).parse(std.os.argv[1..]) catch { + try stderr.writeAll(usage); + try stderr.flush(); + posix.exit(1); + }; + if (result.flags.h) { + try stdout.writeAll(usage); + try stdout.flush(); + posix.exit(0); + } + if (result.args.len != 0) { + log.err("unknown option '{s}'", .{result.args[0]}); + try stderr.writeAll(usage); + try stderr.flush(); + posix.exit(1); + } + + if (result.flags.version) { + try stdout.writeAll(build_options.version ++ "\n"); + try stdout.flush(); + posix.exit(0); + } + if (result.flags.@"log-level") |level| { + if (mem.eql(u8, level, "error")) { + runtime_log_level = .err; + } else if (mem.eql(u8, level, "warning")) { + runtime_log_level = .warn; + } else if (mem.eql(u8, level, "info")) { + runtime_log_level = .info; + } else if (mem.eql(u8, level, "debug")) { + runtime_log_level = .debug; + } else { + log.err("invalid log level '{s}'", .{level}); + posix.exit(1); + } + } + const wayland_display_var = try utils.allocator.dupeZ(u8, process.getEnvVarOwned(utils.allocator, "WAYLAND_DISPLAY") catch { fatal("Error getting WAYLAND_DISPLAY environment variable. Exiting", .{}); }); @@ -134,9 +184,49 @@ fn registryListener(registry: *wl.Registry, event: wl.Registry.Event, globals: * } } +var stderr_buffer: [1024]u8 = undefined; +var stderr_writer = fs.File.stderr().writer(&stderr_buffer); +const stderr = &stderr_writer.interface; + +var stdout_buffer: [1024]u8 = undefined; +var stdout_writer = fs.File.stdout().writer(&stdout_buffer); +const stdout = &stdout_writer.interface; + +/// Set the default log level based on the build mode. +var runtime_log_level: std.log.Level = switch (builtin.mode) { + .Debug => .debug, + .ReleaseSafe, .ReleaseFast, .ReleaseSmall => .info, +}; + +pub const std_options: std.Options = .{ + // Tell std.log to leave all log level filtering to us. + .log_level = .debug, + .logFn = logFn, +}; + +pub fn logFn( + comptime level: std.log.Level, + comptime scope: @TypeOf(.EnumLiteral), + comptime format: []const u8, + args: anytype, +) void { + if (@intFromEnum(level) > @intFromEnum(runtime_log_level)) return; + + if (scope != .default) return; + + const scope_prefix = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): "; + + stderr.print(level.asText() ++ scope_prefix ++ format ++ "\n", args) catch return; + stderr.flush() catch return; +} + +const build_options = @import("build_options"); +const builtin = @import("builtin"); const std = @import("std"); -const mem = std.mem; const fatal = std.process.fatal; +const fs = std.fs; +const mem = std.mem; +const posix = std.posix; const process = std.process; const wayland = @import("wayland"); @@ -144,6 +234,7 @@ const river = wayland.client.river; const wl = wayland.client.wl; const zwlr = wayland.client.zwlr; +const flags = @import("flags.zig"); const utils = @import("utils.zig"); const Config = @import("Config.zig"); const Context = @import("Context.zig");