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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions packages/omamobile-shell/bin/omamobile-keyboards
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Print the names of the real keyboards connected, one per line.

The same rule as omamobile-settings' lock page (#866): an input device udev
marks ID_INPUT_KEYBOARD=1 on the Bluetooth bus (0005) or on USB (0003)
outside /devices/virtual/input, with the letter keys and space, and a name
that is not empty and not a known security token or barcode scanner. The
phone's own keys (gpio-keys, the power button) and the on-screen keyboard
never count. The bar's layout label matches these names against
`hyprctl -j devices` (Hyprland lowercases them and turns spaces into '-').

Test hooks: OMAMOBILE_KEYBOARDS_SYSFS and OMAMOBILE_KEYBOARDS_UDEVDATA
stand in for /sys and /run/udev/data.
"""

import os
import re
import struct

SYSFS = os.environ.get("OMAMOBILE_KEYBOARDS_SYSFS", "/sys")
UDEV = os.environ.get("OMAMOBILE_KEYBOARDS_UDEVDATA", "/run/udev/data")
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
NOT_KEYBOARDS = re.compile(r"yubikey|yubico|nitrokey|solokey|onlykey|token|barcode|scanner", re.I)


def read(path):
try:
with open(path) as f:
return f.read().strip()
except OSError:
return None


def keyboards():
base = os.path.join(SYSFS, "class/input")
try:
events = sorted(os.listdir(base))
except OSError:
return []
found = []
for ev in events:
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 all(bits >> k & 1 for k in NEEDED) and name not in found:
found.append(name)
return found


if __name__ == "__main__":
for name in keyboards():
print(name)
112 changes: 111 additions & 1 deletion packages/omamobile-shell/plugins/omamobile.bar/Bar.qml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -98,6 +99,99 @@ Item {
}
Timer { id: cellRestart; interval: 5000; onTriggered: cellWatch.running = true }

// The hardware keyboard's layout (EN, GR...) beside the clock, only while
// a real keyboard has more than one layout. A switch is read from the
// activelayout event itself (keyboard,description, via event.parse(2)), as
// Omarchy 4.5's bar widget does; squeekboard's own events are ignored.
// The devices are read (omamobile-keyboards for which ones are real
// keyboards, by #866's bus/key rule, then `hyprctl -j devices`) at start,
// after configreloaded, when an activelayout comes from a keyboard not in
// the last read (one connected later), and every 10 s while the label
// shows, so it goes away when the keyboard does. A read that started
// before a switch keeps the switch's layout. A switch event counts only
// from a keyboard the last read found real; one from a device it has not
// seen at all starts a read, and one from a device it saw but didn't find
// real starts one 10 s after the last read at the earliest (deferred, not
// dropped: udev may not have tagged a keyboard yet at the first read). If
// omamobile-keyboards is missing or fails, no label shows and the log says
// why, once. `xkbcli list` runs once, when
// a label is first needed.
property int layoutCount: 0
property string layoutDescription: ""
property var layoutBriefs: ({})
property var layoutKeyboards: []
property var layoutSeen: []
property bool layoutWarned: false
property double layoutReadMs: 0
property bool layoutReread: false
property int layoutSwitches: 0
readonly property string layoutLabel: layoutCount > 1 ? StatusModel.shortLabel(layoutDescription, layoutBriefs) : ""
onLayoutCountChanged: if (layoutCount > 1 && !briefsRead.ran) { briefsRead.ran = true; briefsRead.running = true }
function readLayouts() {
if (layoutRead.running) layoutReread = true
else layoutRead.running = true
}
Process {
id: layoutRead
property int switchesAtStart: 0
command: ["sh", "-c", "omamobile-keyboards || { echo; echo " + StatusModel.keyboardsFailed + "; }; echo " + StatusModel.readSeparator + "; exec hyprctl -j devices"]
running: true
onRunningChanged: if (running) { switchesAtStart = root.layoutSwitches; root.layoutReadMs = Date.now() }
stdout: StdioCollector {
waitForEnd: true
onStreamFinished: {
const r = StatusModel.splitRead(text)
const st = r ? StatusModel.layoutState(r.devices, r.real) : null
if (!st) return
if (r.failed && !root.layoutWarned) {
root.layoutWarned = true
console.warn("bar: omamobile-keyboards is missing or failed, so no keyboard layout label")
}
root.layoutCount = st.count
// a switch's event arrived while this read ran: its layout is newer
if (layoutRead.switchesAtStart === root.layoutSwitches) root.layoutDescription = st.description
root.layoutKeyboards = st.names
root.layoutSeen = (StatusModel.layoutState(r.devices) || st).names
}
}
onExited: if (root.layoutReread) { root.layoutReread = false; running = true }
}
Timer {
interval: 10000
repeat: true
running: root.layoutLabel !== ""
onTriggered: root.readLayouts()
}
// a seen-but-not-real device's event: read again when 10 s have passed
// since the last read, so the switch isn't lost
Timer { id: layoutLater; onTriggered: root.readLayouts() }
Process {
id: briefsRead
property bool ran: false
command: ["xkbcli", "list", "--load-exotic"]
stdout: StdioCollector {
waitForEnd: true
onStreamFinished: root.layoutBriefs = StatusModel.layoutBriefs(text)
}
}
Connections {
target: Hyprland
function onRawEvent(event) {
if (!event) return
if (event.name !== "activelayout" && event.name !== "configreloaded") return
const fields = event.name === "activelayout" && typeof event.parse === "function" ? event.parse(2) : event.data
if (event.name === "activelayout") {
const d = StatusModel.eventLayout(fields, root.layoutKeyboards)
if (d !== null) { root.layoutDescription = d; root.layoutSwitches++ }
}
if (StatusModel.needsDeviceRead(event.name, fields, root.layoutSeen)) root.readLayouts()
else if (StatusModel.needsDeviceRead(event.name, fields, root.layoutKeyboards) && !layoutLater.running) {
layoutLater.interval = Math.max(0, 10000 - (Date.now() - root.layoutReadMs))
layoutLater.start()
}
}
}

// 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).
Expand Down Expand Up @@ -306,14 +400,30 @@ 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 {
id: callChipPill
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)
Expand Down
112 changes: 111 additions & 1 deletion packages/omamobile-shell/plugins/omamobile.bar/StatusModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,11 +145,121 @@ function batteryIcon(percent, charging, full) {
return charging ? chargingIcons[index] : defaultIcons[index]
}

// The keyboard layout label, the way Omarchy 4.5's own bar widget makes it
// (shell/plugins/bar/widgets/KeyboardLayoutModel.js): xkb's short code
// ("brief", from `xkbcli list`) for the layout's description, else the first
// word of the description, capped at 3 characters.
function layoutBriefs(text) {
var briefs = {}
var brief = ""
String(text || "").split("\n").forEach(function(line) {
if (/^\s*- /.test(line)) brief = ""
var field = line.match(/^ (brief|description): (.*)$/)
if (!field) return
if (field[1] === "brief") brief = field[2].replace(/^'|'$/g, "")
else if (brief) { briefs[field[2]] = brief; brief = "" }
})
return briefs
}
function shortLabel(description, briefs) {
if (!description) return ""
var brief = (briefs || {})[description]
var label = typeof brief === "string" && brief ? brief.split("-")[0] : String(description).split(/\s+/)[0]
return label.substring(0, 3).toUpperCase()
}
// Keyboards nobody types on: squeekboard's virtual keyboard and pseudo ones.
var untypedKeyboards = /^hl-virtual-keyboard|consumer-control|power-button|sleep-button|lid-switch|video-bus|radio-control|gpio-keys/
function typedKeyboard(name) {
name = String(name || "")
return name !== "" && !untypedKeyboards.test(name)
}
// Hyprland's activelayout event is "keyboard,description": the layout is read
// from the event itself, no `hyprctl` per switch. `fields` is event.parse(2)
// where Quickshell has it (a description can hold a comma), else the raw
// data split at the first comma. null for a keyboard nobody types on
// (squeekboard sends these while the on-screen keyboard is used). With
// `real` (the names of the real keyboards from the last read) a keyboard
// not among them is null too, the same rule as the devices read (#866's
// bus/key check), so a phone key device the name list misses never sets it.
function eventFields(fields) {
if (Array.isArray(fields)) return fields.length >= 2 ? [String(fields[0]), String(fields[1])] : null
var s = String(fields || "")
var i = s.indexOf(",")
return i < 0 ? null : [s.slice(0, i), s.slice(i + 1)]
}
function eventLayout(fields, real) {
var f = eventFields(fields)
if (!f || !typedKeyboard(f[0])) return null
if (Array.isArray(real) && real.indexOf(f[0]) < 0) return null
return f[1]
}
// Hyprland's device names: the kernel's name lowercased, with space, ',' and
// newline as '-' (deviceNameToInternalString).
function hyprName(name) {
return String(name || "").toLowerCase().replace(/[ ,\n]/g, "-")
}
// Two input devices with one name get "-1", "-2", ... appended by Hyprland.
function isRealName(real, name) {
var n = String(name)
return real.some(function(r) {
return n === r || (n.length > r.length + 1 && n.indexOf(r + "-") === 0 && /^[0-9]+$/.test(n.slice(r.length + 1)))
})
}
// The bar's one read: `omamobile-keyboards` (the real keyboards, #866's
// bus/key rule), a separator line, then `hyprctl -j devices`. When
// omamobile-keyboards is missing or fails, the read has `keyboardsFailed`
// in place of names: no keyboard counts (the phone's keys must never show
// the label) and `failed` is true so the bar can say why in its log.
var readSeparator = "--hyprctl--"
var keyboardsFailed = "--keyboards-failed--"
function splitRead(text) {
var s = String(text || "")
var i = s.indexOf(readSeparator + "\n")
if (i < 0) return null
var lines = s.slice(0, i).split("\n").filter(function(l) { return l !== "" })
var failed = lines.indexOf(keyboardsFailed) >= 0
var real = failed ? [] : lines.map(hyprName)
return { real: real, failed: failed, devices: s.slice(i + readSeparator.length + 1) }
}
// From `hyprctl -j devices` (at start, after a config reload, for a keyboard
// not seen before, and every few seconds while the label shows):
// {count, description, names} of the keyboard furthest along its list, the
// one being typed on (Omarchy's rule). With `real` (hyprName'd names from
// omamobile-keyboards) only those count, so the phone's own key devices
// never do, whatever they are called; without it the name list decides.
function layoutState(text, real) {
var kbs
try { kbs = (JSON.parse(text) || {}).keyboards } catch (e) { return null }
if (!Array.isArray(kbs)) return null
var typed = kbs.filter(function(k) {
return k && typedKeyboard(k.name) && (!Array.isArray(real) || isRealName(real, k.name))
})
var names = typed.map(function(k) { return String(k.name) })
if (!typed.length) return { count: 0, description: "", names: names }
var kb = typed.reduce(function(a, k) { return (k.active_layout_index || 0) > (a.active_layout_index || 0) ? k : a }, typed[0])
var count = String(kb.layout || "").split(",").filter(function(l) { return l !== "" }).length
return { count: count, description: String(kb.active_keymap || ""), names: names }
}
// Whether a Hyprland event means `hyprctl -j devices` must be read again:
// a config reload, or an activelayout from a typed keyboard not seen in the
// last read (one plugged in or paired later; Hyprland has no device-added
// event on its socket). The bar also calls it with the real keyboards as
// `known`, for a device it saw but didn't count (read again, throttled).
function needsDeviceRead(name, fields, known) {
if (name === "configreloaded") return true
if (name !== "activelayout") return false
var f = eventFields(fields)
return !!f && typedKeyboard(f[0]) && (known || []).indexOf(f[0]) < 0
}

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,
layoutBriefs: layoutBriefs, shortLabel: shortLabel, eventLayout: eventLayout, layoutState: layoutState,
needsDeviceRead: needsDeviceRead, eventFields: eventFields, hyprName: hyprName, splitRead: splitRead,
readSeparator: readSeparator, keyboardsFailed: keyboardsFailed
}
}
1 change: 1 addition & 0 deletions packages/omamobile-shell/test/all
Original file line number Diff line number Diff line change
Expand Up @@ -994,6 +994,7 @@ if command -v node >/dev/null; then
node test/status-model.js >/dev/null || { node test/status-model.js; fail "status bar model"; }
node test/battery-state.js || fail "battery state bindings"
fi
python3 -B test/keyboards.py || fail "omamobile-keyboards"
python3 -B -c 'import ast,sys; ast.parse(open(sys.argv[1]).read())' bin/omamobile-cell-watch || fail "omamobile-cell-watch parses"
if command -v dbus-run-session >/dev/null; then
if ! out=$(dbus-run-session -- python3 -B test/cell-watch.py 2>&1); then
Expand Down
Loading