From 9f81c9228a8a12c7c521671d02620514b5d382cb Mon Sep 17 00:00:00 2001 From: Erwin Lejeune Date: Mon, 14 Sep 2026 16:31:35 +0000 Subject: [PATCH 1/3] Never substitute invented motion for a missing sensor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `motion.source = "auto"` fell back to the synthetic `demo` source when no accelerometer was found. That was written for a first run at a desk, where an overlay that visibly does something beats one that silently does not. It is the wrong behaviour in the situation this program exists for. `demo` replays a scripted drive. In a moving vehicle those cues disagree with the motion the passenger actually feels, which is a worse sensory mismatch than no cues at all — precisely the mismatch that makes people ill. Worse, it is invisible: dots move, so it looks like it is working, and the trip is spent being made sicker by the thing meant to help. Auto-detection now uses `iio` when the machine has an accelerometer and otherwise selects an explicit null source that draws nothing. The daemon logs why at startup, and `doctor` names the source it chose and points at the phone route when there is none. `demo` stays available when asked for by name, which is how the README and the capture scripts already use it. Also: the installer asked pip for `motionless-overlay` before checking whether it is published, so a real install printed pipx's "Fatal error from pip prevented installation" and "Error installing motionless-overlay" before the fallback quietly succeeded. It reads as a hard failure. It now asks the PyPI JSON API first and goes straight to the repository while the package does not exist, and starts using PyPI on its own once it does. --- CHANGELOG.md | 14 ++++++++++ README.md | 17 +++++++++--- install.sh | 42 +++++++++++++++++++++++------- src/motionless/daemon.py | 10 ++++++- src/motionless/doctor.py | 19 ++++++++++++++ src/motionless/sources/__init__.py | 24 ++++++++++------- src/motionless/sources/null.py | 29 +++++++++++++++++++++ tests/test_doctor.py | 21 +++++++++++++-- tests/test_sources.py | 40 ++++++++++++++++++++++++++-- 9 files changed, 188 insertions(+), 28 deletions(-) create mode 100644 src/motionless/sources/null.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6361b7d..fb9688c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,21 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Changed +- `motion.source = "auto"` no longer falls back to the synthetic `demo` source + when no accelerometer is present. It reports no source and draws nothing + instead. Cues that disagree with the vehicle you are in are a worse sensory + mismatch than no cues, so inventing motion to fill a missing sensor works + against the point of the program. `demo` remains available explicitly. + `doctor` now names the auto-detected source and explains what to do when + there is none. + ### Fixed +- The installer asked pip to install `motionless-overlay` before checking + whether it exists, so every run printed pipx's "Fatal error from pip + prevented installation" before falling back to the repository and + succeeding. It now asks PyPI first and goes straight to the repository, + silently, while the package is unpublished. - The installer looked frozen at `[sudo] password for ...` when run through `curl | bash`. It now explains that sudo will ask, and that nothing is echoed while you type, before the prompt appears rather than after. diff --git a/README.md b/README.md index 9fe25f5..559ae4f 100644 --- a/README.md +++ b/README.md @@ -123,12 +123,21 @@ Run `motionless sources` to see which of these your machine can use. | Source | Works when | Notes | | --- | --- | --- | -| `iio` | Your device has an accelerometer | Most convertibles, tablets and some laptops. Read straight from `/sys/bus/iio`. | +| `iio` | Your device has an accelerometer | Convertibles, tablets, and laptops with screen-rotation or drive-protection sensors. Read straight from `/sys/bus/iio`. | | `udp` | You stream readings from a phone | A phone in the car's cradle is a *better* motion sensor than a laptop on your knees. | -| `demo` | Always | Synthetic drive loop, for previewing and tuning. | +| `demo` | Always | Synthetic drive loop, for previewing and tuning **only**. | -`motion.source = "auto"` (the default) picks `iio` when an accelerometer -exists and falls back to `demo`. +`motion.source = "auto"` (the default) uses `iio` when this machine has an +accelerometer. When it does not, it reports **no source** and draws nothing. + +That is deliberate. `demo` replays a scripted drive, and cues that disagree +with the vehicle you are actually in are a worse sensory mismatch than no cues +— which is the thing that makes people ill in the first place. Auto-detection +will not quietly substitute invented motion for a missing sensor. Run +`motionless doctor`: it names the source it chose, and says what to do when +there is none. + +Most laptops have no accelerometer. If yours does not, use your phone.
Using your phone as the sensor diff --git a/install.sh b/install.sh index 13cebd0..3939109 100755 --- a/install.sh +++ b/install.sh @@ -8,7 +8,7 @@ # download is cut short, nothing runs at all rather than running half a script. # # Environment overrides: -# MOTIONLESS_SOURCE=pypi|git where to install from (default: pypi, git fallback) +# MOTIONLESS_SOURCE=auto|pypi|git where to install from (default: auto) # MOTIONLESS_REF= git ref when installing from git (default: main) # MOTIONLESS_SKIP_DEPS=1 do not touch the system package manager # MOTIONLESS_YES=1 never prompt (implied when stdin is not a terminal) @@ -212,6 +212,19 @@ venv_install() { ln -sf "$venv/bin/motionless" "$HOME/.local/bin/motionless" } +# Is the package published? Cheap GET against the JSON API, so we never hand +# pip a name it cannot resolve just to discover it does not exist yet. +pypi_has_package() { + local name="$1" + if has curl; then + curl -fsS --max-time 10 -o /dev/null "https://pypi.org/pypi/$name/json" 2>/dev/null + elif has wget; then + wget -q --timeout=10 -O /dev/null "https://pypi.org/pypi/$name/json" 2>/dev/null + else + return 1 + fi +} + install_target() { case "${MOTIONLESS_SOURCE:-pypi}" in git) printf 'git+%s@%s' "$REPO_URL" "${MOTIONLESS_REF:-main}" ;; @@ -220,19 +233,28 @@ install_target() { } install_package() { - local target - target="$(install_target)" - info "Installing $target" - local installer=venv_install if has pipx; then installer=pipx_install; fi + # "auto" asks PyPI whether the package exists yet; git and pypi force it. + local source="${MOTIONLESS_SOURCE:-auto}" + if [ "$source" = "auto" ]; then + if pypi_has_package "$PACKAGE"; then + source=pypi + else + info "not published to PyPI yet; installing from the git repository" + source=git + fi + fi + + local target + target="$(MOTIONLESS_SOURCE="$source" install_target)" + info "Installing $target" + if ! "$installer" "$target"; then - if [ "${MOTIONLESS_SOURCE:-pypi}" = "pypi" ]; then - # Expected until the first release is published; not a failure. - info "not available on PyPI yet; installing from the git repository" - MOTIONLESS_SOURCE=git - "$installer" "$(install_target)" || die "installation failed" + if [ "$source" = "pypi" ]; then + warn "install from PyPI failed; falling back to the git repository" + "$installer" "$(MOTIONLESS_SOURCE=git install_target)" || die "installation failed" else die "installation failed" fi diff --git a/src/motionless/daemon.py b/src/motionless/daemon.py index 76ef38f..393ff83 100644 --- a/src/motionless/daemon.py +++ b/src/motionless/daemon.py @@ -143,7 +143,15 @@ def run(self) -> int: GLib.unix_signal_add(GLib.PRIORITY_HIGH, sig, self._on_signal) self._source.start() - log.info("motion source: %s", self._source.name) + if self._source.name == "none": + log.warning( + "no motion source: this machine has no accelerometer under " + "/sys/bus/iio, so there is nothing to react to and no cues " + "will appear. Run `motionless sources`; the usual answer is " + 'to stream from a phone with `motion.source = "udp"`.' + ) + else: + log.info("motion source: %s", self._source.name) self._overlay.start(visible=self._initial_visible) log.info( "overlay ready on %d monitor(s), cues %s", diff --git a/src/motionless/doctor.py b/src/motionless/doctor.py index aeec66d..60a7a93 100644 --- a/src/motionless/doctor.py +++ b/src/motionless/doctor.py @@ -153,10 +153,29 @@ def check_display() -> list[Check]: def check_sources() -> list[Check]: + from motionless.sources import detect + checks = [] for name, availability in probe_all().items(): + if name == "none": + continue level = Level.OK if availability.available else Level.WARN checks.append(Check(f"Source: {name}", level, availability.detail or "-")) + + chosen = detect() + if chosen.name == "none": + checks.append( + Check( + "Auto-detected source", + Level.WARN, + "none — no accelerometer on this machine, so no cues will appear", + "stream from a phone: `motionless config set motion.source udp` " + "(see the README), or preview the look with " + "`motionless run --source demo`", + ) + ) + else: + checks.append(Check("Auto-detected source", Level.OK, chosen.name)) return checks diff --git a/src/motionless/sources/__init__.py b/src/motionless/sources/__init__.py index 669326b..cf602fc 100644 --- a/src/motionless/sources/__init__.py +++ b/src/motionless/sources/__init__.py @@ -6,15 +6,20 @@ from motionless.sources.base import Availability, MotionSource, SampleCallback from motionless.sources.demo import DemoSource from motionless.sources.iio import IioSource +from motionless.sources.null import NullSource from motionless.sources.udp import UdpSource #: Every source that can be named in configuration, in registry order. -SOURCES: tuple[type[MotionSource], ...] = (IioSource, UdpSource, DemoSource) +SOURCES: tuple[type[MotionSource], ...] = (IioSource, UdpSource, DemoSource, NullSource) -#: Order tried by ``source = "auto"``. ``udp`` is excluded on purpose: it is -#: always "available" but does nothing without a sender, so choosing it -#: automatically would look like a silent failure. -AUTO_ORDER: tuple[type[MotionSource], ...] = (IioSource, DemoSource) +#: Order tried by ``source = "auto"``. +#: +#: ``udp`` is excluded because it is always "available" but does nothing +#: without a sender. ``demo`` is excluded for a more important reason: it +#: replays a *synthetic* drive, and cues that disagree with the vehicle you are +#: actually in are worse than no cues at all. Auto-detection that cannot find a +#: real sensor says so instead of inventing motion. +AUTO_ORDER: tuple[type[MotionSource], ...] = (IioSource,) class UnknownSourceError(ValueError): @@ -40,15 +45,15 @@ def probe_all() -> dict[str, Availability]: def detect() -> type[MotionSource]: - """Pick the best source for this machine. + """Pick the best real source for this machine. - Falls back to the demo source, which always works — an overlay that - visibly does something is easier to debug than one that silently does not. + Returns :class:`NullSource` when there is no real sensor, rather than + substituting synthetic motion. See :data:`AUTO_ORDER`. """ for source in AUTO_ORDER: if source.probe(): return source - return DemoSource + return NullSource def build(config: MotionConfig, on_sample: SampleCallback) -> MotionSource: @@ -70,6 +75,7 @@ def build(config: MotionConfig, on_sample: SampleCallback) -> MotionSource: "DemoSource", "IioSource", "MotionSource", + "NullSource", "UdpSource", "UnknownSourceError", "build", diff --git a/src/motionless/sources/null.py b/src/motionless/sources/null.py new file mode 100644 index 0000000..eeeadc8 --- /dev/null +++ b/src/motionless/sources/null.py @@ -0,0 +1,29 @@ +"""A source that reports no motion at all. + +Selected when ``source = "auto"`` finds no real sensor. Falling back to the +synthetic ``demo`` source would be actively harmful in the situation this +program exists for: dots drifting to a script the vehicle is not following are +a *worse* sensory mismatch than no dots, which is the thing that makes people +ill. Better to draw nothing and say why. +""" + +from __future__ import annotations + +from motionless.sources.base import Availability, MotionSource + + +class NullSource(MotionSource): + """Emits nothing. Present so "no sensor" is explicit rather than implied.""" + + name = "none" + description = "No motion source — cues stay hidden until one is configured" + + @classmethod + def probe(cls) -> Availability: + return Availability.ok("no motion, by design") + + def _run(self) -> None: + # Nothing to read; park until stop() is called. + while not self.stopping: + if self.wait(0.5): + return diff --git a/tests/test_doctor.py b/tests/test_doctor.py index 2c4d873..2699e85 100644 --- a/tests/test_doctor.py +++ b/tests/test_doctor.py @@ -103,9 +103,26 @@ def test_a_broken_file_fails_with_the_reason(self, tmp_path: Path) -> None: class TestOther: - def test_sources_are_all_reported(self) -> None: + def test_real_sources_are_reported_and_the_choice_is_named(self) -> None: names = {c.name for c in check_sources()} - assert names == {"Source: iio", "Source: udp", "Source: demo"} + assert {"Source: iio", "Source: udp", "Source: demo"} <= names + # "none" is an internal placeholder, not something to offer a user. + assert "Source: none" not in names + assert "Auto-detected source" in names + + def test_no_accelerometer_is_surfaced_as_a_warning_with_a_way_out( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + from motionless.sources import IioSource + from motionless.sources.base import Availability + + monkeypatch.setattr( + IioSource, "probe", classmethod(lambda cls, *a: Availability.no("none here")) + ) + chosen = next(c for c in check_sources() if c.name == "Auto-detected source") + assert chosen.level is Level.WARN + assert "no cues will appear" in chosen.detail + assert "udp" in chosen.hint def test_a_stopped_daemon_is_a_warning_not_a_failure(self) -> None: check = check_daemon()[0] diff --git a/tests/test_sources.py b/tests/test_sources.py index 02dbe9a..e83dfe6 100644 --- a/tests/test_sources.py +++ b/tests/test_sources.py @@ -55,13 +55,49 @@ def test_unknown_name_lists_the_alternatives(self) -> None: def test_probe_covers_every_source(self) -> None: assert set(probe_all()) == set(source_names()) + def test_demo_is_never_auto_selected(self) -> None: + # Synthetic cues that disagree with the vehicle you are actually in are + # a worse sensory mismatch than no cues, which is the thing that makes + # people ill. Auto must never substitute them for a real sensor. + from motionless.sources import DemoSource as _Demo + + assert _Demo not in AUTO_ORDER + + def test_auto_reports_no_source_rather_than_inventing_one( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + from motionless.sources import NullSource + from motionless.sources.base import Availability as _A + + monkeypatch.setattr(IioSource, "probe", classmethod(lambda cls, *a: _A.no("none"))) + assert detect() is NullSource + source = build(MotionConfig(source="auto"), lambda _s: None) + assert isinstance(source, NullSource) + assert source.name == "none" + + def test_null_source_emits_nothing_and_stops_promptly(self) -> None: + from motionless.sources import NullSource + + received: list[MotionSample] = [] + source = NullSource(received.append) + source.start() + time.sleep(0.3) + started = time.monotonic() + source.stop() + assert received == [] + assert source.error is None + assert time.monotonic() - started < 2.0 + def test_udp_is_not_auto_selected(self) -> None: # It reports itself available but does nothing without a sender, so # auto-selecting it would look like a silent failure. assert UdpSource not in AUTO_ORDER - def test_detect_always_returns_something_usable(self) -> None: - assert detect() in AUTO_ORDER + def test_detect_returns_a_real_source_or_an_explicit_none(self) -> None: + from motionless.sources import NullSource + + # Never an arbitrary third thing, and never the synthetic drive loop. + assert detect() in (*AUTO_ORDER, NullSource) def test_build_honours_an_explicit_choice(self) -> None: source = build( From 8be4c38c9748e7cc7172397a57eb44a7927f7afa Mon Sep 17 00:00:00 2001 From: Erwin Lejeune Date: Mon, 14 Sep 2026 16:44:19 +0000 Subject: [PATCH 2/3] Stop `motionless stop` hanging when the main loop is busy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The quit was scheduled with GLib.idle_add, which runs at PRIORITY_DEFAULT_IDLE. The overlay redraws on a GLib.timeout_add, which is PRIORITY_DEFAULT — a higher priority. While drawing keeps the main loop busy, the idle callback below it never gets a turn, so the daemon acknowledges the quit and then carries on running forever. It needs a machine slow enough for a frame to take most of the frame interval, which is why it had not shown up: every previous run drew comfortably inside 16ms. A loaded CI runner did not. It took eleven seconds just to open the overlay, and the daemon then ignored `quit` until the test killed it. The quit is now scheduled at PRIORITY_HIGH, above the redraw, so it cannot be starved. A test pins the ordering by asserting the scheduled priority is above PRIORITY_DEFAULT rather than merely that something was scheduled. The smoke job's shutdown timeout goes from 10s to 45s and says what it means when it expires — the reply was sent, so a timeout means the loop did not act on it. A slow shutdown and a stuck one should not look the same. --- .github/workflows/ci.yml | 10 ++++++++-- CHANGELOG.md | 7 +++++++ src/motionless/daemon.py | 8 ++++++-- tests/test_daemon.py | 26 ++++++++++++++++++++++++++ 4 files changed, 47 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fd38b1f..037e98f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -129,10 +129,16 @@ jobs: ipc.request("quit") finally: try: - daemon.wait(timeout=10) + # Generous: a contended runner has taken over ten seconds + # just to open the overlay, and a shutdown that is merely + # slow should not read as one that is stuck. + daemon.wait(timeout=45) except subprocess.TimeoutExpired: daemon.kill() - raise SystemExit("daemon did not stop on request") from None + raise SystemExit( + "daemon did not stop within 45s of `quit` — the reply was " + "sent, so the main loop did not act on it" + ) from None assert daemon.returncode == 0, f"daemon exited {daemon.returncode}" print("smoke test passed") PY diff --git a/CHANGELOG.md b/CHANGELOG.md index fb9688c..af23335 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,13 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). there is none. ### Fixed +- `motionless stop` could hang and leave the daemon running. The quit was + scheduled with `GLib.idle_add`, which runs at `PRIORITY_DEFAULT_IDLE` — + below the overlay's `PRIORITY_DEFAULT` redraw timer. On a machine slow + enough for drawing to saturate the main loop, the quit was starved + indefinitely. It is now scheduled at `PRIORITY_HIGH`. Found when a loaded + CI runner, which took eleven seconds just to open the overlay, hit exactly + this. - The installer asked pip to install `motionless-overlay` before checking whether it exists, so every run printed pipx's "Fatal error from pip prevented installation" before falling back to the repository and diff --git a/src/motionless/daemon.py b/src/motionless/daemon.py index 393ff83..deabeb0 100644 --- a/src/motionless/daemon.py +++ b/src/motionless/daemon.py @@ -205,8 +205,12 @@ def _handle_command(self, command: str, _args: dict[str, Any]) -> dict[str, Any] if command == "reload": return self.reload() if command == "quit": - # Defer so the reply reaches the client before the loop ends. - self._glib.idle_add(self.quit) + # Defer so the reply reaches the client before the loop ends, but + # at high priority: the overlay's redraw is a PRIORITY_DEFAULT + # timeout, and a default-idle callback sits *below* that. On a + # machine slow enough for drawing to saturate the loop, the quit + # would be starved indefinitely and `motionless stop` would hang. + self._glib.idle_add(self.quit, priority=self._glib.PRIORITY_HIGH) return {"stopping": True} raise ValueError(f"unhandled command {command!r}") # pragma: no cover diff --git a/tests/test_daemon.py b/tests/test_daemon.py index 59a50d0..7b7bdcf 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -105,6 +105,32 @@ def test_source_errors_surface(self) -> None: assert daemon.status()["source_error"] is None +class TestQuit: + def test_quit_is_scheduled_above_the_redraw_timer(self) -> None: + # The overlay redraws on a PRIORITY_DEFAULT timeout. A quit scheduled + # at the default idle priority sits below it, so on a machine slow + # enough for drawing to saturate the main loop the daemon never stops. + scheduled: list[tuple[object, object]] = [] + + class FakeGLib: + PRIORITY_HIGH = -100 + PRIORITY_DEFAULT = 0 + PRIORITY_DEFAULT_IDLE = 200 + + @staticmethod + def idle_add(callback: object, *, priority: object = 200) -> int: + scheduled.append((callback, priority)) + return 1 + + daemon = make_daemon() + daemon._glib = FakeGLib() + assert daemon._handle_command("quit", {}) == {"stopping": True} + assert len(scheduled) == 1 + _callback, priority = scheduled[0] + assert priority == FakeGLib.PRIORITY_HIGH + assert priority < FakeGLib.PRIORITY_DEFAULT + + class TestInitialVisibility: def test_defaults_to_visible(self) -> None: assert make_daemon()._initial_visible is True From 908af73095a268dfd68afee1e5a2f42ed2daceb5 Mon Sep 17 00:00:00 2001 From: Erwin Lejeune Date: Mon, 14 Sep 2026 16:51:06 +0000 Subject: [PATCH 3/3] Stop reload reporting failure for a change it applied `motionless config set` triggers a reload, and reload tore down and rebuilt every overlay window whether or not anything about the geometry had changed. On a loaded machine that takes longer than the control socket's three-second timeout, so the client raised while the daemon went on and applied the change correctly. The user sees an error for something that worked. The raised error also skipped whatever the caller meant to do next, which is how this surfaced: CI's smoke test never reached its `quit`, the daemon kept running, and the failure presented as a shutdown that hung. I chased that first and fixed a real but unrelated priority-inversion in the quit path before spotting the actual cause, which was two lines earlier. Reload now restyles the windows that already exist and recomputes their resting positions, and only tears anything down when the set of monitors to cover changes. Commands that do real work get a longer client timeout as defence in depth: giving up early is worse than waiting, because the work happens anyway. Reproduced by making reload take five seconds, which fails identically to CI; both the reproduction and the real smoke script pass with this. Also fixes the overlay connecting a pair of monitor-added/removed handlers on every start and never disconnecting them, and rewrites CI's timeout message, which asserted the reply had been sent when that was exactly what had not happened. --- .github/workflows/ci.yml | 9 +++-- CHANGELOG.md | 18 ++++++++++ install.sh | 60 +++++++++++++++++++++++++++----- src/motionless/cli.py | 31 ++++++++++++++--- src/motionless/ipc.py | 6 ++++ src/motionless/overlay/window.py | 41 ++++++++++++++++++---- tests/test_ipc.py | 31 +++++++++++++++++ 7 files changed, 173 insertions(+), 23 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 037e98f..7ba11e5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -126,6 +126,10 @@ jobs: assert ipc.request("toggle")["visible"] is False assert ipc.request("toggle")["visible"] is True ipc.request("reload") + + # Send quit even if something above raised, so a failure earlier + # in the script cannot leave the daemon running and disguise + # itself as a shutdown that hung. ipc.request("quit") finally: try: @@ -136,8 +140,9 @@ jobs: except subprocess.TimeoutExpired: daemon.kill() raise SystemExit( - "daemon did not stop within 45s of `quit` — the reply was " - "sent, so the main loop did not act on it" + "daemon still running 45s after the script finished. If an " + "error appears above, `quit` was never sent and that error " + "is the real failure; otherwise the main loop ignored it." ) from None assert daemon.returncode == 0, f"daemon exited {daemon.returncode}" print("smoke test passed") diff --git a/CHANGELOG.md b/CHANGELOG.md index af23335..0ee5f74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,16 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added +- `motionless sources` now names the source auto-detection would choose, and + `--auto` prints just that name for scripts. The installer uses it to say, + in the case that cannot be guessed from the overlay, that this machine has + no sensor and what to do about it. + ### Changed +- The installer's closing output explains what it found rather than listing + commands: whether a motion sensor exists, the phone route with the exact + commands when it does not, and the axis check to run parked when it does. - `motion.source = "auto"` no longer falls back to the synthetic `demo` source when no accelerometer is present. It reports no source and draws nothing instead. Cues that disagree with the vehicle you are in are a worse sensory @@ -16,6 +25,15 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). there is none. ### Fixed +- `motionless config set` and `motionless reload` reported a failure for a + change the daemon had in fact applied. Reload tore down and rebuilt every + overlay window even when nothing about the geometry had changed; on a loaded + machine that took longer than the control socket's three-second timeout, so + the client gave up while the daemon carried on and succeeded. Reload now + restyles the existing windows and only rebuilds when the set of monitors to + cover changes, and commands that do real work are allowed longer. +- The overlay connected a pair of monitor-added/removed handlers on every + start and never disconnected them, so each rebuild left another copy behind. - `motionless stop` could hang and leave the daemon running. The quit was scheduled with `GLib.idle_add`, which runs at `PRIORITY_DEFAULT_IDLE` — below the overlay's `PRIORITY_DEFAULT` redraw timer. On a machine slow diff --git a/install.sh b/install.sh index 3939109..ba003ed 100755 --- a/install.sh +++ b/install.sh @@ -269,21 +269,63 @@ post_install() { case ":$PATH:" in *":$bin:"*) ;; - *) warn "$bin is not on your PATH; add it to your shell profile" ;; + *) warn "$bin is not on your PATH; add it to your shell profile, then open a new shell" ;; esac echo - if has motionless; then - motionless doctor || true + if ! has motionless; then + warn "the 'motionless' command is not on your PATH yet — open a new shell and try again" + return 0 + fi + + info "Checking this machine" + echo + motionless doctor || true + echo + + # The one thing people need to know and cannot guess: whether there is + # anything to react to. Without a sensor the overlay is correct and idle, + # which is indistinguishable from broken unless we say so here. + local source + source="$(motionless sources --auto 2>/dev/null || true)" + + if [ "$source" = "none" ]; then + warn "No motion sensor found on this machine." + echo " This laptop has no accelerometer under /sys/bus/iio, so there is" + echo " nothing for the cues to follow. motionless will start, and draw" + echo " nothing, until you give it a source of motion." echo - info "Next steps" - echo " motionless start # run it now" - echo " motionless toggle # bind this to a hotkey" - echo " motionless service install # start with your session" - echo " motionless config edit # tune the look" + info "Use your phone instead — it has the sensor this machine lacks" + echo " 1. Put your laptop and phone on the same network (a phone hotspot is fine)." + echo " 2. Install any Android app that streams the accelerometer over UDP." + echo " 3. Point it at this machine on port 5577, then:" + echo + echo " motionless config set motion.source udp" + echo " motionless config set motion.udp.host 0.0.0.0" + echo " motionless start" + echo " motionless status # 'samples' should climb" + echo + echo " Full instructions: https://github.com/guilyx/motionless#where-the-motion-comes-from" + echo + info "To see what the cues look like without any sensor" + echo " motionless run --source demo --always-on" + echo " (a scripted drive — for previewing only, never use it in a vehicle)" else - warn "the 'motionless' command is not on your PATH yet — open a new shell and try again" + ok "Motion sensor found: $source" + echo + info "Get going" + echo " motionless start # run it now" + echo " motionless toggle # bind this to a hotkey" + echo " motionless service install # start with your session" + echo + warn "Check the axis mapping before you rely on it — parked, not driving:" + echo " motionless start" + echo " watch -n 0.3 'motionless status | grep motion'" + echo " Slide the laptop to your right: 'lat' should go positive." + echo " If it does not, see the Tuning section of the README." fi + echo + info "Anything unclear: motionless doctor | motionless --help" } uninstall() { diff --git a/src/motionless/cli.py b/src/motionless/cli.py index 0cc3afe..15bf40b 100644 --- a/src/motionless/cli.py +++ b/src/motionless/cli.py @@ -140,7 +140,12 @@ def build_parser() -> argparse.ArgumentParser: help="backdrop colour, or 'none' for a transparent PNG", ) - sub.add_parser("sources", help="list motion sources and whether they are usable") + sources = sub.add_parser("sources", help="list motion sources and whether they are usable") + sources.add_argument( + "--auto", + action="store_true", + help="print only the source auto-detection would choose, for scripts", + ) doctor = sub.add_parser("doctor", help="check this machine can run the overlay") doctor.add_argument("--json", action="store_true", help="machine-readable output") @@ -366,16 +371,32 @@ def cmd_preview(args: argparse.Namespace) -> int: return 0 -def cmd_sources(_args: argparse.Namespace) -> int: - from motionless.sources import SOURCES +def cmd_sources(args: argparse.Namespace) -> int: + from motionless.sources import SOURCES, detect + + if args.auto: + # Machine-readable and nothing else, so the installer can branch on it. + print(detect().name) + return 0 + available = probe_all() for source in SOURCES: - availability = probe_all()[source.name] + if source.name == "none": + continue + availability = available[source.name] level = Level.OK if availability.available else Level.WARN print(f"{_paint(_MARKERS[level], level)} {source.name:<6} {source.description}") if availability.detail: print(f" {availability.detail}") - print("\nSelect one with `motionless config set motion.source `.") + + chosen = detect().name + print() + if chosen == "none": + print("Auto-detection finds no sensor on this machine, so no cues will appear.") + print("Stream from a phone instead: `motionless config set motion.source udp`.") + else: + print(f"Auto-detection would use: {chosen}") + print("Override with `motionless config set motion.source `.") return 0 diff --git a/src/motionless/ipc.py b/src/motionless/ipc.py index a3c9ed3..b8a65c2 100644 --- a/src/motionless/ipc.py +++ b/src/motionless/ipc.py @@ -30,6 +30,11 @@ #: Seconds a CLI call waits for the daemon to answer. DEFAULT_TIMEOUT = 3.0 +#: Commands the daemon answers only after real work, and how long to allow. +#: Giving up early is worse than waiting: the daemon still applies the change, +#: so a timeout reports a failure for something that in fact succeeded. +SLOW_COMMANDS = {"reload": 30.0} + #: Dispatches a command name plus arguments and returns the response payload. CommandHandler = Callable[[str, dict[str, Any]], dict[str, Any]] @@ -88,6 +93,7 @@ def request( :class:`RuntimeError` if the daemon reports a failure. """ target = path or socket_file() + timeout = max(timeout, SLOW_COMMANDS.get(command, 0.0)) connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) connection.settimeout(timeout) try: diff --git a/src/motionless/overlay/window.py b/src/motionless/overlay/window.py index 6bf6c96..24e52f6 100644 --- a/src/motionless/overlay/window.py +++ b/src/motionless/overlay/window.py @@ -172,7 +172,7 @@ def __init__(self, config: Config, motion_provider: MotionProvider) -> None: fade_out=config.overlay.fade_out, always_on=config.overlay.always_on, ) - self._monitor_handler: int | None = None + self._monitor_handlers: list[int] = [] # ------------------------------------------------------------- lifecycle @@ -188,13 +188,20 @@ def start(self, *, visible: bool = True) -> None: self._build_windows() display = Gdk.Display.get_default() if display is not None: - self._monitor_handler = display.connect("monitor-added", self._on_monitors_changed) - display.connect("monitor-removed", self._on_monitors_changed) + self._monitor_handlers = [ + display.connect("monitor-added", self._on_monitors_changed), + display.connect("monitor-removed", self._on_monitors_changed), + ] if visible: self.show() def stop(self) -> None: self._stop_timer() + display = Gdk.Display.get_default() + if display is not None: + for handler in self._monitor_handlers: + display.disconnect(handler) + self._monitor_handlers = [] for window, _ in self._windows: window.destroy() self._windows = [] @@ -229,8 +236,16 @@ def toggle(self) -> bool: return self._visible def reload(self, config: Config) -> None: - """Apply a new configuration, rebuilding windows if layout changed.""" - was_visible = self._visible + """Apply a new configuration. + + Only a change of *which monitors* to cover needs the windows torn down + and rebuilt. Everything else — colour, spacing, sensitivity, frame rate + — is a matter of restyling the windows that already exist. Rebuilding + regardless made reload slow enough on a loaded machine to exceed the + control socket's timeout, so `motionless config set` reported a failure + for a change the daemon had in fact applied. + """ + previous = self._config self._config = config self._style = render.Style.from_config(config.overlay, clamp=config.motion.clamp) self._animator = render.CueAnimator( @@ -239,8 +254,20 @@ def reload(self, config: Config) -> None: fade_out=config.overlay.fade_out, always_on=config.overlay.always_on, ) - self.stop() - self.start(visible=was_visible) + + if config.overlay.monitors != previous.overlay.monitors: + was_visible = self._visible + self.stop() + self.start(visible=was_visible) + return + + # Same windows, new resting positions. + self._windows = [ + (window, render.anchors(*window.logical_size, self._style)) + for window, _ in self._windows + ] + if self._visible: + self._start_timer(config.overlay.fps) # --------------------------------------------------------------- windows diff --git a/tests/test_ipc.py b/tests/test_ipc.py index 40ffc80..5775e74 100644 --- a/tests/test_ipc.py +++ b/tests/test_ipc.py @@ -143,6 +143,37 @@ def test_garbage_does_not_kill_the_server(self, server: Harness) -> None: assert is_running(server.path) +class TestSlowCommands: + def test_reload_is_allowed_longer_than_the_default(self) -> None: + from motionless.ipc import DEFAULT_TIMEOUT, SLOW_COMMANDS + + # reload rebuilds overlay state. Giving up at the default made the CLI + # report a failure for a change the daemon had actually applied, and + # the raised error then skipped whatever the caller did next. + assert SLOW_COMMANDS["reload"] > DEFAULT_TIMEOUT + + def test_a_slow_command_is_not_cut_short_by_the_default(self, tmp_path: Path) -> None: + import time + + def slow(command: str, _args: dict[str, Any]) -> dict[str, Any]: + if command == "reload": + time.sleep(DEFAULT_TIMEOUT + 1.5) + return {"reloaded": True} + + from motionless.ipc import DEFAULT_TIMEOUT + + with Harness(tmp_path / "s.sock", slow) as harness: + started = time.monotonic() + assert request("reload", path=harness.path) == {"reloaded": True} + assert time.monotonic() - started > DEFAULT_TIMEOUT + + def test_other_commands_keep_the_short_timeout(self) -> None: + from motionless.ipc import SLOW_COMMANDS + + assert "status" not in SLOW_COMMANDS + assert "quit" not in SLOW_COMMANDS + + class TestBinding: def test_bind_creates_the_socket_owner_only(self, tmp_path: Path) -> None: with Harness(tmp_path / "nested" / "control.sock", lambda c, a: {}) as harness: