diff --git a/docs/screenshots/keyboard/bar-label.png b/docs/screenshots/keyboard/bar-label.png new file mode 100644 index 000000000..eedf1c9e4 Binary files /dev/null and b/docs/screenshots/keyboard/bar-label.png differ diff --git a/docs/screenshots/keyboard/kbd-card.png b/docs/screenshots/keyboard/kbd-card.png new file mode 100644 index 000000000..4293c8ee0 Binary files /dev/null and b/docs/screenshots/keyboard/kbd-card.png differ diff --git a/docs/screenshots/keyboard/kbd-page.png b/docs/screenshots/keyboard/kbd-page.png new file mode 100644 index 000000000..ac12d2583 Binary files /dev/null and b/docs/screenshots/keyboard/kbd-page.png differ diff --git a/docs/screenshots/keyboard/switch-delay.png b/docs/screenshots/keyboard/switch-delay.png new file mode 100644 index 000000000..1a478a43b Binary files /dev/null and b/docs/screenshots/keyboard/switch-delay.png differ diff --git a/packages/omamobile-settings/app/KeyboardPage.qml b/packages/omamobile-settings/app/KeyboardPage.qml new file mode 100644 index 000000000..fd75daba0 --- /dev/null +++ b/packages/omamobile-settings/app/KeyboardPage.qml @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: MIT +// Keyboard layouts (up to 4) and the hardware switch key, through backends/keyboard.sh. Each change is +// saved and applied at once; new layouts are added to the on-screen keyboard's list, and the switch key is an xkb grp: option in kb_options. +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import "." +Flickable { + id: page + clip: true + contentWidth: width; contentHeight: col.implicitHeight + boundsBehavior: Flickable.StopAtBounds + property var layouts: [] // ["us", "gr:polytonic"], index 0 = main layout + property string switchKey: "" + property var available: [] // [{layout, name}] + property var switchKeys: [] // [{option, name}] + property string status: qsTr("Reading the keyboard settings...") + property string warn: "" + property bool busy: true + property int reqId: -1 + property int listId: -1 + readonly property int maxLayouts: 4 + // Same set as LATIN in backends/keyboard.sh + readonly property var latin: ["us", "gb", "de", "fr", "es", "it", "pt", "nl", "be", "ch", "at", "se", "no", "dk", "fi", + "is", "ie", "pl", "cz", "sk", "hu", "ro", "hr", "si", "ee", "lv", "lt", "tr", "br", "latam", + "ca", "au", "nz", "za", "epo"] + function nameOf(code) { + const l = code.split(":")[0], v = code.split(":")[1] || "" + for (const a of available) if (a.layout === l) return v ? a.name + " (" + v + ")" : a.name + return code + } + function keyName(opt) { + for (const k of switchKeys) if (k.option === opt) return k.name + return opt + } + property string lastError: "" // shown after the re-read that follows a failed set + function isLatin(code) { return latin.indexOf(code.split(":")[0]) >= 0 } + function apply(r) { + busy = false + if (r.error) { + // A set can fail half way (file saved, live apply or OSK not): read the real state again so + // the next change is not built from a stale list, and keep the error on screen. + if (lastError === "") { lastError = r.error; status = r.error; busy = true; reqId = actions.run("keyboard", ["get"]) } + else { status = lastError; lastError = "" } + return + } + if (!r.layouts) { status = qsTr("The keyboard backend gave no values."); return } + layouts = r.layouts.map(x => x.variant ? x.layout + ":" + x.variant : x.layout) + switchKey = r.switchKey || "" + warn = layouts.length && !isLatin(layouts[0]) + ? qsTr("The first layout is not a Latin one: passwords on the lock screen are typed in it") : "" + status = lastError !== "" ? lastError : qsTr("Changes apply at once to hardware keyboards and the on-screen keyboard.") + lastError = "" + } + function save(list) { + filter.text = "" + // The backend refuses this too; stop here so nothing is sent. + if (!list.length || !isLatin(list[0])) { + status = qsTr("The first layout must be a Latin one: passwords on the lock screen are typed in it.") + return + } + busy = true + reqId = actions.run("keyboard", ["set", "layouts", list.join(",")]) + } + function move(i, d) { + const l = layouts.slice(), j = i + d + if (j < 0 || j >= l.length) return + const t = l[i]; l[i] = l[j]; l[j] = t + save(l) + } + function remove(i) { const l = layouts.slice(); l.splice(i, 1); save(l) } + function add(code) { if (layouts.indexOf(code) < 0) save(layouts.concat([code])) } + Connections { + target: actions + function onFinished(tool, r, id) { + if (tool !== "keyboard") return + if (id === page.listId) { page.available = r.layouts || []; page.switchKeys = r.switchKeys || [] } + else if (id === page.reqId) page.apply(r) + } + } + Component.onCompleted: { listId = actions.run("keyboard", ["list"]); reqId = actions.run("keyboard", ["get"]) } + ColumnLayout { + id: col + width: page.width + spacing: 14 + SettingsLabel { text: qsTr("Layouts"); font.weight: Font.DemiBold; color: backend.foreground; Layout.fillWidth: true } + Repeater { + model: page.layouts + delegate: RowLayout { + required property string modelData + required property int index + Layout.fillWidth: true; spacing: 8 + SettingsLabel { + text: (index + 1) + ". " + page.nameOf(modelData) + color: backend.foreground; wrapMode: Text.Wrap; Layout.fillWidth: true + } + SettingsButton { text: "↑"; enabled: !page.busy && index > 0; onClicked: page.move(index, -1); Accessible.name: qsTr("Move up") } + SettingsButton { text: "↓"; enabled: !page.busy && index < page.layouts.length - 1; onClicked: page.move(index, 1); Accessible.name: qsTr("Move down") } + SettingsButton { text: "✕"; enabled: !page.busy && page.layouts.length > 1; onClicked: page.remove(index); Accessible.name: qsTr("Remove") } + } + } + SettingsLabel { + visible: page.warn !== "" + text: "⚠ " + page.warn + color: backend.foreground; wrapMode: Text.Wrap; Layout.fillWidth: true + } + // Add a layout: a search field, with matches shown as you type (the full list is ~100 long). + SettingsTextField { + id: filter + visible: page.layouts.length < page.maxLayouts + enabled: !page.busy && page.available.length > 0 + Layout.fillWidth: true; Layout.preferredHeight: 52 + placeholderText: qsTr("Add a layout: type a language or country") + color: backend.foreground; placeholderTextColor: backend.muted + background: Rectangle { radius: Math.min(backend.radius, width / 2, height / 2); color: SettingsStyle.fill("normal") } + } + Repeater { + model: filter.visible && filter.text.trim() !== "" ? page.available.filter(a => { + const q = filter.text.trim().toLowerCase() + return page.layouts.indexOf(a.layout) < 0 && (a.name.toLowerCase().indexOf(q) >= 0 || a.layout.indexOf(q) >= 0) + }).slice(0, 12) : [] + delegate: SettingsButton { + required property var modelData + Layout.fillWidth: true + text: modelData.name + " (" + modelData.layout + ")" + enabled: !page.busy + onClicked: page.add(modelData.layout) + } + } + SettingsLabel { + visible: page.layouts.length > 1 + text: qsTr("Switch key (hardware keyboard)"); font.weight: Font.DemiBold; color: backend.foreground + Layout.fillWidth: true; Layout.topMargin: 8 + } + Flow { + visible: page.layouts.length > 1 + Layout.fillWidth: true; spacing: 8 + Repeater { + // From `keyboard.sh list`: Alt+Shift, Ctrl+Shift, Caps Lock, None (grp:alt_shift_toggle, grp:ctrl_shift_toggle, grp:caps_toggle, no grp:) + model: page.switchKeys + delegate: SettingsButton { + required property var modelData + text: modelData.name + highlighted: page.switchKey === modelData.option + enabled: !page.busy + onClicked: { page.busy = true; page.reqId = actions.run("keyboard", ["set", "switch-key", modelData.option]) } + } + } + } + SettingsLabel { text: page.status; color: backend.muted; font.pixelSize: SettingsStyle.fontPx(13); wrapMode: Text.Wrap; Layout.fillWidth: true } + } +} diff --git a/packages/omamobile-settings/app/Main.qml b/packages/omamobile-settings/app/Main.qml index 25a26417f..bcbc75545 100644 --- a/packages/omamobile-settings/app/Main.qml +++ b/packages/omamobile-settings/app/Main.qml @@ -24,7 +24,7 @@ ApplicationWindow { if (backend.searching) search.clear() backend.back() } - readonly property var customPages: ({ display: "DisplayPage.qml" }) + readonly property var customPages: ({ display: "DisplayPage.qml", keyboard: "KeyboardPage.qml" }) readonly property string customSource: backend.searching ? "" : (customPages[backend.page] || "") readonly property bool showingAbout: backend.page === "about" && !backend.searching Connections { diff --git a/packages/omamobile-settings/app/actionrunner.cpp b/packages/omamobile-settings/app/actionrunner.cpp index a118095f2..4ab875720 100644 --- a/packages/omamobile-settings/app/actionrunner.cpp +++ b/packages/omamobile-settings/app/actionrunner.cpp @@ -16,11 +16,14 @@ void ActionRunner::post(const QString &tool, const QVariantMap &result, int id) int ActionRunner::run(const QString &tool, const QStringList &args) { static const QRegularExpression word("\\A[a-z0-9]{1,16}\\z"); - static const QStringList tools = {"display"}; + // keyboard takes layout lists (us,gr:polytonic), and switch-key names (alt_shift, ctrl_shift, caps, none) + static const QRegularExpression kbdWord("\\A[a-z][a-z0-9_:,-]{0,159}\\z"); + static const QStringList tools = {"display", "keyboard"}; const int id = ++m_next; auto fail = [this, &tool, id](const QString &why) { post(tool, {{"error", why}}, id); return id; }; if (!tools.contains(tool) || args.size() > 3) return fail("unknown action"); - for (const auto &a : args) if (!word.match(a).hasMatch()) return fail("bad argument"); + const auto &allowed = tool == "keyboard" ? kbdWord : word; + for (const auto &a : args) if (!allowed.match(a).hasMatch()) return fail("bad argument"); const QString dir = "/usr/lib/omamobile-settings/backends"; auto *p = new QProcess(this); // bash would run a startup file named by these @@ -31,7 +34,7 @@ int ActionRunner::run(const QString &tool, const QStringList &args) { p->setProgram("/usr/bin/bash"); p->setArguments(QStringList{dir + "/" + tool + ".sh"} + args); connect(p, &QProcess::finished, this, [this, p, tool, id](int code, QProcess::ExitStatus st) { - const auto raw = p->readAllStandardOutput().left(4096); + const auto raw = p->readAllStandardOutput().left(32768); p->readAllStandardError(); auto obj = QJsonDocument::fromJson(raw).object(); if (obj.isEmpty() || st != QProcess::NormalExit) diff --git a/packages/omamobile-settings/app/actionrunner.h b/packages/omamobile-settings/app/actionrunner.h index e56a52234..5685d0b6a 100644 --- a/packages/omamobile-settings/app/actionrunner.h +++ b/packages/omamobile-settings/app/actionrunner.h @@ -4,7 +4,7 @@ #include #include -// Runs the source-owned backend scripts (display) with a fixed argument list and no shell. Pages call run(); +// Runs the source-owned backend scripts (display, keyboard) with a fixed argument list and no shell. Pages call run(); // the JSON the script prints comes back through finished(), always from the event loop and never before run() // has returned its id. class ActionRunner : public QObject { diff --git a/packages/omamobile-settings/app/catalog.json b/packages/omamobile-settings/app/catalog.json index 23efec22b..8aa44de2d 100644 --- a/packages/omamobile-settings/app/catalog.json +++ b/packages/omamobile-settings/app/catalog.json @@ -9,6 +9,13 @@ "icon": "display", "page": "display" }, + { + "id": "keyboard", + "title": "Keyboard", + "detail": "Layouts and the switch key", + "icon": "keyboard", + "page": "keyboard" + }, { "id": "about", "title": "About this device", @@ -25,5 +32,9 @@ "display": { "title": "Display", "rows": [] + }, + "keyboard": { + "title": "Keyboard", + "rows": [] } } diff --git a/packages/omamobile-settings/app/icons/keyboard.svg b/packages/omamobile-settings/app/icons/keyboard.svg new file mode 100644 index 000000000..e6b769689 --- /dev/null +++ b/packages/omamobile-settings/app/icons/keyboard.svg @@ -0,0 +1 @@ + diff --git a/packages/omamobile-settings/app/resources.qrc b/packages/omamobile-settings/app/resources.qrc index 0f18d70dc..8ce5b4243 100644 --- a/packages/omamobile-settings/app/resources.qrc +++ b/packages/omamobile-settings/app/resources.qrc @@ -4,6 +4,8 @@ Main.qml AboutPage.qml DisplayPage.qml + KeyboardPage.qml + icons/keyboard.svg icons/display.svg catalog.json icons/system.svg diff --git a/packages/omamobile-settings/backends/keyboard.sh b/packages/omamobile-settings/backends/keyboard.sh new file mode 100755 index 000000000..12ee9956b --- /dev/null +++ b/packages/omamobile-settings/backends/keyboard.sh @@ -0,0 +1,555 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Keyboard layouts for the Settings app. The hardware keyboard's layouts live in Omarchy's user file +# ~/.config/hypr/input.lua (kb_layout, kb_variant); the on-screen keyboard's list is gsettings +# org.gnome.desktop.input-sources sources, and a layouts change adds new ones there too. +# The switch key is pure xkb, a grp: option in kb_options, never a Hyprland bind (measured on the phone, +# Hyprland 0.57.0-3.2, Dell KB7120W over Bluetooth): alt_shift = grp:alt_shift_toggle (20/20 on 2026-11-18, +# both key orders, 1-2 ms after the second key), ctrl_shift = grp:ctrl_shift_toggle (41 switches in two runs, both orders, no doubles), +# caps = grp:caps_toggle,grp_led:caps (14 timed presses, 2-3 ms, 2026-11-17), none = no grp: option. Press binds on +# top of the xkb option switched twice per press, so phone.lua binds nothing. "get" reads the choice from +# the effective kb_options; any other grp: option (Omarchy's grp:alts_toggle for a non-Latin layout, say) +# reports none, and only a switch-key save replaces it. On a fresh phone nothing switches the hardware +# layout until a key is picked here, unless Omarchy's input.lua already sets a grp: option (it does not +# with Latin layouts only). omamobile-keyboard-switch exists but nothing calls it yet (not the +# quick-settings card either). +# Prints one line of JSON. +# keyboard.sh get {"layouts":[{"layout":"us","variant":""}],"switchKey":"alt_shift","active":0} +# keyboard.sh list {"layouts":[{"layout":"us","name":"English (US)"}],"switchKeys":[...]} +# keyboard.sh set layouts us,gr[:variant] 1 to 4 layouts, each a name (and variant) in the xkb rules list +# keyboard.sh set switch-key NAME alt_shift, ctrl_shift, caps or none +# "active" is the index Hyprland reports for the main real keyboard, or null without one. Real = not +# hl-virtual-keyboard* and not a pseudo-keyboard (consumer-control, power-button, video-bus, radio-control, +# gpio-keys); main = the real one Hyprland marks main, else the first real one with more than one layout, +# else the first real one (the same rule as omamobile-keyboard-switch and the bar). A layouts list whose +# first entry is not a Latin layout is refused (passwords on the lock screen are typed in layout 1). +# input.lua is edited in place: only the last live kb_layout, kb_variant and kb_options strings inside an +# `input = { }` table change (per-device blocks and variables are left alone), comments and every other +# option stays but, on a switch-key save, grp:, grp_led:caps (set only with caps) and compose:caps or omarchy:shift_caps_compose with caps +# (put back when caps lets go, only if it was there: "-- compose-caps: restore" in a small state file, +# ~/.config/hypr/omamobile-keyboard.lua, which nothing loads; it is removed when not needed), a copy of the old +# file goes to input.lua.bak-omamobile first, and the write is dropped if the file changed meanwhile. +# A file with no live kb_layout (Omarchy's stock one has them only in comments) gets one hl.config() block +# appended at the end; get then reports Hyprland's effective values. +# A symlinked input.lua stays a link: its target is written. gsettings is written first, then the change +# is applied live without `hyprctl reload` (a reload sets the configured refresh rate again and re-runs +# phone.lua). gsettings is merged, not replaced: the +# OSK's own languages and its current (first) entry stay; new hardware layouts are added at the end +# (only ones squeekboard has a layout file for, when that directory exists); removed ones are dropped. +# A switch-key change does not touch gsettings. Switching layouts never writes gsettings either (that made +# squeekboard send its keymap again, and the app got Latin letters while Hyprland said Greek). +# Known limits: xkb keeps a layout per keyboard, so with two real keyboards the switch key moves only the +# one it was pressed on (UNVERIFIED on the phone, only one keyboard tested). +# A bind file from earlier unreleased commits of this branch ("-- switch-key: alt_shift" or ctrl_shift) +# is no longer loaded. While kb_options has no grp: option, get reports its choice and the next save +# writes the matching grp: option and removes the file. Binds it registered stay in Hyprland until +# `hyprctl reload` (or a new login). +# When input.lua has no live kb_layout or kb_options, a save needs Hyprland's effective value; if +# `hyprctl getoption` fails, nothing is written. +# Test hooks (nothing in the environment sets them): OMAMOBILE_KBD_INPUT is the input.lua path, +# OMAMOBILE_KBD_BINDS the state file, +# OMAMOBILE_KBD_RULES the xkb rules .lst file, OMAMOBILE_KEYBOARDS_DIR squeekboard's layout files; the test puts a fake hyprctl and gsettings first on PATH. +set -euo pipefail +set +x +fail() { printf '{"error":"%s"}\n' "$1"; exit 2; } + +find_hypr() { + [[ -n ${HYPRLAND_INSTANCE_SIGNATURE:-} ]] && return 0 + local d best='' sig + for d in "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"/hypr/*/; do + [[ -S $d.socket.sock ]] || continue + if [[ -z $best || $d.socket.sock -nt $best.socket.sock ]]; then best=$d; fi + done + [[ -n $best ]] || return 0 + sig=${best%/}; sig=${sig##*/} + export HYPRLAND_INSTANCE_SIGNATURE=$sig +} +find_hypr + +input=${OMAMOBILE_KBD_INPUT:-${XDG_CONFIG_HOME:-$HOME/.config}/hypr/input.lua} +rules=${OMAMOBILE_KBD_RULES:-} +if [[ -z $rules ]]; then + for f in /usr/share/X11/xkb/rules/base.lst /usr/share/X11/xkb/rules/evdev.lst; do + [[ -r $f ]] && { rules=$f; break; } + done +fi +binds=${OMAMOBILE_KBD_BINDS:-${XDG_CONFIG_HOME:-$HOME/.config}/hypr/omamobile-keyboard.lua} +export KBD_INPUT=$input KBD_RULES=$rules KBD_BINDS=$binds + +/usr/bin/python3 -I - "$@" <<'PY' || exit 2 +import fcntl, hashlib, json, os, re, shutil, subprocess, sys + +KEYS = ("kb_layout", "kb_variant", "kb_options") +NAME_RE = re.compile(r"[a-z][a-z0-9_-]{0,31}") +# Switch keys as xkb options (see the header). caps takes the key, so compose:caps goes with it. Shift+Caps +# gives real Caps Lock, but 2 of 4 Shift+Caps presses switched the layout instead on the phone (it also +# had shift:both_capslock_cancel): cause unknown. +SWITCH_OPTS = {"alt_shift": ["grp:alt_shift_toggle"], "ctrl_shift": ["grp:ctrl_shift_toggle"], + "caps": ["grp:caps_toggle", "grp_led:caps"], "none": []} +# Compose on Caps Lock: Omarchy 4.0 sets compose:caps, later Omarchy omarchy:shift_caps_compose (Shift+Caps +# is Compose). Both take the Caps key, so a Caps switch key would not switch with either left in. +COMPOSE_OPTS = ("compose:caps", "omarchy:shift_caps_compose") +SWITCH_NAMES = [("alt_shift", "Alt+Shift"), ("ctrl_shift", "Ctrl+Shift"), ("caps", "Caps Lock"), ("none", "None")] +BINDS = os.environ["KBD_BINDS"] +# xkb option names as in base.lst: group:name, the name may hold "-" (compose:caps-altgr, fkeys:basic_13-24) +OPTION_RE = re.compile(r"[a-z0-9_]{1,32}:[A-Za-z0-9_][A-Za-z0-9_-]{0,47}") +LATIN = {"us", "gb", "de", "fr", "es", "it", "pt", "nl", "be", "ch", "at", "se", "no", "dk", "fi", + "is", "ie", "pl", "cz", "sk", "hu", "ro", "hr", "si", "ee", "lv", "lt", "tr", "br", "latam", + "ca", "au", "nz", "za", "epo"} +MAX = 4 +path = os.path.realpath(os.environ["KBD_INPUT"]) # write a symlink's target, keep the link +KEYBOARDS = os.environ.get("OMAMOBILE_KEYBOARDS_DIR", "/usr/share/omamobile/squeekboard/keyboards") +PSEUDO_RE = re.compile(r"hl-virtual-keyboard|.*(consumer-control|power-button|video-bus|radio-control|gpio-keys)") + +def out(obj): + print(json.dumps(obj, separators=(",", ":"))) + +MARKER_NEW = False # True while a marker this run wrote has no input.lua write behind it yet +MARKER_PREV = [] # the marker's options before this run rewrote it + +def fail(msg): + if MARKER_NEW: + # input.lua was not written, so the marker goes back to what it said before this run + if MARKER_PREV: + write_state(MARKER_PREV) + else: + try: + os.unlink(BINDS) + except OSError: + pass + out({"error": msg}) + sys.exit(2) + +# Lua tokens, enough to see live `key = "string"` assignments: comments and long strings are skipped, +# so an assignment inside `-- ...` or `--[[ ... ]]` is invisible (the same rules as the desktop plugin). +def tokens(text): + i, n = 0, len(text) + while i < n: + m = re.compile(r"--\[(=*)\[").match(text, i) + if m: + e = text.find("]" + m.group(1) + "]", m.end()) + i = n if e < 0 else e + len(m.group(1)) + 2 + continue + if text.startswith("--", i): + e = text.find("\n", i) + i = n if e < 0 else e + continue + c = text[i] + if c.isspace(): + i += 1 + continue + if c in "\"'": + m = re.compile(r"(?:\\.|[^\\\n%s])*" % c, re.S).match(text, i + 1) + e = m.end() + closed = e < n and text[e] == c + yield ("string", text[i + 1:e], i, e + 1 if closed else e, not closed) + i = e + 1 if closed else e + continue + m = re.compile(r"\[(=*)\[").match(text, i) + if m: + e = text.find("]" + m.group(1) + "]", m.end()) + stop = n if e < 0 else e + len(m.group(1)) + 2 + yield ("long", "", i, stop, True) + i = stop + continue + m = re.compile(r"[A-Za-z_][A-Za-z0-9_]*").match(text, i) + if m: + yield ("ident", m.group(0), i, m.end(), False) + i = m.end() + continue + if text.startswith("==", i): + yield ("other", "==", i, i + 2, False) + i += 2 + continue + yield ("eq" if c == "=" else "other", c, i, i + 1, False) + i += 1 + +# The last live assignment of each key wins, as a later hl.config() overrides an earlier one. Only +# assignments whose innermost table was opened by `input = {` count: a per-device block or a variable +# with the same key name is not the global setting. +def scan(text): + t = list(tokens(text)) + found, stack = {}, [] + for i, a in enumerate(t): + if a[0] == "other" and a[1] == "{": + stack.append(i >= 2 and t[i - 2][:2] == ("ident", "input") and t[i - 1][0] == "eq") + elif a[0] == "other" and a[1] == "}": + if stack: + stack.pop() + elif (a[0] == "ident" and a[1] in KEYS and stack and stack[-1] and i + 2 < len(t) + and t[i + 1][0] == "eq" and t[i + 2][0] in ("string", "long")): + found[a[1]] = t[i + 2] + return found + +def fields(raw): + return [x.strip() for x in raw.split(",")] if raw.strip() else [] + +def parse(text): + found = scan(text) + vals = {} + for k, tok in found.items(): + if tok[0] == "long" or tok[4]: + fail("input.lua: %s is not a plain string" % k) + if re.search(r"[\x00-\x1f\x7f\\\"]", tok[1]) or len(tok[1]) > 512: + fail("input.lua: %s has characters this editor does not handle" % k) + vals[k] = tok[1] + layouts = fields(vals.get("kb_layout", "")) + variants = fields(vals.get("kb_variant", "")) + variants = (variants + [""] * len(layouts))[:len(layouts)] + options = [o for o in fields(vals.get("kb_options", "")) if o] + return found, layouts, variants, options + +def read_file(): + try: + with open(path, "rb") as f: + data = f.read(1 << 20) + st = os.fstat(f.fileno()) + except FileNotFoundError: + fail("input.lua is missing") + except OSError: + fail("cannot read input.lua") + try: + text = data.decode("utf-8") + except UnicodeDecodeError: + fail("input.lua is not UTF-8") + return data, st, text + +def run(cmd): + try: + r = subprocess.run(cmd, capture_output=True, text=True, timeout=5) + except (OSError, subprocess.TimeoutExpired): + return None + return r.stdout if r.returncode == 0 else None + +def active(): + s = run(["hyprctl", "-j", "devices"]) + try: + kbs = json.loads(s)["keyboards"] + except (TypeError, ValueError, KeyError): + return None + real = [k for k in kbs if not PSEUDO_RE.match(str(k.get("name", "")))] + multi = [k for k in real if len([l for l in str(k.get("layout", "")).split(",") if l]) > 1] + pick = [k for k in real if k.get("main")] or multi or real + if not pick: + return None + i = pick[0].get("active_layout_index") + return i if isinstance(i, int) and i >= 0 else None + +def compose_marked(): + """The Compose options that were in kb_options before caps took the key, from the state file, else []. + A bare "restore" line (written before the Omarchy 4.5 name was known) means compose:caps.""" + names = "|".join(re.escape(o) for o in COMPOSE_OPTS) + try: + with open(BINDS, encoding="utf-8", errors="replace") as f: + for line in f: + m = re.fullmatch(r"-- compose-caps: restore((?: (?:%s))*)\s*" % names, line) + if m: + return m.group(1).split() or ["compose:caps"] + except OSError: + pass + return [] + +def old_key(): + """alt_shift or ctrl_shift from an earlier commit's bind file, else None.""" + try: + with open(BINDS, encoding="utf-8", errors="replace") as f: + for line in f: + m = re.fullmatch(r"-- switch-key: (alt_shift|ctrl_shift)\s*", line) + if m: + return m.group(1) + except OSError: + pass + return None + +def write_state(compose): + """The compose-caps marker for the options in compose on disk, else (compose empty) no state file.""" + if not compose: + try: + os.unlink(BINDS) + except FileNotFoundError: + pass + except OSError: + return False + return True + text = ("-- Written by Omarchy Mobile Settings (Keyboard); nothing loads it. Changes here are replaced.\n" + "-- compose-caps: restore%s\n" % ("" if compose == ["compose:caps"] else " " + " ".join(compose))) + tmp = "%s.tmp-omamobile.%d" % (BINDS, os.getpid()) + try: + os.makedirs(os.path.dirname(BINDS), exist_ok=True) + with open(tmp, "w", encoding="utf-8") as f: + f.write(text) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, BINDS) + except OSError: + try: + os.unlink(tmp) + except OSError: + pass + return False + return True + +def switch_key(options): + """The choice, from kb_options alone; any other grp: option is none.""" + for name in ("alt_shift", "ctrl_shift", "caps"): + if SWITCH_OPTS[name][0] in options: + return name + return "none" + +def switch_options(options, sw): + """kb_options for switch key sw: every grp: and grp_led:caps out, sw's own back in.""" + keep = [o for o in options if not o.startswith("grp:") and o != "grp_led:caps"] + if sw == "caps": + keep = [o for o in keep if o not in COMPOSE_OPTS] + return keep + SWITCH_OPTS[sw] + +def state(layouts, variants, options): + sw = switch_key(options) + if sw == "none" and not any(o.startswith("grp:") for o in options): + sw = old_key() or sw + return {"layouts": [{"layout": l, "variant": v} for l, v in zip(layouts, variants)], + "switchKey": sw, "active": active()} + +def rules(names=None): + lay, var, opt, sec = set(), set(), set(), None + p = os.environ.get("KBD_RULES") or "" + try: + with open(p, encoding="utf-8", errors="replace") as f: + for line in f: + if line.startswith("!"): + sec = line[1:].strip() + continue + w = line.split() + if not w: + continue + if names is not None and sec in ("layout", "option"): + names.append((sec, w[0], " ".join(w[1:]))) + if sec == "layout": + lay.add(w[0]) + elif sec == "variant" and len(w) > 1 and w[1].endswith(":"): + var.add((w[1][:-1], w[0])) + elif sec == "option": + opt.add(w[0]) + except OSError: + fail("cannot read the xkb layout list") + return lay, var, opt + +def write(data, st, text, found, new): + edits = sorted(((found[k][2], found[k][3], v) for k, v in new.items() if k in found), reverse=True) + for s, e, v in edits: + text = text[:s] + '"' + v + '"' + text[e:] + missing = [k for k in KEYS if k in new and k not in found] + if missing and "kb_layout" not in found: + # Omarchy's stock input.lua has its kb_* lines only in comments: add one hl.config() block at the + # end, as the desktop plugin does (InputLua.pl), and leave the commented example as it is. + if text and not text.endswith("\n"): + text += "\n" + text += "\nhl.config({\n input = {\n" + "".join(' %s = "%s",\n' % (k, new[k]) for k in missing) + " },\n})\n" + missing = [] + if missing: + # A missing key goes on its own line right after the live kb_layout, only when that line ends + # with a comma, so it lands in the same `input = { }` table. Anything else is an error. + anchor = scan(text)["kb_layout"] + ls = text.rfind("\n", 0, anchor[2]) + 1 + indent = re.match(r"[ \t]*", text[ls:]).group(0) + le = text.find("\n", anchor[3]) + le = len(text) if le < 0 else le + if re.fullmatch(r"[ \t]*,[ \t]*(--[^\n]*)?", text[anchor[3]:le]): + text = text[:le] + "".join('\n%s%s = "%s",' % (indent, k, new[k]) for k in missing) + text[le:] + else: + # kb_layout = "us" } on one line: the keys go right after the string, in the same table + text = (text[:anchor[3]] + "".join(', %s = "%s"' % (k, new[k]) for k in missing) + + text[anchor[3]:]) + updated = text.encode("utf-8") + if updated == data: + return + bak = path + ".bak-omamobile" + tmp = "%s.tmp-omamobile.%d" % (path, os.getpid()) + try: + shutil.copyfile(path, bak) + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, st.st_mode & 0o777) + with os.fdopen(fd, "wb") as f: + f.write(updated) + f.flush() + os.fsync(f.fileno()) + with open(path, "rb") as f: + now = f.read(1 << 20) + nst = os.fstat(f.fileno()) + if (hashlib.sha256(now).digest() != hashlib.sha256(data).digest() + or (nst.st_ino, nst.st_mtime_ns) != (st.st_ino, st.st_mtime_ns)): + os.unlink(tmp) + fail("input.lua changed while saving, nothing written") + os.replace(tmp, path) + except OSError: + try: + os.unlink(tmp) + except OSError: + pass + fail("cannot write input.lua") + +def lst_names(layouts, variants): + return [l + ("+" + v if v else "") for l, v in zip(layouts, variants)] + +# Merge into the OSK's list (see the header). UNVERIFIED on the phone: that squeekboard keeps its +# current language when the list changes but its first entry does not. +def sync_osk(old, new): + s = run(["gsettings", "get", "org.gnome.desktop.input-sources", "sources"]) + if s is None: + return False + cur = re.findall(r"\(\s*'([^'\\]*)'\s*,\s*'([^'\\]*)'\s*\)", s) + removed = set(old) - set(new) + keep = [(k, n) for k, n in cur if not (k == "xkb" and n in removed)] + have = {n for k, n in keep if k == "xkb"} + carried = os.path.isdir(KEYBOARDS) + add = [("xkb", n) for n in new + if n not in have and (not carried or os.path.isfile(os.path.join(KEYBOARDS, n + ".yaml")))] + merged = keep + add + if merged == cur: + return True + src = ", ".join("('%s', '%s')" % kn for kn in merged) if merged else "" + return run(["gsettings", "set", "org.gnome.desktop.input-sources", "sources", + "[%s]" % src if merged else "@a(ss) []"]) is not None + +# Live apply without `hyprctl reload`. UNVERIFIED on the phone: that Hyprland 0.57 takes +# `hyprctl eval 'hl.config({ input = {...} })'` for the keymap and re-applies it to keyboards already +# connected. The form is the one patch 0006 uses for other options; `hyprctl keyword` is the fallback. +def apply_live(layouts, variants, options): + kv = {"kb_layout": ",".join(layouts), "kb_variant": ",".join(variants) if any(variants) else "", + "kb_options": ",".join(options)} + lua = "hl.config({ input = { %s } })" % ", ".join('%s = "%s"' % (k, kv[k]) for k in KEYS) + r = run(["hyprctl", "eval", lua]) + if r is not None and "error" not in r.lower(): + return True + # One batch, so Hyprland never builds a keymap from new variants with old layouts in between. + # The values hold only names, commas and colons (checked above), never ";" or spaces. + batch = "; ".join("keyword input:%s %s" % (k, kv[k]) for k in ("kb_variant", "kb_options", "kb_layout")) + r = run(["hyprctl", "--batch", batch]) + return r is not None and "error" not in r.lower() + +def effective(key, need): + """Hyprland's value; None when it cannot say (need: fail then, as a save must not guess).""" + s = run(["hyprctl", "-j", "getoption", "input:" + key]) + try: + v = json.loads(s).get("str", "") + except (TypeError, ValueError, AttributeError): + v = None + if not isinstance(v, str): + v = None + if v is None and need: + fail("cannot read Hyprland's input:%s, nothing written" % key) + return v + +def effective_options(need=False): + return [o for o in fields(effective("kb_options", need) or "") if OPTION_RE.fullmatch(o)] + +# No live kb_layout (the stock file): what Hyprland runs with now; get says "us" when it cannot say. +def effective_layouts(need=False): + lay = [l for l in fields(effective("kb_layout", need) or "") if NAME_RE.fullmatch(l)] or ["us"] + var = fields(effective("kb_variant", need) or "") + var = [v if NAME_RE.fullmatch(v) else "" for v in var][:len(lay)] + return lay, var + [""] * (len(lay) - len(var)) + +args = sys.argv[1:] +verb = args[0] if args else "" +if verb == "get": + _, _, text = read_file() + found, layouts, variants, options = parse(text) + if "kb_layout" not in found: + layouts, variants = effective_layouts() + if "kb_options" not in found: + options = effective_options() # as set does, so get and set agree on the switch key + out(state(layouts, variants, options)) + sys.exit(0) +if verb == "list": + names = [] + rules(names) + out({"layouts": [{"layout": n, "name": d} for s, n, d in names if s == "layout" and NAME_RE.fullmatch(n)], + "switchKeys": [{"option": n, "name": d} for n, d in SWITCH_NAMES]}) + sys.exit(0) +if verb != "set": + fail("usage: get|list|set") +key = args[1] if len(args) > 1 else "" +value = args[2] if len(args) > 2 else "" +if key not in ("layouts", "switch-key"): + fail("unknown key") +lay, var, opt = rules() +if key == "layouts": + items = value.split(",") if value else [] + if not 1 <= len(items) <= MAX: + fail("give 1 to 4 layouts") + new_l, new_v = [], [] + for it in items: + l, _, v = it.partition(":") + if not NAME_RE.fullmatch(l) or (v and not NAME_RE.fullmatch(v)): + fail("bad layout name") + if l not in lay or (v and (l, v) not in var): + fail("unknown layout: " + it) + if (l, v) in zip(new_l, new_v): + fail("layout listed twice: " + it) + new_l.append(l); new_v.append(v) + if new_l[0] not in LATIN: + fail("the first layout must be a Latin one (passwords on the lock screen are typed in it)") +else: + if value not in SWITCH_OPTS: + fail("unknown switch key") + +lockpath = path + ".lock-omamobile" +try: + lockf = open(lockpath, "a") + fcntl.flock(lockf, fcntl.LOCK_EX) +except OSError: + fail("cannot lock input.lua") +data, st, text = read_file() +found, layouts, variants, options = parse(text) +if "kb_layout" not in found: + layouts, variants = effective_layouts(True) +old_names = lst_names(layouts, variants) +if "kb_options" not in found: + options = effective_options(True) # keep Omarchy's defaults when input.lua does not set kb_options +old_options = options +compose = None # None: the state file is left as it is (a layouts save) +if key == "layouts": + layouts, variants = new_l, new_v + migrate = old_key() + if migrate and not any(o.startswith("grp:") for o in options): + options = switch_options(options, migrate) # the earlier bind file's choice, now as xkb + compose = False +else: + sw = value + # compose:caps goes while caps holds the key; the marker brings it back when caps lets go, and only then + was_caps = "grp:caps_toggle" in options + marked = compose_marked() + # every Compose option on Caps that is in kb_options now, or that the marker says was there before caps + keep = (marked if was_caps else []) + [o for o in options if o in COMPOSE_OPTS] + compose = [o for o in COMPOSE_OPTS if o in keep] if sw == "caps" else [] + options = switch_options(options, sw) + if sw != "caps" and was_caps: + options = options + [o for o in marked if o not in options] + # The marker goes to disk before input.lua loses compose:caps, so a failed write in between can't + # lose it (harmless while caps is not on); leaving caps, input.lua gets compose:caps back first, + # then the marker goes. + if compose and compose != marked: + MARKER_PREV = marked if was_caps else [] + if not write_state(compose): + fail("cannot write " + os.path.basename(BINDS)) + MARKER_NEW = True +live_ok = osk_ok = True +if key == "layouts" or options != old_options: + new = {"kb_layout": ",".join(layouts), "kb_options": ",".join(options)} + if "kb_options" not in found and not options: + del new["kb_options"] + if any(variants) or "kb_variant" in found: + new["kb_variant"] = ",".join(variants) if any(variants) else "" + write(data, st, text, found, new) + MARKER_NEW = False + osk_ok = key != "layouts" or sync_osk(old_names, lst_names(layouts, variants)) + live_ok = apply_live(layouts, variants, options) +if compose is not None and not write_state(compose): + fail("cannot write " + os.path.basename(BINDS)) +if not live_ok: + fail("saved, but Hyprland did not take it live" + + ("" if osk_ok else ", and the on-screen keyboard list was not updated")) +if not osk_ok: + fail("saved and applied, but the on-screen keyboard list was not updated") +out(state(layouts, variants, options)) +PY diff --git a/packages/omamobile-settings/install b/packages/omamobile-settings/install index 2963f0a8b..2499bbcb4 100755 --- a/packages/omamobile-settings/install +++ b/packages/omamobile-settings/install @@ -11,3 +11,4 @@ install -Dm644 "$source_dir/org.omamobile.Settings.desktop" "$dest/usr/share/app install -Dm644 "$source_dir/org.omamobile.Settings.svg" "$dest/usr/share/icons/hicolor/scalable/apps/org.omamobile.Settings.svg" install -Dm644 "$source_dir/LICENSE" "$dest/usr/share/licenses/omamobile-settings/LICENSE" install -Dm755 "$source_dir/backends/display.sh" "$dest/usr/lib/omamobile-settings/backends/display.sh" +install -Dm755 "$source_dir/backends/keyboard.sh" "$dest/usr/lib/omamobile-settings/backends/keyboard.sh" diff --git a/packages/omamobile-settings/test/all b/packages/omamobile-settings/test/all index d0c6618eb..fdec653a7 100755 --- a/packages/omamobile-settings/test/all +++ b/packages/omamobile-settings/test/all @@ -5,6 +5,12 @@ source_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) build_dir=${OMAMOBILE_SETTINGS_TEST_BUILD_DIR:-"$source_dir/build/tests"} "$source_dir/bin/build" "$source_dir/test/display-backend.sh" +"$source_dir/test/keyboard-backend.sh" +# Adding a layout is a search: matches show only once something is typed, never the whole list +grep -qF 'model: filter.visible && filter.text.trim() !== "" ? page.available.filter(' "$source_dir/app/KeyboardPage.qml" || { echo "FAIL: layout picker lists everything" >&2; exit 1; } +# The page stops a non-Latin first layout before sending it, and reads the state again after a failed set +grep -qF 'if (!list.length || !isLatin(list[0])) {' "$source_dir/app/KeyboardPage.qml" || { echo "FAIL: page sends a non-Latin first layout" >&2; exit 1; } +grep -qF 'lastError = r.error; status = r.error; busy = true; reqId = actions.run("keyboard", ["get"])' "$source_dir/app/KeyboardPage.qml" || { echo "FAIL: page keeps a stale list after an error" >&2; exit 1; } mkdir -p "$build_dir" fixture=$(mktemp -d) trap 'rm -rf -- "$fixture"' EXIT HUP INT TERM diff --git a/packages/omamobile-settings/test/keyboard-backend.sh b/packages/omamobile-settings/test/keyboard-backend.sh new file mode 100755 index 000000000..44ac59d07 --- /dev/null +++ b/packages/omamobile-settings/test/keyboard-backend.sh @@ -0,0 +1,388 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# backends/keyboard.sh against fake input.lua files, a small xkb rules list and a fake hyprctl and gsettings +# first on PATH that log their arguments. The host's own files and tools are never touched. +set -euo pipefail +src=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +tmp=$(mktemp -d); trap 'rm -rf -- "$tmp"' EXIT +mkdir -p "$tmp/bin" "$tmp/run" +cat > "$tmp/bin/hyprctl" <<'EOT' +#!/bin/bash +printf '%s\n' "$*" >> "$FAKE_LOG" +case "$1 $2" in + "-j devices") cat "$FAKE_DEVICES" 2>/dev/null || exit 1 ;; + "-j getoption") [[ -z ${FAKE_GETOPTION_FAIL:-} ]] || exit 1 + case $3 in + input:kb_options) printf '{"option":"input:kb_options","str":"%s","set":true}\n' "${FAKE_OPTIONS:-}" ;; + input:kb_layout) printf '{"option":"input:kb_layout","str":"%s","set":true}\n' "${FAKE_LAYOUT:-us}" ;; + *) printf '{"option":"%s","str":"","set":false}\n' "$3" ;; + esac ;; + eval*) [[ -n ${FAKE_EVAL_FAIL:-} ]] && echo "error: no eval" || echo ok ;; + --batch*) [[ -n ${FAKE_KEYWORD_FAIL:-} ]] && echo "error: bad" || echo ok ;; +esac +EOT +cat > "$tmp/bin/gsettings" <<'EOT' +#!/bin/bash +printf 'gsettings %s\n' "$*" >> "$FAKE_LOG" +[[ -z ${FAKE_GSETTINGS_FAIL:-} ]] || exit 1 +case $1 in + get) cat "$FAKE_SOURCES" 2>/dev/null || echo "@a(ss) []" ;; + set) printf '%s\n' "$4" > "$FAKE_SOURCES" ;; +esac +EOT +chmod +x "$tmp/bin/hyprctl" "$tmp/bin/gsettings" +cat > "$tmp/rules.lst" <<'EOT' +! layout + us English (US) + gr Greek + de German + ru Russian + +! variant + polytonic gr: Greek (polytonic) + intl us: English (US, intl., with dead keys) + +! option + grp Switching to another layout + grp:alt_shift_toggle Alt+Shift + grp:caps_toggle Caps Lock + grp_led:caps Caps Lock +EOT +cat > "$tmp/devices.json" <<'EOT' +{"keyboards":[{"name":"hl-virtual-keyboard-squeekboard","active_layout_index":0,"main":false}, +{"name":"dell-kb7120w","active_layout_index":1,"main":true}]} +EOT +export PATH="$tmp/bin:$PATH" FAKE_LOG="$tmp/log" FAKE_DEVICES="$tmp/devices.json" FAKE_SOURCES="$tmp/sources" +export OMAMOBILE_KEYBOARDS_DIR="$tmp/nokeyboards" +export XDG_RUNTIME_DIR="$tmp/run" HYPRLAND_INSTANCE_SIGNATURE=test +export OMAMOBILE_KBD_INPUT="$tmp/input.lua" OMAMOBILE_KBD_RULES="$tmp/rules.lst" OMAMOBILE_KBD_BINDS="$tmp/omamobile-keyboard.lua" +unset FAKE_OPTIONS FAKE_GETOPTION_FAIL FAKE_EVAL_FAIL FAKE_KEYWORD_FAIL FAKE_GSETTINGS_FAIL +run() { bash "$src/backends/keyboard.sh" "$@" || true; } +eq() { [[ $1 == "$2" ]] || { echo "FAIL: got $1, want $2" >&2; exit 1; }; } +has() { grep -qF -- "$2" "$1" || { echo "FAIL: $1 lacks $2" >&2; cat "$1" >&2; exit 1; }; } +hasnt() { ! grep -qF -- "$2" "$1" || { echo "FAIL: $1 has $2" >&2; exit 1; }; } + +# Omarchy-style file: comments, an earlier overridden block, grp_led:caps and another option +cat > "$tmp/input.lua" <<'EOT' +-- kb_layout = "fr", a comment, never touched +hl.config({ input = { kb_layout = "de" } }) +--[[ kb_layout = "ru", + kb_options = "grp:caps_toggle" ]] +hl.config({ + input = { + kb_layout = "us", + kb_options = "compose:caps,grp:win_space_toggle,grp_led:caps", -- keep me + repeat_rate = 40, + }, +}) +EOT +chmod 640 "$tmp/input.lua" +# a grp: option that is none of ours: get says none +eq "$(run get)" '{"layouts":[{"layout":"us","variant":""}],"switchKey":"none","active":1}' + +: > "$tmp/log" +eq "$(run set layouts us,gr:polytonic)" '{"layouts":[{"layout":"us","variant":""},{"layout":"gr","variant":"polytonic"}],"switchKey":"none","active":1}' +has "$tmp/input.lua" 'kb_layout = "us,gr",' +has "$tmp/input.lua" 'kb_variant = ",polytonic",' +# a layouts save leaves kb_options as it is, writes no state file and binds nothing +has "$tmp/input.lua" 'kb_options = "compose:caps,grp:win_space_toggle,grp_led:caps", -- keep me' +b=$tmp/omamobile-keyboard.lua +[[ ! -e $b ]] || { echo "FAIL: a layouts save wrote the state file" >&2; exit 1; } +hasnt "$tmp/log" 'hl.bind' +hasnt "$tmp/log" 'unbind' +has "$tmp/input.lua" '-- kb_layout = "fr", a comment, never touched' +has "$tmp/input.lua" 'hl.config({ input = { kb_layout = "de" } })' +has "$tmp/input.lua" ' kb_options = "grp:caps_toggle" ]]' +eq "$(grep -c 'hl.config' "$tmp/input.lua")" 2 +eq "$(stat -c %a "$tmp/input.lua")" 640 +has "$tmp/input.lua.bak-omamobile" 'kb_layout = "us",' +has "$tmp/log" 'eval hl.config({ input = { kb_layout = "us,gr", kb_variant = ",polytonic", kb_options = "compose:caps,grp:win_space_toggle,grp_led:caps" } })' +has "$tmp/log" "gsettings set org.gnome.desktop.input-sources sources [('xkb', 'us'), ('xkb', 'gr+polytonic')]" +# gsettings is written before the live apply +g=$(grep -n '^gsettings set' "$tmp/log" | cut -d: -f1); e=$(grep -n '^eval' "$tmp/log" | head -1 | cut -d: -f1) +(( g < e )) || { echo "FAIL: gsettings ($g) after the live apply ($e)" >&2; exit 1; } +hasnt "$tmp/log" 'reload' + +# the switch key is an xkb option: every grp: and grp_led:caps go, the chosen one comes, applied +# live; gsettings is not touched and no bind is made +: > "$tmp/log" +eq "$(run set switch-key alt_shift)" '{"layouts":[{"layout":"us","variant":""},{"layout":"gr","variant":"polytonic"}],"switchKey":"alt_shift","active":1}' +has "$tmp/input.lua" 'kb_options = "compose:caps,grp:alt_shift_toggle", -- keep me' +has "$tmp/log" 'kb_options = "compose:caps,grp:alt_shift_toggle" } })' +eq "$(run get)" '{"layouts":[{"layout":"us","variant":""},{"layout":"gr","variant":"polytonic"}],"switchKey":"alt_shift","active":1}' +eq "$(run set switch-key ctrl_shift | grep -o '"switchKey":"[^"]*"')" '"switchKey":"ctrl_shift"' +has "$tmp/input.lua" 'kb_options = "compose:caps,grp:ctrl_shift_toggle", -- keep me' +hasnt "$tmp/log" 'hl.bind' +hasnt "$tmp/log" 'unbind' +hasnt "$tmp/log" 'gsettings' +[[ ! -e $b ]] || { echo "FAIL: a state file without caps" >&2; exit 1; } +# caps: grp:caps_toggle + grp_led:caps, compose:caps goes (it takes the key) +: > "$tmp/log" +eq "$(run set switch-key caps | grep -o '"switchKey":"[^"]*"')" '"switchKey":"caps"' +has "$tmp/input.lua" 'kb_options = "grp:caps_toggle,grp_led:caps", -- keep me' +has "$tmp/log" 'kb_options = "grp:caps_toggle,grp_led:caps" } })' +hasnt "$tmp/log" 'gsettings' +eq "$(run get | grep -o '"switchKey":"[^"]*"')" '"switchKey":"caps"' +# a layouts change keeps caps and the marker +eq "$(run set layouts us,gr:polytonic | grep -o '"switchKey":"[^"]*"')" '"switchKey":"caps"' +has "$tmp/input.lua" 'kb_options = "grp:caps_toggle,grp_led:caps", -- keep me' +has "$b" '-- compose-caps: restore' +hasnt "$b" 'hl.' +# away from caps to none: both options go, no grp: at all, compose:caps (there before caps) comes back +eq "$(run set switch-key none | grep -o '"switchKey":"[^"]*"')" '"switchKey":"none"' +has "$tmp/input.lua" 'kb_options = "compose:caps", -- keep me' +[[ ! -e $b ]] || { echo "FAIL: the marker stayed after caps" >&2; exit 1; } +# caps then alt_shift restores compose:caps too +run set switch-key caps >/dev/null +has "$tmp/input.lua" 'kb_options = "grp:caps_toggle,grp_led:caps", -- keep me' +run set switch-key alt_shift >/dev/null +has "$tmp/input.lua" 'kb_options = "grp:alt_shift_toggle,compose:caps", -- keep me' +[[ ! -e $b ]] || { echo "FAIL: the marker stayed after caps" >&2; exit 1; } +# a user without compose:caps never gets it +sed -i 's/kb_options = "grp:alt_shift_toggle,compose:caps", -- keep me/kb_options = "", -- keep me/' "$tmp/input.lua" +run set switch-key caps >/dev/null +[[ ! -e $b ]] || { echo "FAIL: a marker without compose:caps" >&2; exit 1; } +run set switch-key ctrl_shift >/dev/null +has "$tmp/input.lua" 'kb_options = "grp:ctrl_shift_toggle", -- keep me' +# Omarchy 4.5's omarchy:shift_caps_compose takes Caps Lock too: it goes with caps and comes back after +sed -i 's/kb_options = "grp:ctrl_shift_toggle", -- keep me/kb_options = "omarchy:shift_caps_compose", -- keep me/' "$tmp/input.lua" +run set switch-key caps >/dev/null +has "$tmp/input.lua" 'kb_options = "grp:caps_toggle,grp_led:caps", -- keep me' +has "$b" '-- compose-caps: restore omarchy:shift_caps_compose' +run set layouts us,gr >/dev/null +has "$b" '-- compose-caps: restore omarchy:shift_caps_compose' +run set switch-key alt_shift >/dev/null +has "$tmp/input.lua" 'kb_options = "grp:alt_shift_toggle,omarchy:shift_caps_compose", -- keep me' +[[ ! -e $b ]] || { echo "FAIL: the marker stayed after caps" >&2; exit 1; } +# both Compose options at once: both go with caps, the marker names both, both come back +sed -i 's/kb_options = "grp:alt_shift_toggle,omarchy:shift_caps_compose", -- keep me/kb_options = "compose:caps,omarchy:shift_caps_compose", -- keep me/' "$tmp/input.lua" +run set switch-key caps >/dev/null +has "$tmp/input.lua" 'kb_options = "grp:caps_toggle,grp_led:caps", -- keep me' +has "$b" '-- compose-caps: restore compose:caps omarchy:shift_caps_compose' +run set switch-key none >/dev/null +has "$tmp/input.lua" 'kb_options = "compose:caps,omarchy:shift_caps_compose", -- keep me' +[[ ! -e $b ]] || { echo "FAIL: the marker stayed after caps" >&2; exit 1; } +# a Compose option added by hand while caps is on joins the marker, the earlier one stays in it +sed -i 's/kb_options = "compose:caps,omarchy:shift_caps_compose", -- keep me/kb_options = "compose:caps", -- keep me/' "$tmp/input.lua" +run set switch-key caps >/dev/null +has "$b" '-- compose-caps: restore' +hasnt "$b" 'omarchy:' +sed -i 's/kb_options = "grp:caps_toggle,grp_led:caps", -- keep me/kb_options = "grp:caps_toggle,grp_led:caps,omarchy:shift_caps_compose", -- keep me/' "$tmp/input.lua" +run set switch-key caps >/dev/null +has "$b" '-- compose-caps: restore compose:caps omarchy:shift_caps_compose' +run set switch-key alt_shift >/dev/null +has "$tmp/input.lua" 'kb_options = "grp:alt_shift_toggle,compose:caps,omarchy:shift_caps_compose", -- keep me' +sed -i 's/kb_options = "grp:alt_shift_toggle,compose:caps,omarchy:shift_caps_compose", -- keep me/kb_options = "grp:ctrl_shift_toggle", -- keep me/' "$tmp/input.lua" +run set switch-key alt_shift >/dev/null +# one layout left: the option stays (xkb has nowhere to switch then); the variant goes +eq "$(run set layouts us)" '{"layouts":[{"layout":"us","variant":""}],"switchKey":"alt_shift","active":1}' +has "$tmp/input.lua" 'kb_options = "grp:alt_shift_toggle",' +has "$tmp/input.lua" 'kb_variant = "",' + + +# a non-Latin first layout is refused, nothing written +cp "$tmp/input.lua" "$tmp/before"; cp "$tmp/sources" "$tmp/sources.before" +eq "$(run set layouts gr,us)" '{"error":"the first layout must be a Latin one (passwords on the lock screen are typed in it)"}' +eq "$(run set layouts gr)" '{"error":"the first layout must be a Latin one (passwords on the lock screen are typed in it)"}' +cmp -s "$tmp/input.lua" "$tmp/before" && cmp -s "$tmp/sources" "$tmp/sources.before" || { echo "FAIL: a refused set wrote" >&2; exit 1; } +eq "$(run set layouts us,gr | grep -c warn || true)" 0 + +# OSK merge: the OSK's own languages and its current (first) entry stay, new ones are added, +# removed hardware layouts are dropped; only names squeekboard has a file for, when the dir exists +echo "[('xkb', 'gr'), ('xkb', 'fr'), ('ibus', 'x')]" > "$tmp/sources" +mkdir -p "$tmp/kbds"; touch "$tmp/kbds/us.yaml" "$tmp/kbds/gr.yaml" +OMAMOBILE_KEYBOARDS_DIR=$tmp/kbds run set layouts us,gr,de >/dev/null +eq "$(cat "$tmp/sources")" "[('xkb', 'gr'), ('xkb', 'fr'), ('ibus', 'x'), ('xkb', 'us')]" +run set layouts us,de >/dev/null +eq "$(cat "$tmp/sources")" "[('xkb', 'fr'), ('ibus', 'x'), ('xkb', 'us'), ('xkb', 'de')]" +: > "$tmp/log"; run set layouts us,de >/dev/null +hasnt "$tmp/log" 'gsettings set' +run set layouts us,gr >/dev/null + +# per-device blocks and variables named kb_layout are not the global setting +cat > "$tmp/input.lua" <<'EOT' +local kb_layout = "ru" +hl.config({ + input = { + kb_layout = "us", + kb_options = "compose:caps", + touchpad = { kb_layout = "fr" }, + }, +}) +hl.device({ name = "x", kb_layout = "de" }) +EOT +eq "$(run get | grep -o '"layouts":[^]]*]')" '"layouts":[{"layout":"us","variant":""}]' +run set layouts us,gr >/dev/null +has "$tmp/input.lua" ' kb_layout = "us,gr",' +has "$tmp/input.lua" 'local kb_layout = "ru"' +has "$tmp/input.lua" 'touchpad = { kb_layout = "fr" },' +has "$tmp/input.lua" 'hl.device({ name = "x", kb_layout = "de" })' + +# a symlinked input.lua stays a link, its target is written +mkdir -p "$tmp/dots"; mv "$tmp/input.lua" "$tmp/dots/input.lua"; ln -s "$tmp/dots/input.lua" "$tmp/input.lua" +run set layouts us,de >/dev/null +[[ -L $tmp/input.lua ]] || { echo "FAIL: the symlink was replaced" >&2; exit 1; } +has "$tmp/dots/input.lua" ' kb_layout = "us,de",' +rm "$tmp/input.lua"; mv "$tmp/dots/input.lua" "$tmp/input.lua" + +# an effective grp: option (input.lua has no kb_options) is replaced by a switch-key change too +printf 'hl.config({\n input = {\n kb_layout = "us,gr",\n },\n})\n' > "$tmp/input.lua" +FAKE_OPTIONS=compose:caps,grp:alts_toggle run set switch-key ctrl_shift >/dev/null +has "$tmp/input.lua" ' kb_options = "compose:caps,grp:ctrl_shift_toggle",' +printf 'hl.config({\n input = {\n kb_layout = "us,gr",\n },\n})\n' > "$tmp/input.lua" +# get reads the effective kb_options when input.lua has none +eq "$(FAKE_OPTIONS=grp:caps_toggle,grp_led:caps run get | grep -o '"switchKey":"[^"]*"')" '"switchKey":"caps"' +eq "$(FAKE_OPTIONS=compose:caps,grp:alt_shift_toggle run get | grep -o '"switchKey":"[^"]*"')" '"switchKey":"alt_shift"' +eq "$(FAKE_OPTIONS=grp:ctrl_shift_toggle run get | grep -o '"switchKey":"[^"]*"')" '"switchKey":"ctrl_shift"' +eq "$(FAKE_OPTIONS=compose:caps run get | grep -o '"switchKey":"[^"]*"')" '"switchKey":"none"' +# xkb option names with "-" (base.lst has compose:caps-altgr, fkeys:basic_13-24) are kept +FAKE_OPTIONS=compose:caps-altgr,fkeys:basic_13-24 run set switch-key alt_shift >/dev/null +has "$tmp/input.lua" ' kb_options = "compose:caps-altgr,fkeys:basic_13-24,grp:alt_shift_toggle",' +printf 'hl.config({\n input = {\n kb_layout = "us,gr",\n },\n})\n' > "$tmp/input.lua" +# Hyprland cannot say its kb_options / kb_layout: a save writes nothing rather than guess +cp "$tmp/input.lua" "$tmp/before" +eq "$(FAKE_GETOPTION_FAIL=1 run set switch-key alt_shift)" '{"error":"cannot read Hyprland'"'"'s input:kb_options, nothing written"}' +eq "$(FAKE_GETOPTION_FAIL=1 run set layouts us,de)" '{"error":"cannot read Hyprland'"'"'s input:kb_options, nothing written"}' +cmp -s "$tmp/input.lua" "$tmp/before" || { echo "FAIL: a save without Hyprland's values wrote" >&2; exit 1; } +printf 'hl.config({\n input = {\n repeat_rate = 40,\n },\n})\n' > "$tmp/before"; cp "$tmp/before" "$tmp/input.lua" +eq "$(FAKE_GETOPTION_FAIL=1 run set switch-key caps)" '{"error":"cannot read Hyprland'"'"'s input:kb_layout, nothing written"}' +cmp -s "$tmp/input.lua" "$tmp/before" || { echo "FAIL: a save without Hyprland's layout wrote" >&2; exit 1; } +[[ ! -e $b ]] || { echo "FAIL: a refused save wrote the marker" >&2; exit 1; } +# a live kb_options and kb_layout need no getoption +printf 'hl.config({\n input = {\n kb_layout = "us,gr",\n kb_options = "compose:caps",\n },\n})\n' > "$tmp/input.lua" +eq "$(FAKE_GETOPTION_FAIL=1 run set switch-key ctrl_shift | grep -o '"switchKey":"[^"]*"')" '"switchKey":"ctrl_shift"' +# migration: a bind file from earlier commits of this branch, no grp: option. get reports its choice, +# the next save writes the matching xkb option and removes the file +printf 'hl.config({\n input = {\n kb_layout = "us,gr",\n kb_options = "compose:caps",\n },\n})\n' > "$tmp/input.lua" +printf -- '-- switch-key: ctrl_shift\nhl.bind("CTRL + SHIFT_L")\n' > "$b" +eq "$(run get | grep -o '"switchKey":"[^"]*"')" '"switchKey":"ctrl_shift"' +eq "$(run set layouts us,gr | grep -o '"switchKey":"[^"]*"')" '"switchKey":"ctrl_shift"' +has "$tmp/input.lua" ' kb_options = "compose:caps,grp:ctrl_shift_toggle",' +[[ ! -e $b ]] || { echo "FAIL: the old bind file stayed after migrating" >&2; exit 1; } +# with a grp: option already there, the old file is not the truth; a switch-key save removes it +printf -- '-- switch-key: alt_shift\nhl.bind("ALT + SHIFT_L")\n' > "$b" +eq "$(FAKE_OPTIONS=grp:alts_toggle run get | grep -o '"switchKey":"[^"]*"')" '"switchKey":"ctrl_shift"' +sed -i 's/grp:ctrl_shift_toggle/grp:alts_toggle/' "$tmp/input.lua" +eq "$(run get | grep -o '"switchKey":"[^"]*"')" '"switchKey":"none"' +run set layouts us,gr >/dev/null +has "$tmp/input.lua" ' kb_options = "compose:caps,grp:alts_toggle",' +has "$b" 'switch-key: alt_shift' +run set switch-key none >/dev/null +[[ ! -e $b ]] || { echo "FAIL: the old bind file stayed" >&2; exit 1; } +# a switch-key save picks over an old file's choice +printf -- '-- switch-key: alt_shift\n' > "$b" +sed -i 's/kb_options = "[^"]*"/kb_options = ""/' "$tmp/input.lua" +eq "$(run set switch-key caps | grep -o '"switchKey":"[^"]*"')" '"switchKey":"caps"' +has "$tmp/input.lua" ' kb_options = "grp:caps_toggle,grp_led:caps",' +[[ ! -e $b ]] || { echo "FAIL: the old bind file stayed" >&2; exit 1; } +run set switch-key none >/dev/null +# input.lua cannot be written (its directory is read-only) while caps takes compose:caps: the error is +# reported, input.lua is unchanged and the marker written for it is removed again (none is left stale) +mkdir -p "$tmp/ro" +printf 'hl.config({\n input = {\n kb_layout = "us,gr",\n kb_options = "compose:caps,grp:ctrl_shift_toggle",\n },\n})\n' > "$tmp/ro/input.lua" +touch "$tmp/ro/input.lua.lock-omamobile"; chmod 555 "$tmp/ro" # the lock opens, the backup copy cannot be made +eq "$(OMAMOBILE_KBD_INPUT=$tmp/ro/input.lua run set switch-key caps)" '{"error":"cannot write input.lua"}' +chmod 755 "$tmp/ro" +has "$tmp/ro/input.lua" ' kb_options = "compose:caps,grp:ctrl_shift_toggle",' +[[ ! -e $tmp/ro/input.lua.bak-omamobile ]] || { echo "FAIL: the write got further than expected" >&2; exit 1; } +[[ ! -e $b ]] || { echo "FAIL: a stale compose marker after a failed write" >&2; exit 1; } +# the marker goes to disk before input.lua loses compose:caps: when it cannot be written, input.lua is +# not touched +mv "$b" "$b.x" 2>/dev/null || true; mkdir "$b" # a directory where the state file goes: it cannot be written +eq "$(OMAMOBILE_KBD_INPUT=$tmp/ro/input.lua run set switch-key caps)" '{"error":"cannot write omamobile-keyboard.lua"}' +has "$tmp/ro/input.lua" ' kb_options = "compose:caps,grp:ctrl_shift_toggle",' +rmdir "$b"; rm -f "$b.x" +# the retry goes through and later leaving caps brings compose:caps back +export OMAMOBILE_KBD_INPUT=$tmp/ro/input.lua +run set switch-key caps >/dev/null +has "$tmp/ro/input.lua" 'kb_options = "grp:caps_toggle,grp_led:caps",' +has "$b" '-- compose-caps: restore' +run set switch-key alt_shift >/dev/null +has "$tmp/ro/input.lua" 'kb_options = "grp:alt_shift_toggle,compose:caps",' +[[ ! -e $b ]] || { echo "FAIL: the marker stayed" >&2; exit 1; } +export OMAMOBILE_KBD_INPUT=$tmp/input.lua +mv "$tmp/ro/input.lua" "$tmp/input.lua" + + +# bad input never reaches the file +cp "$tmp/input.lua" "$tmp/before" +eq "$(run set layouts us,gr,de,ru,us:intl)" '{"error":"give 1 to 4 layouts"}' +eq "$(run set layouts us,xx)" '{"error":"unknown layout: xx"}' +eq "$(run set layouts us,gr:intl)" '{"error":"unknown layout: gr:intl"}' +eq "$(run set layouts 'us,gr"')" '{"error":"bad layout name"}' +eq "$(run set layouts us,us)" '{"error":"layout listed twice: us"}' +eq "$(run set layouts '')" '{"error":"give 1 to 4 layouts"}' +eq "$(run set switch-key grp:alt_shift_toggle)" '{"error":"unknown switch key"}' +eq "$(run set switch-key 'caps"')" '{"error":"unknown switch key"}' +eq "$(run set numlock on)" '{"error":"unknown key"}' +eq "$(run nonsense)" '{"error":"usage: get|list|set"}' +cmp -s "$tmp/input.lua" "$tmp/before" || { echo "FAIL: a rejected set changed input.lua" >&2; exit 1; } + +# Omarchy's stock file: kb_* only in comments. get reports Hyprland's effective values; set appends +# one hl.config() block and leaves the commented example alone (the phone's file, 0.57, 2026-11-17) +cat > "$tmp/input.lua" <<'EOT' +hl.config({ + input = { + -- Use multiple keyboard layouts and switch between them with Left Alt + Right Alt + -- kb_layout = "us,dk,eu", + -- kb_options = "compose:caps,grp:alts_toggle", + repeat_rate = 40, + }, +}) +EOT +FAKE_OPTIONS="compose:caps,shift:both_capslock_cancel" +export FAKE_OPTIONS +eq "$(run get)" '{"layouts":[{"layout":"us","variant":""}],"switchKey":"none","active":1}' +run set layouts us,gr >/dev/null +has "$tmp/input.lua" '-- kb_layout = "us,dk,eu",' +has "$tmp/input.lua" ' kb_layout = "us,gr",' +has "$tmp/input.lua" ' kb_options = "compose:caps,shift:both_capslock_cancel",' +eq "$(run get)" '{"layouts":[{"layout":"us","variant":""},{"layout":"gr","variant":""}],"switchKey":"none","active":1}' +eq "$(grep -c 'hl.config' "$tmp/input.lua")" 2 +run set layouts us,de >/dev/null +eq "$(grep -c 'hl.config' "$tmp/input.lua")" 2 +has "$tmp/input.lua" ' kb_layout = "us,de",' +unset FAKE_OPTIONS +rm "$tmp/input.lua" +eq "$(run get)" '{"error":"input.lua is missing"}' + +# kb_options and kb_variant absent: added on the kb_layout line's table, Omarchy's effective options kept +printf 'hl.config({\n input = {\n kb_layout = "us",\n },\n})\n' > "$tmp/input.lua" +FAKE_OPTIONS='compose:caps' eq "$(FAKE_OPTIONS=compose:caps run set layouts us,gr:polytonic | grep -o '"switchKey":"[^"]*"')" '"switchKey":"none"' +has "$tmp/input.lua" ' kb_layout = "us,gr",' +has "$tmp/input.lua" ' kb_variant = ",polytonic",' +has "$tmp/input.lua" ' kb_options = "compose:caps",' +eq "$(grep -c 'hl.config' "$tmp/input.lua")" 1 +# a one-line kb_layout with no comma after it: the keys go right after its string +printf 'hl.config({ input = { kb_layout = "us" } })\n' > "$tmp/input.lua" +eq "$(run set layouts us,gr:polytonic)" '{"layouts":[{"layout":"us","variant":""},{"layout":"gr","variant":"polytonic"}],"switchKey":"none","active":1}' +has "$tmp/input.lua" 'hl.config({ input = { kb_layout = "us,gr", kb_variant = ",polytonic" } })' +printf 'hl.config({ input = { kb_layout = "us,gr" } })\n' > "$tmp/input.lua" +eq "$(FAKE_OPTIONS=compose:caps run set switch-key caps | grep -o '"switchKey":"[^"]*"')" '"switchKey":"caps"' +has "$tmp/input.lua" 'hl.config({ input = { kb_layout = "us,gr", kb_options = "grp:caps_toggle,grp_led:caps" } })' +has "$b" '-- compose-caps: restore' +eq "$(run set switch-key none | grep -o '"switchKey":"[^"]*"')" '"switchKey":"none"' +has "$tmp/input.lua" 'kb_options = "compose:caps"' +[[ ! -e $b ]] || { echo "FAIL: the marker stayed" >&2; exit 1; } +printf 'hl.config({ input = { kb_layout = "us" } })\n' > "$tmp/input.lua" +eq "$(run set layouts us,gr)" '{"layouts":[{"layout":"us","variant":""},{"layout":"gr","variant":""}],"switchKey":"none","active":1}' +# a value this editor does not handle is refused +printf 'hl.config({ input = { kb_layout = [[us]], } })\n' > "$tmp/input.lua" +eq "$(run get)" '{"error":"input.lua: kb_layout is not a plain string"}' + +# eval refused: the keyword fallback; both refused: says which half failed +printf 'hl.config({ input = {\n kb_layout = "us",\n kb_options = "compose:caps",\n} })\n' > "$tmp/input.lua" +: > "$tmp/log" +FAKE_EVAL_FAIL=1 run set layouts us,gr >/dev/null +has "$tmp/log" '--batch keyword input:kb_variant ; keyword input:kb_options compose:caps; keyword input:kb_layout us,gr' +eq "$(FAKE_EVAL_FAIL=1 FAKE_KEYWORD_FAIL=1 run set layouts us,de)" '{"error":"saved, but Hyprland did not take it live"}' +has "$tmp/input.lua" 'kb_layout = "us,de",' +eq "$(FAKE_GSETTINGS_FAIL=1 run set layouts us,gr)" '{"error":"saved and applied, but the on-screen keyboard list was not updated"}' +# no Hyprland: active is null +FAKE_DEVICES=$tmp/none eq "$(FAKE_DEVICES=$tmp/none run get)" '{"layouts":[{"layout":"us","variant":""},{"layout":"gr","variant":""}],"switchKey":"none","active":null}' +# list: layouts and grp: switch keys from the rules file, other options left out +eq "$(run list)" '{"layouts":[{"layout":"us","name":"English (US)"},{"layout":"gr","name":"Greek"},{"layout":"de","name":"German"},{"layout":"ru","name":"Russian"}],"switchKeys":[{"option":"alt_shift","name":"Alt+Shift"},{"option":"ctrl_shift","name":"Ctrl+Shift"},{"option":"caps","name":"Caps Lock"},{"option":"none","name":"None"}]}' +# phone.lua binds no switch key and loads no Settings file +for k in "switchxkblayout" "omamobile-keyboard-switch" "omamobile-keyboard.lua" "SHIFT_L" "ALT_L" "CTRL_L" "code:66"; do hasnt "$src/../omamobile-shell/hypr/phone.lua" "$k"; done + +echo "keyboard backend: ok" diff --git a/packages/omamobile-settings/tests/core_tests.cpp b/packages/omamobile-settings/tests/core_tests.cpp index e8e0a2e77..b5e2f68df 100644 --- a/packages/omamobile-settings/tests/core_tests.cpp +++ b/packages/omamobile-settings/tests/core_tests.cpp @@ -18,7 +18,7 @@ private slots: void navigationRejectsUnknownAndHiddenActions() { Backend backend; QVERIFY(backend.catalogProblems().isEmpty()); - QCOMPARE(backend.rows().size(), 2); + QCOMPARE(backend.rows().size(), 3); QVERIFY(!backend.navigate("recording")); backend.activate("arbitrary-command"); QCOMPARE(backend.page(), QString("root")); @@ -29,6 +29,13 @@ private slots: backend.back(); QCOMPARE(backend.page(), QString("root")); } + void keyboardPageGoesBackToRoot() { + Backend backend; + QVERIFY(backend.navigate("keyboard")); + QCOMPARE(backend.page(), QString("keyboard")); + backend.back(); + QCOMPARE(backend.page(), QString("root")); + } void displayPageGoesBackToRoot() { Backend backend; QVERIFY(backend.navigate("display")); diff --git a/packages/omamobile-shell/README.md b/packages/omamobile-shell/README.md index 71f4ac874..b9cfeea77 100644 --- a/packages/omamobile-shell/README.md +++ b/packages/omamobile-shell/README.md @@ -26,7 +26,7 @@ Omarchy Mobile's phone profile for Omarchy's own shell. It isn't a fork: these a | `bin/omamobile-osk-watch` | Reports squeekboard's visibility (sm.puri.OSK0) to the fingerprint, keyboard and launcher plugins | | `bin/omamobile-screenshot-open` | What a screenshot toast's tap ("Tap to view", patch 0020) opens on a phone (`OMARCHY_SCREENSHOT_EDITOR`, set in `environment.d/30-omamobile-screenshot.conf`; Omarchy passes the saved file's path): the screenshot in Loupe (omamobile-apps), fitted, with touch zoom, pan and swipe, and Loupe's copy, share and delete. Tensaku, Omarchy's default, can't be panned or zoomed by touch; without Loupe it is the fallback, through `omamobile-screenshot-edit` | | `bin/omamobile-screenshot-edit` | Tensaku as Omarchy opens a screenshot in it (`tensaku-edit`), with GTK's simple input-method context so the on-screen keyboard doesn't come up over the image (show it by hand for the text tool). `omamobile-setup-user` gives Tensaku's own entry (drawer, Loupe's Open With) the same context once, and `hypr/phone.lua` maximizes its window, which Omarchy floats by class | -| `bin/omamobile-osk-guard` | Turns the on-screen keyboard (`screen-keyboard-enabled`) back on when it was left off with no screensaver running (a user unit for every graphical session) | +| `bin/omamobile-osk-guard` | Owns the on-screen keyboard's auto-show (`screen-keyboard-enabled`): off while a real Bluetooth or USB keyboard is connected (unless the shade's keyboard card says Show, or the session is locked; a polkit prompt is not detected), back on when it was left off with no screensaver running; lists the keyboards for the card in `~/.local/state/omamobile/osk-hwkbd.json`, and runs the card's `--mode show|hide` and `--disconnect MAC` (a user unit for every graphical session) | | `bin/omamobile-doubletap` | Double tap to wake, as on Android: two taps within 0.4 s and about 150 px of each other (14 % of the touchscreen's width) on a dark phone wake it as a short power press does (`omamobile-keys double-tap`, which leaves a lit screen alone). `hypr/phone.lua` turns Hyprland's `misc:mouse_move_enables_dpms` off, so a single touch no longer lights the screen; on the lock no touch wakes it either (patch 0029), and this daemon wakes it through `omamobile-keys double-tap`. With the phone in a pocket (proximity near, through iio-sensor-proxy, claimed only from the first dark tap until 2 s after the last) the double tap is skipped; without a proximity sensor it wakes as before. A screen that goes dark while unlocked (an idle blank, the panel powered off by hand) is locked at once (`omamobile-keys dark-unlocked`), as on Android: Hyprland sends a touch to the window under it whatever the screen's state, so on a dark unlocked phone it reached an app no one could see. It works while the phone is awake: a double tap can't wake it from sleep (with the sleep toggle on, the first 30 s after the screen goes off). It times a double tap from one lift to the next touch, and it only wakes: the lock itself ignores touches while dark (0029). The touchscreen is the first input device with `INPUT_PROP_DIRECT`, `BTN_TOUCH` and `ABS_MT_POSITION_X`, read without a grab (the user is in the `input` group). A user unit for every graphical session | | `bin/omamobile-sleepd` | Sleep (s2idle) once the screen has been off behind a secure lock for `OMAMOBILE_SLEEP_AFTER_OFF` s (30), and again 5 s after a dark resume; `now` for the power key (`omamobile-keys`), `check` to see what holds it awake. Refuses with the screen on, Stay awake on, an SSH session open, a logind sleep block inhibitor (calls, GNSS) or a RUNNING PipeWire sink. A user unit for every graphical session, **off until `omarchy-toggle omamobile-sleep on`** (device/cheetah/SUSPEND-PLAN.md 6.2) | | `bin/omamobile-weather` | The current weather for the lock screen's glance (`~/.local/state/omamobile/weather.json`, with the `source` it used) from Open-Meteo, at login and every 30 minutes (`omamobile-weather.timer`, a user unit for every graphical session). Where, in order: the phone's position from GeoClue at city accuracy, at most every 3 h and only while the Location switch is on and GeoClue has an agent for the user (omamobile-gnss's unit, or any other instance of GeoClue's demo agent the user runs; never a prompt); the setting `~/.config/omamobile/weather.json` (`omamobile-weather set "State College, PA" F`, or `{"latitude", "longitude"}`; `"location": "fixed"` puts it before the position); the home screen's today widget's city, or the weather widget's named place. Unit: the setting's, else the locale's. A failure keeps the old reading; a run that starts before the network is back (login, or the catch-up run on resume) tries again with backoff for up to 75 s and then gives up without failing the unit. `omamobile-weather show` says where it would look | diff --git a/packages/omamobile-shell/bin/omamobile-keyboard-switch b/packages/omamobile-shell/bin/omamobile-keyboard-switch new file mode 100755 index 000000000..2d1bd4299 --- /dev/null +++ b/packages/omamobile-shell/bin/omamobile-keyboard-switch @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Hardware keyboard layout switching. + + omamobile-keyboard-switch next every real keyboard to the next layout + omamobile-keyboard-switch set N every real keyboard to layout N (0 = first) + omamobile-keyboard-switch lock layout 0 on every real keyboard (lock screen, + polkit prompt: passwords are typed in layout 0) + +The hardware switch key does not run this: it is an xkb grp: option in +kb_options (grp:alt_shift_toggle, grp:ctrl_shift_toggle or grp:caps_toggle; see +omamobile-settings/backends/keyboard.sh). Nothing calls this script yet (the +quick-settings card does not); it is kept, with its tests, for scripts and a +later caller. + +Real keyboards are the ones in `hyprctl -j devices` that are not squeekboard's +or another virtual keyboard (hl-virtual-keyboard*) or a pseudo-keyboard +(consumer-control, power-button, video-bus, radio-control, gpio-keys), the same +set as the Settings backend and the bar. The "main" keyboard (whose layout +`next` steps from and the bar shows) is, in all three: the real one Hyprland +marks main, else the first real one with more than one layout, else the first +real one. Every real keyboard is set to the same index. + +This never touches the on-screen keyboard: no gsettings write and no +omamobile-keyboard-languages call. On the phone (Hyprland 0.57.0, 2026-11-17) +a gsettings write on a hardware switch made squeekboard send its keymap again, +and the app then got Latin letters while Hyprland said Greek. The OSK keeps its +own language list and globe key. + +UNVERIFIED on the phone: `switchxkblayout` through `hyprctl --batch` (the +phone test ran `hyprctl switchxkblayout next` directly). + +OMAMOBILE_HYPRCTL points elsewhere for tests.""" + +import glob +import json +import os +import subprocess +import sys + +HYPRCTL = os.environ.get("OMAMOBILE_HYPRCTL", "hyprctl") +PSEUDO = ("consumer-control", "power-button", "video-bus", "radio-control", "gpio-keys") +# hyprctl --batch splits commands on ";" and arguments on spaces: a name with any of these +# cannot be passed safely, so that keyboard is left out (Hyprland names seen on 0.56.2 are +# lowercase with dashes, e.g. dell-kb7120w). +UNSAFE = set(" ;\t\r\n\"'\\") + + +def find_hypr(): + if os.environ.get("HYPRLAND_INSTANCE_SIGNATURE"): + return + run = os.environ.get("XDG_RUNTIME_DIR") or "/run/user/%d" % os.getuid() + socks = glob.glob(os.path.join(run, "hypr", "*", ".socket.sock")) + if socks: + newest = max(socks, key=os.path.getmtime) + os.environ["HYPRLAND_INSTANCE_SIGNATURE"] = os.path.basename(os.path.dirname(newest)) + + +def real(name): + return not name.startswith("hl-virtual-keyboard") and not any(p in name for p in PSEUDO) + + +def keyboards(): + r = subprocess.run([HYPRCTL, "-j", "devices"], capture_output=True, text=True) + if r.returncode: + sys.exit("omamobile-keyboard-switch: hyprctl devices failed") + try: + kbs = json.loads(r.stdout).get("keyboards", []) + except ValueError: + sys.exit("omamobile-keyboard-switch: hyprctl devices gave no JSON") + return [k for k in kbs if real(k.get("name", ""))] + + +def names(kb): + """xkb names: layout or layout+variant.""" + lay = kb.get("layout", "").split(",") + var = kb.get("variant", "").split(",") + var += [""] * (len(lay) - len(var)) + return [l + ("+" + v if v else "") for l, v in zip(lay, var) if l] + + +def main_kb(kbs): + return (next((k for k in kbs if k.get("main")), None) + or next((k for k in kbs if len(names(k)) > 1), None) + or (kbs[0] if kbs else None)) + + +def safe(name): + return bool(name) and not any(c in UNSAFE or ord(c) < 32 for c in name) + + +def switch(n, kbs): + cmds = [] + for k in kbs: + if safe(k["name"]): + cmds.append("switchxkblayout %s %d" % (k["name"], n)) + else: + print("omamobile-keyboard-switch: skipping keyboard %r (name hyprctl --batch cannot take)" + % k["name"], file=sys.stderr) + if cmds: + subprocess.run([HYPRCTL, "--batch", "; ".join(cmds)], stdout=subprocess.DEVNULL) + + +def to(n, kbs=None): + kbs = keyboards() if kbs is None else kbs + kb = main_kb(kbs) + if kb is None: + return + lst = names(kb) + if len(lst) < 2: + return # one layout: the switch key does nothing + n %= len(lst) + switch(n, kbs) + + +def main(argv): + find_hypr() + if argv[:1] == ["next"]: + kbs = keyboards() + kb = main_kb(kbs) + i = kb.get("active_layout_index", 0) if kb else 0 + to((i if isinstance(i, int) else 0) + 1, kbs) + elif argv[:1] == ["set"] and len(argv) == 2 and argv[1].isdigit(): + to(int(argv[1])) + elif argv[:1] == ["lock"]: + to(0) + else: + sys.exit(__doc__) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/packages/omamobile-shell/bin/omamobile-osk-guard b/packages/omamobile-shell/bin/omamobile-osk-guard index bb21cf20c..8faeeb80d 100755 --- a/packages/omamobile-shell/bin/omamobile-osk-guard +++ b/packages/omamobile-shell/bin/omamobile-osk-guard @@ -1,43 +1,435 @@ -#!/bin/bash +#!/usr/bin/python3 -I # SPDX-License-Identifier: MIT -# The on-screen keyboard's safety net (TOUCH-PLAN 0.5). Omarchy's screensaver -# launcher turns the global screen-keyboard-enabled setting off while the -# screensaver runs (patches/omarchy/0006-*), and its exit paths turn it back -# on. A path that missed left a phone with no keyboard for any text field -# until the next login. This watches the setting: whenever it goes off, it -# waits until no screensaver runs, gives the screensaver's own restore its -# time (it waits up to 5 s for the lock), and turns it back on if it is -# still off. On a phone nothing else turns the keyboard off: squeekboard's -# hide button only hides it. +# The on-screen keyboard's owner: the one program that writes the global +# screen-keyboard-enabled setting (squeekboard's "no physical keyboard" flag). # -# omamobile-osk-guard watch (omamobile-osk-guard.service) -# omamobile-osk-guard --once check once and exit -set -u +# 1. Hardware keyboards (OSK-HWKBD-PLAN): while a real Bluetooth or USB +# keyboard is connected, squeekboard does not pop up on a text field +# (the setting is false), unless the user chose "Show on-screen keyboard" +# on the shade's keyboard card (mode "show"). The keyboards and the mode +# are in ~/.local/state/omamobile/osk-hwkbd.json, which the card reads. A +# keyboard that goes away stays listed for a 5 s grace counted from when +# it was first found missing (a Bluetooth keyboard waking up comes back as +# the same uniq and keeps the mode); after it, with no keyboard left, the +# mode goes back to "auto". While the session is locked (any credential: +# the password field, or the ABC field next to a PIN pad) the setting +# stays true. The lock is polled with one process (omarchy-shell lock +# isLocked) every 2 s, 10 s with the screen off, and only while a +# keyboard is listed and the mode is not "show"; output other than +# "false" counts as locked. The setting itself is followed through +# `gsettings monitor`, keyboards through `udevadm monitor` (no polling). +# KNOWN LIMIT: a polkit password prompt is not detected (Omarchy's agent +# is inside the shell, no window to see), so with a keyboard listed the +# on-screen keyboard does not pop up there; the card's Show button or +# disconnecting the keyboard brings it back. +# 2. The safety net (TOUCH-PLAN 0.5): Omarchy's screensaver launcher turns +# the setting off while the screensaver runs (patches/omarchy/0006-*) and +# back on after. When it is off and should not be, this waits until no +# screensaver runs, gives the screensaver's own restore its time, and +# turns it back on. When 0006's restore turns it on while a keyboard is +# connected, this turns it straight back off. No keyboard: always true. +# Stopping the watcher leaves it true. +# +# omamobile-osk-guard watch (omamobile-osk-guard.service) +# omamobile-osk-guard --once check once and exit +# omamobile-osk-guard --mode show|hide|auto +# the card's buttons: set the mode, the +# setting, and show or hide the keyboard +# omamobile-osk-guard --disconnect MAC +# bluetoothctl disconnect (the card) +import fcntl, glob, json, os, re, select, signal, struct, subprocess, sys, tempfile, time + +KEY = ["org.gnome.desktop.a11y.applications", "screen-keyboard-enabled"] +HOME = os.environ.get("HOME", "/") +SYSFS = os.environ.get("OMAMOBILE_OSK_SYSFS", "/sys") +UDEV = os.environ.get("OMAMOBILE_OSK_UDEVDATA", "/run/udev/data") +STATE = os.environ.get("OMAMOBILE_OSK_STATE", HOME + "/.local/state/omamobile/osk-hwkbd.json") + + +def num(name, default): + try: return float(os.environ.get(name, default)) + except ValueError: return float(default) + -key=(org.gnome.desktop.a11y.applications screen-keyboard-enabled) # The launcher turns the setting off a moment before the screensaver's # window opens, and the screensaver's restore waits for the lock. -grace=${OMAMOBILE_OSK_GUARD_GRACE:-10} - -osk_off() { [[ $(gsettings get "${key[@]}" 2>/dev/null) == false ]]; } -screensaver_up() { pgrep -f '[o]rg.omarchy.screensaver' >/dev/null; } - -check() { - osk_off || return 0 - sleep "$grace" - while screensaver_up; do sleep 2; done - sleep "$grace" - if osk_off && ! screensaver_up; then - gsettings set "${key[@]}" true - echo "omamobile-osk-guard: the on-screen keyboard was off with no screensaver running; turned it back on" - fi -} - -check -[[ ${1:-} == --once ]] && exit 0 - -while IFS= read -r line; do - [[ $line == *false ]] && check -done < <(gsettings monitor "${key[@]}") -# The monitor ended (the session bus went away): let systemd restart it. -exit 1 +GRACE = num("OMAMOBILE_OSK_GUARD_GRACE", 10) +KEYBOARD_GRACE = num("OMAMOBILE_OSK_KEYBOARD_GRACE", 5) +SETTLE = num("OMAMOBILE_OSK_SETTLE", 1) +POLL = num("OMAMOBILE_OSK_POLL", 2) +POLL_OFF = num("OMAMOBILE_OSK_POLL_OFF", 10) # the lock poll with the screen off +MAC = re.compile(r"^([0-9a-f]{2}:){5}[0-9a-f]{2}$", re.I) + + +def log(msg): + print("omamobile-osk-guard: " + msg, flush=True) + + +def run(cmd, timeout=10): + try: + return subprocess.run(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, text=True, timeout=timeout) + except (OSError, subprocess.TimeoutExpired): + return None + + +# ------------------------------------------------------------------ keyboards +# The rule of omamobile-settings' lock.sh keyboard_connected() (a copy: that +# is another package): an event node udev calls a keyboard, on Bluetooth +# (bus 0005) or USB (0003, not a virtual device), not a security key or a +# scanner, with the letter rows and space. gpio-keys (0019) and squeekboard's +# virtual keyboard never pass. +NOT_KEYBOARDS = re.compile(r"yubikey|yubico|nitrokey|solokey|onlykey|token|barcode|scanner", re.I) +LONG_BITS = struct.calcsize("l") * 8 +NEEDED = list(range(16, 26)) + list(range(30, 39)) + list(range(44, 51)) + [57] # Q..P, A..L, Z..M, space + + +def read(p): + try: + with open(p) as f: return f.read().strip() + except (OSError, UnicodeDecodeError): + return None + + +def keyboards(): + """Connected keyboards, one per uniq (else phys, else node): name, uniq, bus.""" + base = os.path.join(SYSFS, "class/input") + try: names = sorted(os.listdir(base), key=lambda n: (len(n), n)) + except OSError: return [] + found = {} + for ev in names: + if not ev.startswith("event"): continue + d = os.path.join(base, ev) + dev, bus = read(d + "/dev"), read(d + "/device/id/bustype") + if not dev or not bus: continue + data = read(os.path.join(UDEV, "c" + dev)) or "" + if "E:ID_INPUT_KEYBOARD=1" not in data.splitlines(): continue + path = os.path.realpath(d + "/device") + if bus == "0005": pass + elif bus == "0003" and "/devices/virtual/input/" not in path + "/": pass + else: continue + name = read(d + "/device/name") + if not name or NOT_KEYBOARDS.search(name): continue + caps = (read(d + "/device/capabilities/key") or "").split() + try: bits = sum(int(w, 16) << (i * LONG_BITS) for i, w in enumerate(reversed(caps))) + except ValueError: continue + if not all(bits >> k & 1 for k in NEEDED): continue + uniq = (read(d + "/device/uniq") or "").lower() + key = uniq or read(d + "/device/phys") or ev + if key not in found: + found[key] = {"name": name, "uniq": uniq, "bus": "bluetooth" if bus == "0005" else "usb"} + return [dict(k, id=key) for key, k in found.items()] + + +# ------------------------------------------------------------------ state file +def locked_state(): + os.makedirs(os.path.dirname(STATE), exist_ok=True) + f = open(STATE + ".lock", "a") + fcntl.flock(f, fcntl.LOCK_EX) + return f + + +def load(): + try: + with open(STATE) as f: s = json.load(f) + if not isinstance(s, dict): raise ValueError + except (OSError, ValueError): + s = {} + kbs = s.get("keyboards") if isinstance(s.get("keyboards"), list) else [] + mode = s.get("mode") if s.get("mode") in ("auto", "show", "hide") else "auto" + # An entry without a string id and name is dropped (a hand-edited file + # must not stop the guard). + kbs = [k for k in kbs if isinstance(k, dict) and isinstance(k.get("id"), str) and isinstance(k.get("name"), str)] + return {"keyboards": kbs, "mode": mode} + + +def save(s): + target = os.path.realpath(STATE) + fd, tmp = tempfile.mkstemp(dir=os.path.dirname(target), prefix=".osk-hwkbd.") + try: + with os.fdopen(fd, "w") as f: + json.dump(s, f, ensure_ascii=False); f.write("\n") + os.chmod(tmp, 0o644) + os.replace(tmp, target) + except BaseException: + try: os.unlink(tmp) + except OSError: pass + raise + + +# ------------------------------------------------------------------ the setting +def osk_get(): + r = run(["gsettings", "get"] + KEY) + return parse_bool(r.stdout if r and r.returncode == 0 else "") + + +def parse_bool(text): + v = text.strip().rsplit(" ", 1)[-1] if text.strip() else "" + return True if v == "true" else False if v == "false" else None + + +def osk_set(value): + run(["gsettings", "set"] + KEY + ["true" if value else "false"]) + + +def screensaver_up(): + r = run(["pgrep", "-f", "[o]rg.omarchy.screensaver"]) + return bool(r and r.returncode == 0) + + +def is_locked(): + """One process. Anything but a plain "false" (a timeout, the shell + restarting, odd output) counts as locked: the safe side is a keyboard + that can come up.""" + r = run(["omarchy-shell", "lock", "isLocked"], timeout=5) + return not (r and r.returncode == 0 and r.stdout.strip() == "false") + + +def screen_off(): + """No process: every backlight reads off (bl_power 4 or brightness 0). + UNVERIFIED on the phone that DPMS off shows there; if not, the screen + simply counts as on and the lock is polled at the faster rate.""" + seen = False + for d in glob.glob(os.path.join(SYSFS, "class/backlight/*")): + seen = True + if read(d + "/bl_power") not in ("4",) and read(d + "/brightness") not in ("0",): return False + return seen + + +def wanted(state, locked): + """locked: a callable, asked only when it decides the answer.""" + if not state["keyboards"] or state["mode"] == "show": return True + # Locked (any credential): the lock's field, password or the ABC field + # next to a PIN pad, must be able to bring the keyboard up. + return locked() + + +def set_visible(show): + run(["busctl", "--user", "call", "sm.puri.OSK0", "/sm/puri/OSK0", "sm.puri.OSK0", + "SetVisible", "b", "true" if show else "false"]) + + +# ------------------------------------------------------------------ the watcher +class Guard: + def __init__(self): + self.seen = {} # id -> [keyboard, time first found missing or None] + self.last_wanted = None + self.actual = None # the setting, from gsettings monitor (None: read it) + self.locked = None # the last lock poll (None: not polled) + self.restore_at = None # the safety net's deadline (setting off, wanted on) + self.restore_phase = 0 # 0: first grace, 1: screensaver gone, second grace + self.scan_at = 0.0 + self.poll_at = None + self.state = {"keyboards": [], "mode": "auto"} + # A restart keeps what the file lists for one grace (and its mode): + # counted as missing from now until a scan finds it. + start = time.monotonic() + for k in load()["keyboards"]: + self.seen[k["id"]] = [k, start] + + def refresh(self, now): + """Rescan; write the state file when the list or the mode changes. + The grace runs from when a keyboard was first found missing, and a + keyboard that comes back within it keeps the mode.""" + present = {k["id"]: k for k in keyboards()} + for key, k in present.items(): + self.seen[key] = [k, None] + listed = [] + for key, (k, gone) in list(self.seen.items()): + if key not in present and gone is None: + self.seen[key][1] = gone = now + if gone is None or now - gone < KEYBOARD_GRACE: listed.append(k) + else: del self.seen[key] + listed.sort(key=lambda k: (k["name"], k["id"])) + with locked_state(): + s = load() + new = {"keyboards": listed, "mode": s["mode"] if listed else "auto"} + if new != s: save(new) + self.state = new + return new + + def lock_matters(self, s): + return bool(s["keyboards"]) and s["mode"] != "show" + + def poll_lock(self): + self.locked = is_locked() + return self.locked + + def get_actual(self): + if self.actual is None: self.actual = osk_get() + return self.actual + + def write(self, value): + osk_set(value) + self.actual = value + + def evaluate(self, now, rescan=True, s=None): + s = s or (self.refresh(now) if rescan else load()) + self.state = s + if not self.lock_matters(s): self.locked = None + want = wanted(s, lambda: self.locked if self.locked is not None else self.poll_lock()) + actual = self.get_actual() + if want != self.last_wanted and self.last_wanted is not None: + # Our own change (a keyboard came or went, the lock, the mode). + self.last_wanted = want + self.restore_at = None + if actual == want: return + if want and not self.locked and screensaver_up(): + # A keyboard went away under the screensaver: no keyboard + # over it; the safety net turns it on once it is gone. + self.restore_at = now + POLL + self.restore_phase = 0 + return + self.write(want) + return + self.last_wanted = want + if actual is None or actual == want: + self.restore_at = None + return + if not want: + # Someone turned it on over a connected keyboard (0006's restore). + self.restore_at = None + self.write(False) + log("a keyboard is connected; turned the on-screen keyboard's auto-show back off") + return + if self.restore_at is None: + self.restore_at = now + GRACE + self.restore_phase = 0 + + def due(self, now): + """The safety net's next step when its deadline came.""" + if self.restore_at is None or now < self.restore_at: return + if screensaver_up() and not (self.lock_matters(self.state) and self.locked): + self.restore_at = now + POLL + self.restore_phase = 0 + return + if self.restore_phase == 0: + self.restore_phase = 1 + self.restore_at = now + GRACE + return + self.restore_at = None + self.actual = osk_get() + if self.actual is False and wanted(self.state, self.poll_lock) and \ + (self.locked or not screensaver_up()): + self.write(True) + log("the on-screen keyboard was off with no screensaver running; turned it back on") + + def next_deadline(self, now): + times = [t for t in (self.restore_at, self.scan_at or None) if t is not None] + # A keyboard in its grace: drop it (and maybe the mode) when it ends. + times += [gone + KEYBOARD_GRACE for _, gone in self.seen.values() if gone is not None] + if self.lock_matters(self.state): + if self.poll_at is None: + self.poll_at = now + (POLL_OFF if screen_off() else POLL) + times.append(self.poll_at) + else: + self.poll_at = None + return min(times) if times else None + + def tick(self, now): + """Deadlines: a rescan, a grace end, the lock poll, the safety net.""" + if self.scan_at and now >= self.scan_at: + self.scan_at = 0.0 + self.evaluate(now) + elif any(gone is not None and now - gone >= KEYBOARD_GRACE for _, gone in self.seen.values()): + self.evaluate(now) + if self.poll_at is not None and now >= self.poll_at: + self.poll_at = None + if self.lock_matters(self.state): + self.poll_lock() + self.evaluate(now, s=self.state) + self.due(now) + + +def once(): + g = Guard() + now = time.monotonic() + g.evaluate(now) + while g.restore_at is not None: + time.sleep(max(0.0, g.restore_at - time.monotonic())) + g.due(time.monotonic()) + return 0 + + +def watch(): + children = [] + + def stop(*_): + raise SystemExit(0) + + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGHUP, stop) + try: + mon = subprocess.Popen(["gsettings", "monitor"] + KEY, stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, text=True) + children.append(mon) + udev = subprocess.Popen(["udevadm", "monitor", "--udev", "--subsystem-match=input"], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, text=True) + children.append(udev) + g = Guard() + g.evaluate(time.monotonic()) + streams = [mon.stdout, udev.stdout] + while True: + now = time.monotonic() + deadline = g.next_deadline(now) + timeout = None if deadline is None else max(0.0, deadline - now) + ready, _, _ = select.select(streams, [], [], timeout) + now = time.monotonic() + for r in ready: + line = r.readline() + if not line: + # A monitor ended (the session bus went away, udevadm + # died): let systemd restart the guard. + return 1 + if r is udev.stdout: + g.scan_at = now + SETTLE + else: + g.actual = parse_bool(line) + g.evaluate(now, rescan=False, s=g.state) + g.tick(now) + finally: + for c in children: + try: c.terminate() + except OSError: pass + # Nobody watches the keyboards now: an empty list, so the card goes + # and a "hide" cannot leave auto-show off. + try: + with locked_state(): save({"keyboards": [], "mode": "auto"}) + except OSError: + pass + # Never leave the phone without its keyboard. + if osk_get() is False: osk_set(True) + + +def set_mode(mode): + with locked_state(): + s = load() + s["mode"] = mode + save(s) + want = wanted(s, is_locked) + if osk_get() != want: osk_set(want) + if mode == "show": set_visible(True) + elif mode == "hide": set_visible(False) + return 0 + + +def disconnect(mac): + if not MAC.match(mac): + print("omamobile-osk-guard: not a Bluetooth address: " + mac, file=sys.stderr) + return 2 + r = run(["bluetoothctl", "disconnect", mac.upper()], timeout=15) + return 0 if r and r.returncode == 0 else 1 + + +def main(argv): + if not argv: return watch() + if argv == ["--once"]: return once() + if len(argv) == 2 and argv[0] == "--mode" and argv[1] in ("show", "hide", "auto"): return set_mode(argv[1]) + if len(argv) == 2 and argv[0] == "--disconnect": return disconnect(argv[1]) + print("Usage: omamobile-osk-guard [--once | --mode show|hide|auto | --disconnect MAC]", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/packages/omamobile-shell/hypr/phone.lua b/packages/omamobile-shell/hypr/phone.lua index 08ae4f943..69303c0e2 100644 --- a/packages/omamobile-shell/hypr/phone.lua +++ b/packages/omamobile-shell/hypr/phone.lua @@ -247,3 +247,10 @@ elseif o.cmd_present("voxtype") then { "Stop dictation (push-to-talk)", "voxtype record stop", { release = true } }, }) end + +-- The hardware keyboard's layout switch key is xkb only, a grp: option in +-- kb_options that Settings > Keyboard writes to input.lua; nothing is bound +-- here. On the phone (Hyprland 0.57.0) grp:alt_shift_toggle and +-- grp:ctrl_shift_toggle switched in both key orders, and a press bind on top +-- of the option switched twice per press. A fresh phone has no grp: option +-- unless Omarchy's input.lua adds one (grp:alts_toggle for a non-Latin layout). diff --git a/packages/omamobile-shell/plugins/README.md b/packages/omamobile-shell/plugins/README.md index 6209a381d..88d08a307 100644 --- a/packages/omamobile-shell/plugins/README.md +++ b/packages/omamobile-shell/plugins/README.md @@ -191,6 +191,22 @@ omamobile-omarchy's 4.5 series; without it the rows come back). The card takes the room left under the sheet and scrolls past that; it hides in edit mode, or when the sheet leaves no room for it. +### Hardware keyboard card + +While a real Bluetooth or USB keyboard is connected, the on-screen keyboard +stops popping up on text fields and the shade starts with a keyboard card +(`KeyboardCard.qml`, rules in `HwKeyboardModel.js`, tests in +`test/hwkeyboard-model.js` and `test/osk-guard.sh`). `omamobile-osk-guard` +is the only writer of `screen-keyboard-enabled` and lists the keyboards (one +per `uniq`, so a keyboard's several input nodes are one row) in +`~/.local/state/omamobile/osk-hwkbd.json`, which the card watches. Each row +reads " connected", with Disconnect for a Bluetooth keyboard whose +`uniq` is its address (`bluetoothctl disconnect`). Show on-screen keyboard +turns auto-show back on and shows it; Hide turns it off and hides it. A +keyboard that goes away stays listed for 5 s (a reconnect of the same `uniq` +keeps the mode); with none left the mode goes back to auto and auto-show is +on. Locked (any credential), auto-show stays on; a polkit prompt is not detected (known limit). + ### Media card While a player plays or is paused, the shade starts with a media card, as diff --git a/packages/omamobile-shell/plugins/omamobile.bar/Bar.qml b/packages/omamobile-shell/plugins/omamobile.bar/Bar.qml index 6bd395a12..3af5ace53 100644 --- a/packages/omamobile-shell/plugins/omamobile.bar/Bar.qml +++ b/packages/omamobile-shell/plugins/omamobile.bar/Bar.qml @@ -3,6 +3,7 @@ import QtQuick import Qt.labs.folderlistmodel import Quickshell import Quickshell.Bluetooth +import Quickshell.Hyprland import Quickshell.Io import Quickshell.Networking import Quickshell.Services.UPower @@ -98,6 +99,36 @@ Item { } Timer { id: cellRestart; interval: 5000; onTriggered: cellWatch.running = true } + // The hardware keyboard's layout (EN, GR...) beside the clock, only when + // kb_layout has more than one layout. Read from `hyprctl -j devices` at + // start and again on Hyprland's activelayout and configreloaded events + // (event names checked on Hyprland 0.56.2 only, UNVERIFIED on 0.57). + property string layoutLabel: "" + // An event that comes while a read runs marks it pending: setting running + // on a running Process does nothing, so the read is run again after it ends. + property bool layoutPending: false + function readLayout() { + if (layoutRead.running) layoutPending = true + else layoutRead.running = true + } + Process { + id: layoutRead + command: ["hyprctl", "-j", "devices"] + running: true + onExited: if (root.layoutPending) { root.layoutPending = false; layoutReread.restart() } + stdout: StdioCollector { + waitForEnd: true + onStreamFinished: root.layoutLabel = StatusModel.layoutLabel(text) + } + } + Timer { id: layoutReread; interval: 150; onTriggered: root.readLayout() } + Connections { + target: Hyprland + function onRawEvent(event) { + if (event && (event.name === "activelayout" || event.name === "configreloaded")) layoutReread.restart() + } + } + // A call in progress: a chip with its time beside the clock. omatel's // agent through bin/omamobile-call-watch --observe (the call card runs // the waking, name-holding copy). @@ -306,6 +337,21 @@ Item { font.bold: true } + Text { + id: layoutText + objectName: "layoutLabel" + visible: root.layoutLabel !== "" + anchors.left: clockText.right + anchors.leftMargin: Style.spacing.lg + anchors.verticalCenter: parent.verticalCenter + textFormat: Text.PlainText + text: root.layoutLabel + color: root.foreground + font.family: root.fontFamily + font.pixelSize: Style.font.body + font.bold: true + } + // The call in progress, beside the clock; a tap opens the Phone // app's in-call screen (the bar is never shown over the lock). Rectangle { @@ -313,7 +359,8 @@ Item { objectName: "callChip" visible: root.callChip !== "" z: 2 - anchors.left: clockText.right + // after the layout label, or the clock when the label is hidden + anchors.left: layoutText.visible ? layoutText.right : clockText.right anchors.leftMargin: Style.spacing.lg anchors.verticalCenter: parent.verticalCenter height: Math.round(root.barSize * 0.66) diff --git a/packages/omamobile-shell/plugins/omamobile.bar/StatusModel.js b/packages/omamobile-shell/plugins/omamobile.bar/StatusModel.js index 792817ed5..696634bb1 100644 --- a/packages/omamobile-shell/plugins/omamobile.bar/StatusModel.js +++ b/packages/omamobile-shell/plugins/omamobile.bar/StatusModel.js @@ -145,11 +145,37 @@ function batteryIcon(percent, charging, full) { return charging ? chargingIcons[index] : defaultIcons[index] } +// The keyboard layout label from `hyprctl -j devices`: the main real keyboard +// (not squeekboard's hl-virtual-keyboard or a pseudo one), picked by the same +// rule as bin/omamobile-keyboard-switch and the Settings backend: the real one +// marked main, else the first real one with more than one layout, else the +// first real one. "" when it has one layout or none. +// English layouts read EN, the rest their xkb code in capitals (GR, DE). +var englishLayouts = ["us", "gb", "au", "ca", "ie", "nz", "za"] +function layoutLabel(text) { + var kbs + try { kbs = (JSON.parse(text) || {}).keyboards || [] } catch (e) { return "" } + var real = kbs.filter(function(k) { + var n = String(k && k.name || "") + return n !== "" && n.indexOf("hl-virtual-keyboard") !== 0 && !/consumer-control|power-button|video-bus|radio-control|gpio-keys/.test(n) + }) + var kb = real.filter(function(k) { return k.main })[0] + || real.filter(function(k) { return String(k.layout || "").split(",").filter(function(l) { return l !== "" }).length > 1 })[0] + || real[0] + if (!kb) return "" + var layouts = String(kb.layout || "").split(",").filter(function(l) { return l !== "" }) + var i = kb.active_layout_index + if (layouts.length < 2 || typeof i !== "number" || i < 0 || i >= layouts.length) return "" + var code = layouts[i] + return englishLayouts.indexOf(code) >= 0 ? "EN" : code.slice(0, 3).toUpperCase() +} + if (typeof module !== "undefined") { module.exports = { findDevice: findDevice, connectedNetwork: connectedNetwork, wifiIcon: wifiIcon, networkIcon: networkIcon, cellularIcon: cellularIcon, cellGlyph: cellGlyph, cellText: cellText, parseCell: parseCell, callChip: callChip, elapsed: elapsed, batteryIcon: batteryIcon, - stampOf: stampOf, parseStamp: parseStamp, unreadCount: unreadCount, unreadStored: unreadStored + stampOf: stampOf, parseStamp: parseStamp, unreadCount: unreadCount, unreadStored: unreadStored, + layoutLabel: layoutLabel } } diff --git a/packages/omamobile-shell/plugins/omamobile.quicksettings/HwKeyboardModel.js b/packages/omamobile-shell/plugins/omamobile.quicksettings/HwKeyboardModel.js new file mode 100644 index 000000000..6fb914b1b --- /dev/null +++ b/packages/omamobile-shell/plugins/omamobile.quicksettings/HwKeyboardModel.js @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: MIT +// Pure helpers for the shade's keyboard card (KeyboardCard.qml): the +// hardware keyboards omamobile-osk-guard lists in +// ~/.local/state/omamobile/osk-hwkbd.json, one row each, and the commands of +// the card's buttons. Node runs these in test/hwkeyboard-model.js through the +// module.exports below. + +var MAC = /^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i + +// The guard's file text -> { keyboards: [{ name, uniq, bluetooth, canDisconnect }], mode } +function parse(text) { + var s = null + try { s = JSON.parse(String(text || "")) } catch (e) { s = null } + var out = { keyboards: [], mode: "auto" } + if (!s || typeof s !== "object") return out + if (s.mode === "show" || s.mode === "hide") out.mode = s.mode + var list = Array.isArray(s.keyboards) ? s.keyboards : [] + for (var i = 0; i < list.length; i++) { + var k = list[i] + if (!k || typeof k !== "object") continue + var name = String(k.name || "").trim() || "Keyboard" + var uniq = String(k.uniq || "") + var bluetooth = k.bus === "bluetooth" + out.keyboards.push({ name: name, uniq: uniq, bluetooth: bluetooth, canDisconnect: bluetooth && MAC.test(uniq) }) + } + return out +} + +function rowText(row) { + return row.name + " connected" +} + +function accessibleName(keyboards) { + var n = keyboards.length + if (n === 0) return "" + if (n === 1) return rowText(keyboards[0]) + return n + " keyboards connected" +} + +function modeCommand(mode) { + return ["omamobile-osk-guard", "--mode", mode === "show" ? "show" : "hide"] +} + +// null for a keyboard the card can't disconnect (no Bluetooth address) +function disconnectCommand(row) { + if (!row || !row.canDisconnect) return null + return ["omamobile-osk-guard", "--disconnect", row.uniq] +} + +if (typeof module !== "undefined") { + module.exports = { + parse: parse, + rowText: rowText, + accessibleName: accessibleName, + modeCommand: modeCommand, + disconnectCommand: disconnectCommand + } +} diff --git a/packages/omamobile-shell/plugins/omamobile.quicksettings/KeyboardCard.qml b/packages/omamobile-shell/plugins/omamobile.quicksettings/KeyboardCard.qml new file mode 100644 index 000000000..2dd642307 --- /dev/null +++ b/packages/omamobile-shell/plugins/omamobile.quicksettings/KeyboardCard.qml @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: MIT +import QtQuick +import Quickshell +import Quickshell.Io +import qs.Commons +import qs.Commons as Commons +import qs.Ui +import "HwKeyboardModel.js" as HwKeyboardModel + +// The hardware keyboard card at the top of the notification shade, drawn as +// MediaCard.qml: while a Bluetooth or USB keyboard is connected the on-screen +// keyboard no longer pops up on a text field (omamobile-osk-guard owns that +// and lists the keyboards in ~/.local/state/omamobile/osk-hwkbd.json). One +// row per keyboard, " connected", with Disconnect for a Bluetooth one; +// Show / Hide on-screen keyboard set the guard's mode for all of them. +BorderSurface { + id: card + + property color foreground: Commons.Color.popups.text + property var keyboards: [] + property string mode: "auto" + // The shade is open: only then is the file re-read on a timer. + property bool active: false + + readonly property int inner: Style.spacing.lg + + visible: keyboards.length > 0 + implicitHeight: keyboards.length > 0 ? column.implicitHeight + inner * 2 : 0 + radius: Style.cornerRadius + color: Style.normalFillFor(card.foreground, Commons.Color.accent) + borderSpec: Border.controlSpec("normal", card.foreground, Commons.Color.accent) + + Accessible.role: Accessible.Grouping + Accessible.name: HwKeyboardModel.accessibleName(keyboards) + + function load(text) { + var s = HwKeyboardModel.parse(text) + keyboards = s.keyboards + mode = s.mode + } + + FileView { + id: stateFile + path: Quickshell.env("HOME") + "/.local/state/omamobile/osk-hwkbd.json" + printErrors: false + watchChanges: true + onFileChanged: reload() + onLoaded: card.load(text()) + onLoadFailed: card.load("") + } + + // The guard replaces the file (rename); each reload watches it again, and + // this catches a watch that was lost, while the shade is open (and once + // when it opens). + onActiveChanged: if (active) stateFile.reload() + Timer { interval: 5000; repeat: true; running: card.active; onTriggered: stateFile.reload() } + + Column { + id: column + x: card.inner + y: card.inner + width: card.width - card.inner * 2 + spacing: Style.spacing.md + + Repeater { + model: card.keyboards + + Item { + required property var modelData + width: column.width + height: Math.max(rowText.implicitHeight, disconnectButton.visible ? disconnectButton.height : 0) + + Text { + id: rowText + anchors.left: parent.left + anchors.right: disconnectButton.visible ? disconnectButton.left : parent.right + anchors.rightMargin: disconnectButton.visible ? Style.spacing.md : 0 + anchors.verticalCenter: parent.verticalCenter + textFormat: Text.PlainText + text: "󰌌 " + HwKeyboardModel.rowText(modelData) + color: card.foreground + font.family: Style.font.family + font.pixelSize: Style.font.subtitle + font.bold: true + elide: Text.ElideRight + } + + SheetButton { + id: disconnectButton + visible: modelData.canDisconnect + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + width: Math.max(96, Style.space(120)) + label: "Disconnect" + foreground: card.foreground + onTapped: { + var cmd = HwKeyboardModel.disconnectCommand(modelData) + if (cmd) Quickshell.execDetached(cmd) + } + } + } + } + + SheetButton { + width: column.width + label: "Show on-screen keyboard" + primary: card.mode === "show" + foreground: card.foreground + onTapped: Quickshell.execDetached(HwKeyboardModel.modeCommand("show")) + } + + SheetButton { + width: column.width + label: "Hide on-screen keyboard" + primary: card.mode === "hide" + foreground: card.foreground + onTapped: Quickshell.execDetached(HwKeyboardModel.modeCommand("hide")) + } + } +} diff --git a/packages/omamobile-shell/plugins/omamobile.quicksettings/QuickSettings.qml b/packages/omamobile-shell/plugins/omamobile.quicksettings/QuickSettings.qml index a7e21db5e..3d7df1972 100644 --- a/packages/omamobile-shell/plugins/omamobile.quicksettings/QuickSettings.qml +++ b/packages/omamobile-shell/plugins/omamobile.quicksettings/QuickSettings.qml @@ -1988,8 +1988,9 @@ Item { readonly property real room: window.height - restingTop - Style.gapsOut readonly property real insets: shade.contentTopInset + shade.contentBottomInset readonly property real listHeight: root.notifications.length > 0 ? shadeList.contentHeight : shadeEmpty.implicitHeight - // The media card and the gap under it, when a player is up. - readonly property real mediaRoom: mediaCard.visible ? mediaCard.height + shadeColumn.spacing : 0 + // The keyboard and media cards and the gaps under them, when they show. + readonly property real mediaRoom: (mediaCard.visible ? mediaCard.height + shadeColumn.spacing : 0) + + (keyboardCard.keyboards.length > 0 ? keyboardCard.height + shadeColumn.spacing : 0) readonly property real natural: insets + mediaRoom + shadeHeader.height + shadeColumn.spacing + listHeight visible: !root.editing && root.reveal > 0 && room >= insets + mediaRoom + shadeHeader.height @@ -2015,6 +2016,16 @@ Item { anchors.leftMargin: shade.contentLeftInset spacing: Style.spacing.md + // ---------- A hardware keyboard: the on-screen one's mode, Disconnect + KeyboardCard { + id: keyboardCard + objectName: "keyboardCard" + active: root.reveal > 0 + width: parent.width + height: implicitHeight + foreground: root.foreground + } + // ---------- What is playing, above the notifications MediaCard { id: mediaCard diff --git a/packages/omamobile-shell/systemd/user/omamobile-osk-guard.service b/packages/omamobile-shell/systemd/user/omamobile-osk-guard.service index 21191b08a..b178470f2 100644 --- a/packages/omamobile-shell/systemd/user/omamobile-osk-guard.service +++ b/packages/omamobile-shell/systemd/user/omamobile-osk-guard.service @@ -1,9 +1,11 @@ # SPDX-License-Identifier: MIT -# Turns the on-screen keyboard back on when it was left off with no -# screensaver running (TOUCH-PLAN 0.5). Enabled for every user by a vendor +# Owns the on-screen keyboard's auto-show (screen-keyboard-enabled): off while +# a hardware keyboard is connected, and back on when it was left off with no +# screensaver running (TOUCH-PLAN 0.5, OSK-HWKBD-PLAN). Stopping it, or a +# crash, leaves auto-show on. Enabled for every user by a vendor # wants link; runs for the graphical session. [Unit] -Description=Omarchy Mobile on-screen keyboard safety net +Description=Omarchy Mobile on-screen keyboard owner and safety net PartOf=graphical-session.target After=graphical-session.target @@ -11,6 +13,7 @@ After=graphical-session.target ExecStart=/usr/bin/omamobile-osk-guard Restart=always RestartSec=5 +ExecStopPost=/usr/bin/gsettings set org.gnome.desktop.a11y.applications screen-keyboard-enabled true [Install] WantedBy=graphical-session.target diff --git a/packages/omamobile-shell/test/all b/packages/omamobile-shell/test/all index 0b80220d4..76cb70a9b 100755 --- a/packages/omamobile-shell/test/all +++ b/packages/omamobile-shell/test/all @@ -309,6 +309,8 @@ else fi grep -cF 'call omamobile.bar notificationsSeen' "$qs" >/dev/null || fail "the shade tells the bar what it has shown" grep -cF 'function notificationsSeen(stamp: string): string' plugins/omamobile.bar/Bar.qml >/dev/null || fail "the bar serves notificationsSeen" +grep -cF 'onExited: if (root.layoutPending) { root.layoutPending = false; layoutReread.restart() }' plugins/omamobile.bar/Bar.qml >/dev/null || fail "an event during a layout read reruns it" +grep -cF 'anchors.left: layoutText.visible ? layoutText.right : clockText.right' plugins/omamobile.bar/Bar.qml >/dev/null || fail "the call chip follows the layout label, or the clock when it is hidden" grep -cF '"/.local/state/omamobile/notifications-seen"' plugins/omamobile.bar/Bar.qml >/dev/null || fail "the bar reads the shade's mark at start" grep -cF '"omarchy-shell", "shell", "summon", "omarchy.clipboard"' "$qs" >/dev/null || fail "the Clipboard tile opens Omarchy's clipboard history" # A swipe on a row forgets that one notification through the service's @@ -375,6 +377,7 @@ if command -v node >/dev/null; then node test/gesture-model.js >/dev/null || { node test/gesture-model.js | grep -v '^ok'; fail "home and drawer gesture rules"; } node test/wifi-model.js || fail "Wi-Fi model" node test/bluetooth-model.js || fail "Bluetooth model" + node test/hwkeyboard-model.js || fail "hardware keyboard card model" node test/sensor-model.js || fail "fingerprint sensor model" node test/tiles-model.js || fail "quick-settings tile layout" node test/notifications-model.js >/dev/null || { node test/notifications-model.js; fail "notification shade model"; } @@ -513,6 +516,11 @@ grep -c 'if (offset > Style.space(60)) sheet.dismissed()' plugins/omamobile.keyb if grep -n 'gnome-control-center\|Keyboard Settings' plugins/omamobile.keyboard/*.qml; then fail "no link to a GNOME settings panel the phone doesn't have"; fi python3 -B -c 'import ast,sys; ast.parse(open(sys.argv[1]).read())' bin/omamobile-keyboard-languages || fail "omamobile-keyboard-languages parses" bash test/keyboard-languages.sh >/dev/null || { bash test/keyboard-languages.sh; fail "omamobile-keyboard-languages"; } +python3 -B -c 'import ast,sys; ast.parse(open(sys.argv[1]).read())' bin/omamobile-keyboard-switch || fail "omamobile-keyboard-switch parses" +bash test/keyboard-switch.sh >/dev/null || { bash test/keyboard-switch.sh; fail "omamobile-keyboard-switch"; } +[[ ! -e systemd/user/omamobile-keyboard-switch.service ]] || fail "no layout follower service (it bounced switches back)" +if grep -nE 'switchxkblayout|omamobile-keyboard-switch|omamobile-keyboard\.lua|SHIFT_L|ALT_L|CTRL_L|code:66' hypr/phone.lua; then fail "phone.lua binds no switch key (xkb grp: options do it)"; fi +if grep -n 'SUPER + ALT + SHIFT + SPACE' hypr/phone.lua; then fail "the old next-layout bind is gone"; fi if [[ -n ${OMAMOBILE_KEYBOARD_RENDER:-} ]]; then bash test/keyboard-render "$OMAMOBILE_KEYBOARD_RENDER" >/dev/null || fail "language sheet render" fi @@ -1028,7 +1036,7 @@ pass "permission sheet" # of Hyprland's Lua API and sets what the layout depends on. lua=$(command -v lua || command -v lua5.4 || command -v luajit || true) if [[ -n $lua ]]; then - out=$("$lua" test/phone-rules.lua) || { grep -v '^ok' <<<"$out"; fail "phone.lua window rules"; } + out=$(XDG_CONFIG_HOME=/nonexistent "$lua" test/phone-rules.lua) || { grep -v '^ok' <<<"$out"; fail "phone.lua window rules"; } pass "phone.lua: edge to edge, opaque, dialogs, picture-in-picture" # Dictation keys under Omarchy 4.5's helpers: four homes, four bindings.lua dk=$(mktemp -d) @@ -1037,7 +1045,7 @@ if [[ -n $lua ]]; then printf 'if o.dictation_installed and o.dictation_installed() then\n o.bind_hold("F9", "Start dictation (push-to-talk)", "omarchy-dictation start", "Stop dictation (push-to-talk)", "omarchy-dictation stop")\nend\n' > "$dk/migrated/.config/hypr/bindings.lua" printf 'o.bind("F9", "My own key", "my-own-command")\n' > "$dk/own/.config/hypr/bindings.lua" for sc in installed:plain migrated:migrated own-f9:own none:plain; do - out=$(SCENARIO=${sc%%:*} HOME=$dk/${sc##*:} "$lua" test/phone-dictation.lua) || { grep -v '^ok' <<<"$out"; rm -rf "$dk"; fail "phone.lua dictation keys (${sc%%:*})"; } + out=$(SCENARIO=${sc%%:*} HOME=$dk/${sc##*:} env -u XDG_CONFIG_HOME "$lua" test/phone-dictation.lua) || { grep -v '^ok' <<<"$out"; rm -rf "$dk"; fail "phone.lua dictation keys (${sc%%:*})"; } done rm -rf "$dk" pass "phone.lua on Omarchy 4.5: Alt + Space and the migration's F9 are for hardware keyboards; the owner's own F9 is left alone" @@ -1077,7 +1085,7 @@ pass "screenshot toast: Loupe, or Tensaku without the on-screen keyboard" bash -n bin/omamobile-setup-user || fail "omamobile-setup-user parses" bash test/setup-user.sh || fail "omamobile-setup-user against a scratch home" -bash -n bin/omamobile-osk-guard || fail "omamobile-osk-guard parses" +python3 -c 'import ast,sys; ast.parse(open(sys.argv[1]).read())' bin/omamobile-osk-guard || fail "omamobile-osk-guard parses" # The widget crash guard counts a shell death inside the same boot as a # crash. A widget still "loading" from another boot (reboot, shutdown, dead # battery, or a system crash it caused) gets one retry as a suspect, and is @@ -1183,6 +1191,8 @@ grep -cx 'ExecStart=/usr/bin/omamobile-setup-user' systemd/user/omamobile-setup- [[ -x $tmp/root/usr/bin/omamobile-osk-guard && -f $u/omamobile-osk-guard.service && $(readlink "$u/graphical-session.target.wants/omamobile-osk-guard.service") == ../omamobile-osk-guard.service ]] \ || fail "the keyboard safety net is staged and enabled for every user's session" +grep -cx 'ExecStopPost=/usr/bin/gsettings set org.gnome.desktop.a11y.applications screen-keyboard-enabled true' systemd/user/omamobile-osk-guard.service >/dev/null \ + || fail "the keyboard's owner leaves auto-show on when it stops" # Sleep on screen-off: staged and running for every session, but off until # the user's toggle (SUSPEND-PLAN 6.2): nothing in the package turns it on. [[ -x $tmp/root/usr/bin/omamobile-sleepd && -f $u/omamobile-sleepd.service && diff --git a/packages/omamobile-shell/test/hwkeyboard-model.js b/packages/omamobile-shell/test/hwkeyboard-model.js new file mode 100644 index 000000000..9c6c64794 --- /dev/null +++ b/packages/omamobile-shell/test/hwkeyboard-model.js @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: MIT +// Node tests for plugins/omamobile.quicksettings/HwKeyboardModel.js. Run by test/all. +"use strict" +const assert = require("assert") +const path = require("path") +const M = require(path.join(__dirname, "../plugins/omamobile.quicksettings/HwKeyboardModel.js")) + +const dell = { id: "00:00:5e:00:53:01", name: "Dell Keybd Keyboard", uniq: "00:00:5e:00:53:01", bus: "bluetooth" } +const usb = { id: "usb-1", name: "USB Keyboard", uniq: "", bus: "usb" } + +let s = M.parse(JSON.stringify({ keyboards: [dell, usb], mode: "show" })) +assert.strictEqual(s.mode, "show") +assert.deepStrictEqual(s.keyboards.map(k => [k.name, k.bluetooth, k.canDisconnect]), + [["Dell Keybd Keyboard", true, true], ["USB Keyboard", false, false]]) +assert.strictEqual(M.rowText(s.keyboards[0]), "Dell Keybd Keyboard connected") +assert.strictEqual(M.accessibleName(s.keyboards), "2 keyboards connected") +assert.strictEqual(M.accessibleName(s.keyboards.slice(0, 1)), "Dell Keybd Keyboard connected") +assert.deepStrictEqual(M.disconnectCommand(s.keyboards[0]), ["omamobile-osk-guard", "--disconnect", "00:00:5e:00:53:01"]) +assert.strictEqual(M.disconnectCommand(s.keyboards[1]), null) +console.log("ok - rows per keyboard, Disconnect only with a Bluetooth address") + +// A Bluetooth keyboard without a usable uniq: no Disconnect +s = M.parse(JSON.stringify({ keyboards: [{ name: "", uniq: "", bus: "bluetooth" }, { name: "X", uniq: "x; reboot", bus: "bluetooth" }] })) +assert.deepStrictEqual(s.keyboards.map(k => [k.name, k.canDisconnect]), [["Keyboard", false], ["X", false]]) +assert.strictEqual(s.mode, "auto") +console.log("ok - no or a bad uniq hides Disconnect; a nameless keyboard is 'Keyboard'") + +// Missing, empty or broken file: no card +for (const t of ["", "null", "{", "[]", JSON.stringify({ keyboards: "x", mode: "weird" })]) { + assert.deepStrictEqual(M.parse(t), { keyboards: [], mode: "auto" }) +} +assert.strictEqual(M.accessibleName([]), "") +assert.deepStrictEqual(M.modeCommand("show"), ["omamobile-osk-guard", "--mode", "show"]) +assert.deepStrictEqual(M.modeCommand("hide"), ["omamobile-osk-guard", "--mode", "hide"]) +console.log("ok - a missing or broken file shows no card; the mode buttons' commands") diff --git a/packages/omamobile-shell/test/keyboard-switch.sh b/packages/omamobile-shell/test/keyboard-switch.sh new file mode 100755 index 000000000..6f934ebcc --- /dev/null +++ b/packages/omamobile-shell/test/keyboard-switch.sh @@ -0,0 +1,78 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# omamobile-keyboard-switch against a fake hyprctl: only real keyboards are +# switched (never squeekboard's hl-virtual-keyboard or a consumer-control +# pseudo-keyboard), next wraps around, and the on-screen keyboard is never +# touched (no gsettings, no omamobile-keyboard-languages: both are fakes on +# PATH that log a call). +set -euo pipefail +cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." +fail() { printf 'not ok - %s\n' "$1" >&2; exit 1; } +pass() { printf 'ok - %s\n' "$1"; } +t=$(mktemp -d); trap 'rm -rf "$t"' EXIT +export T=$t +mkdir -p "$t/bin" +cat >"$t/bin/hyprctl" <<'SH' +#!/bin/bash +case "$1 $2" in + "-j devices") cat "$T/devices.json" ;; + --batch*) printf '%s\n' "$2" >>"$T/hypr.log" ;; + *) exit 1 ;; +esac +SH +for f in gsettings omamobile-keyboard-languages; do + printf '#!/bin/bash\necho "%s $*" >>"$T/osk.log"\n' "$f" >"$t/bin/$f" +done +chmod +x "$t/bin/"* +export PATH="$t/bin:$PATH" +cat >"$t/devices.json" <<'J' +{"keyboards":[ +{"name":"hl-virtual-keyboard-squeekboard","layout":"us","variant":"","active_layout_index":0,"main":false}, +{"name":"dell-kb7120w-consumer-control","layout":"us,gr","variant":",polytonic","active_layout_index":0,"main":false}, +{"name":"dell-kb7120w","layout":"us,gr","variant":",polytonic","active_layout_index":1,"main":true}, +{"name":"other-kbd","layout":"us,gr","variant":",polytonic","active_layout_index":1,"main":false}, +{"name":"bad name;exec x","layout":"us,gr","variant":",polytonic","active_layout_index":1,"main":false}]} +J +export OMAMOBILE_HYPRCTL=$t/bin/hyprctl HYPRLAND_INSTANCE_SIGNATURE=test +s=bin/omamobile-keyboard-switch + +python3 -B "$s" next 2>"$t/err" +grep -q "skipping keyboard 'bad name;exec x'" "$t/err" || fail "a name with a space or ; is left out of the batch" +[[ $(cat "$t/hypr.log") == "switchxkblayout dell-kb7120w 0; switchxkblayout other-kbd 0" ]] || fail "next wraps to 0 on real keyboards only: $(cat "$t/hypr.log")" +pass "keyboard-switch next" + +: >"$t/hypr.log" +python3 -B "$s" set 1 +[[ $(cat "$t/hypr.log") == "switchxkblayout dell-kb7120w 1; switchxkblayout other-kbd 1" ]] || fail "set 1" +: >"$t/hypr.log" +python3 -B "$s" lock +[[ $(cat "$t/hypr.log") == "switchxkblayout dell-kb7120w 0; switchxkblayout other-kbd 0" ]] || fail "lock goes to layout 0" +pass "keyboard-switch set and lock" + +python3 -B "$s" bogus 2>/dev/null && fail "unknown verb fails" +python3 -B "$s" listen 2>/dev/null && fail "the follower is gone" +pass "keyboard-switch refuses unknown verbs" + +# main pick with no real keyboard marked main: the first real one with more than one layout +# (not the virtual one marked main, not gpio-keys, not a one-layout keyboard) +cat >"$t/devices.json" <<'J' +{"keyboards":[ +{"name":"hl-virtual-keyboard-squeekboard","layout":"us","variant":"","active_layout_index":0,"main":true}, +{"name":"gpio-keys","layout":"us,gr","variant":"","active_layout_index":0,"main":false}, +{"name":"single","layout":"us","variant":"","active_layout_index":0,"main":false}, +{"name":"dell-kb7120w","layout":"us,gr","variant":",polytonic","active_layout_index":1,"main":false}]} +J +: >"$t/hypr.log" +python3 -B "$s" next +[[ $(cat "$t/hypr.log") == "switchxkblayout single 0; switchxkblayout dell-kb7120w 0" ]] || fail "next steps from the first real keyboard with 2+ layouts: $(cat "$t/hypr.log")" +pass "keyboard-switch main keyboard rule" + +[[ ! -e $t/osk.log ]] || fail "a hardware switch touched the on-screen keyboard: $(cat "$t/osk.log")" +pass "keyboard-switch leaves the on-screen keyboard alone" + +# one layout: the switch key does nothing +printf '{"keyboards":[{"name":"dell-kb7120w","layout":"us","variant":"","active_layout_index":0,"main":true}]}\n' >"$t/devices.json" +rm -f "$t/hypr.log" +python3 -B "$s" next +[[ ! -e $t/hypr.log ]] || fail "one layout: no switch" +pass "keyboard-switch does nothing with one layout" diff --git a/packages/omamobile-shell/test/osk-guard.sh b/packages/omamobile-shell/test/osk-guard.sh index 4d657ea9a..a5f319c99 100644 --- a/packages/omamobile-shell/test/osk-guard.sh +++ b/packages/omamobile-shell/test/osk-guard.sh @@ -1,14 +1,18 @@ #!/bin/bash # SPDX-License-Identifier: MIT -# omamobile-osk-guard against fake gsettings and pgrep: it turns the keyboard -# back on only when no screensaver runs, waits out one that does, and leaves -# an enabled keyboard alone. +# omamobile-osk-guard against fake gsettings, pgrep, udevadm, omarchy-shell, +# busctl and bluetoothctl and a made-up sysfs: with no keyboard it turns the +# on-screen keyboard back on only when no screensaver runs, waits out one that +# does, and leaves an enabled keyboard alone; a real Bluetooth or USB keyboard +# turns auto-show off (one entry per uniq), the card's "show" mode and a +# lock (any credential) keep it on, and a keyboard that went away is dropped after +# its grace with the mode back to auto. set -euo pipefail cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." fail() { printf 'not ok - %s\n' "$1" >&2; exit 1; } pass() { printf 'ok - %s\n' "$1"; } t=$(mktemp -d); trap 'rm -rf "$t"' EXIT -F=$t/fakes; mkdir -p "$F" +F=$t/fakes; mkdir -p "$F" "$t/home" fake() { printf '#!/bin/bash\n%s\n' "$2" >"$F/$1"; chmod +x "$F/$1"; } fake gsettings 'case $1 in get) cat "$T/osk" ;; @@ -17,10 +21,34 @@ fake gsettings 'case $1 in esac' # A screensaver "runs" for as many pgrep calls as $T/screensaver says fake pgrep 'n=$(cat "$T/screensaver" 2>/dev/null || echo 0); ((n > 0)) || exit 1; echo $((n - 1)) >"$T/screensaver"' -fake sleep ':' -guard() { env T="$t" OMAMOBILE_OSK_GUARD_GRACE=0 PATH="$F:/usr/bin:/bin" bash bin/omamobile-osk-guard "$@" >/dev/null; } +fake udevadm 'exec /usr/bin/sleep 30' +fake omarchy-shell 'cat "$T/locked" 2>/dev/null || echo false' +fake busctl 'echo "busctl $*" >>"$T/log"' +fake bluetoothctl 'echo "bluetoothctl $*" >>"$T/log"' +guard() { + env T="$t" HOME="$t/home" OMAMOBILE_OSK_SYSFS="$t/sys" OMAMOBILE_OSK_UDEVDATA="$t/udev" \ + OMAMOBILE_OSK_GUARD_GRACE=0 OMAMOBILE_OSK_POLL=0 OMAMOBILE_OSK_KEYBOARD_GRACE="${KGRACE:-5}" \ + PATH="$F:/usr/bin:/bin" python3 -I bin/omamobile-osk-guard "$@" >/dev/null +} state() { : >"$t/log"; echo "$1" >"$t/osk"; echo "$2" >"$t/screensaver"; } +st=$t/home/.local/state/omamobile/osk-hwkbd.json +mkdir -p "$t/sys/class/input" "$t/udev" +# node N BUS NAME UNIQ [caps] [virtual]: an event node with its udev data +letters="207f07fc3ff0000" # covers Q..P, A..L, Z..M, space +node() { + local n=$1 dev=$t/sys/devices/$1 + [[ ${6:-} == virtual ]] && dev=$t/sys/devices/virtual/input/$1 + mkdir -p "$dev/id" "$dev/capabilities" + mkdir -p "$t/sys/class/input/event$n" + echo "13:$n" >"$t/sys/class/input/event$n/dev" + ln -sfn "$dev" "$t/sys/class/input/event$n/device" + echo "$2" >"$dev/id/bustype"; echo "$3" >"$dev/name"; echo "$4" >"$dev/uniq"; echo "phys-$n" >"$dev/phys" + echo "${5:-$letters}" >"$dev/capabilities/key" + printf 'E:ID_INPUT=1\nE:ID_INPUT_KEYBOARD=1\n' >"$t/udev/c13:$n" +} +unplug() { rm -rf "$t/sys/class/input/event$1"; } +# ---- the safety net, no keyboard state false 0; guard --once [[ $(cat "$t/osk") == true ]] || fail "off with no screensaver: turned back on" state true 0; guard --once @@ -29,10 +57,133 @@ state false 3; guard --once [[ $(cat "$t/osk") == true && $(cat "$t/screensaver") == 0 ]] || fail "a running screensaver is waited out" pass "the keyboard comes back on only once no screensaver runs" -# Watching: the fake monitor turns the keyboard off and reports it; the +# ---- devices that are not keyboards +node 1 0019 gpio-keys "" # the phone's buttons +node 2 0003 "Virtual keyboard" "" "" virtual # squeekboard's +node 3 0005 "YubiKey OTP+FIDO" "aa:bb:cc:dd:ee:01" +node 4 0005 "BT Mouse" "aa:bb:cc:dd:ee:02" "0 0 0 0 0 0 0 0" +state true 0; guard --once +[[ $(cat "$t/osk") == true && ! -s $t/log ]] || fail "buttons, virtual keyboards, keys and mice are no keyboard" +[[ ! -e $st ]] || fail "no keyboard listed (nothing written)" +pass "gpio-keys, squeekboard's virtual keyboard, a security key and a mouse are not keyboards" + +# ---- a Bluetooth keyboard with two nodes, one uniq (the Dell KB7120W) +node 15 0005 "Dell Keybd Keyboard" "00:00:5E:00:53:01" +node 16 0005 "Dell Keybd" "00:00:5e:00:53:01" +state true 0; guard --once +[[ $(cat "$t/osk") == false ]] || fail "a connected keyboard turns auto-show off" +python3 - "$st" <<'EOF' || fail "one entry per uniq, mode auto" +import json, sys +s = json.load(open(sys.argv[1])) +assert s["mode"] == "auto", s +assert [(k["name"], k["uniq"], k["bus"]) for k in s["keyboards"]] == [("Dell Keybd Keyboard", "00:00:5e:00:53:01", "bluetooth")], s +EOF +# Patch 0006's restore wrote true over it: straight back off, screensaver or not +state true 0; guard --once +[[ $(cat "$t/osk") == false ]] || fail "true written over a connected keyboard goes back off" +pass "a Bluetooth keyboard turns auto-show off, listed once by uniq; a restore to true is undone" + +# ---- the card's modes +state false 0; guard --mode show +[[ $(cat "$t/osk") == true ]] && grep -q 'SetVisible b true' "$t/log" || fail "show: auto-show on and the keyboard shown" +state true 0; guard --once +[[ $(cat "$t/osk") == true ]] || fail "show mode is kept by the watcher" +state true 0; guard --mode hide +[[ $(cat "$t/osk") == false ]] && grep -q 'SetVisible b false' "$t/log" || fail "hide: auto-show off and the keyboard hidden" +pass "Show and Hide set the mode, the setting and the keyboard" + +# ---- the lock: any credential keeps it showable; odd isLocked output counts as locked +echo true >"$t/locked" +state false 0; guard --once +[[ $(cat "$t/osk") == true ]] || fail "locked (PIN or password): the keyboard can come up" +echo false >"$t/locked" +state true 0; guard --once +[[ $(cat "$t/osk") == false ]] || fail "unlocked: auto-show off again" +echo "Error: no shell" >"$t/locked" +state false 0; guard --once +[[ $(cat "$t/osk") == true ]] || fail "unknown isLocked output: treated as locked" +echo false >"$t/locked" +pass "while locked (any credential, or unknown) the on-screen keyboard stays showable" + +# ---- a state entry without a string name is dropped, not a crash +python3 - "$st" <<'EOF2' +import json, sys +s = json.load(open(sys.argv[1])); s["keyboards"].append({"id": "x"}); s["keyboards"].append({"id": "y", "name": 3}) +json.dump(s, open(sys.argv[1], "w")) +EOF2 +state true 0; guard --once || fail "a bad state entry does not stop the guard" +[[ $(cat "$t/osk") == false ]] || fail "bad entries ignored, the real keyboard still counts" +pass "state entries without a string id and name are ignored" + +# ---- a USB keyboard; a virtual one never counts +unplug 15; unplug 16 +node 20 0003 "USB Keyboard" "" +state true 0; KGRACE=0 guard --once +[[ $(cat "$t/osk") == false ]] || fail "a USB keyboard turns auto-show off" +python3 -c 'import json,sys; s=json.load(open(sys.argv[1])); assert [k["name"] for k in s["keyboards"]]==["USB Keyboard"], s' "$st" || fail "the Dell is gone after its grace" +pass "a USB keyboard counts" + +# ---- it goes away: kept for its grace, then dropped and the mode back to auto +guard --mode hide +unplug 20 +state false 0; guard --once +[[ $(cat "$t/osk") == false ]] || fail "a keyboard in its grace still counts" +python3 -c 'import json,sys; s=json.load(open(sys.argv[1])); assert s["mode"]=="hide" and len(s["keyboards"])==1' "$st" || fail "kept with its mode in the grace" +state false 0; KGRACE=0 guard --once +[[ $(cat "$t/osk") == true ]] || fail "after the grace, no keyboard: the keyboard is back on" +python3 -c 'import json,sys; s=json.load(open(sys.argv[1])); assert s=={"keyboards":[],"mode":"auto"}, s' "$st" || fail "dropped, mode auto" +pass "a keyboard that went away is kept for its grace, then the mode goes back to auto" + +# ---- disconnect +: >"$t/log"; guard --disconnect 00:00:5e:00:53:01 +grep -qx 'bluetoothctl disconnect 00:00:5E:00:53:01' "$t/log" || fail "disconnect by MAC, upper case" +: >"$t/log"; guard --disconnect 'x; reboot' 2>/dev/null && fail "a bad address is refused" +[[ ! -s $t/log ]] || fail "nothing run for a bad address" +pass "Disconnect runs bluetoothctl for a valid address only" + +# ---- watching: the fake monitor turns the keyboard off and reports it; the # guard turns it back on, and exits non-zero when the monitor ends, so # systemd restarts it state true 0 guard && fail "the guard exits non-zero when its monitor ends" [[ $(cat "$t/osk") == true && $(grep -c set "$t/log") == 1 ]] || fail "a change the monitor reports is checked" pass "the watch loop restores the keyboard and exits for a restart when the monitor ends" + +# ---- the keyboard goes away under the screensaver: no auto-show written over it +mkdir -p "$t/state2"; st2=$t/state2/osk-hwkbd.json +node 30 0005 "BT Keyboard" "aa:bb:cc:dd:ee:30" +echo '{"keyboards":[],"mode":"auto"}' >"$st2" +python3 - "$t" "$st2" <<'EOF2' || fail "grace and screensaver in the watcher class" +import importlib.util, importlib.machinery, os, sys, time +sys.dont_write_bytecode = True +t, st = sys.argv[1], sys.argv[2] +os.environ.update(T=t, HOME=t + "/home", OMAMOBILE_OSK_SYSFS=t + "/sys", OMAMOBILE_OSK_UDEVDATA=t + "/udev", + OMAMOBILE_OSK_STATE=st, OMAMOBILE_OSK_KEYBOARD_GRACE="5", OMAMOBILE_OSK_GUARD_GRACE="0", + OMAMOBILE_OSK_POLL="2", PATH=t + "/fakes:/usr/bin:/bin") +loader = importlib.machinery.SourceFileLoader("guard", "bin/omamobile-osk-guard") +spec = importlib.util.spec_from_loader("guard", loader); g = importlib.util.module_from_spec(spec); loader.exec_module(g) +open(t + "/osk", "w").write("true\n"); open(t + "/locked", "w").write("false\n") +G = g.Guard(); G.evaluate(100.0) +assert open(t + "/osk").read().strip() == "false", "connected: off" +G.state["mode"] = "hide" +import json; json.dump({"keyboards": G.state["keyboards"], "mode": "hide"}, open(st, "w")) +# Last scan long before the removal: the grace still counts from the removal +os.system("rm -rf " + t + "/sys/class/input/event30") +G.evaluate(200.0) +assert G.state["keyboards"] and G.state["mode"] == "hide", ("kept in its grace", G.state) +G.evaluate(203.0) +assert G.state["keyboards"] and G.state["mode"] == "hide", ("still in the grace 3 s after removal", G.state) +# Screensaver running when the grace ends: nothing written +open(t + "/screensaver", "w").write("5\n") +G.evaluate(205.5) +assert not G.state["keyboards"] and G.state["mode"] == "auto", G.state +assert open(t + "/osk").read().strip() == "false", "no auto-show over the screensaver" +assert G.restore_at is not None, "the safety net waits it out" +EOF2 +pass "the grace runs from the removal; a keyboard gone under the screensaver waits for it to end" + +# ---- stopping the watcher clears the list (the card goes, a hide cannot stick) +state true 0 +guard || true +python3 -c 'import json,sys; s=json.load(open(sys.argv[1])); assert s=={"keyboards":[],"mode":"auto"}, s' "$st" || fail "list cleared on exit" +pass "the watcher clears the keyboard list when it stops" diff --git a/packages/omamobile-shell/test/phone-dictation.lua b/packages/omamobile-shell/test/phone-dictation.lua index 4d646bb78..d111d56f5 100644 --- a/packages/omamobile-shell/test/phone-dictation.lua +++ b/packages/omamobile-shell/test/phone-dictation.lua @@ -11,6 +11,7 @@ local scenario = os.getenv("SCENARIO") local noop = function() end local binds = {} +local kbd = {} local function dsp(name) return function(arg) return { dsp = name, arg = arg } end end hl = { config = noop, window_rule = noop, layer_rule = noop, device = noop, @@ -19,7 +20,15 @@ hl = { for _, b in ipairs(binds) do if b.keys ~= keys then kept[#kept + 1] = b end end binds = kept end, - dsp = { window = { cycle_next = dsp("cycle_next"), bring_to_top = dsp("bring_to_top") }, focus = dsp("focus") }, + dsp = { window = { cycle_next = dsp("cycle_next"), bring_to_top = dsp("bring_to_top") }, focus = dsp("focus"), + exec_cmd = function(c) return c end }, + -- phone.lua must bind no layout switch key (xkb does it): any hl.bind is counted + bind = function(keys) + local h = { keys = keys, on = true } + h.set_enabled = function(self, v) self.on = v end + kbd[#kbd + 1] = h + return h + end, } o = { bind = function(keys, description, dispatcher, opts) @@ -72,4 +81,5 @@ else check(#f9 == 1 and f9[1].dispatcher == "my-own-command" and f9[1].opts.device == nil, "the owner's own F9 bind is left as it is") end end +check(#kbd == 0, "no layout switch bind, the switch key is xkb's") os.exit(failed and 1 or 0) diff --git a/packages/omamobile-shell/test/phone-rules.lua b/packages/omamobile-shell/test/phone-rules.lua index 80340ba78..b1b23a55a 100644 --- a/packages/omamobile-shell/test/phone-rules.lua +++ b/packages/omamobile-shell/test/phone-rules.lua @@ -28,7 +28,14 @@ hl = { for _, b in ipairs(binds) do if b.keys ~= keys then kept[#kept + 1] = b end end binds = kept end, - dsp = { window = { cycle_next = dsp("cycle_next"), bring_to_top = dsp("bring_to_top") }, focus = dsp("focus") }, + dsp = { window = { cycle_next = dsp("cycle_next"), bring_to_top = dsp("bring_to_top") }, focus = dsp("focus"), + exec_cmd = function(c) return c end }, + bind = function(keys, dispatcher, opts) + local b = { keys = keys, dispatcher = dispatcher, opts = opts or {}, enabled = true } + function b:set_enabled(v) self.enabled = v end + binds[#binds + 1] = b + return b + end, } o = { bind = function(keys, description, dispatcher, opts) @@ -157,5 +164,14 @@ end check(#find("ALT + TAB") == 2 and find("ALT + TAB")[1].dispatcher.dsp == "cycle_next", "Alt + Tab keeps both of Omarchy's actions") local f9 = find("F9", true) check(#f9 == 1 and f9[1].dispatcher == "voxtype record stop", "F9 still stops Voxtype on release") +-- The layout switch key is an xkb grp: option, so phone.lua binds nothing for it +local sw = 0 +for _, b in ipairs(binds) do + local d, k = tostring(b.dispatcher), tostring(b.keys) + if d:find("switchxkblayout", 1, true) or d:find("omamobile-keyboard-switch", 1, true) + or k:find("SHIFT_L", 1, true) or k:find("ALT_L", 1, true) or k:find("CTRL_L", 1, true) + or k:find("code:66", 1, true) then sw = sw + 1 end +end +check(sw == 0, "no layout switch bind") os.exit(failed and 1 or 0) diff --git a/packages/omamobile-shell/test/status-model.js b/packages/omamobile-shell/test/status-model.js index b239fb966..86a5afc86 100644 --- a/packages/omamobile-shell/test/status-model.js +++ b/packages/omamobile-shell/test/status-model.js @@ -70,3 +70,18 @@ assert.strictEqual(M.unreadStored("[{\"ts\": 5", 0), 0, "torn") assert.strictEqual(M.unreadStored(JSON.stringify([null, 4, { ts: "x" }, { ts: -1 }, {}, { ts: 5 }]), 0), 1) assert.strictEqual(M.unreadStored(undefined, 0), 0) console.log("ok - status model: unread notifications on Omarchy 4.5") + +const dev = (o) => JSON.stringify({ keyboards: o }) +const osk = { name: "hl-virtual-keyboard-squeekboard", layout: "us", active_layout_index: 0, main: false } +assert.strictEqual(M.layoutLabel(dev([osk])), "", "squeekboard alone: no label") +assert.strictEqual(M.layoutLabel(dev([osk, { name: "dell", layout: "us", active_layout_index: 0, main: true }])), "", "one layout: no label") +assert.strictEqual(M.layoutLabel(dev([osk, { name: "dell", layout: "us,gr", active_layout_index: 1, main: true }])), "GR") +assert.strictEqual(M.layoutLabel(dev([{ name: "x-consumer-control", layout: "us,gr", active_layout_index: 1 }, + { name: "dell", layout: "gb,de", active_layout_index: 0 }])), "EN", "pseudo-keyboards skipped, gb is EN") +assert.strictEqual(M.layoutLabel("not json"), "") +assert.strictEqual(M.layoutLabel(dev([{ name: "dell", layout: "us,gr", active_layout_index: 5 }])), "", "index out of range") +// main pick: virtual main ignored, gpio-keys and one-layout keyboards passed over +assert.strictEqual(M.layoutLabel(dev([{ name: "hl-virtual-keyboard-squeekboard", layout: "us,gr", active_layout_index: 0, main: true }, + { name: "gpio-keys", layout: "us,gr", active_layout_index: 0 }, { name: "single", layout: "us", active_layout_index: 0 }, + { name: "dell", layout: "us,gr", active_layout_index: 1 }])), "GR", "first real keyboard with 2+ layouts") +console.log("ok - status model: keyboard layout label")