From b0154e7f15d590dfde0c360d5f297f5e5e281ab0 Mon Sep 17 00:00:00 2001 From: ElGregor Date: Fri, 30 Oct 2026 00:43:24 +0100 Subject: [PATCH 1/7] feat(hotkey): Hotkey ueber gsettings in beiden Sitzungen (#58) --- README.md | 34 +- additional/python/keybinding_files.py | 241 ++++++++++- additional/python/setup_keybinding.py | 360 +++++++++++++++-- .../python/tests/test_keybinding_report.py | 376 ++++++++++++++++++ 4 files changed, 946 insertions(+), 65 deletions(-) create mode 100644 additional/python/tests/test_keybinding_report.py diff --git a/README.md b/README.md index a509505f..2b51000e 100644 --- a/README.md +++ b/README.md @@ -23,23 +23,19 @@ hand. ## Keyboard shortcut -Linux Assistant registers a global hotkey that brings the launcher to the +Linux Assistant has a global hotkey that brings the launcher to the foreground. The default is `Super+Q`, except on **KDE**, **Pop!_OS**, **Ubuntu** and **Zorin OS**, where the desktop convention is `Alt+Q` and the app follows it. `lib/services/linux.dart` (`getHotkeyModifier()`) is the source of truth. -Two registration paths exist and the app picks one at startup based on the -session type: - -- **X11 sessions** — the app grabs the key itself via libkeybinder. The grab - uses the modifier above, so what the greeter tells the user matches what is - actually grabbed. -- **Wayland sessions** — there is no global X11 grab, so the libkeybinder call - is skipped (it used to log `Binding 'q' failed!` on every start) and - the desktop's own gsettings shortcut is registered instead, through - `additional/python/setup_keybinding.py`. The entry is written once and - reused — the script looks for an entry whose `command` is `linux-assistant` - before adding a new one, so repeated starts no longer pile up duplicates. +The desktop registers the shortcut, not the app itself: the app writes a +custom keybinding into the session's own settings (gsettings) through +`additional/python/setup_keybinding.py`. Because the desktop owns the binding, +the same shortcut works under **X11** and **Wayland** alike — there is no +separate X11-only key grab and no X11-only binding library in the dependency +list. The entry is written once and reused — the script looks for an entry +whose `command` is `linux-assistant` before adding a new one, so repeated +starts no longer pile up duplicates. See [Uninstall](#uninstall) for how to remove the shortcut, which lives in the desktop's settings rather than in the package. @@ -49,21 +45,21 @@ desktop's settings rather than in the package. To build: ```bash -sudo apt install libkeybinder-3.0-0 libkeybinder-3.0-dev +sudo apt install ninja-build libgtk-3-dev mesa-utils ``` To run an installed package, only the runtime libraries are needed — the `.deb` declares them, so `apt` pulls them in for you. The declared runtime set is -`libgtk-3-0, libkeybinder-3.0-0, python3, python3-gi, -gir1.2-gtk-3.0, python3-apt, mesa-utils, pkexec | policykit-1, xdg-utils, -libgtk-3-bin, libglib2.0-bin` (see `deb/DEBIAN/control`). +`libgtk-3-0, python3, python3-gi, gir1.2-gtk-3.0, python3-apt, mesa-utils, +pkexec | policykit-1, xdg-utils, libgtk-3-bin, libglib2.0-bin` (see +`deb/DEBIAN/control`). If you build with `flutter build linux` and run the bundle directly (Option 1 under [Build](#build)), `apt` does not install those packages for you. The Python helpers need GObject introspection, so install them by hand first: ```bash -sudo apt install libgtk-3-0 libkeybinder-3.0-0 python3 python3-gi \ +sudo apt install libgtk-3-0 python3 python3-gi \ gir1.2-gtk-3.0 python3-apt mesa-utils policykit-1 \ xdg-utils libgtk-3-bin libglib2.0-bin ``` @@ -71,7 +67,7 @@ sudo apt install libgtk-3-0 libkeybinder-3.0-0 python3 python3-gi \ ## Build ```bash -# Install keybinder, see requirements +# Install the build dependencies, see requirements sudo rm /etc/apt/preferences.d/nosnap.pref # (For Linux Mint) sudo apt install snapd git sudo snap install flutter --classic diff --git a/additional/python/keybinding_files.py b/additional/python/keybinding_files.py index cad2c351..ae8ab189 100644 --- a/additional/python/keybinding_files.py +++ b/additional/python/keybinding_files.py @@ -1,18 +1,32 @@ -"""Pure text transformations for the KDE and XFCE shortcut files. +"""Pure helpers for the keyboard shortcut handling. -Both handlers appended unconditionally. `khotkeysrc` grew another `[Data_N]` -block on every run, `kglobalshortcutsrc` another line carrying the *same* -hardcoded UUID, and XFCE's property path contains the modifier -(`/commands/custom/q`), so switching from Super to Alt left the old -binding in place next to the new one. The GNOME and Cinnamon handlers already -looked for an entry they own before adding one; these bring the other two to -the same behaviour. +Two groups of things live here: + +* the text transformations for the KDE and XFCE shortcut files. Both handlers + appended unconditionally. `khotkeysrc` grew another `[Data_N]` block on + every run, `kglobalshortcutsrc` another line carrying the *same* hardcoded + UUID, and XFCE's property path contains the modifier + (`/commands/custom/q`), so switching from Super to Alt left the old + binding in place next to the new one. The GNOME and Cinnamon handlers + already looked for an entry they own before adding one; these bring the + other two to the same behaviour. + +* the entry helpers for the diagnosis of the shortcut state: the next free + `customN` name, the search for our own entries, the detection of the + orphaned ones and the report that goes with it. + +Everything in the second group works on plain data — lists of entries and +strings — and needs neither a desktop session nor PyGObject. That is why it +is here and not in `setup_keybinding.py`, which can only be exercised on a +running desktop. Kept as line-in, line-out functions so they can be tested without a desktop session. """ +import json import re +from dataclasses import dataclass COMMAND = "linux-assistant" @@ -43,6 +57,19 @@ def find_kde_data_number(lines): return None +def find_kde_trigger_key(lines, number): + """The key combination of an existing `[Data_N…]` block, or None. + + The number comes from `find_kde_data_number`; the key itself lives in + the `Data_NTriggers0` section of that block. + """ + section = f"Data_{number}Triggers0" + for i, line in enumerate(lines): + if line.startswith("Key=") and _section_of(lines, i) == section: + return line[len("Key="):].strip() + return None + + def kde_khotkeysrc(lines, key): """Returns khotkeysrc lines with exactly one shortcut of ours, bound to [key].""" lines = list(lines) @@ -151,3 +178,201 @@ def xfce_properties_of_ours(listing): if len(parts) >= 2 and parts[-1] == COMMAND: paths.append(parts[0]) return paths + + +def xfce_binding_of_path(path): + """The key combination out of an XFCE property path. + + `/commands/custom/q` holds `q`; the property path is the + only place XFCE keeps the combination. + """ + prefix = "/commands/custom/" + if path.startswith(prefix): + return path[len(prefix):] + return path + + +# ------------------------------------------------------------------------------ +# Shortcut entries and the diagnosis of their state +# ------------------------------------------------------------------------------ +# +# GNOME and Cinnamon keep their own shortcuts in a `customN` list of the +# desktop's settings. Every run of the setup used to look for a free name on +# its own, and an entry of ours that carried an outdated key combination was +# never taken away — so a session could end up with several `custom*` entries +# of ours, of which only one actually works. + +DESKTOP_CINNAMON = "cinnamon" +DESKTOP_GNOME = "gnome" +DESKTOP_XFCE = "xfce" +DESKTOP_KDE = "kde" +UNKNOWN = "unknown" + +SESSION_WAYLAND = "wayland" +SESSION_X11 = "x11" + +# The number of a `customN` entry, e.g. `custom12`. The name of the list in +# GNOME ("custom-keybindings") carries no number, so it does not match. +CUSTOM_NAME_PATTERN = re.compile(r"custom(\d+)") + + +@dataclass(frozen=True) +class KeybindingEntry: + """One shortcut entry of the desktop's own keybinding list. + + `path` is where the entry lives (a gsettings path, an xfconf property), + `command` is what it runs and `binding` is the key combination it uses. + """ + + path: str + command: str + binding: str + + +def next_custom_name(names): + """The next free `customN` name for a list of existing names. + + GNOME and Cinnamon both number their custom entries `custom0`, `custom1`, … + and the number is part of the path, so the search looks at the last + `customN` of every name. The lowest free number wins, which keeps the + numbering dense instead of growing on every run. + + The search for the free name was duplicated in both desktop handlers; it + is here once, so both use the same rule. + """ + used = set() + for name in names: + matches = CUSTOM_NAME_PATTERN.findall(name) + if matches: + used.add(int(matches[-1])) + number = 0 + while number in used: + number += 1 + return f"custom{number}" + + +def our_entries(entries): + """The entries that run our own command. + + Everything the cleanup does starts from this list, so a shortcut of + another application can never be touched: it is not in here. + """ + return [entry for entry in entries if entry.command == COMMAND] + + +def find_orphans(entries, wanted_binding): + """Our own entries that are not the currently valid shortcut. + + The valid one is the first of our entries that carries the wanted key + combination; every other entry of ours is an orphan — an older one with + a different modifier, or a duplicate of the valid one. + + Without a known valid combination nothing can be judged an orphan, so + nothing is returned in that case. + """ + ours = our_entries(entries) + if not wanted_binding: + return [] + + valid = None + for entry in ours: + if entry.binding == wanted_binding: + valid = entry + break + + if valid is None: + # None of our entries carries the wanted combination — they are all + # leftovers of an earlier modifier and do not deliver the shortcut. + return list(ours) + + return [entry for entry in ours if entry is not valid] + + +def remove_orphans(entries, wanted_binding): + """The entries without the orphans, and the orphans themselves. + + The second list is always a part of `our_entries`, so removing one can + never hit a shortcut of another application. + """ + orphans = find_orphans(entries, wanted_binding) + orphan_paths = {orphan.path for orphan in orphans} + remaining = [entry for entry in entries if entry.path not in orphan_paths] + return remaining, orphans + + +def is_registered(entries, wanted_binding): + """True iff one of our own entries carries the wanted combination.""" + if not wanted_binding: + return False + return any(entry.binding == wanted_binding for entry in our_entries(entries)) + + +def build_report(desktop, session, entries, wanted_binding): + """The diagnosis of the shortcut state as a plain dict. + + `registered` says whether our shortcut is in place, `orphans` lists our + own entries that are not that one. The desktop and the session are taken + as they are, so this can be built without a running session. + """ + return { + "desktop": desktop, + "session": session, + "binding": wanted_binding, + "registered": is_registered(entries, wanted_binding), + "orphans": [ + {"path": orphan.path, "binding": orphan.binding} + for orphan in find_orphans(entries, wanted_binding) + ], + } + + +def build_cleanup_result(desktop, session, wanted_binding, entries_after, removed): + """What the cleanup did — the shape of the report, plus the removals.""" + return { + "desktop": desktop, + "session": session, + "binding": wanted_binding, + "registered": is_registered(entries_after, wanted_binding), + "removed": [ + {"path": entry.path, "binding": entry.binding} for entry in removed + ], + } + + +def report_json(payload): + """The payload as a single JSON line. + + The whole line is built before anything is written, so a broken payload + can never end up half printed on stdout. + """ + return json.dumps(payload, ensure_ascii=False) + + +def detect_desktop(environment): + """The desktop we are on, read from XDG_CURRENT_DESKTOP. + + The variable holds a colon separated list ("zorin:GNOME"), so all of it + is looked at. The order of the checks is the order the setup uses: + "X-Cinnamon:GNOME" mentions GNOME as well and must not be taken for it. + """ + current = (environment.get("XDG_CURRENT_DESKTOP") or "").lower() + for desktop in (DESKTOP_CINNAMON, DESKTOP_GNOME, DESKTOP_XFCE, DESKTOP_KDE): + if desktop in current: + return desktop + return UNKNOWN + + +def detect_session_type(environment): + """The session type we are in: wayland, x11 or unknown. + + XDG_SESSION_TYPE is the reliable source; the display variables are the + fallback for the case that it is missing. + """ + session_type = (environment.get("XDG_SESSION_TYPE") or "").strip().lower() + if session_type in (SESSION_WAYLAND, SESSION_X11): + return session_type + if environment.get("WAYLAND_DISPLAY"): + return SESSION_WAYLAND + if environment.get("DISPLAY"): + return SESSION_X11 + return UNKNOWN diff --git a/additional/python/setup_keybinding.py b/additional/python/setup_keybinding.py index 806f6f2e..6f258822 100644 --- a/additional/python/setup_keybinding.py +++ b/additional/python/setup_keybinding.py @@ -1,9 +1,30 @@ -from gi.repository import Gio +"""Registration and diagnosis of the "bring me up" shortcut. + +Without an argument the script registers the shortcut with the desktop and +ends — that is what the app calls on its first start. `--report` prints the +current state as a single JSON line (the diagnosis row of the app), +`--cleanup` takes the orphaned `custom*` entries of ours away. + +Both modes read the shortcut list of the desktop, so they run in the session +of the user and need no root. The pure parts of the diagnosis live in +`keybinding_files.py` and are tested without a desktop. +""" + +import os +import subprocess +import sys + +try: + from gi.repository import Gio +except ImportError: + # PyGObject is missing where the GNOME stack is not installed. The report + # still works there as long as the desktop is unknown; everything that + # reads the settings of a desktop fails with a readable message. + Gio = None + import jessentials import jfiles import jfolders -import os -import subprocess import keybinding_files @@ -32,22 +53,11 @@ def add_linux_assistant_keybinding_cinnamon(): entry.apply() return - num_array = [] - for entry in array: - if entry == DUMMY_CUSTOM_ENTRY_CINNAMON: - continue - num_array.append(int(entry.replace("custom", ""))) - num_array.sort() - i = 0 - while True: - if i in num_array: - i += 1 - else: - break - new_str = "custom" + str(i) - array.append(new_str) + # The free name is searched in one place for both desktop handlers. + custom_name = keybinding_files.next_custom_name( + [name for name in array if name != DUMMY_CUSTOM_ENTRY_CINNAMON]) + array.append(custom_name) parent.set_strv("custom-list", array) - custom_name = f"custom{i}" # Insert new keybinding entry custom_path = f"{CUSTOM_KEYS_BASENAME_CINNAMON}/{custom_name}/" @@ -103,19 +113,9 @@ def add_linux_assistant_keybinding_gnome(): entry.apply() return - num_array = [] - for entry in array: - if "/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom" in entry: - num_array.append(int(entry.replace("/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom", "").replace("/", ""))) - num_array.sort() - i = 0 - while True: - if i in num_array: - i += 1 - else: - break - custom_name = f"custom{i}" - array.append(f"/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/{custom_name}/") + # The free name is searched in one place for both desktop handlers. + custom_name = keybinding_files.next_custom_name(array) + array.append(f"{CUSTOM_KEYS_BASENAME_GNOME}/{custom_name}/") parent.set_strv("custom-keybindings", array) # Insert new keybinding entry @@ -188,34 +188,318 @@ def add_linux_assistant_keybinding_kde(): ) +# Diagnosis -------------------------------------------------------------------------------- + +# KDE writes its shortcut as `Alt+Q`, the gsettings based desktops as +# `q` resp. `q`. +KDE_KEY = "Alt+Q" + + +def require_gio(): + """Fails with a readable message when PyGObject is not installed.""" + if Gio is None: + jessentials.fail( + "PyGObject (python3-gi) is not installed, the shortcut list of " + "the desktop cannot be read.", 1) + + +def expected_binding(desktop): + """The key combination the desktop is supposed to use.""" + if desktop == keybinding_files.DESKTOP_KDE: + return KDE_KEY + return f"{KEY_MODIFIER}q" + + +def read_gsettings_entry(schema, path, binding_is_list): + """One custom keybinding entry, or None when it cannot be read. + + A stale path in the list of the desktop is not worth failing the whole + report for, so it is skipped. + """ + try: + child = Gio.Settings.new_with_path(schema, path) + if binding_is_list: + # Cinnamon keeps the combination as a list of accelerators, GNOME + # as a single string. + binding = "".join(child.get_strv("binding")) + else: + binding = child.get_string("binding") + return keybinding_files.KeybindingEntry( + path=path, + command=child.get_string("command"), + binding=binding, + ) + except Exception: + return None + + +def gsettings_entries_gnome(): + """The custom keybindings of GNOME.""" + require_gio() + parent = Gio.Settings.new(CUSTOM_KEYS_PARENT_SCHEMA_GNOME) + entries = [] + for path in parent.get_strv("custom-keybindings"): + entry = read_gsettings_entry(CUSTOM_KEYS_SCHEMA_GNOME, path, False) + if entry is not None: + entries.append(entry) + return entries + + +def gsettings_entries_cinnamon(): + """The custom keybindings of Cinnamon.""" + require_gio() + parent = Gio.Settings.new(CUSTOM_KEYS_PARENT_SCHEMA_CINNAMON) + entries = [] + for name in parent.get_strv("custom-list"): + if name == DUMMY_CUSTOM_ENTRY_CINNAMON: + continue + path = f"{CUSTOM_KEYS_BASENAME_CINNAMON}/{name}/" + entry = read_gsettings_entry(CUSTOM_KEYS_SCHEMA_CINNAMON, path, True) + if entry is not None: + entries.append(entry) + return entries + + +def xfce_entries(): + """Our shortcuts in the shortcut store of XFCE.""" + listing = subprocess.run( + ["xfconf-query", "-c", "xfce4-keyboard-shortcuts", "-lv"], + capture_output=True, text=True, check=False, + ).stdout + entries = [] + for path in keybinding_files.xfce_properties_of_ours(listing): + entries.append(keybinding_files.KeybindingEntry( + path=path, + command=keybinding_files.COMMAND, + binding=keybinding_files.xfce_binding_of_path(path), + )) + return entries + + +def kde_entries(): + """Our shortcut in the shortcut file of KDE.""" + khotkeysrc = jfolders.replace_tilde_to_home("~/.config/khotkeysrc") + if not jfiles.does_file_exist(khotkeysrc): + return [] + lines = jfiles.get_all_lines_from_file(khotkeysrc) + number = keybinding_files.find_kde_data_number(lines) + if number is None: + return [] + binding = keybinding_files.find_kde_trigger_key(lines, number) + if binding is None: + return [] + return [keybinding_files.KeybindingEntry( + path=f"khotkeysrc:Data_{number}", + command=keybinding_files.COMMAND, + binding=binding, + )] + + +def read_entries(desktop): + """The shortcut entries of the desktop we are on. + + An unknown desktop has no list to read — the report then says + `registered: false` instead of guessing. + """ + if desktop == keybinding_files.DESKTOP_GNOME: + return gsettings_entries_gnome() + if desktop == keybinding_files.DESKTOP_CINNAMON: + return gsettings_entries_cinnamon() + if desktop == keybinding_files.DESKTOP_XFCE: + return xfce_entries() + if desktop == keybinding_files.DESKTOP_KDE: + return kde_entries() + return [] + + +def reset_gsettings_entry(schema, path): + """Clears the values of an entry that was taken away. + + The entry is out of the list of the desktop already, so the leftovers + are invisible — but they would still be found by a scan of the settings + database. A failure here must not abort the cleanup. + """ + try: + child = Gio.Settings.new_with_path(schema, path) + for key in ("name", "command", "binding"): + try: + child.reset(key) + except Exception: + continue + child.sync() + except Exception: + return + + +def remove_gnome_orphans(orphans): + """Removes the given entries from the custom keybindings of GNOME.""" + require_gio() + paths = {orphan.path for orphan in orphans} + parent = Gio.Settings.new(CUSTOM_KEYS_PARENT_SCHEMA_GNOME) + current = parent.get_strv("custom-keybindings") + kept = [path for path in current if path not in paths] + if len(kept) == len(current): + return [] + parent.set_strv("custom-keybindings", kept) + for path in paths: + reset_gsettings_entry(CUSTOM_KEYS_SCHEMA_GNOME, path) + return [orphan for orphan in orphans if orphan.path in paths] + + +def remove_cinnamon_orphans(orphans): + """Removes the given entries from the custom keybindings of Cinnamon.""" + require_gio() + paths = {orphan.path for orphan in orphans} + parent = Gio.Settings.new(CUSTOM_KEYS_PARENT_SCHEMA_CINNAMON) + current = parent.get_strv("custom-list") + kept = [ + name for name in current + if name == DUMMY_CUSTOM_ENTRY_CINNAMON + or f"{CUSTOM_KEYS_BASENAME_CINNAMON}/{name}/" not in paths + ] + if len(kept) == len(current): + return [] + parent.set_strv("custom-list", kept) + for path in paths: + reset_gsettings_entry(CUSTOM_KEYS_SCHEMA_CINNAMON, path) + return [orphan for orphan in orphans if orphan.path in paths] + + +def remove_xfce_orphans(orphans): + """Removes the given properties from the shortcut store of XFCE.""" + removed = [] + for orphan in orphans: + result = subprocess.run( + ["xfconf-query", "-c", "xfce4-keyboard-shortcuts", + "-p", orphan.path, "-r"], + check=False, + ) + if result.returncode == 0: + removed.append(orphan) + return removed + + +def remove_orphans(desktop, orphans): + """Removes the given orphan entries and returns the ones that are gone. + + Only entries of ours are ever handed in here — the check is the second + line of defence against taking a shortcut of another application away. + """ + ours = [ + orphan for orphan in orphans + if orphan.command == keybinding_files.COMMAND + ] + if not ours: + return [] + if desktop == keybinding_files.DESKTOP_GNOME: + return remove_gnome_orphans(ours) + if desktop == keybinding_files.DESKTOP_CINNAMON: + return remove_cinnamon_orphans(ours) + if desktop == keybinding_files.DESKTOP_XFCE: + return remove_xfce_orphans(ours) + # KDE keeps its shortcuts in ~/.config/khotkeysrc; there are no custom* + # entries there to take away. + return [] + + +def write_json_line(payload): + """Writes the payload as a single JSON line on stdout. + + The line is built completely before anything is written, so a broken + payload never reaches stdout half finished. + """ + line = keybinding_files.report_json(payload) + sys.stdout.write(line + "\n") + sys.stdout.flush() + + +def run_report(): + """Prints the state of the shortcut as one JSON line on stdout.""" + try: + desktop = keybinding_files.detect_desktop(os.environ) + session = keybinding_files.detect_session_type(os.environ) + binding = expected_binding(desktop) + entries = read_entries(desktop) + payload = keybinding_files.build_report( + desktop, session, entries, binding) + write_json_line(payload) + except Exception as error: + # A broken report is worse than no report: the error goes to stderr, + # the exit code says it failed and stdout stays empty. + jessentials.fail( + f"The state of the keyboard shortcut could not be read: {error}", 1) + + +def run_cleanup(): + """Removes the orphaned entries of ours and reports what it did.""" + try: + desktop = keybinding_files.detect_desktop(os.environ) + session = keybinding_files.detect_session_type(os.environ) + binding = expected_binding(desktop) + entries = read_entries(desktop) + _, orphans = keybinding_files.remove_orphans(entries, binding) + removed = remove_orphans(desktop, orphans) + removed_paths = {entry.path for entry in removed} + remaining = [ + entry for entry in entries if entry.path not in removed_paths] + payload = keybinding_files.build_cleanup_result( + desktop, session, binding, remaining, removed) + write_json_line(payload) + + if orphans and not removed: + jessentials.printerr( + "The orphaned shortcut entries were not removed — this " + "desktop keeps them somewhere else.") + elif removed and not keybinding_files.is_registered(remaining, binding): + jessentials.printerr( + "No valid shortcut entry is left — run setup_keybinding.py " + "without --cleanup to register it again.") + except Exception as error: + jessentials.fail( + f"The orphaned shortcut entries could not be removed: {error}", 1) + + def main(): global KEY_MODIFIER if jessentials.is_argument_option_given("alt", "a"): KEY_MODIFIER = "" else: pass - + + if (jessentials.is_argument_option_given("report") + and jessentials.is_argument_option_given("cleanup")): + jessentials.fail("--report and --cleanup cannot be used together.", 1) + + # The diagnosis modes do not register anything: they read the state of + # the shortcut and clean it up. + if jessentials.is_argument_option_given("report"): + run_report() + return + if jessentials.is_argument_option_given("cleanup"): + run_cleanup() + return + # Read once and defensively: the variable is absent in a TTY and under # pkexec, where `.lower()` on None raised AttributeError. - desktop = (os.getenv("XDG_CURRENT_DESKTOP") or "").lower() + desktop = keybinding_files.detect_desktop(os.environ) # elif, not four separate ifs: XDG_CURRENT_DESKTOP is a colon separated # list ("zorin:GNOME", "X-Cinnamon:GNOME"), so more than one token can # match and the binding would be registered twice. - if "cinnamon" in desktop: + if desktop == keybinding_files.DESKTOP_CINNAMON: add_linux_assistant_keybinding_cinnamon() - elif "gnome" in desktop: + elif desktop == keybinding_files.DESKTOP_GNOME: add_linux_assistant_keybinding_gnome() - elif "xfce" in desktop: + elif desktop == keybinding_files.DESKTOP_XFCE: add_linux_assistant_keybinding_xfce() - elif "kde" in desktop: + elif desktop == keybinding_files.DESKTOP_KDE: add_linux_assistant_keybinding_kde() else: # Exit non-zero: the Dart side marks the hotkey done on success and # never retries. A silent "nothing registered" left the shortcut # dead forever on sessions of unlisted desktops. jessentials.fail( - f"No supported desktop found in XDG_CURRENT_DESKTOP='{desktop}', " + f"No supported desktop found in XDG_CURRENT_DESKTOP='{os.getenv('XDG_CURRENT_DESKTOP') or ''}', " "no keyboard shortcut was registered.", 1) if __name__ == "__main__": diff --git a/additional/python/tests/test_keybinding_report.py b/additional/python/tests/test_keybinding_report.py new file mode 100644 index 00000000..16001a6b --- /dev/null +++ b/additional/python/tests/test_keybinding_report.py @@ -0,0 +1,376 @@ +"""Tests for the keybinding report and the cleanup of orphaned entries. + +The report is the diagnosis row of the app, the cleanup repairs a session +that collected several `custom*` entries of ours. The rules work on plain +data and are tested here without a desktop session; the script itself is +only exercised for its command line contract, which needs neither a +desktop nor PyGObject. +""" + +import json +import os +import subprocess +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import keybinding_files # noqa: E402 + + +PYTHON_HELPER_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SCRIPT = os.path.join(PYTHON_HELPER_DIR, "setup_keybinding.py") + +GNOME_PATH = "/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings" +CINNAMON_PATH = "/org/cinnamon/desktop/keybindings/custom-keybindings" + + +def entry(path, command, binding): + """One shortcut entry of the desktop's own list.""" + return keybinding_files.KeybindingEntry( + path=path, command=command, binding=binding) + + +def run_script(*arguments, environment=None): + """Runs the script with a controlled environment. + + The environment is built from scratch, so the desktop of the machine + that runs the tests cannot leak into the result. + """ + env = { + "PATH": os.environ.get("PATH", "/usr/bin:/bin"), + "HOME": os.environ.get("HOME", "/tmp"), + } + if environment: + env.update(environment) + return subprocess.run( + [sys.executable, SCRIPT, *arguments], + capture_output=True, text=True, env=env, check=False, timeout=60, + ) + + +class NextCustomName(unittest.TestCase): + def test_the_gap_in_the_numbering_is_filled(self): + self.assertEqual( + keybinding_files.next_custom_name(["custom0", "custom2"]), + "custom1", + ) + + def test_a_dense_list_grows_by_one(self): + self.assertEqual( + keybinding_files.next_custom_name(["custom0", "custom1"]), + "custom2", + ) + + def test_an_empty_list_starts_at_zero(self): + self.assertEqual(keybinding_files.next_custom_name([]), "custom0") + + def test_the_gnome_paths_are_read_as_well(self): + self.assertEqual( + keybinding_files.next_custom_name([ + f"{GNOME_PATH}/custom0/", + f"{GNOME_PATH}/custom2/", + ]), + "custom1", + ) + + def test_the_dummy_entry_of_cinnamon_is_ignored(self): + self.assertEqual( + keybinding_files.next_custom_name(["__dummy__", "custom0"]), + "custom1", + ) + + +class OrphanDetection(unittest.TestCase): + OURS_VALID = entry(f"{GNOME_PATH}/custom0/", "linux-assistant", "q") + OURS_STALE = entry(f"{GNOME_PATH}/custom3/", "linux-assistant", "q") + FOREIGN = entry(f"{GNOME_PATH}/custom1/", "firefox", "f") + + def test_the_entry_with_the_wrong_combination_is_an_orphan(self): + orphans = keybinding_files.find_orphans( + [self.OURS_VALID, self.OURS_STALE], "q") + + self.assertEqual([orphan.path for orphan in orphans], + [f"{GNOME_PATH}/custom3/"]) + + def test_a_foreign_entry_is_never_an_orphan(self): + orphans = keybinding_files.find_orphans( + [self.OURS_VALID, self.FOREIGN], "q") + + self.assertEqual(orphans, []) + + def test_a_duplicate_of_the_valid_entry_is_an_orphan(self): + duplicate = entry(f"{GNOME_PATH}/custom4/", "linux-assistant", "q") + + orphans = keybinding_files.find_orphans( + [self.OURS_VALID, duplicate], "q") + + self.assertEqual([orphan.path for orphan in orphans], + [f"{GNOME_PATH}/custom4/"]) + + def test_our_entries_without_the_wanted_combination_are_orphans(self): + orphans = keybinding_files.find_orphans([self.OURS_STALE], "q") + + self.assertEqual([orphan.path for orphan in orphans], + [f"{GNOME_PATH}/custom3/"]) + + def test_without_a_known_combination_nothing_is_an_orphan(self): + orphans = keybinding_files.find_orphans( + [self.OURS_VALID, self.OURS_STALE], "") + + self.assertEqual(orphans, []) + + def test_the_entries_of_ours_are_the_only_ones_considered(self): + entries = [self.OURS_VALID, self.OURS_STALE, self.FOREIGN] + + self.assertEqual( + [item.path for item in keybinding_files.our_entries(entries)], + [f"{GNOME_PATH}/custom0/", f"{GNOME_PATH}/custom3/"], + ) + + +class OrphanRemoval(unittest.TestCase): + OURS_VALID = entry(f"{GNOME_PATH}/custom0/", "linux-assistant", "q") + OURS_STALE = entry(f"{GNOME_PATH}/custom3/", "linux-assistant", "q") + FOREIGN = entry(f"{GNOME_PATH}/custom1/", "firefox", "f") + + def test_the_orphan_is_gone_and_the_rest_stays(self): + entries = [self.OURS_VALID, self.FOREIGN, self.OURS_STALE] + + remaining, removed = keybinding_files.remove_orphans(entries, "q") + + self.assertEqual([item.path for item in remaining], + [f"{GNOME_PATH}/custom0/", f"{GNOME_PATH}/custom1/"]) + self.assertEqual([item.path for item in removed], + [f"{GNOME_PATH}/custom3/"]) + + def test_a_foreign_entry_is_never_removed(self): + entries = [self.FOREIGN] + + remaining, removed = keybinding_files.remove_orphans(entries, "q") + + self.assertEqual(remaining, entries) + self.assertEqual(removed, []) + + +class Report(unittest.TestCase): + OURS_VALID = entry(f"{GNOME_PATH}/custom0/", "linux-assistant", "q") + OURS_STALE = entry(f"{GNOME_PATH}/custom3/", "linux-assistant", "q") + FOREIGN = entry(f"{GNOME_PATH}/custom1/", "firefox", "f") + + def test_the_report_is_valid_json_with_the_expected_fields(self): + payload = keybinding_files.build_report( + "gnome", "wayland", [self.OURS_VALID], "q") + + self.assertEqual( + sorted(payload.keys()), + ["binding", "desktop", "orphans", "registered", "session"], + ) + parsed = json.loads(keybinding_files.report_json(payload)) + self.assertEqual(parsed["desktop"], "gnome") + self.assertEqual(parsed["session"], "wayland") + self.assertEqual(parsed["binding"], "q") + + def test_nothing_registered_gives_an_empty_report(self): + payload = keybinding_files.build_report( + "gnome", "wayland", [], "q") + + self.assertFalse(payload["registered"]) + self.assertEqual(payload["orphans"], []) + + def test_the_orphans_are_listed_with_path_and_combination(self): + payload = keybinding_files.build_report( + "gnome", "x11", [self.OURS_VALID, self.OURS_STALE], "q") + + self.assertTrue(payload["registered"]) + self.assertEqual( + payload["orphans"], + [{"path": f"{GNOME_PATH}/custom3/", "binding": "q"}], + ) + + def test_a_foreign_entry_does_not_show_up_in_the_report(self): + payload = keybinding_files.build_report( + "gnome", "x11", [self.OURS_VALID, self.FOREIGN], "q") + + self.assertEqual(payload["orphans"], []) + + def test_an_unknown_desktop_is_reported_as_unknown(self): + payload = keybinding_files.build_report( + "unknown", "unknown", [], "q") + + self.assertEqual(payload["desktop"], "unknown") + self.assertFalse(payload["registered"]) + + def test_the_report_is_one_line(self): + line = keybinding_files.report_json( + keybinding_files.build_report("gnome", "wayland", [], "q")) + + self.assertNotIn("\n", line) + self.assertEqual(json.loads(line)["desktop"], "gnome") + + +class CleanupResult(unittest.TestCase): + def test_the_removed_entries_are_listed(self): + removed = entry(f"{GNOME_PATH}/custom3/", "linux-assistant", "q") + + payload = keybinding_files.build_cleanup_result( + "gnome", "wayland", "q", [], [removed]) + + self.assertEqual( + payload["removed"], + [{"path": f"{GNOME_PATH}/custom3/", "binding": "q"}], + ) + self.assertFalse(payload["registered"]) + + def test_the_state_after_the_cleanup_is_reported(self): + valid = entry(f"{GNOME_PATH}/custom0/", "linux-assistant", "q") + + payload = keybinding_files.build_cleanup_result( + "gnome", "wayland", "q", [valid], []) + + self.assertTrue(payload["registered"]) + self.assertEqual(payload["removed"], []) + + +class DesktopDetection(unittest.TestCase): + def test_gnome_is_recognized(self): + self.assertEqual( + keybinding_files.detect_desktop({"XDG_CURRENT_DESKTOP": "GNOME"}), + "gnome", + ) + + def test_cinnamon_wins_over_gnome(self): + self.assertEqual( + keybinding_files.detect_desktop( + {"XDG_CURRENT_DESKTOP": "X-Cinnamon:GNOME"}), + "cinnamon", + ) + + def test_a_colon_separated_list_is_read(self): + self.assertEqual( + keybinding_files.detect_desktop({"XDG_CURRENT_DESKTOP": "zorin:GNOME"}), + "gnome", + ) + + def test_xfce_is_recognized(self): + self.assertEqual( + keybinding_files.detect_desktop({"XDG_CURRENT_DESKTOP": "XFCE"}), + "xfce", + ) + + def test_kde_is_recognized(self): + self.assertEqual( + keybinding_files.detect_desktop({"XDG_CURRENT_DESKTOP": "KDE"}), + "kde", + ) + + def test_an_unknown_desktop_says_so(self): + self.assertEqual( + keybinding_files.detect_desktop({"XDG_CURRENT_DESKTOP": "Sway"}), + "unknown", + ) + + def test_a_missing_variable_says_unknown(self): + self.assertEqual(keybinding_files.detect_desktop({}), "unknown") + + +class SessionDetection(unittest.TestCase): + def test_wayland_is_recognized(self): + self.assertEqual( + keybinding_files.detect_session_type( + {"XDG_SESSION_TYPE": "wayland", "DISPLAY": ":0"}), + "wayland", + ) + + def test_x11_is_recognized(self): + self.assertEqual( + keybinding_files.detect_session_type({"XDG_SESSION_TYPE": "x11"}), + "x11", + ) + + def test_the_display_variable_is_the_fallback(self): + self.assertEqual( + keybinding_files.detect_session_type({"WAYLAND_DISPLAY": "wayland-0"}), + "wayland", + ) + self.assertEqual( + keybinding_files.detect_session_type({"DISPLAY": ":0"}), + "x11", + ) + + def test_without_a_session_it_is_unknown(self): + self.assertEqual(keybinding_files.detect_session_type({}), "unknown") + + +class XfceBinding(unittest.TestCase): + def test_the_combination_is_taken_from_the_path(self): + self.assertEqual( + keybinding_files.xfce_binding_of_path("/commands/custom/q"), + "q", + ) + + def test_a_path_without_the_prefix_is_kept_as_it_is(self): + self.assertEqual( + keybinding_files.xfce_binding_of_path("/commands/custom"), + "/commands/custom", + ) + + +class CommandLine(unittest.TestCase): + """The contract of the script on the command line.""" + + def test_the_report_prints_one_json_line(self): + result = run_script("--report", environment={"XDG_CURRENT_DESKTOP": ""}) + + self.assertEqual(result.returncode, 0, result.stderr) + lines = [line for line in result.stdout.splitlines() if line.strip()] + self.assertEqual(len(lines), 1, result.stdout) + payload = json.loads(lines[0]) + self.assertEqual(payload["desktop"], "unknown") + self.assertFalse(payload["registered"]) + self.assertEqual(payload["orphans"], []) + + def test_the_session_type_is_reported(self): + result = run_script( + "--report", environment={"XDG_SESSION_TYPE": "wayland"}) + + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout)["session"], "wayland") + + def test_the_modifier_is_taken_over(self): + result = run_script("--report", "--alt") + + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout)["binding"], "q") + + def test_the_cleanup_reports_what_it_did(self): + result = run_script("--cleanup", environment={"XDG_CURRENT_DESKTOP": ""}) + + self.assertEqual(result.returncode, 0, result.stderr) + payload = json.loads(result.stdout) + self.assertEqual(payload["removed"], []) + self.assertFalse(payload["registered"]) + + def test_both_modes_at_once_fail_without_output(self): + result = run_script("--report", "--cleanup") + + self.assertNotEqual(result.returncode, 0) + self.assertEqual(result.stdout.strip(), "") + self.assertIn("--cleanup", result.stderr) + + def test_the_report_does_not_write_a_broken_line(self): + result = run_script("--report", "--alt", environment={ + "XDG_CURRENT_DESKTOP": "GNOME", + }) + + if result.returncode == 0: + # PyGObject is installed here: the desktop is read for real. + json.loads(result.stdout) + else: + # Without PyGObject the run fails, and stdout stays empty. + self.assertEqual(result.stdout.strip(), "") + self.assertTrue(result.stderr.strip()) + + +if __name__ == "__main__": + unittest.main() From 2f16fceaac4d3f51e682e334a24684d89c34f98b Mon Sep 17 00:00:00 2001 From: ElGregor Date: Fri, 30 Oct 2026 00:43:27 +0100 Subject: [PATCH 2/7] feat(hotkey): Hotkey ueber gsettings in beiden Sitzungen (#58) (Block 2) --- deb/DEBIAN/control | 2 +- docs/handoff/v0.8.6-q4-hotkey-gsettings.md | 183 +++++++++++++++++++++ features.csv | 1 + lib/l10n/app_de.arb | 46 ++++++ 4 files changed, 231 insertions(+), 1 deletion(-) create mode 100644 docs/handoff/v0.8.6-q4-hotkey-gsettings.md diff --git a/deb/DEBIAN/control b/deb/DEBIAN/control index fb361d60..ae52a42c 100644 --- a/deb/DEBIAN/control +++ b/deb/DEBIAN/control @@ -1,5 +1,5 @@ Package: linux-assistant -Depends: libgtk-3-0, libkeybinder-3.0-0, python3, python3-gi, gir1.2-gtk-3.0, python3-apt, mesa-utils, pkexec | policykit-1, xdg-utils, libgtk-3-bin, libglib2.0-bin +Depends: libgtk-3-0, python3, python3-gi, gir1.2-gtk-3.0, python3-apt, mesa-utils, pkexec | policykit-1, xdg-utils, libgtk-3-bin, libglib2.0-bin Maintainer: Jean28518 Architecture: amd64 Homepage: https://www.linux-assistant.org/ diff --git a/docs/handoff/v0.8.6-q4-hotkey-gsettings.md b/docs/handoff/v0.8.6-q4-hotkey-gsettings.md new file mode 100644 index 00000000..5ff302d5 --- /dev/null +++ b/docs/handoff/v0.8.6-q4-hotkey-gsettings.md @@ -0,0 +1,183 @@ +# Q4 — Hotkey über gsettings in beiden Sitzungen (#58) + +> **Stand:** 2026-10-29 · **Basis:** `main` @ `d9321ef` · **Branch:** `feature/58-q4-hotkey` +> **Umfang:** Teilpunkt Q4 aus Issue #58 („Welle 1 Sofort-Nutzen: Q1–Q7"). +> **Zusammengefuehrt aus drei Spuren:** `feature/58-q4-python`, `feature/58-q4-dart`, +> `feature/58-q4-packaging` (Merge konfliktfrei, disjunkte Dateimengen). + +## Was geändert wurde + +### Spur 1 — Python-Seite (`additional/python/`) + +| Datei | Änderung | +|---|---| +| `additional/python/keybinding_files.py` | Neue reine Regeln: `KeybindingEntry`, `next_custom_name`, `our_entries`, `find_orphans`, `remove_orphans`, `is_registered`, `build_report`, `build_cleanup_result`, `report_json`, `detect_desktop`, `detect_session`, `find_kde_trigger_key`, `xfce_binding_of_path`. Alle arbeiten auf reinen Daten und brauchen **keine Desktop-Session** — nur so sind sie ohne Desktop testbar. | +| `additional/python/setup_keybinding.py` | Zwei neue Modi: `--report` (liest Zustand, schreibt eine JSON-Zeile nach stdout) und `--cleanup` (entfernt verwaiste eigene Einträge). Das Verhalten **ohne** Argument ist unverändert: genau eine Registrierung. | +| `additional/python/tests/test_keybinding_report.py` (neu) | 40 Tests für die neuen Regeln. | + +Der doppelte Code fuer den naechsten `customN`-Namen (GNOME- und Cinnamon-Handler +benutzten denselben Block) liegt jetzt an einer Stelle. + +### Spur 2 — Dart-Seite (`lib/`, `test/`) + +| Datei | Änderung | +|---|---| +| `lib/main.dart` | `initHotkeyToShowUp()` registriert den Desktop-Shortcut **immer** — in Wayland und X11. Der eigene `HotKeyScope.system`-Grab und `HotKeyManager.instance.unregisterAll()` entfallen samt Import. | +| `lib/layouts/main_screen/main_search.dart` | `SearchFieldShortcuts` (neu): Pfeil runter/hoch, Escape und Strg+D laufen ueber `Actions` + `Shortcuts` mit eigenen Intent-Typen. Die Tasten wirken **nur, solange das Suchfeld im Fokus ist** — beim globalen Handler war das nicht garantiert. | +| `lib/layouts/run_command_queue.dart` | Enter wird nativ behandelt; das `HotKey?`-Feld und die zugehoerige `dispose`-Logik entfallen. | +| `lib/layouts/after_installation/activate_hotkey.dart` | Der Desktop-Shortcut wird in beiden Sitzungen registriert. Vorher stand dort ein X11-Workaround gegen die Doppel-Ausloesung. | +| `lib/services/hotkey_diagnostics.dart` (neu) | `HotkeyDiagnostics.loadReport()` und `.cleanupOrphans()`, dazu `HotkeyReport` und `HotkeyOrphan`. Fehlerhafte Ausgabe des Skripts liefert `registered: false` statt einer Exception. | +| `lib/services/linux.dart` | `getHotkeyReport()` und `cleanupHotkeyOrphans()` — Prozessaufruf mit Argumentliste, kein Shell-String. | +| `lib/layouts/linux_health/overview.dart` | `HotkeyStatusRow`: aktuelles Binding, Status, Anzahl verwaister Eintraege, Button zum Aufraeumen. | +| `lib/l10n/app_{de,en,it}.arb`, `lib/l10n/linuxassistant_fi.arb` | 7 neue Keys in **allen vier** ARB-Dateien: `hotkeyTitle`, `hotkeyNotRegistered`, `hotkeyUnknown`, `hotkeyOrphanEntries`, `hotkeyCleanup`, `hotkeyCleanupSucceeded`, `hotkeyCleanupFailed`. | +| `test/q4_hotkey_test.dart` (neu) | 17 Tests: Report-Parsing, Fehlerpfade, und die Tastaturwirkung als Widget-Test. | + +### Spur 3 — Packaging und Metadaten + +| Datei | Änderung | +|---|---| +| `pubspec.yaml` | `hotkey_manager: ^0.2.3` raus. | +| `pubspec.lock` | Von `flutter pub get` neu erzeugt: `hotkey_manager` und seine fuenf Plattform-Pakete sind weg (−72 Zeilen). | +| `linux/flutter/generated_plugin_registrant.cc`, `linux/flutter/generated_plugins.cmake` | Von `flutter pub get` neu erzeugt: der `hotkey_manager_linux`-Registrar ist weg. **Diese Dateien sind getrackt** — ohne Regeneration bricht der Linux-Build, weil das Plugin nicht mehr existiert. | +| `deb/DEBIAN/control` | `libkeybinder-3.0-0` aus `Depends:` raus. | +| `README.md` | „Keyboard shortcut" auf einen Weg umgestellt (Desktop registriert, Wayland **und** X11); Build-Anforderung ohne Keybinder. | +| `.github/workflows/build.yml` | apt-Zeile: `libkeybinder-3.0-0 libkeybinder-3.0-dev` raus. | +| `features.csv` | Neue Zeile `Hotkey (gsettings)`, 21 Felder, Distributions-Spalten eingefroren. | + +## Wie das Tastenkürzel jetzt funktioniert + +**Vorher:** Auf X11 griff die App das Key selbst (`libkeybinder` via `hotkey_manager`, +`HotKeyScope.system`), auf Wayland war das technisch unmoeglich — dort registrierte der +Desktop den Shortcut. Zwei Wege, je nach Sitzung. + +**Nachher:** Der Desktop registriert den Shortcut in **beiden** Sitzungen ueber gsettings +(`org.gnome.settings-daemon.plugins.media-keys` bzw. +`org.cinnamon.desktop.keybindings`). Die App greift nichts mehr selbst. Der zweite +Tastendruck landet im laufenden Prozess ueber den Single-Instance-Socket und holt das +Fenster hoch. + +Der Preis: die App braucht keinen Keybinder mehr. Dafuer haengt der Shortcut an der +Desktop-Konfiguration des Benutzers — deshalb die neue Diagnosezeile. + +## Die Diagnosezeile + +`lib/layouts/linux_health/overview.dart` → `HotkeyStatusRow` zeigt: + +- das aktuelle Binding (z. B. `q`) und den Desktop, +- ob der Shortcut registriert ist, +- wie viele verwaiste `custom*`-Eintraege es gibt, mit einem Button zum Aufraeumen. + +Der Report kommt aus `setup_keybinding.py --report`: + +```json +{"desktop": "gnome", "session": "wayland", "binding": "q", + "registered": true, "orphans": [{"path": ".../custom3/", "binding": "q"}]} +``` + +**Was eine Waise ist:** ein `custom*`-Eintrag, dessen `command` `linux-assistant` ist und +der **nicht** das aktuell gueltige Binding traegt (z. B. ein alter Eintrag mit dem +falschen Modifikator, oder ein Duplikat). + +**Harte Grenze:** `our_entries()` filtert zwingend auf `command == "linux-assistant"`. +Ein Eintrag einer fremden App ist damit nie in der Kandidatenliste. Zusaetzlich: ist das +gueltige Binding unbekannt, liefert `find_orphans()` eine **leere** Liste — es wird dann +gar nichts geloescht. Der Cleanup kann also im Zweifel nichts tun, aber nie fremde +Eintraege entfernen. + +Nachgeprueft mit einem eigenen Adversarial-Test (Eintraege von `linux-assistant`, +`firefox` und `thunderbird`): die beiden fremden bleiben unangetastet. + +## TDD-Beleg + +**RED:** Die neuen Tests waren vor der Implementierung rot. Die Python-Tests fielen mit +`AttributeError` (die neuen Funktionen existierten noch nicht), der Dart-Report-Test mit +Compile-Fehlern auf das noch nicht existierende `hotkey_diagnostics.dart`, die +Widget-Tests mit fehlenden Tastatur-Ereignissen. + +**GREEN:** + +| Testdatei | Tests | Ergebnis | +|---|---|---| +| `additional/python/tests/test_keybinding_report.py` | 40 | gruen | +| `test/q4_hotkey_test.dart` | 17 | gruen | +| Python-Root-Runner gesamt | 102 | gruen | +| Dart-Suite gesamt | 314 | gruen | + +Die drei Widget-Tests in `test/q4_hotkey_test.dart` sind der eigentliche Beweis, dass +`hotkey_manager` ersetzt wurde: + +- `arrow down moves the selection in the result list` — die Auswahl wandert wirklich, +- `escape empties the search field` — Escape leert wirklich, +- `the keys only work while the search field has the focus` — die Tasten bleiben stumm, + wenn das Feld nicht im Fokus ist (beim alten globalen Handler war das der Normalfall). + +## Gate-Protokoll + +`bash /workspace/tools/run-mla-gates.sh` — echte Exitcodes, Ausgabe nennt den geprueften +Baum (`/workspace/worktrees/q4-integration`). + +| Gate | Ergebnis | +|---|---| +| `flutter pub get` | OK | +| `bash tool/check-versions.sh` | OK | +| `dart format --output=none --set-exit-if-changed lib test` | OK — 135 Dateien, 0 geaendert | +| `flutter analyze` | OK — *No issues found!* (35,5 s) | +| `flutter test` | OK — **314 Tests** (297 Baseline + 17 neue) | +| Python-Root-Runner | OK — **102 Tests** (62 Baseline + 40 neue) | +| GTK-Token-Gate | OK — 96 Tests (2 skipped) | +| `packages/la_core` | OK — 0 Findings, 68 Tests | + +**Summenzeile: `ALLE GATES GRUEN`, `GATES_EXIT=0`.** + +## Bewusste Entscheidungen + +1. **Die Desktop-Konfiguration bleibt die Quelle der Wahrheit.** Der App-seitige Grab + ist entfallen, damit gibt es nur noch **einen** Mechanismus. Vorher gab es zwei, und + auf X11 feuerte der Desktop-Shortcut zusätzlich zum App-Grab — das war der Grund für + den bisherigen `wayland ? … : true`-Workaround. +2. **Der Report wird in Python erzeugt, nicht in Dart.** Nur das Python-Skript kennt das + Layout der jeweiligen Desktop-Umgebung (GNOME-Schema vs. Cinnamon-Schema vs. + XFCE-Propertypfad vs. KDE-Trigger-Datei). Der Dart-Code kennt nur das JSON. +3. **Eigene Intent-Typen für die Shortcuts.** Das Framework bildet die Pfeiltasten in + `DefaultTextEditingShortcuts` auf den Textcursor ab. Ein eigener Intent-Typ ist + Voraussetzung dafür, dass der eigene Shortcut gewinnt — bei einem `Intent`-Wiederverwendung + wäre er der Cursor-Bewegung unterlegen. +4. **`flutter pub get` regeneriert die getrackten Plugin-Dateien.** `pubspec.lock`, + `linux/flutter/generated_plugin_registrant.cc` und `linux/flutter/generated_plugins.cmake` + sind im Repo getrackt. Nach dem Entfernen der Abhaengigkeit ohne Regeneration bricht der + Linux-Build, weil das Plugin nicht mehr gebaut wird. Das ist im Merge passiert und wurde + behoben — der Punkt ist hier festgehalten, weil er beim naechsten Abhaengigkeits-Entfernen + wieder auftaucht. +5. **Kein `runInShell: true` eingefuehrt.** Der Report-Aufruf nutzt wie alle anderen + Aufrufe in `linux.dart` eine Argumentliste, nie einen Shell-String. +6. **Die polkit-Trinitaet ist unberuehrt.** `org.linux-assistant.operations.policy`, + die `_privilegedEntryPoints`-Liste in `lib/services/linux.dart` und der + `build-deb.sh`-chmod sind in diesem Merge nicht angefasst (per `git diff` geprueft). + +## Offene Punkte + +1. **Manuelle Abnahme auf dem Referenzsystem (Zorin OS 18.1).** Der Gate „Hotkey holt das + Fenster, Fokus im Suchfeld" braucht Wayland **und** X11 mit echter Desktop-Sitzung — + das kann die Sandbox nicht pruefen. Geprueft werden muss: + - der Shortcut holt das Fenster und setzt den Fokus ins Suchfeld, + - das Binding stimmt mit dem ueber die Desktop-Einstellungen gesetzten ueberein, + - der Cleanup entfernt eine Waise und laesst fremde Eintraege unangetastet. + (Issue #51 fuehrt den RV-1-Nachweis als eigenen Vorgang.) +2. **Die CI-apt-Zeile ist eine manuelle Restarbeit.** Die verbundene GitHub-App hat keine + `workflows`-Permission und darf `.github/workflows/*` nicht schreiben — jeder + Schreibzugriff dort wird abgelehnt. Die Aenderung liegt im Branch, ist aber **nicht** + im PR enthalten. Manuell: in `.github/workflows/build.yml` Zeile 71 + `sudo apt-get install -y ninja-build libgtk-3-dev mesa-utils` + (die beiden `libkeybinder`-Pakete entfallen — genau das ist der Stand im Branch). +3. **`build-bundle.sh` und `packaging/unmaintained/`** referenzieren weiterhin + `libkeybinder`. Beides ist geparkt und laut `AGENTS.md` ohnehin defekt bzw. + unmaintained — nicht Teil von Q4, aber als Reststand sichtbar. +4. **Q7 (Feedback an Upstream abklemmen)** ist unberuehrt und wartet auf Bastis + Entscheidung (Empfehlung aus dem Issue: entfernen). Ohne diese Entscheidung bleibt #58 + offen; Q4 blockiert Q7 nicht. + +## Leak-Check + +Keine Hosts, IPs, Ports oder `/home`-Pfade in den geaenderten Dateien. Die beiden +`/home/john doe`-Vorkommen in `lib/services/linux.dart:56-57` und `:1530` sind +**vorbestehend** (aus dem WP-S3-Merge) und stehen nicht in diesem Diff. diff --git a/features.csv b/features.csv index cd62393d..833e55ed 100644 --- a/features.csv +++ b/features.csv @@ -45,3 +45,4 @@ Browser status,Core,?,?,?,?,?,?,?,yes,?,?,?,?,?,?,yes,?,?,?,fork hub tool; read- Quick notes,Core,?,?,?,?,?,?,?,yes,?,?,?,?,?,?,yes,?,?,?,fork hub tool; verified on the reference system only File manager,Core,?,?,?,?,?,?,?,yes,?,?,?,?,?,?,yes,?,?,?,fork hub tool; verified on the reference system only System monitor,Core,?,?,?,?,?,?,?,yes,?,?,?,?,?,?,yes,?,?,?,fork hub tool; verified on the reference system only +Hotkey (gsettings),Core,?,?,?,?,?,?,?,yes,?,?,?,?,?,?,yes,?,?,?,fork hub tool; desktop shortcut via gsettings on Wayland and X11; verified on the reference system only diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 149a70f8..cb189734 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1486,5 +1486,51 @@ "@zramLabel": { "placeholders": {}, "type": "text" + }, + "hotkeyTitle": "Tastenkürzel", + "@hotkeyTitle": { + "description": "Label of the diagnostics line about the app's own keyboard shortcut.", + "placeholders": {}, + "type": "text" + }, + "hotkeyNotRegistered": "nicht registriert", + "@hotkeyNotRegistered": { + "description": "Shown when the desktop does not hold the shortcut.", + "placeholders": {}, + "type": "text" + }, + "hotkeyUnknown": "unbekannt", + "@hotkeyUnknown": { + "description": "Shown when the state of the shortcut could not be read.", + "placeholders": {}, + "type": "text" + }, + "hotkeyOrphanEntries": "{count} verwaiste Einträge", + "@hotkeyOrphanEntries": { + "description": "How many leftover desktop entries still point at this app.", + "placeholders": { + "count": { + "type": "int" + } + }, + "type": "text" + }, + "hotkeyCleanup": "Aufräumen", + "@hotkeyCleanup": { + "description": "Button that removes the orphaned desktop entries.", + "placeholders": {}, + "type": "text" + }, + "hotkeyCleanupSucceeded": "Die verwaisten Einträge wurden entfernt.", + "@hotkeyCleanupSucceeded": { + "description": "Feedback after the orphaned entries were removed.", + "placeholders": {}, + "type": "text" + }, + "hotkeyCleanupFailed": "Die verwaisten Einträge konnten nicht entfernt werden.", + "@hotkeyCleanupFailed": { + "description": "Feedback after removing the orphaned entries failed.", + "placeholders": {}, + "type": "text" } } From b0427d9bf7dc6888502561727c8e6ab40bd74334 Mon Sep 17 00:00:00 2001 From: ElGregor Date: Fri, 30 Oct 2026 00:43:30 +0100 Subject: [PATCH 3/7] feat(hotkey): Hotkey ueber gsettings in beiden Sitzungen (#58) (Block 3) --- lib/l10n/app_en.arb | 46 ++++++++++++++++++++++++++++++ lib/l10n/app_it.arb | 46 ++++++++++++++++++++++++++++++ lib/l10n/app_localizations.dart | 42 +++++++++++++++++++++++++++ lib/l10n/app_localizations_de.dart | 25 ++++++++++++++++ 4 files changed, 159 insertions(+) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index e73225ef..fa1a270b 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1452,5 +1452,51 @@ "@zramLabel": { "placeholders": {}, "type": "text" + }, + "hotkeyTitle": "Keyboard shortcut", + "@hotkeyTitle": { + "description": "Label of the diagnostics line about the app's own keyboard shortcut.", + "placeholders": {}, + "type": "text" + }, + "hotkeyNotRegistered": "not registered", + "@hotkeyNotRegistered": { + "description": "Shown when the desktop does not hold the shortcut.", + "placeholders": {}, + "type": "text" + }, + "hotkeyUnknown": "unknown", + "@hotkeyUnknown": { + "description": "Shown when the state of the shortcut could not be read.", + "placeholders": {}, + "type": "text" + }, + "hotkeyOrphanEntries": "{count} orphaned entries", + "@hotkeyOrphanEntries": { + "description": "How many leftover desktop entries still point at this app.", + "placeholders": { + "count": { + "type": "int" + } + }, + "type": "text" + }, + "hotkeyCleanup": "Clean up", + "@hotkeyCleanup": { + "description": "Button that removes the orphaned desktop entries.", + "placeholders": {}, + "type": "text" + }, + "hotkeyCleanupSucceeded": "The orphaned entries were removed.", + "@hotkeyCleanupSucceeded": { + "description": "Feedback after the orphaned entries were removed.", + "placeholders": {}, + "type": "text" + }, + "hotkeyCleanupFailed": "The orphaned entries could not be removed.", + "@hotkeyCleanupFailed": { + "description": "Feedback after removing the orphaned entries failed.", + "placeholders": {}, + "type": "text" } } diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index ac0cb584..dec1d0eb 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -1472,5 +1472,51 @@ "@zramLabel": { "placeholders": {}, "type": "text" + }, + "hotkeyTitle": "Scorciatoia da tastiera", + "@hotkeyTitle": { + "description": "Label of the diagnostics line about the app's own keyboard shortcut.", + "placeholders": {}, + "type": "text" + }, + "hotkeyNotRegistered": "non registrata", + "@hotkeyNotRegistered": { + "description": "Shown when the desktop does not hold the shortcut.", + "placeholders": {}, + "type": "text" + }, + "hotkeyUnknown": "sconosciuta", + "@hotkeyUnknown": { + "description": "Shown when the state of the shortcut could not be read.", + "placeholders": {}, + "type": "text" + }, + "hotkeyOrphanEntries": "{count} voci orfane", + "@hotkeyOrphanEntries": { + "description": "How many leftover desktop entries still point at this app.", + "placeholders": { + "count": { + "type": "int" + } + }, + "type": "text" + }, + "hotkeyCleanup": "Pulisci", + "@hotkeyCleanup": { + "description": "Button that removes the orphaned desktop entries.", + "placeholders": {}, + "type": "text" + }, + "hotkeyCleanupSucceeded": "Le voci orfane sono state rimosse.", + "@hotkeyCleanupSucceeded": { + "description": "Feedback after the orphaned entries were removed.", + "placeholders": {}, + "type": "text" + }, + "hotkeyCleanupFailed": "Non è stato possibile rimuovere le voci orfane.", + "@hotkeyCleanupFailed": { + "description": "Feedback after removing the orphaned entries failed.", + "placeholders": {}, + "type": "text" } } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 26d8175e..77de47a8 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2285,6 +2285,48 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'zram (compressed)'** String get zramLabel; + + /// Label of the diagnostics line about the app's own keyboard shortcut. + /// + /// In en, this message translates to: + /// **'Keyboard shortcut'** + String get hotkeyTitle; + + /// Shown when the desktop does not hold the shortcut. + /// + /// In en, this message translates to: + /// **'not registered'** + String get hotkeyNotRegistered; + + /// Shown when the state of the shortcut could not be read. + /// + /// In en, this message translates to: + /// **'unknown'** + String get hotkeyUnknown; + + /// How many leftover desktop entries still point at this app. + /// + /// In en, this message translates to: + /// **'{count} orphaned entries'** + String hotkeyOrphanEntries(int count); + + /// Button that removes the orphaned desktop entries. + /// + /// In en, this message translates to: + /// **'Clean up'** + String get hotkeyCleanup; + + /// Feedback after the orphaned entries were removed. + /// + /// In en, this message translates to: + /// **'The orphaned entries were removed.'** + String get hotkeyCleanupSucceeded; + + /// Feedback after removing the orphaned entries failed. + /// + /// In en, this message translates to: + /// **'The orphaned entries could not be removed.'** + String get hotkeyCleanupFailed; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index ab18104e..6f66c08a 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1268,4 +1268,29 @@ class AppLocalizationsDe extends AppLocalizations { @override String get zramLabel => 'zram (komprimiert)'; + + @override + String get hotkeyTitle => 'Tastenkürzel'; + + @override + String get hotkeyNotRegistered => 'nicht registriert'; + + @override + String get hotkeyUnknown => 'unbekannt'; + + @override + String hotkeyOrphanEntries(int count) { + return '$count verwaiste Einträge'; + } + + @override + String get hotkeyCleanup => 'Aufräumen'; + + @override + String get hotkeyCleanupSucceeded => + 'Die verwaisten Einträge wurden entfernt.'; + + @override + String get hotkeyCleanupFailed => + 'Die verwaisten Einträge konnten nicht entfernt werden.'; } From 88fcb18a4e5fb23e997203168863b2fc748bd4f9 Mon Sep 17 00:00:00 2001 From: ElGregor Date: Fri, 30 Oct 2026 00:43:33 +0100 Subject: [PATCH 4/7] feat(hotkey): Hotkey ueber gsettings in beiden Sitzungen (#58) (Block 4) --- lib/l10n/app_localizations_en.dart | 24 ++++++++++++++++ lib/l10n/app_localizations_fi.dart | 23 +++++++++++++++ lib/l10n/app_localizations_it.dart | 24 ++++++++++++++++ lib/l10n/linuxassistant_fi.arb | 46 ++++++++++++++++++++++++++++++ 4 files changed, 117 insertions(+) diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 4ba7d179..83eaec7a 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1259,4 +1259,28 @@ class AppLocalizationsEn extends AppLocalizations { @override String get zramLabel => 'zram (compressed)'; + + @override + String get hotkeyTitle => 'Keyboard shortcut'; + + @override + String get hotkeyNotRegistered => 'not registered'; + + @override + String get hotkeyUnknown => 'unknown'; + + @override + String hotkeyOrphanEntries(int count) { + return '$count orphaned entries'; + } + + @override + String get hotkeyCleanup => 'Clean up'; + + @override + String get hotkeyCleanupSucceeded => 'The orphaned entries were removed.'; + + @override + String get hotkeyCleanupFailed => + 'The orphaned entries could not be removed.'; } diff --git a/lib/l10n/app_localizations_fi.dart b/lib/l10n/app_localizations_fi.dart index 6b2acf8f..a2a7b589 100644 --- a/lib/l10n/app_localizations_fi.dart +++ b/lib/l10n/app_localizations_fi.dart @@ -1271,4 +1271,27 @@ class AppLocalizationsFi extends AppLocalizations { @override String get zramLabel => 'zram (pakattu)'; + + @override + String get hotkeyTitle => 'Näppäinoikku'; + + @override + String get hotkeyNotRegistered => 'ei rekisteröity'; + + @override + String get hotkeyUnknown => 'tuntematon'; + + @override + String hotkeyOrphanEntries(int count) { + return '$count orpoitua merkintää'; + } + + @override + String get hotkeyCleanup => 'Siivoa'; + + @override + String get hotkeyCleanupSucceeded => 'Orpoitut merkinnät poistettiin.'; + + @override + String get hotkeyCleanupFailed => 'Orpoituja merkintöjä ei voitu poistaa.'; } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 5270c49b..62cb8ec0 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1279,4 +1279,28 @@ class AppLocalizationsIt extends AppLocalizations { @override String get zramLabel => 'zram (compresso)'; + + @override + String get hotkeyTitle => 'Scorciatoia da tastiera'; + + @override + String get hotkeyNotRegistered => 'non registrata'; + + @override + String get hotkeyUnknown => 'sconosciuta'; + + @override + String hotkeyOrphanEntries(int count) { + return '$count voci orfane'; + } + + @override + String get hotkeyCleanup => 'Pulisci'; + + @override + String get hotkeyCleanupSucceeded => 'Le voci orfane sono state rimosse.'; + + @override + String get hotkeyCleanupFailed => + 'Non è stato possibile rimuovere le voci orfane.'; } diff --git a/lib/l10n/linuxassistant_fi.arb b/lib/l10n/linuxassistant_fi.arb index 3744e93f..d46852c3 100644 --- a/lib/l10n/linuxassistant_fi.arb +++ b/lib/l10n/linuxassistant_fi.arb @@ -1057,5 +1057,51 @@ "@zramLabel": { "placeholders": {}, "type": "text" + }, + "hotkeyTitle": "Näppäinoikku", + "@hotkeyTitle": { + "description": "Label of the diagnostics line about the app's own keyboard shortcut.", + "placeholders": {}, + "type": "text" + }, + "hotkeyNotRegistered": "ei rekisteröity", + "@hotkeyNotRegistered": { + "description": "Shown when the desktop does not hold the shortcut.", + "placeholders": {}, + "type": "text" + }, + "hotkeyUnknown": "tuntematon", + "@hotkeyUnknown": { + "description": "Shown when the state of the shortcut could not be read.", + "placeholders": {}, + "type": "text" + }, + "hotkeyOrphanEntries": "{count} orpoitua merkintää", + "@hotkeyOrphanEntries": { + "description": "How many leftover desktop entries still point at this app.", + "placeholders": { + "count": { + "type": "int" + } + }, + "type": "text" + }, + "hotkeyCleanup": "Siivoa", + "@hotkeyCleanup": { + "description": "Button that removes the orphaned desktop entries.", + "placeholders": {}, + "type": "text" + }, + "hotkeyCleanupSucceeded": "Orpoitut merkinnät poistettiin.", + "@hotkeyCleanupSucceeded": { + "description": "Feedback after the orphaned entries were removed.", + "placeholders": {}, + "type": "text" + }, + "hotkeyCleanupFailed": "Orpoituja merkintöjä ei voitu poistaa.", + "@hotkeyCleanupFailed": { + "description": "Feedback after removing the orphaned entries failed.", + "placeholders": {}, + "type": "text" } } From c1c4460171607640c557cc4651079f21eddd6fab Mon Sep 17 00:00:00 2001 From: ElGregor Date: Fri, 30 Oct 2026 00:43:36 +0100 Subject: [PATCH 5/7] feat(hotkey): Hotkey ueber gsettings in beiden Sitzungen (#58) (Block 5) --- .../after_installation/activate_hotkey.dart | 14 +- lib/layouts/linux_health/overview.dart | 152 +++++++ lib/layouts/main_screen/main_search.dart | 358 ++++++++++------ lib/layouts/run_command_queue.dart | 388 ++++++++++-------- 4 files changed, 599 insertions(+), 313 deletions(-) diff --git a/lib/layouts/after_installation/activate_hotkey.dart b/lib/layouts/after_installation/activate_hotkey.dart index 94beec90..aed92add 100644 --- a/lib/layouts/after_installation/activate_hotkey.dart +++ b/lib/layouts/after_installation/activate_hotkey.dart @@ -49,12 +49,14 @@ class ActivateHotkeyQuestion extends StatelessWidget { // registration and navigate away in the same frame, so a failure // was invisible — and a second press queued a second run. onPressedFuture: () async { - // Mirror of main.dart: on X11 the app itself grabs the key via - // libkeybinder, and a desktop shortcut on top of that fires - // twice per press (raise plus a second process). - final bool ok = Linux.currentenvironment.wayland - ? await Linux.activateSystemHotkeyForLinuxAssistant() - : true; + // The desktop's own shortcut is registered in both sessions. + // It used to be skipped on X11, because the app grabbed the key + // itself there (libkeybinder) and the desktop shortcut on top of + // that fired twice per press — raise plus a second process. The + // app-side grab is gone, so the desktop shortcut is the only + // mechanism left, and it has to be there under X11 as well. + final bool ok = + await Linux.activateSystemHotkeyForLinuxAssistant(); // Only remember it when it worked. main.dart skips the // registration on later starts based on this flag, so writing // it unconditionally would make a failed setup permanent. diff --git a/lib/layouts/linux_health/overview.dart b/lib/layouts/linux_health/overview.dart index b6ee6676..279517ac 100644 --- a/lib/layouts/linux_health/overview.dart +++ b/lib/layouts/linux_health/overview.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:linux_assistant/l10n/app_localizations.dart'; import 'package:linux_assistant/layouts/mint_y.dart'; import 'package:linux_assistant/linux/linux_filesystem.dart'; +import 'package:linux_assistant/services/hotkey_diagnostics.dart'; import 'package:linux_assistant/services/main_search_loader.dart'; import 'package:linux_assistant/services/system_stats_service.dart'; import 'package:linux_assistant/widgets/success_message.dart'; @@ -55,10 +56,20 @@ class LinuxHealthContent extends StatefulWidget { class _LinuxHealthContentState extends State { final SystemStatsService _service = SystemStatsService(); + /// What the desktop knows about this app's own keyboard shortcut. + /// + /// Started next to the stats poll, not inside the poll: the report is a + /// read of the desktop's settings, and the health page is about the + /// machine. It must not delay the page, and it must not make the page + /// flicker either — which is why the row keeps its place while the report + /// is on its way. + late Future _hotkeyReport; + @override void initState() { super.initState(); _service.acquire(); + _hotkeyReport = const HotkeyDiagnostics().loadReport(); } @override @@ -67,6 +78,27 @@ class _LinuxHealthContentState extends State { super.dispose(); } + /// Reads the report again. + /// + /// The future is created outside of the `setState` callback: a callback + /// that returns a future would be a mistake in a state change, and this + /// one would also be started twice. + void _reloadHotkeyReport() { + final Future report = const HotkeyDiagnostics().loadReport(); + setState(() { + _hotkeyReport = report; + }); + } + + /// Removes the orphaned desktop entries and reads the report again. + Future _cleanupHotkeyOrphans() async { + final bool ok = await const HotkeyDiagnostics().cleanupOrphans(); + if (ok && mounted) { + _reloadHotkeyReport(); + } + return ok; + } + @override Widget build(BuildContext context) { final l10n = AppLocalizations.of(context)!; @@ -111,6 +143,10 @@ class _LinuxHealthContentState extends State { return ListView( shrinkWrap: true, children: [ + HotkeyStatusRow( + report: _hotkeyReport, + onCleanup: _cleanupHotkeyOrphans, + ), Text( l10n.runtime, style: Theme.of(context).textTheme.headlineLarge, @@ -209,3 +245,119 @@ class _LinuxHealthContentState extends State { : SuccessMessage(text: l10n.uptimePass(value, unitText)); } } + +/// One line about this app's own keyboard shortcut. +/// +/// The desktop's settings are the only place that knows whether the shortcut +/// is really registered — the app does not grab the key itself any more, so +/// it cannot know what the desktop did with it. A report that cannot be read +/// must not take the page down with it: the line then says "unknown" and the +/// page stays where it was. +class HotkeyStatusRow extends StatefulWidget { + const HotkeyStatusRow({ + super.key, + required this.report, + required this.onCleanup, + }); + + /// The report as it is now. A new future means: read it again. + final Future report; + + /// Removes the orphaned entries. Returns whether it worked. + final Future Function() onCleanup; + + @override + State createState() => _HotkeyStatusRowState(); +} + +class _HotkeyStatusRowState extends State { + bool _cleaning = false; + bool? _cleanupFailed; + + Future _cleanup() async { + if (_cleaning) { + return; + } + setState(() { + _cleaning = true; + _cleanupFailed = null; + }); + final bool ok = await widget.onCleanup(); + if (!mounted) { + return; + } + setState(() { + _cleaning = false; + _cleanupFailed = ok ? null : true; + }); + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + + return FutureBuilder( + future: widget.report, + builder: (context, snapshot) { + final HotkeyReport? report = snapshot.data; + final int orphanCount = report?.orphans.length ?? 0; + + return Padding( + padding: const EdgeInsets.symmetric(vertical: 8.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "${l10n.hotkeyTitle}: ${_stateText(report)}", + style: Theme.of(context).textTheme.titleMedium, + ), + if (report != null && !report.hasError) + Text( + "${report.desktop} · ${report.session}", + style: Theme.of(context).textTheme.bodySmall, + ), + if (orphanCount > 0) ...[ + const SizedBox(height: 8), + Text( + l10n.hotkeyOrphanEntries(orphanCount), + style: Theme.of(context).textTheme.bodyMedium, + ), + const SizedBox(height: 8), + MintYButton( + text: Text( + l10n.hotkeyCleanup, + style: MintY.heading4, + ), + color: MintY.currentColor, + onPressed: _cleaning ? null : _cleanup, + ), + ], + if (_cleanupFailed == true) + WarningMessage(text: l10n.hotkeyCleanupFailed), + ], + ), + ); + }, + ); + } + + /// What the line says about the shortcut. + String _stateText(HotkeyReport? report) { + final l10n = AppLocalizations.of(context)!; + if (report == null) { + // The report is still on its way. The line keeps its place, so nothing + // jumps when the answer arrives. + return "…"; + } + if (report.hasError) { + return l10n.hotkeyUnknown; + } + if (!report.registered) { + return l10n.hotkeyNotRegistered; + } + if (report.binding.isEmpty) { + return l10n.hotkeyUnknown; + } + return report.binding; + } +} diff --git a/lib/layouts/main_screen/main_search.dart b/lib/layouts/main_screen/main_search.dart index 0f286c12..3755e97e 100644 --- a/lib/layouts/main_screen/main_search.dart +++ b/lib/layouts/main_screen/main_search.dart @@ -3,7 +3,6 @@ import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:hotkey_manager/hotkey_manager.dart'; import 'package:linux_assistant/content/top_level_domains.dart'; import 'package:linux_assistant/enums/softwareManagers.dart'; import 'package:linux_assistant/layouts/feature_overview/feature_overview.dart'; @@ -56,8 +55,15 @@ class MainSearch extends StatefulWidget { @override State createState() => _MainSearchState(); + /// Makes sure the desktop has the "bring me up" shortcut. + /// + /// The name is a leftover: the search screen used to unregister the global + /// hotkeys here, because the old hotkey library kept them in one + /// process-wide registry and the app-side grab had to be gone while the + /// search was on screen. That registry is gone — the shortcut belongs to the + /// desktop and is registered once — so all that is left is making sure the + /// desktop still has it. static void unregisterHotkeysForKeyboardUse() { - hotKeyManager.unregisterAll(); MyApp.initHotkeyToShowUp(); } } @@ -85,10 +91,6 @@ class _MainSearchState extends State { ActionEntry? suggestion; - _MainSearchState() { - initHotkeysForKeyboardUse(); - } - @override void initState() { super.initState(); @@ -152,66 +154,72 @@ class _MainSearchState extends State { width: MediaQuery.of(context).size.width > 750 ? 600 : MediaQuery.of(context).size.width - 50, - child: TextField( - decoration: InputDecoration( - fillColor: Theme.of(context).canvasColor, - filled: true, - // border: const OutlineInputBorder( - // borderSide: BorderSide(color: Colors.white)), - contentPadding: _foundEntries.isEmpty - ? null - : const EdgeInsets.only( - bottom: -20.0, - left: 12, - right: 3, - ), - hintText: suggestion != null - ? suggestion!.name - : AppLocalizations.of( - context, - )! - .enterASearchTerm, - prefixIcon: _foundEntries.isEmpty - ? const Icon( - Icons.search, - color: Colors.grey, - ) - : null, - suffix: _foundEntries.isEmpty - ? null - : IconButton( - iconSize: 14, - splashRadius: 14, - icon: const Icon(Icons.clear), - onPressed: () => - clear(minimze: false), - padding: EdgeInsets.zero, - tooltip: AppLocalizations.of( + child: SearchFieldShortcuts( + onSelectNext: _selectNext, + onSelectPrevious: _selectPrevious, + onClear: _clearSearchField, + onDebugShortcut: _debugShortcut, + child: TextField( + decoration: InputDecoration( + fillColor: Theme.of(context).canvasColor, + filled: true, + // border: const OutlineInputBorder( + // borderSide: BorderSide(color: Colors.white)), + contentPadding: _foundEntries.isEmpty + ? null + : const EdgeInsets.only( + bottom: -20.0, + left: 12, + right: 3, + ), + hintText: suggestion != null + ? suggestion!.name + : AppLocalizations.of( context, )! - .clear, - ), + .enterASearchTerm, + prefixIcon: _foundEntries.isEmpty + ? const Icon( + Icons.search, + color: Colors.grey, + ) + : null, + suffix: _foundEntries.isEmpty + ? null + : IconButton( + iconSize: 14, + splashRadius: 14, + icon: const Icon(Icons.clear), + onPressed: () => + clear(minimze: false), + padding: EdgeInsets.zero, + tooltip: AppLocalizations.of( + context, + )! + .clear, + ), + ), + style: Theme.of(context).textTheme.bodyMedium, + cursorColor: MintY.currentColor, + controller: searchBarController, + autofocus: true, + onChanged: (value) => _runFilter(value), + onSubmitted: (value) { + if (_foundEntries.isNotEmpty) { + ActionHandler.handleActionEntry( + _foundEntries[selectedIndex], + clear, + context, + ); + } else if (suggestion != null) { + ActionHandler.handleActionEntry( + suggestion!, + clear, + context, + ); + } + }, ), - style: Theme.of(context).textTheme.bodyMedium, - cursorColor: MintY.currentColor, - controller: searchBarController, - autofocus: true, - onChanged: (value) => _runFilter(value), - onSubmitted: (value) { - if (_foundEntries.isNotEmpty) { - ActionHandler.handleActionEntry( - _foundEntries[selectedIndex], - clear, - context, - ); - } else if (suggestion != null) { - ActionHandler.handleActionEntry( - suggestion!, - clear, - context, - ); - } - }, ), ), _foundEntries.isEmpty @@ -711,75 +719,63 @@ class _MainSearchState extends State { ); } - void initHotkeysForKeyboardUse() { - HotKey down = HotKey( - key: PhysicalKeyboardKey.arrowDown, - scope: HotKeyScope.inapp, - ); - hotKeyManager.register( - down, - keyDownHandler: (hotKey) { - // A stale instance can still receive this: the handlers are registered - // globally, not per widget. - if (mounted && selectedIndex + 1 < _foundEntries.length) { - setState(() { - selectedIndex += 1; - selectedIndexInView += 1; - if (selectedIndexInView >= visibleEntries) { - scrollController.jumpTo(scrollController.offset + 72); - selectedIndexInView -= 1; - } - }); + /// Moves the selection one entry down in the result list. + /// + /// The same logic the global hotkey handler had, now reached through the + /// field's own shortcut instead of a window-wide key grab. + void _selectNext() { + if (!mounted || selectedIndex + 1 >= _foundEntries.length) { + return; + } + setState(() { + selectedIndex += 1; + selectedIndexInView += 1; + if (selectedIndexInView >= visibleEntries) { + // The list is only there when there is something to select, but the + // controller is not attached in the frame between the entries + // appearing and the list being built. + if (scrollController.hasClients) { + scrollController.jumpTo(scrollController.offset + 72); } - }, - ); + selectedIndexInView -= 1; + } + }); + } - HotKey up = HotKey( - key: PhysicalKeyboardKey.arrowUp, - scope: HotKeyScope.inapp, - ); - hotKeyManager.register( - up, - keyDownHandler: (hotKey) { - if (mounted && selectedIndex - 1 >= 0) { - setState(() { - selectedIndex -= 1; - selectedIndexInView -= 1; - if (selectedIndexInView < 0) { - scrollController.jumpTo(scrollController.offset - 72); - selectedIndexInView += 1; - } - }); + /// Moves the selection one entry up in the result list. + void _selectPrevious() { + if (!mounted || selectedIndex - 1 < 0) { + return; + } + setState(() { + selectedIndex -= 1; + selectedIndexInView -= 1; + if (selectedIndexInView < 0) { + if (scrollController.hasClients) { + scrollController.jumpTo(scrollController.offset - 72); } - }, - ); + selectedIndexInView += 1; + } + }); + } - HotKey escape = HotKey( - key: PhysicalKeyboardKey.escape, - scope: HotKeyScope.inapp, - ); - hotKeyManager.register( - escape, - keyDownHandler: (hotKey) { - clear(minimze: false); - }, - ); + /// Empties the search field. + /// + /// Escape keeps the window open — the user clears the search, they do not + /// leave the app. + void _clearSearchField() { + clear(minimze: false); + } - // Debug Call - HotKey hotKeyDebug = HotKey( - key: PhysicalKeyboardKey.keyD, - modifiers: [HotKeyModifier.control], - scope: HotKeyScope.inapp, - ); - hotKeyManager.register( - hotKeyDebug, - keyDownHandler: (hotKey) async { - // insert here function calls to debug - // Linux.getInstalledFlatpaks(); - // Linux.getInstalledSnaps(); - // Linux.getInstalledAPTPackages(); - }, - ); + /// The debug hook behind Ctrl+D. + /// + /// It does nothing on purpose: it is the place where the next debugging + /// call goes, without the search screen having to be changed for it. + void _debugShortcut() { + // insert here function calls to debug + // Linux.getInstalledFlatpaks(); + // Linux.getInstalledSnaps(); + // Linux.getInstalledAPTPackages(); } void _handleSuggestions() async { @@ -800,6 +796,114 @@ class _MainSearchState extends State { } } +/// The key bindings of the search field. +/// +/// The app used to register these through a global hotkey library, which +/// hooked the keys into the window itself: they fired even when the search +/// field did not have the focus, and they needed the native libkeybinder +/// library to be present. They are plain Flutter shortcuts now, and they sit +/// directly on the field — so they only fire while the field is focused, and +/// the arrow keys move the selection in the result list instead of the text +/// cursor. +/// +/// The ordering matters: the framework maps the arrow keys to the text cursor +/// in `DefaultTextEditingShortcuts`, which sits at the top of the app. A +/// `Shortcuts` widget below it is asked first, so ours wins. +class SearchFieldShortcuts extends StatelessWidget { + const SearchFieldShortcuts({ + super.key, + required this.onSelectNext, + required this.onSelectPrevious, + required this.onClear, + this.onDebugShortcut, + required this.child, + }); + + /// Arrow down: the next entry in the result list. + final VoidCallback onSelectNext; + + /// Arrow up: the previous entry in the result list. + final VoidCallback onSelectPrevious; + + /// Escape: empty the search field. + final VoidCallback onClear; + + /// Ctrl+D: the debug hook. It does nothing on purpose. + final VoidCallback? onDebugShortcut; + + /// The search field itself. + final Widget child; + + @override + Widget build(BuildContext context) { + return Actions( + actions: >{ + _SelectNextIntent: CallbackAction<_SelectNextIntent>( + onInvoke: (_) { + onSelectNext(); + return null; + }, + ), + _SelectPreviousIntent: CallbackAction<_SelectPreviousIntent>( + onInvoke: (_) { + onSelectPrevious(); + return null; + }, + ), + _ClearSearchIntent: CallbackAction<_ClearSearchIntent>( + onInvoke: (_) { + onClear(); + return null; + }, + ), + _DebugIntent: CallbackAction<_DebugIntent>( + onInvoke: (_) { + onDebugShortcut?.call(); + return null; + }, + ), + }, + child: Shortcuts( + shortcuts: { + const SingleActivator(LogicalKeyboardKey.arrowDown): + const _SelectNextIntent(), + const SingleActivator(LogicalKeyboardKey.arrowUp): + const _SelectPreviousIntent(), + const SingleActivator(LogicalKeyboardKey.escape): + const _ClearSearchIntent(), + const SingleActivator(LogicalKeyboardKey.keyD, control: true): + const _DebugIntent(), + }, + child: child, + ), + ); + } +} + +/// Intents of the search field's own shortcuts. +/// +/// Own types on purpose: the framework's text editing intents map the arrow +/// keys to the cursor movement, and a shortcut of ours has to win over them. +/// That only works if it does not reuse their intents. +class _SelectNextIntent extends Intent { + const _SelectNextIntent(); +} + +/// Arrow up in the result list. +class _SelectPreviousIntent extends Intent { + const _SelectPreviousIntent(); +} + +/// Escape: empty the search field. +class _ClearSearchIntent extends Intent { + const _ClearSearchIntent(); +} + +/// Ctrl+D: the debug hook. +class _DebugIntent extends Intent { + const _DebugIntent(); +} + class FeedbackButton extends StatelessWidget { const FeedbackButton({ super.key, diff --git a/lib/layouts/run_command_queue.dart b/lib/layouts/run_command_queue.dart index 308ab6b9..0e403ea3 100644 --- a/lib/layouts/run_command_queue.dart +++ b/lib/layouts/run_command_queue.dart @@ -3,7 +3,6 @@ import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:hotkey_manager/hotkey_manager.dart'; import 'package:linux_assistant/layouts/main_screen/main_search.dart'; import 'package:linux_assistant/layouts/mint_y.dart'; @@ -47,7 +46,6 @@ class _RunCommandQueueState extends State { bool _commandQueueCompleted = false; bool _shutdownAfterwards = false; - HotKey? _enterHotkey; @override void initState() { @@ -55,33 +53,9 @@ class _RunCommandQueueState extends State { _commands = List.from(Linux.commandQueue); if (_commands.isNotEmpty) { _output = Linux.executeCommandQueue(); - _registerEnterHotkey(); } } - @override - void dispose() { - final HotKey? hotkey = _enterHotkey; - if (hotkey != null) { - unawaited(hotKeyManager.unregister(hotkey)); - } - super.dispose(); - } - - void _registerEnterHotkey() { - final HotKey enter = HotKey( - key: PhysicalKeyboardKey.enter, - scope: HotKeyScope.inapp, - ); - _enterHotkey = enter; - unawaited(hotKeyManager.register(enter, keyDownHandler: (hotKey) { - if (!mounted || !_commandQueueCompleted) { - return; - } - _continueAfterQueue(context); - })); - } - /// Where "continue" leads once the queue has run. /// /// With the hub running underneath, pushing the usual fullscreen @@ -126,177 +100,231 @@ class _RunCommandQueueState extends State { ]); } - return FutureBuilder( - future: _output, - builder: (context, snapshot) { - if (snapshot.hasData) { - if (!_commandQueueCompleted) { - _commandQueueCompleted = true; - if (widget.offerShutdownAfterwards && _shutdownAfterwards) { - Linux.shutdown(); + return _EnterContinuesQueue( + onContinue: () { + // Enter only continues when the queue is actually done. While it + // runs, the user watches the table, not the next step. + if (!mounted || !_commandQueueCompleted) { + return; + } + _continueAfterQueue(context); + }, + child: FutureBuilder( + future: _output, + builder: (context, snapshot) { + if (snapshot.hasData) { + if (!_commandQueueCompleted) { + _commandQueueCompleted = true; + if (widget.offerShutdownAfterwards && _shutdownAfterwards) { + Linux.shutdown(); + } } - } - return MintYPage( - title: widget.title, - contentElements: [ - Text( - widget.message, - style: Theme.of(context).textTheme.headlineMedium, - textAlign: TextAlign.center, - ), - const SizedBox( - height: 16, - ), - snapshot.data!.contains( - "Error executing command as another user: Request dismissed") - ? Column( - children: [ - Text( - AppLocalizations.of(context)!.errorThisDidntWork, - style: Theme.of(context).textTheme.bodyMedium, - textAlign: TextAlign.center, - ), - const SizedBox( - height: 16, - ), - MintYButton( - text: Text( - AppLocalizations.of(context)!.retry, - style: MintY.heading4White, - ), - color: MintY.currentColor, - onPressed: () { - Navigator.of(context).push( - MaterialPageRoute( - builder: (context) => RunCommandQueue( - route: widget.route, - title: widget.title, - message: widget.message, - offerShutdownAfterwards: - widget.offerShutdownAfterwards, - )), - ); - }, - ) - ], - ) - : Text( - AppLocalizations.of(context)!.complete, - style: Theme.of(context).textTheme.bodyMedium, - textAlign: TextAlign.center, - ), - ], - bottom: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - MintYButton( - text: const Text( - "Log", - style: MintY.heading4, - ), - onPressed: () { - showDialog( - context: context, - builder: (context) { - return Dialog( - backgroundColor: Colors.black, - child: Column( - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - IconButton( - onPressed: () { - Navigator.of(context).pop(); - }, - icon: const Icon( - Icons.close, - size: 36, - color: Colors.white, - ), - iconSize: 36, - ) - ], - ), - Expanded( - child: Padding( - padding: const EdgeInsets.all(16.0), - child: SingleChildScrollView( - child: SelectableText( - snapshot.data.toString(), - style: const TextStyle( - color: Colors.white, - fontFamily: "Courier"), - ), - ), - ), - ), - ], - ), - ); - }, - ); - }, + return MintYPage( + title: widget.title, + contentElements: [ + Text( + widget.message, + style: Theme.of(context).textTheme.headlineMedium, + textAlign: TextAlign.center, ), const SizedBox( - width: 10, - ), - MintYButton( - text: Text( - AppLocalizations.of(context)!.next, - style: MintY.heading4White, - ), - color: MintY.currentColor, - onPressed: () => _continueAfterQueue(context), + height: 16, ), + snapshot.data!.contains( + "Error executing command as another user: Request dismissed") + ? Column( + children: [ + Text( + AppLocalizations.of(context)!.errorThisDidntWork, + style: Theme.of(context).textTheme.bodyMedium, + textAlign: TextAlign.center, + ), + const SizedBox( + height: 16, + ), + MintYButton( + text: Text( + AppLocalizations.of(context)!.retry, + style: MintY.heading4White, + ), + color: MintY.currentColor, + onPressed: () { + Navigator.of(context).push( + MaterialPageRoute( + builder: (context) => RunCommandQueue( + route: widget.route, + title: widget.title, + message: widget.message, + offerShutdownAfterwards: + widget.offerShutdownAfterwards, + )), + ); + }, + ) + ], + ) + : Text( + AppLocalizations.of(context)!.complete, + style: Theme.of(context).textTheme.bodyMedium, + textAlign: TextAlign.center, + ), ], - ), - ); - } else { - // Loading Screen - return MintYPage( - title: widget.title, - contentElements: [ - Column( + bottom: Row( + mainAxisAlignment: MainAxisAlignment.center, children: [ - Text( - widget.message, - style: Theme.of(context).textTheme.headlineMedium, - textAlign: TextAlign.center, - ), - const SizedBox( - height: 16, + MintYButton( + text: const Text( + "Log", + style: MintY.heading4, + ), + onPressed: () { + showDialog( + context: context, + builder: (context) { + return Dialog( + backgroundColor: Colors.black, + child: Column( + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + IconButton( + onPressed: () { + Navigator.of(context).pop(); + }, + icon: const Icon( + Icons.close, + size: 36, + color: Colors.white, + ), + iconSize: 36, + ) + ], + ), + Expanded( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: SingleChildScrollView( + child: SelectableText( + snapshot.data.toString(), + style: const TextStyle( + color: Colors.white, + fontFamily: "Courier"), + ), + ), + ), + ), + ], + ), + ); + }, + ); + }, ), - const MintYProgressIndicatorCircle(), const SizedBox( - height: 64, - ), - CommandTable( - tableData: tableData, + width: 10, ), - const SizedBox( - height: 8, + MintYButton( + text: Text( + AppLocalizations.of(context)!.next, + style: MintY.heading4White, + ), + color: MintY.currentColor, + onPressed: () => _continueAfterQueue(context), ), - widget.offerShutdownAfterwards - ? ShutdownCheckbox( - value: _shutdownAfterwards, - onChanged: (bool value) { - setState(() { - _shutdownAfterwards = value; - }); - }, - ) - : Container(), ], ), - ], - ); - } + ); + } else { + // Loading Screen + return MintYPage( + title: widget.title, + contentElements: [ + Column( + children: [ + Text( + widget.message, + style: Theme.of(context).textTheme.headlineMedium, + textAlign: TextAlign.center, + ), + const SizedBox( + height: 16, + ), + const MintYProgressIndicatorCircle(), + const SizedBox( + height: 64, + ), + CommandTable( + tableData: tableData, + ), + const SizedBox( + height: 8, + ), + widget.offerShutdownAfterwards + ? ShutdownCheckbox( + value: _shutdownAfterwards, + onChanged: (bool value) { + setState(() { + _shutdownAfterwards = value; + }); + }, + ) + : Container(), + ], + ), + ], + ); + } + }, + ), + ); + } +} + +/// Binds the Enter key to "continue with the next step". +/// +/// The page has no text field of its own, so nothing would have the focus and +/// a key event would never arrive. The [Focus] widget takes the focus as +/// soon as the page is on screen, and the shortcut below it then hears the +/// Enter key — as long as the page is the one that is focused. +class _EnterContinuesQueue extends StatelessWidget { + const _EnterContinuesQueue({ + required this.onContinue, + required this.child, + }); + + /// Called when the user presses Enter. + final VoidCallback onContinue; + + final Widget child; + + @override + Widget build(BuildContext context) { + return Actions( + actions: >{ + _ContinueQueueIntent: CallbackAction<_ContinueQueueIntent>( + onInvoke: (_) { + onContinue(); + return null; + }, + ), }, + child: Shortcuts( + shortcuts: { + const SingleActivator(LogicalKeyboardKey.enter): + const _ContinueQueueIntent(), + }, + child: Focus(autofocus: true, child: child), + ), ); } } +/// The intent behind the Enter key of the command queue. +class _ContinueQueueIntent extends Intent { + const _ContinueQueueIntent(); +} + class ShutdownCheckbox extends StatelessWidget { final bool value; final ValueChanged onChanged; From dc91cfd89841a8f1df5219487cd7e563a326aad1 Mon Sep 17 00:00:00 2001 From: ElGregor Date: Fri, 30 Oct 2026 00:43:39 +0100 Subject: [PATCH 6/7] feat(hotkey): Hotkey ueber gsettings in beiden Sitzungen (#58) (Block 6) --- lib/main.dart | 49 ++-- lib/services/hotkey_diagnostics.dart | 222 +++++++++++++++++++ lib/services/linux.dart | 35 +++ linux/flutter/generated_plugin_registrant.cc | 4 - 4 files changed, 270 insertions(+), 40 deletions(-) create mode 100644 lib/services/hotkey_diagnostics.dart diff --git a/lib/main.dart b/lib/main.dart index 89218e60..db85ca5e 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,9 +1,7 @@ import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; import 'package:hexcolor/hexcolor.dart'; -import 'package:hotkey_manager/hotkey_manager.dart'; import 'package:linux_assistant/enums/distros.dart'; import 'package:linux_assistant/layouts/greeter/flathub_permissions.dart'; import 'package:linux_assistant/layouts/greeter/start_screen.dart'; @@ -33,9 +31,6 @@ void main() async { exit(0); } - // For hot reload, `unregisterAll()` needs to be called. - await HotKeyManager.instance.unregisterAll(); - StatelessWidget firstScreen = const StartScreen(); bool systemIsDark = false; @@ -103,38 +98,17 @@ class MyApp extends StatefulWidget { /// Makes the "bring me up" shortcut work for the session we are in. /// - /// Two mechanisms exist and only one of them can work per session type. On - /// X11 the app grabs the key itself through libkeybinder. Wayland has no - /// global X11 grab at all, so that call can only ever fail there — it is - /// what wrote `Binding 'q' failed!` to the log on every invocation — - /// and the desktop's own shortcut is the only route that carries. + /// The app does not grab the key itself any more. It used to, through + /// libkeybinder, and that had two problems: on X11 the app's grab and the + /// desktop's own shortcut fired together (one press raised the window and + /// started a second process), and on Wayland the grab could not work at all + /// — it wrote `Binding 'q' failed!` to the log on every invocation. + /// + /// The desktop's own shortcut is the one route now, and it exists on both + /// session types. So there is no session distinction here any more: the + /// same registration runs under Wayland and under X11. static void initHotkeyToShowUp() { - if (Linux.currentenvironment.wayland) { - unawaited(_ensureDesktopShortcut()); - return; - } - HotKey hotKey = HotKey( - key: PhysicalKeyboardKey.keyQ, - // Has to agree with what `setup_keybinding.py` writes and with what the - // greeter tells the user. Hardcoding meta meant the app grabbed Super+Q - // on Zorin, Ubuntu and Pop!_OS while advertising Alt+Q. - modifiers: [ - Linux.getHotkeyModifier() == "" - ? HotKeyModifier.alt - : HotKeyModifier.meta - ], - scope: HotKeyScope.system, - ); - hotKeyManager.register( - hotKey, - keyDownHandler: (hotKey) { - // The app raises itself rather than asking wmctrl to do it, which is - // one external dependency fewer and works the same on both session - // types. Raising is only half the job when the hub is open: the - // hotkey is meant to land the user in the search box. - unawaited(raiseWindow()); - }, - ); + unawaited(_ensureDesktopShortcut()); } /// Registers the shortcut with the desktop itself, once. @@ -144,6 +118,9 @@ class MyApp extends StatefulWidget { /// shortcuts, so the flag records that it happened. The script skips an /// entry it already owns as well, which covers the case where the app dies /// before the flag reaches disk. + /// + /// This is the only registration left: it runs under Wayland and under X11 + /// alike, because the desktop's shortcut is the one that works on both. static Future _ensureDesktopShortcut() async { final ConfigHandler configHandler = ConfigHandler(); // Compared rather than used directly: the getter is untyped and the value diff --git a/lib/services/hotkey_diagnostics.dart b/lib/services/hotkey_diagnostics.dart new file mode 100644 index 00000000..20ee5b69 --- /dev/null +++ b/lib/services/hotkey_diagnostics.dart @@ -0,0 +1,222 @@ +import 'dart:convert'; + +import 'package:linux_assistant/helpers/command_helper.dart'; +import 'package:linux_assistant/services/linux.dart'; +import 'package:linux_assistant/services/logger.dart'; + +/// One orphaned `custom*` entry of the desktop's keybinding list. +/// +/// "Orphan" means: the entry belongs to this app — its command is +/// `linux-assistant` — but it is not the entry that is live right now. That +/// happens when the binding was moved (the modifier changed from `` to +/// ``, for example) or when an older setup run left a duplicate behind. +/// The desktop keeps both, and both fire the app. +class HotkeyOrphan { + const HotkeyOrphan({required this.path, required this.binding}); + + /// The gsettings path of the entry, for example + /// `/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom3/`. + final String path; + + /// The key combination the entry is bound to, for example `q`. + final String binding; + + factory HotkeyOrphan.fromJson(Map json) { + return HotkeyOrphan( + path: _asString(json["path"]), + binding: _asString(json["binding"]), + ); + } + + @override + String toString() => "HotkeyOrphan(path: $path, binding: $binding)"; +} + +/// What the desktop says about this app's own keyboard shortcut. +/// +/// The desktop's settings are the only source that can answer whether the +/// shortcut is really there: the app itself no longer grabs the key, so it +/// cannot know what the desktop did with it. +class HotkeyReport { + const HotkeyReport({ + required this.desktop, + required this.session, + required this.binding, + required this.registered, + required this.orphans, + this.error, + }); + + /// The desktop the report was taken on: `gnome`, `cinnamon`, `xfce`, `kde` + /// or `unknown`. + final String desktop; + + /// The session type: `wayland`, `x11` or `unknown`. + final String session; + + /// The key combination the shortcut is bound to, for example `q`. + final String binding; + + /// Whether the desktop currently holds our shortcut. + final bool registered; + + /// The `custom*` entries that point at this app but are not the live one. + final List orphans; + + /// Why the report could not be read. Null when it could. + final String? error; + + /// Whether the report is a failure report rather than a real one. + bool get hasError => error != null; + + /// The report of a run that did not produce a usable answer. + /// + /// A diagnostic that throws takes the page it is shown on down with it, so + /// every failure ends up here instead: not registered, and a reason. + factory HotkeyReport.unavailable(String error) { + return HotkeyReport( + desktop: "unknown", + session: "unknown", + binding: "", + registered: false, + orphans: const [], + error: error, + ); + } + + factory HotkeyReport.fromJson(Map json) { + final List orphans = []; + final Object? rawOrphans = json["orphans"]; + if (rawOrphans is List) { + for (final Object? entry in rawOrphans) { + if (entry is Map) { + orphans.add(HotkeyOrphan.fromJson(entry.cast())); + } + } + } + + return HotkeyReport( + desktop: _asString(json["desktop"]), + session: _asString(json["session"]), + binding: _asString(json["binding"]), + // Only a real `true` counts as registered: a missing field must not + // make the page claim a shortcut that is not there. + registered: json["registered"] == true, + orphans: orphans, + ); + } + + /// Parses the JSON line `setup_keybinding.py --report` writes. + /// + /// Never throws. Broken output is a normal answer here — the script may be + /// missing, the desktop unknown, or the JSON truncated — and the caller + /// gets a report that says "not registered" plus the reason. + static HotkeyReport parse(String rawOutput) { + final String trimmed = rawOutput.trim(); + if (trimmed.isEmpty) { + return HotkeyReport.unavailable( + "The keybinding script did not return anything.", + ); + } + + Object? decoded; + try { + decoded = jsonDecode(trimmed); + } on FormatException catch (error) { + // The script writes one JSON line, but a warning from a wrapper around + // it would turn the whole output into unparseable text. The object in + // between is still worth a try. + final int start = trimmed.indexOf("{"); + final int end = trimmed.lastIndexOf("}"); + if (start < 0 || end <= start) { + return HotkeyReport.unavailable( + "The keybinding script returned invalid JSON: ${error.message}", + ); + } + try { + decoded = jsonDecode(trimmed.substring(start, end + 1)); + } on FormatException catch (innerError) { + return HotkeyReport.unavailable( + "The keybinding script returned invalid JSON: ${innerError.message}", + ); + } + } + + if (decoded is! Map) { + return HotkeyReport.unavailable( + "The keybinding script did not return a JSON object.", + ); + } + + return HotkeyReport.fromJson(decoded.cast()); + } + + @override + String toString() => "HotkeyReport(desktop: $desktop, session: $session, " + "binding: $binding, registered: $registered, orphans: ${orphans.length})"; +} + +/// Reads what the desktop knows about this app's keyboard shortcut. +/// +/// The desktop's own mechanism (gsettings, KDE's own files) is the single +/// source of truth since the app stopped grabbing the key itself. This service +/// only asks the script that owns that mechanism and turns its answer into +/// something the UI can show. +class HotkeyDiagnostics { + const HotkeyDiagnostics(); + + /// Asks the script for the current state and parses its answer. + /// + /// Never throws: a missing script, an unknown desktop or broken JSON all + /// end up as a report with `registered: false` and an error text. + Future loadReport() async { + final CommandResult result; + try { + result = await Linux.getHotkeyReport(); + } catch (error) { + logError("Reading the hotkey report failed", error); + return HotkeyReport.unavailable( + "The keybinding report could not be started: $error", + ); + } + + if (!result.success) { + final String reason = result.error.trim().isNotEmpty + ? result.error.trim() + : result.output.trim(); + logError("Reading the hotkey report failed", reason); + return HotkeyReport.unavailable( + reason.isEmpty + ? "The keybinding script failed without a message." + : reason, + ); + } + + return HotkeyReport.parse(result.output); + } + + /// Removes the orphaned `custom*` entries. + /// + /// What counts as an orphan is decided by the script, never by the app: it + /// is the only place that knows the desktop's own layout, and an entry that + /// belongs to another app is untouchable there. + Future cleanupOrphans() async { + try { + final CommandResult result = await Linux.cleanupHotkeyOrphans(); + if (!result.success) { + final String reason = result.error.trim().isNotEmpty + ? result.error.trim() + : result.output.trim(); + logError("Cleaning up orphaned keybindings failed", reason); + return false; + } + return true; + } catch (error) { + logError("Cleaning up orphaned keybindings failed", error); + return false; + } + } +} + +/// Reads a string out of a JSON map without trusting the type. +String _asString(Object? value) => value is String ? value : ""; diff --git a/lib/services/linux.dart b/lib/services/linux.dart index b06baf43..12841b92 100644 --- a/lib/services/linux.dart +++ b/lib/services/linux.dart @@ -2558,6 +2558,41 @@ class Linux { return result.success; } + /// Asks the keybinding script what the desktop knows about our shortcut. + /// + /// Read-only: the report mode of `setup_keybinding.py` only reads the + /// desktop's settings, it never writes to them. The JSON is parsed by + /// `HotkeyDiagnostics`, so this stays the plain process call every other + /// caller in here does — a script path and its arguments, never a shell + /// string. + static Future getHotkeyReport() async { + return runProcess( + "python3", + [ + "${pythonScriptsFolder}setup_keybinding.py", + "--report", + ], + environment: Platform.environment, + ); + } + + /// Removes the orphaned `custom*` entries of our own shortcut. + /// + /// The counterpart of [getHotkeyReport]. What counts as an orphan is + /// decided by the script, never by the app: it is the only place that + /// knows the desktop's own layout, and an entry that belongs to another app + /// is untouchable there. + static Future cleanupHotkeyOrphans() async { + return runProcess( + "python3", + [ + "${pythonScriptsFolder}setup_keybinding.py", + "--cleanup", + ], + environment: Platform.environment, + ); + } + static String getHotkeyModifier() { if (currentenvironment.desktop == DESKTOPS.KDE) { return ""; diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc index d528dadd..c8f3dcc2 100644 --- a/linux/flutter/generated_plugin_registrant.cc +++ b/linux/flutter/generated_plugin_registrant.cc @@ -6,14 +6,10 @@ #include "generated_plugin_registrant.h" -#include #include #include void fl_register_plugins(FlPluginRegistry* registry) { - g_autoptr(FlPluginRegistrar) hotkey_manager_linux_registrar = - fl_plugin_registry_get_registrar_for_plugin(registry, "HotkeyManagerLinuxPlugin"); - hotkey_manager_linux_plugin_register_with_registrar(hotkey_manager_linux_registrar); g_autoptr(FlPluginRegistrar) screen_retriever_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "ScreenRetrieverLinuxPlugin"); screen_retriever_linux_plugin_register_with_registrar(screen_retriever_linux_registrar); From fe46675cc3bb8e3039099266dd6d7affb70c3956 Mon Sep 17 00:00:00 2001 From: ElGregor Date: Fri, 30 Oct 2026 00:43:42 +0100 Subject: [PATCH 7/7] feat(hotkey): Hotkey ueber gsettings in beiden Sitzungen (#58) (Block 7) --- linux/flutter/generated_plugins.cmake | 1 - pubspec.lock | 72 ---- pubspec.yaml | 1 - test/q4_hotkey_test.dart | 485 ++++++++++++++++++++++++++ 4 files changed, 485 insertions(+), 74 deletions(-) create mode 100644 test/q4_hotkey_test.dart diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index 1df1c684..00303ac7 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -3,7 +3,6 @@ # list(APPEND FLUTTER_PLUGIN_LIST - hotkey_manager_linux screen_retriever_linux window_manager ) diff --git a/pubspec.lock b/pubspec.lock index c72a3544..ab50d665 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -73,14 +73,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.3.3" - fixnum: - dependency: transitive - description: - name: fixnum - sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be - url: "https://pub.dev" - source: hosted - version: "1.1.1" fl_chart: dependency: "direct main" description: @@ -141,46 +133,6 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.1" - hotkey_manager: - dependency: "direct main" - description: - name: hotkey_manager - sha256: "06f0655b76c8dd322fb7101dc615afbdbf39c3d3414df9e059c33892104479cd" - url: "https://pub.dev" - source: hosted - version: "0.2.3" - hotkey_manager_linux: - dependency: transitive - description: - name: hotkey_manager_linux - sha256: "83676bda8210a3377bc6f1977f193bc1dbdd4c46f1bdd02875f44b6eff9a8473" - url: "https://pub.dev" - source: hosted - version: "0.2.0" - hotkey_manager_macos: - dependency: transitive - description: - name: hotkey_manager_macos - sha256: "03b5967e64357b9ac05188ea4a5df6fe4ed4205762cb80aaccf8916ee1713c96" - url: "https://pub.dev" - source: hosted - version: "0.2.0" - hotkey_manager_platform_interface: - dependency: transitive - description: - name: hotkey_manager_platform_interface - sha256: "98ffca25b8cc9081552902747b2942e3bc37855389a4218c9d50ca316b653b13" - url: "https://pub.dev" - source: hosted - version: "0.2.0" - hotkey_manager_windows: - dependency: transitive - description: - name: hotkey_manager_windows - sha256: "0d03ced9fe563ed0b68f0a0e1b22c9ffe26eb8053cb960e401f68a4f070e0117" - url: "https://pub.dev" - source: hosted - version: "0.2.0" http: dependency: "direct main" description: @@ -377,14 +329,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.10.1" - sprintf: - dependency: transitive - description: - name: sprintf - sha256: "1fc9ffe69d4df602376b52949af107d8f5703b77cda567c4d7d86a0693120f23" - url: "https://pub.dev" - source: hosted - version: "7.0.0" stack_trace: dependency: transitive description: @@ -433,22 +377,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.0" - uni_platform: - dependency: transitive - description: - name: uni_platform - sha256: e02213a7ee5352212412ca026afd41d269eb00d982faa552f419ffc2debfad84 - url: "https://pub.dev" - source: hosted - version: "0.1.3" - uuid: - dependency: transitive - description: - name: uuid - sha256: a5be9ef6618a7ac1e964353ef476418026db906c4facdedaa299b7a2e71690ff - url: "https://pub.dev" - source: hosted - version: "4.5.1" vector_graphics: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 5fd03b81..ef5f7a72 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -50,7 +50,6 @@ dependencies: # Use with the CupertinoIcons class for iOS style icons. fl_chart: ^0.70.2 flutter_svg_provider: ^1.0.3 - hotkey_manager: ^0.2.3 window_manager: ^0.4.3 crypto: ^3.0.2 http: ^1.3.0 diff --git a/test/q4_hotkey_test.dart b/test/q4_hotkey_test.dart new file mode 100644 index 00000000..7eecc712 --- /dev/null +++ b/test/q4_hotkey_test.dart @@ -0,0 +1,485 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:linux_assistant/helpers/command_helper.dart'; +import 'package:linux_assistant/l10n/app_localizations.dart'; +import 'package:linux_assistant/layouts/main_screen/action_entry_card.dart'; +import 'package:linux_assistant/layouts/main_screen/main_search.dart'; +import 'package:linux_assistant/layouts/mint_y.dart'; +import 'package:linux_assistant/models/action_entry.dart'; +import 'package:linux_assistant/services/action_entry_list_service.dart'; +import 'package:linux_assistant/services/config_handler.dart'; +import 'package:linux_assistant/services/hotkey_diagnostics.dart'; +import 'package:linux_assistant/services/linux.dart'; + +/// Tests for the Q4 rework of the keyboard shortcut (#58). +/// +/// Two things are proved here: +/// +/// 1. The report of the desktop's keybinding settings is parsed the way the +/// python script writes it — and a broken answer does not become an +/// exception. +/// 2. The keys of the search field work as plain Flutter shortcuts. That is +/// the proof that the global hotkey grab is really gone: the app does not +/// take the keys any more, the field itself reacts to them. +/// +/// Everything runs hermetic: no desktop, no real process. The script call is +/// answered by a fake [CommandRunner] — the seam the app already has — and +/// the search screen runs against an in-memory entry list. +void main() { + group("the report of the desktop", () { + test("a valid report is parsed into the object the page shows", () { + final String raw = jsonEncode({ + "desktop": "gnome", + "session": "wayland", + "binding": "q", + "registered": true, + "orphans": [ + { + "path": "/org/gnome/settings-daemon/plugins/media-keys/" + "custom-keybindings/custom3/", + "binding": "q", + } + ], + }); + + final HotkeyReport report = HotkeyReport.parse(raw); + + expect(report.desktop, "gnome"); + expect(report.session, "wayland"); + expect(report.binding, "q"); + expect(report.registered, isTrue); + expect(report.hasError, isFalse); + expect(report.orphans, hasLength(1)); + expect(report.orphans.first.path, endsWith("custom3/")); + expect(report.orphans.first.binding, "q"); + }); + + test("a report without orphans is not an error", () { + final HotkeyReport report = HotkeyReport.parse(jsonEncode({ + "desktop": "cinnamon", + "session": "x11", + "binding": "q", + "registered": true, + "orphans": [], + })); + + expect(report.registered, isTrue); + expect(report.orphans, isEmpty); + expect(report.hasError, isFalse); + }); + + test("broken JSON becomes a report that says 'not registered'", () { + // No exception, no crash: the page has to be able to show this. + final HotkeyReport report = HotkeyReport.parse("{ this is not json"); + + expect(report.registered, isFalse); + expect(report.hasError, isTrue); + expect(report.error, isNotEmpty); + expect(report.orphans, isEmpty); + }); + + test("empty output becomes a report that says 'not registered'", () { + final HotkeyReport report = HotkeyReport.parse(" \n "); + + expect(report.registered, isFalse); + expect(report.hasError, isTrue); + }); + + test("JSON that is not an object becomes a report, not an exception", () { + final HotkeyReport report = HotkeyReport.parse("[1, 2, 3]"); + + expect(report.registered, isFalse); + expect(report.hasError, isTrue); + }); + + test("missing fields do not crash and do not claim a shortcut", () { + final HotkeyReport report = HotkeyReport.parse('{"desktop": "gnome"}'); + + expect(report.desktop, "gnome"); + expect(report.session, ""); + expect(report.binding, ""); + // A missing field must never be read as "registered". + expect(report.registered, isFalse); + expect(report.orphans, isEmpty); + expect(report.hasError, isFalse); + }); + + test("fields of the wrong type do not crash", () { + final HotkeyReport report = HotkeyReport.parse(jsonEncode({ + "desktop": 42, + "session": null, + "binding": ["q"], + "registered": "yes", + "orphans": "not a list", + })); + + expect(report.desktop, ""); + expect(report.session, ""); + expect(report.binding, ""); + expect(report.registered, isFalse); + expect(report.orphans, isEmpty); + }); + + test("orphans of the wrong type are skipped, the rest is kept", () { + final HotkeyReport report = HotkeyReport.parse(jsonEncode({ + "desktop": "gnome", + "registered": true, + "orphans": [ + "not an object", + {"path": "/a/b/custom1/", "binding": "q"}, + ], + })); + + expect(report.orphans, hasLength(1)); + expect(report.orphans.first.path, "/a/b/custom1/"); + }); + + test("a JSON object in a noisy output is still found", () { + // A warning of a wrapper script in front of the report must not make + // the whole answer unusable. + final HotkeyReport report = HotkeyReport.parse( + "warning: something happened\n" + '{"desktop": "xfce", "session": "x11", "binding": "q", ' + '"registered": true, "orphans": []}\n', + ); + + expect(report.desktop, "xfce"); + expect(report.registered, isTrue); + expect(report.hasError, isFalse); + }); + }); + + group("reading the report from the script", () { + late _FakeRunner runner; + + setUp(() { + runner = _FakeRunner(); + CommandHelper.runner = runner; + Linux.pythonScriptsFolder = "/opt/linux-assistant/additional/python/"; + }); + + tearDown(() { + CommandHelper.runner = CommandHelper.processRunner; + Linux.pythonScriptsFolder = ""; + }); + + test("the script is called with --report and its answer is parsed", + () async { + runner.result = () => const CommandResult( + true, + '{"desktop": "gnome", "session": "wayland", "binding": "q",' + ' "registered": true, "orphans": []}', + "", + ); + + final HotkeyReport report = await const HotkeyDiagnostics().loadReport(); + + expect(report.registered, isTrue); + expect(report.binding, "q"); + + // The script is called with an argument list, never with a shell + // string — and with the report mode, not with the registering one. + expect(runner.calls, hasLength(1)); + expect(runner.calls.single.first, endsWith("python3")); + expect(runner.calls.single[1], endsWith("setup_keybinding.py")); + expect(runner.calls.single[2], "--report"); + expect(runner.calls.single, isNot(contains("--alt"))); + }); + + test("a failing script becomes a report that says 'not registered'", + () async { + runner.result = () => const CommandResult( + false, + "", + "No supported desktop found in XDG_CURRENT_DESKTOP=''", + ); + + final HotkeyReport report = await const HotkeyDiagnostics().loadReport(); + + expect(report.registered, isFalse); + expect(report.hasError, isTrue); + expect(report.error, contains("No supported desktop")); + }); + + test("output that is not JSON becomes a report, not an exception", + () async { + runner.result = () => const CommandResult(true, "Traceback ...", ""); + + final HotkeyReport report = await const HotkeyDiagnostics().loadReport(); + + expect(report.registered, isFalse); + expect(report.hasError, isTrue); + }); + + test("the cleanup calls the script with --cleanup", () async { + runner.result = () => const CommandResult(true, "", ""); + + final bool ok = await const HotkeyDiagnostics().cleanupOrphans(); + + expect(ok, isTrue); + expect(runner.calls.single[1], endsWith("setup_keybinding.py")); + expect(runner.calls.single[2], "--cleanup"); + }); + + test("a failing cleanup is reported as a failure", () async { + runner.result = () => const CommandResult(false, "", "boom"); + + final bool ok = await const HotkeyDiagnostics().cleanupOrphans(); + + expect(ok, isFalse); + }); + }); + + group("the keys of the search field", () { + late Directory sandbox; + + setUp(() { + sandbox = Directory.systemTemp.createTempSync("mla_q4_hotkey_"); + ConfigHandler().resetForTesting(directory: sandbox); + ActionEntryListService.clearEntries(); + // The priorities are different on purpose: the search sorts by + // priority, and a stable order is what the assertions below are + // about. + ActionEntryListService.addEntries([ + ActionEntry( + name: "Alpha result", + description: "The first result", + action: "alpha", + priority: 30, + ), + ActionEntry( + name: "Beta result", + description: "The second result", + action: "beta", + priority: 20, + ), + ActionEntry( + name: "Gamma result", + description: "The third result", + action: "gamma", + priority: 10, + ), + ]); + }); + + tearDown(() { + ConfigHandler().resetForTesting(); + ActionEntryListService.clearEntries(); + if (sandbox.existsSync()) { + sandbox.deleteSync(recursive: true); + } + }); + + testWidgets("arrow down moves the selection in the result list", + (tester) async { + _useDesktopView(tester); + await tester.pumpWidget(_searchHost()); + await tester.pump(); + _swallowCardOverflow(tester); + + await tester.enterText(find.byType(TextField), "resu"); + await tester.pump(); + await tester.pump(); + _swallowCardOverflow(tester); + + // The list is there and the first entry is selected. + expect(find.byType(ActionEntryCard), findsWidgets); + expect(_selectedAction(tester), "alpha"); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + + expect(_selectedAction(tester), "beta"); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + + expect(_selectedAction(tester), "gamma"); + + // The last entry of the list is the web search the search screen adds + // for every term. + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + + expect(_selectedAction(tester), "websearch:resu"); + + // The list does not run past its end. + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + + expect(_selectedAction(tester), "websearch:resu"); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + + expect(_selectedAction(tester), "gamma"); + + await _tearDownSearch(tester); + }); + + testWidgets("escape empties the search field", (tester) async { + _useDesktopView(tester); + await tester.pumpWidget(_searchHost()); + await tester.pump(); + _swallowCardOverflow(tester); + + await tester.enterText(find.byType(TextField), "resu"); + await tester.pump(); + await tester.pump(); + _swallowCardOverflow(tester); + + expect(_searchText(tester), "resu"); + expect(find.byType(ActionEntryCard), findsWidgets); + + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + + expect(_searchText(tester), isEmpty); + // The result list is gone with the search term. + expect(find.byType(ActionEntryCard), findsNothing); + + await _tearDownSearch(tester); + }); + + testWidgets("the keys only work while the search field has the focus", + (tester) async { + _useDesktopView(tester); + await tester.pumpWidget(_searchHost()); + await tester.pump(); + _swallowCardOverflow(tester); + + await tester.enterText(find.byType(TextField), "resu"); + await tester.pump(); + await tester.pump(); + _swallowCardOverflow(tester); + + expect(_selectedAction(tester), "alpha"); + + // Without the focus on the field, the key belongs to nobody: the + // shortcut sits on the field, not on the window. + FocusManager.instance.primaryFocus?.unfocus(); + await tester.pump(); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + + expect(_selectedAction(tester), "alpha"); + + await _tearDownSearch(tester); + }); + }); +} + +/// The app's own shell around the search screen. +Widget _searchHost() { + return MaterialApp( + theme: MintY.theme(), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: const [Locale('en', '')], + home: MainSearch(), + ); +} + +/// Takes the search screen down at the end of a test. +/// +/// The widgets that are on screen while the search is empty start processes, +/// and the start of a process is a timer. A timer that is still running when +/// the test ends counts as a failure, so it gets its turn before the tree +/// goes away. +Future _tearDownSearch(WidgetTester tester) async { + // A millisecond of fake time lets the timers of zero length run out: the + // start of a process is one of them, and the disk space row starts one + // every time it comes back into the screen. + await tester.pump(const Duration(milliseconds: 1)); + await tester.pumpWidget(const SizedBox()); + _swallowCardOverflow(tester); +} + +/// Takes the layout overflow of the recommendation card out of the way. +/// +/// The card at the bottom of the search screen gives its title no width +/// limit, so it overflows with the test font — every character is a full +/// font size wide there. That is a layout problem of the card and not of the +/// key handling, and the card is not part of this change, so the overflow is +/// taken out of the way here. Every other exception is a test failure. +void _swallowCardOverflow(WidgetTester tester) { + const List known = [ + "A RenderFlex overflowed", + // The widget inspector trips over the tree that is being torn down + // while it describes the overflow above. + "Looking up a deactivated widget's ancestor is unsafe", + ]; + while (true) { + final Object? exception = tester.takeException(); + if (exception == null) { + return; + } + final String text = exception.toString(); + if (!known.any(text.contains)) { + throw exception; + } + } +} + +/// Pins the test window to a desktop size. +/// +/// The search screen puts its field and its buttons in one row. In the +/// default test surface (800x600) that row does not fit, and the overflow is +/// reported as a test error — the same overflow a user would never see on a +/// real desktop. +void _useDesktopView(WidgetTester tester) { + tester.view.physicalSize = const Size(1400, 900); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); +} + +/// The action of the entry that is currently selected, null when none is. +String? _selectedAction(WidgetTester tester) { + final Iterable cards = + tester.widgetList(find.byType(ActionEntryCard)); + for (final ActionEntryCard card in cards) { + if (card.selected) { + return card.actionEntry.action; + } + } + return null; +} + +/// The text in the search field. +String _searchText(WidgetTester tester) { + final TextField field = tester.widget(find.byType(TextField)); + return field.controller?.text ?? ""; +} + +/// A [CommandRunner] that answers with a prepared result and records the +/// calls. The script is never really started. +class _FakeRunner implements CommandRunner { + /// Builds the result for one call. + CommandResult Function() result = () => const CommandResult(true, "", ""); + + /// Every call, as the argument list the runner received. + final List> calls = []; + + @override + Future run( + String command, + List arguments, { + Map? environment, + bool asRoot = false, + bool hostOnFlatpak = true, + bool runInShell = false, + }) async { + calls.add([command, ...arguments]); + return result(); + } +}