diff --git a/README.md b/README.md index 3d5efb8..86531a9 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ so the shell stays free of setup-specific code. | Plugin | What it does | | --- | --- | +| [`mx-keymap`](mx-keymap) | Keyboard cheat sheet drawn from a keymap repo (keymap-drawer / ZMK / QMK); redraws when you push a change. | | [`mx-screen-recorder`](mx-screen-recorder) | Fork of the Noctalia screen-recorder: always records DP-5, replay autostarts, right-click-only bar controls. | Install one plugin, or every plugin in the repo: diff --git a/mx-keymap/BarWidget.qml b/mx-keymap/BarWidget.qml new file mode 100644 index 0000000..51a0d3d --- /dev/null +++ b/mx-keymap/BarWidget.qml @@ -0,0 +1,48 @@ +import QtQuick +import Quickshell +import qs.Commons +import qs.Ui + +// Bar button for the keymap cheat sheet. Click opens the sheet under it; the +// icon lights up when the keymap changed since you last looked. +BarWidget { + id: root + moduleName: "mx-keymap" + + readonly property var service: bar && bar.shell ? bar.shell.serviceFor(moduleName) : null + readonly property bool opened: panel.opened + readonly property bool popoutSwitchClosing: panel.popoutSwitchClosing + + implicitWidth: button.implicitWidth + implicitHeight: button.implicitHeight + + function open() { panel.open() } + function close() { panel.close() } + function toggle() { panel.opened ? panel.close() : panel.open() } + function closeForPopoutSwitch() { panel.closeForPopoutSwitch() } + + onServiceChanged: if (service) service.configure(settings) + onSettingsChanged: if (service) service.configure(settings) + + BarIconButton { + id: button + anchors.fill: parent + bar: root.bar + text: "󰌌" + tooltipText: root.service && root.service.unseen ? "Keymap: updated" : "Keymap" + active: !!root.service && root.service.unseen + onPressed: function(mouseButton) { + if (mouseButton === Qt.LeftButton) root.toggle() + else if (mouseButton === Qt.RightButton && root.service) root.service.refresh(true) + } + } + + SheetPanel { + id: panel + bar: root.bar + moduleName: root.moduleName + settings: root.settings + anchorItem: button + service: root.service + } +} diff --git a/mx-keymap/README.md b/mx-keymap/README.md new file mode 100644 index 0000000..33eec58 --- /dev/null +++ b/mx-keymap/README.md @@ -0,0 +1,73 @@ +# Keymap Cheat Sheet + +A keyboard button in the bar that opens a cheat sheet of your keyboard's layers, +drawn from the keymap in a git repository (default: `xnmrph/corne`). Push a +change to the keymap and the sheet redraws by itself; the bar icon lights up +until you look at it. + +- **Overview** shows the base layer in the middle of each key and four more + layers in its corners, each in its own colour (the little key in each tab + shows which corner). The colours follow the theme accent. +- **A layer tab** shows that layer on its own. Keys that fall through to the + base layer are dimmed, the key you are holding to get there says *held*, and + keys that switch layers take that layer's colour. Pointing at a tab + previews it. +- **Combos** for the layer on screen are listed underneath; pointing at one + lights up its keys. Layers you reach by holding two layers (ZMK conditional + layers) are listed too. + +Keys while it is open: arrow keys / Tab (or H/L) switch layers, `0` is the +overview, `1`–`9` pick a layer, `R` checks the repo now, Esc closes. +Right-clicking the bar icon also checks the repo. + +## Where the keymap comes from + +Settings (Settings → Bar → Keymap): + +| Setting | | +| --- | --- | +| Keymap repository | `owner/name` on GitHub, or any git URL / local path. Private repos use your git credentials. | +| Branch | Blank: the default branch. | +| Keymap file | Blank: found automatically. | +| Check for changes every | Minutes between checks (default 2). It also checks when you open the sheet. | +| Opens on | Overview or the base layer. | + +The file is found in this order: + +1. **keymap-drawer YAML** (`keymap parse` output). With several, the one with + the most layers wins, so `corne-layers.yaml` beats the merged `corne.yaml`. + Its legends are already pretty, so this is the best source. +2. **ZMK `.keymap`**, parsed directly (`&kp`, `&mo`, `<`, `&mt`, `&bt`, + mouse keys, combos, conditional layers; other behaviours show their name). +3. **QMK `keymap.json`**. + +The physical layout is drawn from the key count: 42 and 36 keys as a Corne +(3×6+3 / 3×5+3), 34 and 40 as split boards with two thumb keys; anything else +as a plain grid. + +## How it watches the repo + +A check is a `git ls-remote` (no GitHub API, so no rate limit). Only a new +commit fetches: the repo is kept as a shallow clone in +`~/.cache/glassMxrph/keymap/`, together with the last parsed sheet, so the +sheet shows at once after a restart and while offline. + +When the newest commit changed the `.keymap` but not the keymap-drawer YAML, +and a workflow in the repo redraws it (like `xnmrph/corne`'s `draw.yml`), the +sheet says it is waiting for the redraw and checks every 20 seconds until the +new YAML lands. + +## IPC + +```sh +quickshell ipc --path call keymap toggle +quickshell ipc --path call keymap layer Symbols # open on a layer ("overview" too) +quickshell ipc --path call keymap refresh +quickshell ipc --path call keymap status +``` + +With glassMxrph: `glassmxrph plugin toggle mx-keymap`. + +## Tests + +`python3 tests/keymap_test.py` diff --git a/mx-keymap/Service.qml b/mx-keymap/Service.qml new file mode 100644 index 0000000..bd0c191 --- /dev/null +++ b/mx-keymap/Service.qml @@ -0,0 +1,139 @@ +import QtQuick +import Quickshell +import Quickshell.Io + +// Shared state for every Keymap widget (one per bar): the parsed sheet and +// the repo watch. helpers/keymap.py does the git work; a check is a +// `git ls-remote`, and only a new commit fetches and parses again. +Item { + id: root + + property var shell: null + property string pluginId: "mx-keymap" + + property var sheet: null + property bool busy: false + property string error: "" + // Changed since the sheet was last on screen: the bar icon lights up. + property bool unseen: false + property int openPanels: 0 + readonly property bool panelOpen: openPanels > 0 + property real lastCheck: 0 + // A layer asked for over IPC; the panel picks it up when it opens. + property string wantedView: "" + signal showView(string layer) + + // Where to look, from the widget settings. + property string repository: "" + property string branch: "" + property string path: "" + property int checkMinutes: 2 + + readonly property string helper: decodeURIComponent(Qt.resolvedUrl("helpers/keymap.py").toString().replace(/^file:\/\//, "")) + + function configure(settings) { + const s = settings || {} + const repo = String(s.repository === undefined ? "xnmrph/corne" : s.repository).trim() + const br = String(s.branch || "").trim() + const p = String(s.path || "").trim() + checkMinutes = Math.max(1, Number(s.checkMinutes) || 2) + if (repo === repository && br === branch && p === path) return + repository = repo + branch = br + path = p + sheet = null + error = "" + call("load", false) + call("check", false) + } + + function refresh(force) { call("check", !!force) } + function checkIfStale() { + if (Date.now() - lastCheck > 30000) call("check", false) + } + + // One helper run at a time; a request made meanwhile runs after it. + property var queued: null + function call(op, force) { + const request = { op: op, repo: repository, branch: branch, path: path, force: force } + if (job.running) { + // A check supersedes a load; a forced check supersedes a plain one. + if (!queued || op === "check") queued = { op: op, force: force || (queued && queued.force) } + return + } + if (op === "check") { busy = true; lastCheck = Date.now() } + job.request = request + job.command = ["python3", helper, JSON.stringify(request)] + job.running = true + } + + Process { + id: job + property var request: ({}) + stdout: StdioCollector { id: out } + stderr: StdioCollector { id: err } + onExited: function(code) { + let result + try { result = JSON.parse(out.text) } + catch (e) { result = { ok: false, error: (err.text || "The keymap helper failed").trim().split("\n").pop() } } + const req = job.request + // Settings changed while it ran: drop the answer. + const current = req.repo === root.repository && req.branch === root.branch && req.path === root.path + if (current) { + if (!result.ok) { + if (req.op === "check") root.error = result.error || "Could not read the keymap" + } else { + if (req.op === "check") root.error = "" + if (result.sheet) { + const had = !!root.sheet + root.sheet = result.sheet + if (result.changed && had && !root.panelOpen) root.unseen = true + } + } + } + if (req.op === "check") root.busy = false + const next = root.queued + root.queued = null + if (next) Qt.callLater(() => root.call(next.op, next.force)) + } + } + + onPanelOpenChanged: { + if (!panelOpen) return + unseen = false + checkIfStale() + } + + // Poll faster while the repo's CI redraws a keymap-drawer file for a new keymap. + readonly property bool pending: !!sheet && !!sheet.pending + Timer { + interval: root.pending ? 20000 : root.checkMinutes * 60000 + repeat: true + running: root.repository !== "" + onTriggered: root.call("check", false) + } + + IpcHandler { + target: "keymap" + function toggle(): void { + if (root.shell) root.shell.toggle(root.pluginId, "") + } + // Open the sheet on a layer by name ("overview" for every layer at once). + function layer(name: string): void { + root.wantedView = name + if (root.shell && !root.panelOpen) root.shell.summon(root.pluginId, "") + root.showView(name) + } + // Fetch and parse again even when the repo has not changed. + function refresh(): void { + root.refresh(true) + } + function status(): string { + return JSON.stringify({ + repository: root.repository, busy: root.busy, error: root.error, unseen: root.unseen, + open: root.panelOpen, sha: root.sheet ? root.sheet.sha : "", source: root.sheet ? root.sheet.source : "", + layers: root.sheet ? root.sheet.layers.map(l => l.name) : [], pending: root.pending + }) + } + } +} diff --git a/mx-keymap/SheetPanel.qml b/mx-keymap/SheetPanel.qml new file mode 100644 index 0000000..bf229b0 --- /dev/null +++ b/mx-keymap/SheetPanel.qml @@ -0,0 +1,666 @@ +pragma ComponentBehavior: Bound +import QtQuick +import Quickshell +import qs.Commons +import qs.Ui + +// The cheat sheet: the keyboard drawn from the repo's keymap. Overview puts +// the base layer in the middle of each key and four more layers in its +// corners, each in its own colour; a layer tab shows that layer alone, with +// keys that fall through to the base layer dimmed. Combos sit underneath; +// pointing at one lights up its keys. +Panel { + id: root + + property Item anchorItem: null + property var service: null + + readonly property var sheet: service ? service.sheet : null + readonly property var layers: sheet && sheet.layers ? sheet.layers : [] + readonly property var layoutKeys: sheet && sheet.layout ? sheet.layout.keys : [] + readonly property var base: layers.length ? layers[0].keys : [] + + // -1 is the overview; otherwise a layer index. Pointing at a tab previews it. + property int view: -1 + property int preview: -2 + readonly property int shown: preview > -2 ? preview : view + property var highlight: [] + + // Corner of each overview layer (layers 1..4), as in the repo's own drawing. + readonly property var places: ["bl", "tr", "tl", "br"] + + // Board geometry in key units. + readonly property real unitsW: layoutKeys.reduce((m, k) => Math.max(m, k.x + 1), 0) + readonly property real unitsH: layoutKeys.reduce((m, k) => Math.max(m, k.y + 1), 0) + 0.2 + readonly property real unit: Math.min(Style.space(66), unitsW > 0 ? (card.availableCardWidth - card.padding * 2) / unitsW : Style.space(66)) + readonly property real gap: Math.max(3, Math.round(unit * 0.07)) + readonly property int cardWidth: Math.max(Style.space(560), Math.ceil(unitsW * unit)) + card.padding * 2 + + function layerIndex(name) { + if (!name) return -1 + for (let i = 0; i < layers.length; i++) if (layers[i].name === name) return i + return -1 + } + // Layer colours follow the theme accent, spread around the colour wheel. + readonly property var hueSteps: [0, 0.5, 0.27, 0.77, 0.13, 0.63, 0.38, 0.88] + function layerColor(i) { + if (i <= 0) return Color.foreground + const h0 = Color.accent.hslHue < 0 ? 0.6 : Color.accent.hslHue + const h = (h0 + hueSteps[(i - 1) % hueSteps.length]) % 1 + return Qt.hsla(h, 0.68, 0.72, 1) + } + function legend(k) { return k && k.type !== "trans" && k.type !== "held" ? String(k.t || "") : "" } + + // What one key shows in the current view. + function cellFor(i) { + const b = base[i] || {} + const thumb = !!(layoutKeys[i] && layoutKeys[i].thumb) + const out = { t: legend(b), s: b.s || "", h: b.h || "", kind: b.type || "", corners: [], tint: -1, holdTint: -1 } + if (shown >= 0 && shown < layers.length && shown > 0) { + const k = layers[shown].keys[i] || {} + if (k.type === "trans") { out.kind = "trans"; out.s = ""; out.h = "" } + else if (k.type === "held") { out.kind = "held"; out.t = legend(b); out.s = ""; out.h = "" } + else { out.t = legend(k); out.s = k.s || ""; out.h = k.h || ""; out.kind = k.type || "" } + } else if (shown < 0 && !thumb) { + for (let j = 1; j <= Math.min(4, layers.length - 1); j++) { + const t = legend(layers[j].keys[i]) + if (t && t !== out.t) out.corners.push({ place: places[j - 1], text: t, color: layerColor(j) }) + } + if (out.corners.length) out.s = "" + } + out.tint = layerIndex(out.t) + out.holdTint = layerIndex(out.h) + if (out.kind === "held") out.tint = shown + return out + } + readonly property var cells: { + const list = [] + for (let i = 0; i < layoutKeys.length; i++) list.push(cellFor(i)) + return list + } + + readonly property string shownName: shown >= 0 && shown < layers.length ? layers[shown].name : (layers.length ? layers[0].name : "") + readonly property var combos: (sheet && sheet.combos ? sheet.combos : []).filter(c => !c.layers.length || c.layers.indexOf(shownName) >= 0) + readonly property var layerCombos: sheet && sheet.layerCombos ? sheet.layerCombos : [] + + function select(v) { + view = Math.max(-1, Math.min(layers.length - 1, v)) + preview = -2 + } + function showNamed(name) { + const i = String(name).toLowerCase() === "overview" ? -1 : layers.findIndex(l => l.name.toLowerCase() === String(name).toLowerCase()) + if (i >= -1) select(i) + } + Connections { + target: root.service + function onShowView(layer) { if (root.opened) root.showNamed(layer) } + } + + function ago(seconds) { + if (!seconds) return "" + const s = Math.max(0, Math.round(Date.now() / 1000 - seconds)) + if (s < 60) return "just now" + if (s < 3600) return Math.floor(s / 60) + " min ago" + if (s < 86400) return Math.floor(s / 3600) + " h ago" + const d = Math.floor(s / 86400) + return d === 1 ? "yesterday" : d + " days ago" + } + // Arrow glyphs are drawn small in most UI fonts; give them more room. + function isArrow(text) { return /^[←↑→↓⇡⇣⇠⇢]+$/.test(String(text)) } + function sizeFor(text) { + if (isArrow(text)) return Math.round(unit * 0.42) + const n = String(text).length + if (n <= 1) return Math.round(unit * 0.34) + if (n <= 3) return Math.round(unit * 0.25) + if (n <= 5) return Math.round(unit * 0.21) + return Math.round(unit * 0.18) + } + + onOpenedChanged: { + if (!service) return + service.openPanels += opened ? 1 : -1 + if (opened) { + view = setting("startView", "overview") === "base" ? 0 : -1 + if (service.wantedView) showNamed(service.wantedView) + service.wantedView = "" + preview = -2 + highlight = [] + } + } + Component.onDestruction: if (opened && service) service.openPanels-- + + // Relative times stay fresh while it is open. + Timer { + id: clock + property int tick: 0 + interval: 30000 + repeat: true + running: root.opened + onTriggered: tick++ + } + + KeyboardPanel { + id: card + anchorItem: root.anchorItem + owner: root + bar: root.bar + open: root.opened + focusTarget: keys + contentWidth: card.fittedContentWidth(root.cardWidth) + contentHeight: card.fittedContentHeight(column.implicitHeight) + + Item { + id: keys + anchors.fill: parent + focus: true + Keys.onPressed: function(event) { + const n = root.layers.length + if (event.key === Qt.Key_Escape) root.close() + else if (event.key === Qt.Key_Right || event.key === Qt.Key_Tab || event.key === Qt.Key_L) + root.select(root.view + 1 >= n ? -1 : root.view + 1) + else if (event.key === Qt.Key_Left || event.key === Qt.Key_Backtab || event.key === Qt.Key_H) + root.select(root.view - 1 < -1 ? n - 1 : root.view - 1) + else if (event.key === Qt.Key_0 || event.key === Qt.Key_QuoteLeft) root.select(-1) + else if (event.key >= Qt.Key_1 && event.key <= Qt.Key_9 && event.key - Qt.Key_1 < n) root.select(event.key - Qt.Key_1) + else if (event.key === Qt.Key_R && root.service) root.service.refresh(true) + else return + event.accepted = true + } + } + + Column { + id: column + width: parent.width + spacing: Style.spacing.xxl + + // Header: name, where it came from, actions. + Item { + width: parent.width + height: Math.max(titleCol.implicitHeight, actions.implicitHeight) + Row { + anchors.left: parent.left + anchors.verticalCenter: parent.verticalCenter + spacing: Style.spacing.xl + Text { + anchors.verticalCenter: parent.verticalCenter + text: "󰌌" + color: Color.accent + font.family: Style.font.family + font.pixelSize: Style.font.displayLarge + } + Column { + id: titleCol + anchors.verticalCenter: parent.verticalCenter + spacing: Style.spacing.xxs + Row { + spacing: Style.spacing.lg + Text { + id: titleText + text: "Keymap" + color: Color.foreground + font.family: Style.font.family + font.pixelSize: Style.font.heading + font.bold: true + } + Text { + anchors.baseline: titleText.baseline + text: root.sheet ? root.sheet.repo : (root.service ? root.service.repository : "") + color: Color.muted + font.family: Style.font.family + font.pixelSize: Style.font.body + } + } + Text { + text: { + clock.tick + const s = root.sheet + if (root.service && root.service.error) return root.service.error + if (!s) return root.service && root.service.busy ? "Reading the repository…" : "" + if (s.pending) return "Keymap changed, waiting for the repo to redraw it…" + const parts = [] + if (s.committed) parts.push("changed " + root.ago(s.committed)) + if (s.sha) parts.push(s.sha.slice(0, 7)) + if (s.subject) parts.push(s.subject.replace(/^\[Draw\]\s*/, "")) + return parts.join(" · ") + } + width: Math.min(implicitWidth, column.width - actions.width - Style.space(80)) + elide: Text.ElideRight + color: root.service && root.service.error ? Color.urgent : root.sheet && root.sheet.pending ? Color.accent : Color.muted + font.family: Style.font.family + font.pixelSize: Style.font.caption + } + } + } + Row { + id: actions + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + spacing: Style.spacing.sm + Button { + iconText: "󰑐" + iconSpinning: !!root.service && root.service.busy + tooltipText: "Check the repo now (R)" + onClicked: if (root.service) root.service.refresh(true) + } + Button { + visible: !!root.sheet && !!root.sheet.web + iconText: "󰊤" + tooltipText: "Open the repository" + onClicked: { + const s = root.sheet + const url = s.web + (s.source ? "/blob/" + (s.branch || s.sha) + "/" + s.source : "") + Quickshell.execDetached(["xdg-open", url]) + root.close() + } + } + Button { + iconText: "󰅖" + tooltipText: "Close" + onClicked: root.close() + } + } + } + + // Layer tabs. The little key in each shows where that layer sits in the overview. + Flow { + id: tabs + width: parent.width + spacing: Style.spacing.md + visible: root.layers.length > 0 + Repeater { + model: root.layers.length + 1 + delegate: Rectangle { + id: tab + required property int index + readonly property int idx: index - 1 + readonly property bool selected: root.view === idx + readonly property color tone: idx < 0 ? Color.accent : root.layerColor(idx) + readonly property string place: idx >= 1 && idx <= 4 ? root.places[idx - 1] : idx === 0 ? "c" : "" + width: tabRow.implicitWidth + Style.spacing.xxl * 2 + height: Style.space(30) + radius: height / 2 + color: selected ? Qt.alpha(tone, 0.2) : tabMouse.containsMouse ? Qt.alpha(Color.foreground, 0.07) : Qt.alpha(Color.foreground, 0.03) + border.width: 1 + border.color: selected ? Qt.alpha(tone, 0.55) : Qt.alpha(Color.foreground, 0.08) + Behavior on color { ColorAnimation { duration: 120 } } + + Row { + id: tabRow + anchors.centerIn: parent + spacing: Style.spacing.md + // Mini key: a dot in this layer's corner (centre for the base layer). + Rectangle { + anchors.verticalCenter: parent.verticalCenter + visible: tab.idx >= 0 + width: Style.space(13) + height: width + radius: Style.space(3) + color: "transparent" + border.width: 1 + border.color: Qt.alpha(tab.tone, 0.6) + Rectangle { + width: Style.space(5) + height: width + radius: width / 2 + color: tab.tone + x: tab.place === "tl" || tab.place === "bl" ? Style.space(2) : tab.place === "tr" || tab.place === "br" ? parent.width - width - Style.space(2) : (parent.width - width) / 2 + y: tab.place === "tl" || tab.place === "tr" ? Style.space(2) : tab.place === "bl" || tab.place === "br" ? parent.height - height - Style.space(2) : (parent.height - height) / 2 + } + } + Text { + anchors.verticalCenter: parent.verticalCenter + visible: tab.idx < 0 + text: "󰕰" + color: tab.selected ? tab.tone : Color.muted + font.family: Style.font.family + font.pixelSize: Style.font.title + } + Text { + anchors.verticalCenter: parent.verticalCenter + text: tab.idx < 0 ? "Overview" : root.layers[tab.idx].name + color: tab.selected ? Color.foreground : Qt.alpha(Color.foreground, 0.75) + font.family: Style.font.family + font.pixelSize: Style.font.body + font.bold: tab.selected + } + Text { + anchors.verticalCenter: parent.verticalCenter + text: String(tab.index) + visible: tab.index <= 9 + color: Qt.alpha(Color.foreground, 0.32) + font.family: Style.font.family + font.pixelSize: Style.font.caption + } + } + MouseArea { + id: tabMouse + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onContainsMouseChanged: { + if (containsMouse) root.preview = tab.idx + else if (root.preview === tab.idx) root.preview = -2 + } + onClicked: root.select(tab.idx) + } + } + } + } + + // The keyboard. + Item { + id: board + width: parent.width + height: root.layoutKeys.length ? Math.ceil(root.unitsH * root.unit) : Style.space(220) + + Text { + anchors.centerIn: parent + visible: !root.layoutKeys.length + horizontalAlignment: Text.AlignHCenter + text: root.service && root.service.error ? "󰌐\n" + root.service.error : "󰌌\nReading your keymap…" + color: Color.muted + lineHeight: 1.3 + font.family: Style.font.family + font.pixelSize: Style.font.title + } + + Item { + id: plate + width: root.unitsW * root.unit + height: parent.height + anchors.horizontalCenter: parent.horizontalCenter + + Repeater { + model: root.layoutKeys.length + delegate: Item { + id: key + required property int index + readonly property var pos: root.layoutKeys[index] + readonly property var cell: root.cells[index] || ({ t: "", s: "", h: "", kind: "", corners: [], tint: -1, holdTint: -1 }) + readonly property bool dim: cell.kind === "trans" || cell.kind === "blank" + readonly property bool lit: root.highlight.indexOf(index) >= 0 + readonly property color tone: cell.tint > 0 ? root.layerColor(cell.tint) : Color.foreground + readonly property bool toned: cell.tint > 0 && !dim + x: pos.x * root.unit + root.gap / 2 + y: pos.y * root.unit + root.gap / 2 + width: root.unit - root.gap + height: root.unit - root.gap + rotation: pos.r || 0 + + Rectangle { + id: tile + anchors.fill: parent + radius: Math.round(root.unit * 0.17) + gradient: Gradient { + GradientStop { + position: 0 + color: key.cell.kind === "held" ? Qt.alpha(key.tone, 0.42) + : key.toned ? Qt.alpha(key.tone, 0.24) + : key.dim ? Qt.alpha(Color.foreground, 0.025) : Qt.alpha(Color.foreground, 0.09) + Behavior on color { ColorAnimation { duration: 140 } } + } + GradientStop { + position: 1 + color: key.cell.kind === "held" ? Qt.alpha(key.tone, 0.28) + : key.toned ? Qt.alpha(key.tone, 0.13) + : key.dim ? Qt.alpha(Color.foreground, 0.015) : Qt.alpha(Color.foreground, 0.045) + Behavior on color { ColorAnimation { duration: 140 } } + } + } + border.width: key.lit ? 2 : 1 + border.color: key.lit ? Color.accent + : key.toned || key.cell.kind === "held" ? Qt.alpha(key.tone, 0.5) + : Qt.alpha(Color.foreground, key.dim ? 0.05 : 0.1) + Behavior on border.color { ColorAnimation { duration: 140 } } + } + + // Shifted / modifier hint on top. + Text { + anchors.top: parent.top + anchors.topMargin: Math.round(root.unit * 0.07) + anchors.horizontalCenter: parent.horizontalCenter + width: parent.width - 8 + horizontalAlignment: Text.AlignHCenter + visible: text !== "" && !key.dim + text: key.cell.s + elide: Text.ElideRight + color: Qt.alpha(Color.foreground, 0.5) + font.family: Style.font.family + font.pixelSize: Math.round(root.unit * 0.16) + } + + // Main legend. + Text { + anchors.centerIn: parent + anchors.verticalCenterOffset: key.cell.h && !key.dim ? -Math.round(root.unit * 0.06) : 0 + width: parent.width - Math.round(root.unit * 0.12) + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + text: key.cell.kind === "held" ? "held" : key.cell.t + wrapMode: Text.WordWrap + maximumLineCount: 2 + elide: Text.ElideRight + lineHeight: 0.9 + color: key.lit ? Color.accent + : key.cell.kind === "held" ? key.tone + : key.dim ? Qt.alpha(Color.foreground, 0.22) + : key.toned ? key.tone : Color.foreground + font.family: Style.font.family + font.pixelSize: key.cell.kind === "held" ? Math.round(root.unit * 0.19) : root.sizeFor(key.cell.t) + font.weight: key.dim ? Font.Normal : Font.DemiBold + font.italic: key.cell.kind === "held" + } + + // Hold action underneath. + Text { + anchors.bottom: parent.bottom + anchors.bottomMargin: Math.round(root.unit * 0.07) + anchors.horizontalCenter: parent.horizontalCenter + width: parent.width - 6 + horizontalAlignment: Text.AlignHCenter + visible: text !== "" && !key.dim + text: key.cell.h + elide: Text.ElideRight + color: key.cell.holdTint > 0 ? root.layerColor(key.cell.holdTint) : Qt.alpha(Color.foreground, 0.55) + font.family: Style.font.family + font.pixelSize: Math.round(root.unit * 0.155) + font.bold: key.cell.holdTint > 0 + } + + // Overview: the other layers in the corners. + Repeater { + model: key.cell.corners + delegate: Text { + required property var modelData + readonly property bool atLeft: modelData.place === "tl" || modelData.place === "bl" + readonly property bool atTop: modelData.place === "tl" || modelData.place === "tr" + x: atLeft ? Math.round(root.unit * 0.08) : key.width - width - Math.round(root.unit * 0.08) + y: atTop ? Math.round(root.unit * 0.05) : key.height - height - Math.round(root.unit * 0.05) + width: Math.min(implicitWidth, key.width * 0.62) + horizontalAlignment: atLeft ? Text.AlignLeft : Text.AlignRight + text: modelData.text + elide: Text.ElideRight + color: modelData.color + font.family: Style.font.family + font.pixelSize: Math.round(root.unit * (root.isArrow(modelData.text) ? 0.25 : String(modelData.text).length > 3 ? 0.14 : 0.175)) + font.weight: Font.Medium + } + } + } + } + } + } + + // Combos for the layer on screen, and layers you reach by holding two. + Column { + width: parent.width + spacing: Style.spacing.lg + visible: root.combos.length > 0 || root.layerCombos.length > 0 + + Rectangle { + width: parent.width + height: 1 + color: Qt.alpha(Color.foreground, 0.07) + } + Text { + text: "COMBOS" + (root.shown > 0 ? " · " + root.shownName.toUpperCase() : "") + color: Color.muted + font.family: Style.font.family + font.pixelSize: Style.font.caption + font.letterSpacing: 1.2 + font.bold: true + } + Flow { + width: parent.width + spacing: Style.spacing.md + + Repeater { + model: root.layerCombos + delegate: Rectangle { + id: lchip + required property var modelData + width: lrow.implicitWidth + Style.spacing.xxl * 2 + height: Style.space(28) + radius: Style.space(8) + color: Qt.alpha(Color.foreground, 0.04) + border.width: 1 + border.color: Qt.alpha(Color.foreground, 0.08) + Row { + id: lrow + anchors.centerIn: parent + spacing: Style.spacing.sm + Text { + text: "hold" + color: Color.muted + font.family: Style.font.family + font.pixelSize: Style.font.bodySmall + } + Repeater { + model: lchip.modelData.hold + delegate: Text { + required property var modelData + required property int index + text: (index ? "+ " : "") + modelData + color: root.layerColor(root.layerIndex(modelData)) + font.family: Style.font.family + font.pixelSize: Style.font.bodySmall + font.bold: true + } + } + Text { + text: "→" + color: Color.muted + font.family: Style.font.family + font.pixelSize: Style.font.bodySmall + } + Text { + text: lchip.modelData.layer + color: root.layerColor(root.layerIndex(lchip.modelData.layer)) + font.family: Style.font.family + font.pixelSize: Style.font.bodySmall + font.bold: true + } + } + MouseArea { + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.select(root.layerIndex(lchip.modelData.layer)) + } + } + } + + Repeater { + model: root.combos + delegate: Rectangle { + id: chip + required property var modelData + width: crow.implicitWidth + Style.spacing.xl * 2 + height: Style.space(28) + radius: Style.space(8) + color: chipMouse.containsMouse ? Qt.alpha(Color.accent, 0.14) : Qt.alpha(Color.foreground, 0.04) + border.width: 1 + border.color: chipMouse.containsMouse ? Qt.alpha(Color.accent, 0.5) : Qt.alpha(Color.foreground, 0.08) + Behavior on color { ColorAnimation { duration: 100 } } + Row { + id: crow + anchors.centerIn: parent + spacing: Style.spacing.xs + Repeater { + model: chip.modelData.keys + delegate: Row { + id: part + required property var modelData + required property int index + spacing: Style.spacing.xs + Text { + anchors.verticalCenter: parent.verticalCenter + visible: part.index > 0 + text: "+" + color: Qt.alpha(Color.foreground, 0.35) + font.family: Style.font.family + font.pixelSize: Style.font.caption + } + Rectangle { + anchors.verticalCenter: parent.verticalCenter + readonly property string label: root.legend(root.base[part.modelData]) || ("#" + part.modelData) + width: Math.max(Style.space(18), capText.implicitWidth + Style.space(8)) + height: Style.space(18) + radius: Style.space(4) + color: Qt.alpha(Color.foreground, 0.08) + border.width: 1 + border.color: Qt.alpha(Color.foreground, 0.12) + Text { + id: capText + anchors.centerIn: parent + text: parent.label + color: Qt.alpha(Color.foreground, 0.85) + font.family: Style.font.family + font.pixelSize: Style.font.caption + font.weight: Font.DemiBold + } + } + } + } + Text { + anchors.verticalCenter: parent.verticalCenter + leftPadding: Style.spacing.xs + text: "→" + color: Color.muted + font.family: Style.font.family + font.pixelSize: Style.font.bodySmall + } + Text { + anchors.verticalCenter: parent.verticalCenter + text: chip.modelData.legend || "?" + color: chipMouse.containsMouse ? Color.accent : Color.foreground + font.family: Style.font.family + font.pixelSize: Style.font.body + font.bold: true + } + } + MouseArea { + id: chipMouse + anchors.fill: parent + hoverEnabled: true + onContainsMouseChanged: { + if (containsMouse) root.highlight = chip.modelData.keys + else if (root.highlight === chip.modelData.keys) root.highlight = [] + } + } + } + } + } + } + + Text { + width: parent.width + horizontalAlignment: Text.AlignRight + text: "Arrow keys or 0–" + Math.min(9, root.layers.length) + " switch layers · R refresh · checks the repo every " + (root.service ? root.service.checkMinutes : 2) + " min" + color: Qt.alpha(Color.foreground, 0.32) + font.family: Style.font.family + font.pixelSize: Style.font.caption + } + } + } +} diff --git a/mx-keymap/helpers/keymap.py b/mx-keymap/helpers/keymap.py new file mode 100644 index 0000000..bc335af --- /dev/null +++ b/mx-keymap/helpers/keymap.py @@ -0,0 +1,774 @@ +#!/usr/bin/env python3 +"""Keymap Cheat Sheet helper: watch a keyboard config repo and turn its keymap into JSON. + + keymap.py '{"op": "load", "repo": "xnmrph/corne"}' cached sheet, no network + keymap.py '{"op": "check", "repo": "xnmrph/corne"}' ls-remote; fetch + parse on change + keymap.py '{"op": "check", ..., "force": true}' fetch + parse even if unchanged + +Change detection is `git ls-remote` (no GitHub API, so no rate limit; private +repos work with your git credentials). The repo is kept as a shallow clone in +~/.cache/glassMxrph/keymap//repo. + +Sources, first found wins (or the "path" setting): + 1. keymap-drawer YAML (`keymap parse` output; the file with the most layers) + 2. ZMK *.keymap + 3. QMK keymap.json + +Prints one JSON object: {"ok": true, "changed": bool, "sheet": {...}} or +{"ok": false, "error": "..."}. +""" +import json +import os +import re +import subprocess +import sys +import time + +CACHE = os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), "glassMxrph", "keymap") +GIT_ENV = dict(os.environ, GIT_TERMINAL_PROMPT="0", GIT_ASKPASS="true", SSH_ASKPASS="true", + GIT_SSH_COMMAND=os.environ.get("GIT_SSH_COMMAND", "ssh -o BatchMode=yes -o ConnectTimeout=10")) + + +# --------------------------------------------------------------------------- yaml +# A small reader for the YAML keymap-drawer writes (PyYAML is not always +# installed): block mappings and sequences, flow {..} and [..], quoted and plain +# scalars, comments, | and > block scalars. + +def _strip_comment(line): + quote = None + for i, c in enumerate(line): + if quote: + if c == quote: + quote = None + elif c in "'\"" and (i == 0 or line[i - 1] in " \t-:[{,"): + quote = c + elif c == "#" and (i == 0 or line[i - 1] in " \t"): + return line[:i].rstrip() + return line.rstrip() + + +def _find_colon(text): + """Index of the mapping colon in a block line ('key: value' / 'key:'), or -1.""" + depth, quote = 0, None + i = 0 + while i < len(text): + c = text[i] + if quote: + if c == quote: + if quote == "'" and text[i + 1:i + 2] == "'": + i += 1 + else: + quote = None + elif c == "\\" and quote == '"': + i += 1 + elif c in "'\"" and (i == 0 or text[i - 1] in " ,[{"): + quote = c + elif c in "[{": + depth += 1 + elif c in "]}": + depth -= 1 + elif c == ":" and depth == 0 and (i + 1 == len(text) or text[i + 1] in " \t"): + return i + i += 1 + return -1 + + +def _plain(text): + if re.fullmatch(r"[-+]?\d+", text): + return int(text) + if text in ("true", "True"): + return True + if text in ("false", "False"): + return False + if text in ("null", "~", ""): + return None + return text + + +def _quoted(text, i): + q = text[i] + out = [] + i += 1 + while i < len(text): + c = text[i] + if q == "'" and c == "'": + if text[i + 1:i + 2] == "'": + out.append("'") + i += 2 + continue + return "".join(out), i + 1 + if q == '"' and c == "\\": + nxt = text[i + 1:i + 2] + out.append({"n": "\n", "t": "\t", "\\": "\\", '"': '"', "/": "/"}.get(nxt, nxt)) + i += 2 + continue + if q == '"' and c == '"': + return "".join(out), i + 1 + out.append(c) + i += 1 + raise ValueError("unterminated string") + + +def _flow(text, i=0, stops=""): + """Parse a flow value starting at text[i]; returns (value, next index).""" + while i < len(text) and text[i] in " \t": + i += 1 + if i >= len(text): + return None, i + c = text[i] + if c == "{": + out = {} + i += 1 + while True: + while i < len(text) and text[i] in " \t,": + i += 1 + if i >= len(text): + raise ValueError("unterminated mapping") + if text[i] == "}": + return out, i + 1 + key, i = _flow(text, i, ":,}") + while i < len(text) and text[i] in " \t": + i += 1 + value = None + if i < len(text) and text[i] == ":": + value, i = _flow(text, i + 1, ",}") + out[str(key)] = value + if c == "[": + out = [] + i += 1 + while True: + while i < len(text) and text[i] in " \t,": + i += 1 + if i >= len(text): + raise ValueError("unterminated list") + if text[i] == "]": + return out, i + 1 + value, i = _flow(text, i, ",]") + out.append(value) + if c in "'\"": + return _quoted(text, i) + j = i + while j < len(text): + if text[j] in stops and (text[j] != ":" or j + 1 == len(text) or text[j + 1] in " \t,}"): + break + j += 1 + return _plain(text[i:j].strip()), j + + +def _scalar(text): + text = text.strip() + if not text: + return None + if text[0] in "{['\"": + value, _ = _flow(text) + return value + return _plain(text) + + +def load_yaml(source): + lines = [] + raw = source.split("\n") + for line in raw: + if line.strip() in ("---", "..."): + continue + stripped = _strip_comment(line.replace("\t", " ")) + if stripped.strip(): + lines.append([len(stripped) - len(stripped.lstrip()), stripped.strip(), line]) + pos = [0] + + def block_scalar(indent, style): + out = [] + while pos[0] < len(lines) and lines[pos[0]][0] > indent: + original = lines[pos[0]][2] + out.append(original) + pos[0] += 1 + if not out: + return "" + cut = min(len(l) - len(l.lstrip()) for l in out if l.strip()) + body = [l[cut:] for l in out] + return ("\n" if style == "|" else " ").join(body) + "\n" + + def value_after(text, indent): + if text in ("|", "|-", ">", ">-"): + return block_scalar(indent, text[0]) + if text: + return _scalar(text) + if pos[0] < len(lines): + child_indent, child = lines[pos[0]][0], lines[pos[0]][1] + if child_indent > indent or (child_indent == indent and (child == "-" or child.startswith("- "))): + return parse(child_indent) + return None + + def parse(indent): + if pos[0] >= len(lines): + return None + first = lines[pos[0]][1] + if first == "-" or first.startswith("- "): + out = [] + while pos[0] < len(lines) and lines[pos[0]][0] == indent and (lines[pos[0]][1] == "-" or lines[pos[0]][1].startswith("- ")): + rest = lines[pos[0]][1][1:].strip() + if not rest: + pos[0] += 1 + out.append(value_after("", indent)) + elif rest[0] not in "{[" and _find_colon(rest) >= 0: + # "- key: value" starts a mapping indented past the dash. + lines[pos[0]][0] = indent + 2 + lines[pos[0]][1] = rest + out.append(parse(indent + 2)) + else: + pos[0] += 1 + out.append(_scalar(rest)) + return out + out = {} + while pos[0] < len(lines) and lines[pos[0]][0] == indent: + text = lines[pos[0]][1] + if text == "-" or text.startswith("- "): + break + colon = _find_colon(text) + if colon < 0: + raise ValueError("expected 'key: value': " + text) + key = _scalar(text[:colon]) + pos[0] += 1 + out[str(key)] = value_after(text[colon + 1:].strip(), indent) + return out + + if not lines: + return None + return parse(lines[0][0]) + + +# --------------------------------------------------------------------------- keys + +def pretty(legend): + """Unmapped ZMK behaviours ('&smart_shift') read as words ('Smart shift').""" + legend = str(legend) + if legend.startswith("&") and len(legend) > 1: + words = legend[1:].replace("_", " ").split() + return " ".join(words)[:1].upper() + " ".join(words)[1:] + return legend + + +def key_from_drawer(key): + """One keymap-drawer key -> {t, s, h, type}.""" + if key is None: + return {"t": "", "type": "blank"} + if not isinstance(key, dict): + return {"t": pretty(key)} + out = {} + for name in ("t", "s", "h", "tl", "tr", "bl", "br"): + value = key.get(name) + if value is not None and str(value) != "": + if isinstance(value, dict): # nested legend, keep its tap + value = value.get("t", "") + out[name] = pretty(value) + kind = str(key.get("type") or "") + if "trans" in kind.split(): + out["type"] = "trans" + elif "held" in kind.split(): + out["type"] = "held" + elif "ghost" in kind.split() or "blank" in kind.split(): + out["type"] = "blank" if not out.get("t") else "ghost" + out.setdefault("t", "") + return out + + +def parse_drawer(text): + data = load_yaml(text) + if not isinstance(data, dict) or not isinstance(data.get("layers"), dict): + raise ValueError("no layers in the keymap-drawer file") + layers = [] + for name, keys in data["layers"].items(): + if isinstance(keys, list): + layers.append({"name": str(name), "keys": [key_from_drawer(k) for k in _flatten(keys)]}) + names = [l["name"] for l in layers] + combos = [] + for combo in data.get("combos") or []: + if not isinstance(combo, dict) or not isinstance(combo.get("p"), list): + continue + k = combo.get("k") + legend = k.get("t", "") if isinstance(k, dict) else ("" if k is None else str(k)) + only = [str(l) for l in combo.get("l") or [] if str(l) in names] + combos.append({"keys": [int(p) for p in combo["p"] if isinstance(p, int)], "legend": legend, "layers": only}) + layout = data.get("layout") if isinstance(data.get("layout"), dict) else {} + keyboard = str(layout.get("zmk_keyboard") or layout.get("qmk_keyboard") or "") + return {"layers": layers, "combos": combos, "keyboard": keyboard, "layerCombos": []} + + +def _flatten(keys): + out = [] + for k in keys: + if isinstance(k, list): # keymap-drawer also allows rows as lists + out.extend(k) + else: + out.append(k) + return out + + +KEYCODES = { + "EXCLAMATION": "!", "EXCL": "!", "AT_SIGN": "@", "AT": "@", "HASH": "#", "POUND": "#", + "DOLLAR": "$", "DLLR": "$", "PERCENT": "%", "PRCNT": "%", "CARET": "^", "AMPERSAND": "&", + "AMPS": "&", "ASTERISK": "*", "ASTRK": "*", "STAR": "*", "LEFT_PARENTHESIS": "(", "LPAR": "(", + "RIGHT_PARENTHESIS": ")", "RPAR": ")", "EQUAL": "=", "PLUS": "+", "MINUS": "-", "UNDERSCORE": "_", + "UNDER": "_", "SLASH": "/", "FSLH": "/", "QUESTION": "?", "QMARK": "?", "BACKSLASH": "\\", + "BSLH": "\\", "PIPE": "|", "PIPE2": "|", "NON_US_BACKSLASH": "\\", "NUBS": "\\", "SEMICOLON": ";", + "SEMI": ";", "COLON": ":", "SINGLE_QUOTE": "'", "SQT": "'", "APOSTROPHE": "'", "APOS": "'", + "DOUBLE_QUOTES": '"', "DQT": '"', "COMMA": ",", "LESS_THAN": "<", "LT": "<", "PERIOD": ".", + "DOT": ".", "GREATER_THAN": ">", "GT": ">", "LEFT_BRACKET": "[", "LBKT": "[", "RIGHT_BRACKET": "]", + "RBKT": "]", "LEFT_BRACE": "{", "LBRC": "{", "RIGHT_BRACE": "}", "RBRC": "}", "GRAVE": "`", + "TILDE": "~", "TILDE2": "~", "NON_US_HASH": "#", "NUHS": "#", + "BACKSPACE": "Bspc", "BSPC": "Bspc", "ESCAPE": "Esc", "ESC": "Esc", "RETURN": "Enter", "RET": "Enter", + "ENTER": "Enter", "RETURN2": "Enter", "RET2": "Enter", "SPACE": "Space", "SPC": "Space", "TAB": "Tab", + "DELETE": "Del", "DEL": "Del", "INSERT": "Ins", "INS": "Ins", "HOME": "Home", "END": "End", + "PAGE_UP": "PgUp", "PG_UP": "PgUp", "PGUP": "PgUp", "PAGE_DOWN": "PgDn", "PG_DN": "PgDn", "PGDN": "PgDn", + "UP": "↑", "UP_ARROW": "↑", "DOWN": "↓", "DOWN_ARROW": "↓", "LEFT": "←", "LEFT_ARROW": "←", + "RIGHT": "→", "RIGHT_ARROW": "→", "CAPSLOCK": "Caps", "CAPS": "Caps", "CAPS_LOCK": "Caps", + "PRINTSCREEN": "PrtSc", "PSCRN": "PrtSc", "SCROLLLOCK": "ScrLk", "PAUSE_BREAK": "Pause", + "LEFT_SHIFT": "Shift", "LSHIFT": "Shift", "LSHFT": "Shift", "LSFT": "Shift", "RIGHT_SHIFT": "Shift", + "RSHIFT": "Shift", "RSHFT": "Shift", "RSFT": "Shift", "LEFT_CONTROL": "Ctrl", "LCTRL": "Ctrl", + "LCTL": "Ctrl", "RIGHT_CONTROL": "Ctrl", "RCTRL": "Ctrl", "RCTL": "Ctrl", "LEFT_ALT": "Alt", + "LALT": "Alt", "LOPT": "Alt", "RIGHT_ALT": "AltGr", "RALT": "AltGr", "ROPT": "AltGr", "ALGR": "AltGr", + "LEFT_GUI": "Gui", "LGUI": "Gui", "LCMD": "Gui", "LWIN": "Gui", "LMETA": "Gui", "RIGHT_GUI": "Gui", + "RGUI": "Gui", "RCMD": "Gui", "RWIN": "Gui", "RMETA": "Gui", + "C_VOLUME_UP": "Vol+", "C_VOL_UP": "Vol+", "KC_VOLU": "Vol+", "VOLU": "Vol+", "C_VOLUME_DOWN": "Vol−", + "C_VOL_DN": "Vol−", "VOLD": "Vol−", "C_MUTE": "Mute", "MUTE": "Mute", "C_PLAY_PAUSE": "Play", + "C_PP": "Play", "MPLY": "Play", "C_NEXT": "Next", "MNXT": "Next", "C_PREVIOUS": "Prev", "C_PREV": "Prev", + "MPRV": "Prev", "C_BRIGHTNESS_INC": "Bri+", "C_BRI_UP": "Bri+", "C_BRIGHTNESS_DEC": "Bri−", + "C_BRI_DN": "Bri−", "KP_NUMLOCK": "Num", "KP_MINUS": "-", "KP_PLUS": "+", "KP_MULTIPLY": "*", + "KP_SLASH": "/", "KP_ENTER": "Enter", "KP_DOT": ".", +} +MODS = {"LS": "Shift", "RS": "Shift", "LC": "Ctrl", "RC": "Ctrl", "LA": "Alt", "RA": "AltGr", + "LG": "❖", "RG": "❖", "LSFT": "Shift", "RSFT": "Shift", "LCTL": "Ctrl", "RCTL": "Ctrl", + "LALT": "Alt", "RALT": "AltGr", "LGUI": "❖", "RGUI": "❖", "S": "Shift", "C": "Ctrl", "A": "Alt", + "G": "❖", "MOD_LSFT": "Shift", "MOD_LCTL": "Ctrl", "MOD_LALT": "Alt", "MOD_LGUI": "Gui", + "MOD_RSFT": "Shift", "MOD_RCTL": "Ctrl", "MOD_RALT": "AltGr", "MOD_RGUI": "Gui"} + + +def keycode(code): + """ZMK / QMK keycode -> legend ('LG(N1)' -> '❖1', 'KC_A' -> 'A').""" + code = code.strip() + m = re.fullmatch(r"([A-Z_]+)\((.*)\)", code) + if m and m.group(1) in MODS: + mod = MODS[m.group(1)] + inner = keycode(m.group(2)) + if mod == "Shift" and len(inner) == 1 and inner.isalpha(): + return inner.upper() + return mod + inner if mod == "❖" else f"{mod} {inner}" + if code.startswith("KC_"): + code = code[3:] + if code in KEYCODES: + return KEYCODES[code] + m = re.fullmatch(r"(?:N|NUMBER_|KP_N|KP_NUMBER_|P)(\d)", code) + if m: + return m.group(1) + if re.fullmatch(r"F\d{1,2}", code): + return code + if len(code) == 1: + return code.upper() + return code.replace("_", " ").title() + + +# --------------------------------------------------------------------------- zmk + +def _strip_c(text): + text = re.sub(r"/\*.*?\*/", " ", text, flags=re.S) + return re.sub(r"//[^\n]*", " ", text) + + +def _nodes(body): + """Direct child nodes of a devicetree body: [(name, content)].""" + out = [] + i = 0 + while True: + m = re.compile(r"([\w@-]+)(?:\s*:\s*[\w@-]+)?\s*\{").search(body, i) + if not m: + return out + depth, j = 1, m.end() + while j < len(body) and depth: + depth += {"{": 1, "}": -1}.get(body[j], 0) + j += 1 + out.append((m.group(1), body[m.end():j - 1])) + i = j + + +def _block(text, compatible): + m = re.search(r'compatible\s*=\s*"' + re.escape(compatible) + r'"\s*;', text) + if not m: + return "" + start = text.rfind("{", 0, m.start()) + depth, j = 1, start + 1 + while j < len(text) and depth: + depth += {"{": 1, "}": -1}.get(text[j], 0) + j += 1 + return text[start + 1:j - 1] + + +def _prop(content, name): + m = re.search(r"(?= 2: + return {"t": keycode(" ".join(args[1:])), "h": layer(args[0])} + if behavior == "mt" and len(args) >= 2: + return {"t": keycode(" ".join(args[1:])), "h": keycode(args[0])} + if behavior == "sk" and args: + return {"t": keycode(" ".join(args)), "s": "sticky"} + if behavior == "bt" and args: + if args[0] == "BT_SEL" and len(args) > 1 and args[1].isdigit(): + return {"t": f"BT {int(args[1]) + 1}"} + return {"t": {"BT_CLR": "BT✕", "BT_CLR_ALL": "All✕", "BT_NXT": "BT→", "BT_PRV": "BT←"}.get(args[0], args[0])} + if behavior == "bootloader": + return {"t": "Boot"} + if behavior == "sys_reset": + return {"t": "Reset"} + if behavior == "caps_word": + return {"t": "Caps"} + if behavior == "key_repeat": + return {"t": "Repeat"} + if behavior in ("mkp", "mmv", "msc") and args: + a = args[0] + return {"t": {"LCLK": "L-clk", "RCLK": "R-clk", "MCLK": "M-clk", "MOVE_UP": "↑", "MOVE_DOWN": "↓", + "MOVE_LEFT": "←", "MOVE_RIGHT": "→", "SCRL_UP": "⇡", "SCRL_DOWN": "⇣", + "SCRL_LEFT": "⇠", "SCRL_RIGHT": "⇢"}.get(a, a)} + label = behavior.replace("_", " ") + return {"t": label if len(label) <= 6 else label[:1].upper() + label[1:]} + + +def _bindings(value): + value = (value or "").replace("<", " ").replace(">", " ").replace(",", " ") + return [" ".join(b.split()) for b in value.split("&")[1:] if b.strip()] + + +def parse_zmk(text): + text = _strip_c(text) + keymap = _block(text, "zmk,keymap") + if not keymap: + raise ValueError("no zmk,keymap node") + nodes = [(name, content) for name, content in _nodes(keymap) if _prop(content, "bindings") is not None] + names = [] + for name, content in nodes: + label = _prop(content, "display-name") or _prop(content, "label") + names.append(label.strip('"') if label else name) + layers = [] + for (name, content), label in zip(nodes, names): + layers.append({"name": label, "keys": [zmk_binding(b, names) for b in _bindings(_prop(content, "bindings"))]}) + combos = [] + for name, content in _nodes(_block(text, "zmk,combos")): + positions = _cells(_prop(content, "key-positions")) + bindings = _bindings(_prop(content, "bindings")) + if not positions or not bindings: + continue + only = [names[int(n)] for n in _cells(_prop(content, "layers")) if int(n) < len(names)] + combos.append({"keys": [int(p) for p in positions], "legend": zmk_binding(bindings[0], names)["t"], "layers": only}) + return {"layers": layers, "combos": combos, "keyboard": "", "layerCombos": zmk_conditional(text, names)} + + +def zmk_conditional(text, names): + out = [] + for name, content in _nodes(_block(_strip_c(text), "zmk,conditional-layers")): + ifs = [int(n) for n in _cells(_prop(content, "if-layers"))] + then = _cells(_prop(content, "then-layer")) + if ifs and then and all(n < len(names) for n in ifs) and int(then[0]) < len(names): + out.append({"hold": [names[n] for n in ifs], "layer": names[int(then[0])]}) + return out + + +# --------------------------------------------------------------------------- qmk + +def qmk_key(code, count): + code = code.strip() + layer = lambda n: f"L{n}" + if code in ("_______", "KC_TRNS", "KC_TRANSPARENT", "_____"): + return {"t": "", "type": "trans"} + if code in ("XXXXXXX", "KC_NO"): + return {"t": "", "type": "blank"} + m = re.fullmatch(r"(MO|TG|TO|OSL|TT|DF)\((\d+)\)", code) + if m: + return {"t": layer(m.group(2)), "layer": layer(m.group(2))} + m = re.fullmatch(r"LT\((\d+),\s*(.+)\)", code) + if m: + return {"t": keycode(m.group(2)), "h": layer(m.group(1))} + m = re.fullmatch(r"MT\(([^,]+),\s*(.+)\)", code) + if m: + return {"t": keycode(m.group(2)), "h": " ".join(MODS.get(x.strip(), x.strip()) for x in m.group(1).split("|"))} + m = re.fullmatch(r"([LR]?(?:SFT|CTL|ALT|GUI|SHIFT|CTRL|OPT|CMD|WIN))_T\((.+)\)", code) + if m: + return {"t": keycode(m.group(2)), "h": keycode(m.group(1).replace("SHIFT", "SFT").replace("CTRL", "CTL"))} + return {"t": keycode(code)} + + +def parse_qmk(text): + data = json.loads(text) + raw = data.get("layers") if isinstance(data, dict) else None + if not isinstance(raw, list): + raise ValueError("no layers in keymap.json") + layers = [{"name": f"L{i}", "keys": [qmk_key(str(c), len(raw)) for c in keys]} for i, keys in enumerate(raw)] + return {"layers": layers, "combos": [], "keyboard": str(data.get("keyboard") or ""), "layerCombos": []} + + +# --------------------------------------------------------------------------- layout + +def _corne_like(cols, thumbs): + """Split 3xN with a column stagger and a fanned thumb cluster; x,y in key units.""" + stagger = [0.35, 0.35, 0.12, 0.0, 0.12, 0.24][-cols:] + half_gap = 1.1 + width = cols + half_gap # one half plus half the gap + keys = [] + for row in range(3): + for c in range(cols): + keys.append({"x": c, "y": row + stagger[c], "r": 0}) + for c in range(cols): + mirror = cols - 1 - c + keys.append({"x": 2 * width - 1 - mirror, "y": row + stagger[mirror], "r": 0}) + if thumbs == 6: + fan = [(cols - 2.55, 3.32, 0), (cols - 1.5, 3.42, 8), (cols - 0.42, 3.62, 16)] + else: + fan = [(cols - 1.55, 3.36, 4), (cols - 0.45, 3.56, 12)] + for x, y, r in fan: + keys.append({"x": x, "y": y, "r": r, "thumb": True}) + for x, y, r in reversed(fan): + keys.append({"x": 2 * width - 1 - x, "y": y, "r": -r, "thumb": True}) + return keys + + +def layout_for(count, keyboard=""): + """Physical key positions for a key count; split boards are guessed from common sizes.""" + split = {42: (6, 6), 36: (5, 6), 34: (5, 4), 40: (6, 4)} + if count in split: + cols, thumbs = split[count] + return {"split": True, "keys": _corne_like(cols, thumbs)} + per_row = 12 if count % 12 == 0 or count > 40 else 10 + return {"split": False, "keys": [{"x": i % per_row, "y": i // per_row, "r": 0} for i in range(count)]} + + +# --------------------------------------------------------------------------- repo + +def repo_url(repo): + repo = repo.strip() + if re.fullmatch(r"[\w.-]+/[\w.-]+", repo): + return f"https://github.com/{repo.removesuffix('.git')}.git" + if repo.startswith("github.com/"): + return "https://" + repo + return repo + + +def repo_name(repo): + m = re.search(r"([\w.-]+/[\w.-]+?)(?:\.git)?/?$", repo.strip()) + return m.group(1) if m else repo + + +def web_url(repo): + url = repo_url(repo) + m = re.match(r"(?:https://|git@)(github\.com|gitlab\.com|codeberg\.org)[/:](.+?)(?:\.git)?$", url) + return f"https://{m.group(1)}/{m.group(2)}" if m else "" + + +def git(args, cwd=None, timeout=60): + p = subprocess.run(["git"] + args, cwd=cwd, env=GIT_ENV, capture_output=True, text=True, timeout=timeout) + if p.returncode: + lines = [l for l in (p.stderr or p.stdout).strip().splitlines() if l.strip()] + raise RuntimeError(lines[-1] if lines else "git " + args[0] + " failed") + return p.stdout + + +def remote_sha(url, branch): + ref = f"refs/heads/{branch}" if branch else "HEAD" + out = git(["ls-remote", url, ref], timeout=25) + for line in out.splitlines(): + sha, _, name = line.partition("\t") + if name == ref: + return sha + raise RuntimeError(f"branch {branch} not found" if branch else "the repository is empty") + + +def slug(url, branch): + return re.sub(r"[^\w.-]+", "_", url.split("://", 1)[-1].removesuffix(".git")) + (f"@{branch}" if branch else "") + + +def sync(url, branch, folder): + ref = branch or "HEAD" + if not os.path.isdir(os.path.join(folder, ".git")): + os.makedirs(os.path.dirname(folder), exist_ok=True) + git(["init", "-q", folder]) + git(["remote", "add", "origin", url], cwd=folder) + else: + git(["remote", "set-url", "origin", url], cwd=folder) + git(["fetch", "-q", "--depth", "2", "--no-tags", "origin", ref], cwd=folder, timeout=120) + git(["checkout", "-qf", "--detach", "FETCH_HEAD"], cwd=folder) + + +SKIP_DIRS = {".git", ".github", "node_modules", "build", ".cache"} + + +def files(folder): + for root, dirs, names in os.walk(folder): + dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS) + for name in sorted(names): + yield os.path.relpath(os.path.join(root, name), folder) + + +def read(folder, rel): + with open(os.path.join(folder, rel), encoding="utf-8", errors="replace") as f: + return f.read() + + +def parse_file(folder, rel): + text = read(folder, rel) + if rel.endswith(".keymap"): + return parse_zmk(text), "zmk" + if rel.endswith(".json"): + return parse_qmk(text), "qmk" + return parse_drawer(text), "keymap-drawer" + + +def find_source(folder, path): + if path: + if not os.path.isfile(os.path.join(folder, path)): + raise RuntimeError(f"{path} is not in the repository") + return path + all_files = list(files(folder)) + best, most = None, 0 + for rel in all_files: + if not rel.endswith((".yaml", ".yml")) or "config" in os.path.basename(rel) or rel.count(os.sep) > 3: + continue + try: + text = read(folder, rel) + if not re.search(r"^layers:", text, re.M): + continue + data = parse_drawer(text) + except Exception: + continue + n = sum(1 for l in data["layers"] if any(k.get("t") for k in l["keys"])) + if n > most: + best, most = rel, n + if best: + return best + keymaps = sorted((r for r in all_files if r.endswith(".keymap")), key=lambda r: (not r.startswith("config"), len(r))) + if keymaps: + return keymaps[0] + for rel in all_files: + if os.path.basename(rel) == "keymap.json": + return rel + raise RuntimeError("no keymap found (keymap-drawer YAML, ZMK .keymap or QMK keymap.json)") + + +def pending_redraw(folder, source): + """The last commit changed the .keymap but not the drawn YAML, and CI redraws it.""" + if not source.endswith((".yaml", ".yml")): + return False + try: + changed = git(["diff", "--name-only", "HEAD~1", "HEAD"], cwd=folder).split() + except RuntimeError: + return False + if not any(f.endswith(".keymap") for f in changed) or source in changed: + return False + workflows = os.path.join(folder, ".github", "workflows") + if not os.path.isdir(workflows): + return False + for name in os.listdir(workflows): + try: + if "keymap-drawer" in read(workflows, name) or re.search(r"\bkeymap\b.*\bdraw\b", read(workflows, name)): + return True + except OSError: + pass + return False + + +def build(folder, url, branch, path, repo): + source = find_source(folder, path) + sheet, kind = parse_file(folder, source) + keymaps = [r for r in files(folder) if r.endswith(".keymap")] + if not sheet["layerCombos"] and keymaps: + try: + names = [l["name"] for l in sheet["layers"]] + zmk = parse_zmk(read(folder, keymaps[0])) + zmk_names = [l["name"] for l in zmk["layers"]] + sheet["layerCombos"] = [c for c in zmk_conditional(read(folder, keymaps[0]), zmk_names) + if c["layer"] in names and all(h in names for h in c["hold"])] + except Exception: + pass + count = max((len(l["keys"]) for l in sheet["layers"]), default=0) + if not count: + raise RuntimeError(f"{source} has no keys") + for layer in sheet["layers"]: + layer["keys"] += [{"t": "", "type": "blank"}] * (count - len(layer["keys"])) + log = git(["log", "-1", "--format=%H%x00%ct%x00%s"], cwd=folder).strip().split("\x00") + sheet.update({ + "repo": repo_name(repo), + "web": web_url(repo), + "branch": branch, + "source": source, + "format": kind, + "sha": log[0], + "committed": int(log[1]) if len(log) > 1 and log[1].isdigit() else 0, + "subject": log[2] if len(log) > 2 else "", + "fetched": int(time.time()), + "pending": pending_redraw(folder, source), + "layout": layout_for(count, sheet.get("keyboard", "")), + }) + return sheet + + +def main(request): + repo = str(request.get("repo") or "").strip() + if not repo: + return {"ok": False, "error": "Set a keymap repository in the widget settings"} + branch = str(request.get("branch") or "").strip() + path = str(request.get("path") or "").strip().lstrip("/") + url = repo_url(repo) + base = os.path.join(CACHE, slug(url, branch)) + cached_path = os.path.join(base, "sheet.json") + cached = None + try: + with open(cached_path, encoding="utf-8") as f: + cached = json.load(f) + if cached.get("path", "") != path: + cached = None + except (OSError, ValueError): + pass + if request.get("op") == "load": + return {"ok": True, "changed": False, "sheet": cached} + sha = remote_sha(url, branch) + if cached and cached.get("sha") == sha and not request.get("force"): + cached["checked"] = int(time.time()) + return {"ok": True, "changed": False, "sheet": cached} + folder = os.path.join(base, "repo") + sync(url, branch, folder) + sheet = build(folder, url, branch, path, repo) + sheet["path"] = path + sheet["checked"] = int(time.time()) + os.makedirs(base, exist_ok=True) + tmp = cached_path + ".tmp" + with open(tmp, "w", encoding="utf-8") as f: + json.dump(sheet, f, ensure_ascii=False) + os.replace(tmp, cached_path) + changed = not cached or cached.get("sha") != sheet["sha"] or json.dumps(cached.get("layers")) != json.dumps(sheet["layers"]) + return {"ok": True, "changed": changed, "sheet": sheet} + + +if __name__ == "__main__": + try: + result = main(json.loads(sys.argv[1]) if len(sys.argv) > 1 else {}) + except subprocess.TimeoutExpired: + result = {"ok": False, "error": "The repository did not answer in time"} + except Exception as e: # reported in the panel, never a traceback + result = {"ok": False, "error": str(e) or type(e).__name__} + print(json.dumps(result, ensure_ascii=False)) diff --git a/mx-keymap/manifest.json b/mx-keymap/manifest.json new file mode 100644 index 0000000..48913f3 --- /dev/null +++ b/mx-keymap/manifest.json @@ -0,0 +1,76 @@ +{ + "schemaVersion": 1, + "id": "mx-keymap", + "name": "Keymap Cheat Sheet", + "version": "0.1.0", + "author": "mx", + "license": "MIT", + "description": "A cheat sheet for your keyboard's layers, drawn from the keymap in a git repository (keymap-drawer YAML, ZMK .keymap or QMK keymap.json). It watches the repo and redraws the sheet when you push a change.", + "kinds": [ + "bar-widget", + "service" + ], + "entryPoints": { + "barWidget": "BarWidget.qml", + "service": "Service.qml" + }, + "barWidget": { + "displayName": "Keymap", + "description": "Click for a cheat sheet of your keyboard layers.", + "category": "Utilities", + "allowMultiple": false, + "defaultSection": "right", + "defaults": { + "background": "pill", + "repository": "xnmrph/corne", + "branch": "", + "path": "", + "checkMinutes": 2, + "startView": "overview" + }, + "schema": [ + { + "key": "background", + "label": "Background", + "description": "pill: the button sits on a round pill; transparent: just the icon.", + "choices": ["pill", "transparent"], + "defaultValue": "pill" + }, + { + "key": "repository", + "type": "string", + "label": "Keymap repository", + "description": "GitHub owner/name (e.g. xnmrph/corne) or any git URL. Private repos use your git credentials.", + "defaultValue": "xnmrph/corne" + }, + { + "key": "branch", + "type": "string", + "label": "Branch", + "description": "Blank: the repository's default branch.", + "defaultValue": "" + }, + { + "key": "path", + "type": "string", + "label": "Keymap file", + "description": "Path inside the repo. Blank: found automatically (keymap-drawer YAML first, then a ZMK .keymap, then QMK keymap.json).", + "defaultValue": "" + }, + { + "key": "checkMinutes", + "type": "integer", + "label": "Check for changes every (minutes)", + "description": "A git ls-remote, so frequent checks are cheap. The sheet also checks when you open it.", + "defaultValue": 2 + }, + { + "key": "startView", + "label": "Opens on", + "description": "Overview shows every layer on one keyboard; Base shows the first layer on its own.", + "choices": ["overview", "base"], + "defaultValue": "overview" + } + ] + } +} diff --git a/mx-keymap/tests/keymap_test.py b/mx-keymap/tests/keymap_test.py new file mode 100644 index 0000000..4a3dfb7 --- /dev/null +++ b/mx-keymap/tests/keymap_test.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Tests for helpers/keymap.py: the YAML reader, the ZMK/QMK parsers and repo change detection.""" +import json +import os +import subprocess +import sys +import tempfile +import unittest + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "helpers")) +import keymap # noqa: E402 + +DRAWER = """\ +layout: {zmk_keyboard: corne} +layers: + Base: + - {t: Esc, s: '`'} + - Q + - '&smart_shift' + - {t: Tab, h: Symbols} + Symbols: + - '''' + - '!' + - {type: trans} + - {type: held} +combos: +- p: [0, 1] + k: Del +- p: [1, 2] + k: {t: (, s: <} + l: [Base] +""" + +BLOCK = """\ +layers: + Layers: + - t: Esc + s: '`' + tr: '''' # comment + - t: ; + - t: Tab + h: Symbols + type: lh-tr +draw_config: + css: | + a { b: c; } + d +""" + +ZMK = """ +/ { combos { compatible = "zmk,combos"; + esc { bindings = <&kp ESCAPE>; key-positions = <0 1>; }; + sym { bindings = <&kp LS(N1)>; key-positions = <1 2>; layers = <1>; }; }; + keymap { compatible = "zmk,keymap"; + DEF { display-name = "Base"; bindings = < + &kp Q < 1 SPACE &mt LCTRL A &mo 2 // comment + >; }; + SYM { display-name = "Sym"; bindings = < &kp EXCL &trans &none &bt BT_SEL 0 >; }; + FN { bindings = < &kp LG(N1) &trans &trans &trans >; }; }; + conditional_layers { compatible = "zmk,conditional-layers"; + tri { if-layers = <1 2>; then-layer = <0>; }; }; +}; +""" + + +class Yaml(unittest.TestCase): + def test_flow_style(self): + data = keymap.load_yaml(DRAWER) + self.assertEqual(data["layout"], {"zmk_keyboard": "corne"}) + self.assertEqual(data["layers"]["Base"][0], {"t": "Esc", "s": "`"}) + self.assertEqual(data["layers"]["Symbols"][0], "'") + self.assertEqual(data["combos"][1], {"p": [1, 2], "k": {"t": "(", "s": "<"}, "l": ["Base"]}) + + def test_block_style(self): + data = keymap.load_yaml(BLOCK) + self.assertEqual(data["layers"]["Layers"][0], {"t": "Esc", "s": "`", "tr": "'"}) + self.assertEqual(data["layers"]["Layers"][1], {"t": ";"}) + self.assertEqual(data["draw_config"]["css"], "a { b: c; }\nd\n") + + +class Parsers(unittest.TestCase): + def test_drawer(self): + sheet = keymap.parse_drawer(DRAWER) + self.assertEqual([l["name"] for l in sheet["layers"]], ["Base", "Symbols"]) + self.assertEqual(sheet["layers"][0]["keys"][2]["t"], "Smart shift") + self.assertEqual(sheet["layers"][1]["keys"][2]["type"], "trans") + self.assertEqual(sheet["layers"][1]["keys"][3]["type"], "held") + self.assertEqual(sheet["combos"][1], {"keys": [1, 2], "legend": "(", "layers": ["Base"]}) + + def test_zmk(self): + sheet = keymap.parse_zmk(ZMK) + self.assertEqual([l["name"] for l in sheet["layers"]], ["Base", "Sym", "FN"]) + base = sheet["layers"][0]["keys"] + self.assertEqual(base[1], {"t": "Space", "h": "Sym"}) + self.assertEqual(base[2], {"t": "A", "h": "Ctrl"}) + self.assertEqual(base[3]["t"], "FN") + sym = sheet["layers"][1]["keys"] + self.assertEqual([k["t"] for k in sym], ["!", "", "", "BT 1"]) + self.assertEqual(sheet["layers"][2]["keys"][0]["t"], "❖1") + self.assertEqual(sheet["combos"][0], {"keys": [0, 1], "legend": "Esc", "layers": []}) + self.assertEqual(sheet["combos"][1]["layers"], ["Sym"]) + self.assertEqual(sheet["layerCombos"], [{"hold": ["Sym", "FN"], "layer": "Base"}]) + + def test_qmk(self): + sheet = keymap.parse_qmk(json.dumps({"layers": [["KC_A", "LT(1,KC_SPC)", "LCTL_T(KC_ESC)", "_______"]]})) + keys = sheet["layers"][0]["keys"] + self.assertEqual(keys[0], {"t": "A"}) + self.assertEqual(keys[1], {"t": "Space", "h": "L1"}) + self.assertEqual(keys[2], {"t": "Esc", "h": "Ctrl"}) + self.assertEqual(keys[3]["type"], "trans") + + def test_layouts(self): + corne = keymap.layout_for(42) + self.assertTrue(corne["split"]) + self.assertEqual(len(corne["keys"]), 42) + self.assertEqual(sum(1 for k in corne["keys"] if k.get("thumb")), 6) + self.assertEqual(len(keymap.layout_for(36)["keys"]), 36) + self.assertFalse(keymap.layout_for(61)["split"]) + + def test_repo_names(self): + self.assertEqual(keymap.repo_url("xnmrph/corne"), "https://github.com/xnmrph/corne.git") + self.assertEqual(keymap.web_url("git@github.com:xnmrph/corne.git"), "https://github.com/xnmrph/corne") + self.assertEqual(keymap.repo_name("https://github.com/xnmrph/corne.git"), "xnmrph/corne") + + +class Watch(unittest.TestCase): + """A local repository stands in for GitHub: check, commit, check again.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.repo = os.path.join(self.tmp.name, "kb") + os.environ["XDG_CACHE_HOME"] = os.path.join(self.tmp.name, "cache") + keymap.CACHE = os.path.join(self.tmp.name, "cache", "glassMxrph", "keymap") + self.git("init", "-q", "-b", "main", self.repo, cwd=self.tmp.name) + os.makedirs(os.path.join(self.repo, "config")) + self.write(ZMK) + self.commit("first") + + def tearDown(self): + self.tmp.cleanup() + + def git(self, *args, cwd=None): + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=cwd or self.repo, check=True, + capture_output=True) + + def write(self, text): + with open(os.path.join(self.repo, "config", "kb.keymap"), "w") as f: + f.write(text) + + def commit(self, message): + self.git("add", "-A") + self.git("commit", "-q", "-m", message) + + def test_change_is_detected(self): + first = keymap.main({"op": "check", "repo": self.repo}) + self.assertTrue(first["ok"]) + self.assertTrue(first["changed"]) + self.assertEqual(first["sheet"]["source"], "config/kb.keymap") + self.assertEqual(first["sheet"]["layers"][0]["keys"][0]["t"], "Q") + + again = keymap.main({"op": "check", "repo": self.repo}) + self.assertFalse(again["changed"]) + + self.write(ZMK.replace("&kp Q", "&kp W")) + self.commit("swap Q") + after = keymap.main({"op": "check", "repo": self.repo}) + self.assertTrue(after["changed"]) + self.assertEqual(after["sheet"]["layers"][0]["keys"][0]["t"], "W") + self.assertEqual(after["sheet"]["subject"], "swap Q") + + cached = keymap.main({"op": "load", "repo": self.repo}) + self.assertEqual(cached["sheet"]["sha"], after["sheet"]["sha"]) + + def test_pending_redraw(self): + os.makedirs(os.path.join(self.repo, ".github", "workflows")) + with open(os.path.join(self.repo, ".github", "workflows", "draw.yml"), "w") as f: + f.write("run: keymap parse -z config/kb.keymap > drawn.yaml && keymap draw drawn.yaml\n") + with open(os.path.join(self.repo, "drawn.yaml"), "w") as f: + f.write(DRAWER) + self.commit("drawer") + self.assertFalse(keymap.main({"op": "check", "repo": self.repo})["sheet"]["pending"]) + self.write(ZMK.replace("&kp Q", "&kp W")) + self.commit("keymap only") + sheet = keymap.main({"op": "check", "repo": self.repo})["sheet"] + self.assertEqual(sheet["source"], "drawn.yaml") + self.assertTrue(sheet["pending"]) + + def test_missing_repo(self): + with self.assertRaises(RuntimeError): + keymap.main({"op": "check", "repo": os.path.join(self.tmp.name, "nope")}) + + +if __name__ == "__main__": + unittest.main()