Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 15 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 '<Meta>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.
Expand All @@ -49,29 +45,29 @@ 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
```

## 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
Expand Down
241 changes: 233 additions & 8 deletions additional/python/keybinding_files.py
Original file line number Diff line number Diff line change
@@ -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/<Super>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/<Super>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"

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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/<Super>q` holds `<Super>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
Loading
Loading