From 023268773706941a1bb839052872e381636ecf8a Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 17:08:23 +0200 Subject: [PATCH 01/17] Poll Fcitx only when there is an input method to switch to Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 75 ++++++++++++++++++++--- docs/input-methods.md | 2 + test/shell.d/input-indicator-test.sh | 91 +++++++++++++++++++++++++++- 3 files changed, 159 insertions(+), 9 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index d26d10cdcc18..48eef95def39 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -128,6 +128,32 @@ 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 method in one group the reading cannot change until the + # configuration does, and Fcitx saves that to the profile being watched. + return len(methods) > 1 or len(call(self.bus, "InputMethodGroups")[0]) > 1 + + +def profile_paths(): + config_home = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config") + profile = os.path.join(config_home, "fcitx5", "profile") + # A dotfile manager may link the profile elsewhere; follow both ends. + return list(dict.fromkeys([profile, os.path.realpath(profile)])) + + +def follow(bus, changed): + # 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. + watchers = [Gio.bus_watch_name_on_connection(bus, BUS, Gio.BusNameWatcherFlags.NONE, + lambda *_: changed(), lambda *_: changed())] + for path in profile_paths(): + monitor = Gio.File.new_for_path(path).monitor_file(Gio.FileMonitorFlags.WATCH_MOVES, None) + monitor.connect("changed", lambda *_: changed()) + watchers.append(monitor) + return watchers + def watch(bus): previous = None @@ -135,28 +161,59 @@ def watch(bus): loop = GLib.MainLoop() buffer = "" timer = 0 + settle = 0 + polling = False def refresh(): - nonlocal previous + nonlocal previous, polling try: state = indicator.refresh() + polling = indicator.switchable(state["methods"]) except GLib.Error: 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": ""} 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. + 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) + def poll(): nonlocal timer + timer = 0 refresh() - timer = GLib.timeout_add(50 if indicator.pending else 500, poll) + 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 + return poll() + def command(source, condition): - nonlocal buffer, timer + nonlocal buffer data = os.read(sys.stdin.fileno(), 4096) if not data: loop.quit() @@ -170,14 +227,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) # noqa: F841 poll() loop.run() diff --git a/docs/input-methods.md b/docs/input-methods.md index 33a6b5aad20f..b871b7eaa30a 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 `~/.config/fcitx5/profile` is saved or the `org.fcitx.Fcitx5` bus name changes owner. It polls every 500 ms only while there is something to switch between: more than one method in the current group, or more than one group. 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..b406dc261f1f 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,95 @@ 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 +config_home = tempfile.mkdtemp() +os.makedirs(config_home + "/fcitx5") +profile = config_home + "/fcitx5/profile" +open(profile, "w").write("[Groups/0]\nName=Default\n") +live = {"methods": ["keyboard-us"], "current": "keyboard-us", "name": "English", "label": "en", "language": "en"} +groups = ["Default"] +lines, timers, reader = [], [], {} +real_timeout = indicator.GLib.timeout_add + +def timeout(interval, fn): + timers.append(interval) + return real_timeout(interval, fn) + +real_io_add_watch = indicator.GLib.io_add_watch +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) + +# 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) + +def scenario(): + # One method in one group: the startup read is all, until the profile changes. + def single_method_settled(): + assert lines == [live["methods"]], lines + assert 500 not in timers and 50 not in timers, timers + live["methods"] = ["keyboard-us", "mozc"] + with open(profile, "w") as file: + file.write("[Groups/0]\nName=Default\n[Groups/0/Items/1]\nName=mozc\n") + step(0.6, after_save) + def after_save(): + assert lines[-1] == ["keyboard-us", "mozc"], 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 + close_stdin() + step(1.0, single_method_settled) + +state_lines = [] +def output(line, flush=False): + state_lines.append(json.loads(line)) + lines.append(state_lines[-1]["methods"]) + +with patch.dict(os.environ, {"XDG_CONFIG_HOME": config_home}), \ + patch.object(indicator, "snapshot", side_effect=lambda bus: dict(live, methods=list(live["methods"]))), \ + patch.object(indicator, "call", side_effect=lambda bus, method, args=None: (list(groups),) if method == "InputMethodGroups" else (_ for _ in ()).throw(AssertionError(method))), \ + 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(10, lambda: errors.append(AssertionError("timed out")) or close_stdin()) + indicator.watch(None) +assert not errors, errors +assert state_lines and state_lines[-1]["current"] == "mozc", state_lines +print("ok - one input method is read once and again on a profile save, and several are polled for switches") + +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"]) +print("ok - a second group keeps a single-method group polled, since a group switch has no signal either") + PY stubs=$(mktemp -d) From 7e4dae68c6d47307c43e4e5ea00ed803ac4a1e49 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 17:24:27 +0200 Subject: [PATCH 02/17] Keep one Fcitx poll, retry failed reads, and follow a relinked profile Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 74 ++++++++++++++++++++----- docs/input-methods.md | 2 +- test/shell.d/input-indicator-test.sh | 82 ++++++++++++++++++++++------ 3 files changed, 126 insertions(+), 32 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index 48eef95def39..af9d3144e882 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -134,25 +134,58 @@ def switchable(self, methods): return len(methods) > 1 or len(call(self.bus, "InputMethodGroups")[0]) > 1 +def config_home(): + return os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config") + + def profile_paths(): - config_home = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config") - profile = os.path.join(config_home, "fcitx5", "profile") + profile = os.path.join(config_home(), "fcitx5", "profile") # A dotfile manager may link the profile elsewhere; follow both ends. return list(dict.fromkeys([profile, os.path.realpath(profile)])) -def follow(bus, changed): +class ProfileWatch: + """Calls changed() whenever the profile Fcitx saves its configuration to changes.""" + + def __init__(self, changed): + self.changed = changed + self.monitors = [] + # Re-resolve when ~/.config/fcitx5 itself is replaced or relinked, which + # the monitors on the old target would never see. + self.parent = Gio.File.new_for_path(config_home()).monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, None) + self.parent.connect("changed", self.parent_changed) + self.bind() + + def bind(self): + for monitor in self.monitors: + monitor.cancel() + self.monitors = [] + for path in profile_paths(): + monitor = Gio.File.new_for_path(path).monitor_file(Gio.FileMonitorFlags.WATCH_MOVES, None) + monitor.connect("changed", self.profile_changed) + self.monitors.append(monitor) + + def profile_changed(self, *_): + # A relinked profile points somewhere new. + self.bind() + self.changed() + + def parent_changed(self, monitor, file, other, event): + if "fcitx5" in (file.get_basename(), other.get_basename() if other else None): + self.profile_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. - watchers = [Gio.bus_watch_name_on_connection(bus, BUS, Gio.BusNameWatcherFlags.NONE, - lambda *_: changed(), lambda *_: changed())] - for path in profile_paths(): - monitor = Gio.File.new_for_path(path).monitor_file(Gio.FileMonitorFlags.WATCH_MOVES, None) - monitor.connect("changed", lambda *_: changed()) - watchers.append(monitor) - return watchers + def owner(present): + presence(present) + changed() + name = Gio.bus_watch_name_on_connection(bus, BUS, Gio.BusNameWatcherFlags.NONE, + lambda *_: owner(True), lambda *_: owner(False)) + return [name, ProfileWatch(changed)] def watch(bus): @@ -163,13 +196,17 @@ def watch(bus): timer = 0 settle = 0 polling = False + failed = False + present = True def refresh(): - nonlocal previous, polling + nonlocal previous, polling, failed try: state = indicator.refresh() polling = indicator.switchable(state["methods"]) + failed = False except GLib.Error: + failed = True indicator.pending = "" indicator.last = "" # Keep the configured cadence: a timed-out call is not a configuration @@ -181,7 +218,8 @@ def refresh(): 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. + # 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: @@ -191,6 +229,8 @@ def schedule(): 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 @@ -210,7 +250,13 @@ def changed(): def settled(): nonlocal settle settle = 0 - return poll() + refresh() + schedule() + return GLib.SOURCE_REMOVE + + def presence(running): + nonlocal present + present = running def command(source, condition): nonlocal buffer @@ -236,7 +282,7 @@ def command(source, condition): # 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) # noqa: F841 + watchers = follow(bus, changed, presence) # noqa: F841 poll() loop.run() diff --git a/docs/input-methods.md b/docs/input-methods.md index b871b7eaa30a..2462313390fa 100644 --- a/docs/input-methods.md +++ b/docs/input-methods.md @@ -14,7 +14,7 @@ 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 `~/.config/fcitx5/profile` is saved or the `org.fcitx.Fcitx5` bus name changes owner. It polls every 500 ms only while there is something to switch between: more than one method in the current group, or more than one group. A single-method setup costs no wakeups. +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 `~/.config/fcitx5/profile` is saved or the `org.fcitx.Fcitx5` bus name changes owner. It also watches `~/.config` for the `fcitx5` directory being replaced or relinked. It polls every 500 ms only while there is something to switch between: more than one method in the current group, 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. diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index b406dc261f1f..6752be23e9fc 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -179,19 +179,26 @@ print("ok - cycling back walks the same choices in reverse") import sys import tempfile config_home = tempfile.mkdtemp() -os.makedirs(config_home + "/fcitx5") -profile = config_home + "/fcitx5/profile" -open(profile, "w").write("[Groups/0]\nName=Default\n") +os.makedirs(config_home + "/first") +os.makedirs(config_home + "/second") +# A dotfile manager's layout: the Fcitx directory is a link into the dotfiles. +os.symlink("first", config_home + "/fcitx5") + +def save(directory="first"): + with open(f"{config_home}/{directory}/profile", "w") as file: + file.write("[Groups/0]\nName=Default\n# " + ",".join(live["methods"]) + "\n") + live = {"methods": ["keyboard-us"], "current": "keyboard-us", "name": "English", "label": "en", "language": "en"} +save() groups = ["Default"] -lines, timers, reader = [], [], {} +timers, reader, reads, failures = [], {}, [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) -real_io_add_watch = indicator.GLib.io_add_watch def register_reader(source, *args): # GLib's own loop.run() watches a signal pipe through the same call. if source is not sys.stdin: @@ -204,6 +211,13 @@ 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"])) + # GLib swallows exceptions raised in callbacks, so keep them for the end. errors = [] def step(seconds, then): @@ -216,44 +230,78 @@ def step(seconds, then): 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 lines == [live["methods"]], lines + 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"] - with open(profile, "w") as file: - file.write("[Groups/0]\nName=Default\n[Groups/0/Items/1]\nName=mozc\n") + save() step(0.6, after_save) def after_save(): - assert lines[-1] == ["keyboard-us", "mozc"], lines + 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 + # Relinking the Fcitx directory moves the watch to the new target. + os.symlink("second", config_home + "/fcitx5.new") + os.replace(config_home + "/fcitx5.new", config_home + "/fcitx5") + step(0.6, relinked) + def relinked(): + live["methods"] = ["keyboard-us", "hangul"] + save("second") + step(0.6, saved_in_new_target) + def saved_in_new_target(): + assert methods() == ["keyboard-us", "hangul"], state_lines close_stdin() step(1.0, single_method_settled) -state_lines = [] -def output(line, flush=False): - state_lines.append(json.loads(line)) - lines.append(state_lines[-1]["methods"]) - with patch.dict(os.environ, {"XDG_CONFIG_HOME": config_home}), \ - patch.object(indicator, "snapshot", side_effect=lambda bus: dict(live, methods=list(live["methods"]))), \ + patch.object(indicator, "snapshot", side_effect=snapshot), \ patch.object(indicator, "call", side_effect=lambda bus, method, args=None: (list(groups),) if method == "InputMethodGroups" else (_ for _ in ()).throw(AssertionError(method))), \ 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(10, lambda: errors.append(AssertionError("timed out")) or close_stdin()) + step(20, lambda: errors.append(AssertionError("timed out")) or close_stdin()) indicator.watch(None) assert not errors, errors -assert state_lines and state_lines[-1]["current"] == "mozc", state_lines 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, and a failed read is retried") +print("ok - relinking the Fcitx configuration directory moves the profile watch") groups.append("Second") with patch.object(indicator, "call", return_value=(groups,)): From ff65b9946ae955ac8c2543778b400d03709eefb5 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 17:59:57 +0200 Subject: [PATCH 03/17] Cover renamed and linked Fcitx profile saves in the indicator test Co-Authored-By: Claude Opus 5.5 --- test/shell.d/input-indicator-test.sh | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index 6752be23e9fc..8b4f5d00aa3b 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -181,12 +181,16 @@ import tempfile config_home = tempfile.mkdtemp() os.makedirs(config_home + "/first") os.makedirs(config_home + "/second") +os.makedirs(config_home + "/third") # A dotfile manager's layout: the Fcitx directory is a link into the dotfiles. os.symlink("first", config_home + "/fcitx5") -def save(directory="first"): - with open(f"{config_home}/{directory}/profile", "w") as file: +# Saved the way Fcitx and configure.py save it: a new file renamed over the old. +def save(directory="first", name="profile"): + path = f"{config_home}/{directory}/{name}" + 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() @@ -285,6 +289,19 @@ def scenario(): step(0.6, saved_in_new_target) def saved_in_new_target(): assert methods() == ["keyboard-us", "hangul"], state_lines + # A profile that is itself a link is watched at its target too. + live["methods"] = ["keyboard-us"] + save("third", "profile.real") + os.symlink("../third/profile.real", config_home + "/second/profile.new") + os.replace(config_home + "/second/profile.new", config_home + "/second/profile") + step(0.6, linked_profile) + def linked_profile(): + assert methods() == ["keyboard-us"], state_lines + live["methods"] = ["keyboard-us", "pinyin"] + save("third", "profile.real") + step(0.6, saved_through_link) + def saved_through_link(): + assert methods() == ["keyboard-us", "pinyin"], state_lines close_stdin() step(1.0, single_method_settled) @@ -301,7 +318,7 @@ with patch.dict(os.environ, {"XDG_CONFIG_HOME": config_home}), \ 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, and a failed read is retried") -print("ok - relinking the Fcitx configuration directory moves the profile watch") +print("ok - relinking the Fcitx directory or the profile moves the watch, and replaced saves are seen") groups.append("Second") with patch.object(indicator, "call", return_value=(groups,)): From 4ff2f59769af380278f04fd8ba3aeffd25222894 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 18:12:44 +0200 Subject: [PATCH 04/17] Watch the Fcitx profile's directories and honor FCITX_CONFIG_HOME Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 46 +++++++++++++++------------- docs/input-methods.md | 2 +- test/shell.d/input-indicator-test.sh | 20 ++++++++++++ 3 files changed, 46 insertions(+), 22 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index af9d3144e882..505321204d27 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -134,14 +134,24 @@ def switchable(self, methods): return len(methods) > 1 or len(call(self.bus, "InputMethodGroups")[0]) > 1 -def config_home(): - return os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config") - - -def profile_paths(): - profile = os.path.join(config_home(), "fcitx5", "profile") - # A dotfile manager may link the profile elsewhere; follow both ends. - return list(dict.fromkeys([profile, os.path.realpath(profile)])) +def profile_path(): + # Fcitx's own lookup: FCITX_CONFIG_HOME, else $XDG_CONFIG_HOME/fcitx5. + directory = os.environ.get("FCITX_CONFIG_HOME") or os.path.join( + os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"), "fcitx5") + return os.path.join(directory, "profile") + + +def watched_entries(): + # Saves rename a new profile into place, and a dotfile manager may link the + # profile or its directory elsewhere, or replace a linked directory. Watch the + # profile's directory and that directory's parent, along both the path as + # written and the path it resolves to, for the one entry each level holds. + entries = [] + for path in dict.fromkeys([profile_path(), os.path.realpath(profile_path())]): + directory = os.path.dirname(path) + entries += [(directory, os.path.basename(path)), + (os.path.dirname(directory), os.path.basename(directory))] + return list(dict.fromkeys(entries)) class ProfileWatch: @@ -150,30 +160,24 @@ class ProfileWatch: def __init__(self, changed): self.changed = changed self.monitors = [] - # Re-resolve when ~/.config/fcitx5 itself is replaced or relinked, which - # the monitors on the old target would never see. - self.parent = Gio.File.new_for_path(config_home()).monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, None) - self.parent.connect("changed", self.parent_changed) self.bind() def bind(self): for monitor in self.monitors: monitor.cancel() self.monitors = [] - for path in profile_paths(): - monitor = Gio.File.new_for_path(path).monitor_file(Gio.FileMonitorFlags.WATCH_MOVES, None) - monitor.connect("changed", self.profile_changed) + for directory, name in watched_entries(): + monitor = Gio.File.new_for_path(directory).monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, None) + monitor.connect("changed", self.entry_changed, name) self.monitors.append(monitor) - def profile_changed(self, *_): - # A relinked profile points somewhere new. + def entry_changed(self, monitor, file, other, event, name): + if name not in (file.get_basename(), other.get_basename() if other else None): + return + # A relinked or replaced entry may resolve somewhere new. self.bind() self.changed() - def parent_changed(self, monitor, file, other, event): - if "fcitx5" in (file.get_basename(), other.get_basename() if other else None): - self.profile_changed() - def follow(bus, changed, presence): # Fcitx sends no signal when its configuration or current method changes diff --git a/docs/input-methods.md b/docs/input-methods.md index 2462313390fa..0099bd669f4f 100644 --- a/docs/input-methods.md +++ b/docs/input-methods.md @@ -14,7 +14,7 @@ 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 `~/.config/fcitx5/profile` is saved or the `org.fcitx.Fcitx5` bus name changes owner. It also watches `~/.config` for the `fcitx5` directory being replaced or relinked. It polls every 500 ms only while there is something to switch between: more than one method in the current group, 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. +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 `~/.config/fcitx5/profile`; the reader watches its directory and that directory's parent, along the path as written and the path it resolves to, so renamed saves and relinked or replaced dotfile directories are seen. It polls every 500 ms only while there is something to switch between: more than one method in the current group, 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. diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index 8b4f5d00aa3b..4f203d44f917 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -302,9 +302,23 @@ def scenario(): step(0.6, saved_through_link) def saved_through_link(): assert methods() == ["keyboard-us", "pinyin"], state_lines + # The directory the link resolves to is replaced, the link left alone. + live["methods"] = ["keyboard-us"] + os.rename(config_home + "/third", config_home + "/third.old") + os.makedirs(config_home + "/third") + save("third", "profile.real") + step(0.6, target_replaced) + def target_replaced(): + assert methods() == ["keyboard-us"], state_lines + live["methods"] = ["keyboard-us", "chewing"] + save("third", "profile.real") + step(0.6, saved_in_replaced_target) + def saved_in_replaced_target(): + assert methods() == ["keyboard-us", "chewing"], 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=lambda bus, method, args=None: (list(groups),) if method == "InputMethodGroups" else (_ for _ in ()).throw(AssertionError(method))), \ @@ -320,6 +334,12 @@ print("ok - one input method is read once and again on a profile save, and sever print("ok - an event during polling replaces the poll, and a failed read is retried") print("ok - relinking the Fcitx directory or the profile moves the watch, and replaced saves are seen") +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") + groups.append("Second") with patch.object(indicator, "call", return_value=(groups,)): assert indicator.Indicator(None).switchable(["keyboard-us"]) From 48196be75bea2a34bc10066c413059c295199ac7 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 18:25:11 +0200 Subject: [PATCH 05/17] Follow every link to the Fcitx profile and keep polling a lone engine Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 26 +++++++++++++++++--------- docs/input-methods.md | 2 +- test/shell.d/input-indicator-test.sh | 23 +++++++++++++++++++++-- 3 files changed, 39 insertions(+), 12 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index 505321204d27..206687902d7b 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -129,9 +129,12 @@ def refresh(self): return state def switchable(self, methods): - # With one method in one group the reading cannot change until the - # configuration does, and Fcitx saves that to the profile being watched. - return len(methods) > 1 or len(call(self.bus, "InputMethodGroups")[0]) > 1 + # 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 profile_path(): @@ -143,14 +146,19 @@ def profile_path(): def watched_entries(): # Saves rename a new profile into place, and a dotfile manager may link the - # profile or its directory elsewhere, or replace a linked directory. Watch the - # profile's directory and that directory's parent, along both the path as - # written and the path it resolves to, for the one entry each level holds. + # profile, its directory or the configuration home elsewhere, or replace a + # linked directory. Watch each directory on the way to the profile for the + # one entry it holds, along the path as written and the path it resolves to, + # up to the home directory. + home = os.path.realpath(os.path.expanduser("~")) entries = [] for path in dict.fromkeys([profile_path(), os.path.realpath(profile_path())]): - directory = os.path.dirname(path) - entries += [(directory, os.path.basename(path)), - (os.path.dirname(directory), os.path.basename(directory))] + directory, name = os.path.split(path) + while name: + entries.append((directory, name)) + if os.path.realpath(directory) == home: + break + directory, name = os.path.split(directory) return list(dict.fromkeys(entries)) diff --git a/docs/input-methods.md b/docs/input-methods.md index 0099bd669f4f..db2cf5a7ba05 100644 --- a/docs/input-methods.md +++ b/docs/input-methods.md @@ -14,7 +14,7 @@ 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 `~/.config/fcitx5/profile`; the reader watches its directory and that directory's parent, along the path as written and the path it resolves to, so renamed saves and relinked or replaced dotfile directories are seen. It polls every 500 ms only while there is something to switch between: more than one method in the current group, 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. +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 `~/.config/fcitx5/profile`; the reader watches every directory on the way to it, up to the home directory, for the one entry each holds, along the path as written and the path it resolves to, so renamed saves and relinked or replaced dotfile directories are seen. 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. diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index 4f203d44f917..a651b49d1db9 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -178,7 +178,11 @@ print("ok - cycling back walks the same choices in reverse") # replaced by `live`, which a configuration change edits before saving. import sys import tempfile -config_home = tempfile.mkdtemp() +# The configuration home is itself a link, as a dotfile manager may make it. +config_root = tempfile.mkdtemp() +os.makedirs(config_root + "/home-a") +os.symlink("home-a", config_root + "/config") +config_home = config_root + "/config" os.makedirs(config_home + "/first") os.makedirs(config_home + "/second") os.makedirs(config_home + "/third") @@ -315,6 +319,20 @@ def scenario(): step(0.6, saved_in_replaced_target) def saved_in_replaced_target(): assert methods() == ["keyboard-us", "chewing"], state_lines + # Relinking the configuration home moves the watch to the new one. + live["methods"] = ["keyboard-us"] + os.makedirs(config_root + "/home-b/fcitx5") + save("../home-b/fcitx5") + os.symlink("home-b", config_root + "/config.new") + os.replace(config_root + "/config.new", config_root + "/config") + step(0.6, home_relinked) + def home_relinked(): + assert methods() == ["keyboard-us"], state_lines + live["methods"] = ["keyboard-us", "anthy"] + save("fcitx5") + step(0.6, saved_in_new_home) + def saved_in_new_home(): + assert methods() == ["keyboard-us", "anthy"], state_lines close_stdin() step(1.0, single_method_settled) @@ -346,7 +364,8 @@ with patch.object(indicator, "call", return_value=(groups,)): groups.pop() assert not indicator.Indicator(None).switchable(["keyboard-us"]) assert indicator.Indicator(None).switchable(["keyboard-us", "mozc"]) -print("ok - a second group keeps a single-method group polled, since a group switch has no signal either") + 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 From 0cf0279066026e0bd7c97b8c3986647904978385 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 18:33:20 +0200 Subject: [PATCH 06/17] Watch every hop of a chained Fcitx profile link Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 28 +++++++++++++++++++++++----- docs/input-methods.md | 2 +- test/shell.d/input-indicator-test.sh | 18 ++++++++++++++++++ 3 files changed, 42 insertions(+), 6 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index 206687902d7b..b7ff0b140e48 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -144,15 +144,33 @@ def profile_path(): return os.path.join(directory, "profile") +def resolution(path, hops=40): + """The path as written, then as it reads after each symlink on the way.""" + paths = [path] + for _ in range(hops): + prefix, parts = "/", path.strip("/").split("/") + for index, part in enumerate(parts): + candidate = os.path.join(prefix, part) + if os.path.islink(candidate): + # The prefix holds no links, so the target's ".." resolves lexically. + path = os.path.normpath(os.path.join(prefix, os.readlink(candidate), *parts[index + 1:])) + paths.append(path) + break + prefix = candidate + else: + break + return paths + + def watched_entries(): # Saves rename a new profile into place, and a dotfile manager may link the - # profile, its directory or the configuration home elsewhere, or replace a - # linked directory. Watch each directory on the way to the profile for the - # one entry it holds, along the path as written and the path it resolves to, - # up to the home directory. + # profile, its directory or the configuration home elsewhere, chain links, or + # replace a linked directory. Watch each directory the lookup passes through + # for the one entry it holds, along every hop of the resolution, up to the + # home directory. home = os.path.realpath(os.path.expanduser("~")) entries = [] - for path in dict.fromkeys([profile_path(), os.path.realpath(profile_path())]): + for path in resolution(profile_path()): directory, name = os.path.split(path) while name: entries.append((directory, name)) diff --git a/docs/input-methods.md b/docs/input-methods.md index db2cf5a7ba05..a13fee0f53a1 100644 --- a/docs/input-methods.md +++ b/docs/input-methods.md @@ -14,7 +14,7 @@ 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 `~/.config/fcitx5/profile`; the reader watches every directory on the way to it, up to the home directory, for the one entry each holds, along the path as written and the path it resolves to, so renamed saves and relinked or replaced dotfile directories are seen. 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. +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 `~/.config/fcitx5/profile`; the reader watches every directory on the way to it, up to the home directory, for the one entry each holds, along the path as written and after each symlink hop, so renamed saves, chained links and relinked or replaced dotfile directories are seen. 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. diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index a651b49d1db9..c481e7651ecf 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -333,6 +333,24 @@ def scenario(): step(0.6, saved_in_new_home) def saved_in_new_home(): assert methods() == ["keyboard-us", "anthy"], state_lines + # A chain of links: profile -> store/current -> store/profile-a. + live["methods"] = ["keyboard-us"] + os.makedirs(config_home + "/store") + save("store", "profile-a") + os.symlink("profile-a", config_home + "/store/current") + os.symlink("../store/current", config_home + "/fcitx5/profile.new") + os.replace(config_home + "/fcitx5/profile.new", config_home + "/fcitx5/profile") + step(0.6, chained) + def chained(): + assert methods() == ["keyboard-us"], state_lines + # Repointing the middle link is seen, though neither end changed. + live["methods"] = ["keyboard-us", "rime"] + save("store", "profile-b") + os.symlink("profile-b", config_home + "/store/current.new") + os.replace(config_home + "/store/current.new", config_home + "/store/current") + step(0.6, middle_relinked) + def middle_relinked(): + assert methods() == ["keyboard-us", "rime"], state_lines close_stdin() step(1.0, single_method_settled) From e4d0cb2f0441b582e2cb98955ebe543178d9b042 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 18:44:57 +0200 Subject: [PATCH 07/17] Resolve the Fcitx profile path one component at a time Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 52 ++++++++++++---------------- docs/input-methods.md | 2 +- test/shell.d/input-indicator-test.sh | 20 +++++++++++ 3 files changed, 44 insertions(+), 30 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index b7ff0b140e48..1e37423257e9 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -144,39 +144,33 @@ def profile_path(): return os.path.join(directory, "profile") -def resolution(path, hops=40): - """The path as written, then as it reads after each symlink on the way.""" - paths = [path] - for _ in range(hops): - prefix, parts = "/", path.strip("/").split("/") - for index, part in enumerate(parts): - candidate = os.path.join(prefix, part) - if os.path.islink(candidate): - # The prefix holds no links, so the target's ".." resolves lexically. - path = os.path.normpath(os.path.join(prefix, os.readlink(candidate), *parts[index + 1:])) - paths.append(path) - break - prefix = candidate - else: - break - return paths - - -def watched_entries(): +def watched_entries(hops=40): # Saves rename a new profile into place, and a dotfile manager may link the # profile, its directory or the configuration home elsewhere, chain links, or - # replace a linked directory. Watch each directory the lookup passes through - # for the one entry it holds, along every hop of the resolution, up to the - # home directory. + # replace a linked directory. Resolve the path the way the kernel does, one + # component at a time, and watch each directory it passes through for the one + # entry it looks up there, from the home directory down. home = os.path.realpath(os.path.expanduser("~")) entries = [] - for path in resolution(profile_path()): - directory, name = os.path.split(path) - while name: - entries.append((directory, name)) - if os.path.realpath(directory) == home: - break - directory, name = os.path.split(directory) + current, pending = "/", profile_path().split("/") + while pending: + part = pending.pop(0) + if part in ("", "."): + continue + if part == "..": + current = os.path.dirname(current) + continue + if not home.startswith(current.rstrip("/") + "/"): + entries.append((current, part)) + candidate = os.path.join(current, part) + if os.path.islink(candidate) and hops > 0: + hops -= 1 + target = os.readlink(candidate) + if target.startswith("/"): + current = "/" + pending = target.split("/") + pending + else: + current = candidate return list(dict.fromkeys(entries)) diff --git a/docs/input-methods.md b/docs/input-methods.md index a13fee0f53a1..c97cd295d451 100644 --- a/docs/input-methods.md +++ b/docs/input-methods.md @@ -14,7 +14,7 @@ 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 `~/.config/fcitx5/profile`; the reader watches every directory on the way to it, up to the home directory, for the one entry each holds, along the path as written and after each symlink hop, so renamed saves, chained links and relinked or replaced dotfile directories are seen. 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. +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 `~/.config/fcitx5/profile`; the reader resolves that path one component at a time, as the kernel does, and watches each directory the lookup passes through (from the home directory down) for the one entry it looks up there, so renamed saves, chained links and relinked or replaced dotfile directories are seen. 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. diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index c481e7651ecf..03ce99fc7222 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -351,6 +351,26 @@ def scenario(): step(0.6, middle_relinked) def middle_relinked(): assert methods() == ["keyboard-us", "rime"], state_lines + # A link whose target steps back out of another link: + # fcitx5 -> store/redirect/../fcitx5, with store/redirect -> ../x/inner. + live["methods"] = ["keyboard-us"] + for side in ("x", "y"): + os.makedirs(f"{config_home}/{side}/inner") + os.makedirs(f"{config_home}/{side}/fcitx5") + save("x/fcitx5") + os.symlink("../x/inner", config_home + "/store/redirect") + os.rename(config_home + "/fcitx5", config_home + "/fcitx5.old") + os.symlink("store/redirect/../fcitx5", config_home + "/fcitx5") + step(0.6, redirected) + def redirected(): + assert methods() == ["keyboard-us"], state_lines + live["methods"] = ["keyboard-us", "sayura"] + save("y/fcitx5") + os.symlink("../y/inner", config_home + "/store/redirect.new") + os.replace(config_home + "/store/redirect.new", config_home + "/store/redirect") + step(0.6, redirect_repointed) + def redirect_repointed(): + assert methods() == ["keyboard-us", "sayura"], state_lines close_stdin() step(1.0, single_method_settled) From 2718bc3e8f0e5e8b1cd7c96e6be93ddd57aa7251 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 18:56:25 +0200 Subject: [PATCH 08/17] Keep Fcitx profile watches through relink races and missing directories Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 21 ++++++++++----- test/shell.d/input-indicator-test.sh | 40 +++++++++++++++++++++++++++- 2 files changed, 54 insertions(+), 7 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index 1e37423257e9..bec9986f1665 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -138,10 +138,11 @@ def switchable(self, methods): def profile_path(): - # Fcitx's own lookup: FCITX_CONFIG_HOME, else $XDG_CONFIG_HOME/fcitx5. + # Fcitx's own lookup: FCITX_CONFIG_HOME, else $XDG_CONFIG_HOME/fcitx5, cleaned + # lexically the way Fcitx cleans it before any link is followed. directory = os.environ.get("FCITX_CONFIG_HOME") or os.path.join( os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"), "fcitx5") - return os.path.join(directory, "profile") + return os.path.join(os.path.normpath(directory), "profile") def watched_entries(hops=40): @@ -163,14 +164,20 @@ def watched_entries(hops=40): if not home.startswith(current.rstrip("/") + "/"): entries.append((current, part)) candidate = os.path.join(current, part) - if os.path.islink(candidate) and hops > 0: + try: + target = os.readlink(candidate) if hops > 0 else None + except OSError: + target = None + if target is not None: hops -= 1 - target = os.readlink(candidate) if target.startswith("/"): current = "/" pending = target.split("/") + pending - else: + elif os.path.lexists(candidate): current = candidate + else: + # Nothing further exists yet; the watch on this entry sees it arrive. + break return list(dict.fromkeys(entries)) @@ -183,10 +190,12 @@ def __init__(self, changed): self.bind() def bind(self): + # Resolve before dropping the old watches, so a failure keeps them. + entries = watched_entries() for monitor in self.monitors: monitor.cancel() self.monitors = [] - for directory, name in watched_entries(): + for directory, name in entries: monitor = Gio.File.new_for_path(directory).monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, None) monitor.connect("changed", self.entry_changed, name) self.monitors.append(monitor) diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index 03ce99fc7222..451fbffc5806 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -394,7 +394,45 @@ with patch.dict(os.environ, {"XDG_CONFIG_HOME": "/xdg", "FCITX_CONFIG_HOME": "/f 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") + os.environ["FCITX_CONFIG_HOME"] = "/fcitx/link/../cleaned" + assert indicator.profile_path() == "/fcitx/cleaned/profile" +print("ok - the watched profile follows Fcitx's FCITX_CONFIG_HOME override, cleaned the way Fcitx cleans it") + +# A link that vanishes mid-resolution, as a relink in progress makes it, is +# watched as an entry rather than failing the whole watch. +race_root = tempfile.mkdtemp() +os.symlink("elsewhere", race_root + "/fcitx5") +with patch.dict(os.environ, {"XDG_CONFIG_HOME": race_root}), \ + patch.object(indicator.os, "readlink", side_effect=FileNotFoundError("relinked")): + assert (race_root, "fcitx5") in indicator.watched_entries() + +# A configuration that does not exist yet is watched from its nearest existing +# directory, and its profile is seen once Fcitx first saves it. +fresh_root = tempfile.mkdtemp() +events = [] +with patch.dict(os.environ, {"XDG_CONFIG_HOME": fresh_root + "/config"}): + assert indicator.watched_entries()[-1] == (fresh_root, "config"), indicator.watched_entries() + # A context of its own, clear of the sources the reader above left behind. + import time + context = indicator.GLib.MainContext.new() + context.push_thread_default() + profile_watch = indicator.ProfileWatch(lambda: events.append("changed")) + def run_until(seconds): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + context.iteration(False) + time.sleep(0.01) + os.makedirs(fresh_root + "/config") + run_until(0.3) + os.makedirs(fresh_root + "/config/fcitx5") + run_until(0.3) + events.clear() + with open(fresh_root + "/config/fcitx5/profile", "w") as file: + file.write("[Groups/0]\n") + run_until(0.3) + assert events, "the first save of a new profile is seen" + context.pop_thread_default() +print("ok - a missing configuration is watched until it exists, and a vanishing link keeps its watch") groups.append("Second") with patch.object(indicator, "call", return_value=(groups,)): From a8ecb782ef19bab01079790ee3f0f0cf5639a080 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 19:04:13 +0200 Subject: [PATCH 09/17] Resolve a relative FCITX_CONFIG_HOME before watching it Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 5 +++-- test/shell.d/input-indicator-test.sh | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index bec9986f1665..e39858bff8c4 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -139,10 +139,11 @@ def switchable(self, methods): def profile_path(): # Fcitx's own lookup: FCITX_CONFIG_HOME, else $XDG_CONFIG_HOME/fcitx5, cleaned - # lexically the way Fcitx cleans it before any link is followed. + # lexically the way Fcitx cleans it before any link is followed. A relative + # path is relative to the working directory. directory = os.environ.get("FCITX_CONFIG_HOME") or os.path.join( os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"), "fcitx5") - return os.path.join(os.path.normpath(directory), "profile") + return os.path.join(os.path.abspath(directory), "profile") def watched_entries(hops=40): diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index 451fbffc5806..f3c2ea67af35 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -396,6 +396,8 @@ with patch.dict(os.environ, {"XDG_CONFIG_HOME": "/xdg", "FCITX_CONFIG_HOME": "/f assert indicator.profile_path() == "/xdg/fcitx5/profile" os.environ["FCITX_CONFIG_HOME"] = "/fcitx/link/../cleaned" assert indicator.profile_path() == "/fcitx/cleaned/profile" + os.environ["FCITX_CONFIG_HOME"] = "relative/fcitx" + assert indicator.profile_path() == os.path.join(os.getcwd(), "relative/fcitx/profile") print("ok - the watched profile follows Fcitx's FCITX_CONFIG_HOME override, cleaned the way Fcitx cleans it") # A link that vanishes mid-resolution, as a relink in progress makes it, is From 0a446ae1c46f65358d0c2095f01dd6664322a349 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 19:15:34 +0200 Subject: [PATCH 10/17] Watch a Fcitx config beside the home directory and re-resolve after arming Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 27 +++++++++++++++++---------- test/shell.d/input-indicator-test.sh | 19 +++++++++++++++++++ 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index e39858bff8c4..dc2083bc8d76 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -162,9 +162,10 @@ def watched_entries(hops=40): if part == "..": current = os.path.dirname(current) continue - if not home.startswith(current.rstrip("/") + "/"): - entries.append((current, part)) candidate = os.path.join(current, part) + # The way down to the home directory changes with a new session, not a save. + if candidate != home and not home.startswith(candidate + "/"): + entries.append((current, part)) try: target = os.readlink(candidate) if hops > 0 else None except OSError: @@ -191,15 +192,21 @@ def __init__(self, changed): self.bind() def bind(self): - # Resolve before dropping the old watches, so a failure keeps them. + # Resolve before dropping the old watches, so a failure keeps them, and + # again once the new ones are armed, in case the path changed in between. entries = watched_entries() - for monitor in self.monitors: - monitor.cancel() - self.monitors = [] - for directory, name in entries: - monitor = Gio.File.new_for_path(directory).monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, None) - monitor.connect("changed", self.entry_changed, name) - self.monitors.append(monitor) + for _ in range(10): + for monitor in self.monitors: + monitor.cancel() + self.monitors = [] + for directory, name in entries: + monitor = Gio.File.new_for_path(directory).monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, None) + monitor.connect("changed", self.entry_changed, name) + self.monitors.append(monitor) + armed, entries = entries, watched_entries() + if entries == armed: + return + # Still moving: whoever is changing it will send another event. def entry_changed(self, monitor, file, other, event, name): if name not in (file.get_basename(), other.get_basename() if other else None): diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index f3c2ea67af35..4814606ab9e7 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -434,6 +434,25 @@ with patch.dict(os.environ, {"XDG_CONFIG_HOME": fresh_root + "/config"}): run_until(0.3) assert events, "the first save of a new profile is seen" context.pop_thread_default() + +# A configuration beside the home directory, under a shared parent, is still +# watched from its nearest existing directory. +beside_root = tempfile.mkdtemp() +os.makedirs(beside_root + "/home") +with patch.dict(os.environ, {"HOME": beside_root + "/home", "FCITX_CONFIG_HOME": beside_root + "/fcitx5"}): + assert indicator.watched_entries() == [(beside_root, "fcitx5")], indicator.watched_entries() + +# The path changing while the watches are armed is resolved again. +armed = [] +real_new_for_path = indicator.Gio.File.new_for_path +def recording_new_for_path(path): + armed.append(path) + return real_new_for_path(path) +early, late = [(fresh_root, "config")], [(fresh_root + "/config", "fcitx5")] +with patch.object(indicator, "watched_entries", side_effect=[early, late, late]), \ + patch.object(indicator.Gio.File, "new_for_path", side_effect=recording_new_for_path): + indicator.ProfileWatch(lambda: None) +assert armed == [fresh_root, fresh_root + "/config"], armed print("ok - a missing configuration is watched until it exists, and a vanishing link keeps its watch") groups.append("Second") From 4383488e0df3687ab02ca933c6205e44d4599dba Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 19:34:29 +0200 Subject: [PATCH 11/17] Find the Fcitx profile through its owner and skip watching settled directories Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 59 +++++++++++++++++++++------- docs/input-methods.md | 2 +- test/shell.d/input-indicator-test.sh | 37 +++++++++++++++++ 3 files changed, 83 insertions(+), 15 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index dc2083bc8d76..c032949643ea 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -137,24 +137,45 @@ def switchable(self, methods): return len(call(self.bus, "InputMethodGroups")[0]) > 1 -def profile_path(): +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. - directory = os.environ.get("FCITX_CONFIG_HOME") or os.path.join( - os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"), "fcitx5") - return os.path.join(os.path.abspath(directory), "profile") + environment, cwd = owner or (os.environ, os.getcwd()) + home = environment.get("HOME") or os.path.expanduser("~") + directory = environment.get("FCITX_CONFIG_HOME") or os.path.join( + environment.get("XDG_CONFIG_HOME") or os.path.join(home, ".config"), "fcitx5") + return os.path.join(os.path.normpath(os.path.join(cwd, directory)), "profile") -def watched_entries(hops=40): +def watched_entries(owner=None, hops=40): # Saves rename a new profile into place, and a dotfile manager may link the # profile, its directory or the configuration home elsewhere, chain links, or # replace a linked directory. Resolve the path the way the kernel does, one # component at a time, and watch each directory it passes through for the one - # entry it looks up there, from the home directory down. - home = os.path.realpath(os.path.expanduser("~")) + # entry it looks up there when that entry is a link, is missing, or is the + # profile or its directory. + home = os.path.realpath((owner[0] if owner else os.environ).get("HOME") or os.path.expanduser("~")) entries = [] - current, pending = "/", profile_path().split("/") + current, pending = "/", profile_path(owner).split("/") while pending: part = pending.pop(0) if part in ("", "."): @@ -163,13 +184,17 @@ def watched_entries(hops=40): current = os.path.dirname(current) continue candidate = os.path.join(current, part) - # The way down to the home directory changes with a new session, not a save. - if candidate != home and not home.startswith(candidate + "/"): - entries.append((current, part)) try: target = os.readlink(candidate) if hops > 0 else None except OSError: target = None + # The way down to the home directory changes with a new session, not a + # save, and so does a real directory above the profile's own: watching the + # busy home directory for those would wake on every file written there. + toward_home = candidate == home or home.startswith(candidate + "/") + settled = target is None and os.path.isdir(candidate) and len(pending) > 1 + if not toward_home and not settled: + entries.append((current, part)) if target is not None: hops -= 1 if target.startswith("/"): @@ -189,12 +214,13 @@ class ProfileWatch: def __init__(self, changed): self.changed = changed self.monitors = [] + self.owner = None self.bind() def bind(self): # Resolve before dropping the old watches, so a failure keeps them, and # again once the new ones are armed, in case the path changed in between. - entries = watched_entries() + entries = watched_entries(self.owner) for _ in range(10): for monitor in self.monitors: monitor.cancel() @@ -203,7 +229,7 @@ def bind(self): monitor = Gio.File.new_for_path(directory).monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, None) monitor.connect("changed", self.entry_changed, name) self.monitors.append(monitor) - armed, entries = entries, watched_entries() + armed, entries = entries, watched_entries(self.owner) if entries == armed: return # Still moving: whoever is changing it will send another event. @@ -221,12 +247,17 @@ def follow(bus, changed, presence): # (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.owner = owner_environment(bus) + profile.bind() changed() name = Gio.bus_watch_name_on_connection(bus, BUS, Gio.BusNameWatcherFlags.NONE, lambda *_: owner(True), lambda *_: owner(False)) - return [name, ProfileWatch(changed)] + return [name, profile] def watch(bus): diff --git a/docs/input-methods.md b/docs/input-methods.md index c97cd295d451..b20c2ccac9c1 100644 --- a/docs/input-methods.md +++ b/docs/input-methods.md @@ -14,7 +14,7 @@ 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 `~/.config/fcitx5/profile`; the reader resolves that path one component at a time, as the kernel does, and watches each directory the lookup passes through (from the home directory down) for the one entry it looks up there, so renamed saves, chained links and relinked or replaced dotfile directories are seen. 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. +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`, read from the environment and working directory of the process that owns the bus name, so a service drop-in that moves it is followed; the reader resolves that path one component at a time, as the kernel does, and watches each directory the lookup passes through for the one entry it looks up there when that entry is a link, is missing, or is the profile or its directory (never the home directory or above), so renamed saves, chained links and relinked or replaced dotfile directories are seen. 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. diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index 4814606ab9e7..00c281873533 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -442,6 +442,16 @@ os.makedirs(beside_root + "/home") with patch.dict(os.environ, {"HOME": beside_root + "/home", "FCITX_CONFIG_HOME": beside_root + "/fcitx5"}): assert indicator.watched_entries() == [(beside_root, "fcitx5")], indicator.watched_entries() +# A plain ~/.config is not watched from the busy home directory: only the +# profile and its directory can change with a save. +plain_root = tempfile.mkdtemp() +os.makedirs(plain_root + "/home/.config/fcitx5") +with patch.dict(os.environ, {"HOME": plain_root + "/home"}): + os.environ.pop("XDG_CONFIG_HOME", None) + os.environ.pop("FCITX_CONFIG_HOME", None) + assert indicator.watched_entries() == [(plain_root + "/home/.config", "fcitx5"), + (plain_root + "/home/.config/fcitx5", "profile")], indicator.watched_entries() + # The path changing while the watches are armed is resolved again. armed = [] real_new_for_path = indicator.Gio.File.new_for_path @@ -455,6 +465,33 @@ with patch.object(indicator, "watched_entries", side_effect=[early, late, late]) assert armed == [fresh_root, fresh_root + "/config"], armed print("ok - a missing configuration is watched until it exists, and a vanishing link keeps its watch") +# The profile is the one the Fcitx process saves, whose environment a service +# drop-in can set without the shell knowing. +daemon_dir = tempfile.mkdtemp() +os.makedirs(daemon_dir + "/relative/fcitx") +daemon = subprocess.Popen(["sleep", "30"], cwd=daemon_dir, + env={"HOME": daemon_dir, "FCITX_CONFIG_HOME": "relative/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) == daemon_dir + "/relative/fcitx/profile", indicator.profile_path(owner) + appeared, armed = {}, [] + def watch_name(bus, name, flags, on_appeared, on_vanished): + appeared["callback"] = on_appeared + return 1 + 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) + armed.clear() + appeared["callback"]() + assert armed[-1] == daemon_dir + "/relative/fcitx", armed +finally: + daemon.kill() +print("ok - the watch follows the profile of the process that owns Fcitx's bus name") + groups.append("Second") with patch.object(indicator, "call", return_value=(groups,)): assert indicator.Indicator(None).switchable(["keyboard-us"]) From 53a3827d6b1267d45ae88d7cbdedd1535a9f0f7f Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 19:46:50 +0200 Subject: [PATCH 12/17] Resolve a relative XDG_CONFIG_HOME against HOME and skip dot components Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 12 ++++++++---- test/shell.d/input-indicator-test.sh | 12 ++++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index c032949643ea..d29f326c8a9b 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -161,9 +161,12 @@ def profile_path(owner=None): # path is relative to the working directory. environment, cwd = owner or (os.environ, os.getcwd()) home = environment.get("HOME") or os.path.expanduser("~") - directory = environment.get("FCITX_CONFIG_HOME") or os.path.join( - environment.get("XDG_CONFIG_HOME") or os.path.join(home, ".config"), "fcitx5") - return os.path.join(os.path.normpath(os.path.join(cwd, directory)), "profile") + 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") def watched_entries(owner=None, hops=40): @@ -192,7 +195,8 @@ def watched_entries(owner=None, hops=40): # save, and so does a real directory above the profile's own: watching the # busy home directory for those would wake on every file written there. toward_home = candidate == home or home.startswith(candidate + "/") - settled = target is None and os.path.isdir(candidate) and len(pending) > 1 + remaining = [item for item in pending if item not in ("", ".")] + settled = target is None and os.path.isdir(candidate) and len(remaining) > 1 if not toward_home and not settled: entries.append((current, part)) if target is not None: diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index 00c281873533..a3103cb576c4 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -398,6 +398,10 @@ with patch.dict(os.environ, {"XDG_CONFIG_HOME": "/xdg", "FCITX_CONFIG_HOME": "/f assert indicator.profile_path() == "/fcitx/cleaned/profile" os.environ["FCITX_CONFIG_HOME"] = "relative/fcitx" assert indicator.profile_path() == os.path.join(os.getcwd(), "relative/fcitx/profile") + # Without it, a relative XDG_CONFIG_HOME is relative to the home directory. + del os.environ["FCITX_CONFIG_HOME"] + os.environ.update(XDG_CONFIG_HOME="relative/config", HOME="/somewhere") + assert indicator.profile_path() == "/somewhere/relative/config/fcitx5/profile", indicator.profile_path() print("ok - the watched profile follows Fcitx's FCITX_CONFIG_HOME override, cleaned the way Fcitx cleans it") # A link that vanishes mid-resolution, as a relink in progress makes it, is @@ -452,6 +456,14 @@ with patch.dict(os.environ, {"HOME": plain_root + "/home"}): assert indicator.watched_entries() == [(plain_root + "/home/.config", "fcitx5"), (plain_root + "/home/.config/fcitx5", "profile")], indicator.watched_entries() +# A link written with a trailing slash still leads to the profile's directory. +slash_root = tempfile.mkdtemp() +os.makedirs(slash_root + "/home/.config/first") +os.symlink("first/.", slash_root + "/home/.config/fcitx5") +with patch.dict(os.environ, {"HOME": slash_root + "/home"}): + os.environ.pop("XDG_CONFIG_HOME", None) + assert (slash_root + "/home/.config", "first") in indicator.watched_entries(), indicator.watched_entries() + # The path changing while the watches are armed is resolved again. armed = [] real_new_for_path = indicator.Gio.File.new_for_path From dd126d80b5529922e90c6f41f7d3981405294120 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 19:59:49 +0200 Subject: [PATCH 13/17] Rebind the Fcitx profile watch when a watched directory moves away Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 9 ++++++--- test/shell.d/input-indicator-test.sh | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index d29f326c8a9b..7943a5a86aea 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -231,15 +231,18 @@ def bind(self): self.monitors = [] for directory, name in entries: monitor = Gio.File.new_for_path(directory).monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, None) - monitor.connect("changed", self.entry_changed, name) + monitor.connect("changed", self.entry_changed, directory, name) self.monitors.append(monitor) armed, entries = entries, watched_entries(self.owner) if entries == armed: return # Still moving: whoever is changing it will send another event. - def entry_changed(self, monitor, file, other, event, name): - if name not in (file.get_basename(), other.get_basename() if other else None): + def entry_changed(self, monitor, file, other, event, directory, name): + # The watched directory itself moving away (a real ~/.config moved aside + # for a link, say) arrives as an event on the directory, not the entry. + moved = file.get_path() == directory + if not moved and name not in (file.get_basename(), other.get_basename() if other else None): return # A relinked or replaced entry may resolve somewhere new. self.bind() diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index a3103cb576c4..5a08c2bb5a53 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -456,6 +456,25 @@ with patch.dict(os.environ, {"HOME": plain_root + "/home"}): assert indicator.watched_entries() == [(plain_root + "/home/.config", "fcitx5"), (plain_root + "/home/.config/fcitx5", "profile")], indicator.watched_entries() +# Moving that plain ~/.config aside for a link to a new one is still seen, +# through the event on the watched directory itself. +moved = [] +with patch.dict(os.environ, {"HOME": plain_root + "/home"}): + context = indicator.GLib.MainContext.new() + context.push_thread_default() + plain_watch = indicator.ProfileWatch(lambda: moved.append("changed")) + os.rename(plain_root + "/home/.config", plain_root + "/home/.config.old") + os.makedirs(plain_root + "/dotfiles/fcitx5") + os.symlink("../dotfiles", plain_root + "/home/.config") + run_until(0.3) + assert moved, "moving ~/.config aside is seen" + moved.clear() + with open(plain_root + "/dotfiles/fcitx5/profile", "w") as file: + file.write("[Groups/0]\n") + run_until(0.3) + assert moved, "a save in the linked configuration is seen" + context.pop_thread_default() + # A link written with a trailing slash still leads to the profile's directory. slash_root = tempfile.mkdtemp() os.makedirs(slash_root + "/home/.config/first") From 23435c2950ea0c627ad36f64a9875d6850320c8b Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 20:14:07 +0200 Subject: [PATCH 14/17] Watch each Fcitx profile directory below home for its own move Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 19 ++++++++----------- docs/input-methods.md | 2 +- test/shell.d/input-indicator-test.sh | 21 +++++++++++++++++++++ 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index 7943a5a86aea..2d06dde5865b 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -172,10 +172,12 @@ def profile_path(owner=None): def watched_entries(owner=None, hops=40): # Saves rename a new profile into place, and a dotfile manager may link the # profile, its directory or the configuration home elsewhere, chain links, or - # replace a linked directory. Resolve the path the way the kernel does, one - # component at a time, and watch each directory it passes through for the one - # entry it looks up there when that entry is a link, is missing, or is the - # profile or its directory. + # replace a linked directory or any directory above the profile. Resolve the + # path the way the kernel does, one component at a time, and watch each + # directory it passes through below the home directory, for the entry it + # looks up there and for the directory itself moving away. The home directory + # and those above it are busy and change with a session rather than a save, + # so they are watched only for an entry that is a link or missing. home = os.path.realpath((owner[0] if owner else os.environ).get("HOME") or os.path.expanduser("~")) entries = [] current, pending = "/", profile_path(owner).split("/") @@ -191,13 +193,8 @@ def watched_entries(owner=None, hops=40): target = os.readlink(candidate) if hops > 0 else None except OSError: target = None - # The way down to the home directory changes with a new session, not a - # save, and so does a real directory above the profile's own: watching the - # busy home directory for those would wake on every file written there. - toward_home = candidate == home or home.startswith(candidate + "/") - remaining = [item for item in pending if item not in ("", ".")] - settled = target is None and os.path.isdir(candidate) and len(remaining) > 1 - if not toward_home and not settled: + above_home = current == home or home.startswith(current.rstrip("/") + "/") + if not above_home or target is not None or not os.path.lexists(candidate): entries.append((current, part)) if target is not None: hops -= 1 diff --git a/docs/input-methods.md b/docs/input-methods.md index b20c2ccac9c1..535b882ba3c1 100644 --- a/docs/input-methods.md +++ b/docs/input-methods.md @@ -14,7 +14,7 @@ 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`, read from the environment and working directory of the process that owns the bus name, so a service drop-in that moves it is followed; the reader resolves that path one component at a time, as the kernel does, and watches each directory the lookup passes through for the one entry it looks up there when that entry is a link, is missing, or is the profile or its directory (never the home directory or above), so renamed saves, chained links and relinked or replaced dotfile directories are seen. 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. +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`, read from the environment and working directory of the process that owns the bus name, so a service drop-in that moves it is followed; the reader resolves that path one component at a time, as the kernel does, and watches each directory the lookup passes through below the home directory, for the entry it looks up there and for the directory itself moving away; the home directory and those above it are watched only for an entry that is a link or missing. So renamed saves, chained links and relinked or replaced dotfile directories are seen. 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. diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index 5a08c2bb5a53..9473b0baacda 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -475,6 +475,27 @@ with patch.dict(os.environ, {"HOME": plain_root + "/home"}): assert moved, "a save in the linked configuration is seen" context.pop_thread_default() +# With ~/.config linked into a dotfiles tree, replacing the whole tree is seen +# through the watch on the tree's own directory. +tree_root = tempfile.mkdtemp() +os.makedirs(tree_root + "/home/dotfiles/config/fcitx5") +os.symlink("dotfiles/config", tree_root + "/home/.config") +replaced = [] +with patch.dict(os.environ, {"HOME": tree_root + "/home"}): + context = indicator.GLib.MainContext.new() + context.push_thread_default() + tree_watch = indicator.ProfileWatch(lambda: replaced.append("changed")) + os.rename(tree_root + "/home/dotfiles", tree_root + "/home/dotfiles.old") + os.makedirs(tree_root + "/home/dotfiles/config/fcitx5") + run_until(0.3) + assert replaced, "replacing the dotfiles tree is seen" + replaced.clear() + with open(tree_root + "/home/dotfiles/config/fcitx5/profile", "w") as file: + file.write("[Groups/0]\n") + run_until(0.3) + assert replaced, "a save in the replacement tree is seen" + context.pop_thread_default() + # A link written with a trailing slash still leads to the profile's directory. slash_root = tempfile.mkdtemp() os.makedirs(slash_root + "/home/.config/first") From a6ecf698057e2e22ea6249ee9489791bf9a94b0d Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 20:25:18 +0200 Subject: [PATCH 15/17] Always watch the Fcitx profile entry itself Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 6 ++++-- docs/input-methods.md | 2 +- test/shell.d/input-indicator-test.sh | 5 +++++ 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index 2d06dde5865b..4fd84517a5a8 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -177,7 +177,8 @@ def watched_entries(owner=None, hops=40): # directory it passes through below the home directory, for the entry it # looks up there and for the directory itself moving away. The home directory # and those above it are busy and change with a session rather than a save, - # so they are watched only for an entry that is a link or missing. + # so they are watched only for an entry that is a link, is missing, or is the + # profile itself. home = os.path.realpath((owner[0] if owner else os.environ).get("HOME") or os.path.expanduser("~")) entries = [] current, pending = "/", profile_path(owner).split("/") @@ -194,7 +195,8 @@ def watched_entries(owner=None, hops=40): except OSError: target = None above_home = current == home or home.startswith(current.rstrip("/") + "/") - if not above_home or target is not None or not os.path.lexists(candidate): + last = not [item for item in pending if item not in ("", ".")] + if not above_home or last or target is not None or not os.path.lexists(candidate): entries.append((current, part)) if target is not None: hops -= 1 diff --git a/docs/input-methods.md b/docs/input-methods.md index 535b882ba3c1..5f1f13d72dc8 100644 --- a/docs/input-methods.md +++ b/docs/input-methods.md @@ -14,7 +14,7 @@ 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`, read from the environment and working directory of the process that owns the bus name, so a service drop-in that moves it is followed; the reader resolves that path one component at a time, as the kernel does, and watches each directory the lookup passes through below the home directory, for the entry it looks up there and for the directory itself moving away; the home directory and those above it are watched only for an entry that is a link or missing. So renamed saves, chained links and relinked or replaced dotfile directories are seen. 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. +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`, read from the environment and working directory of the process that owns the bus name, so a service drop-in that moves it is followed; the reader resolves that path one component at a time, as the kernel does, and watches each directory the lookup passes through below the home directory, for the entry it looks up there and for the directory itself moving away; the home directory and those above it are watched only for an entry that is a link, is missing, or is the profile itself. So renamed saves, chained links and relinked or replaced dotfile directories are seen. 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. diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index 9473b0baacda..32e13e34a399 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -496,6 +496,11 @@ with patch.dict(os.environ, {"HOME": tree_root + "/home"}): assert replaced, "a save in the replacement tree is seen" context.pop_thread_default() +# A profile kept directly in the home directory is still watched there. +open(plain_root + "/home/profile", "w").close() +with patch.dict(os.environ, {"HOME": plain_root + "/home", "FCITX_CONFIG_HOME": plain_root + "/home"}): + assert indicator.watched_entries() == [(plain_root + "/home", "profile")], indicator.watched_entries() + # A link written with a trailing slash still leads to the profile's directory. slash_root = tempfile.mkdtemp() os.makedirs(slash_root + "/home/.config/first") From f59c2ba3b16509e50a7db80100c026663a91a0b6 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 21:53:26 +0200 Subject: [PATCH 16/17] Watch the Fcitx profile with one file monitor, keep the reading on a failed group count Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 100 +++------- docs/input-methods.md | 2 +- test/shell.d/input-indicator-test.sh | 275 ++++----------------------- 3 files changed, 60 insertions(+), 317 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index 4fd84517a5a8..716502109399 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -169,83 +169,25 @@ def profile_path(owner=None): return os.path.join(os.path.normpath(directory), "profile") -def watched_entries(owner=None, hops=40): - # Saves rename a new profile into place, and a dotfile manager may link the - # profile, its directory or the configuration home elsewhere, chain links, or - # replace a linked directory or any directory above the profile. Resolve the - # path the way the kernel does, one component at a time, and watch each - # directory it passes through below the home directory, for the entry it - # looks up there and for the directory itself moving away. The home directory - # and those above it are busy and change with a session rather than a save, - # so they are watched only for an entry that is a link, is missing, or is the - # profile itself. - home = os.path.realpath((owner[0] if owner else os.environ).get("HOME") or os.path.expanduser("~")) - entries = [] - current, pending = "/", profile_path(owner).split("/") - while pending: - part = pending.pop(0) - if part in ("", "."): - continue - if part == "..": - current = os.path.dirname(current) - continue - candidate = os.path.join(current, part) - try: - target = os.readlink(candidate) if hops > 0 else None - except OSError: - target = None - above_home = current == home or home.startswith(current.rstrip("/") + "/") - last = not [item for item in pending if item not in ("", ".")] - if not above_home or last or target is not None or not os.path.lexists(candidate): - entries.append((current, part)) - if target is not None: - hops -= 1 - if target.startswith("/"): - current = "/" - pending = target.split("/") + pending - elif os.path.lexists(candidate): - current = candidate - else: - # Nothing further exists yet; the watch on this entry sees it arrive. - break - return list(dict.fromkeys(entries)) - - class ProfileWatch: - """Calls changed() whenever the profile Fcitx saves its configuration to changes.""" + """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.owner = None - self.bind() - - def bind(self): - # Resolve before dropping the old watches, so a failure keeps them, and - # again once the new ones are armed, in case the path changed in between. - entries = watched_entries(self.owner) - for _ in range(10): - for monitor in self.monitors: - monitor.cancel() - self.monitors = [] - for directory, name in entries: - monitor = Gio.File.new_for_path(directory).monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, None) - monitor.connect("changed", self.entry_changed, directory, name) - self.monitors.append(monitor) - armed, entries = entries, watched_entries(self.owner) - if entries == armed: - return - # Still moving: whoever is changing it will send another event. - - def entry_changed(self, monitor, file, other, event, directory, name): - # The watched directory itself moving away (a real ~/.config moved aside - # for a link, say) arrives as an event on the directory, not the entry. - moved = file.get_path() == directory - if not moved and name not in (file.get_basename(), other.get_basename() if other else None): - return - # A relinked or replaced entry may resolve somewhere new. - self.bind() - self.changed() + self.monitor = None + self.bind(None) + + def bind(self, owner): + if self.monitor: + self.monitor.cancel() + self.monitor = Gio.File.new_for_path(profile_path(owner)).monitor_file(Gio.FileMonitorFlags.WATCH_MOVES, None) + self.monitor.connect("changed", lambda *_: self.changed()) def follow(bus, changed, presence): @@ -258,8 +200,7 @@ def follow(bus, changed, presence): def owner(present): presence(present) if present: - profile.owner = owner_environment(bus) - profile.bind() + profile.bind(owner_environment(bus)) changed() name = Gio.bus_watch_name_on_connection(bus, BUS, Gio.BusNameWatcherFlags.NONE, lambda *_: owner(True), lambda *_: owner(False)) @@ -281,8 +222,6 @@ def refresh(): nonlocal previous, polling, failed try: state = indicator.refresh() - polling = indicator.switchable(state["methods"]) - failed = False except GLib.Error: failed = True indicator.pending = "" @@ -290,6 +229,13 @@ def refresh(): # 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) diff --git a/docs/input-methods.md b/docs/input-methods.md index 5f1f13d72dc8..496fddf9413c 100644 --- a/docs/input-methods.md +++ b/docs/input-methods.md @@ -14,7 +14,7 @@ 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`, read from the environment and working directory of the process that owns the bus name, so a service drop-in that moves it is followed; the reader resolves that path one component at a time, as the kernel does, and watches each directory the lookup passes through below the home directory, for the entry it looks up there and for the directory itself moving away; the home directory and those above it are watched only for an entry that is a link, is missing, or is the profile itself. So renamed saves, chained links and relinked or replaced dotfile directories are seen. 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. +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. diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index 32e13e34a399..1c8d22bad36e 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -178,20 +178,13 @@ print("ok - cycling back walks the same choices in reverse") # replaced by `live`, which a configuration change edits before saving. import sys import tempfile -# The configuration home is itself a link, as a dotfile manager may make it. -config_root = tempfile.mkdtemp() -os.makedirs(config_root + "/home-a") -os.symlink("home-a", config_root + "/config") -config_home = config_root + "/config" -os.makedirs(config_home + "/first") -os.makedirs(config_home + "/second") -os.makedirs(config_home + "/third") -# A dotfile manager's layout: the Fcitx directory is a link into the dotfiles. -os.symlink("first", config_home + "/fcitx5") +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(directory="first", name="profile"): - path = f"{config_home}/{directory}/{name}" +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) @@ -199,7 +192,7 @@ def save(directory="first", name="profile"): live = {"methods": ["keyboard-us"], "current": "keyboard-us", "name": "English", "label": "en", "language": "en"} save() groups = ["Default"] -timers, reader, reads, failures = [], {}, [0], [0] +timers, reader, reads, failures, group_failures = [], {}, [0], [0], [0] real_timeout = indicator.GLib.timeout_add real_io_add_watch = indicator.GLib.io_add_watch @@ -226,6 +219,13 @@ def snapshot(bus): 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): @@ -283,101 +283,19 @@ def scenario(): step(2.4, recovered) def recovered(): assert methods() == ["keyboard-us"], state_lines - # Relinking the Fcitx directory moves the watch to the new target. - os.symlink("second", config_home + "/fcitx5.new") - os.replace(config_home + "/fcitx5.new", config_home + "/fcitx5") - step(0.6, relinked) - def relinked(): - live["methods"] = ["keyboard-us", "hangul"] - save("second") - step(0.6, saved_in_new_target) - def saved_in_new_target(): - assert methods() == ["keyboard-us", "hangul"], state_lines - # A profile that is itself a link is watched at its target too. - live["methods"] = ["keyboard-us"] - save("third", "profile.real") - os.symlink("../third/profile.real", config_home + "/second/profile.new") - os.replace(config_home + "/second/profile.new", config_home + "/second/profile") - step(0.6, linked_profile) - def linked_profile(): - assert methods() == ["keyboard-us"], state_lines - live["methods"] = ["keyboard-us", "pinyin"] - save("third", "profile.real") - step(0.6, saved_through_link) - def saved_through_link(): - assert methods() == ["keyboard-us", "pinyin"], state_lines - # The directory the link resolves to is replaced, the link left alone. - live["methods"] = ["keyboard-us"] - os.rename(config_home + "/third", config_home + "/third.old") - os.makedirs(config_home + "/third") - save("third", "profile.real") - step(0.6, target_replaced) - def target_replaced(): - assert methods() == ["keyboard-us"], state_lines - live["methods"] = ["keyboard-us", "chewing"] - save("third", "profile.real") - step(0.6, saved_in_replaced_target) - def saved_in_replaced_target(): - assert methods() == ["keyboard-us", "chewing"], state_lines - # Relinking the configuration home moves the watch to the new one. - live["methods"] = ["keyboard-us"] - os.makedirs(config_root + "/home-b/fcitx5") - save("../home-b/fcitx5") - os.symlink("home-b", config_root + "/config.new") - os.replace(config_root + "/config.new", config_root + "/config") - step(0.6, home_relinked) - def home_relinked(): - assert methods() == ["keyboard-us"], state_lines - live["methods"] = ["keyboard-us", "anthy"] - save("fcitx5") - step(0.6, saved_in_new_home) - def saved_in_new_home(): - assert methods() == ["keyboard-us", "anthy"], state_lines - # A chain of links: profile -> store/current -> store/profile-a. - live["methods"] = ["keyboard-us"] - os.makedirs(config_home + "/store") - save("store", "profile-a") - os.symlink("profile-a", config_home + "/store/current") - os.symlink("../store/current", config_home + "/fcitx5/profile.new") - os.replace(config_home + "/fcitx5/profile.new", config_home + "/fcitx5/profile") - step(0.6, chained) - def chained(): - assert methods() == ["keyboard-us"], state_lines - # Repointing the middle link is seen, though neither end changed. - live["methods"] = ["keyboard-us", "rime"] - save("store", "profile-b") - os.symlink("profile-b", config_home + "/store/current.new") - os.replace(config_home + "/store/current.new", config_home + "/store/current") - step(0.6, middle_relinked) - def middle_relinked(): - assert methods() == ["keyboard-us", "rime"], state_lines - # A link whose target steps back out of another link: - # fcitx5 -> store/redirect/../fcitx5, with store/redirect -> ../x/inner. - live["methods"] = ["keyboard-us"] - for side in ("x", "y"): - os.makedirs(f"{config_home}/{side}/inner") - os.makedirs(f"{config_home}/{side}/fcitx5") - save("x/fcitx5") - os.symlink("../x/inner", config_home + "/store/redirect") - os.rename(config_home + "/fcitx5", config_home + "/fcitx5.old") - os.symlink("store/redirect/../fcitx5", config_home + "/fcitx5") - step(0.6, redirected) - def redirected(): + # 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 - live["methods"] = ["keyboard-us", "sayura"] - save("y/fcitx5") - os.symlink("../y/inner", config_home + "/store/redirect.new") - os.replace(config_home + "/store/redirect.new", config_home + "/store/redirect") - step(0.6, redirect_repointed) - def redirect_repointed(): - assert methods() == ["keyboard-us", "sayura"], 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=lambda bus, method, args=None: (list(groups),) if method == "InputMethodGroups" else (_ for _ in ()).throw(AssertionError(method))), \ + 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), \ @@ -387,168 +305,47 @@ with patch.dict(os.environ, {"XDG_CONFIG_HOME": config_home}), \ 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, and a failed read is retried") -print("ok - relinking the Fcitx directory or the profile moves the watch, and replaced saves are seen") +print("ok - an event during polling replaces the poll, a failed read is retried, and a failed group count keeps the reading") 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" - os.environ["FCITX_CONFIG_HOME"] = "/fcitx/link/../cleaned" - assert indicator.profile_path() == "/fcitx/cleaned/profile" - os.environ["FCITX_CONFIG_HOME"] = "relative/fcitx" - assert indicator.profile_path() == os.path.join(os.getcwd(), "relative/fcitx/profile") - # Without it, a relative XDG_CONFIG_HOME is relative to the home directory. - del os.environ["FCITX_CONFIG_HOME"] - os.environ.update(XDG_CONFIG_HOME="relative/config", HOME="/somewhere") - assert indicator.profile_path() == "/somewhere/relative/config/fcitx5/profile", indicator.profile_path() -print("ok - the watched profile follows Fcitx's FCITX_CONFIG_HOME override, cleaned the way Fcitx cleans it") - -# A link that vanishes mid-resolution, as a relink in progress makes it, is -# watched as an entry rather than failing the whole watch. -race_root = tempfile.mkdtemp() -os.symlink("elsewhere", race_root + "/fcitx5") -with patch.dict(os.environ, {"XDG_CONFIG_HOME": race_root}), \ - patch.object(indicator.os, "readlink", side_effect=FileNotFoundError("relinked")): - assert (race_root, "fcitx5") in indicator.watched_entries() - -# A configuration that does not exist yet is watched from its nearest existing -# directory, and its profile is seen once Fcitx first saves it. -fresh_root = tempfile.mkdtemp() -events = [] -with patch.dict(os.environ, {"XDG_CONFIG_HOME": fresh_root + "/config"}): - assert indicator.watched_entries()[-1] == (fresh_root, "config"), indicator.watched_entries() - # A context of its own, clear of the sources the reader above left behind. - import time - context = indicator.GLib.MainContext.new() - context.push_thread_default() - profile_watch = indicator.ProfileWatch(lambda: events.append("changed")) - def run_until(seconds): - deadline = time.monotonic() + seconds - while time.monotonic() < deadline: - context.iteration(False) - time.sleep(0.01) - os.makedirs(fresh_root + "/config") - run_until(0.3) - os.makedirs(fresh_root + "/config/fcitx5") - run_until(0.3) - events.clear() - with open(fresh_root + "/config/fcitx5/profile", "w") as file: - file.write("[Groups/0]\n") - run_until(0.3) - assert events, "the first save of a new profile is seen" - context.pop_thread_default() - -# A configuration beside the home directory, under a shared parent, is still -# watched from its nearest existing directory. -beside_root = tempfile.mkdtemp() -os.makedirs(beside_root + "/home") -with patch.dict(os.environ, {"HOME": beside_root + "/home", "FCITX_CONFIG_HOME": beside_root + "/fcitx5"}): - assert indicator.watched_entries() == [(beside_root, "fcitx5")], indicator.watched_entries() - -# A plain ~/.config is not watched from the busy home directory: only the -# profile and its directory can change with a save. -plain_root = tempfile.mkdtemp() -os.makedirs(plain_root + "/home/.config/fcitx5") -with patch.dict(os.environ, {"HOME": plain_root + "/home"}): - os.environ.pop("XDG_CONFIG_HOME", None) - os.environ.pop("FCITX_CONFIG_HOME", None) - assert indicator.watched_entries() == [(plain_root + "/home/.config", "fcitx5"), - (plain_root + "/home/.config/fcitx5", "profile")], indicator.watched_entries() - -# Moving that plain ~/.config aside for a link to a new one is still seen, -# through the event on the watched directory itself. -moved = [] -with patch.dict(os.environ, {"HOME": plain_root + "/home"}): - context = indicator.GLib.MainContext.new() - context.push_thread_default() - plain_watch = indicator.ProfileWatch(lambda: moved.append("changed")) - os.rename(plain_root + "/home/.config", plain_root + "/home/.config.old") - os.makedirs(plain_root + "/dotfiles/fcitx5") - os.symlink("../dotfiles", plain_root + "/home/.config") - run_until(0.3) - assert moved, "moving ~/.config aside is seen" - moved.clear() - with open(plain_root + "/dotfiles/fcitx5/profile", "w") as file: - file.write("[Groups/0]\n") - run_until(0.3) - assert moved, "a save in the linked configuration is seen" - context.pop_thread_default() - -# With ~/.config linked into a dotfiles tree, replacing the whole tree is seen -# through the watch on the tree's own directory. -tree_root = tempfile.mkdtemp() -os.makedirs(tree_root + "/home/dotfiles/config/fcitx5") -os.symlink("dotfiles/config", tree_root + "/home/.config") -replaced = [] -with patch.dict(os.environ, {"HOME": tree_root + "/home"}): - context = indicator.GLib.MainContext.new() - context.push_thread_default() - tree_watch = indicator.ProfileWatch(lambda: replaced.append("changed")) - os.rename(tree_root + "/home/dotfiles", tree_root + "/home/dotfiles.old") - os.makedirs(tree_root + "/home/dotfiles/config/fcitx5") - run_until(0.3) - assert replaced, "replacing the dotfiles tree is seen" - replaced.clear() - with open(tree_root + "/home/dotfiles/config/fcitx5/profile", "w") as file: - file.write("[Groups/0]\n") - run_until(0.3) - assert replaced, "a save in the replacement tree is seen" - context.pop_thread_default() - -# A profile kept directly in the home directory is still watched there. -open(plain_root + "/home/profile", "w").close() -with patch.dict(os.environ, {"HOME": plain_root + "/home", "FCITX_CONFIG_HOME": plain_root + "/home"}): - assert indicator.watched_entries() == [(plain_root + "/home", "profile")], indicator.watched_entries() - -# A link written with a trailing slash still leads to the profile's directory. -slash_root = tempfile.mkdtemp() -os.makedirs(slash_root + "/home/.config/first") -os.symlink("first/.", slash_root + "/home/.config/fcitx5") -with patch.dict(os.environ, {"HOME": slash_root + "/home"}): - os.environ.pop("XDG_CONFIG_HOME", None) - assert (slash_root + "/home/.config", "first") in indicator.watched_entries(), indicator.watched_entries() - -# The path changing while the watches are armed is resolved again. -armed = [] -real_new_for_path = indicator.Gio.File.new_for_path -def recording_new_for_path(path): - armed.append(path) - return real_new_for_path(path) -early, late = [(fresh_root, "config")], [(fresh_root + "/config", "fcitx5")] -with patch.object(indicator, "watched_entries", side_effect=[early, late, late]), \ - patch.object(indicator.Gio.File, "new_for_path", side_effect=recording_new_for_path): - indicator.ProfileWatch(lambda: None) -assert armed == [fresh_root, fresh_root + "/config"], armed -print("ok - a missing configuration is watched until it exists, and a vanishing link keeps its watch") +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. -daemon_dir = tempfile.mkdtemp() -os.makedirs(daemon_dir + "/relative/fcitx") -daemon = subprocess.Popen(["sleep", "30"], cwd=daemon_dir, - env={"HOME": daemon_dir, "FCITX_CONFIG_HOME": "relative/fcitx"}) +# 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) == daemon_dir + "/relative/fcitx/profile", indicator.profile_path(owner) - appeared, armed = {}, [] + 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) - armed.clear() appeared["callback"]() - assert armed[-1] == daemon_dir + "/relative/fcitx", armed + 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"]) From a1ead6b37605d5f3b63a9ebba2f6a621d6a43b6c Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 12 Oct 2026 22:04:30 +0200 Subject: [PATCH 17/17] Watch the target of a linked Fcitx profile too Co-Authored-By: Claude Opus 5.5 --- default/input-methods/indicator.py | 14 +++++++++----- test/shell.d/input-indicator-test.sh | 27 +++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/default/input-methods/indicator.py b/default/input-methods/indicator.py index 716502109399..2eab70c1d1c0 100644 --- a/default/input-methods/indicator.py +++ b/default/input-methods/indicator.py @@ -180,14 +180,18 @@ class ProfileWatch: def __init__(self, changed): self.changed = changed - self.monitor = None + self.monitors = [] self.bind(None) def bind(self, owner): - if self.monitor: - self.monitor.cancel() - self.monitor = Gio.File.new_for_path(profile_path(owner)).monitor_file(Gio.FileMonitorFlags.WATCH_MOVES, None) - self.monitor.connect("changed", lambda *_: self.changed()) + 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): diff --git a/test/shell.d/input-indicator-test.sh b/test/shell.d/input-indicator-test.sh index 1c8d22bad36e..bb58d28d4782 100755 --- a/test/shell.d/input-indicator-test.sh +++ b/test/shell.d/input-indicator-test.sh @@ -307,6 +307,33 @@ 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"]