diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index d26d10cdcc18..2eab70c1d1c0 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -128,6 +128,88 @@ def refresh(self): state.update(current=entry[0], name=entry[1], label=entry[4], language=entry[5]) return state + def switchable(self, methods): + # With one keyboard method in one group the reading cannot change until the + # configuration does, and Fcitx saves that to the profile being watched. A + # lone composition engine still toggles, and steps aside in password fields. + if len(methods) > 1 or not all(method.startswith("keyboard-") for method in methods): + return True + return len(call(self.bus, "InputMethodGroups")[0]) > 1 + + +def owner_environment(bus): + """The environment and working directory of the process that owns Fcitx's bus name. + + The profile is wherever that process saves it, which a service drop-in can + move without the shell's own environment knowing. + """ + try: + pid = bus.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", + "GetConnectionUnixProcessID", GLib.Variant("(s)", (BUS,)), None, + Gio.DBusCallFlags.NONE, 1000, None).unpack()[0] + with open(f"/proc/{pid}/environ", "rb") as file: + items = file.read().decode(errors="replace").split("\0") + environment = dict(item.split("=", 1) for item in items if "=" in item) + return environment, os.readlink(f"/proc/{pid}/cwd") + except (GLib.Error, OSError, ValueError): + return None + + +def profile_path(owner=None): + # Fcitx's own lookup: FCITX_CONFIG_HOME, else $XDG_CONFIG_HOME/fcitx5, cleaned + # lexically the way Fcitx cleans it before any link is followed. A relative + # path is relative to the working directory. + environment, cwd = owner or (os.environ, os.getcwd()) + home = environment.get("HOME") or os.path.expanduser("~") + if environment.get("FCITX_CONFIG_HOME"): + directory = os.path.join(cwd, environment["FCITX_CONFIG_HOME"]) + else: + # A relative XDG_CONFIG_HOME is relative to the home directory. + directory = os.path.join(home, environment.get("XDG_CONFIG_HOME") or ".config", "fcitx5") + return os.path.join(os.path.normpath(directory), "profile") + + +class ProfileWatch: + """Calls changed() whenever the profile Fcitx saves its configuration to changes. + + The file is located once per Fcitx process, from that process's environment. + The watch follows renamed saves; inotify resolves a linked directory when the + watch is added, so relinking the dotfiles while Fcitx runs is picked up at + its next start. + """ + + def __init__(self, changed): + self.changed = changed + self.monitors = [] + self.bind(None) + + def bind(self, owner): + for monitor in self.monitors: + monitor.cancel() + # A profile linked into dotfiles is saved by replacing the link's target. + path = profile_path(owner) + self.monitors = [Gio.File.new_for_path(watched).monitor_file(Gio.FileMonitorFlags.WATCH_MOVES, None) + for watched in dict.fromkeys([path, os.path.realpath(path)])] + for monitor in self.monitors: + monitor.connect("changed", lambda *_: self.changed()) + + +def follow(bus, changed, presence): + # Fcitx sends no signal when its configuration or current method changes + # (Controller1's InputMethodGroupsChanged stays silent for group edits and + # switches alike), so follow the service's bus name for restarts and the + # profile it saves every configuration change to. + profile = ProfileWatch(changed) + + def owner(present): + presence(present) + if present: + profile.bind(owner_environment(bus)) + changed() + name = Gio.bus_watch_name_on_connection(bus, BUS, Gio.BusNameWatcherFlags.NONE, + lambda *_: owner(True), lambda *_: owner(False)) + return [name, profile] + def watch(bus): previous = None @@ -135,28 +217,77 @@ def watch(bus): loop = GLib.MainLoop() buffer = "" timer = 0 + settle = 0 + polling = False + failed = False + present = True def refresh(): - nonlocal previous + nonlocal previous, polling, failed try: state = indicator.refresh() except GLib.Error: + failed = True indicator.pending = "" indicator.last = "" + # Keep the configured cadence: a timed-out call is not a configuration + # change, and a vanished service is followed by its bus name. state = {"methods": [], "current": "", "name": "", "language": ""} + else: + # A failed group count keeps the reading and the last cadence. + try: + polling = indicator.switchable(state["methods"]) + failed = False + except GLib.Error: + failed = True line = json.dumps(state, ensure_ascii=False) if line != previous: print(line, flush=True) previous = line + # Only a pending click or a group with methods to switch between needs + # reading again on a timer; everything else waits for an event. A failed + # read of a running service is retried, since nothing else would correct it. + def schedule(): + nonlocal timer + if timer: + GLib.source_remove(timer) + timer = 0 + if indicator.pending: + timer = GLib.timeout_add(50, poll) + elif polling: + timer = GLib.timeout_add(500, poll) + elif failed and present: + timer = GLib.timeout_add(2000, poll) + def poll(): nonlocal timer + timer = 0 + refresh() + schedule() + return GLib.SOURCE_REMOVE + + # A save arrives as several file events, and a restarting service as a + # vanish and an appear; read once they settle. + def changed(): + nonlocal settle + if settle: + GLib.source_remove(settle) + settle = GLib.timeout_add(200, settled) + + def settled(): + nonlocal settle + settle = 0 refresh() - timer = GLib.timeout_add(50 if indicator.pending else 500, poll) + schedule() return GLib.SOURCE_REMOVE + def presence(running): + nonlocal present + present = running + def command(source, condition): - nonlocal buffer, timer + nonlocal buffer data = os.read(sys.stdin.fileno(), 4096) if not data: loop.quit() @@ -170,14 +301,16 @@ def command(source, condition): except (GLib.Error, OSError, ValueError, subprocess.CalledProcessError): indicator.pending = "" refresh() - GLib.source_remove(timer) - timer = GLib.timeout_add(50 if indicator.pending else 500, poll) + schedule() return GLib.SOURCE_CONTINUE - # Fcitx's controller has no current-method-changed signal. Keep one bus - # connection open instead of spawning a command on every poll. Polling also - # follows per-application input contexts and recovers after service restarts. + # Fcitx's controller has no current-method-changed signal, so a group with + # more than one method is still read every 500 ms, over one kept-open bus + # connection. That follows per-application input contexts and trigger keys + # pressed inside applications. GLib.io_add_watch(sys.stdin, GLib.IO_IN | GLib.IO_HUP, command) + # Held for as long as the loop runs. + watchers = follow(bus, changed, presence) # noqa: F841 poll() loop.run() diff --git a/docs/input-methods.md b/docs/input-methods.md index 33a6b5aad20f..496fddf9413c 100644 --- a/docs/input-methods.md +++ b/docs/input-methods.md @@ -14,6 +14,8 @@ The ISO carries the extra fields in `omarchy_install.input_method` and `omarchy_ Keyboard selections are persisted as data in `~/.config/omarchy/keyboard-layouts`; `default.hypr.keyboard.selected()` reads them before falling back to installation defaults. Personal Hyprland overrides still take precedence. A save reloads and validates the compositor, aligns the Fcitx group's primary keyboard with the leading layout/variant, and restores the previous configuration and group on failure. Non-Latin selections keep the installer's Latin-leading rule for desktop shortcuts. System console, disk-unlock, and greeter layouts are unchanged. +The bar reads Fcitx through one long-running reader, `default/input-methods/indicator.py`, started by `shell/Commons/InputMethodState.qml`. Fcitx signals neither a method switch nor a configuration change over D-Bus (Controller1's `InputMethodGroupsChanged` stays silent for both), so the reader reads once at startup and again when the `org.fcitx.Fcitx5` bus name changes owner or the profile changes. The profile is `$FCITX_CONFIG_HOME/profile`, else `$XDG_CONFIG_HOME/fcitx5/profile`, located from the environment of the process that owns the bus name each time it appears, so a service drop-in that moves it is followed. The file watch follows saves that rename a new profile into place; a dotfiles directory relinked while Fcitx runs is picked up at Fcitx's next start. It polls every 500 ms only while there is something to switch between: more than one method in the current group, a lone composition engine (which still toggles and steps aside in password fields), or more than one group. A read that fails while the service is running is retried every 2 s. A single-method setup costs no wakeups. + Shortcut defaults reserve Ctrl+Space for Tmux/Herdr, Super+Space for the menu, Super+Shift+Space for the bar, and Super+grave for the console. Hyprland owns Super+I to cycle all selected compositor layouts followed by the configured Fcitx input methods, independently of Fcitx switching keys. With keyboard layouts alone, the same shortcut cycles the compositor layouts, keeping matching devices in sync even without the bar widget. The widget is enabled in the default right-hand bar layout and appears only when more than one input method or keyboard layout is configured. Fcitx handles Zenkaku/Hankaku and Hangul; Henkan activates and Muhenkan deactivates. Ctrl+Space is never a Fcitx toggle: `configure --defaults` removes it from any TriggerKeys list, keeping the user's other keys, and writes Omarchy's list where none exists, since Fcitx's built-in default includes it. Other existing lists, including empty ones, are preserved, and stock generated lists are repaired only while the user still has the single-keyboard default profile. A terminal Ctrl+Space returns to direct input before the following key, with a 300 ms timeout and no D-Bus activation. Wayland and XCB addons do not override the compositor's XKB settings. The migration installs the standard engines and applies conservative defaults. It aligns an untouched Fcitx keyboard profile with the install layout, using the live controller when Fcitx is running. It leaves existing multilingual profiles and working trigger keys alone. Atomic file writes follow configuration symlinks, preserve file modes, and roll back on a failed seed or migration so a retry can complete. Migration bus errors defer profile alignment to the next login and do not restart input. If a pre-update daemon has not discovered a new engine, the migration aligns only its keyboard and prints the setup command. diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index cb8efdfa8e9c..bb58d28d4782 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -153,7 +153,7 @@ def exercise(): state = {"methods": ["keyboard-us", "pinyin"], "current": "keyboard-us", "name": "English", "label": "en", "language": "en"} loop = Mock() loop.run.side_effect = exercise -with patch.object(indicator.GLib, "MainLoop", return_value=loop), patch.object(indicator.GLib, "io_add_watch", side_effect=register), patch.object(indicator.GLib, "timeout_add", return_value=1), patch.object(indicator.GLib, "source_remove"), patch.object(indicator.os, "read", return_value=b"cycle\n"), patch.object(indicator, "snapshot", return_value=state), patch.object(indicator.subprocess, "run", side_effect=[subprocess.CalledProcessError(1, "hyprctl"), subprocess.CompletedProcess([], 0, stdout='{"keyboards": []}')]), patch.object(indicator, "call") as call, patch("builtins.print"): +with patch.object(indicator.GLib, "MainLoop", return_value=loop), patch.object(indicator.GLib, "io_add_watch", side_effect=register), patch.object(indicator.GLib, "timeout_add", return_value=1), patch.object(indicator.GLib, "source_remove"), patch.object(indicator.os, "read", return_value=b"cycle\n"), patch.object(indicator, "snapshot", return_value=state), patch.object(indicator.subprocess, "run", side_effect=[subprocess.CalledProcessError(1, "hyprctl"), subprocess.CompletedProcess([], 0, stdout='{"keyboards": []}')]), patch.object(indicator, "call") as call, patch.object(indicator, "follow"), patch("builtins.print"): indicator.watch(None) assert call.call_args.args[1] == "SetCurrentIM" print("ok - a failed compositor query leaves the bar click reader alive for the next request") @@ -174,6 +174,214 @@ assert indicator.cycle_choice({"methods": ["keyboard-us", "mozc", "hangul"], "cu assert indicator.layout_switches(keyboards, step=-1)[0][-1] == "1" print("ok - cycling back walks the same choices in reverse") +# The reader in a real GLib loop, against a real profile file: Fcitx itself is +# replaced by `live`, which a configuration change edits before saving. +import sys +import tempfile +scratch = tempfile.TemporaryDirectory() +config_home = scratch.name + "/config" +os.makedirs(config_home + "/fcitx5") + +# Saved the way Fcitx and configure.py save it: a new file renamed over the old. +def save(): + path = config_home + "/fcitx5/profile" + with open(path + ".tmp", "w") as file: + file.write("[Groups/0]\nName=Default\n# " + ",".join(live["methods"]) + "\n") + os.replace(path + ".tmp", path) + +live = {"methods": ["keyboard-us"], "current": "keyboard-us", "name": "English", "label": "en", "language": "en"} +save() +groups = ["Default"] +timers, reader, reads, failures, group_failures = [], {}, [0], [0], [0] +real_timeout = indicator.GLib.timeout_add +real_io_add_watch = indicator.GLib.io_add_watch + +def timeout(interval, fn): + timers.append(interval) + return real_timeout(interval, fn) + +def register_reader(source, *args): + # GLib's own loop.run() watches a signal pipe through the same call. + if source is not sys.stdin: + return real_io_add_watch(source, *args) + reader["read"] = args[-1] + return 1 + +# The shell closing stdin is what ends the reader. +def close_stdin(): + with patch.object(indicator.os, "read", return_value=b""): + reader["read"](None, None) + +def snapshot(bus): + reads[0] += 1 + if failures[0]: + failures[0] -= 1 + raise indicator.GLib.Error("timed out") + return dict(live, methods=list(live["methods"])) + +def fake_call(bus, method, args=None): + assert method == "InputMethodGroups", method + if group_failures[0]: + group_failures[0] -= 1 + raise indicator.GLib.Error("timed out") + return (list(groups),) + +# GLib swallows exceptions raised in callbacks, so keep them for the end. +errors = [] +def step(seconds, then): + def run(): + try: + then() + except Exception as error: + errors.append(error) + close_stdin() + return False + real_timeout(int(seconds * 1000), run) + +state_lines = [] +def output(line, flush=False): + state_lines.append(json.loads(line)) + +def methods(): + return state_lines[-1]["methods"] + +def scenario(): + # One method in one group: the startup read is all, until the profile changes. + def single_method_settled(): + assert [line["methods"] for line in state_lines] == [["keyboard-us"]], state_lines + assert 500 not in timers and 50 not in timers, timers + live["methods"] = ["keyboard-us", "mozc"] + save() + step(0.6, after_save) + def after_save(): + assert methods() == ["keyboard-us", "mozc"], state_lines + assert 500 in timers, timers + live["current"] = "mozc" + step(0.7, after_switch) + def after_switch(): + # With two methods, a switch made inside an application is read on the next poll. + assert state_lines[-1]["current"] == "mozc", state_lines + # A save while polling replaces the poll rather than starting a second one. + save() + step(0.4, count_polls) + def count_polls(): + reads[0] = 0 + step(2.0, polls_counted) + def polls_counted(): + assert reads[0] <= 5, f"{reads[0]} reads in 2 s" + live["methods"], live["current"] = ["keyboard-us"], "keyboard-us" + save() + step(0.6, back_to_one) + def back_to_one(): + assert methods() == ["keyboard-us"], state_lines + # A read that fails while the service runs is retried rather than left blank. + failures[0] = 1 + save() + step(0.6, after_failed_read) + def after_failed_read(): + assert methods() == [], state_lines + step(2.4, recovered) + def recovered(): + assert methods() == ["keyboard-us"], state_lines + # A group count that times out keeps the reading on the bar. + group_failures[0] = 1 + save() + step(0.6, after_failed_group_count) + def after_failed_group_count(): + assert methods() == ["keyboard-us"], state_lines + close_stdin() + step(1.0, single_method_settled) + +os.environ.pop("FCITX_CONFIG_HOME", None) +with patch.dict(os.environ, {"XDG_CONFIG_HOME": config_home}), \ + patch.object(indicator, "snapshot", side_effect=snapshot), \ + patch.object(indicator, "call", side_effect=fake_call), \ + patch.object(indicator.Gio, "bus_watch_name_on_connection", return_value=1), \ + patch.object(indicator.GLib, "io_add_watch", side_effect=register_reader), \ + patch.object(indicator.GLib, "timeout_add", side_effect=timeout), \ + patch("builtins.print", side_effect=output): + step(0, scenario) + step(20, lambda: errors.append(AssertionError("timed out")) or close_stdin()) + indicator.watch(None) +assert not errors, errors +print("ok - one input method is read once and again on a profile save, and several are polled for switches") +print("ok - an event during polling replaces the poll, a failed read is retried, and a failed group count keeps the reading") + +# A profile linked into dotfiles is saved by replacing the link's target, which +# the watch on the target sees. +os.makedirs(scratch.name + "/dotfiles") +os.replace(config_home + "/fcitx5/profile", scratch.name + "/dotfiles/profile") +os.symlink("../../dotfiles/profile", config_home + "/fcitx5/profile") +linked = [] +with patch.dict(os.environ, {"XDG_CONFIG_HOME": config_home}): + context = indicator.GLib.MainContext.new() + context.push_thread_default() + profile_watch = indicator.ProfileWatch(lambda: linked.append("changed")) + import time + def pump(seconds): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + context.iteration(False) + time.sleep(0.01) + # Let events from setting up the link go by first. + pump(0.3) + linked.clear() + with open(scratch.name + "/dotfiles/profile.tmp", "w") as file: + file.write("[Groups/0]\n") + os.replace(scratch.name + "/dotfiles/profile.tmp", scratch.name + "/dotfiles/profile") + pump(0.3) + context.pop_thread_default() +assert linked, "a save through a linked profile is seen" +print("ok - a profile linked into dotfiles is watched at its target") + +with patch.dict(os.environ, {"XDG_CONFIG_HOME": "/xdg", "FCITX_CONFIG_HOME": "/fcitx"}): + assert indicator.profile_path() == "/fcitx/profile" + del os.environ["FCITX_CONFIG_HOME"] + assert indicator.profile_path() == "/xdg/fcitx5/profile" +print("ok - the watched profile follows Fcitx's FCITX_CONFIG_HOME override") + +# The profile is the one the Fcitx process saves, whose environment a service +# drop-in can set without the shell knowing; the watch moves there when the +# bus name gains an owner. +os.makedirs(scratch.name + "/daemon/fcitx") +daemon = subprocess.Popen(["sleep", "30"], cwd=scratch.name, + env={"HOME": scratch.name, "FCITX_CONFIG_HOME": "daemon/fcitx"}) +class OwnerBus: + def call_sync(self, name, path, interface, method, args, *rest): + assert method == "GetConnectionUnixProcessID" and args.unpack() == (indicator.BUS,) + return indicator.GLib.Variant("(u)", (daemon.pid,)) +try: + owner = indicator.owner_environment(OwnerBus()) + assert indicator.profile_path(owner) == scratch.name + "/daemon/fcitx/profile", indicator.profile_path(owner) + appeared, watched = {}, [] + real_new_for_path = indicator.Gio.File.new_for_path + def watch_name(bus, name, flags, on_appeared, on_vanished): + appeared["callback"] = on_appeared + return 1 + def recording_new_for_path(path): + watched.append(path) + return real_new_for_path(path) + with patch.object(indicator.Gio, "bus_watch_name_on_connection", side_effect=watch_name), \ + patch.object(indicator.Gio.File, "new_for_path", side_effect=recording_new_for_path): + indicator.follow(OwnerBus(), lambda: None, lambda present: None) + appeared["callback"]() + assert watched[-1] == scratch.name + "/daemon/fcitx/profile", watched +finally: + daemon.kill() + daemon.wait() +print("ok - the watch follows the profile of the process that owns Fcitx's bus name") + +scratch.cleanup() + +groups.append("Second") +with patch.object(indicator, "call", return_value=(groups,)): + assert indicator.Indicator(None).switchable(["keyboard-us"]) + groups.pop() + assert not indicator.Indicator(None).switchable(["keyboard-us"]) + assert indicator.Indicator(None).switchable(["keyboard-us", "mozc"]) + assert indicator.Indicator(None).switchable(["pinyin"]) +print("ok - a second group or a lone composition engine keeps polling, since neither switch has a signal") + PY stubs=$(mktemp -d)