Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
0232687
Poll Fcitx only when there is an input method to switch to
dhh Oct 12, 2026
7e4dae6
Keep one Fcitx poll, retry failed reads, and follow a relinked profile
dhh Oct 12, 2026
ff65b99
Cover renamed and linked Fcitx profile saves in the indicator test
dhh Oct 12, 2026
4ff2f59
Watch the Fcitx profile's directories and honor FCITX_CONFIG_HOME
dhh Oct 12, 2026
48196be
Follow every link to the Fcitx profile and keep polling a lone engine
dhh Oct 12, 2026
0cf0279
Watch every hop of a chained Fcitx profile link
dhh Oct 12, 2026
e4d0cb2
Resolve the Fcitx profile path one component at a time
dhh Oct 12, 2026
2718bc3
Keep Fcitx profile watches through relink races and missing directories
dhh Oct 12, 2026
a8ecb78
Resolve a relative FCITX_CONFIG_HOME before watching it
dhh Oct 12, 2026
0a446ae
Watch a Fcitx config beside the home directory and re-resolve after a…
dhh Oct 12, 2026
4383488
Find the Fcitx profile through its owner and skip watching settled di…
dhh Oct 12, 2026
53a3827
Resolve a relative XDG_CONFIG_HOME against HOME and skip dot components
dhh Oct 12, 2026
dd126d8
Rebind the Fcitx profile watch when a watched directory moves away
dhh Oct 12, 2026
23435c2
Watch each Fcitx profile directory below home for its own move
dhh Oct 12, 2026
a6ecf69
Always watch the Fcitx profile entry itself
dhh Oct 12, 2026
f59c2ba
Watch the Fcitx profile with one file monitor, keep the reading on a …
dhh Oct 12, 2026
a1ead6b
Watch the target of a linked Fcitx profile too
dhh Oct 12, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
149 changes: 141 additions & 8 deletions default/input-methods/indicator.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,35 +128,166 @@ def refresh(self):
state.update(current=entry[0], name=entry[1], label=entry[4], language=entry[5])
return state

def switchable(self, methods):
# With one keyboard method in one group the reading cannot change until the
# configuration does, and Fcitx saves that to the profile being watched. A
# lone composition engine still toggles, and steps aside in password fields.
if len(methods) > 1 or not all(method.startswith("keyboard-") for method in methods):
return True
return len(call(self.bus, "InputMethodGroups")[0]) > 1


def owner_environment(bus):
"""The environment and working directory of the process that owns Fcitx's bus name.

The profile is wherever that process saves it, which a service drop-in can
move without the shell's own environment knowing.
"""
try:
pid = bus.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
"GetConnectionUnixProcessID", GLib.Variant("(s)", (BUS,)), None,
Gio.DBusCallFlags.NONE, 1000, None).unpack()[0]
with open(f"/proc/{pid}/environ", "rb") as file:
items = file.read().decode(errors="replace").split("\0")
environment = dict(item.split("=", 1) for item in items if "=" in item)
return environment, os.readlink(f"/proc/{pid}/cwd")
except (GLib.Error, OSError, ValueError):
return None


def profile_path(owner=None):
# Fcitx's own lookup: FCITX_CONFIG_HOME, else $XDG_CONFIG_HOME/fcitx5, cleaned
# lexically the way Fcitx cleans it before any link is followed. A relative
# path is relative to the working directory.
environment, cwd = owner or (os.environ, os.getcwd())
home = environment.get("HOME") or os.path.expanduser("~")
if environment.get("FCITX_CONFIG_HOME"):
directory = os.path.join(cwd, environment["FCITX_CONFIG_HOME"])
else:
# A relative XDG_CONFIG_HOME is relative to the home directory.
directory = os.path.join(home, environment.get("XDG_CONFIG_HOME") or ".config", "fcitx5")
return os.path.join(os.path.normpath(directory), "profile")


class ProfileWatch:
"""Calls changed() whenever the profile Fcitx saves its configuration to changes.

The file is located once per Fcitx process, from that process's environment.
The watch follows renamed saves; inotify resolves a linked directory when the
watch is added, so relinking the dotfiles while Fcitx runs is picked up at
its next start.
"""

def __init__(self, changed):
self.changed = changed
self.monitors = []
self.bind(None)

def bind(self, owner):
for monitor in self.monitors:
monitor.cancel()
# A profile linked into dotfiles is saved by replacing the link's target.
path = profile_path(owner)
self.monitors = [Gio.File.new_for_path(watched).monitor_file(Gio.FileMonitorFlags.WATCH_MOVES, None)
for watched in dict.fromkeys([path, os.path.realpath(path)])]
for monitor in self.monitors:
monitor.connect("changed", lambda *_: self.changed())


def follow(bus, changed, presence):
# Fcitx sends no signal when its configuration or current method changes
# (Controller1's InputMethodGroupsChanged stays silent for group edits and
# switches alike), so follow the service's bus name for restarts and the
# profile it saves every configuration change to.
profile = ProfileWatch(changed)

def owner(present):
presence(present)
if present:
profile.bind(owner_environment(bus))
changed()
name = Gio.bus_watch_name_on_connection(bus, BUS, Gio.BusNameWatcherFlags.NONE,
lambda *_: owner(True), lambda *_: owner(False))
return [name, profile]


def watch(bus):
previous = None
indicator = Indicator(bus)
loop = GLib.MainLoop()
buffer = ""
timer = 0
settle = 0
polling = False
failed = False
present = True

def refresh():
nonlocal previous
nonlocal previous, polling, failed
try:
state = indicator.refresh()
except GLib.Error:
failed = True
indicator.pending = ""
indicator.last = ""
# Keep the configured cadence: a timed-out call is not a configuration
# change, and a vanished service is followed by its bus name.
state = {"methods": [], "current": "", "name": "", "language": ""}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
else:
# A failed group count keeps the reading and the last cadence.
try:
polling = indicator.switchable(state["methods"])
failed = False
except GLib.Error:
failed = True
line = json.dumps(state, ensure_ascii=False)
if line != previous:
print(line, flush=True)
previous = line

# Only a pending click or a group with methods to switch between needs
# reading again on a timer; everything else waits for an event. A failed
# read of a running service is retried, since nothing else would correct it.
def schedule():
nonlocal timer
if timer:
GLib.source_remove(timer)
timer = 0
if indicator.pending:
timer = GLib.timeout_add(50, poll)
elif polling:
timer = GLib.timeout_add(500, poll)
elif failed and present:
timer = GLib.timeout_add(2000, poll)

def poll():
nonlocal timer
timer = 0
refresh()
schedule()
return GLib.SOURCE_REMOVE

# A save arrives as several file events, and a restarting service as a
# vanish and an appear; read once they settle.
def changed():
nonlocal settle
if settle:
GLib.source_remove(settle)
settle = GLib.timeout_add(200, settled)

def settled():
nonlocal settle
settle = 0
refresh()
timer = GLib.timeout_add(50 if indicator.pending else 500, poll)
schedule()
return GLib.SOURCE_REMOVE

def presence(running):
nonlocal present
present = running

def command(source, condition):
nonlocal buffer, timer
nonlocal buffer
data = os.read(sys.stdin.fileno(), 4096)
if not data:
loop.quit()
Expand All @@ -170,14 +301,16 @@ def command(source, condition):
except (GLib.Error, OSError, ValueError, subprocess.CalledProcessError):
indicator.pending = ""
refresh()
GLib.source_remove(timer)
timer = GLib.timeout_add(50 if indicator.pending else 500, poll)
schedule()
return GLib.SOURCE_CONTINUE

# Fcitx's controller has no current-method-changed signal. Keep one bus
# connection open instead of spawning a command on every poll. Polling also
# follows per-application input contexts and recovers after service restarts.
# Fcitx's controller has no current-method-changed signal, so a group with
# more than one method is still read every 500 ms, over one kept-open bus
# connection. That follows per-application input contexts and trigger keys
# pressed inside applications.
GLib.io_add_watch(sys.stdin, GLib.IO_IN | GLib.IO_HUP, command)
# Held for as long as the loop runs.
watchers = follow(bus, changed, presence) # noqa: F841
poll()
loop.run()

Expand Down
2 changes: 2 additions & 0 deletions docs/input-methods.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ The ISO carries the extra fields in `omarchy_install.input_method` and `omarchy_

Keyboard selections are persisted as data in `~/.config/omarchy/keyboard-layouts`; `default.hypr.keyboard.selected()` reads them before falling back to installation defaults. Personal Hyprland overrides still take precedence. A save reloads and validates the compositor, aligns the Fcitx group's primary keyboard with the leading layout/variant, and restores the previous configuration and group on failure. Non-Latin selections keep the installer's Latin-leading rule for desktop shortcuts. System console, disk-unlock, and greeter layouts are unchanged.

The bar reads Fcitx through one long-running reader, `default/input-methods/indicator.py`, started by `shell/Commons/InputMethodState.qml`. Fcitx signals neither a method switch nor a configuration change over D-Bus (Controller1's `InputMethodGroupsChanged` stays silent for both), so the reader reads once at startup and again when the `org.fcitx.Fcitx5` bus name changes owner or the profile changes. The profile is `$FCITX_CONFIG_HOME/profile`, else `$XDG_CONFIG_HOME/fcitx5/profile`, located from the environment of the process that owns the bus name each time it appears, so a service drop-in that moves it is followed. The file watch follows saves that rename a new profile into place; a dotfiles directory relinked while Fcitx runs is picked up at Fcitx's next start. It polls every 500 ms only while there is something to switch between: more than one method in the current group, a lone composition engine (which still toggles and steps aside in password fields), or more than one group. A read that fails while the service is running is retried every 2 s. A single-method setup costs no wakeups.

Shortcut defaults reserve Ctrl+Space for Tmux/Herdr, Super+Space for the menu, Super+Shift+Space for the bar, and Super+grave for the console. Hyprland owns Super+I to cycle all selected compositor layouts followed by the configured Fcitx input methods, independently of Fcitx switching keys. With keyboard layouts alone, the same shortcut cycles the compositor layouts, keeping matching devices in sync even without the bar widget. The widget is enabled in the default right-hand bar layout and appears only when more than one input method or keyboard layout is configured. Fcitx handles Zenkaku/Hankaku and Hangul; Henkan activates and Muhenkan deactivates. Ctrl+Space is never a Fcitx toggle: `configure --defaults` removes it from any TriggerKeys list, keeping the user's other keys, and writes Omarchy's list where none exists, since Fcitx's built-in default includes it. Other existing lists, including empty ones, are preserved, and stock generated lists are repaired only while the user still has the single-keyboard default profile. A terminal Ctrl+Space returns to direct input before the following key, with a 300 ms timeout and no D-Bus activation. Wayland and XCB addons do not override the compositor's XKB settings.

The migration installs the standard engines and applies conservative defaults. It aligns an untouched Fcitx keyboard profile with the install layout, using the live controller when Fcitx is running. It leaves existing multilingual profiles and working trigger keys alone. Atomic file writes follow configuration symlinks, preserve file modes, and roll back on a failed seed or migration so a retry can complete. Migration bus errors defer profile alignment to the next login and do not restart input. If a pre-update daemon has not discovered a new engine, the migration aligns only its keyboard and prints the setup command.
Expand Down
Loading