RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Add input sources: taskbar layout indicator, switching and Settings page
oxydizer8186ee5b7165
diff --git a/TESTING.md b/TESTING.mdindex d068d0c..3bf0250 100644--- a/TESTING.md+++ b/TESTING.md@@ -41,6 +41,10 @@ agent. Requires OpenSSH, OpenSSL and `gio`; `GIO_USE_VFS=local` keeps Trashwithin the fixture. `--helper-only` skips the compositor; `--bin-dir` selectsthe helper and compositor builds together.+Keyboard layouts and input methods: `python3 tests/input_sources.py` starts+its own `dbus-run-session` with a fake Fcitx5 controller; it never reaches the+host's Fcitx. Layout labels need libxkbregistry.+## Isolation and harness- Use a private headless compositor, temporary home/XDG directories and privatediff --git a/docs/plans/input-sources.md b/docs/plans/input-sources.mdnew file mode 100644index 0000000..1519522--- /dev/null+++ b/docs/plans/input-sources.md@@ -0,0 +1,88 @@+# Input sources plan++A taskbar indicator for the active keyboard layout or input method (`EN`,+`DE`, `JA`, `あ`), click to switch, and Settings → Input → **Input Sources** to+add, remove and reorder layouts. Works with plain XKB and with Fcitx5. Drafted+and decided 2026-11-11; built the same day (see Status).++## Decisions++* **D1, labels are language codes:** xkbregistry's `brief`, uppercased (`EN DE+ JA RU`); a region is dropped (`zh_CN` → ZH); repeats get subscripts (EN₁,+ EN₂). `xkb_labels` overrides by position. Fcitx methods use Fcitx's own label+ (Mozc `あ`), else their language code.+* **D2, clicking opens a list** (the taskbar window menu in its sources mode);+ scrolling over the item steps through the sources.+* **D3, Fcitx5 is read and switched, never written.** Its methods come from its+ current group; `fcitx5-configtool` stays their editor.+* **D4, at most four layouts** (XKB/X11/Xwayland). Settings stops at four; a+ hand-written list is cut to four with a warning in the log.+* **D5, shortcut:** `input_source_next`/`input_source_prev`, default+ `super+shift+space` (added to existing configs like the other always-kept+ bindings), plus XKB's own `grp:` switch keys as a Settings choice.+* **D6, the active source is global;** per-window memory is left for later.+* **D7, storage stays in the existing lists** (`xkb_layout`, `xkb_variant`) plus+ an optional parallel `xkb_labels`, written in one save. With Fcitx entries+ out of the config (D3), a separate `[[input_source]]` table would have bought+ nothing over them and needed a migration.++## How it works++* `input_sources.zig` (`Manager` on `Server`): the layouts from the config,+ then Fcitx's methods; `activeIndex`, `select`, `cycle`, `cycleLayouts` (lock).+ `announce` tells the taskbars, the open menu, the lock, IPC and Settings once+ per real change.+* **Active layout:** one group for every keyboard with the config keymap.+ Switching sets it on all of them (the keyboard in use last); a keyboard that+ switches itself moves it and the rest follow from an idle callback. A reload+ or reorder keeps the active layout by identity.+* **Labels and names:** `input_sources/registry.zig` reads evdev.xml through a+ dlopen'd libxkbregistry (about 11 ms) on a worker, only once there are two+ layouts or Settings asks; without the library labels fall back to the layout+ code and Settings to a short built-in list.+* **Fcitx5** (`input_sources/fcitx.zig`): `org.fcitx.Fcitx5` `/controller`+ `org.fcitx.Fcitx.Controller1`: `CurrentInputMethodGroup`,+ `InputMethodGroupInfo`, `AvailableInputMethods`, `CurrentInputMethod`,+ `SetCurrentIM`, `Deactivate`, signal `InputMethodGroupsChanged`.+ Controller1 has no signal for the current method, so any signal from Fcitx's+ unique name (its tray item updates on every change) re-asks+ `CurrentInputMethod`, one call at a time. NameOwnerChanged follows Fcitx+ starting and leaving. Choosing a layout calls `Deactivate`; choosing a method+ `SetCurrentIM`. Started after the first frame, never in the greeter.+* **Taskbar:** `taskbar_items.Item.input_source` (tray kind `input_source`),+ automatic by default via `Presence.input_sources`; older lists gain it before+ Volume.+* **Lock:** a layout button bottom left (never in the greeter) and the shortcut+ cycle layouts only; the label is copied into `Lock` so painting needs no+ server.+* **Settings:** an Input Sources card before the keyboard repeat rows: layout+ rows with Move up/down and Remove (no drag), an inline search over the+ registry to add, Fcitx's methods read-only with "Configure in Fcitx…", "Also+ switch with" (`grp:` options) and "Show in taskbar".+* **IPC:** `get_input_sources`, `switch_input_source`, event+ `InputSourceChanged`; `rediwm-msg input-sources`, `switch-input-source`.++## Status++Built 2026-11-11, uncommitted. Not yet checked against a real Fcitx5 (none is+installed on the development machine): the Controller1 names above are from+Fcitx5's D-Bus module, and two things need a run with Fcitx5 + Mozc in a nested+session: that Fcitx's tray item (or some other object) really signals on each+method change, and that under input-method-v2 Fcitx forwards keys with the+compositor's current group rather than its own `keyboard-*` layout. Also open:+translations of the new strings, IBus, more than four layouts (keymap swap),+per-window memory, the greeter, and the FreeBSD cross-build check.++## Tests++* Unit: `config/input_sources.zig` (split, join, cap, validation),+ `taskbar_items.zig` (migration, automatic item), `input_sources/labels.zig`,+ `registry.zig` (skipped without the library), `fcitx.zig` (group parsing),+ `sections/input_sources.zig` (`grp:` editing, search), `lock_tests.zig`+ (layout button), IPC parsing and serializer fixtures.+* `python3 tests/input_sources.py` (wraps itself in `dbus-run-session`): labels,+ the automatic item, the menu, Super+Shift+Space, IPC, scrolling, the CLI; a+ fake Fcitx (list, switch, external change, group change, leaving, no+ config writes); Settings add/reorder/remove/visibility.+* Also run: `layout_ipc.py`, `msg.py`, `taskbar_sections.py`, `hotspots.py`,+ `input_protocols.py`, `control_center.py`, `greeter.py`, `zig build test-lock`.diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.mdindex 0b940b5..c148832 100644--- a/docs/wiki/Configuration.md+++ b/docs/wiki/Configuration.md@@ -60,6 +60,36 @@ time vertically. These two options apply only to the taskbar clock.weekday headings and date positions in the taskbar calendar. Existing configskeep 12-hour time and Sunday first until changed.+## Keyboard layouts and input methods++Settings → Input → **Input Sources** adds (from a searchable list of every XKB+layout), reorders and removes keyboard layouts. They are saved as the usual+comma lists, in order:++```toml+[input]+xkb_layout = "us,de,jp"+xkb_variant = ",nodeadkeys," # by position+xkb_labels = ",,JP" # optional indicator texts by position+```++XKB, X11 and Xwayland allow four layouts; later ones are ignored. The taskbar's+input source item shows the active one by its language code (EN, DE, JA) or the+label you set, and appears automatically once there is more than one source+(`~right:input_source` in `taskbar_items`; Settings can show it always or+never). Click it for the list, scroll over it to step through, or press+Super+Shift+Space (`input_source_next` / `input_source_prev`). Settings can+also turn on XKB's own switch keys (Alt+Shift, Ctrl+Shift, Caps Lock, both+Shifts), which edit `xkb_options` and switch layouts only. The lock screen+shows a layout button while there are several, and the shortcut works there.++While Fcitx 5 runs (`[input_method] env = "fcitx"` and an `[[autostart]]`+for `fcitx5 -d`), the input methods of its current group follow the layouts+in the list (its `keyboard-*` entries are left out: layouts are RediWM's).+RediWM switches between them and follows switches made in Fcitx, but never+changes Fcitx's own configuration; use `fcitx5-configtool` (Settings has a+button) to add or remove methods. Input methods never reach the lock screen.+## Handy `[compositor]` keysSettings → Appearance includes **Dock position**, **Dock size** and **Dock hover zoom**.@@ -114,7 +144,10 @@ The center group stays centered on the display when it fits, and shifts ornarrows the window list to avoid the side groups.For example, `taskbar_items = ["left:start", "left:windows", "right:capture", "right:tray",-"right:battery", "~right:wifi", "~right:wired", "right:volume", "right:clock", "-right:power"]` is the default.+"right:battery", "~right:wifi", "~right:wired", "~right:input_source", "right:volume", "right:clock",+"-right:power"]` is the default. The keyboard layout item (`input_source`) is+described under "Keyboard layouts and input methods"; older lists gain it+before Volume, automatic.Wi-Fi and Ethernet are automatic (the `~` prefix): Wi-Fi shows only when themachine has a wireless adapter, and Ethernet only while a cable is connected;Wi-Fi opens the network menu, Ethernet opens Settings → Network. Turning an itemdiff --git a/docs/wiki/IPC-Commands.md b/docs/wiki/IPC-Commands.mdindex 5ba3241..58e7df4 100644--- a/docs/wiki/IPC-Commands.md+++ b/docs/wiki/IPC-Commands.md@@ -104,6 +104,8 @@ Names are the wire names (`"command": "..."`). The CLI column is the| **[auto]** `swipe` | none | phase, `dx`, `dy`, `fingers`, `cancelled` || `get_keyboard_layouts` | `keyboard-layouts` | zero-based active index || `switch_layout` | `switch-layout <next\|prev\|index>` | |+| `get_input_sources` | `input-sources` | layouts and Fcitx methods, zero-based `active` and `active_layout` |+| `switch_input_source` | `switch-input-source <next\|prev\|index>` | event `InputSourceChanged` |## Screenshots and pixelsdiff --git a/docs/wiki/Using-RediWM.md b/docs/wiki/Using-RediWM.mdindex dd630b7..a9793d3 100644--- a/docs/wiki/Using-RediWM.md+++ b/docs/wiki/Using-RediWM.md@@ -5,6 +5,7 @@| Keys | Action || --- | --- || Super+Space | centered app launcher |+| Super+Shift+Space | next keyboard layout or input method || Super+T / E / B | terminal / Files / browser || Super+Q, Super+F, Super+M | close, fullscreen, maximize || Super+Shift+arrows | tile halves and quarters |diff --git a/docs/wiki/rediwm-msg.md b/docs/wiki/rediwm-msg.mdindex 7504e7a..00511b3 100644--- a/docs/wiki/rediwm-msg.md+++ b/docs/wiki/rediwm-msg.md@@ -113,6 +113,7 @@ rediwm-msg close-panel start_menurediwm-msg action set-master-volume --volume 0.4rediwm-msg action toggle-muterediwm-msg switch-layout next+rediwm-msg switch-input-source next```**Anything without a subcommand**diff --git a/po/rediwm.pot b/po/rediwm.potindex 7e95b67..1ba104f 100644--- a/po/rediwm.pot+++ b/po/rediwm.pot@@ -219,6 +219,10 @@ msgstr ""msgid "Add a printer"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Add layout…"+msgstr ""+#: src/files/app_model.zigmsgid "Add to applications"msgstr ""@@ -323,6 +327,19 @@ msgstr ""msgid "Already in Places"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Also switch with"+msgstr ""++#: src/control_center/sections/input_sources.zig+#. raw+msgid "Alt+Shift"+msgstr ""++#: src/control_center/sections/input_sources.zig+msgid "Always"+msgstr ""+#: src/files/open_with.zigmsgid "Always use this app for this file type"msgstr ""@@ -587,7 +604,7 @@ msgstr ""msgid "Auto-join this network"msgstr ""-#: src/control_center/sections/network_details.zig+#: src/control_center/sections/input_sources.zigmsgid "Automatic"msgstr ""@@ -611,6 +628,10 @@ msgstr ""msgid "Automatic power actions are inactive in this session."msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Automatic shows it while there is more than one source."+msgstr ""+#: src/control_center/sections/desktop.zigmsgid "Automatic tiles with a fixed view and Hyprland-style shortcuts. Drag tiles to rearrange; Super+V toggles floating."msgstr ""@@ -747,6 +768,10 @@ msgstr ""msgid "Border glow"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Both Shift keys"+msgstr ""+#: src/control_center/sections/appearance_sections.zigmsgid "Bottom"msgstr ""@@ -1019,6 +1044,10 @@ msgstr ""msgid "Canvas · RediWM preset"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Caps Lock"+msgstr ""+#: src/session/lock_view.zigmsgid "Caps Lock is on"msgstr ""@@ -1407,6 +1436,10 @@ msgstr ""msgid "Configuration URL"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Configure in Fcitx…"+msgstr ""+#: src/control_center/sections/network.zigmsgid "Configure this network with a network tool"msgstr ""@@ -2021,6 +2054,10 @@ msgstr ""msgid "Crop"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Ctrl+Shift"+msgstr ""+#: src/control_center/sections/region.zigmsgid "Currency"msgstr ""@@ -2053,14 +2090,14 @@ msgstr ""msgid "Custom"msgstr ""-#: src/control_center/sections/input.zig-msgid "Custom (config file)"-msgstr ""-#: src/control_center/sections/portals.zigmsgid "Custom ({name})"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Custom ({option})"+msgstr ""+#: src/control_center/sections/appearance_sections.zigmsgid "Custom size"msgstr ""@@ -2803,6 +2840,18 @@ msgstr ""msgid "Failed to start transfer job"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Fcitx 5 is not running. Its input methods appear here while it runs."+msgstr ""++#: src/control_center/sections/input_sources.zig+msgid "Fcitx manages its own list; RediWM only switches between its methods."+msgstr ""++#: src/control_center/sections/input_sources.zig+msgid "Fcitx's current group has no input methods besides keyboards."+msgstr ""+#: src/files/torrents.zigmsgid "Fetching file list…"msgstr ""@@ -3119,6 +3168,10 @@ msgstr ""msgid "Forward"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Four keyboard layouts is the most XKB allows."+msgstr ""+#: src/control_center/sections/region.zigmsgid "Friday"msgstr ""@@ -3359,6 +3412,26 @@ msgstr ""msgid "Input"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Input Sources"+msgstr ""++#: src/control_center/sections/input_sources.zig+msgid "Input methods (Fcitx 5)"+msgstr ""++#: src/taskbar/window_menu.zig+msgid "Input settings…"+msgstr ""++#: src/control_center/search_index.zig+msgid "Input sources"+msgstr ""++#: src/control_center/sections/input_sources.zig+msgid "Input sources are unavailable."+msgstr ""+#: src/control_center/sections/bluetooth.zigmsgid "Input · Keyboard, mouse or controller"msgstr ""@@ -3547,10 +3620,6 @@ msgstr ""msgid "Keyboard backlight"msgstr ""-#: src/control_center/sections/input.zig-msgid "Keyboard layout"-msgstr ""-#: src/control_center/search_index.zigmsgid "Keyboard repeat delay"msgstr ""@@ -3623,6 +3692,10 @@ msgstr ""msgid "Launcher"msgstr ""+#: src/control_center/search_index.zig+msgid "Layout switch keys"+msgstr ""+#: src/control_center/sections/desktop.zigmsgid "Layouts and split sizes are saved for your next session."msgstr ""@@ -3719,6 +3792,10 @@ msgstr ""msgid "Loading image…"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Loading layouts…"+msgstr ""+#: src/control_center/sections/printers.zigmsgid "Loading printers…"msgstr ""@@ -3987,6 +4064,10 @@ msgstr ""msgid "Move To Workspace"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Move down"+msgstr ""+#: src/control_center/sections/appearance_rows.zigmsgid "Move file manager aside"msgstr ""@@ -4039,6 +4120,10 @@ msgstr ""msgid "Move to workspace."msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Move up"+msgstr ""+#: src/control_center/welcome.zigmsgid "Move, resize and overlap windows."msgstr ""@@ -4143,7 +4228,7 @@ msgstr ""msgid "NetworkManager unavailable"msgstr ""-#: src/control_center/sections/power.zig+#: src/control_center/sections/input_sources.zigmsgid "Never"msgstr ""@@ -4211,6 +4296,10 @@ msgstr ""msgid "Next"msgstr ""+#: src/control_center/sections/shortcuts.zig+msgid "Next Input Source"+msgstr ""+#: src/session/lock_view.zigmsgid "Next account"msgstr ""@@ -4295,6 +4384,10 @@ msgstr ""msgid "No internet connection"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "No layouts match."+msgstr ""+#: src/control_center/sections/users.zigmsgid "No login accounts were found."msgstr ""@@ -4583,6 +4676,11 @@ msgstr ""msgid "Only the owner can change permissions"msgstr ""+#: src/control_center/sections/input_sources.zig+#. raw+msgid "Only the shortcut (Super+Shift+Space)"+msgstr ""+#: src/files/appimage.zigmsgid "Only type-2 AppImages are supported"msgstr ""@@ -5047,6 +5145,10 @@ msgstr ""msgid "Previous"msgstr ""+#: src/control_center/sections/shortcuts.zig+msgid "Previous Input Source"+msgstr ""+#: src/session/lock_view.zigmsgid "Previous account"msgstr ""@@ -5933,6 +6035,10 @@ msgstr ""msgid "Search domains"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Search layouts or languages…"+msgstr ""+#: src/system_monitor/app.zigmsgid "Search name, PID or user"msgstr ""@@ -6137,6 +6243,10 @@ msgstr ""msgid "Show in folder"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "Show in taskbar"+msgstr ""+#: src/control_center/sections/appearance_rows.zigmsgid "Show launch splash"msgstr ""@@ -6461,6 +6571,10 @@ msgstr ""msgid "Swap the focused tile up."msgstr ""+#: src/control_center/sections/shortcuts.zig+msgid "Switch to the next keyboard layout or input method."+msgstr ""+#: src/control_center/sections/shortcuts.zigmsgid "Switch to the next power profile."msgstr ""@@ -6469,6 +6583,10 @@ msgstr ""msgid "Switch to the next window."msgstr ""+#: src/control_center/sections/shortcuts.zig+msgid "Switch to the previous keyboard layout or input method."+msgstr ""+#: src/control_center/sections/shortcuts.zigmsgid "Switch to the previous window."msgstr ""@@ -6897,6 +7015,10 @@ msgstr ""msgid "The system service manager is unavailable; start CUPS using your distribution's service tools."msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "The taskbar shows the active source. Click it, or press Super+Shift+Space, to switch."+msgstr ""+#: src/control_center/search_index.zigmsgid "Theme"msgstr ""@@ -7685,6 +7807,10 @@ msgstr ""msgid "Write"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "XKB switch keys change keyboard layouts only."+msgstr ""+#: src/control_center/search_index.zigmsgid "Xwayland scale"msgstr ""@@ -8005,6 +8131,14 @@ msgstr ""msgid "keep icons in place"msgstr ""+#: src/control_center/search_index.zig+msgid "keyboard layout alt shift caps lock toggle"+msgstr ""++#: src/control_center/search_index.zig+msgid "keyboard layout language input method ime fcitx switch"+msgstr ""+#: src/control_center/search_index.zigmsgid "keyboard touchpad trackpad"msgstr ""@@ -8581,6 +8715,10 @@ msgstr[1] ""msgid "{rate} KiB/s"msgstr ""+#: src/control_center/sections/input_sources.zig+msgid "{shown} of {total} layouts; type to narrow the list."+msgstr ""+#: src/files/properties.zigmsgid "{size} ({bytes} byte)"msgid_plural "{size} ({bytes} bytes)"diff --git a/src/Output.zig b/src/Output.zigindex ea2deac..d2729aa 100644--- a/src/Output.zig+++ b/src/Output.zig@@ -447,6 +447,7 @@ pub const closeStartMenu = output_panels.closeStartMenu;pub const syncStartMenu = output_panels.syncStartMenu;pub const toggleControlCenter = output_panels.toggleControlCenter;pub const openNetworkSettings = output_panels.openNetworkSettings;+pub const openInputSettings = output_panels.openInputSettings;pub const closeControlCenter = output_panels.closeControlCenter;pub const openPowerMenu = output_panels.openPowerMenu;pub const closePowerMenu = output_panels.closePowerMenu;diff --git a/src/Server.zig b/src/Server.zigindex 283ea83..05ae333 100644--- a/src/Server.zig+++ b/src/Server.zig@@ -205,6 +205,8 @@ config_watcher: ?watcher_mod.ConfigWatcher = null,config_generation: u64 = 1,config_reload_error: ?[]const u8 = null,layout_keyboard: ?*@import("Keyboard.zig") = null,+/// Keyboard layouts and Fcitx input methods (`input_sources.zig`).+input_sources: ?*@import("input_sources.zig").Manager = null,start_menu_catalog: *applications.Catalog,launcher_history: @import("start_menu/history.zig").History = .{},/// Memoizes `iconNameForAppId`, which is three linear scans over the wholediff --git a/src/Taskbar.zig b/src/Taskbar.zigindex a75e701..699e2f1 100644--- a/src/Taskbar.zig+++ b/src/Taskbar.zig@@ -162,7 +162,9 @@ capture_sessions: usize = 0,start: start_button.State = .{},start_logo: ?icon_service.Entry = null,chips: std.ArrayList(ChipState) = .empty,-tray: [tray_count]TrayState = .{ .{ .kind = .volume }, .{ .kind = .wifi }, .{ .kind = .power }, .{ .kind = .wired } },+tray: [tray_count]TrayState = .{ .{ .kind = .volume }, .{ .kind = .wifi }, .{ .kind = .power }, .{ .kind = .wired }, .{ .kind = .input_source } },+// Touchpad scrolling over the input source item, gathered into steps.+source_scroll: f32 = 0,capture_hover: Anim = .{},capture_press: Anim = .{ .to = 1 },hover_target: Target = .none,@@ -179,7 +181,8 @@ audio_muted: bool = false,// colour, like a muted speaker. Pushed by `network.Manager`, never polled.network_offline: bool = false,// Whether a wireless adapter exists and a cable is connected: decides the-// automatic Wi-Fi and Ethernet items. Pushed by `network.Manager`.+// automatic Wi-Fi and Ethernet items. Pushed by `network.Manager`; its+// `input_sources` part comes from `input_sources.Manager`.network_presence: taskbar_items.Presence = .{},// While offline the wifi icon also blinks (one cycle a second) so a dropped// connection stands out. A real deadline only while offline: the timer is@@ -213,8 +216,8 @@ pub const BarBuffer = taskbar_types.BarBuffer;pub const ChipPaint = taskbar_types.ChipPaint;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 };+// New kinds come last so the IPC tray indices of the others stay put.+pub const TrayKind = enum { volume, wifi, power, wired, input_source };pub const tray_count = @typeInfo(TrayKind).@"enum".field_names.len;pub const AppKind = enum { file_explorer, notes, terminal, settings, text_doc, browser, other };@@ -272,7 +275,11 @@ pub fn create(server: *Server, wlr_output: *wlr.Output) !*Taskbar {.glass_effect = glass_effect,.battery_state = server.power_policy.state,.network_offline = if (server.network) |network| network.offline() else false,- .network_presence = if (server.network) |network| network.presence() else .{},+ .network_presence = presence: {+ var presence: taskbar_items.Presence = if (server.network) |network| network.presence() else .{};+ presence.input_sources = if (server.input_sources) |sources| sources.switchable() else false;+ break :presence presence;+ },.clock_minute = @divFloor(c_time.time(null), 60),.timer = undefined,};@@ -351,7 +358,9 @@ pub fn applyNetwork(bar: *Taskbar, offline: bool) void {/// An adapter or a cable appearing or going shows or hides the automatic/// items, which moves their neighbours like a battery coming or going.-pub fn applyNetworkPresence(bar: *Taskbar, next: taskbar_items.Presence) void {+pub fn applyNetworkPresence(bar: *Taskbar, network: taskbar_items.Presence) void {+ var next = network;+ next.input_sources = bar.network_presence.input_sources;if (std.meta.eql(next, bar.network_presence)) return;bar.network_presence = next;_ = bar.reconcile(nowMs());@@ -362,6 +371,26 @@ pub fn applyNetworkPresence(bar: *Taskbar, next: taskbar_items.Presence) void {bar.wlr_output.scheduleFrame();}+/// The active input source or the number of sources changed. Only the+/// indicator repaints unless it appears or goes, which moves its neighbours.+pub fn applyInputSource(bar: *Taskbar, presence_changed: bool) void {+ const switchable = if (bar.server.input_sources) |sources| sources.switchable() else false;+ if (presence_changed or switchable != bar.network_presence.input_sources) {+ var next = bar.network_presence;+ next.input_sources = switchable;+ bar.network_presence = next;+ _ = bar.reconcile(nowMs());+ bar.tray_dirty = @splat(true);+ bar.clock_dirty = true;+ bar.capture_dirty = true;+ bar.markDirty(paint_tray | paint_clock | paint_capture);+ } else {+ bar.tray_dirty[@backingInt(TrayKind.input_source)] = true;+ bar.markDirty(paint_tray);+ }+ bar.wlr_output.scheduleFrame();+}+pub const blink_half_ms = 500;/// Arm the blink timer while offline, disarm it otherwise.diff --git a/src/config/default.zig b/src/config/default.zigindex ce9bcf0..3b323d9 100644--- a/src/config/default.zig+++ b/src/config/default.zig@@ -95,8 +95,11 @@ pub const source =\\disable_while_typing = true\\disable_while_typing_touchpad = true\\# Empty XKB names use XKB_DEFAULT_* or system defaults.+ \\# Several layouts are input sources (at most 4): the taskbar shows the active+ \\# one and switches on click; super+shift+space cycles them.\\xkb_layout = "" # e.g. "fr" for AZERTY, "us,ru"- \\xkb_variant = ""+ \\xkb_variant = "" # by position, e.g. ",nodeadkeys"+ \\xkb_labels = "" # optional indicator texts by position, e.g. ",,JP"\\xkb_options = "" # e.g. "grp:caps_toggle"\\xkb_model = ""\\key_repeat_delay = 400 # ms@@ -150,9 +153,10 @@ pub const source =\\# Taskbar sections, ordered within each section; prefix with - to hide an item.\\taskbar_position = "bottom" # top or bottom\\taskbar_alignment = "center" # left, center or right; visible below 100% length- \\taskbar_items = ["left:start", "left:windows", "right:capture", "right:tray", "right:battery", "~right:wifi", "~right:wired", "right:volume", "right:clock", "-right:power"]+ \\taskbar_items = ["left:start", "left:windows", "right:capture", "right:tray", "right:battery", "~right:wifi", "~right:wired", "~right:input_source", "right:volume", "right:clock", "-right:power"]\\# A ~ prefix (~right:wifi, ~right:wired) shows the item only while a wireless adapter- \\# exists, or a cable is connected; a plain or - entry always shows or hides it.+ \\# exists, or a cable is connected, and ~right:input_source while there is more than+ \\# one keyboard layout or input method; a plain or - entry always shows or hides it.\\# Hiding capture (-right:capture) removes the recording/sharing indicator; not recommended.\\focus_follows_mouse = false\\canvas_columns = 3 # screens wide (1-10)@@ -379,6 +383,7 @@ pub const source =\\"super+b" = "spawn firefox"\\"super+e" = "spawn default-file-manager"\\"super+space" = "toggle_start_menu"+ \\"super+shift+space" = "input_source_next"\\\\# Window management\\"super+q" = "close_window"diff --git a/src/config/input_sources.zig b/src/config/input_sources.zignew file mode 100644index 0000000..bc2b05c--- /dev/null+++ b/src/config/input_sources.zig@@ -0,0 +1,155 @@+//! Keyboard layouts as an ordered list of input sources. They live in the+//! existing comma lists (`xkb_layout`, `xkb_variant`), so older configs and+//! other tools keep reading them; `xkb_labels` adds optional indicator texts+//! in the same positions. Order is the XKB group order.+const std = @import("std");++/// XKB, X11 and Xwayland address at most four groups.+pub const max_layouts = 4;+/// Longest indicator text a source may carry (a few characters, any script).+pub const max_label_bytes = 16;++pub const Layout = struct {+ layout: []const u8,+ variant: []const u8 = "",+ label: []const u8 = "",++ pub fn eql(a: Layout, b: Layout) bool {+ return std.mem.eql(u8, a.layout, b.layout) and std.mem.eql(u8, a.variant, b.variant);+ }++ /// `de(nodeadkeys)`, the usual XKB spelling of a layout and variant.+ pub fn format(self: Layout, buf: []u8) []const u8 {+ if (self.variant.len == 0) return std.fmt.bufPrint(buf, "{s}", .{self.layout}) catch self.layout;+ return std.fmt.bufPrint(buf, "{s}({s})", .{ self.layout, self.variant }) catch self.layout;+ }+};++pub const List = struct {+ items: [max_layouts]Layout = undefined,+ len: usize = 0,+ /// Entries past `max_layouts` that were dropped.+ dropped: usize = 0,++ pub fn slice(self: *const List) []const Layout {+ return self.items[0..self.len];+ }+};++/// The configured layouts in group order; empty when `xkb_layout` is empty+/// (XKB then falls back to XKB_DEFAULT_LAYOUT or its built-in default).+/// The returned strings point into `cfg`.+pub fn split(cfg: anytype) List {+ var list: List = .{};+ if (std.mem.trim(u8, cfg.xkb_layout, " \t").len == 0) return list;+ var layouts = std.mem.splitScalar(u8, cfg.xkb_layout, ',');+ var variants = std.mem.splitScalar(u8, cfg.xkb_variant, ',');+ var labels = std.mem.splitScalar(u8, if (@hasField(@TypeOf(cfg), "xkb_labels")) cfg.xkb_labels else "", ',');+ while (layouts.next()) |raw| {+ const variant = std.mem.trim(u8, variants.next() orelse "", " \t");+ const label = std.mem.trim(u8, labels.next() orelse "", " \t");+ const layout = std.mem.trim(u8, raw, " \t");+ if (list.len == max_layouts) {+ list.dropped += 1;+ continue;+ }+ list.items[list.len] = .{ .layout = layout, .variant = variant, .label = if (label.len <= max_label_bytes) label else "" };+ list.len += 1;+ }+ return list;+}++pub const Joined = struct {+ layout: []u8,+ variant: []u8,+ labels: []u8,++ pub fn deinit(self: Joined, allocator: std.mem.Allocator) void {+ allocator.free(self.layout);+ allocator.free(self.variant);+ allocator.free(self.labels);+ }+};++/// The three config values for `layouts`. Variant and label lists collapse to+/// "" when every entry is empty, as people write them by hand.+pub fn join(allocator: std.mem.Allocator, layouts: []const Layout) !Joined {+ const layout = try joinField(allocator, layouts, "layout", false);+ errdefer allocator.free(layout);+ const variant = try joinField(allocator, layouts, "variant", true);+ errdefer allocator.free(variant);+ const labels = try joinField(allocator, layouts, "label", true);+ return .{ .layout = layout, .variant = variant, .labels = labels };+}++fn joinField(allocator: std.mem.Allocator, layouts: []const Layout, comptime field: []const u8, collapse: bool) ![]u8 {+ if (collapse) {+ var any = false;+ for (layouts) |l| any = any or @field(l, field).len > 0;+ if (!any) return allocator.dupe(u8, "");+ }+ var out: std.ArrayList(u8) = .empty;+ errdefer out.deinit(allocator);+ for (layouts, 0..) |l, i| {+ if (i > 0) try out.append(allocator, ',');+ try out.appendSlice(allocator, @field(l, field));+ }+ return out.toOwnedSlice(allocator);+}++/// A layout or variant name as XKB spells them; anything else would break the+/// comma lists or the rule lookup.+pub fn validName(name: []const u8) bool {+ if (name.len == 0 or name.len > 64) return false;+ for (name) |ch| switch (ch) {+ 'a'...'z', 'A'...'Z', '0'...'9', '_', '-', '+', '.' => {},+ else => return false,+ };+ return true;+}++/// An indicator label: short, and free of the list separator.+pub fn validLabel(label: []const u8) bool {+ if (label.len > max_label_bytes) return false;+ if (std.mem.indexOfAny(u8, label, ",\"\\\n\r\t") != null) return false;+ return std.unicode.utf8ValidateSlice(label);+}++test "layout lists split by position, cap at four and join back" {+ const cfg = .{ .xkb_layout = "us, de,jp", .xkb_variant = ",nodeadkeys", .xkb_labels = ",,JP" };+ const list = split(cfg);+ try std.testing.expectEqual(@as(usize, 3), list.len);+ try std.testing.expectEqualStrings("de", list.items[1].layout);+ try std.testing.expectEqualStrings("nodeadkeys", list.items[1].variant);+ try std.testing.expectEqualStrings("", list.items[2].variant);+ try std.testing.expectEqualStrings("JP", list.items[2].label);+ var buf: [64]u8 = undefined;+ try std.testing.expectEqualStrings("de(nodeadkeys)", list.items[1].format(&buf));++ const joined = try join(std.testing.allocator, list.slice());+ defer joined.deinit(std.testing.allocator);+ try std.testing.expectEqualStrings("us,de,jp", joined.layout);+ try std.testing.expectEqualStrings(",nodeadkeys,", joined.variant);+ try std.testing.expectEqualStrings(",,JP", joined.labels);++ const plain = try join(std.testing.allocator, &.{ .{ .layout = "us" }, .{ .layout = "ru" } });+ defer plain.deinit(std.testing.allocator);+ try std.testing.expectEqualStrings("", plain.variant);+ try std.testing.expectEqualStrings("", plain.labels);++ const many = split(.{ .xkb_layout = "us,de,fr,ru,jp", .xkb_variant = "" });+ try std.testing.expectEqual(@as(usize, 4), many.len);+ try std.testing.expectEqual(@as(usize, 1), many.dropped);+ try std.testing.expectEqual(@as(usize, 0), split(.{ .xkb_layout = " ", .xkb_variant = "" }).len);+}++test "names and labels are validated before they reach the comma lists" {+ try std.testing.expect(validName("de"));+ try std.testing.expect(validName("nodeadkeys"));+ try std.testing.expect(!validName("us,ru"));+ try std.testing.expect(!validName(""));+ try std.testing.expect(validLabel("あ"));+ try std.testing.expect(validLabel(""));+ try std.testing.expect(!validLabel("a,b"));+ try std.testing.expect(!validLabel("much too long for a chip"));+}diff --git a/src/config/keybinds.zig b/src/config/keybinds.zigindex 31dfd5d..ac3140e 100644--- a/src/config/keybinds.zig+++ b/src/config/keybinds.zig@@ -44,6 +44,9 @@ pub const Action = union(enum) {brightness_up,brightness_down,power_profile_cycle,+ /// The next or previous keyboard layout or input method (`input_sources.zig`).+ input_source_next,+ input_source_prev,spawn: []const u8,close_window,toggle_fullscreen,@@ -99,6 +102,12 @@ pub fn isHardwareAction(action: Action) bool {};}+/// Switching keyboard layouts also works on the lock screen (layouts only:+/// input methods never reach it), where passwords are typed.+pub fn worksWhileLocked(action: Action) bool {+ return isHardwareAction(action) or action == .input_source_next or action == .input_source_prev;+}+pub fn repeats(action: Action) bool {return switch (action) {.volume_up, .volume_down, .brightness_up, .brightness_down => true,diff --git a/src/config/keymap.zig b/src/config/keymap.zigindex a1eb16a..63eb327 100644--- a/src/config/keymap.zig+++ b/src/config/keymap.zig@@ -1,5 +1,6 @@const std = @import("std");const xkb = @import("xkbcommon");+const input_sources = @import("input_sources.zig");/// Empty names deliberately defer to XKB_DEFAULT_* and xkbcommon defaults.pub fn compile(allocator: std.mem.Allocator, cfg: anytype) !*xkb.Keymap {@@ -8,10 +9,20 @@ pub fn compile(allocator: std.mem.Allocator, cfg: anytype) !*xkb.Keymap {const a = arena.allocator();const context = xkb.Context.new(.no_flags) orelse return error.InvalidKeymap;defer context.unref();+ // X11, Xwayland and older clients know four groups; later layouts are dropped.+ var layout_names: []const u8 = cfg.xkb_layout;+ var variant_names: []const u8 = cfg.xkb_variant;+ const sources = input_sources.split(cfg);+ if (sources.dropped > 0) {+ std.log.scoped(.config).warn("only the first {d} keyboard layouts are used; {d} more ignored", .{ input_sources.max_layouts, sources.dropped });+ const joined = try input_sources.join(a, sources.slice());+ layout_names = joined.layout;+ variant_names = joined.variant;+ }const names = xkb.RuleNames{.rules = null,- .layout = try name(a, cfg.xkb_layout),- .variant = try name(a, cfg.xkb_variant),+ .layout = try name(a, layout_names),+ .variant = try name(a, variant_names),.options = try name(a, cfg.xkb_options),.model = try name(a, cfg.xkb_model),};diff --git a/src/config/loader.zig b/src/config/loader.zigindex e80a4a9..4006004 100644--- a/src/config/loader.zig+++ b/src/config/loader.zig@@ -93,6 +93,9 @@ pub const InputConfig = struct {xkb_variant: []const u8 = "",xkb_options: []const u8 = "",xkb_model: []const u8 = "",+ /// Optional indicator texts for the layouts above, by position+ /// (`input_sources.zig`); empty entries use the layout's language code.+ xkb_labels: []const u8 = "",natural_scroll: bool = true,// Compositor-side flip applied to every scroll axis event regardless of// device/backend support, unlike `natural_scroll` which only takesdiff --git a/src/config/loader_fields.zig b/src/config/loader_fields.zigindex 93a4416..6565a23 100644--- a/src/config/loader_fields.zig+++ b/src/config/loader_fields.zig@@ -53,6 +53,7 @@ pub const input_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(InputConfig).xkb_variant = .string,.xkb_options = .string,.xkb_model = .string,+ .xkb_labels = .string,.natural_scroll = .boolean,.invert_scroll = .boolean,.pointer_speed = .{ .float = .{ .min = -1, .max = 1 } },diff --git a/src/config/loader_parse.zig b/src/config/loader_parse.zigindex 5e77ebb..3ba5bcd 100644--- a/src/config/loader_parse.zig+++ b/src/config/loader_parse.zig@@ -249,13 +249,14 @@ const ParseState = struct {}if (state.seen_keybinds) {- // Keep laptop controls, System Monitor, nested-session switching and- // the way out of an inhibiting client available in existing configs too.+ // Keep laptop controls, System Monitor, nested-session switching, the+ // input source shortcut and the way out of an inhibiting client+ // available in existing configs too.// Explicit bindings (including noop) always take precedence.const defaults = try parseKeybindsOnly(cfg.arena.allocator(), default_file.source);for (defaults) |bind| {const nested_switcher = bind.modifiers.ctrl and (bind.action == .focus_next or bind.action == .focus_prev);- if (!keybinds.isHardwareAction(bind.action) and !nested_switcher and bind.action != .restore_shortcuts and bind.action != .open_system_monitor) continue;+ if (!keybinds.isHardwareAction(bind.action) and !nested_switcher and bind.action != .restore_shortcuts and bind.action != .open_system_monitor and bind.action != .input_source_next) continue;const key = keybinds.pack(bind.modifiers, bind.sym);var overridden = false;for (state.bind_list.items) |custom| {diff --git a/src/config/mod.zig b/src/config/mod.zigindex 12098f0..231d5e4 100644--- a/src/config/mod.zig+++ b/src/config/mod.zig@@ -4,6 +4,7 @@ pub const animations = @import("animations.zig");pub const app_theme = @import("app_theme.zig");pub const default = @import("default.zig");pub const input_device = @import("input_device.zig");+pub const input_sources = @import("input_sources.zig");pub const keybinds = @import("keybinds.zig");pub const keymap = @import("keymap.zig");pub const loader = @import("loader.zig");diff --git a/src/config/setting_save.zig b/src/config/setting_save.zigindex d60c431..64114a2 100644--- a/src/config/setting_save.zig+++ b/src/config/setting_save.zig@@ -166,6 +166,21 @@ pub fn saveCanvas(allocator: std.mem.Allocator, io: Io, path: []const u8, columntry writeValidated(allocator, io, path, result);}+/// The keyboard layout lists (`input_sources.zig`) in one write, so a reload+/// never sees a layout list paired with the previous variants.+pub fn saveInputSources(allocator: std.mem.Allocator, io: Io, path: []const u8, layout: []const u8, variant: []const u8, labels: []const u8) !void {+ if (path.len == 0) return error.NoConfigPath;+ const original = try Io.Dir.cwd().readFileAlloc(io, path, allocator, .limited(1 << 20));+ defer allocator.free(original);+ const with_layout = try patch(allocator, original, "input", "xkb_layout", layout);+ defer allocator.free(with_layout);+ const with_variant = try patch(allocator, with_layout, "input", "xkb_variant", variant);+ defer allocator.free(with_variant);+ const result = try patch(allocator, with_variant, "input", "xkb_labels", labels);+ defer allocator.free(result);+ try writeValidated(allocator, io, path, result);+}+pub fn writeValidated(allocator: std.mem.Allocator, io: Io, path: []const u8, result: []const u8) !void {var checked = try loader.parse(allocator, result, path);defer checked.deinit();diff --git a/src/config/taskbar_items.zig b/src/config/taskbar_items.zigindex 093b11a..b7aaaf0 100644--- a/src/config/taskbar_items.zig+++ b/src/config/taskbar_items.zig@@ -13,6 +13,7 @@ pub const Item = enum {power,capture,wired,+ input_source,pub fn label(item: Item) []const u8 {return switch (item) {@@ -26,13 +27,15 @@ pub const Item = enum {.power => "Power",.capture => "Screen capture",.wired => "Ethernet",+ .input_source => "Keyboard layout",};}- /// Only the network items can be automatic: shown while their hardware- /// (a wireless adapter, a connected cable) is there.+ /// The network items can be automatic: shown while their hardware (a+ /// wireless adapter, a connected cable) is there. The input source item+ /// shows while there is more than one source to switch between.pub fn canAutomate(item: Item) bool {- return item == .wifi or item == .wired;+ return item == .wifi or item == .wired or item == .input_source;}};pub const count = @typeInfo(Item).@"enum".field_names.len;@@ -41,15 +44,17 @@ pub const count = @typeInfo(Item).@"enum".field_names.len;pub const Presence = struct {wifi: bool = false,wired: bool = false,+ /// More than one keyboard layout or input method to switch between.+ input_sources: bool = false,};pub const Config = struct {- order: [count]Item = .{ .start, .windows, .capture, .tray, .battery, .wifi, .wired, .volume, .clock, .power },- visible: [count]bool = .{ true, true, true, true, true, true, true, false, true, true },- sections: [count]Section = .{ .right, .right, .right, .right, .left, .left, .right, .right, .right, .right },+ order: [count]Item = .{ .start, .windows, .capture, .tray, .battery, .wifi, .wired, .input_source, .volume, .clock, .power },+ visible: [count]bool = .{ true, true, true, true, true, true, true, false, true, true, true },+ sections: [count]Section = .{ .right, .right, .right, .right, .left, .left, .right, .right, .right, .right, .right },/// An automatic item follows `Presence` instead of `visible`. An explicit/// choice (a plain or `-` entry) clears it; it is written as `~`.- auto: [count]bool = .{ false, true, false, false, false, false, false, false, false, true },+ auto: [count]bool = .{ false, true, false, false, false, false, false, false, false, true, true },/// One keyboard step: swap with the neighbour in the same section, or at/// a section's end step into the next section over (an empty one too).@@ -115,6 +120,7 @@ pub const Config = struct {return switch (item) {.wifi => presence.wifi,.wired => presence.wired,+ .input_source => presence.input_sources,else => config.visible[id],};}@@ -174,15 +180,16 @@ pub const Config = struct {index += 1;}if (legacy and index == 4) {- result.order = .{ .start, .windows, .tray, order[0], order[1], order[2], order[3], .power, .capture, .wired };+ result.order = .{ .start, .windows, .tray, order[0], order[1], order[2], order[3], .power, .capture, .wired, .input_source };} else {- // Older lists can omit Power, Screen capture and Ethernet. Every- // other item remains required, so incomplete lists still fail closed.+ // Older lists can omit Power, Screen capture, Ethernet and the+ // keyboard layout. Every other item remains required, so incomplete+ // lists still fail closed.for (std.enums.values(Item)) |item| {- if (item != .power and item != .capture and item != .wired and !seen[@intFromEnum(item)]) return error.InvalidValue;+ if (!optional(item) and !seen[@intFromEnum(item)]) return error.InvalidValue;}@memcpy(result.order[0..index], order[0..index]);- for ([_]Item{ .power, .capture, .wired }) |item| {+ for ([_]Item{ .power, .capture, .wired, .input_source }) |item| {if (seen[@intFromEnum(item)]) continue;result.order[index] = item;index += 1;@@ -215,9 +222,32 @@ pub const Config = struct {}}}+ if (!seen[@intFromEnum(Item.input_source)]) {+ // The keyboard layout joins right before Volume, in its section,+ // automatic: one layout shows nothing new.+ const zone = result.section(.volume);+ var slot: usize = 0;+ for (result.order) |item| {+ if (item == .input_source) continue;+ if (item == .volume) break;+ if (result.section(item) == zone) slot += 1;+ }+ for (result.order, 0..) |item, i| {+ if (item == .input_source) {+ _ = result.place(i, zone, slot);+ break;+ }+ }+ result.visible[@intFromEnum(Item.input_source)] = true;+ result.auto[@intFromEnum(Item.input_source)] = true;+ }return result;}+ fn optional(item: Item) bool {+ return item == .power or item == .capture or item == .wired or item == .input_source;+ }+pub fn serialize(config: Config, allocator: std.mem.Allocator) ![]u8 {var buffer: std.Io.Writer.Allocating = .init(allocator);errdefer buffer.deinit();@@ -315,18 +345,34 @@ test "taskbar sections and hidden state round trip, migrate old lists and rejecttry std.testing.expect(!legacy.shown(.power));// Drops land anywhere; keyboard steps cross into the next section at an edge.var moved: Config = .{};- try std.testing.expectEqual(@as(usize, 1), moved.place(8, .left, 1));- try std.testing.expectEqualSlices(Item, &.{ .start, .clock, .windows, .capture, .tray, .battery, .wifi, .wired, .volume, .power }, &moved.order);+ try std.testing.expectEqual(@as(usize, 1), moved.place(9, .left, 1));+ try std.testing.expectEqualSlices(Item, &.{ .start, .clock, .windows, .capture, .tray, .battery, .wifi, .wired, .input_source, .volume, .power }, &moved.order);try std.testing.expectEqual(Section.left, moved.section(.clock));moved.move(2, true);try std.testing.expectEqual(Section.center, moved.section(.windows));- try std.testing.expectEqual(@as(usize, 9), moved.place(2, .right, 9));- try std.testing.expectEqual(Item.windows, moved.order[9]);+ try std.testing.expectEqual(@as(usize, 10), moved.place(2, .right, 10));+ try std.testing.expectEqual(Item.windows, moved.order[10]);for ([_][]const u8{ "[]", "[\"battery\", \"network\", \"volume\", \"volume\"]", "[\"battery\", \"network\", \"volume\", \"chevron\"]", "[\"left:battery\", \"network\", \"volume\", \"clock\"]", "[\"~battery\", \"network\", \"volume\", \"clock\"]" }) |bad| {try std.testing.expectError(error.InvalidValue, Config.parse(bad));}}+test "the keyboard layout item joins old lists before Volume and follows the source count" {+ const old = try Config.parse("[\"left:start\", \"left:windows\", \"right:tray\", \"right:battery\", \"~right:wifi\", \"~right:wired\", \"center:volume\", \"right:clock\"]");+ const at = std.mem.indexOfScalar(Item, &old.order, .input_source).?;+ try std.testing.expectEqual(Item.volume, old.order[at + 1]);+ try std.testing.expectEqual(Section.center, old.section(.input_source));+ try std.testing.expect(old.auto[@intFromEnum(Item.input_source)]);+ try std.testing.expect(!old.resolved(.input_source, .{}));+ try std.testing.expect(old.resolved(.input_source, .{ .input_sources = true }));+ var config: Config = .{};+ config.setVisible(.input_source, false);+ try std.testing.expect(!config.resolved(.input_source, .{ .input_sources = true }));+ const encoded = try config.serialize(std.testing.allocator);+ defer std.testing.allocator.free(encoded);+ try std.testing.expectEqualDeep(config, try Config.parse(encoded));+}+test "wifi and ethernet follow the hardware until the user decides" {var config: Config = .{};try std.testing.expect(!config.resolved(.wifi, .{}));@@ -356,7 +402,7 @@ test "wifi and ethernet follow the hardware until the user decides" {test "taskbar defaults windows left, supports centering and shrinks windows before fixed items" {var config: Config = .{};- const widths = [count]f32{ 0, 34, 34, 96, 42, 200, 0, 34, 120, 0 };+ const widths = [count]f32{ 0, 34, 34, 96, 42, 200, 0, 34, 120, 0, 0 };const defaults = arrange(config, 4, 980, 500, widths, 6, 16);try std.testing.expectEqual(@as(?f32, 52), defaults.x[@intFromEnum(Item.windows)]);try std.testing.expect(defaults.x[@intFromEnum(Item.capture)].? + 120 <= defaults.x[@intFromEnum(Item.wifi)].?);@@ -368,7 +414,7 @@ test "taskbar defaults windows left, supports centering and shrinks windows befoconfig.setSection(.wifi, .left);const moved = arrange(config, 4, 980, 500, widths, 6, 16);try std.testing.expectEqual(@as(?f32, 52), moved.x[@intFromEnum(Item.wifi)]);- const crowded = arrange(config, 4, 400, 200, .{ 0, 34, 34, 96, 42, 1000, 0, 34, 120, 0 }, 6, 16);+ const crowded = arrange(config, 4, 400, 200, .{ 0, 34, 34, 96, 42, 1000, 0, 34, 120, 0, 0 }, 6, 16);try std.testing.expect(crowded.widths[@intFromEnum(Item.windows)] < 1000);try std.testing.expect(crowded.x[@intFromEnum(Item.clock)].? + 96 <= crowded.x[@intFromEnum(Item.volume)].? - 16);config.visible = @splat(false);diff --git a/src/config_runtime/actions.zig b/src/config_runtime/actions.zigindex 28d5c1b..252aeca 100644--- a/src/config_runtime/actions.zig+++ b/src/config_runtime/actions.zig@@ -13,7 +13,10 @@ const log = std.log.scoped(.config);const gpa = @import("../main.zig").gpa;pub fn executeAction(server: *Server, action: Action) void {- if (server.locker != null and !keybinds.isHardwareAction(action)) return;+ if (server.locker != null and !keybinds.isHardwareAction(action)) {+ if (keybinds.worksWhileLocked(action)) if (server.input_sources) |sources| sources.cycleLayouts();+ return;+ }if (server.world.workspaces.active) switch (action) {.set_depth, .zoom_in, .zoom_out, .zoom_reset, .camera_zoom_in, .camera_zoom_out, .camera_zoom_reset, .pan_left, .pan_right, .pan_up, .pan_down => return,else => {},@@ -30,6 +33,8 @@ pub fn executeAction(server: *Server, action: Action) void {},.volume_up, .volume_down, .volume_mute, .mic_mute, .brightness_up, .brightness_down => @import("../hardware_keys.zig").execute(server, action),.power_profile_cycle => if (server.power_profiles) |pp| pp.cycle(),+ .input_source_next => if (server.input_sources) |sources| sources.cycle(true),+ .input_source_prev => if (server.input_sources) |sources| sources.cycle(false),.spawn => |cmd| launchPreferred(server, cmd),.close_window => if (focusedToplevel(server)) |t| t.sendClose(),.toggle_fullscreen => if (focusedToplevel(server)) |t| t.toggleFullscreen(),diff --git a/src/config_runtime/apply.zig b/src/config_runtime/apply.zigindex b346c2b..26f9bf8 100644--- a/src/config_runtime/apply.zig+++ b/src/config_runtime/apply.zig@@ -85,6 +85,9 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {}}}+ if (!@import("config").keymap.namesEqual(old.input, new.input) or !std.mem.eql(u8, old.input.xkb_labels, new.input.xkb_labels)) {+ if (server.input_sources) |sources| sources.reload();+ }if (old.compositor.canvas_columns != new.compositor.canvas_columns orold.compositor.canvas_rows != new.compositor.canvas_rows)diff --git a/src/control_center/ControlCenter.zig b/src/control_center/ControlCenter.zigindex 3126e91..f9fc2a5 100644--- a/src/control_center/ControlCenter.zig+++ b/src/control_center/ControlCenter.zig@@ -148,6 +148,7 @@ region: region_section.Section = .{},portals: portal_section.Section = .{},default_apps: default_apps_section.Section = .{},input: input_section.Section = .{},+input_sources: @import("sections/input_sources.zig").Section = .{},users: users_section.Section = .{},network: network_section.Section = .{},bluetooth: bluetooth_section.Section = .{},@@ -249,6 +250,7 @@ pub fn destroy(cc: *ControlCenter) void {cc.welcome.deinit();cc.search.deinit();cc.input.arena.deinit();+ cc.input_sources.deinit();cc.services.deinit();cc.printers.deinit();cc.key_settings.deinit();diff --git a/src/control_center/search_index.zig b/src/control_center/search_index.zigindex da29f4c..36cad80 100644--- a/src/control_center/search_index.zig+++ b/src/control_center/search_index.zig@@ -51,6 +51,8 @@ const source_entries = [_]SourceEntry{.{ .page = .general, .title = i18n.msg("Brightness"), .target = "@Brightness", .heading = i18n.msg("Brightness"), .keywords = i18n.msg("backlight screen light") },.{ .page = .general, .title = i18n.msg("Open files with a single click"), .target = "files_single_click_open", .keywords = i18n.msg("double click folders") },.{ .page = .general, .title = i18n.msg("Built-in audio player"), .target = "files_audio_player", .keywords = i18n.msg("music play sound mp3 flac wav files") },+ .{ .page = .input, .title = i18n.msg("Input sources"), .target = "input_sources", .keywords = i18n.msg("keyboard layout language input method ime fcitx switch") },+ .{ .page = .input, .title = i18n.msg("Layout switch keys"), .target = "input_source_switch_with", .keywords = i18n.msg("keyboard layout alt shift caps lock toggle") },.{ .page = .input, .title = i18n.msg("Pointer device"), .target = "pointer_device", .keywords = i18n.msg("mouse touchpad trackpad select") },.{ .page = .input, .title = i18n.msg("Show all devices"), .target = "pointer_show_all", .keywords = i18n.msg("mouse touchpad trackpad select") },.{ .page = .input, .title = i18n.msg("Reset pointer settings"), .target = "pointer_reset", .keywords = i18n.msg("mouse touchpad trackball default custom inherit") },diff --git a/src/control_center/sections/input.zig b/src/control_center/sections/input.zigindex b539f16..10c65bf 100644--- a/src/control_center/sections/input.zig+++ b/src/control_center/sections/input.zig@@ -26,44 +26,13 @@ const pan_speed_values = [4]f32{ 1, 2, 3, 4 };const pan_speed_labels = [_][]const u8{ "1x", "2x", "3x", "4x" };const pan_speed_segmented_width: f32 = 180;-const KeyboardLayout = struct { label: []const u8, layout: []const u8, variant: []const u8 = "" };--// Layout names are shown in their own language, so they are not translated.-const keyboard_layouts = [_]KeyboardLayout{- .{ .label = "English (US, QWERTY)", .layout = "us" }, // i18n: raw- .{ .label = "Français (AZERTY)", .layout = "fr" }, // i18n: raw- .{ .label = "Français (BÉPO)", .layout = "fr", .variant = "bepo" }, // i18n: raw- .{ .label = "Belge (AZERTY)", .layout = "be" }, // i18n: raw- .{ .label = "Suisse romand (QWERTZ)", .layout = "ch", .variant = "fr" }, // i18n: raw- .{ .label = "Canadien multilingue", .layout = "ca", .variant = "multix" }, // i18n: raw- .{ .label = "Deutsch (QWERTZ)", .layout = "de" }, // i18n: raw- .{ .label = "Español", .layout = "es" }, // i18n: raw- .{ .label = "Italiano", .layout = "it" }, // i18n: raw- .{ .label = "Português", .layout = "pt" }, // i18n: raw- .{ .label = "English (UK)", .layout = "gb" }, // i18n: raw- .{ .label = "English (Dvorak)", .layout = "us", .variant = "dvorak" }, // i18n: raw- .{ .label = "Русский", .layout = "ru" }, // i18n: raw-};--const keyboard_layout_labels = blk: {- var out: [keyboard_layouts.len][]const u8 = undefined;- for (keyboard_layouts, 0..) |l, i| out[i] = l.label;- const final = out;- break :blk final;-};--fn keyboardLayoutIndex(cfg: anytype) ?usize {- for (keyboard_layouts, 0..) |l, i| {- if (std.mem.eql(u8, l.layout, cfg.xkb_layout) and std.mem.eql(u8, l.variant, cfg.xkb_variant)) return i;- }- return null;-}-pub const Section = struct {root: Widget = undefined,top_children: [2]Widget = undefined,row_storage: [7]Widget = undefined,row_count: usize = 0,+ /// The first keyboard row: Settings puts the Input Sources card before it.+ keyboard_row: usize = 0,selector_children: [4]Widget = undefined,selector_header_children: [2]Widget = undefined,speed_group_children: [2]Widget = undefined,@@ -73,7 +42,6 @@ pub const Section = struct {bool_row_children: [bool_keys.len][2]Widget = undefined,bool_label_children: [bool_keys.len][2]Widget = undefined,speed_value_buf: [16]u8 = undefined,- layout_row_children: [2]Widget = undefined,pan_speed_row_children: [2]Widget = undefined,delay_row_children: [2]Widget = undefined,rate_row_children: [2]Widget = undefined,@@ -514,17 +482,7 @@ pub fn build(out: *Section, input: *Input) void {const pan_speed_row: Widget = .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.pan_speed_row_children };layout.appendRow(&out.row_storage, &row_count, pan_speed_row);- out.layout_row_children = .{- fgLabel(i18n.tr("Keyboard layout")),- .{- .name = "keyboard_layout",- .kind = .{ .select = .{ .labels = &keyboard_layout_labels, .selected = keyboardLayoutIndex(input.server.config.input), .placeholder = i18n.tr("Custom (config file)"), .owner = out, .on_change = &onKeyboardLayoutPicked } },- .width = .{ .fixed = 220 },- },- };- const layout_row: Widget = .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.layout_row_children };- layout.appendRow(&out.row_storage, &row_count, layout_row);-+ out.keyboard_row = row_count;out.delay_row_children = .{fgLabel(i18n.tr("Repeat delay")),.{ .name = "repeat_delay", .kind = .{ .stepper = .{ .value = repeat.delay, .min = 100, .max = 2000, .step = default_delay_step, .unit = "ms", .owner = out, .on_change = &onRepeatDelayChanged } } },@@ -548,24 +506,6 @@ pub fn build(out: *Section, input: *Input) void {out.root = .{ .name = "input", .kind = .container, .direction = .column, .gap = 8, .children = &out.top_children };}-// Only the file is written here: the reload diffs it against the live config-// and recompiles the keymap on every keyboard (`config_runtime/apply.zig`).-fn onKeyboardLayoutPicked(owner: ?*anyopaque, _: usize, index: usize) void {- const s: *Section = @ptrCast(@alignCast(owner orelse return));- if (index >= keyboard_layouts.len) return;- const server = s.input.server;- const choice = keyboard_layouts[index];- const save = @import("config").setting_save;- save.saveInput(@import("../../main.zig").gpa, server.io, server.config.path, "xkb_layout", choice.layout) catch |err| {- std.log.warn("could not save keyboard layout: {}", .{err});- return;- };- save.saveInput(@import("../../main.zig").gpa, server.io, server.config.path, "xkb_variant", choice.variant) catch |err| {- std.log.warn("could not save keyboard variant: {}", .{err});- };- @import("../../config_runtime/watcher.zig").reloadConfig(server);-}-fn onPanSpeedChanged(owner: ?*anyopaque, _: usize, index: usize) void {const s: *Section = @ptrCast(@alignCast(owner orelse return));persist(s, "pan_speed", pan_speed_values[index]);diff --git a/src/control_center/sections/input_sources.zig b/src/control_center/sections/input_sources.zignew file mode 100644index 0000000..30c07e8--- /dev/null+++ b/src/control_center/sections/input_sources.zig@@ -0,0 +1,511 @@+//! Settings → Input → Input Sources: the keyboard layouts (add, remove,+//! reorder; at most four, XKB's group limit), Fcitx's input methods read-only,+//! how to switch and whether the taskbar shows the indicator. Layouts are+//! written to `xkb_layout`/`xkb_variant`/`xkb_labels` in one save and applied+//! by the config reload (`input_sources.zig`).+const std = @import("std");+const i18n = @import("i18n");+const tr = i18n.tr;+const ui = @import("ui");+const W = ui.layout.Widget;+const config = @import("config");+const config_sources = config.input_sources;+const taskbar_items = config.taskbar_items;+const panel = @import("../panel.zig");+const gpa = @import("../../main.zig").gpa;++const max_results = 40;++/// When the XKB registry is missing: common layouts, named in their own language.+const fallback = [_]struct { layout: []const u8, variant: []const u8 = "", name: []const u8 }{+ .{ .layout = "us", .name = "English (US)" }, // i18n: raw+ .{ .layout = "gb", .name = "English (UK)" }, // i18n: raw+ .{ .layout = "us", .variant = "dvorak", .name = "English (Dvorak)" }, // i18n: raw+ .{ .layout = "de", .name = "Deutsch" }, // i18n: raw+ .{ .layout = "fr", .name = "Français (AZERTY)" }, // i18n: raw+ .{ .layout = "fr", .variant = "bepo", .name = "Français (BÉPO)" }, // i18n: raw+ .{ .layout = "be", .name = "Belge" }, // i18n: raw+ .{ .layout = "ch", .variant = "fr", .name = "Suisse romand" }, // i18n: raw+ .{ .layout = "ca", .variant = "multix", .name = "Canadien multilingue" }, // i18n: raw+ .{ .layout = "es", .name = "Español" }, // i18n: raw+ .{ .layout = "it", .name = "Italiano" }, // i18n: raw+ .{ .layout = "pt", .name = "Português" }, // i18n: raw+ .{ .layout = "br", .name = "Português (Brasil)" }, // i18n: raw+ .{ .layout = "ru", .name = "Русский" }, // i18n: raw+ .{ .layout = "ua", .name = "Українська" }, // i18n: raw+ .{ .layout = "jp", .name = "日本語" }, // i18n: raw+ .{ .layout = "kr", .name = "한국어" }, // i18n: raw+ .{ .layout = "cn", .name = "中文" }, // i18n: raw+};++/// XKB's own layout switch keys, kept in `xkb_options`.+const switch_options = [_]struct { option: []const u8, label: i18n.Message }{+ .{ .option = "", .label = i18n.msg("Only the shortcut (Super+Shift+Space)") },+ .{ .option = "grp:alt_shift_toggle", .label = i18n.msg("Alt+Shift") },+ .{ .option = "grp:ctrl_shift_toggle", .label = i18n.msg("Ctrl+Shift") },+ .{ .option = "grp:caps_toggle", .label = i18n.msg("Caps Lock") },+ .{ .option = "grp:shifts_toggle", .label = i18n.msg("Both Shift keys") },+};++const show_labels = [_]i18n.Message{ i18n.msg("Automatic"), i18n.msg("Always"), i18n.msg("Never") };++const Result = struct { layout: []const u8, variant: []const u8 };++pub const Section = struct {+ arena: std.heap.ArenaAllocator = .init(gpa),+ root: W = undefined,+ picker_open: bool = false,+ search: ?*W = null,+ search_focus: bool = false,+ results: []Result = &.{},+ message: []const u8 = "",++ /// Before a rebuild. A picker that just opened has no field yet and keeps+ /// its request for focus.+ pub fn capture(s: *Section) void {+ if (s.search) |field| s.search_focus = ui.input.current.focused == field;+ }++ pub fn deinit(s: *Section) void {+ if (s.search) |w| gpa.free(w.kind.text_input.value);+ s.search = null;+ s.arena.deinit();+ }+};++fn owner(ctx: ?*anyopaque) *panel.ControlCenter {+ return @ptrCast(@alignCast(ctx.?));+}++fn text(value: []const u8, size: f32, dim: bool) W {+ return panel.label(value, size, dim);+}++fn row(a: std.mem.Allocator, items: []const W) !W {+ return .{ .kind = .container, .direction = .row, .gap = 10, .@"align" = .center, .width = .{ .percent = 1 }, .children = try a.dupe(W, items) };+}++fn column(a: std.mem.Allocator, items: []const W, gap: f32) !W {+ return .{ .kind = .container, .direction = .column, .gap = gap, .@"align" = .stretch, .width = .{ .percent = 1 }, .children = try a.dupe(W, items) };+}++fn card(a: std.mem.Allocator, items: []const W) !W {+ var result = try column(a, items, 12);+ result.name = "input_sources";+ const t = ui.theme.global;+ result.kind = .{ .rect = .{ .color = t.app_item, .radius = t.settings_card_radius, .border_width = 1, .border_color = t.app_item_border, .relief = t.settings_card_relief } };+ result.padding = ui.layout.Edges.all(16);+ return result;+}++fn badge(a: std.mem.Allocator, value: []const u8) !W {+ const t = panel.palette();+ var label = text(value, 12, false);+ label.kind.text.weight = 700;+ const width: f32 = 44;+ const ink = ui.measure.textNatural(value, .sans, 700, 12).w;+ return .{+ .kind = .{ .rect = .{ .color = t.surface_hover, .radius = 6 } },+ .direction = .row,+ .@"align" = .center,+ .width = .{ .fixed = width },+ .height = .{ .fixed = 26 },+ .padding = .{ .left = @max(0, @floor((width - ink) / 2)) },+ .children = try a.dupe(W, &.{label}),+ };+}++fn iconButton(cc: *panel.ControlCenter, name: []const u8, label: []const u8, icon: ui.layout.IconId, id: usize, enabled: bool, callback: *const fn (?*anyopaque, usize) void) W {+ return .{ .name = name, .kind = .{ .button = .{ .label = label, .icon = icon, .owner = cc, .id = id, .on_click = callback, .state = if (enabled) .idle else .disabled } }, .width = .{ .fixed = 32 }, .height = .{ .fixed = 32 } };+}++pub fn build(s: *Section, cc: *panel.ControlCenter) void {+ const saved = if (s.search) |w| w.kind.text_input else null;+ _ = s.arena.reset(.retain_capacity);+ s.search = null;+ s.results = &.{};+ const manager = cc.server.input_sources orelse {+ if (saved) |field| gpa.free(field.value);+ s.root = text(tr("Input sources are unavailable."), 13, true);+ return;+ };+ if (s.picker_open) manager.wantCatalog();+ s.root = tree(s, cc, manager, s.arena.allocator(), saved) catch blk: {+ s.search_focus = false;+ break :blk panel.outOfMemory();+ };+ // A field that took the text over owns it; otherwise it is dropped here.+ if (s.search == null) if (saved) |field| gpa.free(field.value);+}++fn tree(s: *Section, cc: *panel.ControlCenter, manager: anytype, a: std.mem.Allocator, saved: ?ui.layout.TextInputData) !W {+ var items: std.ArrayList(W) = .empty;+ try items.append(a, panel.sectionTitle(tr("Input Sources")));+ try items.append(a, try panel.paragraph(a, tr("The taskbar shows the active source. Click it, or press Super+Shift+Space, to switch."), contentWidth(cc), 12, true));++ const layouts = manager.configuredLayouts();+ const sources = manager.sources();+ const active = manager.activeIndex();+ for (layouts, 0..) |layout, i| {+ const label = if (i < sources.len) sources[i].label else layout.layout;+ const name = if (i < sources.len) sources[i].name else layout.layout;+ var id_buf: [160]u8 = undefined;+ var info = try column(a, &.{ text(name, 13, false), idText(try a.dupe(u8, layout.format(&id_buf))) }, 2);+ info.width = .{ .flex = 1 };+ var line = try row(a, &.{+ try badge(a, label),+ info,+ iconButton(cc, try std.fmt.allocPrint(a, "input_source_up_{d}", .{i}), tr("Move up"), .chevron_up, i, i > 0, moveUp),+ iconButton(cc, try std.fmt.allocPrint(a, "input_source_down_{d}", .{i}), tr("Move down"), .chevron_down, i, i + 1 < layouts.len, moveDown),+ iconButton(cc, try std.fmt.allocPrint(a, "input_source_remove_{d}", .{i}), tr("Remove"), .close, i, layouts.len > 1, remove),+ });+ line.name = try std.fmt.allocPrint(a, "input_source_{d}", .{i});+ if (active == i) line.children[0].kind.rect.color = panel.palette().accent;+ if (active == i) line.children[0].children[0].kind.text.color = panel.palette().on_accent;+ try items.append(a, line);+ }++ if (layouts.len < config_sources.max_layouts) {+ const add: W = .{ .name = "input_source_add", .kind = .{ .button = .{ .label = if (s.picker_open) tr("Close") else tr("Add layout…"), .leading_icon = if (s.picker_open) null else .plus, .owner = cc, .on_click = togglePicker } }, .height = .{ .fixed = 34 } };+ try items.append(a, try row(a, &.{add}));+ if (s.picker_open) try items.append(a, try picker(s, cc, manager, a, saved, layouts));+ } else {+ try items.append(a, text(tr("Four keyboard layouts is the most XKB allows."), 12, true));+ }+ if (s.message.len > 0) try items.append(a, text(s.message, 12, true));++ if (cc.server.config.input_method.env == .fcitx or manager.fcitxRunning()) try items.append(a, try fcitxBlock(cc, manager, a, sources));+ try items.append(a, try options(cc, a));+ return card(a, items.items);+}++fn contentWidth(cc: *panel.ControlCenter) f32 {+ return @as(f32, @floatFromInt(cc.panel_box.width)) - panel.sidebarWidth(cc) - 100;+}++fn picker(s: *Section, cc: *panel.ControlCenter, manager: anytype, a: std.mem.Allocator, saved: ?ui.layout.TextInputData, layouts: []const config_sources.Layout) !W {+ const field = try a.create(W);+ field.* = .{+ .name = "input_source_search",+ .kind = .{ .text_input = saved orelse .{ .field = .{ .leading_icon = .search }, .placeholder = tr("Search layouts or languages…"), .value = try gpa.dupe(u8, ""), .owner = cc, .on_change = searchChanged } },+ .height = .{ .fixed = 36 },+ .width = .{ .percent = 1 },+ };+ s.search = field;+ const query = std.mem.trim(u8, field.kind.text_input.value, " ");+ var children: std.ArrayList(W) = .empty;+ try children.append(a, field.*);+ var results: std.ArrayList(Result) = .empty;+ var rows: std.ArrayList(W) = .empty;+ var total: usize = 0;+ switch (manager.catalogState()) {+ .loading => try children.append(a, text(tr("Loading layouts…"), 12, true)),+ .ready => for (manager.catalog.?.entries) |entry| {+ if (configured(layouts, entry.layout, entry.variant)) continue;+ var id_buf: [160]u8 = undefined;+ const spelled = (config_sources.Layout{ .layout = entry.layout, .variant = entry.variant }).format(&id_buf);+ if (!matches(query, &.{ entry.description, entry.layout, entry.variant, entry.brief, entry.languages, spelled })) continue;+ total += 1;+ if (results.items.len >= max_results) continue;+ try rows.append(a, try resultRow(cc, a, results.items.len, entry.description, try a.dupe(u8, spelled)));+ try results.append(a, .{ .layout = entry.layout, .variant = entry.variant });+ },+ .unavailable => for (fallback) |entry| {+ if (configured(layouts, entry.layout, entry.variant)) continue;+ if (!matches(query, &.{ entry.name, entry.layout, entry.variant })) continue;+ total += 1;+ var id_buf: [160]u8 = undefined;+ const spelled = (config_sources.Layout{ .layout = entry.layout, .variant = entry.variant }).format(&id_buf);+ try rows.append(a, try resultRow(cc, a, results.items.len, entry.name, try a.dupe(u8, spelled)));+ try results.append(a, .{ .layout = entry.layout, .variant = entry.variant });+ },+ }+ s.results = results.items;+ if (manager.catalogState() != .loading) {+ if (rows.items.len == 0) try children.append(a, text(tr("No layouts match."), 12, true));+ try children.append(a, try column(a, rows.items, 2));+ if (total > rows.items.len) try children.append(a, text(try i18n.allocPrint(a, tr("{shown} of {total} layouts; type to narrow the list."), .{ .shown = rows.items.len, .total = total }), 11, true));+ }+ return column(a, children.items, 8);+}++fn resultRow(cc: *panel.ControlCenter, a: std.mem.Allocator, index: usize, name: []const u8, spelled: []const u8) !W {+ var label = text(name, 13, false);+ label.width = .{ .flex = 1 };+ return .{+ .name = try std.fmt.allocPrint(a, "input_source_result_{d}", .{index}),+ .kind = .{ .row = .{ .owner = cc, .id = index, .on_click = addResult } },+ .direction = .row,+ .@"align" = .center,+ .gap = 10,+ .width = .{ .percent = 1 },+ .height = .{ .fixed = 34 },+ .padding = ui.layout.Edges.xy(10, 0),+ .children = try a.dupe(W, &.{ label, idText(spelled) }),+ };+}++/// A layout's XKB spelling at its own measured width, so a fractional scale+/// never ellipsizes it.+fn idText(spelled: []const u8) W {+ var id = text(spelled, 11, true);+ id.width = .{ .fixed = @ceil(ui.measure.textNatural(spelled, .sans, 400, 11).w) + 8 };+ return id;+}++fn configured(layouts: []const config_sources.Layout, layout: []const u8, variant: []const u8) bool {+ for (layouts) |l| if (l.eql(.{ .layout = layout, .variant = variant })) return true;+ return false;+}++/// Every word of the query appears in one of the fields (case-insensitive).+fn matches(query: []const u8, fields: []const []const u8) bool {+ var words = std.mem.tokenizeScalar(u8, query, ' ');+ while (words.next()) |word| {+ var found = false;+ for (fields) |field| if (containsIgnoreCase(field, word)) {+ found = true;+ break;+ };+ if (!found) return false;+ }+ return true;+}++fn containsIgnoreCase(haystack: []const u8, needle: []const u8) bool {+ if (needle.len > haystack.len) return false;+ for (0..haystack.len - needle.len + 1) |i| {+ if (std.ascii.eqlIgnoreCase(haystack[i..][0..needle.len], needle)) return true;+ }+ return false;+}++fn fcitxBlock(cc: *panel.ControlCenter, manager: anytype, a: std.mem.Allocator, sources: anytype) !W {+ var items: std.ArrayList(W) = .empty;+ try items.append(a, text(tr("Input methods (Fcitx 5)"), 13, false));+ if (!manager.fcitxRunning()) {+ try items.append(a, text(tr("Fcitx 5 is not running. Its input methods appear here while it runs."), 12, true));+ } else {+ var any = false;+ for (sources, 0..) |source, i| {+ if (source.kind != .fcitx) continue;+ any = true;+ var name = text(source.name, 13, false);+ name.width = .{ .flex = 1 };+ var line = try row(a, &.{ try badge(a, source.label), name });+ line.name = try std.fmt.allocPrint(a, "input_method_{d}", .{i});+ try items.append(a, line);+ }+ if (!any) try items.append(a, text(tr("Fcitx's current group has no input methods besides keyboards."), 12, true));+ }+ try items.append(a, text(tr("Fcitx manages its own list; RediWM only switches between its methods."), 11, true));+ const tool = config.app_theme.executable(a, cc.server.io, cc.server.environ, "fcitx5-configtool") catch null;+ if (tool != null) try items.append(a, try row(a, &.{.{ .name = "fcitx_configure", .kind = .{ .button = .{ .label = tr("Configure in Fcitx…"), .owner = cc, .on_click = configureFcitx } }, .height = .{ .fixed = 34 } }}));+ return column(a, items.items, 8);+}++fn options(cc: *panel.ControlCenter, a: std.mem.Allocator) !W {+ const group = groupOption(cc.server.config.input.xkb_options);+ var labels: std.ArrayList([]const u8) = .empty;+ var selected: ?usize = null;+ for (switch_options, 0..) |choice, i| {+ try labels.append(a, choice.label.get());+ if (std.mem.eql(u8, choice.option, group)) selected = i;+ }+ if (selected == null) {+ try labels.append(a, try i18n.allocPrint(a, tr("Custom ({option})"), .{ .option = group }));+ selected = labels.items.len - 1;+ }+ var switch_label = text(tr("Also switch with"), 13, false);+ switch_label.width = .{ .flex = 1 };+ const switch_row = try row(a, &.{+ switch_label,+ .{ .name = "input_source_switch_with", .kind = .{ .select = .{ .labels = labels.items, .selected = selected, .owner = cc, .on_change = switchWithChanged } }, .width = .{ .fixed = 260 } },+ });+ const items = cc.server.config.compositor.taskbar_items;+ const id = @backingInt(taskbar_items.Item.input_source);+ const show: usize = if (items.auto[id]) 0 else if (items.visible[id]) 1 else 2;+ var show_label = text(tr("Show in taskbar"), 13, false);+ show_label.width = .{ .flex = 1 };+ const show_row = try row(a, &.{+ show_label,+ .{ .name = "input_source_show", .kind = .{ .select = .{ .labels = panel.translatedLabels(&show_labels), .selected = show, .owner = cc, .on_change = showChanged } }, .width = .{ .fixed = 260 } },+ });+ return column(a, &.{ switch_row, text(tr("XKB switch keys change keyboard layouts only."), 11, true), show_row, text(tr("Automatic shows it while there is more than one source."), 11, true) }, 8);+}++/// The first `grp:` entry of an `xkb_options` list, or "".+fn groupOption(xkb_options: []const u8) []const u8 {+ var it = std.mem.splitScalar(u8, xkb_options, ',');+ while (it.next()) |raw| {+ const option = std.mem.trim(u8, raw, " ");+ if (std.mem.startsWith(u8, option, "grp:")) return option;+ }+ return "";+}++/// `xkb_options` with its `grp:` entries replaced by `option` (or dropped).+fn withGroupOption(a: std.mem.Allocator, xkb_options: []const u8, option: []const u8) ![]const u8 {+ var out: std.ArrayList(u8) = .empty;+ var it = std.mem.splitScalar(u8, xkb_options, ',');+ while (it.next()) |raw| {+ const entry = std.mem.trim(u8, raw, " ");+ if (entry.len == 0 or std.mem.startsWith(u8, entry, "grp:")) continue;+ if (out.items.len > 0) try out.append(a, ',');+ try out.appendSlice(a, entry);+ }+ if (option.len > 0) {+ if (out.items.len > 0) try out.append(a, ',');+ try out.appendSlice(a, option);+ }+ return out.items;+}++// ---- actions ------------------------------------------------------------++fn save(cc: *panel.ControlCenter, layouts: []const config_sources.Layout) void {+ const joined = config_sources.join(gpa, layouts) catch return;+ defer joined.deinit(gpa);+ config.setting_save.saveInputSources(gpa, cc.server.io, cc.server.config.path, joined.layout, joined.variant, joined.labels) catch |err| {+ std.log.warn("could not save keyboard layouts: {}", .{err});+ cc.input_sources.message = tr("Could not save. Check the configuration file and try again.");+ cc.refresh();+ return;+ };+ cc.input_sources.message = "";+ @import("../../config_runtime/watcher.zig").reloadConfig(cc.server);+ cc.refresh();+}++/// A copy of the layouts, so a reload during the save can't pull them away.+fn current(cc: *panel.ControlCenter, buf: *[config_sources.max_layouts + 1]config_sources.Layout, storage: *[config_sources.max_layouts + 1][3][64]u8) []config_sources.Layout {+ const manager = cc.server.input_sources orelse return buf[0..0];+ const layouts = manager.configuredLayouts();+ for (layouts, 0..) |layout, i| {+ buf[i] = .{ .layout = copy(&storage[i][0], layout.layout), .variant = copy(&storage[i][1], layout.variant), .label = copy(&storage[i][2], layout.label) };+ }+ return buf[0..layouts.len];+}++fn copy(dest: *[64]u8, value: []const u8) []const u8 {+ const n = @min(value.len, dest.len);+ @memcpy(dest[0..n], value[0..n]);+ return dest[0..n];+}++fn moveUp(ctx: ?*anyopaque, index: usize) void {+ move(owner(ctx), index, false);+}++fn moveDown(ctx: ?*anyopaque, index: usize) void {+ move(owner(ctx), index, true);+}++fn move(cc: *panel.ControlCenter, index: usize, down: bool) void {+ var buf: [config_sources.max_layouts + 1]config_sources.Layout = undefined;+ var storage: [config_sources.max_layouts + 1][3][64]u8 = undefined;+ const layouts = current(cc, &buf, &storage);+ const other = if (down) index + 1 else index -% 1;+ if (index >= layouts.len or other >= layouts.len) return;+ std.mem.swap(config_sources.Layout, &layouts[index], &layouts[other]);+ save(cc, layouts);+}++fn remove(ctx: ?*anyopaque, index: usize) void {+ const cc = owner(ctx);+ var buf: [config_sources.max_layouts + 1]config_sources.Layout = undefined;+ var storage: [config_sources.max_layouts + 1][3][64]u8 = undefined;+ const layouts = current(cc, &buf, &storage);+ if (index >= layouts.len or layouts.len < 2) return;+ var kept: [config_sources.max_layouts]config_sources.Layout = undefined;+ var n: usize = 0;+ for (layouts, 0..) |layout, i| if (i != index) {+ kept[n] = layout;+ n += 1;+ };+ save(cc, kept[0..n]);+}++fn addResult(ctx: ?*anyopaque, index: usize) void {+ const cc = owner(ctx);+ const s = &cc.input_sources;+ if (index >= s.results.len) return;+ var result_storage: [2][64]u8 = undefined;+ const chosen: config_sources.Layout = .{ .layout = copy(&result_storage[0], s.results[index].layout), .variant = copy(&result_storage[1], s.results[index].variant) };+ if (!config_sources.validName(chosen.layout) or (chosen.variant.len > 0 and !config_sources.validName(chosen.variant))) return;+ var buf: [config_sources.max_layouts + 1]config_sources.Layout = undefined;+ var storage: [config_sources.max_layouts + 1][3][64]u8 = undefined;+ const layouts = current(cc, &buf, &storage);+ if (layouts.len >= config_sources.max_layouts) return;+ buf[layouts.len] = chosen;+ // The rebuild frees the search text; this tree still shows it.+ s.picker_open = false;+ save(cc, buf[0 .. layouts.len + 1]);+}++fn togglePicker(ctx: ?*anyopaque, _: usize) void {+ const cc = owner(ctx);+ const s = &cc.input_sources;+ s.picker_open = !s.picker_open;+ s.search_focus = s.picker_open;+ cc.refresh();+}++fn searchChanged(ctx: ?*anyopaque, _: usize, _: []const u8) void {+ owner(ctx).refresh();+}++fn configureFcitx(ctx: ?*anyopaque, _: usize) void {+ const cc = owner(ctx);+ @import("../../config_runtime/actions.zig").executeAction(cc.server, .{ .spawn = "fcitx5-configtool" });+}++fn switchWithChanged(ctx: ?*anyopaque, _: usize, index: usize) void {+ const cc = owner(ctx);+ if (index >= switch_options.len) return;+ var arena: std.heap.ArenaAllocator = .init(gpa);+ defer arena.deinit();+ const value = withGroupOption(arena.allocator(), cc.server.config.input.xkb_options, switch_options[index].option) catch return;+ config.setting_save.saveInput(gpa, cc.server.io, cc.server.config.path, "xkb_options", value) catch |err| {+ std.log.warn("could not save the layout switch keys: {}", .{err});+ return;+ };+ @import("../../config_runtime/watcher.zig").reloadConfig(cc.server);+ cc.refresh();+}++fn showChanged(ctx: ?*anyopaque, _: usize, index: usize) void {+ const cc = owner(ctx);+ var items = cc.server.config.compositor.taskbar_items;+ const id = @backingInt(taskbar_items.Item.input_source);+ switch (index) {+ 0 => {+ items.visible[id] = true;+ items.auto[id] = true;+ },+ 1 => items.setVisible(.input_source, true),+ 2 => items.setVisible(.input_source, false),+ else => return,+ }+ config.setting_save.saveCompositor(gpa, cc.server.io, cc.server.config.path, "taskbar_items", items) catch |err| {+ std.log.warn("could not save taskbar items: {}", .{err});+ return;+ };+ cc.server.config.compositor.taskbar_items = items;+ cc.server.refreshTaskbarsGeometry();+ cc.refresh();+}++test "group options are replaced without touching other XKB options" {+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ try std.testing.expectEqualStrings("grp:caps_toggle", groupOption("ctrl:nocaps, grp:caps_toggle"));+ try std.testing.expectEqualStrings("", groupOption("ctrl:nocaps"));+ try std.testing.expectEqualStrings("ctrl:nocaps,grp:alt_shift_toggle", try withGroupOption(a, "ctrl:nocaps,grp:caps_toggle", "grp:alt_shift_toggle"));+ try std.testing.expectEqualStrings("ctrl:nocaps", try withGroupOption(a, "grp:caps_toggle,ctrl:nocaps", ""));+ try std.testing.expectEqualStrings("grp:shifts_toggle", try withGroupOption(a, "", "grp:shifts_toggle"));+ try std.testing.expect(matches("ger nodead", &.{ "German (no dead keys)", "de", "nodeadkeys" }));+ try std.testing.expect(matches("jpn", &.{ "Japanese", "jp", "", "ja", "jpn" }));+ try std.testing.expect(!matches("french", &.{ "German", "de" }));+}diff --git a/src/control_center/sections/shortcuts.zig b/src/control_center/sections/shortcuts.zigindex f41dd91..3e764b3 100644--- a/src/control_center/sections/shortcuts.zig+++ b/src/control_center/sections/shortcuts.zig@@ -100,7 +100,7 @@ fn group(action: keys.Action) usize {return switch (action) {.toggle_floating, .toggle_split, .toggle_workspace_tiling, .swap_left, .swap_right, .swap_up, .swap_down, .resize_split_left, .resize_split_right, .resize_split_up, .resize_split_down, .close_window, .toggle_fullscreen, .toggle_maximize, .tile_left, .tile_right, .tile_up, .tile_down => 0,.set_depth, .zoom_in, .zoom_out, .zoom_reset, .camera_zoom_in, .camera_zoom_out, .camera_zoom_reset, .pan_left, .pan_right, .pan_up, .pan_down, .focus_next, .focus_prev, .focus_left, .focus_right, .focus_up, .focus_down, .save_layout, .restore_layout, .undo => 1,- .spawn, .toggle_start_menu => 2,+ .spawn, .toggle_start_menu, .input_source_next, .input_source_prev => 2,.screenshot_region, .screenshot_output => 3,.volume_up, .volume_down, .volume_mute, .mic_mute, .brightness_up, .brightness_down, .power_profile_cycle => 4,else => 5,@@ -277,6 +277,8 @@ fn descriptionFor(action: keys.Action, buf: []u8) []const u8 {.brightness_up => i18n.tr("Increase display brightness."),.brightness_down => i18n.tr("Decrease display brightness."),.power_profile_cycle => i18n.tr("Switch to the next power profile."),+ .input_source_next => i18n.tr("Switch to the next keyboard layout or input method."),+ .input_source_prev => i18n.tr("Switch to the previous keyboard layout or input method."),.quit => i18n.tr("Log out of the desktop session."),.poweroff, .poweroff_auto => i18n.tr("Shut down the computer."),.reboot, .reboot_auto => i18n.tr("Restart the computer."),@@ -321,6 +323,8 @@ fn actionTitle(action: keys.Action) []const u8 {.brightness_up => i18n.tr("Brightness Up"),.brightness_down => i18n.tr("Brightness Down"),.power_profile_cycle => i18n.tr("Power Profile Cycle"),+ .input_source_next => i18n.tr("Next Input Source"),+ .input_source_prev => i18n.tr("Previous Input Source"),.spawn => i18n.tr("Spawn"),.close_window => i18n.tr("Close Window"),.toggle_fullscreen => i18n.tr("Toggle Fullscreen"),diff --git a/src/control_center/tree.zig b/src/control_center/tree.zigindex 7de9e9c..68bbbcd 100644--- a/src/control_center/tree.zig+++ b/src/control_center/tree.zig@@ -79,6 +79,7 @@ pub fn buildTree(cc: *ControlCenter) void {if (cc.page == .network and cc.built_page == .network) cc.network.captureFocus();if (cc.page == .printers and cc.built_page == .printers) cc.printers.capture();if (cc.page == .keys and cc.built_page == .keys) cc.key_settings.capture();+ if (cc.page == .input and cc.built_page == .input) cc.input_sources.capture();if (cc.page == .appearance) appearance_section.captureItemFocus(&cc.appearance);ui.input.reset();const has_services = if (cc.systemd_client) |client| client.available() else false;@@ -195,7 +196,11 @@ pub fn buildTree(cc: *ControlCenter) void {network_section.build(&cc.network, cc);cc.append(cc.network.root);},- .input => for (cc.input.row_storage[0..cc.input.row_count]) |*row| {+ .input => for (cc.input.row_storage[0..cc.input.row_count], 0..) |*row, i| {+ if (i == cc.input.keyboard_row) {+ @import("sections/input_sources.zig").build(&cc.input_sources, cc);+ cc.append(cc.input_sources.root);+ }var framed = card(row.children);framed.name = "input";framed.direction = row.direction;@@ -278,6 +283,9 @@ pub fn buildTree(cc: *ControlCenter) void {if (!cc.search.empty() and cc.page == .services and cc.services.search_focus) {if (cc.services.search) |field| ui.input.current.focus(&cc.root, field);}+ if (!cc.search.empty() and cc.page == .input and cc.input_sources.search_focus) {+ if (cc.input_sources.search) |field| ui.input.current.focus(&cc.root, field);+ }if (!cc.search.empty() and cc.page == .users) {if (users_section.initialFormFocus(&cc.users)) |field| ui.input.current.focus(&cc.root, field);}diff --git a/src/input/AGENTS.md b/src/input/AGENTS.mdindex 59cf1ba..6e27b5c 100644--- a/src/input/AGENTS.md+++ b/src/input/AGENTS.md@@ -20,6 +20,15 @@text.* **Layouts:** layout-zero fallback is for binding lookup only; text uses theactive XKB state.+* **Input sources** (`input_sources.zig`, `input_sources/`): the config's+ layouts (XKB groups, at most four) plus Fcitx5's methods, read and switched+ over D-Bus, never written. The active group is global: switching sets it on+ every keyboard with the config keymap; a keyboard that switches itself (a+ `grp:` toggle, `layouts.observe`) moves it and the others follow from an+ idle callback, never inside their own modifiers signal. Fcitx has no+ current-method signal: any signal from its unique name re-asks+ `CurrentInputMethod`. The lock types with layouts only (`cycleLayouts`).+ `tests/input_sources.py` uses a fake Fcitx on a private session bus.* **Shell key repeat:** one `shell_repeat` per keyboard; a new shell targetneeds a `ShellTarget` case, a freeable panel calls `forgetShellTarget`.Return, Escape, Tab and modifier chords never repeat.diff --git a/src/input/axis.zig b/src/input/axis.zigindex cb00bde..adfcc50 100644--- a/src/input/axis.zig+++ b/src/input/axis.zig@@ -176,7 +176,7 @@ pub fn processAxis(},.taskbar => |hit| {if (orientation == .vertical_scroll) {- hit.bar.scrollVolume(hit.sx, hit.sy, ui_scroll.axisDeltaPx(delta, delta_discrete));+ hit.bar.scrollVolume(hit.sx, hit.sy, ui_scroll.axisDeltaPx(delta, delta_discrete), notch);}return;},diff --git a/src/input/layouts.zig b/src/input/layouts.zigindex 2886e84..1619e0f 100644--- a/src/input/layouts.zig+++ b/src/input/layouts.zig@@ -28,6 +28,7 @@ pub fn activate(keyboard: *Keyboard) void {server.layout_keyboard = keyboard;keyboard.layout_idx = current(keyboard);events.onKeyboardLayoutsChanged(server);+ if (server.input_sources) |sources| sources.observe(keyboard, keyboard.layout_idx, true);} else changed(keyboard, false);}@@ -38,6 +39,7 @@ pub fn changed(keyboard: *Keyboard, keymap: bool) void {if (keyboard.server.layout_keyboard != keyboard) return;if (keymap) events.onKeyboardLayoutsChanged(keyboard.server) else if (idx != previous) {if (idx) |value| events.onKeyboardLayoutSwitched(keyboard.server, value);+ if (keyboard.server.input_sources) |sources| sources.observe(keyboard, idx, false);}}diff --git a/src/input_sources.zig b/src/input_sources.zignew file mode 100644index 0000000..efc660e--- /dev/null+++ b/src/input_sources.zig@@ -0,0 +1,399 @@+//! Input sources: the configured keyboard layouts (XKB groups, in config+//! order) followed by the input methods of Fcitx5's current group while Fcitx+//! runs. One source is active. The taskbar indicator, its menu, the+//! `input_source_*` bindings, the lock screen and IPC all act through here.+//!+//! The active layout is one group for every keyboard that uses the config+//! keymap. Switching sets it on all of them; a keyboard that switches by+//! itself (an XKB `grp:` toggle) moves the global group, and the others follow+//! from an idle callback, never from inside a keyboard's own signal.+const std = @import("std");+const wl = @import("wayland").server.wl;++const Server = @import("Server.zig");+const Keyboard = @import("Keyboard.zig");+const config_sources = @import("config").input_sources;+const registry = @import("input_sources/registry.zig");+const labels = @import("input_sources/labels.zig");+const fcitx = @import("input_sources/fcitx.zig");+const text_input = @import("input/text_input.zig");+const gpa = @import("main.zig").gpa;++const log = std.log.scoped(.input_sources);++pub const Kind = enum { xkb, fcitx };++pub const Source = struct {+ kind: Kind,+ /// `de(nodeadkeys)` for a layout, Fcitx's unique name for a method.+ id: []const u8,+ /// What Settings and the menu show: "German (no dead keys)", "Mozc".+ name: []const u8,+ /// The indicator text.+ label: []const u8,+ /// The XKB group of a layout.+ group: u32 = 0,+};++pub const Manager = struct {+ server: *Server,+ /// Layout strings, replaced by `reload`.+ layout_arena: std.heap.ArenaAllocator = .init(gpa),+ /// The combined list, replaced by every `rebuild`.+ list_arena: std.heap.ArenaAllocator = .init(gpa),+ layouts: [config_sources.max_layouts]config_sources.Layout = undefined,+ layout_count: usize = 0,+ list: []Source = &.{},+ active_group: u32 = 0,++ catalog: ?registry.Catalog = null,+ catalog_failed: bool = false,+ job: ?*registry.Job = null,+ job_source: ?*wl.EventSource = null,++ fcitx: ?*fcitx.Client = null,+ sync_idle: ?*wl.EventSource = null,++ /// What was last announced, so a repeated state notifies nobody.+ announced_index: ?usize = null,+ announced_label: labels.Text = .{},+ announced_count: usize = 0,+ generation: u64 = 0,++ pub fn create(server: *Server) !*Manager {+ const self = try gpa.create(Manager);+ self.* = .{ .server = server };+ self.reload();+ return self;+ }++ pub fn deinit(self: *Manager) void {+ if (self.sync_idle) |source| source.remove();+ if (self.job_source) |source| source.remove();+ if (self.job) |job| if (job.finish()) |found| {+ var catalog = found;+ catalog.deinit();+ };+ if (self.fcitx) |client| client.destroy();+ if (self.catalog) |*catalog| catalog.deinit();+ self.list_arena.deinit();+ self.layout_arena.deinit();+ gpa.destroy(self);+ }++ /// Optional services, after the first desktop frame and never in the greeter.+ pub fn startServices(self: *Manager) void {+ if (self.server.greeter_mode or self.fcitx != null) return;+ const client = fcitx.Client.create(gpa, self.server.wl_server.getEventLoop(), self.server.environ) catch return;+ client.on_change = fcitxChanged;+ client.change_owner = self;+ self.fcitx = client;+ }++ pub fn sources(self: *const Manager) []const Source {+ return self.list;+ }++ pub fn layoutCount(self: *const Manager) usize {+ return self.layout_count;+ }++ pub fn configuredLayouts(self: *const Manager) []const config_sources.Layout {+ return self.layouts[0..self.layout_count];+ }++ /// The source in effect: an active Fcitx method, else the active layout.+ pub fn activeIndex(self: *const Manager) ?usize {+ if (self.list.len == 0) return null;+ if (self.fcitx) |client| if (client.activeMethod()) |method| {+ const index = self.layout_count + method;+ if (index < self.list.len) return index;+ };+ return @min(self.active_group, self.layout_count -| 1);+ }++ pub fn activeLabel(self: *const Manager) []const u8 {+ const index = self.activeIndex() orelse return "";+ return self.list[index].label;+ }++ /// The active layout's text, whatever Fcitx does: what the lock screen+ /// types with, since input methods never reach it.+ pub fn activeLayoutLabel(self: *const Manager) []const u8 {+ if (self.list.len == 0) return "";+ return self.list[@min(self.active_group, self.layout_count -| 1)].label;+ }++ /// More than one thing to switch between; drives the automatic taskbar item.+ pub fn switchable(self: *const Manager) bool {+ return self.list.len > 1;+ }++ pub fn fcitxRunning(self: *const Manager) bool {+ const client = self.fcitx orelse return false;+ return client.running();+ }++ // ---- configuration --------------------------------------------------++ /// Re-reads the layouts from the config. The active layout keeps its place+ /// by identity when the list is reordered.+ pub fn reload(self: *Manager) void {+ var previous: ?config_sources.Layout = null;+ var previous_buf: [2][64]u8 = undefined;+ if (self.active_group < self.layout_count) {+ const old = self.layouts[self.active_group];+ const layout_len = @min(old.layout.len, 64);+ const variant_len = @min(old.variant.len, 64);+ @memcpy(previous_buf[0][0..layout_len], old.layout[0..layout_len]);+ @memcpy(previous_buf[1][0..variant_len], old.variant[0..variant_len]);+ previous = .{ .layout = previous_buf[0][0..layout_len], .variant = previous_buf[1][0..variant_len] };+ }+ _ = self.layout_arena.reset(.retain_capacity);+ const a = self.layout_arena.allocator();+ const split = config_sources.split(self.server.config.input);+ self.layout_count = 0;+ for (split.slice()) |layout| {+ self.layouts[self.layout_count] = .{+ .layout = a.dupe(u8, layout.layout) catch break,+ .variant = a.dupe(u8, layout.variant) catch break,+ .label = a.dupe(u8, layout.label) catch break,+ };+ self.layout_count += 1;+ }+ if (self.layout_count == 0) {+ // XKB's own fallback, so the indicator names what is really typed.+ const environ = self.server.environ;+ self.layouts[0] = .{+ .layout = a.dupe(u8, environ.getPosix("XKB_DEFAULT_LAYOUT") orelse "us") catch "us",+ .variant = a.dupe(u8, environ.getPosix("XKB_DEFAULT_VARIANT") orelse "") catch "",+ };+ if (std.mem.indexOfScalar(u8, self.layouts[0].layout, ',')) |comma| self.layouts[0].layout = self.layouts[0].layout[0..comma];+ if (std.mem.indexOfScalar(u8, self.layouts[0].variant, ',')) |comma| self.layouts[0].variant = self.layouts[0].variant[0..comma];+ self.layout_count = 1;+ }+ var group: u32 = 0;+ if (previous) |old| {+ for (self.configuredLayouts(), 0..) |layout, i| if (layout.eql(old)) {+ group = @intCast(i);+ break;+ };+ }+ self.active_group = group;+ if (self.layout_count > 1) self.wantCatalog();+ self.rebuild();+ self.scheduleSync();+ }++ /// Starts the registry load once; Settings asks for it too.+ pub fn wantCatalog(self: *Manager) void {+ if (self.catalog != null or self.job != null or self.catalog_failed) return;+ const job = registry.Job.start() catch |err| {+ log.warn("could not start the layout catalogue: {}", .{err});+ self.catalog_failed = true;+ return;+ };+ self.job_source = self.server.wl_server.getEventLoop().addFd(*Manager, job.fd, .{ .readable = true }, catalogReady, self) catch {+ if (job.finish()) |found| self.catalog = found else self.catalog_failed = true;+ self.rebuild();+ return;+ };+ self.job = job;+ }++ pub fn catalogState(self: *const Manager) enum { loading, ready, unavailable } {+ if (self.catalog != null) return .ready;+ if (self.catalog_failed) return .unavailable;+ return .loading;+ }++ fn catalogReady(_: c_int, _: wl.EventMask, self: *Manager) c_int {+ if (self.job_source) |source| source.remove();+ self.job_source = null;+ const job = self.job orelse return 0;+ self.job = null;+ if (job.finish()) |found| self.catalog = found else self.catalog_failed = true;+ self.rebuild();+ if (self.server.input.open_control_center) |cc| cc.refresh();+ return 0;+ }++ /// A layout's description from the catalogue, or its XKB spelling.+ pub fn describe(self: *const Manager, a: std.mem.Allocator, layout: config_sources.Layout) []const u8 {+ if (self.catalog) |*catalog| if (catalog.find(layout.layout, layout.variant)) |entry| {+ if (entry.description.len > 0) return entry.description;+ };+ var buf: [160]u8 = undefined;+ return a.dupe(u8, layout.format(&buf)) catch layout.layout;+ }++ fn rebuild(self: *Manager) void {+ self.list = &.{};+ _ = self.list_arena.reset(.retain_capacity);+ const a = self.list_arena.allocator();+ const methods: []const fcitx.Method = if (self.fcitx) |client| (if (client.running()) client.methods else &.{}) else &.{};+ const total = self.layout_count + methods.len;+ const list = a.alloc(Source, total) catch {+ self.list = &.{};+ return;+ };+ var texts: [config_sources.max_layouts + 32]labels.Text = undefined;+ var explicit: [config_sources.max_layouts + 32]bool = @splat(false);+ const n = @min(total, texts.len);+ for (self.configuredLayouts(), 0..) |layout, i| {+ if (layout.label.len > 0) {+ texts[i] = .{};+ texts[i].set(layout.label);+ explicit[i] = true;+ } else {+ const brief = if (self.catalog) |*catalog| (if (catalog.find(layout.layout, layout.variant)) |entry| entry.brief else "") else "";+ texts[i] = labels.base(brief, layout.layout);+ }+ var buf: [160]u8 = undefined;+ list[i] = .{+ .kind = .xkb,+ .id = a.dupe(u8, layout.format(&buf)) catch layout.layout,+ .name = self.describe(a, layout),+ .label = "",+ .group = @intCast(i),+ };+ }+ for (methods, 0..) |method, j| {+ const i = self.layout_count + j;+ if (i >= n) break;+ if (method.label.len > 0) {+ texts[i] = .{};+ texts[i].set(method.label);+ explicit[i] = true;+ } else texts[i] = labels.base(method.language, method.name);+ // The client's strings go with its next refresh; keep our own.+ list[i] = .{ .kind = .fcitx, .id = a.dupe(u8, method.name) catch "", .name = a.dupe(u8, method.display) catch "", .label = "" };+ }+ labels.disambiguate(texts[0..n], explicit[0..n]);+ for (list[0..n], 0..) |*source, i| source.label = a.dupe(u8, texts[i].slice()) catch "";+ self.list = list[0..n];+ self.announce();+ }++ fn fcitxChanged(owner: ?*anyopaque) void {+ const self: *Manager = @ptrCast(@alignCast(owner orelse return));+ self.rebuild();+ }++ // ---- switching ----------------------------------------------------------++ pub fn select(self: *Manager, index: usize) bool {+ if (index >= self.list.len) return false;+ const source = self.list[index];+ switch (source.kind) {+ .xkb => {+ if (self.fcitx) |client| client.deactivate();+ self.setGroup(source.group);+ },+ .fcitx => if (self.fcitx) |client| client.select(source.id),+ }+ self.announce();+ return true;+ }++ pub fn cycle(self: *Manager, forward: bool) void {+ if (self.list.len < 2) return;+ const current = self.activeIndex() orelse 0;+ const count = self.list.len;+ _ = self.select(if (forward) (current + 1) % count else (current + count - 1) % count);+ }++ /// Layouts only: the lock screen and anything that must not hand keys to+ /// an input method.+ pub fn cycleLayouts(self: *Manager) void {+ if (self.layout_count < 2) return;+ self.setGroup(@intCast((self.active_group + 1) % self.layout_count));+ self.announce();+ }++ fn setGroup(self: *Manager, group: u32) void {+ if (group >= self.layout_count) return;+ self.active_group = group;+ self.syncKeyboards();+ }++ /// Keyboards that use the config keymap; virtual and synthetic ones carry+ /// their own.+ fn follows(self: *const Manager, keyboard: *Keyboard) bool {+ if (keyboard.synthetic or text_input.isVirtual(keyboard.device)) return false;+ const kb = keyboard.device.toKeyboard();+ const keymap = kb.keymap orelse return false;+ return keymap.numLayouts() == self.layout_count;+ }++ fn syncKeyboards(self: *Manager) void {+ if (self.sync_idle) |source| source.remove();+ self.sync_idle = null;+ // The active keyboard last, so the seat ends on the keyboard in use.+ var it = self.server.input.keyboards.iterator(.forward);+ while (it.next()) |keyboard| if (keyboard != self.server.layout_keyboard) self.apply(keyboard);+ if (self.server.layout_keyboard) |keyboard| self.apply(keyboard);+ }++ fn apply(self: *Manager, keyboard: *Keyboard) void {+ if (!self.follows(keyboard)) return;+ const kb = keyboard.device.toKeyboard();+ if (kb.modifiers.group == self.active_group) return;+ var mods = kb.modifiers;+ mods.group = self.active_group;+ kb.notifyModifiers(mods);+ }++ pub fn scheduleSync(self: *Manager) void {+ if (self.sync_idle != null) return;+ self.sync_idle = self.server.wl_server.getEventLoop().addIdle(*Manager, syncIdle, self) catch null;+ }++ fn syncIdle(self: *Manager) void {+ self.sync_idle = null;+ self.syncKeyboards();+ }++ /// A keyboard's group changed or it became the one in use (layouts.zig).+ pub fn observe(self: *Manager, keyboard: *Keyboard, group: ?u32, became_active: bool) void {+ if (!self.follows(keyboard)) return;+ if (became_active) {+ // A keyboard picked up after another follows the global layout.+ if (group != self.active_group) self.scheduleSync();+ return;+ }+ const value = group orelse return;+ if (value == self.active_group or value >= self.layout_count) return;+ self.active_group = value;+ self.scheduleSync();+ self.announce();+ }++ // ---- notification -------------------------------------------------------++ /// Tells everything that shows the active source, once per real change.+ pub fn announce(self: *Manager) void {+ const index = self.activeIndex();+ const label = self.activeLabel();+ const count = self.list.len;+ if (index == self.announced_index and count == self.announced_count and std.mem.eql(u8, label, self.announced_label.slice())) return;+ const presence_changed = (count > 1) != (self.announced_count > 1);+ self.announced_index = index;+ self.announced_count = count;+ self.announced_label.set(label);+ self.generation +%= 1;+ var outputs = self.server.outputs.iterator(.forward);+ while (outputs.next()) |output| if (output.taskbar) |bar| bar.applyInputSource(presence_changed);+ self.server.input.window_menu.sourcesChanged();+ if (self.server.locker) |lock| lock.inputSourceChanged();+ @import("ipc/events.zig").onInputSourceChanged(self.server);+ if (self.server.input.open_control_center) |cc| if (cc.page == .input) cc.refresh();+ }+};++test {+ _ = registry;+ _ = labels;+ _ = fcitx;+ _ = @import("control_center/sections/input_sources.zig");+}diff --git a/src/input_sources/fcitx.zig b/src/input_sources/fcitx.zignew file mode 100644index 0000000..438adb1--- /dev/null+++ b/src/input_sources/fcitx.zig@@ -0,0 +1,441 @@+//! Fcitx5 on the session bus, read and switched only: RediWM lists the input+//! methods of Fcitx's current group and asks Fcitx to change between them, and+//! never writes Fcitx's configuration (`fcitx5-configtool` stays its editor).+//! Keyboard layouts belong to RediWM, so Fcitx's `keyboard-*` entries are not+//! listed.+//!+//! Event-driven: NameOwnerChanged follows Fcitx starting, crashing and+//! restarting. Controller1 has no signal for the current method, but Fcitx+//! updates its tray item (and other objects it owns) on every change, so any+//! signal from Fcitx's unique name asks for `CurrentInputMethod` again, one+//! call at a time. `InputMethodGroupsChanged` re-reads the list.+const std = @import("std");+const dbus = @import("dbus");+const wire = dbus.wire;++const log = std.log.scoped(.input_sources);++pub const bus_name = "org.fcitx.Fcitx5";+const object_path = "/controller";+const interface = "org.fcitx.Fcitx.Controller1";+const call_timeout_ms: u32 = 3000;+const owner_rule = "type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',path='/org/freedesktop/DBus',arg0='" ++ bus_name ++ "'";++pub const Method = struct {+ /// Fcitx's unique name, e.g. "mozc", "pinyin".+ name: []const u8,+ /// "Mozc", or the native name when Fcitx has one.+ display: []const u8,+ /// Fcitx's short label ("あ", "拼"), or "".+ label: []const u8,+ /// Language code ("ja", "zh_CN"), or "".+ language: []const u8,+};++pub fn isKeyboard(name: []const u8) bool {+ return std.mem.startsWith(u8, name, "keyboard-");+}++pub const Client = struct {+ allocator: std.mem.Allocator,+ loop: *@import("wayland").server.wl.EventLoop,+ environ: std.process.Environ,+ conn: ?*dbus.Connection = null,+ owner: ?[]u8 = null,+ owner_rule_buf: [128]u8 = undefined,+ owner_rule_len: usize = 0,+ /// Each new owner starts a new epoch; replies from an older one are dropped.+ epoch: u64 = 0,+ closing: bool = false,++ /// What Fcitx reported last, owned by `arena`.+ arena: std.heap.ArenaAllocator,+ methods: []Method = &.{},+ current_buf: [128]u8 = undefined,+ current_len: usize = 0,+ group_buf: [128]u8 = undefined,+ group_len: usize = 0,++ querying: bool = false,+ query_again: bool = false,+ refreshing: bool = false,+ refresh_again: bool = false,++ /// Called after any change to `methods`, `current` or `running`.+ on_change: ?*const fn (owner: ?*anyopaque) void = null,+ change_owner: ?*anyopaque = null,++ pub fn create(allocator: std.mem.Allocator, loop: anytype, environ: std.process.Environ) !*Client {+ const self = try allocator.create(Client);+ self.* = .{ .allocator = allocator, .loop = loop, .environ = environ, .arena = .init(allocator) };+ self.connect();+ return self;+ }++ pub fn destroy(self: *Client) void {+ self.closing = true;+ if (self.conn) |conn| conn.destroy();+ if (self.owner) |owner| self.allocator.free(owner);+ self.arena.deinit();+ self.allocator.destroy(self);+ }++ pub fn running(self: *const Client) bool {+ return self.owner != null;+ }++ /// Fcitx's current method, keyboards included; null while not running.+ pub fn current(self: *const Client) ?[]const u8 {+ if (self.owner == null or self.current_len == 0) return null;+ return self.current_buf[0..self.current_len];+ }++ /// The method from the list that is active, if any (not a keyboard).+ pub fn activeMethod(self: *const Client) ?usize {+ const name = self.current() orelse return null;+ for (self.methods, 0..) |method, i| if (std.mem.eql(u8, method.name, name)) return i;+ return null;+ }++ pub fn select(self: *Client, name: []const u8) void {+ var body = self.writer();+ defer body.deinit();+ body.string(name) catch return;+ self.send("SetCurrentIM", "s", &body);+ // Fcitx answers with a tray update as well; ask directly in case it does not.+ self.queryCurrent();+ }++ /// Back to plain keyboard input: Fcitx's inactive state passes keys to the+ /// layout RediWM chose.+ pub fn deactivate(self: *Client) void {+ if (self.activeMethod() == null) return;+ var body = self.writer();+ defer body.deinit();+ self.send("Deactivate", "", &body);+ self.queryCurrent();+ }++ fn writer(self: *Client) wire.Writer {+ return .{ .allocator = self.allocator };+ }++ fn send(self: *Client, member: []const u8, signature: []const u8, body: *const wire.Writer) void {+ const conn = self.conn orelse return;+ if (conn.closed or self.owner == null) return;+ _ = conn.call(bus_name, object_path, interface, member, signature, body, null, null, call_timeout_ms) catch |err| {+ log.warn("fcitx {s} failed: {}", .{ member, err });+ };+ }++ fn notify(self: *Client) void {+ if (self.closing) return;+ if (self.on_change) |callback| callback(self.change_owner);+ }++ fn connect(self: *Client) void {+ const conn = dbus.Connection.openSession(self.allocator, self.loop, self.environ) catch |err| {+ log.info("no session bus, Fcitx input methods unavailable: {}", .{err});+ return;+ };+ _ = conn.hello(self, onHello) catch |err| {+ log.warn("could not register on the session bus: {}", .{err});+ conn.destroy();+ return;+ };+ conn.on_disconnect = .{ .owner = self, .callback = onDisconnect };+ self.conn = conn;+ }++ fn onDisconnect(owner: ?*anyopaque) void {+ const self: *Client = @ptrCast(@alignCast(owner orelse return));+ if (self.closing) return;+ self.setOwner(null);+ }++ fn onHello(owner: ?*anyopaque, conn: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {+ const self: *Client = @ptrCast(@alignCast(owner orelse return));+ if (self.closing) return;+ const msg = result catch {+ conn.close();+ return;+ };+ if (msg.kind != .method_return) {+ conn.close();+ return;+ }+ conn.registerSignal(.{+ .sender = "org.freedesktop.DBus",+ .path = "/org/freedesktop/DBus",+ .interface = "org.freedesktop.DBus",+ .member = "NameOwnerChanged",+ .owner = self,+ .callback = onNameOwnerChanged,+ }) catch return;+ // Everything Fcitx emits; the sender is checked in the handler.+ conn.registerSignal(.{ .owner = self, .callback = onFcitxSignal }) catch return;+ _ = conn.addMatch(owner_rule, null, null) catch return;+ var body = self.writer();+ defer body.deinit();+ body.string(bus_name) catch return;+ _ = conn.call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetNameOwner", "s", &body, self, onNameOwner, call_timeout_ms) catch {};+ }++ fn onNameOwner(owner: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {+ const self: *Client = @ptrCast(@alignCast(owner orelse return));+ if (self.closing) return;+ var msg = result catch return;+ if (msg.kind != .method_return) return; // Fcitx is not running yet.+ const unique = msg.body.string() catch return;+ if (self.owner != null) return; // NameOwnerChanged was first.+ self.setOwner(unique);+ }++ fn onNameOwnerChanged(owner: ?*anyopaque, _: *dbus.Connection, msg: wire.Message) anyerror!void {+ const self: *Client = @ptrCast(@alignCast(owner orelse return));+ if (self.closing) return;+ var body = msg.body;+ const name = try body.string();+ _ = try body.string();+ const new_owner = try body.string();+ if (!std.mem.eql(u8, name, bus_name)) return;+ self.setOwner(if (new_owner.len == 0) null else new_owner);+ }++ fn setOwner(self: *Client, unique: ?[]const u8) void {+ if (self.conn) |conn| if (self.owner_rule_len > 0 and !conn.closed) {+ _ = conn.removeMatch(self.owner_rule_buf[0..self.owner_rule_len], null, null) catch {};+ };+ self.owner_rule_len = 0;+ if (self.owner) |old| self.allocator.free(old);+ self.owner = null;+ self.epoch +%= 1;+ _ = self.arena.reset(.retain_capacity);+ self.methods = &.{};+ self.current_len = 0;+ self.group_len = 0;+ self.querying = false;+ self.query_again = false;+ self.refreshing = false;+ self.refresh_again = false;+ if (unique) |name| {+ self.owner = self.allocator.dupe(u8, name) catch null;+ if (self.owner != null) {+ log.info("Fcitx5 is running ({s})", .{name});+ if (self.conn) |conn| {+ const rule = std.fmt.bufPrint(&self.owner_rule_buf, "type='signal',sender='{s}'", .{name}) catch "";+ self.owner_rule_len = rule.len;+ if (rule.len > 0) _ = conn.addMatch(rule, null, null) catch {};+ }+ self.refresh();+ }+ } else log.info("Fcitx5 is not running", .{});+ self.notify();+ }++ fn fromOwner(self: *const Client, msg: wire.Message) bool {+ const owner = self.owner orelse return false;+ return std.mem.eql(u8, owner, msg.headers.sender orelse "");+ }++ fn onFcitxSignal(owner: ?*anyopaque, _: *dbus.Connection, msg: wire.Message) anyerror!void {+ const self: *Client = @ptrCast(@alignCast(owner orelse return));+ if (self.closing or !self.fromOwner(msg)) return;+ if (std.mem.eql(u8, msg.headers.member orelse "", "InputMethodGroupsChanged")) self.refresh() else self.queryCurrent();+ }++ const Request = struct { client: *Client, epoch: u64 };++ fn request(self: *Client) ?*Request {+ const req = self.allocator.create(Request) catch return null;+ req.* = .{ .client = self, .epoch = self.epoch };+ return req;+ }++ fn call(self: *Client, member: []const u8, signature: []const u8, body: *const wire.Writer, callback: dbus.Connection.Callback) bool {+ const conn = self.conn orelse return false;+ if (conn.closed or self.owner == null) return false;+ const req = self.request() orelse return false;+ _ = conn.call(bus_name, object_path, interface, member, signature, body, req, callback, call_timeout_ms) catch {+ self.allocator.destroy(req);+ return false;+ };+ return true;+ }++ /// Takes a reply for the current owner, or frees a stale one.+ fn accept(owner: ?*anyopaque, result: dbus.Connection.Failure!wire.Message) ?struct { client: *Client, msg: wire.Message } {+ const req: *Request = @ptrCast(@alignCast(owner orelse return null));+ const self = req.client;+ const epoch = req.epoch;+ self.allocator.destroy(req);+ if (self.closing or epoch != self.epoch) return null;+ const msg = result catch return .{ .client = self, .msg = .{ .kind = .error_reply, .serial = 0, .headers = .{}, .body = .{ .bytes = &.{} } } };+ return .{ .client = self, .msg = msg };+ }++ pub fn queryCurrent(self: *Client) void {+ if (self.querying) {+ self.query_again = true;+ return;+ }+ var body = self.writer();+ defer body.deinit();+ self.querying = self.call("CurrentInputMethod", "", &body, onCurrent);+ }++ fn onCurrent(owner: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {+ const got = accept(owner, result) orelse return;+ const self = got.client;+ var msg = got.msg;+ self.querying = false;+ if (msg.kind == .method_return and self.fromOwner(msg) and std.mem.eql(u8, msg.headers.signature, "s")) {+ const name = msg.body.string() catch "";+ if (name.len <= self.current_buf.len and !std.mem.eql(u8, name, self.current_buf[0..self.current_len])) {+ @memcpy(self.current_buf[0..name.len], name);+ self.current_len = name.len;+ self.notify();+ }+ }+ if (self.query_again) {+ self.query_again = false;+ self.queryCurrent();+ }+ }++ /// Group name, then its entries, then the method descriptions.+ fn refresh(self: *Client) void {+ if (self.refreshing) {+ self.refresh_again = true;+ return;+ }+ var body = self.writer();+ defer body.deinit();+ self.refreshing = self.call("CurrentInputMethodGroup", "", &body, onGroup);+ }++ fn refreshDone(self: *Client) void {+ self.refreshing = false;+ if (self.refresh_again) {+ self.refresh_again = false;+ self.refresh();+ }+ }++ fn onGroup(owner: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {+ const got = accept(owner, result) orelse return;+ const self = got.client;+ var msg = got.msg;+ if (msg.kind != .method_return or !self.fromOwner(msg) or !std.mem.eql(u8, msg.headers.signature, "s")) return self.refreshDone();+ const group = msg.body.string() catch "";+ const len = @min(group.len, self.group_buf.len);+ @memcpy(self.group_buf[0..len], group[0..len]);+ self.group_len = len;+ var body = self.writer();+ defer body.deinit();+ body.string(self.group_buf[0..len]) catch return self.refreshDone();+ if (!self.call("InputMethodGroupInfo", "s", &body, onGroupInfo)) self.refreshDone();+ }++ fn onGroupInfo(owner: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {+ const got = accept(owner, result) orelse return;+ const self = got.client;+ var msg = got.msg;+ if (msg.kind != .method_return or !self.fromOwner(msg) or !std.mem.eql(u8, msg.headers.signature, "sa(ss)")) return self.refreshDone();+ _ = self.arena.reset(.retain_capacity);+ self.methods = parseGroup(self.arena.allocator(), &msg.body) catch &.{};+ var body = self.writer();+ defer body.deinit();+ if (!self.call("AvailableInputMethods", "", &body, onAvailable)) {+ self.refreshDone();+ self.notify();+ }+ }++ fn onAvailable(owner: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {+ const got = accept(owner, result) orelse return;+ const self = got.client;+ var msg = got.msg;+ if (msg.kind == .method_return and self.fromOwner(msg) and std.mem.eql(u8, msg.headers.signature, "a(ssssssb)")) {+ describe(self.arena.allocator(), self.methods, &msg.body) catch {};+ }+ self.refreshDone();+ self.notify();+ self.queryCurrent();+ }+};++/// `InputMethodGroupInfo` returns (default layout, [(method, layout)]). Keyboard+/// entries are dropped; the rest keep Fcitx's order. Strings are copied.+pub fn parseGroup(arena: std.mem.Allocator, body: *wire.Reader) ![]Method {+ _ = try body.string();+ var items = try body.array(8);+ var list: std.ArrayList(Method) = .empty;+ while (items.offset < items.bytes.len) {+ try items.alignTo(8);+ const name = try items.string();+ _ = try items.string();+ if (isKeyboard(name) or name.len == 0 or list.items.len >= 32) continue;+ const copy = try arena.dupe(u8, name);+ try list.append(arena, .{ .name = copy, .display = copy, .label = "", .language = "" });+ }+ return list.items;+}++/// Fills names and labels from `AvailableInputMethods`+/// (unique name, name, native name, icon, label, language code, configurable).+pub fn describe(arena: std.mem.Allocator, methods: []Method, body: *wire.Reader) !void {+ var items = try body.array(8);+ while (items.offset < items.bytes.len) {+ try items.alignTo(8);+ const unique = try items.string();+ const name = try items.string();+ const native = try items.string();+ _ = try items.string();+ const label = try items.string();+ const language = try items.string();+ _ = try items.boolean();+ for (methods) |*method| {+ if (!std.mem.eql(u8, method.name, unique)) continue;+ method.display = try arena.dupe(u8, if (name.len > 0) name else if (native.len > 0) native else unique);+ method.label = try arena.dupe(u8, label);+ method.language = try arena.dupe(u8, language);+ }+ }+}++test "group entries skip Fcitx keyboards and pick up names and labels" {+ const a = std.testing.allocator;+ var arena: std.heap.ArenaAllocator = .init(a);+ defer arena.deinit();+ var group: wire.Writer = .{ .allocator = a };+ defer group.deinit();+ try group.string("us");+ const items = try group.beginArray(8);+ for ([_][2][]const u8{ .{ "keyboard-us", "" }, .{ "mozc", "" }, .{ "pinyin", "" } }) |entry| {+ try group.alignTo(8);+ try group.string(entry[0]);+ try group.string(entry[1]);+ }+ try group.endArray(items);+ var reader: wire.Reader = .{ .bytes = group.bytes.items, .endian = .little };+ const methods = try parseGroup(arena.allocator(), &reader);+ try std.testing.expectEqual(@as(usize, 2), methods.len);+ try std.testing.expectEqualStrings("mozc", methods[0].name);++ var available: wire.Writer = .{ .allocator = a };+ defer available.deinit();+ const list = try available.beginArray(8);+ for ([_][6][]const u8{ .{ "mozc", "Mozc", "Mozc", "fcitx-mozc", "あ", "ja" }, .{ "keyboard-us", "English (US)", "", "input-keyboard", "us", "en" } }) |entry| {+ try available.alignTo(8);+ for (entry) |field| try available.string(field);+ try available.boolean(true);+ }+ try available.endArray(list);+ var available_reader: wire.Reader = .{ .bytes = available.bytes.items, .endian = .little };+ try describe(arena.allocator(), methods, &available_reader);+ try std.testing.expectEqualStrings("Mozc", methods[0].display);+ try std.testing.expectEqualStrings("あ", methods[0].label);+ try std.testing.expectEqualStrings("ja", methods[0].language);+ try std.testing.expectEqualStrings("pinyin", methods[1].display);+}diff --git a/src/input_sources/labels.zig b/src/input_sources/labels.zignew file mode 100644index 0000000..cf9db3c--- /dev/null+++ b/src/input_sources/labels.zig@@ -0,0 +1,103 @@+//! Indicator texts: the language code a layout carries in the XKB registry,+//! uppercased (`us` → EN, `de` → DE, `jp` → JA). Two sources that would read+//! the same get subscripts (EN₁, EN₂); a configured label always wins.+const std = @import("std");++pub const max_bytes = 24;++pub const Text = struct {+ bytes: [max_bytes]u8 = undefined,+ len: u8 = 0,++ pub fn slice(self: *const Text) []const u8 {+ return self.bytes[0..self.len];+ }++ pub fn set(self: *Text, value: []const u8) void {+ // Never cut a UTF-8 sequence in half.+ var n = @min(value.len, max_bytes);+ while (n > 0 and n < value.len and value[n] & 0xc0 == 0x80) n -= 1;+ @memcpy(self.bytes[0..n], value[0..n]);+ self.len = @intCast(n);+ }++ fn append(self: *Text, value: []const u8) void {+ if (self.len + value.len > max_bytes) return;+ @memcpy(self.bytes[self.len..][0..value.len], value);+ self.len += @intCast(value.len);+ }+};++/// A layout's base text: its registry code when known, else the layout name+/// itself, both uppercased and kept to three letters.+pub fn base(brief: []const u8, layout: []const u8) Text {+ const full = if (brief.len > 0) brief else layout;+ // A language tag's region is not part of its code: zh_CN reads ZH.+ const source = full[0 .. std.mem.indexOfAny(u8, full, "_-@.") orelse full.len];+ var out: Text = .{};+ var ascii: [3]u8 = undefined;+ var n: usize = 0;+ for (source) |ch| {+ if (n == ascii.len) break;+ if (ch >= 0x80) {+ // A non-Latin brief is shown as written.+ out.set(source);+ return out;+ }+ if (!std.ascii.isAlphanumeric(ch)) continue;+ ascii[n] = std.ascii.toUpper(ch);+ n += 1;+ }+ out.set(ascii[0..n]);+ return out;+}++const subscripts = [_][]const u8{ "₀", "₁", "₂", "₃", "₄", "₅", "₆", "₇", "₈", "₉" };++/// Numbers repeated texts in place. `explicit[i]` marks a configured label,+/// which is never changed and never numbered.+pub fn disambiguate(texts: []Text, explicit: []const bool) void {+ var numbered: [16]?usize = @splat(null);+ for (texts, 0..) |text, i| {+ if (explicit[i] or i >= numbered.len) continue;+ var position: usize = 1;+ var total: usize = 0;+ for (texts, 0..) |other, j| {+ if (explicit[j] or !std.mem.eql(u8, other.slice(), text.slice())) continue;+ total += 1;+ if (j < i) position += 1;+ }+ if (total > 1) numbered[i] = position;+ }+ for (texts, 0..) |*text, i| {+ if (i >= numbered.len) break;+ const n = numbered[i] orelse continue;+ text.append(subscripts[@min(n, 9)]);+ }+}++test "layout codes become uppercase language codes and repeats are numbered" {+ var texts = [_]Text{ base("en", "us"), base("en", "us"), base("de", "de"), base("ja", "jp"), base("", "custom"), base("zh_CN", "pinyin") };+ const explicit = [_]bool{ false, false, false, false, false, false };+ disambiguate(&texts, &explicit);+ try std.testing.expectEqualStrings("EN₁", texts[0].slice());+ try std.testing.expectEqualStrings("EN₂", texts[1].slice());+ try std.testing.expectEqualStrings("DE", texts[2].slice());+ try std.testing.expectEqualStrings("JA", texts[3].slice());+ try std.testing.expectEqualStrings("CUS", texts[4].slice());+ try std.testing.expectEqualStrings("ZH", texts[5].slice());+}++test "configured labels are kept as written and never numbered" {+ var jp: Text = .{};+ jp.set("JP");+ var texts = [_]Text{ base("ja", "jp"), jp, base("ja", "jp") };+ const explicit = [_]bool{ false, true, false };+ disambiguate(&texts, &explicit);+ try std.testing.expectEqualStrings("JA₁", texts[0].slice());+ try std.testing.expectEqualStrings("JP", texts[1].slice());+ try std.testing.expectEqualStrings("JA₂", texts[2].slice());+ var long: Text = .{};+ long.set("あいうえおかきくけ");+ try std.testing.expect(std.unicode.utf8ValidateSlice(long.slice()));+}diff --git a/src/input_sources/registry.zig b/src/input_sources/registry.zignew file mode 100644index 0000000..0137819--- /dev/null+++ b/src/input_sources/registry.zig@@ -0,0 +1,176 @@+//! The XKB layout catalogue (names, language codes, descriptions) from+//! libxkbregistry. Parsing evdev.xml takes about 11 ms, so it runs once on a+//! worker the first time something needs it (more than one layout, or the+//! Settings page) and wakes the event loop through an eventfd. The library is+//! opened with dlopen: some distributions package it separately, and without+//! it labels fall back to the layout code and Settings to a short built-in list.+const std = @import("std");+const builtin = @import("builtin");+const platform = @import("platform");+const sys = std.posix.system;++const a = std.heap.c_allocator;+const log = std.log.scoped(.input_sources);++pub const Entry = struct {+ layout: []const u8,+ variant: []const u8,+ /// Short language code from the registry ("en", "de", "ja"), or "".+ brief: []const u8,+ /// "German (no dead keys)".+ description: []const u8,+ /// ISO 639-3 codes, space separated, for searching ("deu", "jpn").+ languages: []const u8,+};++pub const Catalog = struct {+ arena: std.heap.ArenaAllocator,+ entries: []Entry,++ pub fn deinit(self: *Catalog) void {+ self.arena.deinit();+ }++ pub fn find(self: *const Catalog, layout: []const u8, variant: []const u8) ?*const Entry {+ for (self.entries) |*entry| {+ if (std.mem.eql(u8, entry.layout, layout) and std.mem.eql(u8, entry.variant, variant)) return entry;+ }+ return null;+ }+};++const Context = opaque {};+const Layout = opaque {};+const Code = opaque {};++const Api = struct {+ library: std.DynLib,+ context_new: *const fn (c_int) callconv(.c) ?*Context,+ parse_default: *const fn (*Context) callconv(.c) bool,+ context_unref: *const fn (*Context) callconv(.c) ?*Context,+ layout_first: *const fn (*Context) callconv(.c) ?*Layout,+ layout_next: *const fn (*Layout) callconv(.c) ?*Layout,+ layout_name: *const fn (*Layout) callconv(.c) ?[*:0]const u8,+ layout_variant: *const fn (*Layout) callconv(.c) ?[*:0]const u8,+ layout_brief: *const fn (*Layout) callconv(.c) ?[*:0]const u8,+ layout_description: *const fn (*Layout) callconv(.c) ?[*:0]const u8,+ iso639_first: *const fn (*Layout) callconv(.c) ?*Code,+ iso639_next: *const fn (*Code) callconv(.c) ?*Code,+ iso639_code: *const fn (*Code) callconv(.c) ?[*:0]const u8,++ fn open() ?Api {+ if (builtin.os.tag != .linux and builtin.os.tag != .freebsd) return null;+ var library = std.DynLib.open("libxkbregistry.so.0") catch return null;+ errdefer library.close();+ var api: Api = undefined;+ api.library = library;+ inline for (.{+ .{ "context_new", "rxkb_context_new" },+ .{ "parse_default", "rxkb_context_parse_default_ruleset" },+ .{ "context_unref", "rxkb_context_unref" },+ .{ "layout_first", "rxkb_layout_first" },+ .{ "layout_next", "rxkb_layout_next" },+ .{ "layout_name", "rxkb_layout_get_name" },+ .{ "layout_variant", "rxkb_layout_get_variant" },+ .{ "layout_brief", "rxkb_layout_get_brief" },+ .{ "layout_description", "rxkb_layout_get_description" },+ .{ "iso639_first", "rxkb_layout_get_iso639_first" },+ .{ "iso639_next", "rxkb_iso639_code_next" },+ .{ "iso639_code", "rxkb_iso639_code_get_code" },+ }) |pair| {+ @field(api, pair[0]) = library.lookup(@FieldType(Api, pair[0]), pair[1]) orelse {+ library.close();+ return null;+ };+ }+ return api;+ }+};++fn span(value: ?[*:0]const u8) []const u8 {+ return if (value) |v| std.mem.span(v) else "";+}++/// Blocking: reads the whole default ruleset. Null without the library or+/// rules.+pub fn load() ?Catalog {+ var api = Api.open() orelse return null;+ defer api.library.close();+ // RXKB_CONTEXT_NO_FLAGS: system include paths, no exotic layouts.+ const context = api.context_new(0) orelse return null;+ defer _ = api.context_unref(context);+ if (!api.parse_default(context)) return null;+ return build(&api, context) catch null;+}++fn build(api: *const Api, context: *Context) !Catalog {+ var catalog: Catalog = .{ .arena = .init(a), .entries = &.{} };+ errdefer catalog.deinit();+ const arena = catalog.arena.allocator();+ var list: std.ArrayList(Entry) = .empty;+ var it = api.layout_first(context);+ while (it) |layout| : (it = api.layout_next(layout)) {+ var languages: std.ArrayList(u8) = .empty;+ var code = api.iso639_first(layout);+ while (code) |c| : (code = api.iso639_next(c)) {+ if (languages.items.len > 0) try languages.append(arena, ' ');+ try languages.appendSlice(arena, span(api.iso639_code(c)));+ }+ try list.append(arena, .{+ .layout = try arena.dupe(u8, span(api.layout_name(layout))),+ .variant = try arena.dupe(u8, span(api.layout_variant(layout))),+ .brief = try arena.dupe(u8, span(api.layout_brief(layout))),+ .description = try arena.dupe(u8, span(api.layout_description(layout))),+ .languages = languages.items,+ });+ }+ catalog.entries = list.items;+ return catalog;+}++/// One background load. The owner polls `fd` on its event loop and calls+/// `finish` when it turns readable.+pub const Job = struct {+ fd: std.posix.fd_t,+ thread: ?std.Thread = null,+ result: ?Catalog = null,++ pub fn start() !*Job {+ const self = try a.create(Job);+ errdefer a.destroy(self);+ const fd = platform.wake.create() orelse return error.EventFdFailed;+ errdefer _ = sys.close(fd);+ self.* = .{ .fd = fd };+ self.thread = try std.Thread.spawn(.{}, run, .{self});+ return self;+ }++ fn run(self: *Job) void {+ self.result = load();+ if (self.result == null) log.info("libxkbregistry unavailable; layout names fall back to their codes", .{});+ const one: u64 = 1;+ _ = sys.write(self.fd, std.mem.asBytes(&one), @sizeOf(u64));+ }++ /// Joins the worker and hands its catalogue over. Also safe while it still+ /// runs (shutdown): the join waits for it.+ pub fn finish(self: *Job) ?Catalog {+ if (self.thread) |thread| thread.join();+ self.thread = null;+ const result = self.result;+ _ = sys.close(self.fd);+ a.destroy(self);+ return result;+ }+};++test "the registry, when installed, names common layouts and their language codes" {+ var catalog = load() orelse return error.SkipZigTest;+ defer catalog.deinit();+ const de = catalog.find("de", "") orelse return error.TestUnexpectedResult;+ try std.testing.expectEqualStrings("de", de.brief);+ try std.testing.expect(std.mem.indexOf(u8, de.languages, "deu") != null);+ const jp = catalog.find("jp", "") orelse return error.TestUnexpectedResult;+ try std.testing.expectEqualStrings("ja", jp.brief);+ try std.testing.expect(catalog.find("us", "dvorak") != null);+}diff --git a/src/ipc/commands.zig b/src/ipc/commands.zigindex b2320b3..1802a30 100644--- a/src/ipc/commands.zig+++ b/src/ipc/commands.zig@@ -753,6 +753,21 @@ pub const specs = [_]CommandSpec{.description_order = 86,.cli = .{ .name = "switch-layout", .synopsis = "<next|prev|index>" },},+ .{+ .id = .get_input_sources,+ .kind = .query,+ .description = "Inspect keyboard layouts and Fcitx input methods, and the zero-based active source",+ .description_order = 110,+ .cli = .{ .name = "input-sources" },+ },+ .{+ .id = .switch_input_source,+ .kind = .action,+ .description = "Switch to a keyboard layout or Fcitx input method; index is zero-based",+ .params_schema = "{\"source\": \"next\" | \"prev\" | number}",+ .description_order = 111,+ .cli = .{ .name = "switch-input-source", .synopsis = "<next|prev|index>" },+ },.{.id = .list_panels,.kind = .query,diff --git a/src/ipc/events.zig b/src/ipc/events.zigindex befe5d3..d5f855d 100644--- a/src/ipc/events.zig+++ b/src/ipc/events.zig@@ -16,6 +16,7 @@ fn eventMatchesFilter(filter: ?protocol.EventFilter, event: protocol.Event) boolconst event_name: []const u8 = switch (event) {.keyboard_layouts_changed => "keyboard_layouts_changed",.keyboard_layout_switched => "keyboard_layout_switched",+ .input_source_changed => "input_source_changed",.config_loaded => "config_loaded",.polkit_prompt_opened => "polkit_prompt_opened",.polkit_prompt_closed => "polkit_prompt_closed",@@ -348,6 +349,15 @@ pub fn onKeyboardLayoutSwitched(server: *Server, idx: u32) void {broadcastEvent(ipc, .{ .keyboard_layout_switched = .{ .seq = ipc.seq, .idx = idx } });}+pub fn onInputSourceChanged(server: *Server) void {+ const ipc = server.ipc orelse return;+ var arena = std.heap.ArenaAllocator.init(ipc.allocator);+ defer arena.deinit();+ const data = handlers.inputSourcesData(server, arena.allocator()) catch return;+ ipc.seq += 1;+ broadcastEvent(ipc, .{ .input_source_changed = .{ .seq = ipc.seq, .input_sources = data } });+}+pub fn onWidgetChanged(ipc: *ipc_server_mod.Server, panel: []const u8, node: protocol.WidgetNodeData) void {ipc.seq += 1;broadcastEvent(ipc, .{ .widget_changed = .{diff --git a/src/ipc/handlers.zig b/src/ipc/handlers.zigindex d001f3c..6fedec7 100644--- a/src/ipc/handlers.zig+++ b/src/ipc/handlers.zig@@ -113,6 +113,7 @@ pub fn handleRequest(.get_theme => return @import("settings.zig").getTheme(server, allocator),.get_processes => return @import("processes.zig").start(server, request_id, client),.get_keyboard_layouts => return .{ .ok = .{ .keyboard_layouts = try @import("../input/layouts.zig").inspect(server, allocator) } },+ .get_input_sources => return .{ .ok = .{ .input_sources = try inputSourcesData(server, allocator) } },.version => {return .{ .ok = .{ .version = "0.1.0" } };},@@ -355,6 +356,15 @@ pub fn handleAction(@import("../input/layouts.zig").switchLayout(server, target) catch |err| return .{ .err = @errorName(err) };return .{ .ok = .handled };},+ .switch_input_source => |target| {+ const sources = server.input_sources orelse return .{ .err = "Unsupported" };+ switch (target) {+ .next => sources.cycle(true),+ .prev => sources.cycle(false),+ .index => |index| if (!sources.select(index)) return .{ .err = "InvalidSourceIndex" },+ }+ return .{ .ok = .handled };+ },.reload_config => {@import("../config_runtime/watcher.zig").reloadConfig(server);return .{ .ok = .handled };@@ -481,3 +491,18 @@ pub const DumpTarget = enum {test {_ = @import("handlers_tests.zig");}++/// The input source list as IPC reports it (also the `InputSourceChanged` body).+pub fn inputSourcesData(server: *Server, allocator: std.mem.Allocator) !protocol.InputSourcesData {+ const manager = server.input_sources orelse return .{};+ const list = manager.sources();+ const out = try allocator.alloc(protocol.InputSourceData, list.len);+ for (list, out) |source, *item| item.* = .{ .kind = @tagName(source.kind), .id = source.id, .name = source.name, .label = source.label };+ const active_layout: ?u32 = if (list.len == 0) null else @intCast(@min(manager.active_group, manager.layoutCount() -| 1));+ return .{+ .sources = out,+ .active = if (manager.activeIndex()) |index| @intCast(index) else null,+ .active_layout = active_layout,+ .fcitx_running = manager.fcitxRunning(),+ };+}diff --git a/src/ipc/handlers_panels.zig b/src/ipc/handlers_panels.zigindex 684c899..3704b9e 100644--- a/src/ipc/handlers_panels.zig+++ b/src/ipc/handlers_panels.zig@@ -76,9 +76,17 @@ pub fn resolveWindowPicker(output: *Output) ?PanelRoot {return .{ .root = &menu.picker_root, .box = menu.box };}+/// The taskbar's input source list: rows `source_<n>` and `input_settings`.+pub fn resolveInputSources(output: *Output) ?PanelRoot {+ const menu = &output.server.input.window_menu;+ if (menu.output != output or menu.node == null or !menu.sources) return null;+ return .{ .root = &menu.picker_root, .box = menu.box };+}+pub const panel_registry = [_]PanelRegistryEntry{.{ .name = "dock", .resolve = resolveDock },.{ .name = "window_picker", .resolve = resolveWindowPicker },+ .{ .name = "input_sources", .resolve = resolveInputSources },.{ .name = "start_menu", .resolve = resolveStartMenu },.{ .name = "control_center", .resolve = resolveControlCenter },.{ .name = "power_menu", .resolve = resolvePowerMenu },diff --git a/src/ipc/handlers_widgets.zig b/src/ipc/handlers_widgets.zigindex 33766f7..f1bd63f 100644--- a/src/ipc/handlers_widgets.zig+++ b/src/ipc/handlers_widgets.zig@@ -422,6 +422,23 @@ pub fn buildTaskbarWidgetTree(});}+ if (bar.itemBox(.input_source)) |source_box| {+ const label = if (server.input_sources) |sources| sources.activeLabel() else "";+ try widgets.append(allocator, .{+ .id = widgets.items.len + 1,+ .parent_index = 0,+ .role = "button",+ .name = "input_source",+ .path = "taskbar/input_source",+ .semantic_id = "tray_input_source",+ .label = try allocator.dupe(u8, label),+ .box = .{ .x = source_box.x - bar.box.x, .y = source_box.y - bar.box.y, .width = source_box.width, .height = source_box.height },+ .global_box = .{ .x = source_box.x, .y = source_box.y, .width = source_box.width, .height = source_box.height },+ .visible = true,+ .is_disabled = false,+ });+ }+if (bar.itemBox(.power)) |pbox| {try widgets.append(allocator, .{.id = widgets.items.len + 1,diff --git a/src/ipc/protocol.zig b/src/ipc/protocol.zigindex 3539d79..166b6cc 100644--- a/src/ipc/protocol.zig+++ b/src/ipc/protocol.zig@@ -90,6 +90,8 @@ pub const GesturePhase = protocol_results.GesturePhase;pub const OutputConfigPatch = protocol_results.OutputConfigPatch;pub const MoveWindowToParams = protocol_results.MoveWindowToParams;pub const KeyboardLayoutsData = protocol_results.KeyboardLayoutsData;+pub const InputSourcesData = protocol_results.InputSourcesData;+pub const InputSourceData = protocol_results.InputSourceData;pub const LayoutTarget = protocol_results.LayoutTarget;pub const ConfigLoadedEvent = protocol_results.ConfigLoadedEvent;pub const ThemeToken = protocol_results.ThemeToken;@@ -166,6 +168,7 @@ pub const Action = union(enum) {set_accent_color: struct { color: [4]f32, persist: bool = true },set_night_light: struct { enabled: ?bool = null, temperature: ?u16 = null, persist: bool = true },switch_layout: LayoutTarget,+ switch_input_source: LayoutTarget,open_appearance,focus_window: struct { id: u64 },close_window: struct { id: ?u64 = null },@@ -267,6 +270,7 @@ pub const Request = union(enum) {get_theme,get_processes,get_keyboard_layouts,+ get_input_sources,version,capabilities,describe_ipc,@@ -359,6 +363,7 @@ pub const ResponsePayload = union(enum) {async_pending,text_input: TextInputResult,keyboard_layouts: KeyboardLayoutsData,+ input_sources: InputSourcesData,list_panels: ListPanelsResult,click_widget: WidgetPointResult,hover_widget: WidgetPointResult,@@ -387,6 +392,7 @@ pub const Event = union(enum) {window_urgency_changed: struct { seq: u64, id: u64, urgent: bool },keyboard_layouts_changed: struct { seq: u64, keyboard_layouts: KeyboardLayoutsData },keyboard_layout_switched: struct { seq: u64, idx: u32 },+ input_source_changed: struct { seq: u64, input_sources: InputSourcesData },config_loaded: ConfigLoadedEvent,polkit_prompt_opened: PolkitPromptEvent,polkit_prompt_closed: PolkitPromptEvent,diff --git a/src/ipc/protocol_params.zig b/src/ipc/protocol_params.zigindex de47a38..bbe3f70 100644--- a/src/ipc/protocol_params.zig+++ b/src/ipc/protocol_params.zig@@ -246,6 +246,16 @@ pub fn parseActionParams(allocator: std.mem.Allocator, command_tag: commands.Rou};return .{ .switch_layout = target };},+ .switch_input_source => {+ const p = params orelse return error.InvalidRequest;+ const value = p.get("source") orelse return error.InvalidRequest;+ const target: LayoutTarget = switch (value) {+ .string => |name| if (std.ascii.eqlIgnoreCase(name, "next")) .next else if (std.ascii.eqlIgnoreCase(name, "prev")) .prev else return error.InvalidRequest,+ .integer => |idx| .{ .index = std.math.cast(u32, idx) orelse return error.InvalidRequest },+ else => return error.InvalidRequest,+ };+ return .{ .switch_input_source = target };+ },.focus_window => {const p = params orelse return error.InvalidRequest;const id_v = p.get("id") orelse p.get("window_id") orelse return error.InvalidRequest;diff --git a/src/ipc/protocol_results.zig b/src/ipc/protocol_results.zigindex c2d9bdb..561f536 100644--- a/src/ipc/protocol_results.zig+++ b/src/ipc/protocol_results.zig@@ -325,6 +325,22 @@ pub const KeyboardLayoutsData = struct {pub const LayoutTarget = union(enum) { next, prev, index: u32 };+/// One keyboard layout ("xkb") or Fcitx input method ("fcitx").+pub const InputSourceData = struct {+ kind: []const u8,+ id: []const u8,+ name: []const u8,+ label: []const u8,+};++pub const InputSourcesData = struct {+ sources: []const InputSourceData = &.{},+ active: ?u32 = null,+ /// The active keyboard layout's index among the sources.+ active_layout: ?u32 = null,+ fcitx_running: bool = false,+};+pub const ConfigLoadedEvent = struct {seq: u64,generation: u64,diff --git a/src/ipc/protocol_stringify.zig b/src/ipc/protocol_stringify.zigindex fec7872..9d2130f 100644--- a/src/ipc/protocol_stringify.zig+++ b/src/ipc/protocol_stringify.zig@@ -58,6 +58,9 @@ pub fn stringifyResponsePayload(payload: ResponsePayload, writer: anytype) !voidtry writer.print("{f}", .{std.json.fmt(v, .{})});try writer.writeByte('}');},+ .input_sources => |data| {+ try writer.print("{{\"InputSources\":{f}}}", .{std.json.fmt(data, .{})});+ },.keyboard_layouts => |layouts| {try writer.print("{{\"KeyboardLayouts\":{f}}}", .{std.json.fmt(layouts, .{})});},@@ -678,11 +681,12 @@ pub fn stringifyNotifications(n: GetNotificationsResult, writer: anytype) !voidpub fn stringifyEvent(event: Event, writer: anytype) !void {switch (event) {- inline .window_urgency_changed, .keyboard_layouts_changed, .keyboard_layout_switched, .config_loaded => |ev, tag| {+ inline .window_urgency_changed, .keyboard_layouts_changed, .keyboard_layout_switched, .input_source_changed, .config_loaded => |ev, tag| {const name = comptime switch (tag) {.window_urgency_changed => "WindowUrgencyChanged",.keyboard_layouts_changed => "KeyboardLayoutsChanged",.keyboard_layout_switched => "KeyboardLayoutSwitched",+ .input_source_changed => "InputSourceChanged",.config_loaded => "ConfigLoaded",else => unreachable,};diff --git a/src/ipc_serializers.jsonl b/src/ipc_serializers.jsonlindex 2d7860b..d673eef 100644--- a/src/ipc_serializers.jsonl+++ b/src/ipc_serializers.jsonl@@ -90,6 +90,8 @@{"Ok":{"TextInput":{"input_method":{"connected":true,"active":true,"keyboard_grab":true,"popup_count":7},"focused":{"window_id":7,"enabled":true,"features":7,"content_purpose":7,"content_hint":7,"cursor_rectangle":{"x":7,"y":7,"width":7,"height":7},"surrounding_bytes":7,"pending":true},"popups":[{"mapped":true,"visible":true,"x":7,"y":7,"width":7,"height":7,"output":"text \"quoted\"\n\\"}]}}}{"Ok":{"KeyboardLayouts":{"names":["text \"quoted\"\n\\"],"current_idx":null}}}{"Ok":{"KeyboardLayouts":{"names":["text \"quoted\"\n\\"],"current_idx":7}}}+{"Ok":{"InputSources":{"sources":[{"kind":"text \"quoted\"\n\\","id":"text \"quoted\"\n\\","name":"text \"quoted\"\n\\","label":"text \"quoted\"\n\\"}],"active":null,"active_layout":null,"fcitx_running":false}}}+{"Ok":{"InputSources":{"sources":[{"kind":"text \"quoted\"\n\\","id":"text \"quoted\"\n\\","name":"text \"quoted\"\n\\","label":"text \"quoted\"\n\\"}],"active":7,"active_layout":7,"fcitx_running":true}}}{"Ok":{"ListPanels":{"panels":[{"name":"text \"quoted\"\n\\","open":false,"box":null}]}}}{"Ok":{"ListPanels":{"panels":[{"name":"text \"quoted\"\n\\","open":true,"box":{"x":7,"y":7,"width":7,"height":7}}]}}}{"Ok":{"ClickWidget":{"point":{"x":0,"y":0},"x":0,"y":0}}}diff --git a/src/ipc_tests.zig b/src/ipc_tests.zigindex e915c98..6732e3b 100644--- a/src/ipc_tests.zig+++ b/src/ipc_tests.zig@@ -283,7 +283,7 @@ test "every v1 command parses" {\\"condition":"menu_opened","timeout_ms":42,"seconds":2,"enabled":true,\\"blank_after_seconds":600,"suspend_after_seconds":0,"desktop_id":"example.desktop",\\"action":"toggle_split","action_key":"default","phase":"begin","scale":1.2,"rotation":0,- \\"fingers":2,"cancelled":false,"layout":"next","path":"start_menu/settings","at":0.5,+ \\"fingers":2,"cancelled":false,"layout":"next","source":"next","path":"start_menu/settings","at":0.5,\\"service":"alpha.service","mode":"on","event":"bell","color":"#aabbcc","workspace":2,"automatic":true,"gap":12,"apps":["utility*"]};inline for (protocol.commands.specs) |s| {@@ -334,6 +334,10 @@ test "layout switch validates targets" {try std.testing.expectError(error.InvalidRequest, protocol.parseRequest(a, json));}try std.testing.expectError(error.InvalidRequest, protocol.parseRequest(a, "{\"version\":1,\"command\":\"switch_layout\",\"params\":{}}"));+ const source = try protocol.parseRequest(a, "{\"version\":1,\"command\":\"switch_input_source\",\"params\":{\"source\":2}}");+ try std.testing.expectEqual(@as(u32, 2), source.action.switch_input_source.index);+ try std.testing.expectEqual(protocol.LayoutTarget.prev, (try protocol.parseRequest(a, "{\"version\":1,\"command\":\"switch_input_source\",\"params\":{\"source\":\"prev\"}}")).action.switch_input_source);+ try std.testing.expectError(error.InvalidRequest, protocol.parseRequest(a, "{\"version\":1,\"command\":\"switch_input_source\",\"params\":{\"source\":\"first\"}}"));}test "urgency event has stable window identity and boolean state" {diff --git a/src/keyboard/process.zig b/src/keyboard/process.zigindex 7723bf0..7fe5fa6 100644--- a/src/keyboard/process.zig+++ b/src/keyboard/process.zig@@ -121,7 +121,7 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state}for (keyboard.bindingSyms(keycode)) |sym| {const action = keyboard.server.config.lookupKeybind(wlr_keyboard.getModifiers(), sym) orelse continue;- if (!keybinds.isHardwareAction(action)) continue;+ if (!keybinds.isHardwareAction(action) and !(keyboard.server.locker != null and keybinds.worksWhileLocked(action))) continue;keyboard.stopRepeat();keyboard.hardware_consumed[event_keycode] = true;keyboard.server.executeAction(action);diff --git a/src/msg/main.zig b/src/msg/main.zigindex d8f9969..30dcdb8 100644--- a/src/msg/main.zig+++ b/src/msg/main.zig@@ -329,6 +329,7 @@ pub fn runMsg(init: std.process.Init, allocator: std.mem.Allocator) !void {.match_window_rules => try printUnwrappedJson(ok_val, "MatchWindowRules"),.shell_state => try printUnwrappedJson(ok_val, "ShellState"),.keyboard_layouts => try printUnwrappedJson(ok_val, "KeyboardLayouts"),+ .input_sources => try printUnwrappedJson(ok_val, "InputSources"),.text_input => try printUnwrappedJson(ok_val, "TextInput"),.input_state => try printUnwrappedJson(ok_val, "InputState"),.hit_test => try printUnwrappedJson(ok_val, "HitTest"),diff --git a/src/msg/msg_cli.zig b/src/msg/msg_cli.zigindex 6fcbe55..c9540c0 100644--- a/src/msg/msg_cli.zig+++ b/src/msg/msg_cli.zig@@ -33,6 +33,8 @@ pub const Command = union(enum) {text_input,keyboard_layouts,switch_layout: protocol.LayoutTarget,+ input_sources,+ switch_input_source: protocol.LayoutTarget,hit_test: struct { x: i32, y: i32, output: ?[]const u8 = null },scene_tree: struct { max_depth: ?u32 = null },layers,diff --git a/src/msg/msg_parse.zig b/src/msg/msg_parse.zigindex 670ed58..8872939 100644--- a/src/msg/msg_parse.zig+++ b/src/msg/msg_parse.zig@@ -110,6 +110,17 @@ pub fn parseCommand(cli: FlagParser, arg: []const u8) !void {opts.command = .{ .switch_layout = if (std.ascii.eqlIgnoreCase(value, "next")) .next else if (std.ascii.eqlIgnoreCase(value, "prev")) .prev else .{ .index = std.fmt.parseInt(u32, value, 10) catch return error.InvalidArguments } };arg_idx.* += 1;},+ .get_input_sources => {+ opts.command = .input_sources;+ arg_idx.* += 1;+ },+ .switch_input_source => {+ arg_idx.* += 1;+ if (arg_idx.* >= raw_args.len) return error.InvalidArguments;+ const value = std.mem.span(raw_args[arg_idx.*]);+ opts.command = .{ .switch_input_source = if (std.ascii.eqlIgnoreCase(value, "next")) .next else if (std.ascii.eqlIgnoreCase(value, "prev")) .prev else .{ .index = std.fmt.parseInt(u32, value, 10) catch return error.InvalidArguments } };+ arg_idx.* += 1;+ },.get_text_input => {opts.command = .text_input;arg_idx.* += 1;diff --git a/src/msg/msg_reply.zig b/src/msg/msg_reply.zigindex c1c3ec6..4d89f79 100644--- a/src/msg/msg_reply.zig+++ b/src/msg/msg_reply.zig@@ -527,6 +527,8 @@ pub fn printTextReply(val: std.json.Value) void {}} else if (obj.get("KeyboardLayouts")) |state| {printOut("Keyboard layouts:\n{f}\n", .{std.json.fmt(state, .{ .whitespace = .indent_2 })});+ } else if (obj.get("InputSources")) |state| {+ printOut("Input sources:\n{f}\n", .{std.json.fmt(state, .{ .whitespace = .indent_2 })});} else if (obj.get("TextInput")) |state| {printOut("Text input:\n{f}\n", .{std.json.fmt(state, .{ .whitespace = .indent_2 })});} else if (obj.get("Notifications")) |notif_val| {diff --git a/src/msg/msg_request.zig b/src/msg/msg_request.zigindex b5600f8..89f899b 100644--- a/src/msg/msg_request.zig+++ b/src/msg/msg_request.zig@@ -247,6 +247,17 @@ pub fn buildRequest(allocator: std.mem.Allocator, command: Command) !std.ArrayLi}try bw.writeAll("}}\n");},+ .input_sources => try req_buf.appendSlice(allocator, "{\"version\":1,\"command\":\"get_input_sources\"}\n"),+ .switch_input_source => |target| {+ const bw = protocol.BufferWriter{ .list = &req_buf, .allocator = allocator };+ try bw.writeAll("{\"version\":1,\"command\":\"switch_input_source\",\"params\":{\"source\":");+ switch (target) {+ .next => try bw.writeAll("\"next\""),+ .prev => try bw.writeAll("\"prev\""),+ .index => |idx| try bw.print("{d}", .{idx}),+ }+ try bw.writeAll("}}\n");+ },.text_input => try req_buf.appendSlice(allocator, "{\"version\":1,\"command\":\"get_text_input\"}\n"),.input_state => try req_buf.appendSlice(allocator, "{\"version\":1,\"command\":\"get_input_state\"}\n"),.hit_test => |p| {diff --git a/src/output/panels.zig b/src/output/panels.zigindex 5086523..262d121 100644--- a/src/output/panels.zig+++ b/src/output/panels.zig@@ -129,6 +129,12 @@ pub fn openNetworkSettings(output: *Output) void {if (output.server.input.open_control_center) |cc| cc.selectPage(.network);}+/// Opens Settings on its Input page (the input source list).+pub fn openInputSettings(output: *Output) void {+ output.toggleControlCenter();+ if (output.server.input.open_control_center) |cc| cc.selectPage(.input);+}+/// Closes the settings window, like its titlebar close button.pub fn closeControlCenter(output: *Output) void {const cc = output.server.input.open_control_center orelse return;diff --git a/src/server/session.zig b/src/server/session.zigindex 136049b..a8e5409 100644--- a/src/server/session.zig+++ b/src/server/session.zig@@ -164,6 +164,7 @@ pub fn startDesktopService(server: *Server, step: usize) bool {}}},+ 5 => if (server.input_sources) |sources| sources.startServices(),else => return false,}return true;diff --git a/src/server/setup.zig b/src/server/setup.zigindex b22a410..14fc4db 100644--- a/src/server/setup.zig+++ b/src/server/setup.zig@@ -230,6 +230,11 @@ fn initSession(server: *Server, world_tree: *sn.Tree) CompositorError!void {errdefer server.launch_feedback.deinit();server.text_input = @import("../input/text_input.zig").create(server) catch return error.TextInputManagerCreateFailed;errdefer if (server.text_input) |relay| relay.destroy();+ server.input_sources = @import("../input_sources.zig").Manager.create(server) catch null;+ errdefer if (server.input_sources) |sources| {+ server.input_sources = null;+ sources.deinit();+ };server.idle = idle_mod.IdleManager.create(server, server.config.idle) catch |err| blk: {log.warn("init: could not create idle manager: {}", .{err});diff --git a/src/server/teardown.zig b/src/server/teardown.zigindex 0236790..02ab6a8 100644--- a/src/server/teardown.zig+++ b/src/server/teardown.zig@@ -80,6 +80,10 @@ pub fn deinit(server: *Server) void {relay.destroy();server.text_input = null;}+ if (server.input_sources) |sources| {+ server.input_sources = null;+ sources.deinit();+ }server.new_output.link.remove();server.new_layer.link.remove();diff --git a/src/session/lock.zig b/src/session/lock.zigindex 60fb454..709e356 100644--- a/src/session/lock.zig+++ b/src/session/lock.zig@@ -86,6 +86,10 @@ pub const Lock = struct {avatar: ?png.Image = null,/// Volume and brightness sliders; none in the greeter.controls: Controls = .{},+ /// The active keyboard layout's text for the layout button; empty hides+ /// it (one layout, or the greeter). Copied, so painting needs no server.+ layout_label: [24]u8 = undefined,+ layout_label_len: u8 = 0,pub fn start(server: *Server) void {if (server.locker != null) return;@@ -137,6 +141,7 @@ pub const Lock = struct {server.switcher.cancel();server.screenshot_selector.cancel();server.locker = self;+ self.refreshLayoutLabel();if (server.bluetooth) |bluetooth| bluetooth.closed();if (server.input.open_control_center) |cc| {cc.bluetooth.clearPin();@@ -291,6 +296,8 @@ pub const Lock = struct {pub const changed = lock_events.changed;pub const themeChanged = lock_events.themeChanged;+ pub const inputSourceChanged = lock_events.inputSourceChanged;+ pub const refreshLayoutLabel = lock_events.refreshLayoutLabel;pub const controlsChanged = lock_events.controlsChanged;pub const showControl = lock_events.showControl;pub const showControls = lock_events.showControls;@@ -332,6 +339,8 @@ pub const unlock_hint = "Press Enter to unlock";pub const login_hint = "Press Enter to log in";pub const focus_account: u8 = 5;pub const focus_session: u8 = 6;+/// The keyboard layout button (`lock_view.layoutButtonShown`).+pub const focus_layout: u8 = 7;const lock_view = @import("lock_view.zig");pub const Geometry = lock_view.Geometry;diff --git a/src/session/lock_events.zig b/src/session/lock_events.zigindex 2a927a7..271c957 100644--- a/src/session/lock_events.zig+++ b/src/session/lock_events.zig@@ -16,6 +16,25 @@ pub fn changed(self: *Lock) void {self.server.scheduleFrames();}+/// The active keyboard layout changed: the lock's layout button shows it.+pub fn inputSourceChanged(self: *Lock) void {+ self.refreshLayoutLabel();+ if (self.greeter == null) self.changed();+}++/// Several layouts on the user's lock (never the greeter): passwords are often+/// typed with the wrong one.+pub fn refreshLayoutLabel(self: *Lock) void {+ self.layout_label_len = 0;+ if (self.greeter != null) return;+ const sources = self.server.input_sources orelse return;+ if (sources.layoutCount() < 2) return;+ const label = sources.activeLayoutLabel();+ const n = @min(label.len, self.layout_label.len);+ @memcpy(self.layout_label[0..n], label[0..n]);+ self.layout_label_len = @intCast(n);+}+/// A reskin invalidates both the screen and its small controls raster.pub fn themeChanged(self: *Lock) void {var outputs = self.server.outputs.iterator(.forward);diff --git a/src/session/lock_input.zig b/src/session/lock_input.zigindex 935c966..4ae04cf 100644--- a/src/session/lock_input.zig+++ b/src/session/lock_input.zig@@ -24,6 +24,7 @@ const rediwm_auth_destroy = lock_mod.rediwm_auth_destroy;const focus_account = lock_mod.focus_account;const focus_session = lock_mod.focus_session;const Geometry = lock_mod.Geometry;+const lock_view = @import("lock_view.zig");const field_options = lock_mod.field_options;const powerExited = Lock.powerExited;@@ -105,6 +106,10 @@ pub fn choose(self: *Lock, target: u8, delta: isize) void {/// Tab order; greeter mode adds the account and session choosers.pub fn focusOrder(self: *const Lock, buf: *[7]u8) []const u8 {const greeter = self.greeter orelse {+ if (lock_view.layoutButtonShown(self)) {+ buf[0..6].* = .{ 0, 1, 2, lock_mod.focus_layout, 3, 4 };+ return buf[0..6];+ }buf[0..5].* = .{ 0, 1, 2, 3, 4 };return buf[0..5];};@@ -200,6 +205,7 @@ pub fn activate(self: *Lock, focus: u8) void {switch (focus) {0, 2 => self.submit(),1 => self.reveal = !self.reveal,+ lock_mod.focus_layout => if (self.server.input_sources) |sources| sources.cycleLayouts(),3, 4 => {if (self.power_child != null) return;const reboot = focus == 4;@@ -281,6 +287,13 @@ pub fn click(self: *Lock, x: f64, y: f64) void {self.choose(focus_session, 1);}};+ if (lock_view.layoutButtonShown(self)) {+ const button = geo.layoutButton();+ if (dx >= button.x and dx <= button.x + button.w and dy >= button.y and dy <= button.y + button.h) {+ self.focus = lock_mod.focus_layout;+ self.activate(lock_mod.focus_layout);+ }+ }if (py >= geo.h - 100 * geo.s and py <= geo.h - 20 * geo.s) {if (px >= geo.w - 220 * geo.s and px < geo.w - 120 * geo.s) {self.focus = 3;diff --git a/src/session/lock_tests.zig b/src/session/lock_tests.zigindex ef69c55..0fd9766 100644--- a/src/session/lock_tests.zig+++ b/src/session/lock_tests.zig@@ -554,3 +554,33 @@ test "greeter appearance follows account selection and resets missing or brokentry std.testing.expect(lock.greeter_appearance == null);try std.testing.expectEqual(lock.greeter_default_theme.lock_bg, ui.theme.global.lock_bg);}++test "the lock shows the active keyboard layout only while there are several" {+ var lock = Lock{ .server = undefined, .timer = undefined };+ const width: i32 = 1280;+ const height: i32 = 720;+ const geo = Geometry.init(@floatFromInt(width), @floatFromInt(height));+ const button = geo.layoutButton();+ var counts: [2]usize = undefined;+ for ([_][]const u8{ "", "DE" }, 0..) |label, i| {+ @memcpy(lock.layout_label[0..label.len], label);+ lock.layout_label_len = @intCast(label.len);+ const buf = try Buffer.create(width, height, 1);+ defer buf.base.drop();+ @memset(buf.pixels, 0xff090b12);+ var renderer = ui.paint.Renderer{ .pixels = buf.pixels, .width = buf.width, .height = buf.height, .scale = 1 };+ _ = paint(&renderer, &lock, @floatFromInt(width), @floatFromInt(height), true);+ var changed: usize = 0;+ const x0: usize = @intFromFloat(button.x * geo.s);+ const y0: usize = @intFromFloat(button.y * geo.s);+ for (y0..y0 + @as(usize, @intFromFloat(button.h * geo.s))) |y| {+ for (x0..x0 + @as(usize, @intFromFloat(button.w * geo.s))) |x| {+ if (buf.pixels[y * @as(usize, @intCast(width)) + x] != 0xff090b12) changed += 1;+ }+ }+ counts[i] = changed;+ }+ // One layout draws nothing there; several draw the keyboard and its code.+ try std.testing.expectEqual(@as(usize, 0), counts[0]);+ try std.testing.expect(counts[1] > 50);+}diff --git a/src/session/lock_view.zig b/src/session/lock_view.zigindex de53f36..ea89d24 100644--- a/src/session/lock_view.zig+++ b/src/session/lock_view.zig@@ -62,6 +62,12 @@ pub const Geometry = struct {};}+ /// The keyboard layout button, bottom left, in the same units (the+ /// greeter's session chooser sits there instead).+ pub fn layoutButton(geo: Geometry) text_field.Rect {+ return .{ .x = 30, .y = geo.h / geo.s - 96, .w = 90, .h = 76 };+ }+/// The Unlock / Log In button, in the same units.pub fn submit(geo: Geometry) text_field.Rect {return .{ .x = geo.left / geo.s, .y = geo.top / geo.s + 508, .w = 390, .h = 52 };@@ -291,9 +297,21 @@ pub fn paint(r: *ui.paint.Renderer, lock: *Lock, w: f32, h: f32, clock_24h: bool.label = if (i == 0) i18n.tr("Power") else i18n.tr("Restart"),}, .{ .focused = lock.focus == 3 + i });r.fillRect(w - 120 * s, h - 90 * s, s, 34 * s, .{ .color = ui.theme.global.lock_divider });+ if (layoutButtonShown(lock)) ui.widgets.button.paint(&zoomed, geo.layoutButton(), .{+ .variant = .ghost,+ .size = .sm,+ .stacked = true,+ .leading_icon = .keyboard,+ .label = lock.layout_label[0..lock.layout_label_len],+ }, .{ .focused = lock.focus == lock_mod.focus_layout });return .{ .caret = field.caret, .factor = s };}+/// See `Lock.refreshLayoutLabel`.+pub fn layoutButtonShown(lock: *const Lock) bool {+ return lock.layout_label_len > 0;+}+/// Greeter: account arrows beside the picture, session chooser bottom-left.pub fn paintChoices(r: *ui.paint.Renderer, lock: *const Lock, greeter: *const Greeter, geo: Geometry, h: f32) void {const fg = ui.theme.global.lock_fg;diff --git a/src/taskbar/layout.zig b/src/taskbar/layout.zigindex 071e677..d824d34 100644--- a/src/taskbar/layout.zig+++ b/src/taskbar/layout.zig@@ -176,7 +176,7 @@ pub fn calculateLayout(bar: *Taskbar, window_count: usize) taskbar_items.Layoutconst capture_width: f32 = if (bar.capturing()) @floatFromInt(bar.captureWidth()) else 0;const windows_width = if (window_count == 0) 0 else @as(f32, @floatFromInt(window_count)) * @max(@as(f32, @floatFromInt(chipSize())), ui_theme.global.chip_width) +@as(f32, @floatFromInt(window_count - 1)) * @as(f32, @floatFromInt(chipGap()));- return taskbar_items.arrange(items, @floatFromInt(startButtonLeft()), @floatFromInt(bar.box.width - rightPad()), @as(f32, @floatFromInt(bar.box.width)) / 2, .{ if (bar.battery_state.percent != null) battery_width else 0, @floatFromInt(trayHit()), @floatFromInt(trayHit()), bar.clockColumnWidth(), @floatFromInt(buttonSize()), windows_width, app_width, @floatFromInt(trayHit()), capture_width, @floatFromInt(trayHit()) }, tray_gap, clock_gap);+ return taskbar_items.arrange(items, @floatFromInt(startButtonLeft()), @floatFromInt(bar.box.width - rightPad()), @as(f32, @floatFromInt(bar.box.width)) / 2, .{ if (bar.battery_state.percent != null) battery_width else 0, @floatFromInt(trayHit()), @floatFromInt(trayHit()), bar.clockColumnWidth(), @floatFromInt(buttonSize()), windows_width, app_width, @floatFromInt(trayHit()), capture_width, @floatFromInt(trayHit()), @floatFromInt(trayHit()) }, tray_gap, clock_gap);}pub fn itemBox(bar: *Taskbar, item: taskbar_items.Item) ?wlr.Box {@@ -199,6 +199,7 @@ pub fn trayItem(index: usize) taskbar_items.Item {.wifi => .wifi,.power => .power,.wired => .wired,+ .input_source => .input_source,};}diff --git a/src/taskbar/paint.zig b/src/taskbar/paint.zigindex 2fe36c9..3246ae8 100644--- a/src/taskbar/paint.zig+++ b/src/taskbar/paint.zig@@ -180,24 +180,32 @@ pub fn renderPart(bar: *Taskbar, now_ms: i64, part: Part, origin_x: i32, origin_}if (part == .tray) {const i = part.tray;- const alert = switch (@as(TrayKind, @enumFromInt(i))) {+ const kind: TrayKind = @enumFromInt(i);+ const alert = switch (kind) {.volume => bar.audio_muted,.wifi, .wired => bar.network_offline,- .power => false,+ .power, .input_source => false,};const color = if (alert) blk: {var danger = Color.fromRgba(ui_theme.taskbar(.danger));- if ((@as(TrayKind, @enumFromInt(i)) == .wifi or @as(TrayKind, @enumFromInt(i)) == .wired) and bar.blink_dim) danger.a *= 0.25;+ if ((kind == .wifi or kind == .wired) and bar.blink_dim) danger.a *= 0.25;break :blk danger;} else Color.lerp(Color.tray_icon(), Color.tray_icon_hover(), hover);- const size = 20 * press;- var renderer = @import("ui").paint.Renderer.init(buf.pixels, buf.width, buf.height, scale);- renderer.drawIcon(bar.trayPositions()[i] + @as(f32, @floatFromInt(trayHit())) / 2 - size / 2 - @as(f32, @floatFromInt(origin_x)), @as(f32, @floatFromInt(bar.box.height)) / 2 - size / 2 - @as(f32, @floatFromInt(origin_y)), size, size, .{ .id = switch (@as(TrayKind, @enumFromInt(i))) {- .wifi => .wifi,- .wired => .ethernet,- .volume => if (bar.audio_muted) .volume_muted else .volume,- .power => .power,- }, .color = .{ color.r, color.g, color.b, color.a } });+ const tx = bar.trayPositions()[i] - @as(f32, @floatFromInt(origin_x));+ const hit: f32 = @floatFromInt(trayHit());+ if (kind == .input_source) {+ paintSourceLabel(bar, buf, tx, @as(f32, @floatFromInt(@divTrunc(bar.box.height - trayHit(), 2) - origin_y)), hit, press, color, scale);+ } else {+ const size = 20 * press;+ var renderer = @import("ui").paint.Renderer.init(buf.pixels, buf.width, buf.height, scale);+ renderer.drawIcon(tx + hit / 2 - size / 2, @as(f32, @floatFromInt(bar.box.height)) / 2 - size / 2 - @as(f32, @floatFromInt(origin_y)), size, size, .{ .id = switch (kind) {+ .wifi => .wifi,+ .wired => .ethernet,+ .volume => if (bar.audio_muted) .volume_muted else .volume,+ .power => .power,+ .input_source => unreachable,+ }, .color = .{ color.r, color.g, color.b, color.a } });+ }}drawPartText(bar, now_ms, part, buf, origin_x, origin_y);node.node.setPosition(origin_x, origin_y);@@ -218,6 +226,24 @@ pub fn renderPart(bar: *Taskbar, now_ms: i64, part: Part, origin_x: i32, origin_});}+/// The active input source's text ("EN", "あ") centred in its tray target,+/// shrinking for longer labels so three characters and a subscript still fit.+fn paintSourceLabel(bar: *Taskbar, buf: *BarBuffer, x: f32, y: f32, hit: f32, press: f32, color: Color, scale: f32) void {+ const sources = bar.server.input_sources orelse return;+ const label = sources.activeLabel();+ if (label.len == 0) return;+ const text = @import("ui").text;+ var size: f32 = 13 * press;+ var width = text.measureWidth(label, .manrope_bold, size, scale) catch return;+ const room: i32 = @intFromFloat(hit - 6);+ while (width > room and size > 8) {+ size -= 1;+ width = text.measureWidth(label, .manrope_bold, size, scale) catch return;+ }+ const left: i32 = @intFromFloat(@round(x + (hit - @as(f32, @floatFromInt(width))) / 2));+ Taskbar.drawCenteredText(buf.pixels, buf.width, buf.height, .{ .x = left, .y = @intFromFloat(@round(y)), .w = width + 1, .h = @intFromFloat(hit) }, label, .{ .r = color.r, .g = color.g, .b = color.b, .a = color.a }, scale, .manrope_bold, size) catch {};+}+/// Bilinear sample of an icon raster. `x`/`y` are logical offsets from the/// icon's top-left and `logical` its logical size, so a raster made at the/// output's device size lands exactly on its texels when the placement isdiff --git a/src/taskbar/pointer.zig b/src/taskbar/pointer.zigindex 61522cc..3b695e0 100644--- a/src/taskbar/pointer.zig+++ b/src/taskbar/pointer.zig@@ -24,6 +24,8 @@ const targetEql = Taskbar.targetEql;const markPaintCauseFromTarget = Taskbar.markPaintCauseFromTarget;const trayItem = Taskbar.trayItem;+const source_scroll_step: f32 = 60;+pub fn hitTest(bar: *Taskbar, sx: f64, sy: f64) Target {const bh = bar.box.height;if (sy < 0 or sy >= @as(f64, @floatFromInt(bh))) return .none;@@ -145,6 +147,10 @@ pub fn pointerPress(bar: *Taskbar, sx: f64, sy: f64) void {if (@as(TrayKind, @enumFromInt(i)) == .wired) {if (Output.fromWlr(bar.wlr_output)) |out| out.openNetworkSettings();}+ if (@as(TrayKind, @enumFromInt(i)) == .input_source) {+ const x = bar.box.x + @as(i32, @intFromFloat(@round(bar.trayPositions()[i])));+ bar.server.input.window_menu.openSources(bar, x);+ }if (@as(TrayKind, @enumFromInt(i)) == .power) {if (Output.fromWlr(bar.wlr_output)) |out| out.openPowerMenu();}@@ -166,14 +172,28 @@ pub fn pointerPress(bar: *Taskbar, sx: f64, sy: f64) void {if (did_mutate) bar.wlr_output.scheduleFrame();}-/// Scroll wheel over the volume tray icon: ±`volume_scroll_step` per tick.-/// Called from Input.processAxis's scroll-hit switch — the taskbar itself-/// has no other scrollable surface, so this is the only scroll case it needs.-pub fn scrollVolume(bar: *Taskbar, sx: f64, sy: f64, delta_px: f32) void {+/// Scroll wheel over the volume tray icon: ±`volume_scroll_step` per tick;+/// over the input source item, the next or previous source per notch (a+/// touchpad steps every `source_scroll_step` px). Called from+/// Input.processAxis's scroll-hit switch.+pub fn scrollVolume(bar: *Taskbar, sx: f64, sy: f64, delta_px: f32, notch: bool) void {const idx = switch (bar.hitTest(sx, sy)) {.tray => |i| i,else => return,};+ if (@as(TrayKind, @enumFromInt(idx)) == .input_source) {+ const sources = bar.server.input_sources orelse return;+ if (notch) {+ if (delta_px != 0) sources.cycle(delta_px > 0);+ return;+ }+ bar.source_scroll += delta_px;+ while (@abs(bar.source_scroll) >= source_scroll_step) {+ sources.cycle(bar.source_scroll > 0);+ bar.source_scroll -= std.math.copysign(source_scroll_step, bar.source_scroll);+ }+ return;+ }if (@as(TrayKind, @enumFromInt(idx)) != .volume) return;const mgr = bar.server.audio orelse return;// Natural convention: scrolling up (negative delta) raises volume.diff --git a/src/taskbar/tick.zig b/src/taskbar/tick.zigindex 0e3e3a2..936d4f0 100644--- a/src/taskbar/tick.zig+++ b/src/taskbar/tick.zig@@ -189,5 +189,5 @@ pub fn appendLive(pub fn trayPositions(bar: *Taskbar) [tray_count]f32 {const positions = bar.rightLayout().x;- return .{ positions[@intFromEnum(taskbar_items.Item.volume)] orelse 0, positions[@intFromEnum(taskbar_items.Item.wifi)] orelse 0, positions[@intFromEnum(taskbar_items.Item.power)] orelse 0, positions[@intFromEnum(taskbar_items.Item.wired)] orelse 0 };+ return .{ positions[@intFromEnum(taskbar_items.Item.volume)] orelse 0, positions[@intFromEnum(taskbar_items.Item.wifi)] orelse 0, positions[@intFromEnum(taskbar_items.Item.power)] orelse 0, positions[@intFromEnum(taskbar_items.Item.wired)] orelse 0, positions[@intFromEnum(taskbar_items.Item.input_source)] orelse 0 };}diff --git a/src/taskbar/window_menu.zig b/src/taskbar/window_menu.zigindex 6d733ce..764975a 100644--- a/src/taskbar/window_menu.zig+++ b/src/taskbar/window_menu.zig@@ -1,4 +1,5 @@-//! The taskbar's window actions. Input owns one menu across all outputs.+//! The taskbar's window actions, and the input source list its keyboard+//! layout item opens. Input owns one menu across all outputs.const i18n = @import("i18n");const std = @import("std");const wlr = @import("wlroots");@@ -31,6 +32,10 @@ pub const Menu = struct {visible_rows: usize = 0,picker_arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator),picker_root: ui.layout.Widget = .{ .kind = .container },+ /// The input source list (`openSources`): one row per source, then Settings.+ sources: bool = false,+ source_count: usize = 0,+ anchor_x: i32 = 0,const padding = 6;const row_height = 32;@@ -60,19 +65,54 @@ pub const Menu = struct {pub fn open(self: *Menu, bar: *Taskbar, target: *Toplevel, x: i32) void {const output = Output.fromWlr(bar.wlr_output) orelse return;- self.openOn(output, bar, null, target, null, null, x, 0, &.{});+ self.openOn(output, bar, null, target, null, null, x, 0, &.{}, 0);+ }++ /// The input sources, anchored above (or below) the taskbar item at `x`.+ pub fn openSources(self: *Menu, bar: *Taskbar, x: i32) void {+ const sources = bar.server.input_sources orelse return;+ const output = Output.fromWlr(bar.wlr_output) orelse return;+ if (self.sources and self.node != null and self.bar == bar) {+ self.close();+ return;+ }+ self.openOn(output, bar, null, null, null, null, x - 140 + @divTrunc(Taskbar.trayHit(), 2), 0, &.{}, sources.sources().len);+ self.anchor_x = x;+ }++ /// The list or the active source changed while it is open.+ pub fn sourcesChanged(self: *Menu) void {+ if (!self.sources or self.node == null) return;+ const bar = self.bar orelse return;+ const count = if (bar.server.input_sources) |s| s.sources().len else 0;+ if (count != self.source_count) {+ // A new height; open again in place, keeping the keyboard selection.+ const selected = self.selected;+ const x = self.anchor_x;+ self.close();+ self.openSources(bar, x);+ if (selected) |i| if (i < self.itemCount()) {+ self.selected = i;+ self.paint();+ };+ return;+ }+ self.paint();}pub fn openDock(self: *Menu, dock: *Dock, target: ?*Toplevel, shortcut: ?Dock.Shortcut, pin: ?[]const u8, x: i32, y: i32) void {- self.openOn(dock.output orelse return, null, dock, target, shortcut, pin, x, y, &.{});+ self.openOn(dock.output orelse return, null, dock, target, shortcut, pin, x, y, &.{}, 0);}pub fn openDockWindows(self: *Menu, dock: *Dock, ids: []const u64, shortcut: ?Dock.Shortcut, x: i32, y: i32) void {- self.openOn(dock.output orelse return, null, dock, null, shortcut, null, x, y, ids);+ self.openOn(dock.output orelse return, null, dock, null, shortcut, null, x, y, ids, 0);}- fn openOn(self: *Menu, output: *Output, bar: ?*Taskbar, dock: ?*Dock, target: ?*Toplevel, shortcut: ?Dock.Shortcut, pin: ?[]const u8, x: i32, pointer_y: i32, ids: []const u64) void {+ /// `sources` > 0 opens the input source list with that many sources.+ fn openOn(self: *Menu, output: *Output, bar: ?*Taskbar, dock: ?*Dock, target: ?*Toplevel, shortcut: ?Dock.Shortcut, pin: ?[]const u8, x: i32, pointer_y: i32, ids: []const u64, sources: usize) void {self.close();+ self.sources = sources > 0;+ self.source_count = sources;const server = output.server;const input = &server.input;if (input.open_start_menu) |other| if (Output.fromWlr(other.wlr_output)) |out| out.closeStartMenu();@@ -82,7 +122,7 @@ pub const Menu = struct {if (input.open_calendar) |other| other.output.closeCalendar();if (server.tray) |tray| tray.closeMenu();const bounds = output.dockAreaBox();- const width = @min(if (ids.len > 0) @as(i32, 360) else 216, bounds.width);+ const width = @min(if (ids.len > 0) @as(i32, 360) else if (self.sources) @as(i32, 280) else 216, bounds.width);self.node = server.overlay_tree.createSceneBuffer(null) catch return;if (ids.len > 0) self.window_ids = gpa.dupe(u64, ids) catch {self.close();@@ -137,10 +177,17 @@ pub const Menu = struct {}pub fn close(self: *Menu) void {+ const was_sources = self.sources and self.node != null;+ const bar = self.bar;if (self.node) |node| node.node.destroy();gpa.free(self.window_ids);self.picker_arena.deinit();self.* = .{};+ if (was_sources) if (bar) |b| {+ b.tray_dirty[@backingInt(Taskbar.TrayKind.input_source)] = true;+ b.markDirty(Taskbar.paint_tray);+ b.wlr_output.scheduleFrame();+ };}pub fn references(self: *const Menu, top: *Toplevel) bool {@@ -156,10 +203,11 @@ pub const Menu = struct {}fn rowGap(self: *const Menu) i32 {- return if (self.window_ids.len > 0) 2 else separator;+ return if (self.window_ids.len > 0 or self.sources) 2 else separator;}fn itemCount(self: *const Menu) usize {+ if (self.sources) return self.source_count + 1;return if (self.window_ids.len > 0) self.window_ids.len else self.actions().len;}@@ -252,6 +300,15 @@ pub const Menu = struct {fn activate(self: *Menu) void {const index = self.selected orelse return;+ if (self.sources) {+ const output = self.output.?;+ const count = self.source_count;+ self.close();+ if (index < count) {+ if (output.server.input_sources) |sources| _ = sources.select(index);+ } else output.openInputSettings();+ return;+ }if (self.window_ids.len > 0) {const top = self.findWindow(self.window_ids[index]);const output = self.output.?;@@ -290,7 +347,7 @@ pub const Menu = struct {renderer.palette = t;const width: f32 = @floatFromInt(self.box.width);renderer.fillRect(0, 0, width, @floatFromInt(self.box.height), .{ .color = if (self.window_ids.len > 0) t.start_menu_bg else t.window_bg, .radius = 12, .border_width = 1, .border_color = t.border });- if (self.window_ids.len > 0) self.paintWindows(&renderer) else for (self.actions(), 0..) |action, i| {+ if (self.sources) self.paintSources(&renderer) else if (self.window_ids.len > 0) self.paintWindows(&renderer) else for (self.actions(), 0..) |action, i| {const y: f32 = @floatFromInt(self.rowY(i));if (i > 0) renderer.fillRect(12, y - 4, @max(0, width - 24), 1, .{ .color = t.border_soft });const row: ui.layout.Widget = .{@@ -310,6 +367,50 @@ pub const Menu = struct {node.node.raiseToTop();}+ /// One row per source: its indicator text in a small badge, its name and a+ /// check on the active one; then a row that opens Settings → Input. Named+ /// rows also serve IPC (`input_sources` panel).+ fn paintSources(self: *Menu, renderer: *ui.paint.Renderer) void {+ self.picker_root = .{ .kind = .container };+ _ = self.picker_arena.reset(.retain_capacity);+ const a = self.picker_arena.allocator();+ const output = self.output.?;+ const manager = output.server.input_sources orelse return;+ const list = manager.sources();+ const count = @min(list.len, self.source_count);+ const active = manager.activeIndex();+ const t = ui.theme.global;+ const width: f32 = @floatFromInt(self.box.width);+ const rows = a.alloc(ui.layout.Widget, count + 1) catch return;+ for (rows, 0..) |*row, index| {+ const y: f32 = @floatFromInt(self.rowY(index));+ const is_source = index < count;+ row.* = .{+ .name = if (is_source) std.fmt.allocPrint(a, "source_{d}", .{index}) catch return else "input_settings",+ .kind = .{ .row = .{ .state = if (self.selected == index) .hover else .idle, .selected = is_source and active == index } },+ .computed_x = padding,+ .computed_y = y,+ .computed_width = @max(0, width - 2 * padding),+ .computed_height = row_height,+ };+ if (index == count and count > 0) renderer.fillRect(12, y - 1, @max(0, width - 24), 1, .{ .color = t.border_soft });+ ui.paint.paint(row, renderer);+ if (!is_source) {+ renderer.drawIcon(18, y + 8, 16, 16, .{ .id = .settings, .color = t.window_fg });+ renderer.drawText(44, y, @max(0, width - 60), row_height, .{ .content = i18n.tr("Input settings…"), .font_size = t.font_size, .color = t.window_fg });+ continue;+ }+ const source = list[index];+ renderer.fillRect(16, y + 6, 36, row_height - 12, .{ .color = t.surface_hover, .radius = 5 });+ const label_w: f32 = @floatFromInt(ui.text.measureWidth(source.label, .manrope_heavy, t.font_size - 1, output.wlr_output.scale) catch 0);+ renderer.drawText(16 + @max(0, (36 - label_w) / 2), y, 36, row_height, .{ .content = source.label, .font_size = t.font_size - 1, .weight = 700, .color = t.window_fg });+ const dim = source.kind == .fcitx and !manager.fcitxRunning();+ renderer.drawText(62, y, @max(0, width - 100), row_height, .{ .content = source.name, .font_size = t.font_size, .color = if (dim) t.dim else t.window_fg });+ if (active == index) renderer.drawIcon(width - 34, y + 8, 16, 16, .{ .id = .checkmark, .color = t.accent });+ }+ self.picker_root = .{ .kind = .container, .computed_width = width, .computed_height = @floatFromInt(self.box.height), .children = rows };+ }+fn paintWindows(self: *Menu, renderer: *ui.paint.Renderer) void {self.picker_root = .{ .kind = .container };_ = self.picker_arena.reset(.retain_capacity);diff --git a/src/ui_tests.zig b/src/ui_tests.zigindex 2bb0158..6744c8b 100644--- a/src/ui_tests.zig+++ b/src/ui_tests.zig@@ -17,6 +17,7 @@ test {_ = @import("config").keymap;_ = @import("input/repeat_keys.zig");_ = @import("input/wheel_debounce.zig");+ _ = @import("input_sources.zig");_ = @import("pointer_identity.zig");_ = @import("pointer_presentation.zig");_ = @import("ui").key_repeat;diff --git a/tests/input_sources.py b/tests/input_sources.pynew file mode 100644index 0000000..bb6a075--- /dev/null+++ b/tests/input_sources.py@@ -0,0 +1,352 @@+#!/usr/bin/env python3+"""Input sources: keyboard layouts and Fcitx5 input methods.++Runs on a private dbus-run-session (the session bus Fcitx would use), with a+fake org.fcitx.Fcitx5 controller; the host's real Fcitx and buses are never+reached. Covers:+- Layout labels (registry language codes, a configured override), the+ automatic taskbar item, its click menu, Super+Shift+Space, IPC switching,+ scrolling over the item and the `rediwm-msg` commands.+- Fcitx read and switch only: its group's methods join the list (keyboards+ left out), switching calls SetCurrentIM / Deactivate, a change made inside+ Fcitx follows from any signal it emits, a group change re-reads the list,+ and the methods go when Fcitx leaves the bus. RediWM never calls a method+ that writes Fcitx's configuration.+- Settings → Input → Input Sources: add from the registry search, reorder+ (the active layout keeps its place by identity), remove, "Show in taskbar".+Requires PyGObject and dbus-run-session.+"""+import json+import os+from pathlib import Path+import re+import select+import subprocess+import sys+import tempfile+import time++sys.path.insert(0, str(Path(__file__).resolve().parent))+from ipc_client import IPCClient, IPCError, ROOT, spawn_compositor, stop_process+from ui_driver import UIDriver++FAKE_FCITX = r'''+import json, sys, warnings+warnings.simplefilter("ignore", DeprecationWarning)+from gi.repository import Gio, GLib++NAME = "org.fcitx.Fcitx5"+XML = """<node><interface name='org.fcitx.Fcitx.Controller1'>+<method name='CurrentInputMethod'><arg type='s' direction='out'/></method>+<method name='SetCurrentIM'><arg type='s' direction='in'/></method>+<method name='Activate'/><method name='Deactivate'/><method name='Toggle'/>+<method name='State'><arg type='i' direction='out'/></method>+<method name='CurrentInputMethodGroup'><arg type='s' direction='out'/></method>+<method name='InputMethodGroupInfo'><arg type='s' direction='in'/><arg type='s' direction='out'/><arg type='a(ss)' direction='out'/></method>+<method name='AvailableInputMethods'><arg type='a(ssssssb)' direction='out'/></method>+<method name='SetInputMethodGroupInfo'><arg type='s' direction='in'/><arg type='s' direction='in'/><arg type='a(ss)' direction='in'/></method>+<method name='AddInputMethodGroup'><arg type='s' direction='in'/></method>+<signal name='InputMethodGroupsChanged'/>+</interface></node>"""+TRAY = "<node><interface name='org.kde.StatusNotifierItem'><signal name='NewIcon'/></interface></node>"++state = {"current": "keyboard-us", "group": ["keyboard-us", "mozc", "pinyin"]}+AVAILABLE = [+ ("keyboard-us", "English (US)", "", "input-keyboard", "us", "en", True),+ ("mozc", "Mozc", "Mozc", "fcitx-mozc", "あ", "ja", True),+ ("pinyin", "Pinyin", "拼音", "fcitx-pinyin", "", "zh_CN", True),+]+conn = Gio.bus_get_sync(Gio.BusType.SESSION)++def emit(path, iface, member):+ conn.emit_signal(None, path, iface, member, None)+ conn.flush_sync()++def call(c, sender, path, iface, method, params, invocation):+ print(json.dumps({"call": method, "args": list(params.unpack())}), flush=True)+ if method == "CurrentInputMethod":+ invocation.return_value(GLib.Variant("(s)", (state["current"],)))+ elif method == "SetCurrentIM":+ state["current"] = params.unpack()[0]+ invocation.return_value(None)+ emit("/StatusNotifierItem", "org.kde.StatusNotifierItem", "NewIcon")+ elif method == "Deactivate":+ state["current"] = state["group"][0]+ invocation.return_value(None)+ emit("/StatusNotifierItem", "org.kde.StatusNotifierItem", "NewIcon")+ elif method == "State":+ invocation.return_value(GLib.Variant("(i)", (1,)))+ elif method == "CurrentInputMethodGroup":+ invocation.return_value(GLib.Variant("(s)", ("Default",)))+ elif method == "InputMethodGroupInfo":+ invocation.return_value(GLib.Variant("(sa(ss))", ("us", [(name, "") for name in state["group"]])))+ elif method == "AvailableInputMethods":+ invocation.return_value(GLib.Variant("(a(ssssssb))", (AVAILABLE,)))+ else:+ invocation.return_value(None)++def on_stdin(channel, cond):+ line = sys.stdin.readline()+ if not line:+ return False+ req = json.loads(line)+ if req["action"] == "external":+ state["current"] = req["method"]+ emit("/StatusNotifierItem", "org.kde.StatusNotifierItem", "NewIcon")+ elif req["action"] == "group":+ state["group"] = req["methods"]+ emit("/controller", "org.fcitx.Fcitx.Controller1", "InputMethodGroupsChanged")+ print(json.dumps({"done": req["action"]}), flush=True)+ return True++GLib.io_add_watch(sys.stdin.fileno(), GLib.IO_IN, on_stdin)+conn.register_object("/controller", Gio.DBusNodeInfo.new_for_xml(XML).interfaces[0], call, None, None)+conn.register_object("/StatusNotifierItem", Gio.DBusNodeInfo.new_for_xml(TRAY).interfaces[0], None, None, None)+Gio.bus_own_name_on_connection(conn, NAME, Gio.BusNameOwnerFlags.NONE, lambda *_: print("ready", flush=True), None)+GLib.MainLoop().run()+'''++KEY_LEFTMETA, KEY_LEFTSHIFT, KEY_SPACE = 125, 42, 57+WRITES = {"SetInputMethodGroupInfo", "AddInputMethodGroup"}+ANSI_RE = re.compile(r'\x1b\[[0-9;]*[mK]')+++def wait_for(predicate, description, timeout=5.0, interval=0.05):+ deadline = time.monotonic() + timeout+ last = None+ while time.monotonic() < deadline:+ last = predicate()+ if last:+ return last+ time.sleep(interval)+ raise AssertionError(f"timed out waiting for {description}")+++class Fake:+ def __init__(self):+ self.process = subprocess.Popen([sys.executable, "-c", FAKE_FCITX], stdout=subprocess.PIPE, stdin=subprocess.PIPE, text=True)+ assert select.select([self.process.stdout], [], [], 5)[0], "fake Fcitx did not start"+ assert self.process.stdout.readline().strip() == "ready"+ self.calls = []++ def drain(self, timeout=0.0):+ while select.select([self.process.stdout], [], [], timeout)[0]:+ line = self.process.stdout.readline()+ if not line:+ break+ value = json.loads(line)+ if "call" in value:+ self.calls.append(value)+ timeout = 0.0+ return self.calls++ def called(self, method, arg=None):+ def check():+ self.drain(0.05)+ return any(c["call"] == method and (arg is None or c["args"] == [arg]) for c in self.calls)+ return check++ def command(self, action, **fields):+ self.process.stdin.write(json.dumps({"action": action, **fields}) + "\n")+ self.process.stdin.flush()+ while True:+ assert select.select([self.process.stdout], [], [], 5)[0], "no reply from fake Fcitx"+ value = json.loads(self.process.stdout.readline())+ if "call" in value:+ self.calls.append(value)+ elif value == {"done": action}:+ return++ def stop(self):+ self.drain()+ self.process.terminate()+ self.process.wait(timeout=5)+++def sources(ipc):+ return ipc.query("get_input_sources")+++def indicator(ipc):+ widgets = ipc.get_widget_tree("taskbar").get("widgets", [])+ return next((w for w in widgets if w.get("path") == "taskbar/input_source"), None)+++def super_shift_space(ipc):+ for code, pressed in ((KEY_LEFTMETA, True), (KEY_LEFTSHIFT, True), (KEY_SPACE, True), (KEY_SPACE, False), (KEY_LEFTSHIFT, False), (KEY_LEFTMETA, False)):+ ipc.key(code, pressed)+ time.sleep(0.02)+++def active_is(ipc, index, label=None):+ def check():+ data = sources(ipc)+ if data["active"] != index:+ return False+ widget = indicator(ipc)+ return label is None or (widget is not None and widget.get("label") == label)+ return check+++def test_switching(tmp):+ config = '[input]\nxkb_layout = "us,de,jp"\nxkb_labels = ",,JP"\n'+ process, log = spawn_compositor(tmp, config_content=config)+ fake = None+ try:+ with IPCClient(tmp, timeout=15) as ipc:+ ipc.wait_for("wallpaper_presented", timeout_ms=10000)+ ui = UIDriver(ipc)+ # The registry loads on a worker; labels settle when it is done.+ data = wait_for(lambda: (lambda d: d if [s["label"] for s in d["sources"]] == ["EN", "DE", "JP"] else None)(sources(ipc)), "layout labels")+ assert [s["kind"] for s in data["sources"]] == ["xkb"] * 3 and data["active"] == 0, data+ assert data["sources"][1]["id"] == "de" and data["sources"][1]["name"] == "German", data+ assert data["fcitx_running"] is False+ assert wait_for(lambda: indicator(ipc), "automatic indicator")["label"] == "EN"++ # The taskbar item opens the list; a row switches.+ ipc.click_widget(path="taskbar/input_source")+ ipc.wait_for_widget_present("input_sources/source_1")+ assert ui.find("input_settings", panel="input_sources")+ ipc.click_widget(path="input_sources/source_1")+ wait_for(active_is(ipc, 1, "DE"), "menu switch to DE")+ ipc.wait_for_widget_absent("input_sources/source_1")++ super_shift_space(ipc)+ wait_for(active_is(ipc, 2, "JP"), "shortcut to JP")+ super_shift_space(ipc)+ wait_for(active_is(ipc, 0, "EN"), "shortcut wraps to EN")+ ipc.action("switch_input_source", {"source": "prev"})+ wait_for(active_is(ipc, 2), "IPC prev")+ try:+ ipc.action("switch_input_source", {"source": 9})+ raise AssertionError("an out-of-range source was accepted")+ except IPCError as err:+ assert "InvalidSourceIndex" in str(err), err++ # Scrolling over the item steps through the sources.+ box = indicator(ipc)["global_box"]+ ipc.move_cursor(box["x"] + box["width"] // 2, box["y"] + box["height"] // 2)+ ipc.scroll(0, 120)+ wait_for(lambda: sources(ipc)["active"] != 2, "scroll switches")++ cli = [str(ROOT / "zig-out/bin/rediwm-msg"), "--socket", str(next(tmp.glob("rediwm-*.sock")))]+ assert json.loads(subprocess.check_output(cli + ["--json", "input-sources"], text=True)) == sources(ipc)+ subprocess.run(cli + ["switch-input-source", "1"], check=True, capture_output=True)+ wait_for(active_is(ipc, 1), "CLI switch")++ # Fcitx joins: its non-keyboard methods follow the layouts.+ fake = Fake()+ data = wait_for(lambda: (lambda d: d if len(d["sources"]) == 5 else None)(sources(ipc)), "Fcitx methods listed")+ assert data["fcitx_running"] is True+ assert [s["id"] for s in data["sources"][3:]] == ["mozc", "pinyin"], data+ assert [s["label"] for s in data["sources"][3:]] == ["あ", "ZH"], data+ assert data["active"] == 1, "keyboard-us in Fcitx keeps RediWM's layout active"++ ipc.action("switch_input_source", {"source": 3})+ wait_for(fake.called("SetCurrentIM", "mozc"), "SetCurrentIM mozc")+ wait_for(active_is(ipc, 3, "あ"), "Mozc active")+ assert sources(ipc)["active_layout"] == 1+ ipc.action("switch_input_source", {"source": 0})+ wait_for(fake.called("Deactivate"), "Deactivate for a layout")+ wait_for(active_is(ipc, 0, "EN"), "layout after Mozc")++ # A switch made inside Fcitx (its own hotkey or tray menu).+ fake.command("external", method="pinyin")+ wait_for(active_is(ipc, 4, "ZH"), "external Fcitx change")+ fake.command("group", methods=["keyboard-us", "mozc"])+ wait_for(lambda: len(sources(ipc)["sources"]) == 4, "group change re-read")+ assert sources(ipc)["active"] == 0, "the vanished method falls back to the layout"++ fake.stop()+ assert not (WRITES & {c["call"] for c in fake.calls}), fake.calls+ fake = None+ data = wait_for(lambda: (lambda d: d if not d["fcitx_running"] else None)(sources(ipc)), "Fcitx gone")+ assert len(data["sources"]) == 3 and data["active"] == 0, data+ assert process.poll() is None+ except Exception:+ print(ANSI_RE.sub("", (tmp / "compositor.log").read_text())[-6000:])+ raise+ finally:+ if fake is not None:+ fake.stop()+ stop_process(process)+ log.close()+ print("input_sources: labels, menu, shortcut, IPC, scroll, CLI and Fcitx read/switch")+++def config_value(tmp, key):+ match = re.search(r'^' + key + r'\s*=\s*"([^"]*)"', (tmp / "rediwm-config.toml").read_text(), re.M)+ return match.group(1) if match else None+++def test_settings(tmp):+ process, log = spawn_compositor(tmp, config_content='[input]\nxkb_layout = "us"\n')+ try:+ with IPCClient(tmp, timeout=15) as ipc:+ ipc.wait_for("wallpaper_presented", timeout_ms=10000)+ ui = UIDriver(ipc)++ def press(name):+ ui.wait_settled("control_center")+ ui.click(ui.scroll_into_view(name), panel="control_center")++ assert indicator(ipc) is None, "one layout shows no automatic indicator"+ ipc.action("open_control_center")+ ui.wait_settled("control_center")+ ui.click("Input", panel="control_center")+ ui.wait_settled("control_center")+ ui.scroll_into_view("input_source_add")+ assert ui.find("input_source_0", panel="control_center")+ assert ui.find("input_source_remove_0", panel="control_center")["is_disabled"] is True++ press("input_source_add")+ ipc.wait_for_widget_present("control_center/input_source_search")+ ipc.type_text("de(nodeadkeys)")+ ipc.wait_for_widget_present("control_center/input_source_result_0")+ ipc.wait_for_widget_absent("control_center/input_source_result_1")+ press("input_source_result_0")+ wait_for(lambda: config_value(tmp, "xkb_layout") == "us,de", "layout saved")+ assert config_value(tmp, "xkb_variant") == ",nodeadkeys"+ wait_for(lambda: len(sources(ipc)["sources"]) == 2, "reloaded with two layouts")+ wait_for(lambda: indicator(ipc), "indicator appears with a second layout")++ # The active layout keeps its place by identity across a reorder.+ ipc.action("switch_input_source", {"source": 1})+ wait_for(active_is(ipc, 1), "German active")+ press("input_source_up_1")+ wait_for(lambda: config_value(tmp, "xkb_layout") == "de,us", "reorder saved")+ assert config_value(tmp, "xkb_variant") == "nodeadkeys,"+ wait_for(lambda: sources(ipc)["sources"][0]["id"] == "de(nodeadkeys)", "reorder reloaded")+ assert sources(ipc)["active"] == 0, sources(ipc)++ press("input_source_remove_0")+ wait_for(lambda: config_value(tmp, "xkb_layout") == "us", "removal saved")+ wait_for(lambda: indicator(ipc) is None, "indicator hides again")++ # "Show in taskbar" → Always keeps it for a single layout.+ press("input_source_show")+ time.sleep(0.2)+ ipc.key_press("Down")+ ipc.key_press("Return")+ wait_for(lambda: '"right:input_source"' in (tmp / "rediwm-config.toml").read_text(), "taskbar item saved as always")+ assert wait_for(lambda: indicator(ipc), "indicator always shown")["label"] == "EN"+ assert process.poll() is None+ except Exception:+ print(ANSI_RE.sub("", (tmp / "compositor.log").read_text())[-6000:])+ raise+ finally:+ stop_process(process)+ log.close()+ print("input_sources: Settings add, reorder by identity, remove and taskbar visibility")+++def main():+ if "--private" not in sys.argv:+ sys.exit(subprocess.call(["dbus-run-session", "--", sys.executable, __file__, "--private"]))+ for test in (test_switching, test_settings):+ with tempfile.TemporaryDirectory(prefix="rediwm-input-sources-") as directory:+ test(Path(directory))+++if __name__ == "__main__":+ main()diff --git a/tests/msg_v1.json b/tests/msg_v1.jsonindex 6f3b038..70761b0 100644--- a/tests/msg_v1.json+++ b/tests/msg_v1.json@@ -1473,5 +1473,52 @@"code": 1,"saved": null}+ },+ {+ "args": [+ "input-sources"+ ],+ "expected": {+ "request": {+ "version": 1,+ "command": "get_input_sources"+ },+ "code": 0,+ "saved": null+ }+ },+ {+ "args": [+ "switch-input-source",+ "next"+ ],+ "expected": {+ "request": {+ "version": 1,+ "command": "switch_input_source",+ "params": {+ "source": "next"+ }+ },+ "code": 0,+ "saved": null+ }+ },+ {+ "args": [+ "switch-input-source",+ "2"+ ],+ "expected": {+ "request": {+ "version": 1,+ "command": "switch_input_source",+ "params": {+ "source": 2+ }+ },+ "code": 0,+ "saved": null+ }}]