From 18bab45d4c12f64c3c28b07243c79e807fe45ccd Mon Sep 17 00:00:00 2001 From: Isaac Freund Date: Sun, 17 Jan 2021 16:30:47 +0100 Subject: [PATCH] riverctl: implement river-options interface To make this cleaner, introduce some arg-parsing infrastructure that will useful when porting riverctl to river-control-v2 in the future as well. --- build.zig | 1 + deps/zig-wayland | 2 +- doc/riverctl.1.scd | 19 +++++ riverctl/args.zig | 115 ++++++++++++++++++++++++++ riverctl/main.zig | 79 +++++++++++++----- riverctl/options.zig | 187 +++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 380 insertions(+), 23 deletions(-) create mode 100644 riverctl/args.zig create mode 100644 riverctl/options.zig diff --git a/build.zig b/build.zig index 0c9c217..b8e847e 100644 --- a/build.zig +++ b/build.zig @@ -40,6 +40,7 @@ pub fn build(b: *zbs.Builder) !void { const scanner = ScanProtocolsStep.create(b); scanner.addSystemProtocol("stable/xdg-shell/xdg-shell.xml"); + scanner.addSystemProtocol("unstable/xdg-output/xdg-output-unstable-v1.xml"); scanner.addProtocolPath("protocol/river-control-unstable-v1.xml"); scanner.addProtocolPath("protocol/river-options-unstable-v1.xml"); scanner.addProtocolPath("protocol/river-status-unstable-v1.xml"); diff --git a/deps/zig-wayland b/deps/zig-wayland index 05f539c..6880196 160000 --- a/deps/zig-wayland +++ b/deps/zig-wayland @@ -1 +1 @@ -Subproject commit 05f539c8934f18f93ac50aad654fa469bf5121f8 +Subproject commit 6880196f57df7f4d8b783bbab94b1bf5c3e38453 diff --git a/doc/riverctl.1.scd b/doc/riverctl.1.scd index 9caa4ac..05eafdf 100644 --- a/doc/riverctl.1.scd +++ b/doc/riverctl.1.scd @@ -280,6 +280,25 @@ A complete list may be found in _/usr/include/linux/input-event-codes.h_ and is made available through the _XCURSOR_THEME_ and _XCURSOR_SIZE_ environment variables. +# OPTIONS + +River has various options that are saved in a typed key-value store. It also +allows users to store arbitrary custom options in the store. Options are +scoped either globally or per-output if the -output flag is passed with the +name of the output as obtained from the xdg-output protocol. + +*declare-option* [-output _output_name_] _name_ _type_ _value_ + Declare a new option with the given _type_ and inital _value_. If + the option already exists with the given _type_, it is still set + to _value_. If the option already exists with a different type, + nothing happens. + +*get-option* [-output _output_name_] _name_ + Print the current value of the given option to stdout. + +*set-option* [-output _output_name_] _name_ _value_ + Set the value of the specified option to _value_. + # EXAMPLES Bind bemenu-run to Super+P in normal mode: diff --git a/riverctl/args.zig b/riverctl/args.zig new file mode 100644 index 0000000..3240a97 --- /dev/null +++ b/riverctl/args.zig @@ -0,0 +1,115 @@ +// This file is part of river, a dynamic tiling wayland compositor. +// +// Copyright 2021 The River Developers +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +const std = @import("std"); +const mem = std.mem; +const cstr = std.cstr; + +const root = @import("root"); + +pub const FlagDef = struct { + name: [*:0]const u8, + kind: enum { boolean, arg }, +}; + +pub fn Args(comptime num_positionals: comptime_int, comptime flag_defs: []const FlagDef) type { + return struct { + const Self = @This(); + + positionals: [num_positionals][*:0]const u8, + flags: [flag_defs.len]struct { + name: [*:0]const u8, + value: union { + boolean: bool, + arg: ?[*:0]const u8, + }, + }, + + pub fn parse(argv: [][*:0]const u8) Self { + var ret: Self = undefined; + + // Init all flags in the flags array to false/null + inline for (flag_defs) |flag_def, flag_idx| { + switch (flag_def.kind) { + .boolean => ret.flags[flag_idx] = .{ + .name = flag_def.name, + .value = .{ .boolean = false }, + }, + .arg => ret.flags[flag_idx] = .{ + .name = flag_def.name, + .value = .{ .arg = null }, + }, + } + } + + // Parse the argv in to the positionals and flags arrays + var arg_idx: usize = 0; + var positional_idx: usize = 0; + outer: while (arg_idx < argv.len) : (arg_idx += 1) { + inline for (flag_defs) |flag_def, flag_idx| { + if (cstr.cmp(flag_def.name, argv[arg_idx]) == 0) { + switch (flag_def.kind) { + .boolean => ret.flags[flag_idx].value.boolean = true, + .arg => { + arg_idx += 1; + ret.flags[flag_idx].value.arg = if (arg_idx < argv.len) + argv[arg_idx] + else + root.printErrorExit("flag '" ++ flag_def.name ++ + "' requires an argument but none was provided!", .{}); + }, + } + continue :outer; + } + } + + if (positional_idx == num_positionals) { + root.printErrorExit( + "{} positional arguments expected but more were provided!", + .{num_positionals}, + ); + } + + ret.positionals[positional_idx] = argv[arg_idx]; + positional_idx += 1; + } + + if (positional_idx < num_positionals) { + root.printErrorExit( + "{} positional arguments expected but only {} were provided!", + .{ num_positionals, positional_idx }, + ); + } + + return ret; + } + + pub fn boolFlag(self: Self, flag_name: [*:0]const u8) bool { + for (self.flags) |flag| { + if (cstr.cmp(flag.name, flag_name) == 0) return flag.value.boolean; + } + unreachable; + } + + pub fn argFlag(self: Self, flag_name: [*:0]const u8) ?[*:0]const u8 { + for (self.flags) |flag| { + if (cstr.cmp(flag.name, flag_name) == 0) return flag.value.arg; + } + unreachable; + } + }; +} diff --git a/riverctl/main.zig b/riverctl/main.zig index dad41ea..4c3f1c8 100644 --- a/riverctl/main.zig +++ b/riverctl/main.zig @@ -1,6 +1,6 @@ // This file is part of river, a dynamic tiling wayland compositor. // -// Copyright 2020 The River Developers +// Copyright 2020-2021 The River Developers // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by @@ -16,48 +16,78 @@ // along with this program. If not, see . const std = @import("std"); +const mem = std.mem; +const os = std.os; const wayland = @import("wayland"); const wl = wayland.client.wl; const zriver = wayland.client.zriver; +const zxdg = wayland.client.zxdg; -const SetupContext = struct { - river_control: ?*zriver.ControlV1 = null, +const gpa = std.heap.c_allocator; + +const options = @import("options.zig"); + +pub const Output = struct { + wl_output: *wl.Output, + name: []const u8, +}; + +pub const Globals = struct { + control: ?*zriver.ControlV1 = null, + options_manager: ?*zriver.OptionsManagerV1 = null, seat: ?*wl.Seat = null, + output_manager: ?*zxdg.OutputManagerV1 = null, + outputs: std.ArrayList(Output) = std.ArrayList(Output).init(gpa), }; pub fn main() !void { const display = try wl.Display.connect(null); const registry = try display.getRegistry(); - var context = SetupContext{}; + var globals = Globals{}; - registry.setListener(*SetupContext, registryListener, &context) catch unreachable; + registry.setListener(*Globals, registryListener, &globals) catch unreachable; _ = try display.roundtrip(); - const river_control = context.river_control orelse return error.RiverControlNotAdvertised; - const seat = context.seat orelse return error.SeatNotAdverstised; + if (os.argv.len > 2 and mem.eql(u8, "declare-option", mem.span(os.argv[1]))) { + try options.declareOption(display, &globals); + } else if (os.argv.len > 2 and mem.eql(u8, "get-option", mem.span(os.argv[1]))) { + try options.getOption(display, &globals); + } else if (os.argv.len > 2 and mem.eql(u8, "set-option", mem.span(os.argv[1]))) { + try options.setOption(display, &globals); + } else { + const control = globals.control orelse return error.RiverControlNotAdvertised; + const seat = globals.seat orelse return error.SeatNotAdverstised; - // Skip our name, send all other args - // This next line is needed cause of https://github.com/ziglang/zig/issues/2622 - const args = std.os.argv; - for (args[1..]) |arg| river_control.addArgument(arg); + // Skip our name, send all other args + // This next line is needed cause of https://github.com/ziglang/zig/issues/2622 + const args = os.argv; + for (args[1..]) |arg| control.addArgument(arg); - const callback = try river_control.runCommand(seat); + const callback = try control.runCommand(seat); - callback.setListener(?*c_void, callbackListener, null) catch unreachable; + callback.setListener(?*c_void, callbackListener, null) catch unreachable; - // Loop until our callback is called and we exit. - while (true) _ = try display.dispatch(); + // Loop until our callback is called and we exit. + while (true) _ = try display.dispatch(); + } } -fn registryListener(registry: *wl.Registry, event: wl.Registry.Event, context: *SetupContext) void { +fn registryListener(registry: *wl.Registry, event: wl.Registry.Event, globals: *Globals) void { switch (event) { .global => |global| { - if (context.seat == null and std.cstr.cmp(global.interface, wl.Seat.getInterface().name) == 0) { - context.seat = registry.bind(global.name, wl.Seat, 1) catch return; + if (globals.seat == null and std.cstr.cmp(global.interface, wl.Seat.getInterface().name) == 0) { + globals.seat = registry.bind(global.name, wl.Seat, 1) catch @panic("out of memory"); } else if (std.cstr.cmp(global.interface, zriver.ControlV1.getInterface().name) == 0) { - context.river_control = registry.bind(global.name, zriver.ControlV1, 1) catch return; + globals.control = registry.bind(global.name, zriver.ControlV1, 1) catch @panic("out of memory"); + } else if (std.cstr.cmp(global.interface, zriver.OptionsManagerV1.getInterface().name) == 0) { + globals.options_manager = registry.bind(global.name, zriver.OptionsManagerV1, 1) catch @panic("out of memory"); + } else if (std.cstr.cmp(global.interface, zxdg.OutputManagerV1.getInterface().name) == 0 and global.version >= 2) { + globals.output_manager = registry.bind(global.name, zxdg.OutputManagerV1, 2) catch @panic("out of memory"); + } else if (std.cstr.cmp(global.interface, wl.Output.getInterface().name) == 0) { + const output = registry.bind(global.name, wl.Output, 1) catch @panic("out of memory"); + globals.outputs.append(.{ .wl_output = output, .name = undefined }) catch @panic("out of memory"); } }, .global_remove => {}, @@ -67,15 +97,20 @@ fn registryListener(registry: *wl.Registry, event: wl.Registry.Event, context: * fn callbackListener(callback: *zriver.CommandCallbackV1, event: zriver.CommandCallbackV1.Event, _: ?*c_void) void { switch (event) { .success => |success| { - if (std.mem.len(success.output) > 0) { + if (mem.len(success.output) > 0) { const stdout = std.io.getStdOut().outStream(); stdout.print("{}\n", .{success.output}) catch @panic("failed to write to stdout"); } - std.os.exit(0); + os.exit(0); }, .failure => |failure| { std.debug.print("Error: {}\n", .{failure.failure_message}); - std.os.exit(1); + os.exit(1); }, } } + +pub fn printErrorExit(comptime format: []const u8, args: anytype) noreturn { + std.debug.print("err: " ++ format ++ "\n", args); + os.exit(1); +} diff --git a/riverctl/options.zig b/riverctl/options.zig new file mode 100644 index 0000000..99e0be5 --- /dev/null +++ b/riverctl/options.zig @@ -0,0 +1,187 @@ +// This file is part of river, a dynamic tiling wayland compositor. +// +// Copyright 2021 The River Developers +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +const std = @import("std"); +const os = std.os; +const mem = std.mem; +const fmt = std.fmt; + +const wayland = @import("wayland"); +const wl = wayland.client.wl; +const zriver = wayland.client.zriver; +const zxdg = wayland.client.zxdg; + +const root = @import("root"); + +const Args = @import("args.zig").Args; +const FlagDef = @import("args.zig").FlagDef; +const Globals = @import("main.zig").Globals; +const Output = @import("main.zig").Output; + +const ValueType = enum { + int, + uint, + fixed, + string, +}; + +const Context = struct { + display: *wl.Display, + key: [*:0]const u8, + raw_value: [*:0]const u8, + output: ?*Output, +}; + +pub fn declareOption(display: *wl.Display, globals: *Globals) !void { + // https://github.com/ziglang/zig/issues/7807 + const argv: [][*:0]const u8 = os.argv; + const args = Args(3, &[_]FlagDef{.{ .name = "-output", .kind = .arg }}).parse(argv[2..]); + const key = args.positionals[0]; + const value_type = std.meta.stringToEnum(ValueType, mem.span(args.positionals[1])) orelse + root.printErrorExit("'{}' is not a valid type, must be int, uint, fixed, or string", .{args.positionals[1]}); + const raw_value = args.positionals[2]; + const output = if (args.argFlag("-output")) |o| try parseOutputName(display, globals, o) else null; + + const options_manager = globals.options_manager orelse return error.RiverOptionsManagerNotAdvertised; + const handle = try options_manager.getOptionHandle(key, if (output) |o| o.wl_output else null); + + switch (value_type) { + .int => setIntValueRaw(handle, raw_value), + .uint => setUintValueRaw(handle, raw_value), + .fixed => setFixedValueRaw(handle, raw_value), + .string => handle.setStringValue(raw_value), + } + _ = display.flush() catch os.exit(1); +} + +fn setIntValueRaw(handle: *zriver.OptionHandleV1, raw_value: [*:0]const u8) void { + handle.setIntValue(fmt.parseInt(i32, mem.span(raw_value), 10) catch + root.printErrorExit("{} is not a valid int", .{raw_value})); +} + +fn setUintValueRaw(handle: *zriver.OptionHandleV1, raw_value: [*:0]const u8) void { + handle.setUintValue(fmt.parseInt(u32, mem.span(raw_value), 10) catch + root.printErrorExit("{} is not a valid uint", .{raw_value})); +} + +fn setFixedValueRaw(handle: *zriver.OptionHandleV1, raw_value: [*:0]const u8) void { + handle.setFixedValue(wl.Fixed.fromDouble(fmt.parseFloat(f64, mem.span(raw_value)) catch + root.printErrorExit("{} is not a valid fixed", .{raw_value}))); +} + +pub fn getOption(display: *wl.Display, globals: *Globals) !void { + // https://github.com/ziglang/zig/issues/7807 + const argv: [][*:0]const u8 = os.argv; + const args = Args(1, &[_]FlagDef{.{ .name = "-output", .kind = .arg }}).parse(argv[2..]); + const ctx = Context{ + .display = display, + .key = args.positionals[0], + .raw_value = undefined, + .output = if (args.argFlag("-output")) |o| try parseOutputName(display, globals, o) else null, + }; + + const options_manager = globals.options_manager orelse return error.RiverOptionsManagerNotAdvertised; + const handle = try options_manager.getOptionHandle(ctx.key, if (ctx.output) |o| o.wl_output else null); + handle.setListener(*const Context, getOptionListener, &ctx) catch unreachable; + + // We always exit when our listener is called + while (true) _ = try display.dispatch(); +} + +pub fn setOption(display: *wl.Display, globals: *Globals) !void { + // https://github.com/ziglang/zig/issues/7807 + const argv: [][*:0]const u8 = os.argv; + const args = Args(2, &[_]FlagDef{.{ .name = "-output", .kind = .arg }}).parse(argv[2..]); + const ctx = Context{ + .display = display, + .key = args.positionals[0], + .raw_value = args.positionals[1], + .output = if (args.argFlag("-output")) |o| try parseOutputName(display, globals, o) else null, + }; + + const options_manager = globals.options_manager orelse return error.RiverOptionsManagerNotAdvertised; + const handle = try options_manager.getOptionHandle(ctx.key, if (ctx.output) |o| o.wl_output else null); + handle.setListener(*const Context, setOptionListener, &ctx) catch unreachable; + + // We always exit when our listener is called + while (true) _ = try display.dispatch(); +} + +fn parseOutputName(display: *wl.Display, globals: *Globals, output_name: [*:0]const u8) !*Output { + const output_manager = globals.output_manager orelse return error.XdgOutputNotAdvertised; + for (globals.outputs.items) |*output| { + const xdg_output = try output_manager.getXdgOutput(output.wl_output); + xdg_output.setListener(*Output, xdgOutputListener, output) catch unreachable; + } + _ = try display.roundtrip(); + + for (globals.outputs.items) |*output| { + if (mem.eql(u8, output.name, mem.span(output_name))) return output; + } + root.printErrorExit("unknown output '{}'", .{output_name}); +} + +fn xdgOutputListener(xdg_output: *zxdg.OutputV1, event: zxdg.OutputV1.Event, output: *Output) void { + switch (event) { + .name => |ev| output.name = std.heap.c_allocator.dupe(u8, mem.span(ev.name)) catch @panic("out of memory"), + else => {}, + } +} + +fn getOptionListener( + handle: *zriver.OptionHandleV1, + event: zriver.OptionHandleV1.Event, + ctx: *const Context, +) void { + switch (event) { + .unset => if (ctx.output) |output| { + root.printErrorExit("option '{}' has not been declared on output '{}'", .{ ctx.key, output.name }); + } else { + root.printErrorExit("option '{}' has not been declared globally", .{ctx.key}); + }, + .int_value => |ev| printOutputExit("{}", .{ev.value}), + .uint_value => |ev| printOutputExit("{}", .{ev.value}), + .fixed_value => |ev| printOutputExit("{d}", .{ev.value.toDouble()}), + .string_value => |ev| printOutputExit("{}", .{ev.value}), + } +} + +fn printOutputExit(comptime format: []const u8, args: anytype) noreturn { + const stdout = std.io.getStdOut().writer(); + stdout.print(format ++ "\n", args) catch os.exit(1); + os.exit(0); +} + +fn setOptionListener( + handle: *zriver.OptionHandleV1, + event: zriver.OptionHandleV1.Event, + ctx: *const Context, +) void { + switch (event) { + .unset => if (ctx.output) |output| { + root.printErrorExit("option '{}' has not been declared on output '{}'", .{ ctx.key, output.name }); + } else { + root.printErrorExit("option '{}' has not been declared globally", .{ctx.key}); + }, + .int_value => |ev| setIntValueRaw(handle, ctx.raw_value), + .uint_value => |ev| setUintValueRaw(handle, ctx.raw_value), + .fixed_value => |ev| setFixedValueRaw(handle, ctx.raw_value), + .string_value => |ev| handle.setStringValue(ctx.raw_value), + } + _ = ctx.display.flush() catch os.exit(1); + os.exit(0); +}