diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000..1c2ad0e
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,17 @@
+root = true
+
+[*]
+charset = utf-8
+end_of_line = lf
+insert_final_newline = true
+indent_style = space
+trim_trailing_whitespace = true
+
+[*.py]
+indent_size = 4
+
+[*.{js,json,yml,yaml,sh}]
+indent_size = 2
+
+[*.md]
+trim_trailing_whitespace = false
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
new file mode 100644
index 0000000..f5f550c
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -0,0 +1,22 @@
+name: Bug report
+description: Report reproducible application behavior.
+body:
+ - type: textarea
+ id: environment
+ attributes:
+ label: Environment
+ description: App version, distribution, Python/GTK/Libadwaita versions, desktop/compositor, and Bolt or Bluetooth.
+ validations:
+ required: true
+ - type: textarea
+ id: reproduction
+ attributes:
+ label: Steps, expected result, and actual result
+ validations:
+ required: true
+ - type: textarea
+ id: diagnostics
+ attributes:
+ label: Diagnostics and relevant logs
+ description: Include doctor --json or a traceback when relevant. Remove device serials, usernames, and other private information.
+ render: text
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000..9fe61d8
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,5 @@
+blank_issues_enabled: true
+contact_links:
+ - name: Security reporting
+ url: https://github.com/Dijo-404/mx4-linux/blob/main/SECURITY.md
+ about: Read private reporting guidance before sharing security-sensitive information.
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
new file mode 100644
index 0000000..9aa5d84
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -0,0 +1,16 @@
+name: Feature request
+description: Describe a mouse-control or desktop workflow improvement.
+body:
+ - type: textarea
+ id: problem
+ attributes:
+ label: What task is difficult today?
+ validations:
+ required: true
+ - type: textarea
+ id: proposal
+ attributes:
+ label: Proposed behavior
+ description: Include the target desktop/compositor and connection type if relevant.
+ validations:
+ required: true
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000..f02c297
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,11 @@
+version: 2
+updates:
+ - package-ecosystem: github-actions
+ directory: /
+ schedule:
+ interval: weekly
+ - package-ecosystem: pip
+ directory: /
+ schedule:
+ interval: monthly
+ open-pull-requests-limit: 3
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 0000000..1cc96ca
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,10 @@
+Describe the problem and the behavior after this change.
+
+## Validation
+
+- [ ] Python checks pass (`pytest`, `ruff`, compilation).
+- [ ] Launcher/package checks pass when packaging changes (`npm test`, `npm run check`, `npm run test:package`).
+- [ ] GUI changes checked with `gui --demo`, including reduced motion and keyboard access.
+- [ ] Documentation and `CHANGELOG.md` updated for user-visible changes.
+
+State any remaining limitations. For hardware changes, distinguish simulated checks from physical-device observations and describe settings changed.
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..7b39c26
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,96 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ workflow_dispatch:
+ workflow_call:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ci-${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ python:
+ name: Python ${{ matrix.python }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 15
+ strategy:
+ fail-fast: false
+ matrix:
+ python: ['3.11', '3.14']
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
+ with:
+ python-version: ${{ matrix.python }}
+ cache: pip
+ cache-dependency-path: pyproject.toml
+ - name: Install native build dependencies
+ run: |
+ sudo apt-get update
+ sudo apt-get install --no-install-recommends -y gcc pkg-config libdbus-1-dev libcairo2-dev libgirepository-2.0-dev gir1.2-gtk-4.0 gir1.2-adw-1
+ - name: Install application and development tools
+ run: python -m pip install -e '.[test,dev]'
+ - name: Check Python correctness
+ run: |
+ python -m ruff check src tests scripts/gtk-smoke.py
+ python -m compileall -q src tests
+ python -m pytest -q
+ - name: Validate shell scripts and udev rules
+ run: |
+ for script in scripts/*.sh; do bash -n "$script"; done
+ udevadm verify data/70-mx4-linux.rules data/71-mx4-input.rules
+ - name: Build Python distributions
+ run: python -m build
+
+ npm:
+ name: npm / Node ${{ matrix.node }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ strategy:
+ fail-fast: false
+ matrix:
+ node: ['22', '24']
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
+ with:
+ node-version: ${{ matrix.node }}
+ - name: Test launcher and install packed application
+ run: |
+ npm ci --ignore-scripts
+ npm test
+ npm run check
+ npm run test:package
+
+ gtk:
+ name: Native runtime and GTK smoke
+ runs-on: ubuntu-24.04
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
+ with:
+ node-version: '24'
+ - name: Install desktop dependencies
+ run: |
+ sudo apt-get update
+ sudo apt-get install --no-install-recommends -y python3-venv python3-gi python3-gi-cairo python3-cairo python3-dbus gir1.2-gtk-4.0 gir1.2-adw-1 xvfb xauth dbus-x11
+ - name: Install the npm archive, set up its native runtime, and preview GUI
+ env:
+ PYTHON: /usr/bin/python3
+ GDK_BACKEND: x11
+ run: |
+ npm ci --ignore-scripts
+ dbus-run-session -- xvfb-run -a npm run test:native
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..faae0a5
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,52 @@
+name: Build release packages
+
+on:
+ release:
+ types: [published]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ checks:
+ uses: ./.github/workflows/ci.yml
+ package:
+ name: Build verified release artifacts
+ needs: checks
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
+ with:
+ python-version: '3.14'
+ - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
+ with:
+ node-version: '24'
+ - name: Verify release tag matches package versions
+ env:
+ RELEASE_TAG: ${{ github.event.release.tag_name }}
+ run: |
+ node --input-type=module - <<'JS'
+ import assert from 'node:assert/strict';
+ import { readFileSync } from 'node:fs';
+ const { version } = JSON.parse(readFileSync('package.json', 'utf8'));
+ if (process.env.RELEASE_TAG) assert.equal(process.env.RELEASE_TAG, `v${version}`, 'Use a release tag matching the package version');
+ JS
+ - name: Build archives and checksums
+ run: |
+ python -m pip install 'build>=1.2,<2'
+ python -m build
+ npm ci --ignore-scripts
+ npm run check
+ npm pack --pack-destination dist
+ sha256sum dist/*.whl dist/*.tar.gz dist/*.tgz > dist/SHA256SUMS
+ - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
+ with:
+ name: mx4-linux-release
+ path: dist/
+ if-no-files-found: error
+ retention-days: 30
diff --git a/.gitignore b/.gitignore
index bd87479..c9c4963 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,5 +6,8 @@ __pycache__/
.pytest_cache/
build/
dist/
+node_modules/
+*.tgz
+.ruff_cache/
evidence/artifacts/
evidence/*.png
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..fb659ec
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,37 @@
+# Changelog
+
+User-visible changes are recorded here. This project follows semantic versioning; 0.x releases may change configuration or behavior with migration notes.
+
+## [Unreleased]
+
+### Added
+
+- Linux npm launcher with explicit per-user Python setup, bundled application sources and icons, and `npm start` support.
+- Separate Mouse, Actions and Profiles views, an animated wheel preview, and clearer ring and Smart Actions controls.
+- Compact circular icon ring with animated radial opening, outward hover labels, a center close button and a live labeled editor preview.
+- Optional side menus containing up to six existing routines, with pointer and keyboard selection and safe held-button release.
+- Finite ring transitions and selection feedback that honor the desktop's reduced-motion preference.
+- GitHub CI for Python 3.11/3.14, Node 22/24, package installation and native GTK smoke checks; validated release archives and checksums.
+- Development checks, contribution conventions and issue/PR templates.
+
+### Improved
+
+- Keep Python dependencies in `pyproject.toml` and share the packaged SVG icon with the README.
+- Detect unused imports in development and CI checks.
+- Setting changes update the confirmed value without a complete follow-up discovery scan; saving profiles keeps existing device data.
+- Ring rendering reuses native labels and controls, reducing work during animation.
+- Hardware writes and listener startup address the selected receiver slot; setting writes construct only the needed capabilities while preserving live validation and readback.
+- Bounded optional paired-node discovery removes repeated one-second waits; event bursts share a GTK dispatch while preserving movement and release order.
+
+## [0.2.0] — unreleased baseline
+
+- Native GTK 4 / Libadwaita control panel and CLI using Solaar 1.1.20.
+- Supported settings, diagnostics, haptic playback and manual hardware profiles.
+- Eight-position Actions Ring, Smart Actions editor and opt-in extra-button bindings for Niri on Wayland.
+- Cancellable action execution, focus restoration and exact event-reporting cleanup.
+- Optional native wtype helper, separate hidraw/uinput access installers, and application icon.
+
+Physical settings, panel interaction, haptic feel, Bluetooth and reconnect behavior still need interactive validation. Flow remains deferred.
+
+[Unreleased]: https://github.com/Dijo-404/mx4-linux/commits/main
+[0.2.0]: https://github.com/Dijo-404/mx4-linux
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 78d7bcc..3e928c9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -11,12 +11,31 @@ git clone https://github.com/Dijo-404/mx4-linux.git
cd mx4-linux
./scripts/setup.sh
.venv/bin/python -m pytest -q
+.venv/bin/python -m ruff check src tests scripts/gtk-smoke.py
.venv/bin/python -m compileall -q src tests
for script in scripts/*.sh; do bash -n "$script"; done
+npm ci --ignore-scripts
+npm test
+npm run check
+npm run test:package
```
+Build outputs (`build/`, `dist/`), pytest/Ruff caches, `__pycache__/` and source `*.egg-info/` directories are generated and can be removed when no longer needed. Keep `.venv/` for the installed development runtime. `.tools/` also holds the installed wtype checksum used by setup; its downloaded source and build directories are disposable.
+
+The tracked records in `evidence/` support the research and validation guides. Current documentation images live in `docs/assets/`; the README shares the application icon from `src/mx4_linux/icons/`.
+
Use `.venv/bin/mx4-linux gui --demo` to inspect the settings interface without device access, and `actions run ID --dry-run` or `ring --preview` to inspect desktop behavior without executing a routine. Tests use simulated hardware; passing them is not a physical-device verification.
+On a graphical session, `GDK_BACKEND=x11 .venv/bin/python scripts/gtk-smoke.py` checks demo loading, finite wheel/ring animations, reduced motion and the editor. For a headless machine with Xvfb installed:
+
+```bash
+GDK_BACKEND=x11 dbus-run-session -- xvfb-run -a .venv/bin/python scripts/gtk-smoke.py
+```
+
+The smoke script uses a temporary configuration directory and preview callbacks; it does not execute routines or write hardware settings. For UI changes, also check the actual window at narrow and normal widths, keyboard navigation, visible focus, both color schemes and disabled desktop animations.
+
+`PYTHON=/usr/bin/python3 GDK_BACKEND=x11 npm run test:native` additionally installs the real npm archive into a temporary prefix, performs setup in an isolated XDG directory, checks its CLI and exercises the installed GTK runtime. It downloads Python dependencies; use the system interpreter that can import GObject. CI runs this under Xvfb.
+
If changing udev files, check their syntax when `udevadm` is available:
```bash
@@ -31,9 +50,32 @@ udevadm verify data/70-mx4-linux.rules data/71-mx4-input.rules
- Preserve opt-in diversion, exact reporting restoration and cancelled cleanup releases. Include regression coverage for meaningful lifecycle or validation changes.
- Keep command steps as explicit argument arrays, validate complete documents before writes and preserve cancellation/held-key cleanup.
- Update documentation when commands, configuration, access rules or supported behavior change.
+- Add a concise user-visible entry under `Unreleased` in [CHANGELOG.md](CHANGELOG.md).
Do not bundle vendor installers, downloaded proprietary binaries, virtual environments, build caches or personal configuration. Avoid user paths, device serials and unrelated desktop content in new screenshots and reports.
+## Code conventions and boundaries
+
+- Use Python 3.11-compatible syntax, four-space indentation, descriptive `snake_case` names and small functions. Match the touched module's style; keep unrelated formatting out of the diff. Ruff checks syntax, definite correctness errors and unused imports through the checked-in configuration.
+- Keep GTK construction and widget updates on the GTK thread. Run device I/O and potentially blocking desktop work off that thread; return results through the existing callbacks. Do not rescan hardware when a confirmed write response is sufficient.
+- Keep Solaar imports and handles in workers. UI modules depend on the backend interface, and animation/state models remain testable without GTK or hardware. Add a layer only when a concrete second caller needs it.
+- Animate on GTK's frame clock using elapsed time. Stop callbacks when motion settles or a widget hides; honor `gtk-enable-animations`. Native labels, keyboard operation and accessible names must remain available.
+- Node code uses built-in modules, explicit argument arrays and two-space indentation. The npm launcher stays a small bridge to the native application. Keep npm installation free of hooks that install Python, invoke sudo, access devices or start the GUI.
+- Validate external JSON and process responses before use. Preserve atomic configuration writes, cancellation, worker deadlines and actionable error messages. Avoid logging serials or private desktop contents.
+- Add a focused regression test for changed validation, lifecycle or subprocess behavior. Avoid tests that only repeat constants or widget construction without checking behavior.
+
+The architecture guide describes responsibilities. Keep shared behavior in its existing owner instead of duplicating it across GUI, CLI and package entry points. `.editorconfig` defines whitespace, `pyproject.toml` defines Python metadata/checks, and `package.json` defines the npm launch surface.
+
+## CI and release preparation
+
+CI tests Python 3.11 and 3.14, Node 22 and 24, actual npm archive installation, and a native GTK demo smoke test on Ubuntu 24.04. Native tests do not establish Niri/Wayland or physical hardware compatibility. GitHub Actions dependencies are pinned by commit; Dependabot proposes updates for review. Solaar updates need deliberate worker compatibility validation because internal APIs are used.
+
+Before a release, update `pyproject.toml`, `src/mx4_linux/__init__.py`, `package.json` and `package-lock.json` together, move reviewed changelog entries into a dated version, then run the checks above. `npm run check` rejects differing package versions and missing runtime assets. Inspect `npm pack --dry-run` and build Python distributions with `.venv/bin/python -m build`.
+
+The **Build release packages** workflow runs manually or when a GitHub release is published. It requires CI, verifies a release tag of `vVERSION`, and uploads wheel, source archive, npm archive and SHA-256 checksums as an Actions artifact. It does not publish to npm or PyPI. Download and review that artifact before a maintainer publishes it.
+
+For an initial npm release, verify ownership/availability of the package name, use an npm account with publishing rights and 2FA, and publish the reviewed `.tgz` with `npm publish ./mx4-linux-VERSION.tgz --access public`. Configure [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/) before adding automatic registry publication; [npm package metadata](https://docs.npmjs.com/cli/v11/configuring-npm/package-json/) documents `bin`, packaged files and platform requirements. Registry configuration and publication are maintainer actions outside application setup.
+
## Bug reports and hardware validation
Include the application version, distribution, Python/GTK/Libadwaita versions, compositor/session, Bolt or Bluetooth connection, steps to reproduce and the actual error. Relevant `doctor --json` and `devices --json` output helps; redact identifying details first.
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..e5d508a
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,7 @@
+include CHANGELOG.md CONTRIBUTING.md SECURITY.md package*.json .editorconfig
+recursive-include bin *.js
+recursive-include scripts *.sh *.py *.js
+recursive-include data *.rules
+recursive-include docs *.md *.png
+recursive-include tests *.py *.js
+recursive-include .github *.yml *.md
diff --git a/README.md b/README.md
index e11042e..8fbe043 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
-
+
# MX4 Linux
@@ -22,7 +22,7 @@
-
+
> [!NOTE]
@@ -35,8 +35,10 @@ MX4 Linux is a GTK 4 / Libadwaita application and CLI for MX Master 4 owners on
### Features
- **Control supported mouse settings.** Adjust DPI, wheel modes and direction, SmartShift, haptic strength, panel force and built-in button assignments when reported by the device.
-- **Choose from eight ring actions.** Hold the haptic panel, move and release, or select with a click or keyboard.
+- **Choose from eight ring actions.** Use compact icon buttons, outward labels and a center close control. Hold the haptic panel, move and release, or select with a click or keyboard.
+- **Group related actions.** Turn a position into a side menu of up to six existing routines. The editor shows a live ring preview and keeps labels and assignments together.
- **Build Smart Actions.** Combine shortcuts, application launches, text, delays and Niri commands, with optional exact application conditions.
+- **Find controls quickly.** Mouse, Actions and Profiles have separate views; the wheel preview and ring respond with finite animations and respect the desktop animation preference.
- **Reuse manual profiles.** Save current hardware settings and apply them by name; haptic playback is excluded.
- **Inspect before changing.** JSON discovery, access diagnostics, simulated GUI preview and action dry runs are available from the CLI.
@@ -71,6 +73,28 @@ cd mx4-linux
Setup creates `.venv` with system site packages, installs MX4 Linux and pinned Solaar 1.1.20, and attempts to build the optional Wayland keyboard helper when needed. It installs no system service or autostart entry.
+### Launch with npm
+
+The npm package launches the same native GTK application. Install the system dependencies above and Node.js 22+, then either run from this checkout:
+
+```bash
+npm ci --ignore-scripts
+npm run setup
+npm start
+npm start -- gui --demo
+```
+
+Or build and install the self-contained local package:
+
+```bash
+npm pack
+npm install --global --prefix "$HOME/.local" ./mx4-linux-0.2.0.tgz
+~/.local/bin/mx4-linux setup
+~/.local/bin/mx4-linux
+```
+
+Add `~/.local/bin` to your `PATH` to use `mx4-linux` directly. No npm registry release has been published by this change. npm installation runs no setup hooks; the explicit `setup` command downloads Python dependencies into a versioned user environment, without sudo. GTK libraries and Python GObject remain system dependencies. See [npm installation](docs/install.md#npm-package) for runtime locations, updates and removal.
+
If `doctor` reports denied device access, install the device rule:
```bash
@@ -114,7 +138,7 @@ Saved settings remain in `${XDG_CONFIG_HOME:-$HOME/.config}/mx4-linux/`. See [co
.venv/bin/mx4-linux # open the control panel
```
-In **Actions Ring and Smart Actions**, click **Enable**, then use the haptic panel from the application you want to control. **Configure** edits routines, eight ring assignments and optional extra-button bindings. Keep MX4 Linux running while using mouse integration; **Disable** or closing the app restores the selected buttons' prior reporting flags.
+Open the **Actions** tab and click **Enable**, then use the haptic panel from the application you want to control. **Try the ring** previews selection; **Edit actions** opens native forms for routines, eight ring assignments and optional extra-button bindings. Keep MX4 Linux running while using mouse integration; **Disable** or closing the app restores the selected buttons' prior reporting flags.
## Usage
@@ -148,8 +172,8 @@ These keys apply while the Actions Ring is open:
| :--- | :--- |
| `1`–`8` | Select and run the corresponding position, clockwise from the top. |
| Arrow keys | Move the selection. |
-| `Enter` | Run the selected action. |
-| `Escape` | Cancel the ring. |
+| `Enter` | Run the selected action or open its group. |
+| `Escape` | Return from an action group, or close the ring. |
### Examples
@@ -210,7 +234,8 @@ Without a saved desktop file, defaults provide Overview, Screenshot, Terminal, N
| `XDG_CONFIG_HOME` | Overrides the configuration root; defaults to `~/.config`. |
| `XDG_DATA_HOME` | Overrides the desktop launcher's data root; defaults to `~/.local/share`. |
| `TERMINAL` | Preferred terminal command for the default Terminal action, if executable. |
-| `PYTHON` | Python executable used by `scripts/setup.sh`; defaults to `python3`. |
+| `PYTHON` | System Python used by source setup or `mx4-linux setup`; defaults to `python3`. |
+| `MX4_LINUX_PYTHON` | npm launcher override for an existing Python environment with the runtime dependencies installed. |
| `WAYLAND_DISPLAY` | Identifies the active Wayland session for native input and optional helper setup. |
| `XDG_SESSION_TYPE`, `XDG_CURRENT_DESKTOP` | Included in `doctor` diagnostics. |
@@ -281,10 +306,13 @@ Read [docs/architecture.md](docs/architecture.md) and [CONTRIBUTING.md](CONTRIBU
```bash
git clone https://github.com/Dijo-404/mx4-linux.git
cd mx4-linux
-./scripts/setup.sh # install runtime and test dependencies
+./scripts/setup.sh # install runtime and development tools
.venv/bin/python -m pytest -q # run automated checks
+.venv/bin/python -m ruff check src tests # syntax, undefined names and unused imports
.venv/bin/python -m compileall -q src tests # check Python compilation
for script in scripts/*.sh; do bash -n "$script"; done # check shell syntax
+npm ci --ignore-scripts
+npm test && npm run check && npm run test:package # launcher and packed install
```
The recorded validation includes simulated hardware tests, live Bolt discovery, event reporting restoration, a GTK ring preview and controlled native input. These checks do not establish physical setting behavior or real panel selection; see [validation notes](docs/validation.md).
@@ -358,6 +386,7 @@ The optional shortcut fallback rule is installed with `./scripts/install-input-a
| [Validation](docs/validation.md) | Recorded checks and remaining hardware work |
| [Linux support research](docs/linux-support-research.md) | Protocol sources and implementation constraints |
| [Installer analysis](docs/installer-analysis.md) | Static artifact investigation and evidence limits |
+| [Changelog](CHANGELOG.md) | User-visible changes and release history |
## Contributing
diff --git a/bin/mx4-linux.js b/bin/mx4-linux.js
new file mode 100755
index 0000000..d90449a
--- /dev/null
+++ b/bin/mx4-linux.js
@@ -0,0 +1,91 @@
+#!/usr/bin/env node
+import { spawn, spawnSync } from 'node:child_process';
+import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { homedir, constants, tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = dirname(dirname(fileURLToPath(import.meta.url)));
+const { version } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
+const dataRoot = process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share');
+const runtime = join(dataRoot, 'mx4-linux', 'runtime', version);
+const runtimePython = join(runtime, 'bin', 'python');
+const ready = join(runtime, '.ready');
+const args = process.argv.slice(2);
+
+function run(command, arguments_) {
+ const result = spawnSync(command, arguments_, { stdio: 'inherit' });
+ if (result.error) throw new Error(`Cannot run ${command}: ${result.error.message}`);
+ if (result.status !== 0) throw new Error(`${command} failed. Check the output above and rerun mx4-linux setup.`);
+}
+
+function setup() {
+ if (args.length !== 1) throw new Error('Usage: mx4-linux setup (select the system interpreter with PYTHON=/path/to/python3).');
+ const python = process.env.PYTHON || 'python3';
+ run(python, ['-c', `
+import sys
+if sys.version_info < (3, 11):
+ raise SystemExit('Python 3.11 or later is required.')
+try:
+ import gi
+ gi.require_version('Gtk', '4.0')
+ gi.require_version('Adw', '1')
+ gi.require_foreign('cairo')
+ from gi.repository import Gtk, Adw
+ if Gtk.get_major_version() < 4 or Gtk.get_minor_version() < 12 or Adw.get_major_version() < 1 or (Adw.get_major_version() == 1 and Adw.get_minor_version() < 4):
+ raise ValueError('GTK 4.12+ and Libadwaita 1.4+ are required')
+except (ImportError, ValueError) as exc:
+ raise SystemExit(f'Install system Python GObject with Cairo support, GTK 4.12+ and Libadwaita 1.4+ first. See https://github.com/Dijo-404/mx4-linux/blob/main/docs/install.md: {exc}')
+`]);
+ mkdirSync(dirname(runtime), { recursive: true });
+ rmSync(ready, { force: true });
+ run(python, ['-m', 'venv', '--system-site-packages', runtime]);
+ // setuptools writes metadata while building; npm may install into a read-only location.
+ const staging = mkdtempSync(join(tmpdir(), 'mx4-linux-setup-'));
+ try {
+ for (const file of ['pyproject.toml', 'README.md', 'LICENSE']) copyFileSync(join(root, file), join(staging, file));
+ cpSync(join(root, 'src'), join(staging, 'src'), {
+ recursive: true,
+ filter: source => !source.endsWith('__pycache__') && !source.endsWith('.egg-info'),
+ });
+ run(runtimePython, ['-m', 'pip', 'install', '--disable-pip-version-check', '--upgrade', staging]);
+ } finally {
+ rmSync(staging, { recursive: true, force: true });
+ }
+ writeFileSync(ready, `${version}\n`, { mode: 0o600 });
+ console.log(`Ready. Run mx4-linux, or mx4-linux gui --demo. Runtime: ${runtime}`);
+}
+
+function launch() {
+ const python = process.env.MX4_LINUX_PYTHON
+ || (existsSync(ready) && existsSync(runtimePython) ? runtimePython : null)
+ || (existsSync(join(root, '.venv', 'bin', 'python')) ? join(root, '.venv', 'bin', 'python') : null);
+ if (!python) {
+ if (args[0] === '--help' || args[0] === '-h') {
+ console.log('MX4 Linux — native Linux mouse controls\n\n mx4-linux setup Install the per-user Python runtime\n mx4-linux [gui --demo] Open the control panel\n mx4-linux doctor Check device access\n\nInstall system GTK 4.12+, Libadwaita 1.4+ and Python GObject first.\nAfter setup, mx4-linux --help lists every application command.');
+ return;
+ }
+ throw new Error('Run mx4-linux setup first (or npm run setup in a checkout). See docs/install.md for system dependencies.');
+ }
+ const source = join(root, 'src');
+ const env = { ...process.env, PYTHONPATH: [source, process.env.PYTHONPATH].filter(Boolean).join(':') };
+ const child = spawn(python, ['-m', 'mx4_linux', ...args], { stdio: 'inherit', env });
+ for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => child.kill(signal));
+ child.on('error', error => {
+ console.error(`mx4-linux: Cannot start Python: ${error.message}. Rerun mx4-linux setup after Python upgrades.`);
+ process.exitCode = 1;
+ });
+ child.on('exit', (code, signal) => {
+ process.exitCode = code ?? (128 + (constants.signals[signal] || 1));
+ });
+}
+
+try {
+ if (process.platform !== 'linux') throw new Error('MX4 Linux requires Linux.');
+ if (args.length === 1 && args[0] === '--version') console.log(`mx4-linux ${version}`);
+ else if (args[0] === 'setup') setup();
+ else launch();
+} catch (error) {
+ console.error(`mx4-linux: ${error.message}`);
+ process.exitCode = 1;
+}
diff --git a/docs/architecture.md b/docs/architecture.md
index dfd5afb..cf093ea 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -13,17 +13,22 @@ MX4 Linux has three boundaries: the native user interface, isolated HID++ worker
| `profiles.py` | Manual snapshots, locked atomic saves, profile validation and sequential application. |
| `desktop.py` | GUI desktop integration, focus capture/restore, routine lifecycle and listener events. |
| `desktop_editor.py` | Ring assignment and Smart Actions editor. |
-| `ring.py`, `ring_model.py` | GTK overlay and testable eight-sector interaction state. |
+| `ring.py`, `ring_model.py` | GTK icon overlay, circular pointer geometry, held eight-sector interaction and optional side menus. |
+| `ring_icons.py`, `ring_preview.py` | Step-based native icon mapping and the editor’s static assignment diagram. |
| `event_session.py` | Nonblocking subprocess lifecycle and session-tagged event delivery. |
| `event_worker.py` | Retained HID++ event handle, temporary control reporting and restoration. |
| `actions.py` | Desktop schema, defaults, persistence, execution and input backends. |
| `gtk_support.py` | GTK/Adwaita imports and optional layer-shell loading. |
+| `motion.py`, `wheel.py` | Frame-time transitions and a finite, illustrative wheel preview without hardware polling. |
+| `bin/mx4-linux.js` | Linux npm entry point, explicit per-user runtime setup, argument/signal forwarding. |
## Hardware requests
The UI uses a one-shot subprocess for scans and writes. This keeps Solaar's GTK 3 imports outside the GTK 4 process and contains HID handles. The backend sends a JSON request and waits up to 90 seconds for a JSON response. Failures become visible application errors.
-Discovery limits itself to supported MX Master 4 settings. Controls and numeric ranges come from the device through Solaar; unreadable settings are omitted with diagnostics. The worker avoids applying Solaar's saved settings during discovery. A write validates its value against the discovered schema, applies it and checks readback. `haptic-play` is command-only and has no readback value.
+Discovery limits itself to supported MX Master 4 settings. Controls and numeric ranges come from the device through Solaar; unreadable settings are omitted with diagnostics. The worker avoids applying Solaar's saved settings during discovery. Writes address the selected receiver slot and construct only the requested setting and any coupled wheel settings, then validate, apply and read back the result. `haptic-play` is command-only and has no readback value. The worker bounds Solaar's optional paired-node search instead of repeating its default one-second wait; HID++ reply deadlines remain intact.
+
+The GUI applies confirmed write values to existing controls instead of running another discovery scan and rebuilding the page. Coupled wheel readbacks update related controls without issuing extra writes. A failed write invalidates uncertain values and refreshes from hardware. Saving a profile uses the existing confirmed snapshot on the background executor and does not rescan the mouse.
Profile application validates a full plan before writing. It then makes sequential hardware changes, so it cannot provide a transaction across a disconnect or device failure. Errors state how many changes completed. Profiles never snapshot or replay waveform commands.
@@ -37,12 +42,20 @@ The settings worker uses HID++ software ID `0xC`; the event worker uses `0xD`, d
Each event session has an identity. Old readers cannot mutate a replacement session's lifecycle or emit events into it; the GUI also checks session identity for events already queued on the GTK loop. Cleanup releases are explicitly cancelled, so disconnecting or disabling while holding the panel cannot commit a ring selection. Readiness is cleared before restoration finishes, and shutdown waits off the GTK thread.
+An event burst schedules one GTK idle dispatch. The queue preserves each XY packet and its order relative to button releases; summing deltas would change selection because the ring clamps movement at its radius. Listener setup addresses the selected receiver slot directly.
+
## Ring and focus
-The ring uses an eight-sector model with a center dead zone. It supports raw relative mouse movement while held, pointer selection after a short click and keyboard selection. It opens at screen center, without warping the pointer. Layer-shell gives it an overlay and exclusive keyboard handling on supported Wayland desktops; otherwise it can be a regular window.
+Held movement keeps the calibrated eight-sector model and center dead zone. After a short click, pointer selection instead hits the actual round icon faces; the gaps and square widget corners cannot execute actions. The center close button and native keyboard focus remain available. It opens at screen center, without warping the pointer. Layer-shell gives it an overlay and exclusive keyboard handling on supported Wayland desktops; otherwise it can be a regular window.
Before opening the ring, desktop integration records Niri's focused application/window. Before executing the chosen action, it restores that focus and verifies the original window still exists. A vanished target stops execution. Ring/button dispatch refuses shortcuts and text when an MX4 configuration window is the target; direct CLI `actions run` does not use this GUI focus guard. A preview follows the selection UI but prints steps without action execution or haptic feedback.
+Animations use GTK frame callbacks and elapsed time. Wheel motion settles after an impulse; ring callbacks stop when transitions finish or the ring hides. GTK's `gtk-enable-animations` preference disables decorative motion. Labels and buttons are native widgets reused across frames. Opening spreads the icons outward over 180 ms; side menus reveal over 160 ms and labels fade over 100 ms. Hit testing follows the painted positions. Emerging children cannot receive pointer clicks while they overlap their parent, another main button or each other. Ring selection dispatches immediately after hiding; no exit animation delays the action. The wheel illustration previews scrolling visually and does not read or claim to represent physical wheel rotation.
+
+Optional `ring_groups` references existing routines by slot. Hovering or choosing a grouped position opens its side menu; a held parent release latches the menu, while an explicit child choice dispatches its routine. This does not change direct CLI execution of the parent action. Version 1 documents without groups remain valid. The editor prevalidates group references, preserves ID renames and removes deleted children before saving.
+
+The existing 80 ms compositor focus handoff before input execution remains. It allows Niri focus restoration to reach the target application and is separate from animation timing.
+
## Smart Actions
The whole configuration is validated before saving or executing. Routines contain explicit steps: Niri actions, command argument arrays, keyboard chords, text or delays. Command steps start a process without a shell and do not wait for the application to close. Their processes are reaped in the background.
@@ -57,6 +70,10 @@ Hardware profiles and desktop configuration are separate versioned JSON document
Setup installs into a local virtual environment with system site packages for GObject. Mouse hidraw access and optional `/dev/uinput` access have separate udev installers. Each uses active-seat `uaccess`, with a dry-run mode. The desktop launcher points directly to the checkout; no compositor configuration or login autostart is changed.
+The npm launcher is a thin distribution boundary around the same Python modules. Its tarball includes source and assets, with no npm dependencies or install hooks. Explicit setup builds a versioned environment under the user's XDG data directory with access to system GObject bindings. The launcher forwards CLI arguments and termination signals, loads its own bundled source, and leaves device access to the existing optional installers. A readiness marker prevents an interrupted setup from being selected as a completed runtime.
+
+Python runtime dependencies and optional test/development tools live in `pyproject.toml`. CI installs the project and its extras directly, checks supported Python and Node versions, native GTK demo widgets, subprocess cleanup, and installation of the actual npm archive. Release workflows build Python/npm archives with checksums after CI passes and verify release tags against the package version. Publishing remains a separate maintainer action.
+
## Verification boundaries
Tests simulate device schemas, writes, protocol replies and lifecycle races. Recorded live checks separately cover Bolt discovery, exact listener reporting restoration, GTK preview and controlled native input. They do not establish actual panel press/move/release, haptic feel, physical settings behavior or Bluetooth reliability. See [validation.md](validation.md) and retain this distinction when reporting new checks.
diff --git a/docs/assets/action-editor-ring.png b/docs/assets/action-editor-ring.png
new file mode 100644
index 0000000..f75f05a
Binary files /dev/null and b/docs/assets/action-editor-ring.png differ
diff --git a/docs/assets/actions-ring-groups.png b/docs/assets/actions-ring-groups.png
new file mode 100644
index 0000000..ede6fee
Binary files /dev/null and b/docs/assets/actions-ring-groups.png differ
diff --git a/docs/assets/actions-ring.png b/docs/assets/actions-ring.png
index d641d04..44acc55 100644
Binary files a/docs/assets/actions-ring.png and b/docs/assets/actions-ring.png differ
diff --git a/docs/assets/logo.svg b/docs/assets/logo.svg
deleted file mode 100644
index c18f921..0000000
--- a/docs/assets/logo.svg
+++ /dev/null
@@ -1,1642 +0,0 @@
-
-
-
diff --git a/docs/configuration.md b/docs/configuration.md
index e157316..05651ca 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -4,7 +4,7 @@ MX4 Linux separates hardware profiles from desktop actions. Both use `$XDG_CONFI
## Desktop configuration
-`desktop.json` holds the ring, routines, button bindings and feedback preference. Edit it through **Configure** in the GUI, or export the complete document before changing it:
+`desktop.json` holds the ring, routines, button bindings and feedback preference. Edit it through **Actions → Edit actions** in the GUI, or export the complete document before changing it:
```bash
.venv/bin/mx4-linux actions show > desktop.json
@@ -14,12 +14,13 @@ MX4 Linux separates hardware profiles from desktop actions. Both use `$XDG_CONFI
`validate` checks without saving or executing. `import` validates then replaces the saved document. Disable and re-enable mouse integration after importing changed button bindings while the GUI is running. Saving in the GUI stops mouse integration; enable it again afterwards.
-All top-level fields are required. Unknown fields are rejected. The file and its serialized configuration are limited to 1 MiB.
+All top-level fields except `ring_groups` are required. Unknown fields are rejected. The file and its serialized configuration are limited to 1 MiB.
| Field | Type and limits | Default when no file exists |
| :--- | :--- | :--- |
| `version` | Integer, exactly `1` | `1` |
| `ring` | Exactly eight existing action IDs, clockwise from the top; IDs may repeat | `overview`, `screenshot`, `terminal`, `workspace-next`, `paste`, `copy`, `undo`, `workspace-previous` |
+| `ring_groups` | Optional object mapping decimal ring positions `"0"`–`"7"` to 1–6 distinct existing action IDs in display order | Absent; each position runs its assigned action directly |
| `actions` | Object containing 1–128 named routines | Eight built-in routines listed below |
| `button_bindings` | Object mapping supported decimal button IDs to existing action IDs | `{}` |
| `ring_button` | Integer: one of `82`, `83`, `86`, `195`, `196`, `416` | `416` (haptic panel) |
@@ -27,6 +28,18 @@ All top-level fields are required. Unknown fields are rejected. The file and its
`button_bindings` cannot assign the selected `ring_button`. Supported IDs are a configuration allowlist; the listener also verifies that the connected device supports each selected control. Primary left/right click and scrolling are excluded from diversion.
+### Action groups
+
+Expand **Action groups (optional)** in the Actions Ring editor to make a position open a submenu. Its assigned routine provides the group's label and icon; choosing a child runs that child's existing routine. A group belongs to a ring position, so assigning the same routine elsewhere does not create another group. Calling the parent routine directly, including through a mouse button shortcut, still runs its normal steps.
+
+For example, this optional fragment puts three routines behind the right-hand position (position `"2"`):
+
+```json
+"ring_groups": {"2": ["copy", "paste", "undo"]}
+```
+
+Choose entries in the order you want them displayed. Empty dropdowns are omitted; leaving all six empty removes the group. Groups have one level and cannot repeat an action within the same group. Renaming a routine updates its group entries when you save. Deleting a routine removes its entries and removes groups left empty. Existing version 1 files without `ring_groups` continue to work unchanged.
+
### Routines
An action ID is 1–64 lowercase ASCII letters, digits, hyphens or underscores, starting with a letter or digit. Each routine requires:
diff --git a/docs/desktop-features.md b/docs/desktop-features.md
index 7452d8b..d311952 100644
--- a/docs/desktop-features.md
+++ b/docs/desktop-features.md
@@ -5,11 +5,15 @@ These features are Linux implementations using the MX4's HID++ event stream and
## Use the ring
1. Open MX4 Linux and wait for your mouse settings to load.
-2. Under **Actions Ring and Smart Actions**, click **Enable**.
+2. Open the **Actions** tab and click **Enable**.
3. Hold the haptic panel, move the mouse towards a position and release. A short panel click instead leaves the ring open so you can point and click.
-4. Use **Configure** to change positions, create routines or assign additional mouse buttons. Configuration changes stop mouse integration; enable it again after saving.
+4. Use **Edit actions** to change positions, create routines or assign additional mouse buttons. Configuration changes stop mouse integration; enable it again after saving.
-The eight positions run clockwise from the top. Keys **1–8** select them; arrow keys move the selection, Enter confirms, and Escape cancels. Moving within the center dead zone does not select an action. A second panel click cancels an open ring. **Preview ring** uses the same interface but prints the chosen steps without executing them or playing feedback.
+The eight circular icon buttons run clockwise from the top. Labels appear beside the hovered or keyboard-selected button; the small center **×** closes the ring. Pointer clicks target the visible circles, so the gaps do not execute actions. Keys **1–8** select them; arrow keys move the selection, Enter confirms, and Escape returns from a group or closes the ring. Moving within the center dead zone does not select an action. A second panel click cancels an open ring. **Try the ring** uses the same interface but prints the chosen steps without executing them or playing feedback. Motion follows the desktop animation preference and stops when the ring settles or closes.
+
+In **Edit actions → Actions Ring**, the live diagram shows the assignments with their labels. Click a diagram button to focus its assignment. Expand **Action groups (optional)** to choose up to six different existing routines for a position. Hovering or choosing that position opens a side menu; it does not run the parent routine. Select a child with the pointer, arrows and Enter, or keys **1–6**. When holding the panel, release over a grouped position to leave its submenu open for selection. The center **×** always cancels. Old configurations remain valid, and groups are optional.
+
+
The ring is a centered layer-shell overlay, not a cursor-position popup. It captures the original application before opening and restores that focus before executing an action. A vanished target stops the action. Shortcuts and text triggered while an MX4 configuration window is focused are refused; use the panel from the application you want to control.
@@ -19,7 +23,9 @@ Default assignments are Overview, Screenshot, Terminal, Next workspace, Paste, C
## Create a Smart Action
-Open **Configure → Smart Actions**. Choose an existing routine or create one from a shortcut, launch, text or multiple-step template. Edit its ID, display name and JSON steps. An optional `app_id` condition requires an exact match with the focused Niri application. Use `niri msg --json focused-window` to inspect that ID.
+Open **Actions → Edit actions → Smart Actions**. Choose an existing routine or create one from a shortcut, launch, text or multiple-step template. Give it a name, expand a step to edit its fields, and use **Add step** plus the move/remove controls to build the sequence. **Edit steps as JSON** exposes the same data for advanced editing; **Advanced routine settings** contains the action ID. An optional application condition requires an exact match with the focused Niri `app_id`. Use `niri msg --json focused-window` to inspect that ID. Editing and saving do not execute the routine.
+
+
Example steps:
@@ -35,7 +41,7 @@ Example steps:
The example copies from the original application, launches a terminal, waits for it to focus, and types text. Launch steps return after starting the application; a delay may be needed before interacting with a newly launched window. Niri steps use `{"type":"niri","action":"toggle-overview","args":[]}`. Commands are explicit argument arrays and are never implicitly passed through a shell.
-The whole document is validated before Save or execution. Each routine may have up to 64 steps and 60 seconds of total configured delay; execution is bounded to two minutes. The **Cancel** button stops subsequent steps. Held shortcut keys are released on cancellation/errors. A running routine rejects repeated triggers rather than building an unbounded queue.
+The whole document is validated before **Save changes** or execution. Each routine may have up to 64 steps and 60 seconds of total configured delay; execution is bounded to two minutes. **Stop routine** on the Actions tab stops subsequent steps. Held shortcut keys are released on cancellation/errors. A running routine rejects repeated triggers rather than building an unbounded queue.
The native Wayland keyboard backend uses [wtype](https://github.com/atx/wtype), pinned to release 0.4 / commit `d71be3a7b3f93b534a2823fd68cabd7ac2a02359` in `scripts/setup-wtype.sh`. It supports common modifiers, letters, digits, function keys and navigation/media keys. Unicode text uses the virtual-keyboard protocol and preserves the clipboard. Unsupported Linux key codes fall back to evdev `/dev/uinput`; an optional `scripts/install-input-access.sh` grants active-seat access if needed. The normal Niri path requires no extra privileged setup. A failed native key injection is not replayed through a second backend.
@@ -64,7 +70,7 @@ No compositor configuration or login autostart is modified automatically. If imp
## Verification and remaining interactive checks
-The physical MX Master 4 reached listener-ready with haptic-panel diversion and raw XY enabled, then stopped with the exact original reporting flags and mapping restored. [Hardware smoke record](../evidence/desktop-hardware-smoke.json). The GTK ring was opened and selected in preview mode, and native Ctrl+A / Unicode text insertion was tested against an isolated GTK entry. Tests also cover malformed packets, disconnect/cancellation, temporary flag restoration, focus checks, macro execution and session replacement.
+The physical MX Master 4 reached listener-ready with haptic-panel diversion and raw XY enabled, then stopped with the exact original reporting flags and mapping restored. [Hardware smoke record](https://github.com/Dijo-404/mx4-linux/blob/main/evidence/desktop-hardware-smoke.json). The GTK ring was opened and selected in preview mode, and native Ctrl+A / Unicode text insertion was tested against an isolated GTK entry. Tests also cover malformed packets, disconnect/cancellation, temporary flag restoration, focus checks, macro execution and session replacement.
No automated check simulates a physical panel press. Interactive confirmation remains for hold/release selection with the real mouse, haptic feedback during selection, and unplug/reconnect while holding. Bluetooth has not been exercised. See [validation notes](validation.md).
diff --git a/docs/install.md b/docs/install.md
index 14a1200..f6a81d8 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -1,6 +1,6 @@
# Installation
-MX4 Linux is installed from a source checkout. Version 0.2.0 is unreleased; no distribution package or published binary is documented here. The validated environment is Arch Linux with Python 3.14, GTK 4.24, Libadwaita 1.10 and Niri / Wayland. Other distributions need equivalent packages and remain unverified.
+MX4 Linux supports source installation and a self-contained npm package that launches the native Python/GTK application. Version 0.2.0 is unreleased; the npm archive can be built locally, and no registry publication is implied. The validated environment is Arch Linux with Python 3.14, GTK 4.24, Libadwaita 1.10 and Niri / Wayland. Other distributions need equivalent packages and remain unverified.
## System dependencies
@@ -11,7 +11,7 @@ The GUI requires Python 3.11+, Python GObject, GTK 4.12+ and Libadwaita 1.4+. In
sudo pacman -S python python-gobject gtk4 libadwaita python-pip
# Debian / Ubuntu; check that your release meets the GTK and Libadwaita minimums
-sudo apt install python3-venv python3-pip python3-gi gir1.2-gtk-4.0 gir1.2-adw-1
+sudo apt install python3-venv python3-pip python3-gi python3-gi-cairo gir1.2-gtk-4.0 gir1.2-adw-1
```
For the Actions Ring overlay, install the system `gtk4-layer-shell` library and its `Gtk4LayerShell-1.0` typelib. Package names vary by distribution. If the library or compositor support is unavailable, the ring can fall back to a normal window.
@@ -32,7 +32,7 @@ cd mx4-linux
.venv/bin/mx4-linux doctor --json
```
-`setup.sh` creates `.venv` with `--system-site-packages` so the application can use the distribution's GObject bindings. It installs the editable application, test dependencies and Solaar 1.1.20. If `uv` is installed, setup uses it; otherwise it uses the environment's pip. To select a different compatible interpreter, run `PYTHON=python3.11 ./scripts/setup.sh` with that interpreter's matching system bindings installed.
+`setup.sh` creates `.venv` with `--system-site-packages` so the application can use the distribution's GObject bindings. It installs the editable application, test/lint/build tools and Solaar 1.1.20. If `uv` is installed, setup uses it; otherwise it uses the environment's pip. To select a different compatible interpreter, run `PYTHON=python3.11 ./scripts/setup.sh` with that interpreter's matching system bindings installed.
The optional `scripts/setup-wtype.sh` downloads commit `d71be3a7b3f93b534a2823fd68cabd7ac2a02359` from wtype 0.4, verifies its source checksum and installs the built executable, MIT license and man page inside `.venv`. Download/source/build files stay under `.tools`. An existing local helper is reused only when its stored executable checksum matches.
@@ -42,6 +42,44 @@ To build the helper separately:
./scripts/setup-wtype.sh
```
+After creating a virtual environment with system site packages, `python -m pip install .` installs the application and its runtime dependencies. For an editable checkout with lint/build/test tools, use `python -m pip install -e '.[test,dev]'`. Dependencies and optional development tools are declared in `pyproject.toml`.
+
+## npm package
+
+Install the system dependencies above and Node.js 22 or later. In a source checkout:
+
+```bash
+npm ci --ignore-scripts
+npm run setup
+npm start -- gui --demo
+```
+
+Build and install an archive to launch independently of the checkout:
+
+```bash
+npm pack
+npm install --global --prefix "$HOME/.local" ./mx4-linux-0.2.0.tgz
+~/.local/bin/mx4-linux setup
+~/.local/bin/mx4-linux
+```
+
+The archive includes the Python application, icon, access-rule installers and documentation. npm installation runs no scripts and installs no Node dependencies. Add `~/.local/bin` to your `PATH` if you want to invoke `mx4-linux` without its full path.
+
+`mx4-linux setup` checks Python 3.11+, GTK 4.12+, Libadwaita 1.4+ and Python GObject, creates a virtual environment with system site packages, and installs the application and Solaar using pip. It writes to `$XDG_DATA_HOME/mx4-linux/runtime/0.2.0/` (default `~/.local/share/mx4-linux/runtime/0.2.0/`); it does not need sudo or change device permissions. `PYTHON=/usr/bin/python3 mx4-linux setup` selects the system interpreter whose GObject bindings match the installed libraries. Install system `wtype` separately for keyboard/text actions; npm setup does not build it automatically.
+
+The launcher first honors `MX4_LINUX_PYTHON=/path/to/environment/bin/python`, then a completed per-user runtime, then a checkout's `.venv`. It always loads the source shipped with the selected npm package. Arguments after `npm start --` reach the native CLI unchanged; for example, `npm start -- doctor --json`. Only `setup` is handled by the launcher.
+
+Rerun setup after a Python upgrade or package update. Updating a global package replaces its bundled source; configuration is stored separately. If setup was interrupted, the environment is not considered ready until setup succeeds. The packaged access-rule installers can be found under `$(npm root --global --prefix "$HOME/.local")/mx4-linux/scripts/`; inspect `--dry-run` before installing rules.
+
+To remove a package installed with the prefix above:
+
+```bash
+npm uninstall --global --prefix "$HOME/.local" mx4-linux
+rm -rf -- "${XDG_DATA_HOME:-$HOME/.local/share}/mx4-linux/runtime"
+```
+
+This leaves saved actions/profiles and any explicitly installed desktop launcher or udev rules. Remove them separately using the instructions below.
+
## Device access
The application needs read/write access to the relevant `/dev/hidraw*` interfaces. If your installed Solaar rules already provide it, no additional rule is needed. Otherwise:
@@ -127,6 +165,7 @@ These removal steps do not undo hardware settings already written to the mouse o
- **Mouse absent:** wake it, inspect `doctor --json`, verify access, and refresh. A receiver's presence alone does not establish an online MX Master 4.
- **Intermittent discovery or writes:** close other mouse configuration tools, including Solaar's UI, to avoid competing settings. Device operations can wait up to 90 seconds before reporting a timeout.
- **Helper build failure:** install system wtype, or install the missing build tools printed by `setup-wtype.sh` and rerun it.
+- **npm says setup is required or Python cannot start:** run `mx4-linux setup` again with the current system Python. An npm installation alone does not create the native runtime.
- **Settings reset after reconnect:** apply a saved profile manually. There is no automatic hardware-profile reapplication.
See [recorded validation](validation.md) for tested behavior and remaining physical checks.
diff --git a/docs/installer-analysis.md b/docs/installer-analysis.md
index 6fda1ff..94272c5 100644
--- a/docs/installer-analysis.md
+++ b/docs/installer-analysis.md
@@ -49,19 +49,19 @@ R-prefixed entries below are actual REA Evidence records from version 6.7.0. L1
| Ref | File | Identity |
| --- | --- | --- |
-| R1 | [rea-artifact.json](../evidence/installer/rea-artifact.json) | Inspection `ev_a458ebcb5cfa2b290aae048a1370d4b84f2dd725b06959221be61274711cfac4`; embedded inventory `ev_fdfe8f918415b78fb5d8c453e365d717ddb2aff349034007f9ca644f3c14affc` |
-| R2 | [rea-apple-graph.json](../evidence/installer/rea-apple-graph.json) | `ev_0f06ae230e91d98f2a5d5fe16e0b380a6a4409f7b7c5fc3ebe7d06d55fc1b014` |
-| R3 | [rea-extraction.json](../evidence/installer/rea-extraction.json) | `ev_b524d96264bb91f49ab18e6c98a536a2588d32b81e8ed09b7033ce516b2a71ea` |
-| L1 | [static-observations.json](../evidence/installer/static-observations.json) | `local_sha256_aae3f58937b3b9fa452afa4b8add785b487179f584a1f019d27b4b4079a390e4` |
+| R1 | [rea-artifact.json](https://github.com/Dijo-404/mx4-linux/blob/main/evidence/installer/rea-artifact.json) | Inspection `ev_a458ebcb5cfa2b290aae048a1370d4b84f2dd725b06959221be61274711cfac4`; embedded inventory `ev_fdfe8f918415b78fb5d8c453e365d717ddb2aff349034007f9ca644f3c14affc` |
+| R2 | [rea-apple-graph.json](https://github.com/Dijo-404/mx4-linux/blob/main/evidence/installer/rea-apple-graph.json) | `ev_0f06ae230e91d98f2a5d5fe16e0b380a6a4409f7b7c5fc3ebe7d06d55fc1b014` |
+| R3 | [rea-extraction.json](https://github.com/Dijo-404/mx4-linux/blob/main/evidence/installer/rea-extraction.json) | `ev_b524d96264bb91f49ab18e6c98a536a2588d32b81e8ed09b7033ce516b2a71ea` |
+| L1 | [static-observations.json](https://github.com/Dijo-404/mx4-linux/blob/main/evidence/installer/static-observations.json) | `local_sha256_aae3f58937b3b9fa452afa4b8add785b487179f584a1f019d27b4b4079a390e4` |
R1/R2/R3 bind to graph manifest `agm_170c0e8ef3e979ca2dcc2db5a4b24daa3ac25d5bb922707c97482db22a4bfdd7`, graph digest `91e576e7fde24933493a0b8368709064476693a11213840ba8a02c71bf623ead`. R3 reports successful containment verification. The extracted binary and plist digests agree between R2 and L1.
REA's Codex registration was aligned after setup, but REA tools were not connected in the active agent session. Analysis therefore used the version-pinned CLI. Archive inspection, safe extraction, and Apple graph projection succeeded. The following REA native operations returned explicit `capability_unavailable` errors because their `native-macos` utilities require macOS:
-- [rea-macho.json](../evidence/installer/rea-macho.json): `inspect_macho`.
-- [rea-plist.json](../evidence/installer/rea-plist.json): `inspect_plist`.
+- [rea-macho.json](https://github.com/Dijo-404/mx4-linux/blob/main/evidence/installer/rea-macho.json): `inspect_macho`.
+- [rea-plist.json](https://github.com/Dijo-404/mx4-linux/blob/main/evidence/installer/rea-plist.json): `inspect_plist`.
-These two files are error records and have no REA Evidence IDs. No analysis engine was installed. The fallback [inspect_static.py](../evidence/installer/inspect_static.py) uses Python's standard library to parse the supplied ZIP/plist and this Mach-O's declared headers, sections, dependencies and symbol names. It performs no disassembly or semantic recovery. Complete limitations are retained in each record.
+These two files are error records and have no REA Evidence IDs. No analysis engine was installed. The fallback [inspect_static.py](https://github.com/Dijo-404/mx4-linux/blob/main/evidence/installer/inspect_static.py) uses Python's standard library to parse the supplied ZIP/plist and this Mach-O's declared headers, sections, dependencies and symbol names. It performs no disassembly or semantic recovery. Complete limitations are retained in each record.
## Reproduction
diff --git a/docs/validation.md b/docs/validation.md
index 1a17afd..60fd338 100644
--- a/docs/validation.md
+++ b/docs/validation.md
@@ -34,10 +34,45 @@ Automated suite after the fix: **54 passed**, plus 30 successful subtests. New c
Scope: Actions Ring and Smart Actions. Flow was explicitly deferred by the user for a later Linux, Windows and macOS implementation.
- Automated suite: **258 passed**, plus 30 successful subtests. New coverage includes action/config validation, native Wayland input and fallback, held-key cleanup, macro cancellation, ring interaction, listener packet decoding, reporting restoration, child-process lifecycle/generation races, stale queued events, and cancellation during selection.
-- Live physical MX4 listener: reached ready with haptic panel diversion and raw XY enabled. After stop, flags/mapping were exactly restored from `[0,416]` to `[0,416]`. Exit code 0, no error events. See [hardware record](../evidence/desktop-hardware-smoke.json). No haptic waveform or macro was executed by this check.
+- Live physical MX4 listener: reached ready with haptic panel diversion and raw XY enabled. After stop, flags/mapping were exactly restored from `[0,416]` to `[0,416]`. Exit code 0, no error events. See [hardware record](https://github.com/Dijo-404/mx4-linux/blob/main/evidence/desktop-hardware-smoke.json). No haptic waveform or macro was executed by this check.
- Native GTK layer-shell preview: opened, selected Copy without side effects, closed/reopened, and canceled correctly on a synthetic cleanup release. Both editor tabs and all eight slot assignments were exercised.
- Native input: locally built checksum-pinned wtype 0.4. A controlled Niri/Wayland test focused a dedicated GTK entry, executed Ctrl+A and inserted `MX4 ring ✓`, and verified the exact entry contents. The original focus was restored. No user application received test text.
- Remote CLI: `mx4-linux ring --preview` successfully showed the running application's `mx4-actions-ring` layer on output DP-3, with overlay layer and exclusive keyboard handling. Preview was dismissed.
- Setup: rebuilt and installed version 0.2.0, reused the verified local keyboard helper. No new privileged permission changes were needed. Both udev rules pass `udevadm verify`; shell syntax and Python compilation checks pass.
Interactive checks still needed: a real haptic panel press/move/release selecting an action, haptic ticks during selection, and unplug/reconnect while holding. Bluetooth and other compositors remain outside verified coverage. The existing hardware-setting read-only evidence is separate from listener setup/cleanup and native-input testing.
+
+
+## UI, latency and npm packaging follow-up
+
+Changes on `feat/ui-performance-packaging` retain the native Python/GTK application. Mouse, Actions and Profiles have separate views; the wheel preview and ring use finite frame callbacks that stop when settled or hidden and honor GTK's animation preference. Ring labels are reused native controls with keyboard focus, while pointer hit testing follows the painted wedges. Smart Actions now has a native step builder with optional JSON, inline validation and reordering. The installer ZIP digest still matches the retained static analysis; it contains no application UI source or reusable device protocol implementation, and was not executed.
+
+Read-only MX Master 4 / Bolt measurements on this machine:
+
+| Operation | Observed work |
+| --- | --- |
+| Discover and read all eleven settings | 0.780 seconds; 33 HID feature requests |
+| Discover and read one selected setting | 0.060 seconds; 2 HID feature requests |
+| Cold import, target selection and selected read before paired-node wait change | 2.074 seconds |
+| Same cold operation after bounded paired-node wait | 1.496 seconds |
+
+These are individual samples, with variable radio timing. The first comparison measures capability discovery/read work, not complete setting-write latency or whole-application speed. Profiling attributed approximately one second and 600,000 Python calls to Solaar's repeated paired-node udev busy wait. Worker isolation bounds that lookup to 10 ms and retains its receiver fallback. Writes still discover and validate the live target, require acknowledgement and verify readback; no persistent HID cache was introduced.
+
+Confirmed setting edits now update existing controls without a follow-up scan. Failed writes and partial profile applications clear uncertain controls and refresh before profiles can save stale values. Profile and Smart Actions persistence run off the GTK thread. Event dispatch batches a burst into one GTK idle callback while retaining each raw packet in order; summing motion would change the model's radius-clamped trajectory.
+
+Validation includes full Python regressions, real GTK demo/widget checks under Wayland and X11, reduced motion and finite callback cleanup, dark/light editor inspection, Python/Node syntax and package checks, and Python wheel/source distribution builds. The npm tarball was installed into a temporary prefix; its real setup created an isolated per-user runtime with system Python, and that installed runtime passed CLI and GTK smoke checks without an interpreter override. GitHub workflow definitions are checked locally; hosted Actions have not run for these local changes.
+
+No physical settings, haptic waveform, button diversion or user routine was executed for this follow-up. Physical interaction, haptic feel, reconnect and Bluetooth checks remain open. npm/PyPI publication and remote branch changes were not performed.
+
+Final local checks: **301 Python tests and 32 subtests**, five Node launcher tests, Ruff, Python compilation, ShellCheck (Bash), both udev rules, 33 local documentation links, and actionlint passed. Native GTK smoke passed on Wayland and X11. The reviewed npm archive, Python wheel and source archive are generated under `dist/`; their Python sources and icon are checked against the working tree.
+
+
+## Video-reference ring follow-up
+
+Visual reference: supplied `looks.mp4`, 62.93 seconds, 720 × 1280, 30 fps; SHA-256 `e94b9ff40bff8cfa690f087fb180391a0b637d4c60e952bbb4b68c8cea33f4ae`. Review used overview frame samples and denser samples around the transitions, plus the two supplied screenshots. Audio was not analyzed. Around 00:46.10–00:46.27 the icon ring expands; around 00:47.10–00:47.30 a group reveals its side menu; around 00:48.10–00:48.20 a hovered child inverts its circle and displays an outward label. These timings are approximate observations, not a recovered vendor implementation.
+
+The application now uses eight separate native icon buttons, a small center close button, outward hover/focus labels and a radial opening transition. The editor has a labeled, live assignment diagram. Optional `ring_groups` add one to six existing routines to a side menu; legacy version 1 documents remain valid. Held physical motion keeps its original calibration, while latched pointer targeting follows the actual painted circles during animation. Emerging children cannot accept pointer clicks while overlapping a trigger or sibling. Keyboard focus, explicit close, Escape/back, cancellation and reduced motion are covered by native tests. Group entries retain references across routine renames and remove deleted children; empty editor entries compact to match displayed shortcut order.
+
+Final local checks: **401 Python tests and 32 subtests**, five Node launcher tests, Ruff, compilation, whitespace checks and 35 local documentation links passed. The mapped GTK smoke checks pass on Wayland and X11, including groups and finite/reduced-motion behavior. The actual npm archive was installed into a temporary prefix, its native runtime was set up, and that installed runtime passed the updated GTK group smoke check. Native snapshots were inspected on light and dark backgrounds, with six-child menus and long labels. Source screenshots are in `docs/assets/`; a four-second scripted GTK preview is generated under ignored `evidence/artifacts/actions-ring-demo.mp4`. Captures contain only the application's widgets, and selection callbacks did not execute routines.
+
+This follow-up did not write physical mouse settings, enable diversion, play haptics or execute user routines. Interactive panel selection, haptic feel, Bluetooth and reconnect checks remain open. Changes are committed locally on the existing improvement branch; hosted CI and registry publication were not run.
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..a60ca08
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,22 @@
+{
+ "name": "mx4-linux",
+ "version": "0.2.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "mx4-linux",
+ "version": "0.2.0",
+ "license": "GPL-3.0-or-later",
+ "os": [
+ "linux"
+ ],
+ "bin": {
+ "mx4-linux": "bin/mx4-linux.js"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..70a3d0e
--- /dev/null
+++ b/package.json
@@ -0,0 +1,28 @@
+{
+ "name": "mx4-linux",
+ "version": "0.2.0",
+ "description": "Native Linux controls, Actions Ring and Smart Actions for Logitech MX Master 4",
+ "license": "GPL-3.0-or-later",
+ "type": "module",
+ "bin": { "mx4-linux": "bin/mx4-linux.js" },
+ "engines": { "node": ">=22" },
+ "os": ["linux"],
+ "repository": { "type": "git", "url": "git+https://github.com/Dijo-404/mx4-linux.git" },
+ "homepage": "https://github.com/Dijo-404/mx4-linux#readme",
+ "bugs": { "url": "https://github.com/Dijo-404/mx4-linux/issues" },
+ "keywords": ["logitech", "mx-master-4", "linux", "gtk", "hidpp", "wayland"],
+ "files": [
+ "bin/", "src/mx4_linux/**/*.py", "src/mx4_linux/icons/*.svg",
+ "data/", "scripts/*.sh", "pyproject.toml",
+ "docs/", "CONTRIBUTING.md", "CHANGELOG.md", "SECURITY.md"
+ ],
+ "scripts": {
+ "start": "node bin/mx4-linux.js",
+ "setup": "node bin/mx4-linux.js setup",
+ "test": "node --test tests/npm/*.test.js",
+ "check": "node --check bin/mx4-linux.js && node --check scripts/check-package.js && node scripts/check-package.js",
+ "test:package": "node scripts/check-package.js --smoke",
+ "test:native": "node scripts/check-package.js --smoke --native"
+ },
+ "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" }
+}
diff --git a/pyproject.toml b/pyproject.toml
index 1733b8e..ba523ef 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -11,7 +11,13 @@ license = "GPL-3.0-or-later"
dependencies = ["solaar==1.1.20"]
[project.optional-dependencies]
-test = ["pytest>=8"]
+test = ["pytest>=8,<10"]
+dev = ["ruff>=0.14,<1", "build>=1.2,<2"]
+
+[project.urls]
+Homepage = "https://github.com/Dijo-404/mx4-linux"
+Issues = "https://github.com/Dijo-404/mx4-linux/issues"
+Changelog = "https://github.com/Dijo-404/mx4-linux/blob/main/CHANGELOG.md"
[project.scripts]
mx4-linux = "mx4_linux.cli:main"
@@ -24,3 +30,10 @@ mx4_linux = ["icons/*.svg"]
[tool.pytest.ini_options]
testpaths = ["tests"]
+
+[tool.ruff]
+target-version = "py311"
+line-length = 120
+
+[tool.ruff.lint]
+select = ["E9", "F401", "F63", "F7", "F82"]
diff --git a/scripts/check-package.js b/scripts/check-package.js
new file mode 100755
index 0000000..63fa06f
--- /dev/null
+++ b/scripts/check-package.js
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = dirname(dirname(fileURLToPath(import.meta.url)));
+const metadata = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
+const pythonVersion = readFileSync(join(root, 'src', 'mx4_linux', '__init__.py'), 'utf8').match(/__version__ = "([^"]+)"/)[1];
+const projectVersion = readFileSync(join(root, 'pyproject.toml'), 'utf8').match(/^version = "([^"]+)"/m)[1];
+assert.equal(metadata.version, pythonVersion, 'npm and Python versions differ');
+assert.equal(metadata.version, projectVersion, 'npm and pyproject versions differ');
+assert.ok(!metadata.scripts.install && !metadata.scripts.postinstall && !metadata.scripts.preinstall, 'npm installation must not modify Python or the host');
+
+function run(command, args, options = {}) {
+ const result = spawnSync(command, args, { cwd: root, encoding: 'utf8', ...options });
+ if (result.error) throw result.error;
+ assert.equal(result.status, 0, `${command} ${args.join(' ')}\n${result.stdout}\n${result.stderr}`);
+ return result.stdout;
+}
+
+const directory = mkdtempSync(join(tmpdir(), 'mx4-linux-package-'));
+try {
+ const packed = JSON.parse(run('npm', ['pack', '--json', '--pack-destination', directory]));
+ const [archive] = Array.isArray(packed) ? packed : Object.values(packed);
+ const files = new Set(archive.files.map(file => file.path));
+ for (const path of ['bin/mx4-linux.js', 'pyproject.toml', 'LICENSE',
+ 'src/mx4_linux/__main__.py', 'src/mx4_linux/gui.py', 'src/mx4_linux/device_worker.py',
+ 'src/mx4_linux/icons/io.github.mx4linux.Control.svg', 'scripts/install-udev-rule.sh',
+ 'scripts/lib-device-access.sh', 'data/70-mx4-linux.rules', 'docs/install.md']) {
+ assert.ok(files.has(path), `Missing package file: ${path}`);
+ }
+ for (const path of files) {
+ assert.ok(!/(^|\/)(__pycache__|\.venv|\.git|node_modules|evidence)(\/|$)|\.(pyc|zip|tgz)$/.test(path), `Unexpected package file: ${path}`);
+ }
+ if (process.argv.includes('--smoke')) {
+ const prefix = join(directory, 'installed');
+ run('npm', ['install', '--global', '--prefix', prefix, '--ignore-scripts', '--no-audit', '--no-fund', join(directory, archive.filename)]);
+ const executable = join(prefix, 'bin', 'mx4-linux');
+ assert.equal(run(executable, ['--version']).trim(), `mx4-linux ${metadata.version}`);
+ const env = { ...process.env, XDG_DATA_HOME: join(directory, 'data'), XDG_CONFIG_HOME: join(directory, 'config') };
+ if (process.argv.includes('--native')) {
+ delete env.MX4_LINUX_PYTHON;
+ run(executable, ['setup'], { env });
+ } else {
+ env.MX4_LINUX_PYTHON = process.env.PYTHON || 'python3';
+ }
+ assert.match(run(executable, ['--help'], { env }), /MX Master 4 controls for Linux/);
+ const doctor = JSON.parse(run(executable, ['doctor', '--json'], { env }));
+ assert.ok(Array.isArray(doctor.logitech_nodes));
+ if (process.argv.includes('--native')) {
+ const runtimePython = join(env.XDG_DATA_HOME, 'mx4-linux', 'runtime', metadata.version, 'bin', 'python');
+ console.log(run(runtimePython, [join(root, 'scripts', 'gtk-smoke.py')], { env }).trim());
+ }
+ }
+ console.log(`Verified npm package ${archive.filename}: ${files.size} files${process.argv.includes('--smoke') ? ', installed CLI smoke passed' : ''}.`);
+} finally {
+ rmSync(directory, { recursive: true, force: true });
+}
diff --git a/scripts/gtk-smoke.py b/scripts/gtk-smoke.py
new file mode 100644
index 0000000..ab1fa15
--- /dev/null
+++ b/scripts/gtk-smoke.py
@@ -0,0 +1,103 @@
+#!/usr/bin/env python3
+"""Exercise native demo widgets; use dbus-run-session and xvfb-run in CI."""
+
+import os
+from pathlib import Path
+import tempfile
+from time import monotonic, sleep
+
+
+def main():
+ with tempfile.TemporaryDirectory(prefix="mx4-gtk-smoke-") as directory:
+ os.environ["XDG_CONFIG_HOME"] = directory
+ from mx4_linux.actions import DesktopConfigStore, default_config
+ from mx4_linux.desktop_editor import DesktopEditor
+ from mx4_linux.gtk_support import Adw, Gdk, Gio, GLib, Gtk
+ from mx4_linux.gui import ControlWindow
+ from mx4_linux.ring import ActionsRing, CENTER_X, CENTER_Y
+ from mx4_linux.ring_model import button_center
+
+ context = GLib.MainContext.default()
+
+ def wait_until(condition, timeout=4):
+ deadline = monotonic() + timeout
+ while not condition():
+ while context.pending():
+ context.iteration(False)
+ if monotonic() > deadline:
+ raise AssertionError("GTK smoke check timed out")
+ sleep(0.01)
+
+ app = Adw.Application(application_id="io.github.mx4linux.Smoke", flags=Gio.ApplicationFlags.NON_UNIQUE)
+ app.register(None)
+ window = ControlWindow(app, demo=True)
+ ring = None
+ editor = None
+ settings = Gtk.Settings.get_default()
+ animations = settings.get_property("gtk-enable-animations")
+ try:
+ window.present()
+ wait_until(lambda: window.current is not None and not window.busy)
+ assert window.wheel.get_visible()
+ settings.set_property("gtk-enable-animations", True)
+ window.wheel.spin(1)
+ assert window.wheel.tick_id
+ wait_until(lambda: window.wheel.tick_id == 0)
+
+ selected = []
+ ring = ActionsRing(app, lambda action, preview: selected.append((action, preview)), lambda: None)
+ config = default_config()
+ ring.show_ring(config, preview=True)
+ wait_until(lambda: ring.tick_id == 0)
+ ring.key_pressed(None, Gdk.KEY_Right, 0, 0)
+ ring.key_pressed(None, Gdk.KEY_Return, 0, 0)
+ assert selected == [(config["ring"][0], True)]
+ assert ring.tick_id == 0 and not ring.get_visible()
+
+ config["ring_groups"] = {"2": ["copy", "paste"]}
+ ring.show_ring(config, preview=True)
+ wait_until(lambda: ring.tick_id == 0)
+ dx, dy = button_center(2)
+ ring.pointer_motion(None, CENTER_X + dx * ring.spread, CENTER_Y + dy * ring.spread)
+ assert ring.group_slot == 2 and len(selected) == 1
+ wait_until(lambda: ring.tick_id == 0)
+ assert len(ring.child_positions) == 2
+ ring.pointer_motion(None, *ring.child_positions[1])
+ assert ring.child_selected == 1
+ ring.pointer_click(None, 1, *ring.child_positions[1])
+ assert selected == [(config["ring"][0], True), ("paste", True)]
+ assert ring.tick_id == 0 and not ring.get_visible()
+
+ settings.set_property("gtk-enable-animations", False)
+ ring.show_ring(config, preview=True)
+ ring.pointer_motion(None, CENTER_X + dx, CENTER_Y + dy)
+ assert ring.tick_id == 0 and ring.group_slot == 2
+ assert not any(transition.active() for transition in
+ (ring.reveal, ring.group_reveal, ring.label_reveal))
+ ring.dismiss()
+ window.wheel.spin(1)
+ assert window.wheel.tick_id == 0
+
+ settings.set_property("gtk-enable-animations", True)
+ window.wheel.spin(1)
+ window.wheel.set_visible(False)
+ wait_until(lambda: window.wheel.tick_id == 0)
+ editor = DesktopEditor(window, DesktopConfigStore(Path(directory) / "desktop.json"), lambda: None)
+ editor.present()
+ wait_until(editor.get_mapped)
+ assert len(editor.ring_choices) == 8
+ assert not editor.dirty
+ print("GTK smoke passed: demo settings, wheel, ring groups, reduced motion, editor, cleanup.")
+ finally:
+ settings.set_property("gtk-enable-animations", animations)
+ if editor is not None:
+ editor.destroy()
+ if ring is not None:
+ ring.hide_ring()
+ ring.destroy()
+ window.close()
+ app.quit()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/setup.sh b/scripts/setup.sh
index 92186c8..d2132eb 100755
--- a/scripts/setup.sh
+++ b/scripts/setup.sh
@@ -8,17 +8,18 @@ try:
import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')
+ gi.require_foreign('cairo')
from gi.repository import Gtk, Adw
except (ImportError, ValueError) as exc:
- raise SystemExit(f'Install Python GObject, GTK 4 and Libadwaita first (see README): {exc}')
+ raise SystemExit(f'Install Python GObject with Cairo support, GTK 4 and Libadwaita first (see README): {exc}')
PY
if [[ ! -x .venv/bin/python ]]; then
"$python_bin" -m venv --system-site-packages .venv
fi
if command -v uv >/dev/null 2>&1; then
- uv pip install --python .venv/bin/python -e '.[test]'
+ uv pip install --python .venv/bin/python -e '.[test,dev]'
else
- .venv/bin/python -m pip install -e '.[test]'
+ .venv/bin/python -m pip install -e '.[test,dev]'
fi
if [[ -n "${WAYLAND_DISPLAY:-}" ]] && ! command -v wtype >/dev/null 2>&1; then
if ! "$project_dir/scripts/setup-wtype.sh"; then
diff --git a/src/mx4_linux/actions.py b/src/mx4_linux/actions.py
index 4708c5d..e04643d 100644
--- a/src/mx4_linux/actions.py
+++ b/src/mx4_linux/actions.py
@@ -25,6 +25,7 @@
MAX_CONFIG_BYTES = 1024 * 1024
MAX_ACTIONS = 128
MAX_STEPS = 64
+MAX_GROUP_ACTIONS = 6
MAX_DELAY_MS = 30_000
MAX_TOTAL_DELAY_MS = 60_000
MAX_RUN_SECONDS = 120
@@ -178,7 +179,8 @@ def _wtype_shortcut_args(codes):
def validate_config(config):
"""Validate the entire document before it is saved or any action is run."""
- _fields(config, ("version", "ring", "actions", "button_bindings", "ring_button", "haptic_feedback"), location="document")
+ _fields(config, ("version", "ring", "actions", "button_bindings", "ring_button", "haptic_feedback"),
+ ("ring_groups",), location="document")
if type(config["version"]) is not int or config["version"] != 1:
_fail("only version 1 is supported.")
actions = config["actions"]
@@ -235,6 +237,17 @@ def validate_config(config):
ring = config["ring"]
if not isinstance(ring, list) or len(ring) != 8 or any(not isinstance(value, str) or value not in actions for value in ring):
_fail("ring must contain exactly eight existing action IDs.")
+ groups = config.get("ring_groups", {})
+ if not isinstance(groups, dict):
+ _fail("ring_groups must map ring positions 0–7 to lists of action IDs.")
+ for position, children in groups.items():
+ if not isinstance(position, str) or position not in {str(index) for index in range(8)}:
+ _fail("ring_groups positions must be decimal strings from 0 to 7.")
+ if (not isinstance(children, list) or not 1 <= len(children) <= MAX_GROUP_ACTIONS
+ or any(not isinstance(child, str) or child not in actions for child in children)):
+ _fail(f"ring group {position} needs 1–{MAX_GROUP_ACTIONS} existing action IDs.")
+ if len(set(children)) != len(children):
+ _fail(f"ring group {position} cannot repeat an action ID.")
ring_button = config["ring_button"]
if type(ring_button) is not int or ring_button not in BUTTON_IDS:
_fail("ring_button must be one of 82, 83, 86, 195, 196 or 416.")
diff --git a/src/mx4_linux/desktop.py b/src/mx4_linux/desktop.py
index 1377b6b..ac9fd94 100644
--- a/src/mx4_linux/desktop.py
+++ b/src/mx4_linux/desktop.py
@@ -1,5 +1,6 @@
"""Coordinate the overlay, Smart Actions, and opt-in hardware events."""
+from collections import deque
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
import json
@@ -22,7 +23,10 @@ def __init__(self, window):
self.action_busy = False
self.cancelled = threading.Event()
self.executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="mx4-actions")
- self.session = EventSession(lambda event: GLib.idle_add(self.event, event))
+ self._event_lock = threading.Lock()
+ self._event_queue = deque()
+ self._events_pending = False
+ self.session = EventSession(self.queue_event)
self.ring = None
self.target = None
self.opening = False
@@ -32,6 +36,26 @@ def __init__(self, window):
self._pending_motion = [0, 0]
self.reload_config()
+ def queue_event(self, event):
+ """Batch UI dispatch without changing the radius-clamped motion path."""
+ with self._event_lock:
+ if self.closed:
+ return
+ self._event_queue.append(dict(event))
+ if self._events_pending:
+ return
+ self._events_pending = True
+ GLib.idle_add(self.flush_events)
+
+ def flush_events(self):
+ with self._event_lock:
+ events = tuple(self._event_queue)
+ self._event_queue.clear()
+ self._events_pending = False
+ for event in events:
+ self.event(event)
+ return GLib.SOURCE_REMOVE
+
def reload_config(self):
try:
self.config = self.store.read()
@@ -252,6 +276,8 @@ def saved(self):
def close(self):
self.closed = True
+ with self._event_lock:
+ self._event_queue.clear()
self._open_token += 1
self._dispatch_token += 1
self.cancelled.set()
diff --git a/src/mx4_linux/desktop_editor.py b/src/mx4_linux/desktop_editor.py
index a64792d..c759fcd 100644
--- a/src/mx4_linux/desktop_editor.py
+++ b/src/mx4_linux/desktop_editor.py
@@ -8,12 +8,17 @@
from copy import deepcopy
import json
from pathlib import Path
+import shlex
+import threading
import gi
gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
-from gi.repository import Adw, Gtk, Pango
+from gi.repository import Adw, GLib, Gtk, Pango
+
+from .actions import ACTION_ID, MAX_ACTIONS, MAX_GROUP_ACTIONS, MAX_STEPS, validate_config
+from .ring_preview import RingPreview
SLOT_NAMES = ("Top", "Upper right", "Right", "Lower right", "Bottom",
@@ -30,6 +35,44 @@
{"type": "shortcut", "keys": ["CTRL", "V"]},
]),
)
+STEP_TYPES = (
+ ("Keyboard shortcut", "shortcut", {"type": "shortcut", "keys": ["CTRL", "C"]}),
+ ("Open application", "command", {"type": "command", "argv": ["xdg-open", str(Path.home())]}),
+ ("Insert text", "text", {"type": "text", "text": "Hello"}),
+ ("Wait", "delay", {"type": "delay", "milliseconds": 150}),
+ ("Niri desktop action", "niri", {"type": "niri", "action": "toggle-overview", "args": []}),
+)
+STEP_NAMES = {kind: label for label, kind, _default in STEP_TYPES}
+
+
+def _step_values(step):
+ """Represent valid steps as editable strings without changing their data."""
+ kind = step["type"]
+ if kind == "shortcut":
+ value, extra = " + ".join(step["keys"]), ""
+ elif kind == "command":
+ value, extra = shlex.join(step["argv"]), ""
+ elif kind == "text":
+ value, extra = step["text"], ""
+ elif kind == "delay":
+ value, extra = str(step["milliseconds"]), ""
+ else:
+ value, extra = step["action"], shlex.join(step.get("args", []))
+ return {"type": kind, "value": value, "extra": extra}
+
+
+def _values_step(values):
+ """Parse form values; command strings become literal argv, never a shell."""
+ kind, value = values["type"], values["value"]
+ if kind == "shortcut":
+ return {"type": kind, "keys": [key.strip().upper() for key in value.split("+") if key.strip()]}
+ if kind == "command":
+ return {"type": kind, "argv": shlex.split(value)}
+ if kind == "text":
+ return {"type": kind, "text": value}
+ if kind == "delay":
+ return {"type": kind, "milliseconds": int(value)}
+ return {"type": kind, "action": value, "args": shlex.split(values["extra"])}
class _DraftError(ValueError):
@@ -55,8 +98,9 @@ def _page():
return box, scroll
-def _action_dropdown(**kwargs):
+def _action_dropdown(*, accessible_name, **kwargs):
choice = Gtk.DropDown(enable_search=True, **kwargs)
+ choice.update_property([Gtk.AccessibleProperty.LABEL], [accessible_name])
factory = Gtk.SignalListItemFactory()
def setup(_factory, item):
@@ -89,25 +133,31 @@ def __init__(self, parent, store, on_saved):
}
self.selected_id = next(iter(self.drafts))
self.dirty = False
+ self.saving = False
self.loading = True
+ self.syncing_steps = False
self.allow_close = False
self.close_dialog = None
self.ring_choices = []
+ self.group_choices = []
self.binding_choices = []
self.connect("close-request", self._close_requested)
toolbar = Adw.ToolbarView()
header = Adw.HeaderBar()
- header.set_title_widget(Adw.WindowTitle(title="Actions Ring and Smart Actions"))
- save = Gtk.Button(label="Save changes")
- save.add_css_class("suggested-action")
- save.connect("clicked", self._save)
- header.pack_end(save)
+ self.window_title = Adw.WindowTitle(title="Actions Ring and Smart Actions",
+ subtitle="Customize your mouse workflow")
+ header.set_title_widget(self.window_title)
+ self.save_button = Gtk.Button(label="Save changes", sensitive=False)
+ self.save_button.add_css_class("suggested-action")
+ self.save_button.connect("clicked", self._save)
+ header.pack_end(self.save_button)
toolbar.add_top_bar(header)
content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.stack = Gtk.Stack(vexpand=True)
self.stack.set_transition_type(Gtk.StackTransitionType.CROSSFADE)
+ self.stack.set_transition_duration(160)
switcher = Gtk.StackSwitcher(stack=self.stack, halign=Gtk.Align.CENTER,
margin_top=10, margin_bottom=10)
content.append(switcher)
@@ -118,6 +168,7 @@ def __init__(self, parent, store, on_saved):
self.error = _label("", dim=False)
self.error.add_css_class("error")
self.error.set_selectable(True)
+ self.error.set_focusable(True)
self.error.set_margin_start(24)
self.error.set_margin_end(24)
self.error.set_margin_top(10)
@@ -132,12 +183,18 @@ def __init__(self, parent, store, on_saved):
def _build_ring(self):
page, scroll = _page()
- page.append(_label("Press the haptic panel to open the ring, then choose an action. "
- "Assign a Smart Action to any of the eight positions."))
- group = Adw.PreferencesGroup(title="Ring positions", description="Positions run clockwise from the top.")
+ intro = _label("Your shortcuts, one gesture away")
+ intro.add_css_class("title-2")
+ page.append(intro)
+ page.append(_label("Hold the haptic panel, move toward an action, then release. "
+ "A short click opens the ring for point-and-click selection. "
+ "Choose what each position does below.", dim=True))
+ self.ring_preview = RingPreview(self.config, on_selected=self._preview_selected)
+ page.append(self.ring_preview)
+ group = Adw.PreferencesGroup(title="Ring positions", description="Eight actions, clockwise from the top. Edit their steps in Smart Actions.")
for index, name in enumerate(SLOT_NAMES):
- row = Adw.ActionRow(use_markup=False, title=f"{index + 1}. {name}")
- choice = _action_dropdown(valign=Gtk.Align.CENTER)
+ row = Adw.ActionRow(use_markup=False, title=name, subtitle=f"Position {index + 1} · key {index + 1} in the ring")
+ choice = _action_dropdown(accessible_name=f"Action at {name.lower()} ring position", valign=Gtk.Align.CENTER)
choice.set_tooltip_text(f"Action at ring position {index + 1}: {name}")
choice.set_hexpand(False)
choice.connect("notify::selected", self._ring_changed, index)
@@ -146,6 +203,25 @@ def _build_ring(self):
group.add(row)
page.append(group)
+ groups = Adw.PreferencesGroup(description="Turn a ring position into a group of up to six routines. "
+ "Choose them in display order; leave every entry empty to run the position's action directly.")
+ for index, name in enumerate(SLOT_NAMES):
+ row = Adw.ExpanderRow(title=name, use_markup=False)
+ choices = []
+ for child in range(MAX_GROUP_ACTIONS):
+ child_row = Adw.ActionRow(title=f"Action {child + 1}", use_markup=False)
+ choice = _action_dropdown(accessible_name=f"Group action {child + 1} at {name.lower()} ring position",
+ valign=Gtk.Align.CENTER)
+ choice.connect("notify::selected", self._group_changed, index)
+ child_row.add_suffix(choice)
+ row.add_row(child_row)
+ choices.append(choice)
+ self.group_choices.append((row, choices))
+ groups.add(row)
+ self.groups_expander = Gtk.Expander(label="Action groups (optional)")
+ self.groups_expander.set_child(groups)
+ page.append(self.groups_expander)
+
behavior = Adw.PreferencesGroup(title="Ring behavior")
ring_button = self.config["ring_button"]
behavior.add(Adw.ActionRow(use_markup=False, title="Open Actions Ring",
@@ -159,50 +235,91 @@ def _build_ring(self):
behavior.add(feedback)
page.append(behavior)
- bindings = Adw.PreferencesGroup(title="Optional button shortcuts",
+ bindings = Adw.PreferencesGroup(
description="A shortcut replaces that button's normal function while desktop controls are enabled.")
for cid, name in BUTTON_NAMES.items():
if cid == ring_button:
continue
row = Adw.ActionRow(use_markup=False, title=name)
- choice = _action_dropdown(valign=Gtk.Align.CENTER)
+ choice = _action_dropdown(accessible_name=f"Smart Action for {name.lower()}", valign=Gtk.Align.CENTER)
choice.set_tooltip_text(f"Smart Action for {name.lower()}")
choice.connect("notify::selected", self._binding_changed, cid)
row.add_suffix(choice)
self.binding_choices.append((cid, choice))
bindings.add(row)
- page.append(bindings)
+ shortcuts = Gtk.Expander(label="Additional button shortcuts")
+ shortcuts.set_child(bindings)
+ page.append(shortcuts)
self.stack.add_titled(scroll, "ring", "Actions Ring")
def _build_actions(self):
page, scroll = _page()
- page.append(_label("Create routines from keyboard shortcuts, applications, text, delays and niri desktop commands. "
- "Steps run in order when you choose the action."))
+ intro = _label("Make a shortcut your own")
+ intro.add_css_class("title-2")
+ page.append(intro)
+ page.append(_label("Choose a routine, name it, then add the steps you need. "
+ "Assign it to a ring position or mouse button in Actions Ring. "
+ "Editing and saving never run a routine.", dim=True))
+ chooser_title = _label("Routine")
+ chooser_title.add_css_class("heading")
+ page.append(chooser_title)
chooser_row = Gtk.Box(spacing=12)
- self.action_choice = _action_dropdown(hexpand=True)
+ self.action_choice = _action_dropdown(accessible_name="Routine to edit", hexpand=True)
self.action_choice.set_tooltip_text("Select a routine to edit")
self.action_choice.connect("notify::selected", self._action_selected)
chooser_row.append(self.action_choice)
self.delete = Gtk.Button(icon_name="user-trash-symbolic", tooltip_text="Delete selected routine")
+ self.delete.update_property([Gtk.AccessibleProperty.LABEL], ["Delete selected routine"])
self.delete.add_css_class("destructive-action")
self.delete.connect("clicked", self._delete_selected)
chooser_row.append(self.delete)
page.append(chooser_row)
- fields = Adw.PreferencesGroup(title="Selected routine")
+ add_row = Gtk.Box(spacing=12)
+ self.template_choice = Gtk.DropDown.new_from_strings([item[0] for item in TEMPLATES])
+ self.template_choice.update_property([Gtk.AccessibleProperty.LABEL], ["New routine template"])
+ self.template_choice.set_tooltip_text("Starting point for a new routine")
+ self.template_choice.set_hexpand(True)
+ add_row.append(self.template_choice)
+ self.add_routine_button = Gtk.Button(label="New routine")
+ self.add_routine_button.connect("clicked", self._add_routine)
+ add_row.append(self.add_routine_button)
+ page.append(add_row)
+
+ fields = Adw.PreferencesGroup(title="Routine details")
self.name_entry = Adw.EntryRow(title="Name")
self.name_entry.set_max_length(80)
self.id_entry = Adw.EntryRow(title="Action ID")
self.id_entry.set_max_length(64)
- self.app_entry = Adw.EntryRow(title="Only in application (optional app ID)")
+ self.app_entry = Adw.EntryRow(title="Only in this application (optional)")
self.app_entry.set_max_length(256)
for widget in (self.name_entry, self.id_entry, self.app_entry):
widget.connect("changed", self._draft_changed)
- fields.add(widget)
+ fields.add(self.name_entry)
+ fields.add(self.app_entry)
page.append(fields)
- page.append(_label("Action IDs use lowercase letters, numbers, hyphens and underscores. "
- "An application condition must match the focused niri app ID exactly. "
- "Leave it empty to run in any application.", dim=True))
+ page.append(_label("Leave the application field empty to run anywhere. "
+ "To limit a routine, enter the exact focused Niri app ID.", dim=True))
+
+ self.steps_group = Adw.PreferencesGroup(title="Steps", description="Run from top to bottom. Expand a step to edit it.")
+ page.append(self.steps_group)
+ self.step_rows = []
+ self.step_error = _label("")
+ self.step_error.add_css_class("error")
+ self.step_error.set_visible(False)
+ page.append(self.step_error)
+
+ step_add = Gtk.Box(spacing=12)
+ self.step_choice = Gtk.DropDown.new_from_strings([item[0] for item in STEP_TYPES])
+ self.step_choice.update_property([Gtk.AccessibleProperty.LABEL], ["New step type"])
+ self.step_choice.set_hexpand(True)
+ self.step_choice.set_tooltip_text("Type of step to add")
+ step_add.append(self.step_choice)
+ self.add_step_button = Gtk.Button(label="Add step")
+ self.add_step_button.connect("clicked", self._add_step)
+ step_add.append(self.add_step_button)
+ page.append(step_add)
+ self.step_add_box = step_add
steps_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
title = _label("Steps (JSON)")
@@ -212,22 +329,31 @@ def _build_actions(self):
left_margin=12, right_margin=12,
top_margin=12, bottom_margin=12)
self.steps_view.set_accepts_tab(False)
+ self.steps_view.update_property([Gtk.AccessibleProperty.LABEL], ["Routine steps JSON"])
self.steps_buffer = self.steps_view.get_buffer()
self.steps_buffer.connect("changed", self._draft_changed)
code_scroll = Gtk.ScrolledWindow(min_content_height=230, vexpand=True)
code_scroll.add_css_class("card")
code_scroll.set_child(self.steps_view)
steps_box.append(code_scroll)
+ self.json_box = steps_box
+ self.json_box.set_visible(False)
page.append(steps_box)
- add_row = Gtk.Box(spacing=12)
- self.template_choice = Gtk.DropDown.new_from_strings([item[0] for item in TEMPLATES])
- self.template_choice.set_hexpand(True)
- add_row.append(self.template_choice)
- add = Gtk.Button(label="Add routine")
- add.connect("clicked", self._add_routine)
- add_row.append(add)
- page.append(add_row)
+ self.json_toggle = Gtk.CheckButton(label="Edit steps as JSON")
+ self.json_toggle.connect("toggled", self._toggle_json)
+ page.append(self.json_toggle)
+
+ advanced = Gtk.Expander(label="Advanced routine settings")
+ advanced_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8, margin_top=12)
+ id_group = Adw.PreferencesGroup()
+ id_group.add(self.id_entry)
+ advanced_box.append(id_group)
+ advanced_box.append(_label("Action IDs use lowercase letters, numbers, hyphens and underscores. "
+ "Ring positions and button assignments follow ID changes automatically.", dim=True))
+ advanced.set_child(advanced_box)
+ self.advanced = advanced
+ page.append(advanced)
help_expander = Gtk.Expander(label="Step examples and help")
help_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10,
@@ -252,15 +378,187 @@ def _build_actions(self):
page.append(help_expander)
self.stack.add_titled(scroll, "actions", "Smart Actions")
+ def _mark_dirty(self):
+ self.dirty = True
+ self.save_button.set_sensitive(True)
+ self.window_title.set_subtitle("Unsaved changes")
+ self.error.set_visible(False)
+
+ def _show_step_error(self, message=""):
+ self.step_error.set_text(message)
+ self.step_error.set_visible(bool(message))
+
+ def _form_steps(self, values):
+ steps = []
+ for index, value in enumerate(values, 1):
+ try:
+ steps.append(_values_step(value))
+ except (ValueError, KeyError) as exc:
+ raise ValueError(f"Step {index}: {exc}. Check the field and any quotation marks.") from exc
+ return steps
+
+ def _validate_selected(self):
+ draft = self.drafts[self.selected_id]
+ try:
+ if not draft["label"]:
+ raise ValueError("Give this routine a name.")
+ if not ACTION_ID.fullmatch(draft["id"]):
+ self.advanced.set_expanded(True)
+ raise ValueError("Use 1–64 lowercase letters, numbers, hyphens or underscores for the action ID.")
+ if any(key != self.selected_id and other["id"] == draft["id"] for key, other in self.drafts.items()):
+ self.advanced.set_expanded(True)
+ raise ValueError("This action ID already belongs to another routine. Choose a unique ID.")
+ steps = (self._form_steps(draft["form_values"]) if draft.get("form_values") is not None
+ else json.loads(draft["steps_text"]))
+ action = {"label": draft["label"], "steps": steps}
+ if draft["app_id"]:
+ action["app_id"] = draft["app_id"]
+ validate_config({"version": 1, "actions": {"routine": action}, "ring": ["routine"] * 8,
+ "ring_button": 416, "haptic_feedback": True, "button_bindings": {}})
+ except (RuntimeError, ValueError, RecursionError) as exc:
+ self._show_step_error(str(exc).removeprefix("Invalid desktop configuration: "))
+ return False
+ self._show_step_error()
+ return True
+
+ def _render_steps(self, expanded=None):
+ for row in self.step_rows:
+ self.steps_group.remove(row)
+ self.step_rows.clear()
+ values = self.drafts[self.selected_id].get("form_values") or []
+ self.steps_group.set_description("Run from top to bottom. Expand a step to edit it." if values
+ else "Add your first step below.")
+ self.add_step_button.set_sensitive(len(values) < MAX_STEPS)
+ for index, value in enumerate(values):
+ row = Adw.ExpanderRow(title=f"{index + 1}. {STEP_NAMES[value['type']]}",
+ subtitle=self._step_summary(value), use_markup=False)
+ for icon, label, offset in (("user-trash-symbolic", "Remove step", 0),
+ ("go-down-symbolic", "Move step down", 1),
+ ("go-up-symbolic", "Move step up", -1)):
+ button = Gtk.Button(icon_name=icon, tooltip_text=f"{label}: step {index + 1}", valign=Gtk.Align.CENTER)
+ button.update_property([Gtk.AccessibleProperty.LABEL], [f"{label}: step {index + 1}"])
+ button.add_css_class("flat")
+ button.set_sensitive(offset == 0 or 0 <= index + offset < len(values))
+ button.connect("clicked", self._move_step, index, offset)
+ row.add_suffix(button)
+ kind = value["type"]
+ if kind == "text":
+ text = Gtk.TextView(wrap_mode=Gtk.WrapMode.WORD_CHAR, accepts_tab=False,
+ top_margin=10, bottom_margin=10, left_margin=12, right_margin=12)
+ text.set_tooltip_text("Text to insert, including line breaks")
+ text.update_property([Gtk.AccessibleProperty.LABEL], [f"Text to insert in step {index + 1}"])
+ text.get_buffer().set_text(value["value"])
+ text.get_buffer().connect("changed", self._text_step_changed, index, row)
+ scroll = Gtk.ScrolledWindow(min_content_height=100)
+ scroll.set_child(text)
+ row.add_row(scroll)
+ else:
+ title = {"shortcut": "Keys, separated by +", "command": "Application and arguments",
+ "delay": "Wait in milliseconds (0–30000)", "niri": "Niri action"}[kind]
+ entry = Adw.EntryRow(title=title, text=value["value"])
+ entry.connect("changed", self._step_changed, index, "value", row)
+ row.add_row(entry)
+ if kind == "niri":
+ arguments = Adw.EntryRow(title="Arguments (optional)", text=value["extra"])
+ arguments.connect("changed", self._step_changed, index, "extra", row)
+ row.add_row(arguments)
+ hint = {"shortcut": "For example: CTRL + SHIFT + S. Use Linux key names such as ENTER, F1 and SPACE.",
+ "command": 'For example: kitty --title "My terminal". Quote arguments with spaces; commands run directly.',
+ "text": "Insert this text into the focused application. Line breaks are preserved.",
+ "delay": "1000 milliseconds = 1 second. Keep waits short for responsive routines.",
+ "niri": "For example: toggle-overview or focus-workspace-down. Requires Niri."}[kind]
+ row.add_row(Adw.ActionRow(title=hint, title_lines=0, use_markup=False))
+ self.steps_group.add(row)
+ self.step_rows.append(row)
+ row.set_expanded(index == expanded)
+
+ @staticmethod
+ def _step_summary(value):
+ text = value["value"].replace("\n", " ↵ ")
+ if value["type"] == "delay":
+ text += " ms"
+ return text[:100] or "Needs a value"
+
+ def _step_changed(self, entry, index, field, row):
+ if self.loading:
+ return
+ self.drafts[self.selected_id]["form_values"][index][field] = entry.get_text()
+ row.set_subtitle(self._step_summary(self.drafts[self.selected_id]["form_values"][index]))
+ self._mark_dirty()
+ self._validate_selected()
+
+ def _text_step_changed(self, buffer, index, row):
+ start, end = buffer.get_bounds()
+ self.drafts[self.selected_id]["form_values"][index]["value"] = buffer.get_text(start, end, True)
+ row.set_subtitle(self._step_summary(self.drafts[self.selected_id]["form_values"][index]))
+ self._mark_dirty()
+ self._validate_selected()
+
+ def _move_step(self, _button, index, offset):
+ values = self.drafts[self.selected_id]["form_values"]
+ if offset:
+ other = index + offset
+ values[index], values[other] = values[other], values[index]
+ else:
+ del values[index]
+ self._mark_dirty()
+ self._render_steps(index + offset if values else None)
+ self._validate_selected()
+
+ def _add_step(self, *_):
+ values = self.drafts[self.selected_id]["form_values"]
+ if len(values) >= MAX_STEPS:
+ return
+ values.append(_step_values(deepcopy(STEP_TYPES[self.step_choice.get_selected()][2])))
+ self._mark_dirty()
+ self._render_steps(len(values) - 1)
+ self._validate_selected()
+
+ def _toggle_json(self, *_):
+ if self.loading:
+ return
+ draft = self.drafts[self.selected_id]
+ use_json = self.json_toggle.get_active()
+ try:
+ if use_json:
+ steps = self._form_steps(draft["form_values"])
+ draft["steps_text"] = json.dumps(steps, indent=2, ensure_ascii=False)
+ draft["form_values"] = None
+ self.syncing_steps = True
+ self.steps_buffer.set_text(draft["steps_text"])
+ self.syncing_steps = False
+ else:
+ steps = json.loads(draft["steps_text"])
+ if not self._validate_selected():
+ raise ValueError("Fix the JSON steps before returning to the step builder.")
+ draft["form_values"] = [_step_values(step) for step in steps]
+ self._render_steps()
+ except (ValueError, KeyError, TypeError, RecursionError) as exc:
+ self.loading = True
+ self.json_toggle.set_active(not use_json)
+ self.loading = False
+ self._show_step_error(str(exc))
+ return
+ draft["json_mode"] = use_json
+ self.steps_group.set_visible(not use_json)
+ self.step_add_box.set_visible(not use_json)
+ self.json_box.set_visible(use_json)
+ self._show_step_error()
+
def _refresh_choices(self):
previous = self.loading
self.loading = True
self.choice_ids = list(self.drafts)
- labels = [f"{self.drafts[key]['label'] or 'Untitled'} · {self.drafts[key]['id']}"
- for key in self.choice_ids]
+ labels = [self.drafts[key]["label"] or "Untitled routine" for key in self.choice_ids]
for index, choice in enumerate(self.ring_choices):
choice.set_model(Gtk.StringList.new(labels))
choice.set_selected(self.choice_ids.index(self.config["ring"][index]))
+ for index, (row, choices) in enumerate(self.group_choices):
+ children = self.config.get("ring_groups", {}).get(str(index), [])
+ row.set_subtitle(f"{len(children)} actions · opens a submenu" if children else "No group · runs the assigned action")
+ for child, choice in enumerate(choices):
+ choice.set_model(Gtk.StringList.new(["No action"] + labels))
+ choice.set_selected(self.choice_ids.index(children[child]) + 1 if child < len(children) else 0)
for cid, choice in self.binding_choices:
choice.set_model(Gtk.StringList.new(["Normal button function"] + labels))
binding = self.config["button_bindings"].get(str(cid))
@@ -268,12 +566,41 @@ def _refresh_choices(self):
self.action_choice.set_model(Gtk.StringList.new(labels))
self.action_choice.set_selected(self.choice_ids.index(self.selected_id))
self.delete.set_sensitive(len(self.drafts) > 1)
+ self.add_routine_button.set_sensitive(len(self.drafts) < MAX_ACTIONS)
+ self.loading = previous
+ self._refresh_ring_preview()
+
+ def _refresh_labels(self):
+ previous = self.loading
+ self.loading = True
+ index = self.choice_ids.index(self.selected_id)
+ label = self.drafts[self.selected_id]["label"] or "Untitled routine"
+ for choice in self.ring_choices + [self.action_choice]:
+ choice.get_model().splice(index, 1, [label])
+ for _cid, choice in self.binding_choices:
+ choice.get_model().splice(index + 1, 1, [label])
+ for _row, choices in self.group_choices:
+ for choice in choices:
+ choice.get_model().splice(index + 1, 1, [label])
self.loading = previous
+ self._refresh_ring_preview()
+
+ def _refresh_ring_preview(self):
+ config = deepcopy(self.config)
+ config["actions"] = {key: {**self.config["actions"].get(key, {}), "label": draft["label"]}
+ for key, draft in self.drafts.items()}
+ self.ring_preview.update_config(config)
+
+ def _preview_selected(self, index):
+ if not self.loading:
+ self.ring_choices[index].grab_focus()
def _ring_changed(self, choice, _param, index):
if not self.loading and choice.get_selected() < len(self.choice_ids):
self.config["ring"][index] = self.choice_ids[choice.get_selected()]
- self.dirty = True
+ self._mark_dirty()
+ self._refresh_ring_preview()
+ self.ring_preview.select(index)
def _binding_changed(self, choice, _param, cid):
if self.loading:
@@ -285,25 +612,57 @@ def _binding_changed(self, choice, _param, cid):
self.config["button_bindings"][str(cid)] = self.choice_ids[selected - 1]
else:
return
- self.dirty = True
+ self._mark_dirty()
+
+ def _group_changed(self, _choice, _param, index):
+ if self.loading:
+ return
+ row, choices = self.group_choices[index]
+ selected = [choice.get_selected() for choice in choices]
+ if any(value > len(self.choice_ids) for value in selected):
+ return
+ children = [self.choice_ids[value - 1] for value in selected if value]
+ previous = self.config.get("ring_groups", {}).get(str(index), [])
+ if len(children) != len(set(children)):
+ self.loading = True
+ for child, choice in enumerate(choices):
+ choice.set_selected(self.choice_ids.index(previous[child]) + 1 if child < len(previous) else 0)
+ self.loading = False
+ self.error.set_text("Each action can appear only once within a group. Choose a different routine.")
+ self.error.set_visible(True)
+ return
+ if children == previous:
+ return
+ if children:
+ self.config.setdefault("ring_groups", {})[str(index)] = children
+ else:
+ self.config.get("ring_groups", {}).pop(str(index), None)
+ self.loading = True
+ for child, choice in enumerate(choices):
+ choice.set_selected(self.choice_ids.index(children[child]) + 1 if child < len(children) else 0)
+ self.loading = False
+ row.set_subtitle(f"{len(children)} actions · opens a submenu" if children else "No group · runs the assigned action")
+ self._mark_dirty()
+ self._refresh_ring_preview()
def _haptics_changed(self, *_):
if not self.loading:
self.config["haptic_feedback"] = self.haptics.get_active()
- self.dirty = True
+ self._mark_dirty()
def _draft_changed(self, source, *_):
- if self.loading:
+ if self.loading or self.syncing_steps:
return
start, end = self.steps_buffer.get_bounds()
- self.drafts[self.selected_id] = {
+ self.drafts[self.selected_id].update({
"id": self.id_entry.get_text(), "label": self.name_entry.get_text(),
"app_id": self.app_entry.get_text(),
"steps_text": self.steps_buffer.get_text(start, end, True),
- }
- self.dirty = True
- if source in (self.name_entry, self.id_entry):
- self._refresh_choices()
+ })
+ self._mark_dirty()
+ if source == self.name_entry:
+ self._refresh_labels()
+ self._validate_selected()
def _action_selected(self, choice, _param):
index = choice.get_selected()
@@ -319,9 +678,25 @@ def _load_selected(self):
self.id_entry.set_text(draft["id"])
self.app_entry.set_text(draft["app_id"])
self.steps_buffer.set_text(draft["steps_text"])
+ if "form_values" not in draft:
+ try:
+ draft["form_values"] = [_step_values(step) for step in json.loads(draft["steps_text"])]
+ except (ValueError, KeyError, TypeError, RecursionError):
+ draft["form_values"] = None
+ draft["json_mode"] = True
+ json_mode = draft.get("json_mode", False)
+ self.json_toggle.set_active(json_mode)
+ self.steps_group.set_visible(not json_mode)
+ self.step_add_box.set_visible(not json_mode)
+ self.json_box.set_visible(json_mode)
+ self._render_steps()
+ self._show_step_error()
self.loading = previous
+ self._validate_selected()
def _add_routine(self, *_):
+ if len(self.drafts) >= MAX_ACTIONS:
+ return
_, prefix, label, steps = TEMPLATES[self.template_choice.get_selected()]
number = 1
used_ids = set(self.drafts) | {draft["id"] for draft in self.drafts.values()}
@@ -331,7 +706,7 @@ def _add_routine(self, *_):
self.drafts[action_id] = {"id": action_id, "label": label, "app_id": "",
"steps_text": json.dumps(steps, indent=2)}
self.selected_id = action_id
- self.dirty = True
+ self._mark_dirty()
self._refresh_choices()
self._load_selected()
self.name_entry.grab_focus()
@@ -344,7 +719,7 @@ def _delete_selected(self, *_):
label = self.drafts[action_id]["label"] or action_id
replacement = self.drafts[fallback]["label"] or fallback
dialog = Adw.MessageDialog(transient_for=self, modal=True, heading=f"Delete {label}?",
- body=f"Its ring positions will use {replacement}. Its button shortcuts will be removed. Changes apply when you save.")
+ body=f"Its ring positions will use {replacement}. Its button shortcuts and group entries will be removed. Changes apply when you save.")
dialog.add_response("cancel", "Cancel")
dialog.add_response("delete", "Delete routine")
dialog.set_response_appearance("delete", Adw.ResponseAppearance.DESTRUCTIVE)
@@ -358,8 +733,13 @@ def answered(_dialog, response):
self.config["ring"] = [fallback if item == action_id else item for item in self.config["ring"]]
self.config["button_bindings"] = {cid: item for cid, item in self.config["button_bindings"].items()
if item != action_id}
+ if "ring_groups" in self.config:
+ self.config["ring_groups"] = {
+ position: remaining for position, children in self.config["ring_groups"].items()
+ if (remaining := [item for item in children if item != action_id])
+ }
self.selected_id = fallback
- self.dirty = True
+ self._mark_dirty()
self._refresh_choices()
self._load_selected()
@@ -375,23 +755,33 @@ def _candidate(self):
if action_id in actions:
raise _DraftError(original_id, f"Action ID {action_id!r} is used by more than one routine.")
try:
- steps = json.loads(draft["steps_text"])
+ steps = (self._form_steps(draft["form_values"]) if draft.get("form_values") is not None
+ else json.loads(draft["steps_text"]))
except (ValueError, RecursionError) as exc:
raise _DraftError(original_id, f"Cannot read steps for {draft['label'] or original_id}: {exc}") from exc
action = {"label": draft["label"], "steps": steps}
if draft["app_id"]:
action["app_id"] = draft["app_id"]
+ try:
+ validate_config({"version": 1, "actions": {action_id: action}, "ring": [action_id] * 8,
+ "ring_button": 416, "haptic_feedback": True, "button_bindings": {}})
+ except RuntimeError as exc:
+ raise _DraftError(original_id, str(exc)) from exc
actions[action_id] = action
renames[original_id] = action_id
candidate["actions"] = actions
candidate["ring"] = [renames[item] for item in candidate["ring"]]
candidate["button_bindings"] = {cid: renames[item] for cid, item in candidate["button_bindings"].items()}
+ if "ring_groups" in candidate:
+ candidate["ring_groups"] = {position: [renames[item] for item in children]
+ for position, children in candidate["ring_groups"].items()}
return candidate
def _save(self, *_):
+ if self.saving:
+ return
try:
- candidate = self._candidate()
- self.store.save(candidate)
+ candidate = validate_config(self._candidate())
except (RuntimeError, ValueError, OSError, RecursionError) as exc:
if isinstance(exc, _DraftError):
self.selected_id = exc.action_id
@@ -400,18 +790,57 @@ def _save(self, *_):
self.stack.set_visible_child_name("actions")
self.error.set_text(str(exc))
self.error.set_visible(True)
+ self.error.grab_focus()
return
+ self.saving = True
+ self.stack.set_sensitive(False)
+ self.save_button.set_sensitive(False)
+ self.save_button.set_label("Saving…")
+ self.window_title.set_subtitle("Saving changes…")
+ self.error.set_visible(False)
+
+ def persist():
+ try:
+ self.store.save(candidate)
+ except Exception as exc:
+ error = str(exc) or type(exc).__name__
+ else:
+ error = None
+ GLib.idle_add(self._save_finished, error)
+
+ # File locks and fsync can wait indefinitely on a slow filesystem.
+ try:
+ threading.Thread(target=persist, name="mx4-config-save").start()
+ except RuntimeError as exc:
+ self._save_finished(str(exc))
+
+ def _save_finished(self, error):
+ self.saving = False
+ self.stack.set_sensitive(True)
+ self.save_button.set_label("Save changes")
+ if error:
+ self.save_button.set_sensitive(self.dirty)
+ self.window_title.set_subtitle("Unsaved changes")
+ self.error.set_text(error)
+ self.error.set_visible(True)
+ self.error.grab_focus()
+ return GLib.SOURCE_REMOVE
self.dirty = False
+ self.save_button.set_sensitive(False)
+ self.window_title.set_subtitle("Changes saved")
try:
self.on_saved()
except Exception as exc:
self.error.set_text(f"Configuration saved, but desktop controls could not reload: {exc}")
self.error.set_visible(True)
- return
+ return GLib.SOURCE_REMOVE
self.allow_close = True
self.close()
+ return GLib.SOURCE_REMOVE
def _close_requested(self, *_):
+ if self.saving:
+ return True
if self.allow_close or not self.dirty:
return False
if self.close_dialog is not None:
diff --git a/src/mx4_linux/device_worker.py b/src/mx4_linux/device_worker.py
index 2acb54e..190fdb0 100644
--- a/src/mx4_linux/device_worker.py
+++ b/src/mx4_linux/device_worker.py
@@ -63,6 +63,7 @@ def _isolated_solaar(api, software_id=0x0C):
old_persister = api.configuration.persister
old_pending = api.hidpp10.set_configuration_pending_flags
old_open, old_close = api.base.open_path, api.base.close
+ old_find_paired = getattr(api.base, "find_paired_node", None)
has_software_id = hasattr(api.base, "SOLAAR_SOFTWARE_ID")
old_software_id = getattr(api.base, "SOLAAR_SOFTWARE_ID", None)
handles = {}
@@ -86,6 +87,10 @@ def tracked_close(handle, *args, **kwargs):
api.configuration.persister = lambda _device: None
api.hidpp10.set_configuration_pending_flags = lambda *_args, **_kwargs: True
api.base.open_path, api.base.close = tracked_open, tracked_close
+ if old_find_paired is not None:
+ # The receiver handle works while a paired udev node appears. Solaar's
+ # one-second busy wait otherwise repeats for every request and scan.
+ api.base.find_paired_node = lambda path, number, timeout: old_find_paired(path, number, min(timeout, .01))
if has_software_id:
api.base.SOLAAR_SOFTWARE_ID = software_id
try:
@@ -97,6 +102,8 @@ def tracked_close(handle, *args, **kwargs):
except Exception:
logging.getLogger(__name__).exception("Closing HID handle")
api.base.open_path, api.base.close = old_open, old_close
+ if old_find_paired is not None:
+ api.base.find_paired_node = old_find_paired
api.configuration.persister = old_persister
api.hidpp10.set_configuration_pending_flags = old_pending
if has_software_id:
@@ -205,11 +212,11 @@ def _describe_setting(setting, dev, api):
return result
-def _discover_settings(dev, api, path, diagnostics):
+def _discover_settings(dev, api, path, diagnostics, names=ALLOWED_SETTINGS):
"""Only build reviewed templates: broad discovery can add event handlers."""
found = []
templates = api.settings_templates.SETTINGS
- for name in ALLOWED_SETTINGS:
+ for name in names:
for template in templates:
if template.name != name or not template.feature:
continue
@@ -250,9 +257,18 @@ def _children(owner, info, diagnostics):
diagnostics.append(_diagnostic(info.path, error))
-def _devices(api, diagnostics):
+def _devices(api, diagnostics, target_id=None):
"""Yield devices while owning their receiver/direct-device handle."""
+ if target_id is not None:
+ try:
+ target_path, target_number = json.loads(target_id)
+ if not isinstance(target_path, str) or type(target_number) is not int:
+ return
+ except (ValueError, TypeError):
+ return
for info in api.base.receivers_and_devices():
+ if target_id is not None and str(info.path) != target_path:
+ continue
owner = None
try:
factory = api.device.create_device if info.isDevice else api.receiver.create_receiver
@@ -260,7 +276,17 @@ def _devices(api, diagnostics):
if owner is None:
diagnostics.append(_diagnostic(info.path, RuntimeError("Unable to open HID device")))
continue
- for dev in _children(owner, info, diagnostics):
+ # Open only enumerated paths; a selection must never become an
+ # arbitrary user-supplied path or probe unrelated receiver slots.
+ if target_id is None:
+ children = _children(owner, info, diagnostics)
+ elif info.isDevice:
+ children = (owner,) if owner.number == target_number else ()
+ else:
+ children = (owner[target_number],) if 1 <= target_number <= 7 else ()
+ for dev in children:
+ if dev is None:
+ continue
try:
dev.ping()
if _is_mx4(dev.name):
@@ -343,13 +369,19 @@ def _write(request, api):
if "value" not in request:
raise ValueError("A setting value is required")
diagnostics = []
- with contextlib.closing(_devices(api, diagnostics)) as discovered:
+ with contextlib.closing(_devices(api, diagnostics, target_id)) as discovered:
for dev, path in discovered:
if _device_id(path, dev.number) != target_id:
continue
if not dev.online:
raise RuntimeError("Device is offline; wake it and scan again")
- settings = _discover_settings(dev, api, path, diagnostics)
+ names = [name]
+ if name in ("smart-shift", "scroll-ratchet"):
+ names.append("scroll-ratchet" if name == "smart-shift" else "smart-shift")
+ elif name == "scroll-ratchet-torque":
+ names.append("scroll-ratchet")
+ settings = _discover_settings(dev, api, path, diagnostics, names)
+ refresh_required = bool(diagnostics)
setting = next((item for item in settings if item.name == name), None)
if setting is None:
raise ValueError("Setting is not supported by the connected device")
@@ -371,7 +403,24 @@ def _write(request, api):
actual = actual.get(key, actual.get(str(key)))
if actual is None or type(value) is bool and type(actual) is not bool or actual != value:
raise RuntimeError(f"Device readback did not confirm the change (received {_json_value(actual)!r})")
- return {"ok": True, "value": _json_value(actual)}
+ response = {"ok": True, "value": _json_value(actual)}
+ values = {}
+ for related in settings:
+ if related is not setting:
+ try:
+ value = _read_live(related, dev, api)
+ if value is not None:
+ values[related.name] = _json_value(value)
+ else:
+ refresh_required = True
+ except Exception:
+ refresh_required = True
+ logging.getLogger(__name__).debug("Reading related setting %s", related.name, exc_info=True)
+ if values:
+ response["values"] = values
+ if refresh_required:
+ response["refresh_required"] = True
+ return response
message = "Device is unavailable; scan again"
if diagnostics:
message += ": " + "; ".join(item["message"] for item in diagnostics)
diff --git a/src/mx4_linux/event_worker.py b/src/mx4_linux/event_worker.py
index 3bd7e43..3387a0c 100644
--- a/src/mx4_linux/event_worker.py
+++ b/src/mx4_linux/event_worker.py
@@ -312,7 +312,7 @@ def send(event):
api.hidpp20 = importlib.import_module("logitech_receiver.hidpp20")
with _isolated_solaar(api, software_id=0x0D):
diagnostics = []
- with contextlib.closing(_devices(api, diagnostics)) as devices:
+ with contextlib.closing(_devices(api, diagnostics, target)) as devices:
for dev, path in devices:
if _device_id(path, dev.number) != target:
continue
diff --git a/src/mx4_linux/gtk_support.py b/src/mx4_linux/gtk_support.py
index b3e1bf9..835822c 100644
--- a/src/mx4_linux/gtk_support.py
+++ b/src/mx4_linux/gtk_support.py
@@ -2,6 +2,8 @@
from ctypes import CDLL, RTLD_GLOBAL
+__all__ = ["Adw", "Gdk", "Gio", "GLib", "Gtk", "Layer"]
+
try:
CDLL("libgtk4-layer-shell.so.0", mode=RTLD_GLOBAL)
except OSError:
diff --git a/src/mx4_linux/gui.py b/src/mx4_linux/gui.py
index cad4b1a..8d66cf6 100644
--- a/src/mx4_linux/gui.py
+++ b/src/mx4_linux/gui.py
@@ -20,6 +20,7 @@ def __init__(self, app, demo=False):
self.devices = []
self.selected_id = None
self.current = None
+ self.setting_widgets = {}
from .desktop import DesktopController
self.desktop_status = self.desktop_toggle = self.cancel_action = None
self.desktop = DesktopController(self)
@@ -41,35 +42,62 @@ def __init__(self, app, demo=False):
self.refresh.connect("clicked", lambda *_: self.reload())
header.pack_end(self.refresh)
toolbar.add_top_bar(header)
+ self.stack = Gtk.Stack(vexpand=True, transition_type=Gtk.StackTransitionType.CROSSFADE,
+ transition_duration=150)
+ switcher = Gtk.StackSwitcher(stack=self.stack, halign=Gtk.Align.CENTER,
+ margin_top=6, margin_bottom=6)
+ toolbar.add_top_bar(switcher)
- page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=18,
- margin_start=24, margin_end=24, margin_top=24, margin_bottom=24)
- clamp = Adw.Clamp(maximum_size=760, tightening_threshold=620)
- clamp.set_child(page)
- scroll = Gtk.ScrolledWindow(hscrollbar_policy=Gtk.PolicyType.NEVER, vexpand=True)
- scroll.set_child(clamp)
- toolbar.set_content(scroll)
- self.set_content(toolbar)
-
- intro = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
- heading = Gtk.Label(label="Your mouse, on Linux", xalign=0)
- heading.add_css_class("title-1")
- intro.append(heading)
- text = "Changes in this preview are simulated." if demo else "Tune scrolling, assign buttons and control haptic feedback."
- intro.append(Gtk.Label(label=text, xalign=0, wrap=True))
- page.append(intro)
+ mouse_page = self.add_page("mouse", "Mouse", "Your mouse, your way",
+ "Changes in this preview are simulated." if demo
+ else "Fine-tune your pointer, scrolling and haptic feedback.")
+ from .wheel import WheelPreview
+ self.wheel = WheelPreview()
+ self.wheel.set_visible(False)
+ mouse_page.append(self.wheel)
+ self.controls = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=24)
+ mouse_page.append(self.controls)
+ self.actions_box = self.add_page("actions", "Actions", "A shortcut to your next move",
+ "Choose an action from the ring, or build a routine that does more in one press.")
+ self.profiles_box = self.add_page("profiles", "Profiles", "A setup for every task",
+ "Save your mouse settings, then switch between them when you need to.")
+ self.profile_controls = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=24)
+ self.profiles_box.append(self.profile_controls)
+ self.add_desktop_controls()
- self.status = Gtk.Label(label="Reading connected devices…", xalign=0, wrap=True, selectable=True)
+ status_bar = Gtk.Box(spacing=12, margin_start=24, margin_end=24,
+ margin_top=12, margin_bottom=12)
+ self.spinner = Gtk.Spinner(visible=False, valign=Gtk.Align.CENTER)
+ status_bar.append(self.spinner)
+ self.status = Gtk.Label(label="Reading connected devices…", xalign=0,
+ wrap=True, selectable=True, hexpand=True)
self.status.add_css_class("dim-label")
- page.append(self.status)
- self.spinner = Gtk.Spinner(halign=Gtk.Align.START)
- page.append(self.spinner)
- self.controls = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=24)
- page.append(self.controls)
+ status_bar.append(self.status)
+ toolbar.add_bottom_bar(status_bar)
+ toolbar.set_content(self.stack)
+ self.toasts = Adw.ToastOverlay(child=toolbar)
+ self.set_content(self.toasts)
self.reload()
+ def add_page(self, name, title, heading, description):
+ page = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=24,
+ margin_start=24, margin_end=24, margin_top=24, margin_bottom=24)
+ intro = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
+ label = Gtk.Label(label=heading, xalign=0, wrap=True)
+ label.add_css_class("title-1")
+ intro.append(label)
+ detail = Gtk.Label(label=description, xalign=0, wrap=True)
+ detail.add_css_class("dim-label")
+ intro.append(detail)
+ page.append(intro)
+ clamp = Adw.Clamp(maximum_size=760, tightening_threshold=620, child=page)
+ scroll = Gtk.ScrolledWindow(hscrollbar_policy=Gtk.PolicyType.NEVER, vexpand=True, child=clamp)
+ self.stack.add_titled(scroll, name, title)
+ return page
+
def on_close(self, *_):
self.closed = True
+ self.wheel.stop()
self.desktop.close()
if self.device_refresh_source:
GLib.source_remove(self.device_refresh_source)
@@ -104,10 +132,12 @@ def job(self, work, done, message, failed=None):
return
self.busy = True
self.controls.set_sensitive(False)
+ self.profile_controls.set_sensitive(False)
self.refresh.set_sensitive(False)
self.spinner.set_visible(True)
self.spinner.start()
self.status.set_text(message)
+ self.update_desktop_status()
future = self.executor.submit(work)
def finish():
@@ -115,9 +145,11 @@ def finish():
return GLib.SOURCE_REMOVE
self.busy = False
self.controls.set_sensitive(True)
+ self.profile_controls.set_sensitive(True)
self.refresh.set_sensitive(True)
self.spinner.stop()
self.spinner.set_visible(False)
+ self.update_desktop_status()
try:
result = future.result()
except Exception as exc:
@@ -140,12 +172,14 @@ def loaded(result):
self.job(self.backend.scan, loaded, "Reading connected devices… Wake the mouse if it is asleep.")
def clear_controls(self):
+ self.setting_widgets.clear()
while child := self.controls.get_first_child():
self.controls.remove(child)
def render(self, result):
self.clear_controls()
self.current = None
+ self.wheel.set_visible(False)
if not self.devices:
denied = any(d.get("permission_denied") for d in result.get("diagnostics", []))
title = "Allow access to your mouse" if denied else "Connect an MX Master 4"
@@ -158,7 +192,8 @@ def render(self, result):
self.controls.append(empty)
diagnostics = "\n".join(f"{d.get('path', '')}: {d['message']}" for d in result.get("diagnostics", []))
self.status.set_text(diagnostics or "No accessible MX Master 4 found.")
- self.add_desktop_controls()
+ self.add_profiles()
+ self.update_desktop_status()
return
self.current = next((d for d in self.devices if d["id"] == self.selected_id), self.devices[0])
@@ -176,9 +211,13 @@ def render(self, result):
self.controls.append(device_group)
if not self.current.get("online"):
self.status.set_text("Mouse is asleep or offline. Wake it and refresh.")
- self.add_desktop_controls()
+ self.add_profiles()
+ self.update_desktop_status()
return
+ self.wheel.set_visible(True)
+ self.update_wheel()
+
groups = {}
names = [("Pointer and scrolling", ("dpi", "smart-shift", "scroll-", "hires-", "thumb-")),
("Haptic feedback", ("haptic-", "force-sensing")), ("Buttons", ("reprogrammable-keys",))]
@@ -193,7 +232,7 @@ def render(self, result):
self.controls.append(Gtk.Label(label="The mouse did not report any supported settings. Wake it and refresh.", wrap=True))
self.add_profiles()
- self.add_desktop_controls()
+ self.update_desktop_status()
diagnostic_text = " · ".join(d["message"] for d in result.get("diagnostics", []))
if self.demo:
self.status.set_text("Demo mode · all changes are simulated")
@@ -202,8 +241,8 @@ def render(self, result):
def add_desktop_controls(self):
group = Adw.PreferencesGroup(title="Actions Ring and Smart Actions",
- description="Eight ring positions, shortcuts and multi-step routines. Flow is planned for later.")
- self.controls.append(group)
+ description="Start with a preview. Enable mouse integration when you're ready to use the haptic panel.")
+ self.actions_box.append(group)
self.desktop_status = Adw.ActionRow(use_markup=False, title="Mouse integration", subtitle=self.desktop.message)
self.desktop_status.set_subtitle_lines(5)
self.desktop_toggle = Gtk.Button(valign=Gtk.Align.CENTER)
@@ -211,25 +250,28 @@ def add_desktop_controls(self):
self.desktop_status.add_suffix(self.desktop_toggle)
group.add(self.desktop_status)
ring_row = Adw.ActionRow(use_markup=False, title="Actions Ring", subtitle="Hold the haptic panel, move and release, or click then select. Escape closes the ring.")
- preview = Gtk.Button(label="Preview ring", valign=Gtk.Align.CENTER)
+ preview = Gtk.Button(label="Try the ring", valign=Gtk.Align.CENTER,
+ tooltip_text="Explore the ring without running actions")
preview.connect("clicked", lambda *_: self.desktop.open_ring(preview=True))
ring_row.add_suffix(preview)
group.add(ring_row)
edit_row = Adw.ActionRow(use_markup=False, title="Customize actions", subtitle="Assign ring positions and mouse buttons; create routines with shortcuts, applications, text and delays.")
edit_row.set_subtitle_lines(3)
- edit = Gtk.Button(label="Configure", valign=Gtk.Align.CENTER)
+ edit = Gtk.Button(label="Edit actions", valign=Gtk.Align.CENTER)
+ edit.add_css_class("suggested-action")
edit.connect("clicked", lambda *_: self.desktop.configure())
edit_row.add_suffix(edit)
group.add(edit_row)
cancel_row = Adw.ActionRow(use_markup=False, title="Running routine", subtitle="Cancel stops subsequent steps and releases any held shortcut keys.")
- self.cancel_action = Gtk.Button(label="Cancel", valign=Gtk.Align.CENTER)
+ self.cancel_action = Gtk.Button(label="Stop routine", valign=Gtk.Align.CENTER)
self.cancel_action.connect("clicked", lambda *_: self.desktop.cancelled.set())
cancel_row.add_suffix(self.cancel_action)
group.add(cancel_row)
import os
from .actions import _native_wtype
if not _native_wtype() and not os.access("/dev/uinput", os.R_OK | os.W_OK):
- group.add(Adw.ActionRow(use_markup=False, title="Enable keyboard shortcuts", subtitle="Run ./scripts/install-input-access.sh once. Desktop actions and app launches work without it."))
+ group.add(Adw.ActionRow(use_markup=False, title="Set up keyboard input",
+ subtitle="Install wtype for native Wayland shortcuts and text. See the installation guide for the optional input-access fallback."))
self.update_desktop_status()
def update_desktop_status(self):
@@ -238,7 +280,8 @@ def update_desktop_status(self):
if self.desktop_toggle:
active = self.desktop.session.running
self.desktop_toggle.set_label("Disable" if active else "Enable")
- self.desktop_toggle.set_sensitive(not self.demo and not self.desktop.session.stopping)
+ self.desktop_toggle.set_sensitive(not self.demo and not self.desktop.session.stopping
+ and (active or (not self.busy and bool(self.current and self.current.get("online")))))
if self.cancel_action:
self.cancel_action.set_sensitive(self.desktop.action_busy)
@@ -256,6 +299,7 @@ def add_setting(self, group, setting):
value = (setting.get("value") or {}).get(key["value"])
row = Adw.ActionRow(use_markup=False, title=key["label"], subtitle="Built-in mouse function")
widget = self.choice(setting, key["choices"], value, key["value"])
+ widget.update_property([Gtk.AccessibleProperty.LABEL], [key["label"]])
row.add_suffix(widget)
group.add(row)
return
@@ -266,13 +310,18 @@ def add_setting(self, group, setting):
if kind == "toggle":
widget = Gtk.Switch(active=bool(value), valign=Gtk.Align.CENTER)
widget.set_sensitive(value is not None)
- widget.connect("notify::active", lambda switch, _p: self.change(setting, switch.get_active()))
+ handler = widget.connect("notify::active", lambda switch, _p: self.change(setting, switch.get_active()))
+ self.setting_widgets[(setting["name"], None)] = (widget, handler, widget.set_active)
+ row.set_activatable_widget(widget)
elif kind == "range":
box = Gtk.Box(spacing=8, valign=Gtk.Align.CENTER)
widget = Gtk.SpinButton.new_with_range(setting["minimum"], setting["maximum"], 1)
widget.set_value(value if value is not None else setting["minimum"])
widget.set_sensitive(value is not None)
+ widget.update_property([Gtk.AccessibleProperty.LABEL], [setting["label"]])
+ self.setting_widgets[(setting["name"], None)] = (widget, None, widget.set_value)
apply_button = Gtk.Button(label="Apply", sensitive=value is not None)
+ apply_button.set_tooltip_text(f"Apply {setting['label'].lower()}")
apply_button.connect("clicked", lambda *_, spin=widget: self.change(setting, spin.get_value_as_int()))
box.append(widget)
box.append(apply_button)
@@ -305,32 +354,100 @@ def changed(widget, _param):
index = widget.get_selected()
if index < len(choices):
self.change(setting, choices[index]["value"], key)
- dropdown.connect("notify::selected", changed)
+ handler = dropdown.connect("notify::selected", changed)
+ def select(confirmed):
+ dropdown.set_selected(next((i for i, item in enumerate(choices) if item["value"] == confirmed), Gtk.INVALID_LIST_POSITION))
+ self.setting_widgets[(setting["name"], key)] = (dropdown, handler, select)
return dropdown
def change(self, setting, value, key=None):
+ if self.busy:
+ return
+ previous = setting.get("value")
+ if key is not None:
+ previous = (previous or {}).get(str(key), (previous or {}).get(key))
+ if setting["name"] != "haptic-play" and previous == value:
+ return
device_id = self.current["id"]
text = "Simulated change." if self.demo else f"Applied {setting['label']}."
+ def applied(response):
+ if response.get("refresh_required"):
+ self.refresh_after_write(text)
+ return
+ confirmed = {setting["name"]: response["value"], **response.get("values", {})}
+ for name, result in confirmed.items():
+ item = next((s for s in self.current["settings"] if s["name"] == name), None)
+ if item is None or name == "haptic-play":
+ continue
+ if key is not None and name == setting["name"]:
+ item["value"][str(key)] = result
+ else:
+ item["value"] = result
+ self.sync_setting(item, key if name == setting["name"] else None)
+ self.update_wheel()
+ self.status.set_text(text)
+ self.toasts.add_toast(Adw.Toast(title=text, timeout=2))
+ def failed(error):
+ self.refresh_after_write(error)
self.job(lambda: self.backend.write(device_id, setting["name"], value, key),
- lambda _: self.reload(text), f"Applying {setting['label']}…", failed=lambda error: self.reload(error))
+ applied, f"Applying {setting['label']}…", failed=failed)
+
+ def sync_setting(self, setting, key=None):
+ entry = self.setting_widgets.get((setting["name"], key))
+ if entry is None:
+ return
+ widget, handler, update = entry
+ value = setting.get("value")
+ if key is not None:
+ value = (value or {}).get(str(key), (value or {}).get(key))
+ if value is not None:
+ if handler is not None:
+ widget.handler_block(handler)
+ try:
+ update(value)
+ finally:
+ if handler is not None:
+ widget.handler_unblock(handler)
+
+ def update_wheel(self):
+ mode = next((s.get("value") for s in self.current["settings"] if s["name"] == "scroll-ratchet"), None)
+ self.wheel.configure(mode == 1)
+
+ def refresh_after_write(self, notice):
+ # A timed-out reply or partial profile can follow physical changes.
+ self.current = None
+ self.clear_controls()
+ self.wheel.set_visible(False)
+ self.add_profiles()
+ self.reload(notice)
def add_profiles(self):
+ while child := self.profile_controls.get_first_child():
+ self.profile_controls.remove(child)
+ if not self.current or not self.current.get("online"):
+ self.profile_controls.append(Adw.StatusPage(title="Connect your mouse to use profiles",
+ description="Profiles save settings from a connected, awake mouse.",
+ icon_name="input-mouse-symbolic"))
+ return
group = Adw.PreferencesGroup(title="Profiles", description="Save current settings and apply them manually. Haptic playback is excluded.")
- self.controls.append(group)
+ self.profile_controls.append(group)
save_row = Adw.ActionRow(title="Save current settings")
entry = Gtk.Entry(placeholder_text="Profile name", max_length=64, valign=Gtk.Align.CENTER)
- save_button = Gtk.Button(label="Save", valign=Gtk.Align.CENTER)
+ entry.update_property([Gtk.AccessibleProperty.LABEL], ["Profile name"])
+ save_button = Gtk.Button(label="Save", valign=Gtk.Align.CENTER, sensitive=False)
+ entry.connect("changed", lambda *_: save_button.set_sensitive(bool(entry.get_text().strip())))
save_row.add_suffix(entry)
save_row.add_suffix(save_button)
group.add(save_row)
def save(*_):
- try:
- self.store.save(entry.get_text(), self.current, demo=self.demo)
+ name, device = entry.get_text(), self.current
+ def saved(_result):
self.status.set_text("Profile saved.")
- self.reload("Profile saved.")
- except Exception as exc:
- self.status.set_text(str(exc))
+ self.add_profiles()
+ self.toasts.add_toast(Adw.Toast(title="Profile saved.", timeout=2))
+ self.job(lambda: self.store.save(name, device, demo=self.demo), saved, "Saving profile…")
save_button.connect("clicked", save)
+ entry.connect("activate", lambda *_: save() if entry.get_text().strip() else None)
try:
profiles = {n: p for n, p in self.store.read().items() if p.get("demo", False) == self.demo}
except Exception as exc:
@@ -347,8 +464,8 @@ def apply(*_):
profile = profiles[names[chooser.get_selected()]]
device = self.current
self.job(lambda: apply_profile(self.backend, device, profile, demo=self.demo, cancelled=lambda: self.closed),
- lambda count: self.reload(f"Profile applied · {count} changes."), "Applying profile…",
- failed=lambda error: self.reload(error))
+ lambda count: self.refresh_after_write(f"Profile applied · {count} changes."), "Applying profile…",
+ failed=self.refresh_after_write)
apply_button.connect("clicked", apply)
load_row.add_suffix(chooser)
load_row.add_suffix(apply_button)
diff --git a/src/mx4_linux/motion.py b/src/mx4_linux/motion.py
new file mode 100644
index 0000000..88efeb4
--- /dev/null
+++ b/src/mx4_linux/motion.py
@@ -0,0 +1,60 @@
+"""Small, time-based transitions shared by native previews.
+
+No frame counting: interrupted animations continue from their current position,
+and a slow frame still reaches the target on time.
+"""
+
+import math
+from time import monotonic
+
+
+class Transition:
+ def __init__(self, value=0.0, duration=0.16):
+ self.start = self.target = float(value)
+ self.started = 0.0
+ self.duration = duration
+
+ def value(self, now=None):
+ now = monotonic() if now is None else now
+ progress = min(1.0, max(0.0, (now - self.started) / self.duration))
+ return self.start + (self.target - self.start) * (1 - (1 - progress) ** 3)
+
+ def move(self, target, *, animate=True, now=None):
+ now = monotonic() if now is None else now
+ self.start = self.value(now) if animate else float(target)
+ self.target, self.started = float(target), now
+
+ def active(self, now=None):
+ now = monotonic() if now is None else now
+ return self.start != self.target and now < self.started + self.duration
+
+
+class WheelMotion:
+ """Finite wheel impulse with exponential slowdown, independent of frame rate."""
+
+ def __init__(self):
+ self.position = 0.0
+ self.velocity = 0.0
+ self.updated = None
+
+ def impulse(self, amount):
+ if math.isfinite(amount):
+ self.velocity = max(-24.0, min(24.0, self.velocity + amount * 6))
+
+ def advance(self, now, *, free_spin=False):
+ if self.updated is not None:
+ elapsed = max(0.0, now - self.updated)
+ decay = 3.8 if free_spin else 8.0
+ remaining = math.exp(-decay * elapsed)
+ self.position += self.velocity * (1 - remaining) / decay
+ self.velocity *= remaining
+ self.updated = now
+ if abs(self.velocity) < 0.025:
+ # Settle the subpixel tail at the same position on every refresh rate.
+ self.position += self.velocity / (3.8 if free_spin else 8.0)
+ self.velocity = 0.0
+ return self.velocity != 0.0
+
+ def stop(self):
+ self.velocity = 0.0
+ self.updated = None
diff --git a/src/mx4_linux/ring.py b/src/mx4_linux/ring.py
index bcbbabc..2d1212f 100644
--- a/src/mx4_linux/ring.py
+++ b/src/mx4_linux/ring.py
@@ -1,20 +1,39 @@
-"""Centered Wayland Actions Ring, operated by pointer, keyboard or raw XY."""
+"""Compact native Actions Ring with animated icon buttons and action groups."""
import math
+from time import monotonic
-from .gtk_support import Adw, Gdk, Gtk, Layer
-from .ring_model import RingState
+from .gtk_support import Gdk, Gtk, Layer
+from gi.repository import GObject, Pango
+from .motion import Transition
+from .ring_icons import action_icon
+from .ring_model import BUTTON_RADIUS, CENTER_RADIUS, RingState, button_center
+
+
+WIDTH, HEIGHT = 720, 460
+CENTER_X, CENTER_Y = 270, 220
+CHILD_RADIUS = 23
class ActionsRing(Gtk.Window):
def __init__(self, application, selected, dismissed, hovered=None):
super().__init__(application=application, title="MX4 Actions Ring", decorated=False,
- resizable=False, default_width=460, default_height=500)
+ resizable=False, default_width=WIDTH, default_height=HEIGHT)
self.state = RingState()
self.on_selected, self.on_dismissed, self.on_hover = selected, dismissed, hovered
self.config = None
self.preview = False
- self.overlay_supported = bool(Layer and Layer.is_supported())
+ self.tick_id = 0
+ self.reveal = Transition(1, duration=0.18)
+ self.group_reveal = Transition(0, duration=0.16)
+ self.label_reveal = Transition(1, duration=0.10)
+ self.spread = 1.0
+ self.group_slot = self.child_selected = None
+ self.children = []
+ self.child_positions = []
+ self.settings = Gtk.Settings.get_default()
+ display = Gdk.Display.get_default()
+ self.overlay_supported = bool(Layer and display.__gtype__.name == "GdkWaylandDisplay" and Layer.is_supported())
if self.overlay_supported:
Layer.init_for_window(self)
Layer.set_namespace(self, "mx4-actions-ring")
@@ -23,31 +42,134 @@ def __init__(self, application, selected, dismissed, hovered=None):
Layer.set_exclusive_zone(self, 0)
self.add_css_class("mx4-ring")
css = Gtk.CssProvider()
- css.load_from_string("window.mx4-ring { background: transparent; box-shadow: none; }")
- Gtk.StyleContext.add_provider_for_display(Gdk.Display.get_default(), css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
- self.canvas = Gtk.DrawingArea(content_width=460, content_height=500, focusable=True)
+ css.load_from_string("""
+ window.mx4-ring { background: transparent; box-shadow: none; }
+ .mx4-ring button.ring-action, .mx4-ring button.ring-close {
+ background: #eef2f4; color: #15181d; border: 1px solid alpha(black, 0.15);
+ border-radius: 9999px; padding: 0; box-shadow: 0 2px 5px alpha(black, 0.16);
+ min-width: 0; min-height: 0;
+ }
+ .mx4-ring button.ring-action.selected { background: #15181d; color: white; border-color: #eef2f4; }
+ .mx4-ring button.ring-close { background: #d9e1e5; }
+ .mx4-ring button:focus-visible { outline: 3px solid #3584e4; outline-offset: 3px; }
+ .mx4-ring .ring-callout {
+ background: #f8fafb; color: #15181d; border: 1px solid alpha(black, 0.12);
+ border-radius: 12px; padding: 7px 10px; box-shadow: 0 2px 5px alpha(black, 0.12);
+ }
+ .mx4-ring .ring-shortcut { color: #53616b; font-size: 11px; }
+ .mx4-ring .ring-hint {
+ background: #20242b; color: #f0f3f6; border-radius: 12px;
+ padding: 6px 12px; font-size: 12px;
+ }
+ """)
+ Gtk.StyleContext.add_provider_for_display(display, css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
+ self.canvas = Gtk.DrawingArea(content_width=WIDTH, content_height=HEIGHT, focusable=True)
+ self.canvas.update_property([Gtk.AccessibleProperty.LABEL],
+ ["Actions Ring. Arrow keys select, Enter opens or runs, keys 1 through 8 choose, Escape goes back or closes."])
self.canvas.set_draw_func(self.draw)
- self.set_child(self.canvas)
+ self.surface = Gtk.Overlay(child=self.canvas)
+ self.labels = Gtk.Fixed()
+ self.surface.add_overlay(self.labels)
+ self.buttons, self.icons = [], []
+ for index in range(8):
+ button, icon = self.make_button(BUTTON_RADIUS)
+ button.connect("clicked", lambda _button, i=index: self.commit(i) if not self.state.held else None)
+ focus = Gtk.EventControllerFocus()
+ focus.connect("enter", lambda _controller, i=index: self.focus_action(i))
+ button.add_controller(focus)
+ self.labels.put(button, 0, 0)
+ self.buttons.append(button)
+ self.icons.append(icon)
+ self.child_buttons, self.child_icons = [], []
+ for index in range(6):
+ button, icon = self.make_button(CHILD_RADIUS)
+ button.add_css_class("child-action")
+ button.set_visible(False)
+ button.connect("clicked", lambda _button, i=index: self.commit_child(i))
+ focus = Gtk.EventControllerFocus()
+ focus.connect("enter", lambda _controller, i=index: self.focus_child(i))
+ button.add_controller(focus)
+ self.labels.put(button, 0, 0)
+ self.child_buttons.append(button)
+ self.child_icons.append(icon)
+ self.close_button = Gtk.Button(icon_name="window-close-symbolic", width_request=32, height_request=32,
+ tooltip_text="Close Actions Ring")
+ self.close_button.add_css_class("ring-close")
+ self.close_button.update_property([Gtk.AccessibleProperty.LABEL], ["Close Actions Ring"])
+ self.close_button.connect("clicked", lambda *_: self.dismiss())
+ self.labels.put(self.close_button, CENTER_X - CENTER_RADIUS, CENTER_Y - CENTER_RADIUS)
+ self.callout = Gtk.Box(spacing=8, valign=Gtk.Align.CENTER)
+ self.callout.add_css_class("ring-callout")
+ self.callout.set_can_target(False)
+ self.callout_label = Gtk.Label(wrap=True, lines=2, wrap_mode=Pango.WrapMode.WORD_CHAR,
+ ellipsize=Pango.EllipsizeMode.END, max_width_chars=1, hexpand=True)
+ self.callout.append(self.callout_label)
+ self.callout_key = Gtk.Label()
+ self.callout_key.add_css_class("ring-shortcut")
+ self.callout.append(self.callout_key)
+ self.labels.put(self.callout, 0, 0)
+ self.instructions = Gtk.Label(width_request=480)
+ self.instructions.add_css_class("ring-hint")
+ self.instructions.set_can_target(False)
+ self.labels.put(self.instructions, 30, HEIGHT - 28)
+ self.set_child(self.surface)
motion = Gtk.EventControllerMotion()
motion.connect("motion", self.pointer_motion)
- self.canvas.add_controller(motion)
+ motion.connect("leave", self.pointer_leave)
+ self.surface.add_controller(motion)
click = Gtk.GestureClick(button=1)
+ # Native buttons have square allocations. Claim pointer clicks here so
+ # only the actual circular faces can select an action.
+ click.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
+ click.connect("pressed", lambda gesture, *_: gesture.set_state(Gtk.EventSequenceState.CLAIMED))
click.connect("released", self.pointer_click)
- self.canvas.add_controller(click)
+ self.surface.add_controller(click)
keys = Gtk.EventControllerKey()
+ keys.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
keys.connect("key-pressed", self.key_pressed)
self.add_controller(keys)
self.connect("close-request", lambda *_: self.dismiss() or True)
+ self.connect("unmap", lambda *_: self.stop_animation())
+ self.settings.connect("notify::gtk-enable-animations", self.motion_preference_changed)
+
+ @staticmethod
+ def make_button(radius):
+ button = Gtk.Button(width_request=radius * 2, height_request=radius * 2)
+ button.add_css_class("ring-action")
+ icon = Gtk.Image(pixel_size=23)
+ button.set_child(icon)
+ return button, icon
+
+ def groups(self):
+ return self.config.get("ring_groups", {}) if self.config else {}
def show_ring(self, config, held=False, preview=False):
self.config, self.preview = config, preview
+ self.close_group()
self.state.open(held)
- self.canvas.queue_draw()
+ for index, action_id in enumerate(config["ring"]):
+ action = config["actions"][action_id]
+ grouped = str(index) in self.groups()
+ self.icons[index].set_from_icon_name(action_icon(action, grouped=grouped))
+ text = f"{index + 1}. {action['label']}" + (". Open action group" if grouped else "")
+ self.buttons[index].set_tooltip_text(text)
+ self.buttons[index].update_property([Gtk.AccessibleProperty.LABEL], [text])
+ if grouped:
+ self.expanded_state(self.buttons[index], False)
+ else:
+ self.buttons[index].reset_state(Gtk.AccessibleState.EXPANDED)
+ self.reveal.move(0, animate=False)
+ self.reveal.move(1, animate=self.animations_enabled())
+ self.apply_frame(monotonic())
+ self.update_labels()
self.present()
self.canvas.grab_focus()
+ self.animate()
def hide_ring(self):
self.state.cancel()
+ self.close_group()
+ self.stop_animation()
self.set_visible(False)
Gdk.Display.get_default().flush()
@@ -58,17 +180,29 @@ def dismiss(self):
return False
def commit(self, index):
+ if not self.state.visible or type(index) is not int or not 0 <= index < 8:
+ return
+ if str(index) in self.groups():
+ self.state.held = False
+ self.state.selected = index
+ self.open_group(index, focus=True)
+ return
chosen = self.state.choose(index)
if chosen is not None:
self.hide_ring()
self.on_selected(self.config["ring"][chosen], self.preview)
def release_button(self):
+ index = self.state.selected
+ if self.state.visible and self.state.held and index is not None and str(index) in self.groups():
+ self.commit(index)
+ return
index = self.state.release()
if index is not None:
self.hide_ring()
self.on_selected(self.config["ring"][index], self.preview)
else:
+ self.update_labels()
self.canvas.queue_draw()
def motion(self, dx, dy):
@@ -77,95 +211,289 @@ def motion(self, dx, dy):
self.changed(before)
def changed(self, before):
- if before != self.state.selected and self.state.selected is not None and self.on_hover:
- self.on_hover(self.state.selected)
+ if before != self.state.selected:
+ self.child_selected = None
+ self.update_labels()
+ if self.state.selected is not None and self.on_hover:
+ self.on_hover(self.state.selected)
+ if before != self.state.selected or self.state.held:
+ self.canvas.queue_draw()
+
+ def focus_action(self, index):
+ if self.state.visible and not self.state.held:
+ if self.group_slot is not None and index != self.group_slot:
+ self.close_group()
+ before = self.state.selected
+ self.state.selected = index
+ self.changed(before)
+
+ def open_group(self, index, focus=False):
+ children = self.groups().get(str(index))
+ if not children or not self.state.visible:
+ return
+ if self.group_slot != index:
+ if self.group_slot is not None:
+ self.expanded_state(self.buttons[self.group_slot], False)
+ self.group_slot, self.children, self.child_selected = index, list(children), None
+ self.expanded_state(self.buttons[index], True)
+ for i, button in enumerate(self.child_buttons):
+ button.set_visible(i < len(children))
+ if i < len(children):
+ action = self.config["actions"][children[i]]
+ self.child_icons[i].set_from_icon_name(action_icon(action))
+ label = f"{i + 1}. {action['label']}"
+ button.set_tooltip_text(label)
+ button.update_property([Gtk.AccessibleProperty.LABEL], [label])
+ self.group_reveal.move(0, animate=False)
+ self.group_reveal.move(1, animate=self.animations_enabled())
+ self.apply_frame(monotonic())
+ self.animate()
+ if focus:
+ self.child_selected = 0
+ self.child_buttons[0].grab_focus()
+ self.update_labels()
+
+ def close_group(self):
+ if self.group_slot is not None:
+ self.expanded_state(self.buttons[self.group_slot], False)
+ self.group_slot = self.child_selected = None
+ self.children = []
+ self.child_positions = []
+ self.group_reveal.move(0, animate=False)
+ for button in getattr(self, "child_buttons", []):
+ button.set_visible(False)
+
+ def focus_child(self, index):
+ if self.state.visible and self.group_slot is not None and index < len(self.children):
+ before = self.child_selected
+ self.child_selected = index
+ self.update_labels()
+ if before != index and self.on_hover:
+ self.on_hover(index)
+
+ def commit_child(self, index):
+ if (self.state.visible and not self.state.held and self.group_slot is not None
+ and type(index) is int and 0 <= index < len(self.children)):
+ action_id = self.children[index]
+ self.hide_ring()
+ self.on_selected(action_id, self.preview)
+
+ def update_labels(self):
+ for index, button in enumerate(self.buttons):
+ self.selected_style(button, index == self.state.selected or index == self.group_slot)
+ for index, button in enumerate(self.child_buttons):
+ self.selected_style(button, index == self.child_selected)
+ selected = self.state.selected
+ child = self.child_selected
+ self.callout.set_visible(selected is not None or child is not None)
+ if child is not None and self.group_slot is not None:
+ action_id = self.children[child]
+ x, y = self.child_positions[child]
+ position, width = (x + CHILD_RADIUS + 10, y - 18), 176
+ key = str(child + 1)
+ elif self.group_slot is not None:
+ action_id = self.config["ring"][self.group_slot]
+ position, width = (CENTER_X + 150, 4), 230
+ key = "group"
+ elif selected is not None:
+ action_id = self.config["ring"][selected]
+ dx, dy = button_center(selected)
+ x, y = CENTER_X + dx, CENTER_Y + dy
+ width = 116 if dx < -40 else 170
+ if abs(dx) < 40:
+ position = (x - width / 2, y - 86 if dy < 0 else y + 40)
+ elif dx < 0:
+ position = (max(8, x - BUTTON_RADIUS - width - 10), y - 20)
+ else:
+ position = (x + BUTTON_RADIUS + 10, y - 20)
+ key = str(selected + 1)
+ else:
+ action_id = None
+ if action_id is not None:
+ text = self.config["actions"][action_id]["label"]
+ if text != self.callout_label.get_text():
+ self.label_reveal.move(0, animate=False)
+ self.label_reveal.move(1, animate=self.animations_enabled())
+ self.animate()
+ self.callout_label.set_text(text)
+ self.callout_label.set_lines(1 if self.group_slot is not None and child is None else 2)
+ self.callout_key.set_text(key)
+ self.callout.set_size_request(width, -1)
+ self.labels.move(self.callout, *position)
+ self.callout.set_opacity(self.label_reveal.value())
+ if self.group_slot is not None:
+ hint = f"{'Preview · ' if self.preview else ''}Choose a group action · 1–{len(self.children)} · Esc to go back"
+ else:
+ hint = ("Preview · " if self.preview else "") + ("Hold · move · release" if self.state.held else "Choose an action · 1–8 · Esc to close")
+ self.instructions.set_text(hint)
+
+ @staticmethod
+ def expanded_state(button, expanded):
+ value = GObject.Value(GObject.TYPE_INT, int(expanded))
+ button.update_state([Gtk.AccessibleState.EXPANDED], [value])
+
+ @staticmethod
+ def selected_style(button, selected):
+ if selected:
+ button.add_css_class("selected")
+ else:
+ button.remove_css_class("selected")
+
+ def animations_enabled(self):
+ return self.settings.get_property("gtk-enable-animations")
+
+ def animate(self):
+ if self.state.visible and self.animations_enabled() and not self.tick_id:
+ self.tick_id = self.canvas.add_tick_callback(self.tick)
+
+ def apply_frame(self, now):
+ reveal = self.reveal.value(now)
+ self.spread = 0.78 + 0.22 * reveal
+ self.surface.set_opacity(reveal)
+ for index, button in enumerate(self.buttons):
+ dx, dy = button_center(index)
+ self.labels.move(button, CENTER_X + dx * self.spread - BUTTON_RADIUS,
+ CENTER_Y + dy * self.spread - BUTTON_RADIUS)
+ self.callout.set_opacity(self.label_reveal.value(now))
+ if self.group_slot is not None:
+ progress = self.group_reveal.value(now)
+ dx, dy = button_center(self.group_slot)
+ origin_x, origin_y = CENTER_X + dx, CENTER_Y + dy
+ self.child_positions = []
+ for index in range(len(self.children)):
+ offset = index - (len(self.children) - 1) / 2
+ x, y = CENTER_X + 214 - abs(offset) * 7, CENTER_Y + offset * 62
+ px, py = origin_x + (x - origin_x) * progress, origin_y + (y - origin_y) * progress
+ self.child_positions.append((px, py))
+ self.labels.move(self.child_buttons[index], px - CHILD_RADIUS, py - CHILD_RADIUS)
+ self.child_buttons[index].set_opacity(progress)
+ if self.child_selected is not None:
+ x, y = self.child_positions[self.child_selected]
+ self.labels.move(self.callout, x + CHILD_RADIUS + 10, y - 18)
+
+ def tick(self, _widget, _clock):
+ now = monotonic()
+ self.apply_frame(now)
self.canvas.queue_draw()
+ active = self.state.visible and any(t.active(now) for t in (self.reveal, self.group_reveal, self.label_reveal))
+ if not active:
+ self.tick_id = 0
+ return active
+
+ def stop_animation(self):
+ if self.tick_id:
+ self.canvas.remove_tick_callback(self.tick_id)
+ self.tick_id = 0
+
+ def motion_preference_changed(self, *_):
+ if not self.animations_enabled():
+ self.stop_animation()
+ for transition in (self.reveal, self.group_reveal, self.label_reveal):
+ transition.move(transition.target, animate=False)
+ self.apply_frame(monotonic())
+ self.canvas.queue_draw()
+
+ def child_at(self, x, y):
+ if not math.isfinite(x) or not math.isfinite(y):
+ return None
+ for index, (cx, cy) in enumerate(self.child_positions):
+ if math.hypot(x - cx, y - cy) > CHILD_RADIUS:
+ continue
+ # Revealing children start on their parent. A trigger click must
+ # never execute an overlapping, still emerging child action.
+ main_centers = ((CENTER_X + dx * self.spread, CENTER_Y + dy * self.spread)
+ for dx, dy in (button_center(i) for i in range(8)))
+ if any(math.hypot(cx - mx, cy - my) <= CHILD_RADIUS + BUTTON_RADIUS for mx, my in main_centers):
+ continue
+ if any(i != index and math.hypot(cx - px, cy - py) < CHILD_RADIUS * 2
+ for i, (px, py) in enumerate(self.child_positions)):
+ continue
+ return index
+ return None
def pointer_motion(self, _controller, x, y):
- if self.state.held:
- return # Raw XY remains relative to the ring center while held.
+ if not self.state.visible or self.state.held:
+ return
+ if self.group_slot is not None:
+ child = self.child_at(x, y)
+ if child is not None:
+ self.focus_child(child)
+ return
before = self.state.selected
- self.state.point(x - self.canvas.get_width() / 2, y - 225)
+ self.state.point(x - CENTER_X, y - CENTER_Y, spread=self.spread)
+ selected = self.state.selected
+ if selected is not None and str(selected) in self.groups():
+ self.open_group(selected)
+ elif selected is not None:
+ self.close_group()
+ elif self.group_slot is not None:
+ self.state.selected = self.group_slot
+ self.child_selected = None
self.changed(before)
+ self.update_labels()
+
+ def pointer_leave(self, *_):
+ if not self.state.held and self.group_slot is None:
+ before = self.state.selected
+ self.state.selected = None
+ self.changed(before)
def pointer_click(self, _gesture, _count, x, y):
- if self.state.held:
+ if self.state.held or not self.state.visible:
+ return
+ if math.hypot(x - CENTER_X, y - CENTER_Y) <= CENTER_RADIUS:
+ self.dismiss()
return
- self.state.point(x - self.canvas.get_width() / 2, y - 225)
+ if self.group_slot is not None:
+ child = self.child_at(x, y)
+ if child is not None:
+ self.commit_child(child)
+ return
+ self.state.point(x - CENTER_X, y - CENTER_Y, spread=self.spread)
if self.state.selected is None:
self.dismiss()
else:
self.commit(self.state.selected)
def key_pressed(self, _controller, keyval, _keycode, _state):
- if keyval == Gdk.KEY_Escape:
+ if not self.state.visible:
+ return False
+ if keyval in (Gdk.KEY_Escape, Gdk.KEY_BackSpace) and self.group_slot is not None:
+ parent = self.group_slot
+ self.close_group()
+ self.state.selected = parent
+ self.buttons[parent].grab_focus()
+ self.update_labels()
+ elif keyval == Gdk.KEY_Escape:
self.dismiss()
elif Gdk.KEY_1 <= keyval <= Gdk.KEY_8:
- self.commit(keyval - Gdk.KEY_1)
- elif keyval in (Gdk.KEY_Return, Gdk.KEY_space) and self.state.selected is not None:
- self.commit(self.state.selected)
+ index = keyval - Gdk.KEY_1
+ self.commit_child(index) if self.group_slot is not None else self.commit(index)
+ elif keyval in (Gdk.KEY_Return, Gdk.KEY_space):
+ if self.get_focus() == self.close_button:
+ self.dismiss()
+ elif self.group_slot is not None and self.child_selected is not None:
+ self.commit_child(self.child_selected)
+ elif self.state.selected is not None:
+ self.commit(self.state.selected)
elif keyval in (Gdk.KEY_Right, Gdk.KEY_Down, Gdk.KEY_Left, Gdk.KEY_Up):
- before = self.state.selected
direction = 1 if keyval in (Gdk.KEY_Right, Gdk.KEY_Down) else -1
- self.state.selected = ((before if before is not None else -direction) + direction) % 8
- self.changed(before)
+ if self.group_slot is not None:
+ before = self.child_selected
+ self.child_selected = ((before if before is not None else -direction) + direction) % len(self.children)
+ self.child_buttons[self.child_selected].grab_focus()
+ self.update_labels()
+ else:
+ before = self.state.selected
+ self.state.selected = ((before if before is not None else -direction) + direction) % 8
+ self.buttons[self.state.selected].grab_focus()
+ self.changed(before)
else:
return False
return True
- @staticmethod
- def label(cr, text, x, y, size=12, bold=False, width=104):
- # Pango handles user labels, Unicode and wrapping without markup.
- from gi.repository import Pango, PangoCairo
- layout = PangoCairo.create_layout(cr)
- description = Pango.FontDescription.from_string(f"Sans {'Bold ' if bold else ''}{size}")
- layout.set_font_description(description)
- layout.set_text(text, -1)
- layout.set_width(width * Pango.SCALE)
- layout.set_alignment(Pango.Alignment.CENTER)
- layout.set_wrap(Pango.WrapMode.WORD_CHAR)
- layout.set_height(-2)
- layout.set_ellipsize(Pango.EllipsizeMode.END)
- _w, height = layout.get_pixel_size()
- cr.move_to(x - width / 2, y - height / 2)
- PangoCairo.show_layout(cr, layout)
-
def draw(self, _area, cr, width, height):
- if not self.config:
- return
- cx, cy = width / 2, 225
- # Opaque ring segments remain legible over every desktop wallpaper.
- for index in range(8):
- angle = index * math.pi / 4 - math.pi / 2
- a, b = angle - math.pi / 8 + .025, angle + math.pi / 8 - .025
- cr.new_path()
- cr.arc(cx, cy, 205, a, b)
- cr.arc_negative(cx, cy, 76, b, a)
- cr.close_path()
- if self.state.selected == index:
- cr.set_source_rgba(.22, .45, .92, .99)
- else:
- cr.set_source_rgba(.13, .14, .17, .98)
- cr.fill_preserve()
- cr.set_source_rgba(.4, .43, .52, .4)
- cr.set_line_width(1)
- cr.stroke()
- x, y = cx + 143 * math.cos(angle), cy + 143 * math.sin(angle)
- cr.set_source_rgb(.64, .70, .85)
- self.label(cr, str(index + 1), x, y - 26, 10)
- cr.set_source_rgb(1, 1, 1)
- action = self.config["actions"][self.config["ring"][index]]
- self.label(cr, action["label"], x, y + 3, 11, True)
- cr.arc(cx, cy, 71, 0, 2 * math.pi)
- cr.set_source_rgba(.09, .10, .12, .98)
- cr.fill()
- cr.set_source_rgb(.95, .96, 1)
- self.label(cr, "Preview" if self.preview else "Actions Ring", cx, cy - 8, 12, True)
- cr.set_source_rgb(.65, .68, .75)
- self.label(cr, "Esc to close", cx, cy + 20, 9)
- cr.set_source_rgb(.83, .85, .91)
- self.label(cr, "Hold, move, release" if self.state.held else "Click an action · keys 1–8", cx, 455, 10, width=420)
- if self.state.held:
- cr.arc(cx + self.state.x, cy + self.state.y, 4, 0, 2 * math.pi)
- cr.set_source_rgb(1, 1, 1)
+ if self.state.visible and self.state.held:
+ cr.arc(CENTER_X + self.state.x, CENTER_Y + self.state.y, 3, 0, math.tau)
+ cr.set_source_rgb(0.2, 0.52, 0.92)
cr.fill()
diff --git a/src/mx4_linux/ring_icons.py b/src/mx4_linux/ring_icons.py
new file mode 100644
index 0000000..c51ac50
--- /dev/null
+++ b/src/mx4_linux/ring_icons.py
@@ -0,0 +1,38 @@
+"""Choose native symbolic icons from an action's actual steps."""
+
+from pathlib import PurePath
+
+
+def action_icon(action, grouped=False):
+ if grouped:
+ return "view-app-grid-symbolic"
+ steps = action.get("steps", [])
+ if not steps:
+ return "system-run-symbolic"
+ step = steps[0]
+ kind = step.get("type")
+ if kind == "shortcut":
+ keys = tuple(key.upper().removeprefix("KEY_") for key in step.get("keys", []))
+ icons = {("CTRL", "C"): "edit-copy-symbolic", ("CTRL", "V"): "edit-paste-symbolic",
+ ("CTRL", "X"): "edit-cut-symbolic", ("CTRL", "Z"): "edit-undo-symbolic",
+ ("CTRL", "SHIFT", "Z"): "edit-redo-symbolic", ("PLAYPAUSE",): "media-playback-start-symbolic",
+ ("SYSRQ",): "camera-photo-symbolic"}
+ return icons.get(keys, "input-keyboard-symbolic")
+ if kind == "command":
+ argv = step.get("argv", [])
+ command = PurePath(argv[0]).name if argv else ""
+ if command in {"kitty", "foot", "alacritty", "wezterm", "gnome-terminal", "xterm", "konsole", "x-terminal-emulator"}:
+ return "utilities-terminal-symbolic"
+ if command in {"firefox", "chromium", "google-chrome"}:
+ return "web-browser-symbolic"
+ if command in {"xdg-open", "gio"}:
+ return "web-browser-symbolic" if any(arg.startswith(("http://", "https://")) for arg in argv[1:]) else "folder-symbolic"
+ return "application-x-executable-symbolic"
+ if kind == "niri":
+ name = step.get("action", "")
+ if "screenshot" in name:
+ return "camera-photo-symbolic"
+ if "workspace" in name:
+ return "go-previous-symbolic" if any(part in name for part in ("up", "previous", "left")) else "go-next-symbolic"
+ return "view-grid-symbolic"
+ return {"text": "insert-text-symbolic", "delay": "preferences-system-time-symbolic"}.get(kind, "system-run-symbolic")
diff --git a/src/mx4_linux/ring_model.py b/src/mx4_linux/ring_model.py
index d920d8c..f664919 100644
--- a/src/mx4_linux/ring_model.py
+++ b/src/mx4_linux/ring_model.py
@@ -3,6 +3,30 @@
import math
+ORBIT_RADIUS = 116
+BUTTON_RADIUS = 26
+CENTER_RADIUS = 16
+_BUTTON_CENTERS = tuple(
+ (ORBIT_RADIUS * math.sin(index * math.pi / 4), -ORBIT_RADIUS * math.cos(index * math.pi / 4))
+ for index in range(8)
+)
+
+
+def button_center(index):
+ """Return a button center relative to the middle of the ring."""
+ return _BUTTON_CENTERS[index]
+
+
+def button_at(x, y, *, spread=1.0):
+ """Select only a painted button circle, leaving the gaps inert."""
+ if not math.isfinite(x) or not math.isfinite(y) or not math.isfinite(spread) or spread <= 0:
+ return None
+ for index, (cx, cy) in enumerate(_BUTTON_CENTERS):
+ if math.hypot(x - cx * spread, y - cy * spread) <= BUTTON_RADIUS:
+ return index
+ return None
+
+
def sector(x, y, deadzone=24):
if not math.isfinite(x) or not math.isfinite(y) or math.hypot(x, y) < deadzone:
return None
@@ -41,9 +65,9 @@ def motion(self, dx, dy):
self.selected = sector(self.x, self.y)
return self.selected
- def point(self, x, y):
+ def point(self, x, y, *, spread=1.0):
if self.visible:
- self.selected = sector(x, y, 76) if math.hypot(x, y) <= 205 else None
+ self.selected = button_at(x, y, spread=spread)
return self.selected
def release(self):
diff --git a/src/mx4_linux/ring_preview.py b/src/mx4_linux/ring_preview.py
new file mode 100644
index 0000000..48afe01
--- /dev/null
+++ b/src/mx4_linux/ring_preview.py
@@ -0,0 +1,102 @@
+"""Static, accessible ring assignment preview for the native action editor."""
+
+from .gtk_support import Gdk, Gtk
+from gi.repository import Pango
+from .ring_icons import action_icon
+from .ring_model import BUTTON_RADIUS, CENTER_RADIUS, button_center
+
+
+class RingPreview(Gtk.Fixed):
+ """Show the overlay's eight positions without executing assigned actions."""
+
+ def __init__(self, config, on_selected=None):
+ super().__init__(width_request=640, height_request=390, halign=Gtk.Align.CENTER)
+ self.on_selected = on_selected
+ self.selected = None
+ self.add_css_class("mx4-ring-preview")
+ self.update_property([Gtk.AccessibleProperty.LABEL], ["Actions Ring assignment preview"])
+ css = Gtk.CssProvider()
+ css.load_from_string("""
+ .mx4-ring-preview button.preview-ring-action {
+ background: #08090b; color: white; border: none;
+ border-radius: 9999px; padding: 0; box-shadow: none;
+ min-width: 52px; min-height: 52px;
+ }
+ .mx4-ring-preview button.preview-ring-action:hover {
+ background: #41434a;
+ }
+ .mx4-ring-preview button.preview-ring-action.selected {
+ background: #26cbbf; color: #12221f;
+ }
+ .mx4-ring-preview button.preview-ring-action:focus-visible {
+ outline: 2px solid @accent_color; outline-offset: 3px;
+ }
+ .mx4-ring-preview label.preview-ring-label {
+ background: @card_bg_color; color: @card_fg_color; border: 1px solid @borders;
+ border-radius: 6px; padding: 6px 8px;
+ }
+ .mx4-ring-preview label.preview-ring-label.selected {
+ border-color: #26cbbf;
+ }
+ .mx4-ring-preview label.preview-ring-center {
+ background: alpha(@window_fg_color, 0.08);
+ color: @window_fg_color;
+ border-radius: 9999px;
+ }
+ """)
+ Gtk.StyleContext.add_provider_for_display(Gdk.Display.get_default(), css,
+ Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
+ self.buttons, self.icons, self.labels = [], [], []
+ # Labels sit outside the circles, preserving the overlay's clockwise order.
+ label_positions = [(250, 0), (446, 88), (476, 172), (446, 286),
+ (250, 346), (54, 286), (24, 172), (54, 88)]
+ for index, (label_x, label_y) in enumerate(label_positions):
+ x, y = button_center(index)
+ button = Gtk.Button(width_request=BUTTON_RADIUS * 2, height_request=BUTTON_RADIUS * 2)
+ button.add_css_class("preview-ring-action")
+ icon = Gtk.Image(pixel_size=24)
+ button.set_child(icon)
+ button.connect("clicked", self._clicked, index)
+ self.put(button, 320 + x - BUTTON_RADIUS, 190 + y - BUTTON_RADIUS)
+ label = Gtk.Label(width_request=140, wrap=True, wrap_mode=Pango.WrapMode.WORD_CHAR,
+ max_width_chars=14, lines=2, ellipsize=Pango.EllipsizeMode.END,
+ justify=Gtk.Justification.CENTER)
+ label.add_css_class("preview-ring-label")
+ label.set_can_target(False)
+ self.put(label, label_x, label_y)
+ self.buttons.append(button)
+ self.icons.append(icon)
+ self.labels.append(label)
+ center = Gtk.Label(label="×", width_request=CENTER_RADIUS * 2, height_request=CENTER_RADIUS * 2)
+ center.add_css_class("preview-ring-center")
+ center.set_can_target(False)
+ center.update_state([Gtk.AccessibleState.HIDDEN], [True])
+ self.put(center, 320 - CENTER_RADIUS, 190 - CENTER_RADIUS)
+ self.update_config(config)
+
+ def update_config(self, config):
+ self.config = config
+ groups = config.get("ring_groups", {})
+ for index, action_id in enumerate(config["ring"]):
+ action = config["actions"][action_id]
+ label = action.get("label", action_id)
+ grouped = str(index) in groups
+ self.icons[index].set_from_icon_name(action_icon(action, grouped=grouped))
+ self.labels[index].set_text(label)
+ description = f"{index + 1}. {label}" + (". Action group" if grouped else "")
+ self.buttons[index].set_tooltip_text(description)
+ self.buttons[index].update_property([Gtk.AccessibleProperty.LABEL], [description])
+
+ def select(self, index):
+ self.selected = index
+ for position, (button, label) in enumerate(zip(self.buttons, self.labels)):
+ for widget in (button, label):
+ if position == index:
+ widget.add_css_class("selected")
+ else:
+ widget.remove_css_class("selected")
+
+ def _clicked(self, _button, index):
+ self.select(index)
+ if self.on_selected:
+ self.on_selected(index)
diff --git a/src/mx4_linux/wheel.py b/src/mx4_linux/wheel.py
new file mode 100644
index 0000000..8958568
--- /dev/null
+++ b/src/mx4_linux/wheel.py
@@ -0,0 +1,112 @@
+"""Interactive scroll-wheel illustration; no HID access or idle render loop."""
+
+import math
+from time import monotonic
+
+from .gtk_support import Gtk
+from .motion import WheelMotion
+
+
+class WheelPreview(Gtk.Box):
+ def __init__(self):
+ super().__init__(spacing=20)
+ self.add_css_class("card")
+ self.set_margin_bottom(4)
+ self.motion = WheelMotion()
+ self.free_spin = False
+ self.tick_id = 0
+ self.settings = Gtk.Settings.get_default()
+ self.canvas = Gtk.DrawingArea(content_width=128, content_height=156)
+ self.canvas.set_draw_func(self.draw)
+ self.canvas.update_property([Gtk.AccessibleProperty.LABEL], ["Interactive scroll wheel preview"])
+ scroll = Gtk.EventControllerScroll(flags=Gtk.EventControllerScrollFlags.VERTICAL)
+ scroll.connect("scroll", self.scroll)
+ self.canvas.add_controller(scroll)
+ self.append(self.canvas)
+ content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6,
+ valign=Gtk.Align.CENTER, hexpand=True,
+ margin_top=16, margin_bottom=16, margin_end=16)
+ title = Gtk.Label(label="Make every scroll feel right", xalign=0, wrap=True)
+ title.add_css_class("title-3")
+ content.append(title)
+ self.detail = Gtk.Label(xalign=0, wrap=True)
+ self.detail.add_css_class("dim-label")
+ content.append(self.detail)
+ self.try_button = Gtk.Button(label="Try the wheel", halign=Gtk.Align.START,
+ tooltip_text="Animate a preview without changing mouse settings")
+ self.try_button.add_css_class("pill")
+ self.try_button.connect("clicked", lambda *_: self.spin(2))
+ content.append(self.try_button)
+ self.append(content)
+ self.configure(False)
+ self.connect("unmap", self.stop)
+ self.settings.connect("notify::gtk-enable-animations", self.motion_changed)
+ self.motion_changed()
+
+ def configure(self, free_spin):
+ self.free_spin = free_spin
+ self.detail.set_text("Free spin · coast through long pages." if free_spin
+ else "Ratchet · precise steps, one line at a time.")
+
+ def motion_changed(self, *_):
+ enabled = self.settings.get_property("gtk-enable-animations")
+ self.try_button.set_sensitive(enabled)
+ if not enabled:
+ self.stop()
+
+ def spin(self, amount):
+ if not self.settings.get_property("gtk-enable-animations"):
+ return
+ self.motion.advance(monotonic(), free_spin=self.free_spin)
+ self.motion.impulse(amount)
+ if not self.tick_id:
+ self.tick_id = self.canvas.add_tick_callback(self.tick)
+
+ def scroll(self, _controller, _dx, dy):
+ if not self.settings.get_property("gtk-enable-animations"):
+ return False
+ self.spin(dy)
+ return True
+
+ def tick(self, _widget, _clock):
+ active = self.motion.advance(monotonic(), free_spin=self.free_spin)
+ self.canvas.queue_draw()
+ if not active:
+ self.tick_id = 0
+ return active
+
+ def stop(self, *_):
+ if self.tick_id:
+ self.canvas.remove_tick_callback(self.tick_id)
+ self.tick_id = 0
+ self.motion.stop()
+
+ def draw(self, _area, cr, width, height):
+ cx, cy = width / 2, height / 2
+ color = self.get_color()
+ # Shading and projected grooves suggest depth without a 3D renderer.
+ cr.set_source_rgba(color.red, color.green, color.blue, 0.07)
+ cr.arc(cx, cy, 48, 0, math.tau)
+ cr.fill()
+ cr.save()
+ cr.translate(cx, cy)
+ cr.scale(0.56, 1)
+ cr.arc(0, 0, 44, 0, math.tau)
+ cr.set_source_rgb(0.12, 0.14, 0.18)
+ cr.fill_preserve()
+ cr.set_source_rgba(color.red, color.green, color.blue, 0.25)
+ cr.set_line_width(2)
+ cr.stroke_preserve()
+ cr.clip()
+ cr.set_line_width(2)
+ for index in range(18):
+ angle = index * math.tau / 18 + self.motion.position
+ depth = math.cos(angle)
+ if depth < 0:
+ continue
+ y = math.sin(angle) * 42
+ cr.move_to(-34, y)
+ cr.line_to(34, y)
+ cr.set_source_rgba(0.74, 0.79, 0.88, 0.25 + 0.65 * depth)
+ cr.stroke()
+ cr.restore()
diff --git a/tests/npm/launcher.test.js b/tests/npm/launcher.test.js
new file mode 100644
index 0000000..a625002
--- /dev/null
+++ b/tests/npm/launcher.test.js
@@ -0,0 +1,108 @@
+import assert from 'node:assert/strict';
+import { spawn, spawnSync } from 'node:child_process';
+import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { test } from 'node:test';
+import { setTimeout } from 'node:timers/promises';
+
+const root = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
+
+function fixture(t) {
+ const directory = mkdtempSync(join(tmpdir(), 'mx4 launcher '));
+ t.after(() => rmSync(directory, { recursive: true, force: true }));
+ const packageRoot = join(directory, 'package');
+ mkdirSync(join(packageRoot, 'bin'), { recursive: true });
+ for (const path of ['bin/mx4-linux.js', 'package.json', 'pyproject.toml', 'README.md', 'LICENSE']) copyFileSync(join(root, path), join(packageRoot, path));
+ mkdirSync(join(packageRoot, 'src', 'mx4_linux'), { recursive: true });
+ copyFileSync(join(root, 'src', 'mx4_linux', '__init__.py'), join(packageRoot, 'src', 'mx4_linux', '__init__.py'));
+ const log = join(directory, 'python.jsonl');
+ const python = join(directory, 'system python');
+ writeFileSync(python, `#!/usr/bin/env node
+const fs = require('node:fs');
+const path = require('node:path');
+const args = process.argv.slice(2);
+fs.appendFileSync(process.env.TEST_LOG, JSON.stringify({args, source: process.env.PYTHONPATH}) + '\\n');
+if (args[0] === '-m' && args[1] === 'venv') {
+ const bin = path.join(args.at(-1), 'bin');
+ fs.mkdirSync(bin, {recursive: true});
+ fs.copyFileSync(__filename, path.join(bin, 'python'));
+ fs.chmodSync(path.join(bin, 'python'), 0o755);
+}
+if (process.env.FAIL_PIP && args[1] === 'pip') process.exit(9);
+if (process.env.TEST_WAIT && args[1] === 'mx4_linux') {
+ fs.writeFileSync(process.env.TEST_WAIT, 'ready');
+ process.on('SIGTERM', () => { fs.writeFileSync(process.env.TEST_WAIT, 'stopped'); process.exit(0); });
+ setInterval(() => {}, 1000);
+} else process.exit(Number(process.env.TEST_EXIT || 0));
+`);
+ chmodSync(python, 0o755);
+ const env = { ...process.env, XDG_DATA_HOME: join(directory, 'data'), TEST_LOG: log };
+ delete env.MX4_LINUX_PYTHON;
+ delete env.PYTHON;
+ const launcher = join(packageRoot, 'bin', 'mx4-linux.js');
+ const version = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')).version;
+ return {
+ directory, packageRoot, python, launcher, env, version,
+ ready: join(env.XDG_DATA_HOME, 'mx4-linux', 'runtime', version, '.ready'),
+ logs: () => readFileSync(log, 'utf8').trim().split('\n').map(line => JSON.parse(line)),
+ run: (args = [], extra = {}) => spawnSync(process.execPath, [launcher, ...args], { env: { ...env, ...extra }, encoding: 'utf8' }),
+ };
+}
+
+test('version and setup help work before installing Python dependencies', t => {
+ const f = fixture(t);
+ assert.equal(f.run(['--version']).stdout, `mx4-linux ${f.version}\n`);
+ assert.match(f.run(['--help']).stdout, /mx4-linux setup/);
+ const result = f.run();
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /setup first/);
+ assert.ok(!existsSync(f.ready));
+});
+
+test('forwards argument boundaries, bundled source, and exit codes without a shell', t => {
+ const f = fixture(t);
+ const args = ['actions', 'run', 'literal $(touch sentinel); id with spaces'];
+ const result = f.run(args, { MX4_LINUX_PYTHON: f.python, TEST_EXIT: '7', PYTHONPATH: '/existing/path' });
+ assert.equal(result.status, 7);
+ assert.deepEqual(f.logs()[0].args, ['-m', 'mx4_linux', ...args]);
+ assert.equal(f.logs()[0].source, `${join(f.packageRoot, 'src')}:/existing/path`);
+});
+
+test('setup creates a per-user environment and only marks successful installation ready', t => {
+ const f = fixture(t);
+ const setup = f.run(['setup'], { PYTHON: f.python });
+ assert.equal(setup.status, 0, setup.stderr);
+ assert.ok(existsSync(f.ready));
+ assert.deepEqual(f.logs()[1].args.slice(0, 3), ['-m', 'venv', '--system-site-packages']);
+ assert.deepEqual(f.logs()[2].args.slice(0, 5), ['-m', 'pip', 'install', '--disable-pip-version-check', '--upgrade']);
+ assert.notEqual(f.logs()[2].args.at(-1), f.packageRoot);
+ assert.ok(!existsSync(f.logs()[2].args.at(-1)), 'temporary build source should be removed');
+ assert.equal(f.run(['doctor']).status, 0);
+ assert.deepEqual(f.logs().at(-1).args, ['-m', 'mx4_linux', 'doctor']);
+ assert.equal(f.run(['setup'], { PYTHON: f.python, FAIL_PIP: '1' }).status, 1);
+ assert.ok(!existsSync(f.ready));
+ assert.equal(f.run(['doctor']).status, 1);
+});
+
+test('setup rejects unsupported arguments and reports a missing Python executable', t => {
+ const f = fixture(t);
+ assert.match(f.run(['setup', '--unknown']).stderr, /Usage:/);
+ const result = f.run(['doctor'], { MX4_LINUX_PYTHON: join(f.directory, 'absent') });
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /Cannot start Python/);
+});
+
+test('termination reaches Python so the listener can clean up', { timeout: 5000 }, async t => {
+ const f = fixture(t);
+ const marker = join(f.directory, 'state');
+ const child = spawn(process.execPath, [f.launcher], { env: { ...f.env, MX4_LINUX_PYTHON: f.python, TEST_WAIT: marker }, stdio: 'pipe' });
+ t.after(() => { if (child.exitCode === null) child.kill('SIGKILL'); });
+ const exited = new Promise(resolve => child.once('exit', (code, signal) => resolve({ code, signal })));
+ for (let attempt = 0; !existsSync(marker) && attempt < 100; attempt++) await setTimeout(20);
+ assert.ok(existsSync(marker), 'Python child did not start');
+ child.kill('SIGTERM');
+ assert.deepEqual(await exited, { code: 0, signal: null });
+ assert.equal(readFileSync(marker, 'utf8'), 'stopped');
+});
diff --git a/tests/test_actions.py b/tests/test_actions.py
index 93d5750..4d8971a 100644
--- a/tests/test_actions.py
+++ b/tests/test_actions.py
@@ -1,6 +1,4 @@
-from copy import deepcopy
import json
-from pathlib import Path
from types import SimpleNamespace
import pytest
@@ -29,6 +27,41 @@ def test_defaults_are_fresh_valid_and_have_eight_ring_actions():
assert len(default_config()["actions"]["copy"]["steps"]) == 1
+def test_optional_groups_round_trip_without_changing_parent_execution(tmp_path):
+ config = default_config()
+ config["ring_groups"] = {"2": ["copy", "paste", "undo"], "7": ["overview"]}
+ store = DesktopConfigStore(tmp_path / "desktop.json")
+ store.save(config)
+ assert store.read() == config
+ assert DesktopActions(config, dry_run=True).execute(config["ring"][2])["action_id"] == "terminal"
+
+
+def test_legacy_configuration_validation_keeps_optional_groups_absent():
+ config = default_config()
+ assert "ring_groups" not in config
+ assert validate_config(config) is config
+ assert "ring_groups" not in config
+
+
+def test_groups_accept_all_positions_and_six_distinct_children():
+ config = default_config()
+ config["ring_groups"] = {str(index): config["ring"][:6] for index in range(8)}
+ assert validate_config(config) is config
+
+
+@pytest.mark.parametrize("groups", [
+ None, [], "groups", {0: ["copy"]}, {True: ["copy"]}, {"8": ["copy"]},
+ {"-1": ["copy"]}, {"00": ["copy"]}, {"1.0": ["copy"]},
+ {"0": []}, {"0": ["copy"] * 7}, {"0": ("copy",)}, {"0": "copy"},
+ {"0": ["missing"]}, {"0": [None]}, {"0": [{}]}, {"0": ["copy", "copy"]},
+])
+def test_invalid_action_groups_rejected(groups):
+ config = default_config()
+ config["ring_groups"] = groups
+ with pytest.raises(RuntimeError, match="Invalid desktop configuration: ring[_ ]group"):
+ validate_config(config)
+
+
def test_terminal_environment_is_split_into_literal_argv(monkeypatch):
monkeypatch.setenv("TERMINAL", 'kitty --title "hello $(touch nope)"')
monkeypatch.setattr(actions.shutil, "which", lambda program: "/usr/bin/" + program)
diff --git a/tests/test_desktop_controller.py b/tests/test_desktop_controller.py
index 1ce6173..d9a3263 100644
--- a/tests/test_desktop_controller.py
+++ b/tests/test_desktop_controller.py
@@ -1,17 +1,23 @@
"""UI coordination regressions without a display or a physical mouse."""
+from collections import deque
+import threading
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
from mx4_linux.desktop import DesktopController
+from mx4_linux.ring_model import RingState
@pytest.fixture
def controller():
value = DesktopController.__new__(DesktopController)
value.closed = False
+ value._event_lock = threading.Lock()
+ value._event_queue = deque()
+ value._events_pending = False
value._open_token = value._dispatch_token = 0
value.opening = False
value._pending_motion = [0, 0]
@@ -86,3 +92,61 @@ def test_selection_dispatch_preserves_original_focus_target(controller, monkeypa
controller.target = {"window_id": 99}
scheduled[0]()
controller.execute.assert_called_once_with("copy", target={"window_id": 10}, preview=False)
+
+
+def test_motion_burst_uses_one_ui_callback_and_preserves_release_order(controller, monkeypatch):
+ scheduled = []
+ monkeypatch.setattr("mx4_linux.desktop.GLib.idle_add", lambda fn: scheduled.append(fn))
+ controller.event = Mock()
+ controller.queue_event({"type": "button", "control": 416, "pressed": True, "session_id": 2})
+ for _ in range(1000):
+ controller.queue_event({"type": "motion", "dx": 2, "dy": -1, "session_id": 2})
+ controller.queue_event({"type": "button", "control": 416, "pressed": False, "session_id": 2})
+ assert len(scheduled) == 1
+ scheduled.pop()()
+ events = [call.args[0] for call in controller.event.call_args_list]
+ assert [event["type"] for event in events] == ["button", *["motion"] * 1000, "button"]
+ assert all(event == {"type": "motion", "dx": 2, "dy": -1, "session_id": 2} for event in events[1:-1])
+ assert not events[-1]["pressed"]
+
+
+def test_batched_motion_preserves_radius_clamping_when_direction_reverses(controller, monkeypatch):
+ scheduled = []
+ monkeypatch.setattr("mx4_linux.desktop.GLib.idle_add", lambda fn: scheduled.append(fn))
+ state = RingState()
+ state.open(held=True)
+ controller.ring.motion = state.motion
+ controller.queue_event({"type": "motion", "dx": 1000, "dy": 0, "session_id": 2})
+ controller.queue_event({"type": "motion", "dx": -1000, "dy": 0, "session_id": 2})
+ scheduled.pop()()
+ assert state.x == -155
+ assert state.selected == 6
+
+
+def test_motion_batch_keeps_session_boundaries_and_invalid_values(controller, monkeypatch):
+ monkeypatch.setattr("mx4_linux.desktop.GLib.idle_add", lambda fn: None)
+ controller.event = Mock()
+ events = [{"type": "motion", "dx": 2, "dy": 1, "session_id": 1},
+ {"type": "motion", "dx": 2, "dy": 1, "session_id": 2},
+ {"type": "motion", "dx": "bad", "dy": 1, "session_id": 2}]
+ for event in events:
+ controller.queue_event(event)
+ controller.flush_events()
+ assert [call.args[0] for call in controller.event.call_args_list] == events
+
+
+def test_events_arriving_during_flush_get_another_callback(controller, monkeypatch):
+ scheduled, seen = [], []
+ monkeypatch.setattr("mx4_linux.desktop.GLib.idle_add", lambda fn: scheduled.append(fn))
+
+ def receive(event):
+ seen.append(event["type"])
+ if event["type"] == "ready":
+ controller.queue_event({"type": "stopped"})
+
+ controller.event = receive
+ controller.queue_event({"type": "ready"})
+ scheduled.pop(0)()
+ assert seen == ["ready"]
+ scheduled.pop(0)()
+ assert seen == ["ready", "stopped"]
diff --git a/tests/test_desktop_editor.py b/tests/test_desktop_editor.py
new file mode 100644
index 0000000..5ff86c9
--- /dev/null
+++ b/tests/test_desktop_editor.py
@@ -0,0 +1,296 @@
+"""Keep the native editor's form and JSON drafts lossless and side-effect free."""
+
+from copy import deepcopy
+import json
+import threading
+from time import monotonic, sleep
+
+import pytest
+
+gi = pytest.importorskip("gi")
+try:
+ gi.require_version("Gtk", "4.0")
+ gi.require_version("Adw", "1")
+except ValueError as exc:
+ pytest.skip(str(exc), allow_module_level=True)
+
+from gi.repository import Adw, GLib, Gtk
+
+from mx4_linux.actions import default_config, validate_config
+from mx4_linux.desktop_editor import DesktopEditor, _DraftError, _step_values, _values_step
+
+
+@pytest.mark.parametrize("step", [
+ {"type": "shortcut", "keys": ["CTRL", "SHIFT", "S"]},
+ {"type": "command", "argv": ["kitty", "--title", "Hello $(touch nope)", ""]},
+ {"type": "text", "text": "Hello\n世界"},
+ {"type": "delay", "milliseconds": 150},
+ {"type": "niri", "action": "focus-workspace", "args": ["work space"]},
+])
+def test_step_fields_preserve_values_and_literal_arguments(step):
+ assert _values_step(_step_values(step)) == step
+
+
+@pytest.fixture
+def editor(request):
+ if not Gtk.init_check():
+ pytest.skip("A graphical session is needed for native editor interaction tests")
+ Adw.init()
+
+ class Store:
+ saved = None
+
+ def read(self):
+ return deepcopy(getattr(request, "param", default_config()))
+
+ def save(self, value):
+ self.saved = deepcopy(validate_config(value))
+
+ store = Store()
+ window = DesktopEditor(None, store, lambda: None)
+ yield window
+ iterate_until(lambda: not window.saving)
+ window.allow_close = True
+ window.destroy()
+
+
+def iterate_until(predicate, timeout=2):
+ context = GLib.MainContext.default()
+ deadline = monotonic() + timeout
+ while not predicate() and monotonic() < deadline:
+ while context.pending():
+ context.iteration(False)
+ sleep(0.001)
+ assert predicate(), "GTK callback did not complete in time"
+
+
+def select(editor, action_id):
+ editor.action_choice.set_selected(editor.choice_ids.index(action_id))
+
+
+def entry_in(widget, title):
+ child = widget.get_first_child()
+ while child:
+ if isinstance(child, Adw.EntryRow) and child.get_title() == title:
+ return child
+ nested = entry_in(child, title)
+ if nested:
+ return nested
+ child = child.get_next_sibling()
+ return None
+
+
+def test_incomplete_form_survives_routine_switch_without_saving(editor):
+ select(editor, "terminal")
+ entry_in(editor.steps_group, "Application and arguments").set_text('kitty --title "incomplete')
+ assert editor.step_error.get_visible()
+ select(editor, "copy")
+ select(editor, "terminal")
+ assert entry_in(editor.steps_group, "Application and arguments").get_text() == 'kitty --title "incomplete'
+ with pytest.raises(_DraftError, match="quotation marks"):
+ editor._candidate()
+ assert editor.store.saved is None
+
+
+def test_json_draft_survives_switch_and_returns_to_builder(editor):
+ select(editor, "copy")
+ editor.json_toggle.set_active(True)
+ editor.steps_buffer.set_text("[{")
+ editor.json_toggle.set_active(False)
+ assert editor.json_toggle.get_active()
+ select(editor, "paste")
+ select(editor, "copy")
+ assert editor.json_toggle.get_active()
+ assert editor.drafts["copy"]["steps_text"] == "[{"
+ steps = [{"type": "text", "text": "First\nSecond"}]
+ editor.steps_buffer.set_text(json.dumps(steps))
+ editor.json_toggle.set_active(False)
+ assert not editor.json_toggle.get_active()
+ assert editor._candidate()["actions"]["copy"]["steps"] == steps
+
+
+def test_builder_add_reorder_remove_and_rename_preserves_assignments(editor):
+ select(editor, "copy")
+ editor.step_choice.set_selected(3) # Wait
+ editor._add_step()
+ editor._move_step(None, 1, -1)
+ assert editor._candidate()["actions"]["copy"]["steps"][0] == {"type": "delay", "milliseconds": 150}
+ editor._move_step(None, 0, 0)
+ editor.config["button_bindings"]["83"] = "copy"
+ editor.id_entry.set_text("copy-selection")
+ candidate = validate_config(editor._candidate())
+ assert candidate["ring"][5] == "copy-selection"
+ assert candidate["button_bindings"]["83"] == "copy-selection"
+ assert candidate["actions"]["copy-selection"]["steps"] == [{"type": "shortcut", "keys": ["CTRL", "C"]}]
+ assert editor.save_button.get_sensitive()
+ editor._save()
+ iterate_until(lambda: not editor.saving)
+ assert editor.store.saved == candidate
+
+
+def test_legacy_editor_keeps_groups_optional_and_collapsed(editor):
+ assert not editor.groups_expander.get_expanded()
+ assert "ring_groups" not in editor._candidate()
+ assert all(choice.get_selected() == 0 for _row, choices in editor.group_choices for choice in choices)
+
+
+def test_ring_preview_tracks_draft_labels_and_new_assignments(editor):
+ select(editor, "copy")
+ editor.name_entry.set_text("Copy selection")
+ assert editor.ring_preview.labels[5].get_text() == "Copy selection"
+ editor._add_routine()
+ action_id = editor.selected_id
+ editor.name_entry.set_text("My shortcut")
+ editor.ring_choices[0].set_selected(editor.choice_ids.index(action_id))
+ assert editor.ring_preview.labels[0].get_text() == "My shortcut"
+ assert editor.ring_preview.selected == 0
+ assert editor.store.saved is None
+
+
+def test_groups_follow_order_and_renames_without_running_or_saving(editor):
+ _row, choices = editor.group_choices[2]
+ choices[0].set_selected(editor.choice_ids.index("copy") + 1)
+ choices[2].set_selected(editor.choice_ids.index("paste") + 1)
+ assert editor.config["ring_groups"] == {"2": ["copy", "paste"]}
+ select(editor, "copy")
+ editor.name_entry.set_text("Copy selection")
+ editor.id_entry.set_text("copy-selection")
+ candidate = validate_config(editor._candidate())
+ assert candidate["ring_groups"] == {"2": ["copy-selection", "paste"]}
+ assert editor.config["ring_groups"] == {"2": ["copy", "paste"]}
+ assert editor.store.saved is None
+ editor._save()
+ iterate_until(lambda: not editor.saving)
+ assert editor.store.saved == candidate
+
+
+def test_duplicate_group_choice_restores_previous_selection(editor):
+ _row, choices = editor.group_choices[0]
+ selected = editor.choice_ids.index("copy") + 1
+ choices[0].set_selected(selected)
+ choices[1].set_selected(selected)
+ assert editor.config["ring_groups"] == {"0": ["copy"]}
+ assert choices[0].get_selected() == selected and choices[1].get_selected() == 0
+ assert editor.error.get_visible() and "only once" in editor.error.get_text()
+ assert validate_config(editor._candidate())
+
+
+def test_removing_last_group_choice_restores_direct_action(editor):
+ _row, choices = editor.group_choices[0]
+ choices[0].set_selected(editor.choice_ids.index("copy") + 1)
+ choices[0].set_selected(0)
+ assert editor._candidate()["ring_groups"] == {}
+ assert editor.config["ring"][0] == "overview"
+
+
+def test_deleting_routine_removes_group_references_and_empty_groups(editor):
+ editor.config["ring_groups"] = {"0": ["copy", "paste"], "1": ["copy"]}
+ editor.config["button_bindings"] = {"83": "copy"}
+ select(editor, "copy")
+ editor._delete_selected()
+ dialog = next(window for window in Gtk.Window.list_toplevels()
+ if isinstance(window, Adw.MessageDialog) and window.get_transient_for() is editor)
+ dialog.response("delete")
+ candidate = validate_config(editor._candidate())
+ assert candidate["ring_groups"] == {"0": ["paste"]}
+ assert "copy" not in candidate["actions"]
+ assert "copy" not in candidate["ring"]
+ assert candidate["button_bindings"] == {}
+ assert editor.store.saved is None
+
+
+@pytest.mark.parametrize("editor", [{**default_config(), "ring_groups": {"7": ["paste", "copy"]}}], indirect=True)
+def test_saved_groups_load_without_changing_order_or_dirtying_editor(editor):
+ assert not editor.dirty
+ _row, choices = editor.group_choices[7]
+ assert choices[0].get_selected() == editor.choice_ids.index("paste") + 1
+ assert choices[1].get_selected() == editor.choice_ids.index("copy") + 1
+ assert editor._candidate()["ring_groups"] == {"7": ["paste", "copy"]}
+
+
+def test_last_step_can_be_replaced_but_empty_routine_cannot_save(editor):
+ select(editor, "copy")
+ editor._move_step(None, 0, 0)
+ assert editor.step_error.get_visible()
+ editor._save()
+ assert editor.store.saved is None
+ assert editor.error.get_visible()
+ editor._add_step()
+ assert not editor.step_error.get_visible()
+ assert validate_config(editor._candidate())
+
+
+def test_blocked_save_keeps_gtk_responsive_and_prevents_edits_or_close(editor, monkeypatch):
+ select(editor, "copy")
+ editor.name_entry.set_text("Copy selection")
+ candidate, draft = editor._candidate(), deepcopy(editor.drafts)
+ entered, release, pulse = threading.Event(), threading.Event(), threading.Event()
+ main_thread = threading.get_ident()
+ save_threads, notifications = [], []
+ persist = editor.store.save
+
+ def blocked_save(value):
+ save_threads.append(threading.get_ident())
+ entered.set()
+ if not release.wait(5):
+ raise RuntimeError("Save was not released by the test")
+ persist(value)
+
+ monkeypatch.setattr(editor.store, "save", blocked_save)
+ editor.on_saved = lambda: notifications.append(threading.get_ident())
+ try:
+ editor._save()
+ assert entered.wait(1)
+ assert editor.saving and editor.dirty
+ assert not editor.stack.get_sensitive()
+ assert not editor.save_button.get_sensitive()
+ assert editor._close_requested()
+ assert editor.close_dialog is None
+ editor._save()
+ GLib.idle_add(lambda: (pulse.set(), GLib.SOURCE_REMOVE)[1])
+ iterate_until(pulse.is_set)
+ assert editor.store.saved is None
+ assert editor.drafts == draft
+ assert len(save_threads) == 1 and save_threads[0] != main_thread
+ finally:
+ release.set()
+ iterate_until(lambda: not editor.saving)
+ assert editor.store.saved == candidate
+ assert notifications == [main_thread]
+ assert editor.allow_close and not editor.dirty
+
+
+def test_failed_background_save_keeps_draft_and_allows_retry(editor, monkeypatch):
+ select(editor, "copy")
+ editor.name_entry.set_text("Copy selection")
+ candidate, draft = editor._candidate(), deepcopy(editor.drafts)
+ persist = editor.store.save
+ notifications = []
+ editor.on_saved = lambda: notifications.append(True)
+
+ def failed_save(_value):
+ raise OSError("Disk is full")
+
+ monkeypatch.setattr(editor.store, "save", failed_save)
+ editor._save()
+ iterate_until(lambda: not editor.saving)
+ assert editor.dirty and not editor.allow_close
+ assert editor.stack.get_sensitive() and editor.save_button.get_sensitive()
+ assert editor.error.get_visible() and "Disk is full" in editor.error.get_text()
+ assert editor.drafts == draft
+ assert not notifications
+ monkeypatch.setattr(editor.store, "save", persist)
+ editor._save()
+ iterate_until(lambda: not editor.saving)
+ assert editor.store.saved == candidate
+ assert notifications == [True]
+
+
+def test_clearing_group_entry_compacts_the_visible_order_to_match_shortcuts(editor):
+ _row, choices = editor.group_choices[2]
+ choices[0].set_selected(editor.choice_ids.index("copy") + 1)
+ choices[1].set_selected(editor.choice_ids.index("paste") + 1)
+ choices[0].set_selected(0)
+ assert editor.config["ring_groups"]["2"] == ["paste"]
+ assert choices[0].get_selected() == editor.choice_ids.index("paste") + 1
+ assert all(choice.get_selected() == 0 for choice in choices[1:])
diff --git a/tests/test_device_worker.py b/tests/test_device_worker.py
index 801c896..326d5f4 100644
--- a/tests/test_device_worker.py
+++ b/tests/test_device_worker.py
@@ -136,6 +136,22 @@ def create_receiver(low_level, _info):
class WorkerTests(unittest.TestCase):
+ def test_isolation_bounds_paired_node_wait_and_restores_on_failure(self):
+ api, _, _ = fake_api()
+ original = api.base.find_paired_node = Mock(return_value="/dev/paired")
+ with self.assertRaisesRegex(RuntimeError, "injected failure"):
+ with worker._isolated_solaar(api):
+ self.assertEqual(api.base.find_paired_node("/dev/receiver", 2, 1), "/dev/paired")
+ original.assert_called_once_with("/dev/receiver", 2, .01)
+ scoped = api.base.find_paired_node
+ with worker._isolated_solaar(api):
+ self.assertEqual(api.base.find_paired_node("/dev/receiver", 2, 1), "/dev/paired")
+ self.assertIs(api.base.find_paired_node, scoped)
+ api.base.find_paired_node("/dev/receiver", 2, 0)
+ self.assertEqual(original.call_args.args[-1], 0)
+ raise RuntimeError("injected failure")
+ self.assertIs(api.base.find_paired_node, original)
+
def test_isolation_uses_distinct_software_id_and_restores_after_error(self):
api, _, _ = fake_api()
api.base.SOLAAR_SOFTWARE_ID = 0x0B
@@ -265,6 +281,102 @@ def test_range_write_disables_save_and_confirms_live_readback(self):
self.assertEqual(setting.reads, [False, False])
dev.close.assert_called_once()
+ def test_single_setting_write_does_not_build_unrelated_capabilities(self):
+ settings = [FakeSetting(name) for name in worker.ALLOWED_SETTINGS]
+ api, _, _ = fake_api(settings)
+ self.assertTrue(self.request_write(api, "haptic-level", 75)["ok"])
+ checked = [call.args[1].name for call in api.settings_templates.check_feature.call_args_list]
+ self.assertEqual(checked, ["haptic-level"])
+ self.assertTrue(all(not setting.reads for setting in settings if setting.name != "haptic-level"))
+
+ def test_wheel_write_returns_related_live_values_without_a_full_scan(self):
+ shift, ratchet, unrelated = FakeSetting(), FakeSetting("scroll-ratchet", value=2), FakeSetting("haptic-level")
+ api, _, _ = fake_api([shift, ratchet, unrelated])
+ self.assertEqual(self.request_write(api, "smart-shift", 25), {
+ "ok": True, "value": 25, "values": {"scroll-ratchet": 2}})
+ self.assertEqual(ratchet.reads, [False])
+ self.assertFalse(unrelated.reads)
+ self.assertFalse(ratchet.writes)
+
+ def test_failed_related_wheel_read_requires_refresh_without_failing_confirmed_write(self):
+ for result in (None, RuntimeError("Related wheel read timed out")):
+ with self.subTest(result=result):
+ shift, ratchet = FakeSetting(), FakeSetting("scroll-ratchet", value=2)
+ if isinstance(result, Exception):
+ ratchet.read = Mock(side_effect=result)
+ else:
+ ratchet.read = Mock(return_value=result)
+ api, _, _ = fake_api([shift, ratchet])
+ self.assertEqual(self.request_write(api, "smart-shift", 25), {
+ "ok": True, "value": 25, "refresh_required": True})
+ self.assertEqual(shift.writes, [(25, False)])
+ self.assertEqual(shift.reads, [False, False])
+
+ def test_failed_wheel_dependency_discovery_requires_refresh_after_confirmed_write(self):
+ shift, ratchet = FakeSetting(), FakeSetting("scroll-ratchet", value=2)
+ api, _, _ = fake_api([shift, ratchet])
+
+ def check(_dev, template):
+ if template.name == "scroll-ratchet":
+ raise RuntimeError("Wheel capability query timed out")
+ return template.instance
+
+ api.settings_templates.check_feature.side_effect = check
+ self.assertEqual(self.request_write(api, "smart-shift", 25), {
+ "ok": True, "value": 25, "refresh_required": True})
+ self.assertEqual(shift.writes, [(25, False)])
+
+ def test_torque_write_keeps_the_solaar_wheel_mode_dependency(self):
+ torque, ratchet = FakeSetting("scroll-ratchet-torque"), FakeSetting("scroll-ratchet", value=2)
+ api, dev, _ = fake_api([torque, ratchet])
+ original_write = torque.write
+
+ def write(value, save=True):
+ self.assertEqual([setting.name for setting in dev._settings], ["scroll-ratchet-torque", "scroll-ratchet"])
+ return original_write(value, save=save)
+
+ torque.write = write
+ self.assertEqual(self.request_write(api, torque.name, 75), {
+ "ok": True, "value": 75, "values": {"scroll-ratchet": 2}})
+ self.assertFalse(ratchet.writes)
+
+ def test_targeted_receiver_lookup_skips_unrelated_paths_and_slots(self):
+ setting = FakeSetting()
+ devices = [FakeDevice(number=1), FakeDevice(number=2)]
+ api, _, info = fake_api([setting], devices, receiver=True)
+ api.base.receivers_and_devices.return_value = [SimpleNamespace(path="/dev/other", isDevice=False), info]
+ original = api.receiver.create_receiver.side_effect
+ slots = []
+
+ def create(base, selected):
+ self.assertIs(selected, info)
+ owner = original(base, selected)
+
+ class Receiver:
+ close = owner.close
+
+ def __getitem__(self, slot):
+ slots.append(slot)
+ return owner[slot]
+
+ return Receiver()
+
+ api.receiver.create_receiver.side_effect = create
+ response = worker.handle_request({"op": "write", "device_id": worker._device_id(info.path, 2),
+ "setting": setting.name, "value": 75}, api)
+ self.assertTrue(response["ok"])
+ self.assertEqual(slots, [2])
+ devices[0].ping.assert_not_called()
+ devices[1].ping.assert_called_once()
+
+ def test_target_ids_cannot_open_paths_outside_device_enumeration(self):
+ for target in ('["/dev/arbitrary",255]', '"ab"', 'null', '{}', '["/dev/hidraw-test",true]'):
+ api, _, _ = fake_api([FakeSetting()])
+ response = worker.handle_request({"op": "write", "device_id": target,
+ "setting": "smart-shift", "value": 25}, api)
+ self.assertFalse(response["ok"])
+ api.device.create_device.assert_not_called()
+
def test_invalid_range_values_never_write(self):
for value in (True, False, -1, 101, 40.0, "40", None):
with self.subTest(value=value):
diff --git a/tests/test_gui.py b/tests/test_gui.py
new file mode 100644
index 0000000..54254be
--- /dev/null
+++ b/tests/test_gui.py
@@ -0,0 +1,128 @@
+"""Readback updates preserve native controls and avoid redundant HID discovery."""
+
+from time import monotonic, sleep
+from unittest.mock import Mock
+from uuid import uuid4
+
+import pytest
+
+pytest.importorskip("gi")
+from mx4_linux.gtk_support import Adw, Gio, GLib, Gtk
+from mx4_linux.backend import BackendError
+from mx4_linux.gui import ControlWindow
+
+
+def settle(window):
+ context = GLib.MainContext.default()
+ deadline = monotonic() + 3
+ while window.busy and monotonic() < deadline:
+ while context.pending():
+ context.iteration(False)
+ sleep(0.001)
+ assert not window.busy
+
+
+@pytest.fixture
+def window(tmp_path, monkeypatch):
+ if not Gtk.init_check():
+ pytest.skip("A graphical session is needed for native control tests")
+ Adw.init()
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
+ app = Adw.Application(application_id=f"io.github.mx4linux.GuiTests.t{uuid4().hex}", flags=Gio.ApplicationFlags.NON_UNIQUE)
+ app.register(None)
+ window = ControlWindow(app, demo=True)
+ settle(window)
+ window.backend.scan = Mock(side_effect=AssertionError("Editing must not trigger another scan"))
+ yield window
+ window.close()
+
+
+def setting(window, name):
+ return next(item for item in window.current["settings"] if item["name"] == name)
+
+
+def test_confirmed_edit_updates_existing_widget_without_scan(window):
+ dropdown = window.setting_widgets[("dpi", None)][0]
+ dropdown.set_selected(3)
+ settle(window)
+ assert setting(window, "dpi")["value"] == 1600
+ assert window.setting_widgets[("dpi", None)][0] is dropdown
+ window.backend.scan.assert_not_called()
+
+
+def test_failed_toggle_refreshes_uncertain_hardware_state_without_retry(window):
+ window.backend.write = Mock(side_effect=BackendError("Mouse disconnected"))
+ window.backend.scan = Mock(return_value={"ok": True, "devices": [window.backend.device], "diagnostics": []})
+ switch = window.setting_widgets[("hires-smooth-invert", None)][0]
+ switch.set_active(True)
+ settle(window)
+ assert not window.setting_widgets[("hires-smooth-invert", None)][0].get_active()
+ assert setting(window, "hires-smooth-invert")["value"] is False
+ assert "Mouse disconnected" in window.status.get_text()
+ window.backend.write.assert_called_once()
+ window.backend.scan.assert_called_once()
+
+
+def test_related_wheel_readback_updates_controls_without_another_write(window):
+ window.backend.write = Mock(return_value={"ok": True, "value": 1, "values": {"smart-shift": 0}})
+ window.setting_widgets[("scroll-ratchet", None)][0].set_selected(0)
+ settle(window)
+ assert setting(window, "smart-shift")["value"] == 0
+ assert window.setting_widgets[("smart-shift", None)][0].get_value_as_int() == 0
+ assert window.wheel.free_spin
+ window.backend.write.assert_called_once()
+ window.backend.scan.assert_not_called()
+
+
+def test_save_profile_uses_confirmed_settings_without_scan(window):
+ entry = None
+ def find(widget):
+ nonlocal entry
+ if isinstance(widget, Gtk.Entry):
+ entry = widget
+ child = widget.get_first_child()
+ while child:
+ find(child)
+ child = child.get_next_sibling()
+ find(window.profile_controls)
+ entry.set_text("Work")
+ entry.emit("activate")
+ settle(window)
+ profile = window.store.read()["Work"]
+ assert profile["settings"]["dpi"] == 1000
+ assert "haptic-play" not in profile["settings"]
+ window.backend.scan.assert_not_called()
+
+
+def test_hardware_job_keeps_action_cancellation_available(window):
+ window.desktop.action_busy = True
+ window.change(setting(window, "haptic-level"), 60)
+ assert window.cancel_action.is_sensitive()
+ assert not window.controls.is_sensitive()
+ settle(window)
+
+
+def test_unchanged_value_does_not_write(window):
+ window.backend.write = Mock()
+ window.change(setting(window, "dpi"), 1000)
+ assert not window.busy
+ window.backend.write.assert_not_called()
+
+
+def test_failed_refresh_after_uncertain_write_clears_stale_profile_state(window):
+ window.backend.scan = Mock(side_effect=BackendError("Mouse still unavailable"))
+ window.refresh_after_write("Profile partly applied")
+ settle(window)
+ assert window.current is None
+ assert window.controls.get_first_child() is None
+ assert not window.wheel.get_visible()
+ assert not window.desktop_toggle.get_sensitive()
+
+
+def test_uncertain_related_readback_refreshes_before_saving_profiles(window):
+ window.backend.write = Mock(return_value={"ok": True, "value": 1, "refresh_required": True})
+ window.backend.scan = Mock(side_effect=BackendError("Related settings unavailable"))
+ window.change(setting(window, "scroll-ratchet"), 1)
+ settle(window)
+ window.backend.scan.assert_called_once()
+ assert window.current is None
diff --git a/tests/test_motion.py b/tests/test_motion.py
new file mode 100644
index 0000000..fa6119e
--- /dev/null
+++ b/tests/test_motion.py
@@ -0,0 +1,55 @@
+import pytest
+
+from mx4_linux.motion import Transition, WheelMotion
+
+
+def test_transition_retargets_without_a_jump_and_finishes_on_time():
+ transition = Transition(duration=0.2)
+ transition.move(1, now=10)
+ halfway = transition.value(10.1)
+ assert 0 < halfway < 1
+ transition.move(0, now=10.1)
+ assert transition.value(10.1) == halfway
+ assert transition.value(10.3) == pytest.approx(0)
+ assert not transition.active(10.31)
+
+
+def test_reduced_motion_sets_the_final_value_immediately():
+ transition = Transition()
+ transition.move(1, animate=False, now=5)
+ assert transition.value(5) == 1
+ assert not transition.active(5)
+
+
+def test_wheel_integrates_the_same_distance_at_different_frame_rates():
+ positions = []
+ for frames in (30, 60, 144):
+ wheel = WheelMotion()
+ wheel.impulse(1)
+ wheel.advance(0)
+ for frame in range(1, frames + 1):
+ wheel.advance(frame / frames)
+ positions.append(wheel.position)
+ assert positions == pytest.approx([positions[0]] * 3)
+
+
+def test_wheel_bounds_impulses_and_stops_after_settling():
+ wheel = WheelMotion()
+ wheel.impulse(10000)
+ wheel.impulse(float('nan'))
+ assert wheel.velocity == 24
+ wheel.advance(1)
+ assert not wheel.advance(10)
+ wheel.stop()
+ assert wheel.updated is None
+
+
+def test_free_spin_coasts_farther_than_ratchet():
+ positions = []
+ for free_spin in (False, True):
+ wheel = WheelMotion()
+ wheel.impulse(1)
+ wheel.advance(0)
+ wheel.advance(1, free_spin=free_spin)
+ positions.append(wheel.position)
+ assert positions[1] > positions[0]
diff --git a/tests/test_profiles.py b/tests/test_profiles.py
index af8a8a9..d61ab94 100644
--- a/tests/test_profiles.py
+++ b/tests/test_profiles.py
@@ -6,7 +6,7 @@
import pytest
from mx4_linux.backend import BackendError, DemoBackend
-from mx4_linux.profiles import ProfileStore, apply_profile, settings_snapshot
+from mx4_linux.profiles import ProfileStore, apply_profile
def test_round_trip_snapshot_excludes_haptic_playback(tmp_path):
diff --git a/tests/test_ring_icons.py b/tests/test_ring_icons.py
new file mode 100644
index 0000000..82910b2
--- /dev/null
+++ b/tests/test_ring_icons.py
@@ -0,0 +1,37 @@
+"""Choose recognizable icons from action behavior rather than editable labels."""
+
+import pytest
+
+from mx4_linux.ring_icons import action_icon
+
+
+@pytest.mark.parametrize(("step", "icon"), [
+ ({"type": "shortcut", "keys": ["key_ctrl", "key_c"]}, "edit-copy-symbolic"),
+ ({"type": "shortcut", "keys": ["CTRL", "V"]}, "edit-paste-symbolic"),
+ ({"type": "shortcut", "keys": ["CTRL", "SHIFT", "Z"]}, "edit-redo-symbolic"),
+ ({"type": "shortcut", "keys": ["PLAYPAUSE"]}, "media-playback-start-symbolic"),
+ ({"type": "shortcut", "keys": ["SUPER", "Q"]}, "input-keyboard-symbolic"),
+ ({"type": "command", "argv": ["/usr/bin/kitty", "--title", "Work"]}, "utilities-terminal-symbolic"),
+ ({"type": "command", "argv": ["x-terminal-emulator"]}, "utilities-terminal-symbolic"),
+ ({"type": "command", "argv": ["firefox"]}, "web-browser-symbolic"),
+ ({"type": "command", "argv": ["xdg-open", "https://example.org"]}, "web-browser-symbolic"),
+ ({"type": "command", "argv": ["gio", "open", "/home/user/notes"]}, "folder-symbolic"),
+ ({"type": "command", "argv": ["custom-application"]}, "application-x-executable-symbolic"),
+ ({"type": "niri", "action": "focus-workspace-up"}, "go-previous-symbolic"),
+ ({"type": "niri", "action": "focus-workspace-down"}, "go-next-symbolic"),
+ ({"type": "niri", "action": "screenshot-screen"}, "camera-photo-symbolic"),
+ ({"type": "text", "text": "Hello"}, "insert-text-symbolic"),
+ ({"type": "delay", "milliseconds": 100}, "preferences-system-time-symbolic"),
+])
+def test_icons_describe_the_action_even_after_renaming(step, icon):
+ action = {"label": "My custom name", "steps": [step]}
+ assert action_icon(action) == icon
+
+
+def test_group_icon_distinguishes_an_action_collection_from_its_parent_routine():
+ action = {"label": "Clipboard", "steps": [{"type": "shortcut", "keys": ["CTRL", "C"]}]}
+ assert action_icon(action, grouped=True) == "view-app-grid-symbolic"
+
+
+def test_incomplete_editor_drafts_have_a_neutral_icon():
+ assert action_icon({"label": "New action", "steps": []}) == "system-run-symbolic"
diff --git a/tests/test_ring_model.py b/tests/test_ring_model.py
index 0dab091..e6ee539 100644
--- a/tests/test_ring_model.py
+++ b/tests/test_ring_model.py
@@ -2,7 +2,7 @@
import pytest
-from mx4_linux.ring_model import RingState, sector
+from mx4_linux.ring_model import BUTTON_RADIUS, ORBIT_RADIUS, RingState, button_at, button_center, sector
@pytest.mark.parametrize("index", range(8))
@@ -38,7 +38,7 @@ def test_short_click_latches_then_pointer_choose_closes():
ring.press()
assert ring.release() is None
assert ring.visible and not ring.held
- assert ring.point(140, 0) == 2
+ assert ring.point(*button_center(2)) == 2
assert ring.choose(2) == 2
assert not ring.visible
@@ -47,7 +47,7 @@ def test_second_press_cancels_latched_ring_and_release_does_nothing():
ring = RingState()
ring.press()
ring.release()
- ring.point(0, -140)
+ ring.point(*button_center(0))
assert ring.press() == "cancel"
assert not ring.visible and not ring.held
assert ring.release() is None
@@ -75,11 +75,62 @@ def test_raw_motion_is_ignored_when_closed_or_latched_and_radius_is_bounded():
assert ring.x == ring.y == 0
-@pytest.mark.parametrize("radius,expected", [(0, None), (65, None), (71, None), (75.99, None), (76, 2), (140, 2), (205, 2), (205.01, None)])
-def test_pointer_hit_area_matches_visible_ring(radius, expected):
+@pytest.mark.parametrize("index", range(8))
+def test_pointer_selects_each_circular_button(index):
+ ring = RingState()
+ ring.open()
+ assert ring.point(*button_center(index)) == index
+
+
+@pytest.mark.parametrize("index", range(8))
+def test_button_centers_match_clockwise_orbit(index):
+ x, y = button_center(index)
+ assert math.hypot(x, y) == pytest.approx(ORBIT_RADIUS)
+ assert sector(x, y) == index
+
+
+@pytest.mark.parametrize("offset,expected", [(-26.01, None), (-26, 2), (0, 2), (26, 2), (26.01, None)])
+def test_pointer_hit_area_stops_at_circle_boundary(offset, expected):
+ assert button_at(ORBIT_RADIUS + offset, 0) == expected
+
+
+@pytest.mark.parametrize("index", range(8))
+def test_gaps_between_buttons_do_not_select_invisible_sector(index):
+ angle = (index + .5) * math.pi / 4
+ assert button_at(ORBIT_RADIUS * math.sin(angle), -ORBIT_RADIUS * math.cos(angle)) is None
+
+
+@pytest.mark.parametrize("x,y", [(0, 0), (23, 0), (205, 0), (float("nan"), 100), (100, float("inf"))])
+def test_pointer_center_outside_and_nonfinite_positions_clear_selection(x, y):
+ ring = RingState()
+ ring.open()
+ ring.point(*button_center(0))
+ assert ring.point(x, y) is None
+
+
+def test_pointer_cannot_select_in_a_button_bounding_box_corner():
+ assert button_at(ORBIT_RADIUS + BUTTON_RADIUS, BUTTON_RADIUS) is None
+
+
+def test_pointer_is_ignored_when_closed():
+ ring = RingState()
+ assert ring.point(*button_center(0)) is None
+
+
+def test_pointer_tracks_painted_button_positions_during_entry():
ring = RingState()
ring.open()
- assert ring.point(radius, 0) == expected
+ x, y = button_center(0)
+ spread = .78
+ assert ring.point(x * spread, y * spread, spread=spread) == 0
+ assert ring.point(x * spread, y * spread + BUTTON_RADIUS - 1, spread=spread) == 0
+ assert ring.point(x, y - BUTTON_RADIUS, spread=spread) is None
+ assert ring.point(x * spread + BUTTON_RADIUS, y * spread + BUTTON_RADIUS, spread=spread) is None
+
+
+@pytest.mark.parametrize("spread", [0, -1, float("nan"), float("inf")])
+def test_invalid_animation_spread_has_no_pointer_target(spread):
+ assert button_at(*button_center(0), spread=spread) is None
@pytest.mark.parametrize("index", [-1, 8, 3.2, True, "1", None])
diff --git a/tests/test_ring_preview.py b/tests/test_ring_preview.py
new file mode 100644
index 0000000..c485785
--- /dev/null
+++ b/tests/test_ring_preview.py
@@ -0,0 +1,71 @@
+"""Exercise the editor preview without presenting a desktop overlay."""
+
+from copy import deepcopy
+
+import pytest
+
+gi = pytest.importorskip("gi")
+try:
+ gi.require_version("Gtk", "4.0")
+ gi.require_version("Adw", "1")
+except ValueError as exc:
+ pytest.skip(str(exc), allow_module_level=True)
+
+from mx4_linux.actions import default_config
+from mx4_linux.gtk_support import Adw, Gtk
+from mx4_linux.ring_icons import action_icon
+from mx4_linux.ring_model import BUTTON_RADIUS, button_center
+from mx4_linux.ring_preview import RingPreview
+
+
+@pytest.fixture
+def preview():
+ if not Gtk.init_check():
+ pytest.skip("A graphical session is needed for native ring preview tests")
+ Adw.init()
+ selected = []
+ widget = RingPreview(default_config(), selected.append)
+ widget.allocate(640, 390, -1, None)
+ return widget, selected
+
+
+def test_round_preview_preserves_ring_order_and_shared_geometry(preview):
+ widget, selected = preview
+ assert len(widget.buttons) == len(widget.labels) == 8
+ for index, action_id in enumerate(widget.config["ring"]):
+ action = widget.config["actions"][action_id]
+ assert widget.labels[index].get_text() == action["label"]
+ assert widget.icons[index].get_icon_name() == action_icon(action)
+ x, y = button_center(index)
+ assert widget.get_child_position(widget.buttons[index]) == pytest.approx((320 + x - BUTTON_RADIUS,
+ 190 + y - BUTTON_RADIUS))
+ assert widget.buttons[index].get_tooltip_text().startswith(f"{index + 1}. ")
+ assert not selected
+
+
+def test_preview_selection_is_visual_and_click_only_focuses_assignment(preview):
+ widget, selected = preview
+ widget.select(2)
+ assert not selected
+ assert widget.buttons[2].has_css_class("selected")
+ widget.buttons[5].emit("clicked")
+ assert selected == [5]
+ assert widget.selected == 5
+ assert widget.buttons[5].has_css_class("selected")
+ assert widget.labels[5].has_css_class("selected")
+ assert not widget.buttons[2].has_css_class("selected")
+
+
+def test_preview_refresh_keeps_draft_labels_and_group_icons(preview):
+ widget, selected = preview
+ config = deepcopy(widget.config)
+ action_id = config["ring"][0]
+ config["actions"][action_id]["label"] = "My actions"
+ config["ring_groups"] = {"0": ["copy", "paste"]}
+ widget.select(0)
+ widget.update_config(config)
+ assert widget.labels[0].get_text() == "My actions"
+ assert widget.icons[0].get_icon_name() == action_icon(config["actions"][action_id], grouped=True)
+ assert widget.buttons[0].get_tooltip_text() == "1. My actions. Action group"
+ assert widget.buttons[0].has_css_class("selected")
+ assert not selected
diff --git a/tests/test_ring_view.py b/tests/test_ring_view.py
new file mode 100644
index 0000000..5fdbc87
--- /dev/null
+++ b/tests/test_ring_view.py
@@ -0,0 +1,297 @@
+"""Exercise native ring previews without presenting or running desktop actions."""
+
+from time import monotonic
+from types import SimpleNamespace
+
+import pytest
+
+gi = pytest.importorskip("gi")
+try:
+ gi.require_version("Gtk", "4.0")
+ gi.require_version("Adw", "1")
+except ValueError as exc:
+ pytest.skip(str(exc), allow_module_level=True)
+
+from mx4_linux import ring
+from mx4_linux.actions import default_config
+from mx4_linux.gtk_support import Adw, Gdk, Gtk
+from mx4_linux.ring_model import BUTTON_RADIUS, button_center
+
+
+@pytest.fixture
+def preview(monkeypatch):
+ if not Gtk.init_check():
+ pytest.skip("A graphical session is needed for native ring interaction tests")
+ Adw.init()
+ monkeypatch.setattr(ring, "Layer", None)
+ selected, dismissed = [], []
+ window = ring.ActionsRing(None, lambda *args: selected.append(args), lambda: dismissed.append(True))
+ # Allocate native widgets for hit testing without taking desktop focus.
+ monkeypatch.setattr(window, "present", lambda: None)
+ settings = Gtk.Settings.get_default()
+ original_motion = settings.get_property("gtk-enable-animations")
+ settings.set_property("gtk-enable-animations", True)
+ window.show_ring(default_config(), preview=True)
+ window.allocate(ring.WIDTH, ring.HEIGHT, -1, None)
+ yield SimpleNamespace(window=window, selected=selected, dismissed=dismissed, settings=settings)
+ settings.set_property("gtk-enable-animations", original_motion)
+ window.hide_ring()
+ window.destroy()
+
+
+def controllers(widget, kind):
+ model = widget.observe_controllers()
+ return [model.get_item(index) for index in range(model.get_n_items()) if isinstance(model.get_item(index), kind)]
+
+
+def main_position(window, index):
+ dx, dy = button_center(index)
+ return ring.CENTER_X + dx * window.spread, ring.CENTER_Y + dy * window.spread
+
+
+def settle(window):
+ for transition in (window.reveal, window.group_reveal, window.label_reveal):
+ transition.move(transition.target, animate=False)
+ window.apply_frame(monotonic())
+
+
+def show_group(preview, *, held=False):
+ config = default_config()
+ config["ring_groups"] = {"2": ["copy", "paste"]}
+ preview.window.show_ring(config, held=held, preview=True)
+ settle(preview.window)
+ return preview.window
+
+
+def test_pointer_capture_selects_only_the_painted_circular_button(preview):
+ window = preview.window
+ gestures = controllers(window.surface, Gtk.GestureClick)
+ assert len(gestures) == 1
+ assert gestures[0].get_propagation_phase() == Gtk.PropagationPhase.CAPTURE
+ window.pointer_click(None, 1, *main_position(window, 0))
+ window.buttons[1].emit("clicked") # A stale native activation must not run another action.
+ assert preview.selected == [("overview", True)]
+ assert not preview.dismissed
+
+
+def test_corner_of_native_button_allocation_cannot_run_an_action(preview):
+ window = preview.window
+ x, y = main_position(window, 0)
+ window.pointer_click(None, 1, x + BUTTON_RADIUS, y + BUTTON_RADIUS)
+ assert preview.dismissed == [True]
+ assert not preview.selected
+
+
+def test_native_faces_have_the_same_diameter_as_pointer_hit_geometry(preview):
+ for button in preview.window.buttons:
+ assert button.get_allocated_width() == BUTTON_RADIUS * 2
+ assert button.get_allocated_height() == BUTTON_RADIUS * 2
+ assert preview.window.close_button.get_allocated_width() == ring.CENTER_RADIUS * 2
+ assert preview.window.close_button.get_allocated_height() == ring.CENTER_RADIUS * 2
+
+
+def test_group_heading_and_footer_do_not_cover_the_six_child_targets(preview):
+ window = preview.window
+ config = default_config()
+ config["ring_groups"] = {"2": list(config["actions"])[:6]}
+ config["actions"][config["ring"][2]]["label"] = "An action group with a longer name"
+ window.show_ring(config, preview=True)
+ settle(window)
+ window.pointer_motion(None, *main_position(window, 2))
+ settle(window)
+ window.update_labels()
+ window.allocate(ring.WIDTH, ring.HEIGHT, -1, None)
+ heading = window.callout.get_allocation()
+ footer = window.instructions.get_allocation()
+ assert heading.y + heading.height < min(y - ring.CHILD_RADIUS for _x, y in window.child_positions)
+ assert footer.y > max(y + ring.CHILD_RADIUS for _x, y in window.child_positions)
+ assert footer.y + footer.height <= ring.HEIGHT
+
+
+def test_native_action_button_runs_once_in_preview(preview):
+ window = preview.window
+ window.buttons[3].emit("clicked")
+ window.buttons[3].emit("clicked")
+ assert preview.selected == [("workspace-next", True)]
+ assert not window.state.visible
+
+
+@pytest.mark.parametrize("coordinate", [(ring.CENTER_X, ring.CENTER_Y), (0, 0)])
+def test_center_and_outside_clicks_dismiss_without_selecting(preview, coordinate):
+ preview.window.pointer_click(None, 1, *coordinate)
+ assert preview.dismissed == [True]
+ assert not preview.selected
+
+
+def test_arrows_keep_native_focus_with_highlight_and_enter_uses_it(preview):
+ window = preview.window
+ keys = controllers(window, Gtk.EventControllerKey)
+ assert keys
+ assert all(controller.get_propagation_phase() == Gtk.PropagationPhase.CAPTURE for controller in keys)
+ window.buttons[2].grab_focus()
+ assert window.state.selected == 2
+ assert window.key_pressed(None, Gdk.KEY_Right, 0, 0)
+ assert window.state.selected == 3
+ assert window.get_focus() == window.buttons[3]
+ assert window.buttons[3].has_css_class("selected")
+ assert not window.buttons[2].has_css_class("selected")
+ assert window.callout_label.get_text() == "Next workspace"
+ window.key_pressed(None, Gdk.KEY_Return, 0, 0)
+ assert preview.selected == [("workspace-next", True)]
+
+
+def test_hover_opens_group_and_keeps_parent_action_inert(preview):
+ window = show_group(preview)
+ window.pointer_motion(None, *main_position(window, 2))
+ assert window.group_slot == 2
+ assert window.children == ["copy", "paste"]
+ assert len(window.child_positions) == 2
+ assert not window.child_buttons[2].get_visible()
+ assert "group action" in window.instructions.get_text()
+ assert not preview.selected
+ settle(window)
+ window.pointer_motion(None, *window.child_positions[1])
+ assert window.child_selected == 1
+ assert window.callout_label.get_text() == "Paste"
+ assert not preview.selected
+
+
+def test_clicking_group_parent_during_entry_cannot_run_collapsed_child(preview):
+ window = show_group(preview)
+ parent = main_position(window, 2)
+ window.pointer_motion(None, *parent)
+ window.group_reveal.move(0, animate=False)
+ window.apply_frame(monotonic())
+ window.pointer_click(None, 1, *parent)
+ assert window.state.visible and window.group_slot == 2
+ assert window.child_selected == 0
+ assert not preview.selected
+ window.group_reveal.move(1, animate=False)
+ window.apply_frame(monotonic())
+ window.pointer_click(None, 1, *window.child_positions[1])
+ assert preview.selected == [("paste", True)]
+
+
+@pytest.mark.parametrize("selection", ["click", "number", "enter", "native"])
+def test_group_child_selection_runs_exactly_once(preview, selection):
+ window = show_group(preview)
+ window.commit(2)
+ assert window.get_focus() == window.child_buttons[0]
+ assert window.child_selected == 0
+ assert not preview.selected
+ settle(window)
+ if selection == "click":
+ window.pointer_click(None, 1, *window.child_positions[1])
+ elif selection == "number":
+ window.key_pressed(None, Gdk.KEY_2, 0, 0)
+ elif selection == "enter":
+ window.key_pressed(None, Gdk.KEY_Down, 0, 0)
+ assert window.get_focus() == window.child_buttons[1]
+ window.key_pressed(None, Gdk.KEY_Return, 0, 0)
+ else:
+ window.child_buttons[1].emit("clicked")
+ window.child_buttons[1].emit("clicked")
+ assert preview.selected == [("paste", True)]
+ assert not window.state.visible
+
+
+def test_held_group_parent_release_latches_without_running_an_action(preview):
+ window = show_group(preview, held=True)
+ window.motion(100, 0)
+ assert window.state.selected == 2
+ window.release_button()
+ assert window.state.visible and not window.state.held
+ assert window.group_slot == 2 and window.child_selected == 0
+ assert not preview.selected
+ window.key_pressed(None, Gdk.KEY_Return, 0, 0)
+ assert preview.selected == [("copy", True)]
+
+
+@pytest.mark.parametrize("back_key", [Gdk.KEY_Escape, Gdk.KEY_BackSpace])
+def test_escape_returns_to_group_parent_then_closes(preview, back_key):
+ window = show_group(preview)
+ window.commit(2)
+ window.key_pressed(None, back_key, 0, 0)
+ assert window.state.visible and window.group_slot is None
+ assert window.state.selected == 2
+ assert window.get_focus() == window.buttons[2]
+ assert not window.child_positions
+ assert not any(button.get_visible() for button in window.child_buttons)
+ window.key_pressed(None, Gdk.KEY_Escape, 0, 0)
+ assert preview.dismissed == [True]
+ assert not preview.selected
+
+
+def test_escape_and_cleanup_never_commit_an_action(preview):
+ window = show_group(preview, held=True)
+ window.motion(100, 0)
+ window.key_pressed(None, Gdk.KEY_Escape, 0, 0)
+ window.release_button()
+ window.hide_ring()
+ assert preview.dismissed == [True]
+ assert not preview.selected
+ assert window.group_slot is None
+ assert window.tick_id == 0
+
+
+@pytest.mark.parametrize("key", [Gdk.KEY_Return, Gdk.KEY_space])
+def test_keyboard_activation_of_center_close_never_runs_selected_action(preview, key):
+ window = preview.window
+ window.buttons[3].grab_focus()
+ window.close_button.grab_focus()
+ assert window.get_focus() == window.close_button
+ handled = window.key_pressed(None, key, 0, 0)
+ if not handled: # GTK activates the focused native button after capture.
+ window.close_button.emit("clicked")
+ assert preview.dismissed == [True]
+ assert not preview.selected
+
+
+def test_reduced_motion_snaps_all_transitions_and_reopen_leaves_no_tick(preview):
+ window = show_group(preview)
+ window.commit(2)
+ assert window.tick_id
+ preview.settings.set_property("gtk-enable-animations", False)
+ assert window.tick_id == 0
+ assert window.surface.get_opacity() == 1
+ assert window.spread == 1
+ for transition in (window.reveal, window.group_reveal, window.label_reveal):
+ assert not transition.active()
+ assert transition.value() == transition.target
+ assert all(window.child_buttons[index].get_opacity() == 1 for index in range(2))
+ window.show_ring(default_config(), preview=True)
+ assert window.tick_id == 0
+ assert window.surface.get_opacity() == 1
+ assert window.group_slot is None
+ assert not window.child_positions
+
+
+def test_group_accessibility_does_not_leave_expandable_state_on_regular_actions(preview):
+ window = show_group(preview)
+ assert Gtk.test_accessible_has_state(window.buttons[2], Gtk.AccessibleState.EXPANDED)
+ assert not Gtk.test_accessible_has_state(window.buttons[0], Gtk.AccessibleState.EXPANDED)
+ window.commit(2)
+ window.show_ring(default_config(), preview=True)
+ assert not Gtk.test_accessible_has_state(window.buttons[2], Gtk.AccessibleState.EXPANDED)
+
+
+@pytest.mark.parametrize("coordinates", [(float("nan"), 0), (0, float("inf"))])
+def test_nonfinite_child_pointer_coordinates_never_select(preview, coordinates):
+ window = show_group(preview)
+ window.commit(2)
+ settle(window)
+ assert window.child_at(*coordinates) is None
+ assert not preview.selected
+
+
+def test_finite_group_animation_stops_after_all_transitions_finish(preview, monkeypatch):
+ window = show_group(preview)
+ window.commit(2)
+ assert window.tick_id
+ deadline = max(t.started + t.duration for t in (window.reveal, window.group_reveal, window.label_reveal)) + .01
+ monkeypatch.setattr(ring, "monotonic", lambda: deadline)
+ window.stop_animation() # The unmapped fixture has no frame clock to invoke the registered callback.
+ assert window.tick(None, None) is False
+ assert window.tick_id == 0
+ assert window.group_reveal.value(deadline) == 1
+ assert window.child_positions[0] != window.child_positions[1]
diff --git a/tests/test_wayland_actions.py b/tests/test_wayland_actions.py
index 4de3ece..e54a001 100644
--- a/tests/test_wayland_actions.py
+++ b/tests/test_wayland_actions.py
@@ -1,6 +1,5 @@
"""Native keyboard selection and injection, using process/device doubles."""
-from pathlib import Path
from types import SimpleNamespace
import evdev