From 08d23a48e937745cb3f1e549ac8cb515a3277bce Mon Sep 17 00:00:00 2001 From: firestar5683 <168790843+firestar5683@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:42:01 -0600 Subject: [PATCH] Add optional steering wheel rotation to Big UI --- openpilot/starpilot/galaxy/onroad_layout.py | 48 +++++-- .../galaxy/tests/test_onroad_layout.mjs | 69 ++++++++++ .../galaxy/tests/test_onroad_layout.py | 38 ++++++ .../galaxy/tests/test_toggle_backup.py | 13 ++ openpilot/starpilot/galaxy/toggle_backup.py | 9 +- .../galaxy/web/js/onroad-layout-document.js | 9 +- .../galaxy/web/js/onroad-layout-template.js | 2 + .../starpilot/galaxy/web/js/onroad-layout.js | 17 ++- .../starpilot/galaxy/web/js/toggle-backup.js | 5 +- openpilot/starpilot/saved_document.py | 4 +- openpilot/starpilot/ui/README.md | 8 ++ .../starpilot/ui/onroad_customization.py | 9 ++ .../starpilot/ui/onroad_large_widgets.py | 15 ++- openpilot/starpilot/ui/onroad_state.py | 1 + openpilot/starpilot/ui/runtime_snapshot.py | 6 + .../starpilot/ui/tests/test_wheel_rotation.py | 124 ++++++++++++++++++ openpilot/starpilot/ui/wheel_rotation.py | 51 +++++++ prebuilt.json | 2 +- 18 files changed, 409 insertions(+), 21 deletions(-) create mode 100644 openpilot/starpilot/ui/tests/test_wheel_rotation.py create mode 100644 openpilot/starpilot/ui/wheel_rotation.py diff --git a/openpilot/starpilot/galaxy/onroad_layout.py b/openpilot/starpilot/galaxy/onroad_layout.py index ad1b4ccaa5..3bd88014f8 100644 --- a/openpilot/starpilot/galaxy/onroad_layout.py +++ b/openpilot/starpilot/galaxy/onroad_layout.py @@ -12,6 +12,7 @@ from openpilot.starpilot.ui.onroad_customization import ( MAX_BYTES, PARAM_KEY, customization_metadata, decode_document, default_document, validate_document, ) from openpilot.starpilot.ui.presentation import Profile +from openpilot.starpilot.ui.wheel_rotation import read_rotation, take_rotation, write_rotation from openpilot.starpilot.galaxy.setting_descriptions import description # Display preferences edited with the layout but saved in their own params. Groups order the editor. @@ -28,8 +29,9 @@ class LayoutChanged(Exception): pass -def _revision(raw: bytes | None, rows=()) -> str: +def _revision(raw: bytes | None, rows=(), rotation: bytes | None = None) -> str: digest = hashlib.sha256(b"\x00" if raw is None else b"\x01" + raw) + digest.update(b"\x00" if rotation is None else b"\x01" + rotation) for row in rows: digest.update(repr((row.key, row.source, row.related_source, row.dependencies)).encode()) return digest.hexdigest() @@ -55,6 +57,10 @@ class OnroadLayoutOwner: document = decode_document(raw) except (ValueError, TypeError, UnicodeError, RecursionError): valid = False + rotation, rotation_readable = read_rotation(self.params) + take_rotation(document) + if rotation_readable and rotation == b'1': + document['layouts']['large']['steering_wheel']['rotate'] = True parked = self.parked() rows = self._display_rows() lead_readable = read_lead_info(self.params).readable @@ -71,8 +77,8 @@ class OnroadLayoutOwner: metadata = customization_metadata() for profile in metadata["profiles"].values(): profile["widgets"]["rear_fog"]["hidden"] = main_bus(self.vehicle_params()) is None - return {"document": document, "defaults": default_document(), "revision": _revision(raw, rows), - "metadata": metadata, "editable": readable and parked, "valid": valid, + return {"document": document, "defaults": default_document(), "revision": _revision(raw, rows, rotation), + "metadata": metadata, "editable": readable and rotation_readable and parked, "valid": valid, "activeProfile": None, "display": display, "failed": []} def save(self, payload: dict, *, session_valid: Callable[[], bool]) -> dict: @@ -87,19 +93,43 @@ class OnroadLayoutOwner: for key, value in display.items())): raise ValueError("Invalid display preferences") document = validate_document(document) + rotate = take_rotation(document) encoded = json.dumps(document, separators=(",", ":"), allow_nan=False).encode() if len(encoded) > MAX_BYTES: raise ValueError("Layout is too large") source, readable = read_saved(self.params, PARAM_KEY, MAX_BYTES) - if not readable: + rotation, rotation_readable = read_rotation(self.params) + if not readable or not rotation_readable: raise OSError("Saved layout is unavailable") - if payload["revision"] != _revision(source, tuple(rows.values())): + if payload["revision"] != _revision(source, tuple(rows.values()), rotation): raise LayoutChanged("Saved layout changed; reload before saving") - result = commit_exact(self.params, key=PARAM_KEY, max_bytes=MAX_BYTES, raw=encoded, expected=source, - authorized=lambda: session_valid() and self.parked(), temp_prefix=".onroad-layout-") - if not result.committed or not result.verified: + def authorized(): + return session_valid() and self.parked() + + # Rotation-only saves must not rewrite or create the layout document. + layout_changed = encoded != source + if layout_changed and rotate != (rotation == b'1'): + try: + current = decode_document(source) if source is not None else default_document() + take_rotation(current) + layout_changed = current != document + except (ValueError, TypeError, UnicodeError, RecursionError): + pass + if layout_changed: + result = commit_exact(self.params, key=PARAM_KEY, max_bytes=MAX_BYTES, raw=encoded, expected=source, + authorized=lambda: authorized() and read_rotation(self.params) == (rotation, True), + temp_prefix=".onroad-layout-") + if not result.committed or not result.verified: + raise LayoutChanged("Layout could not be saved; check that the device is parked and reload") + elif not authorized(): raise LayoutChanged("Layout could not be saved; check that the device is parked and reload") - failed = self._save_display(display, rows, session_valid) + expected_layout = encoded if layout_changed else source + failed = [] + if rotate != (rotation == b'1'): + if not write_rotation(self.params, rotate, rotation, + lambda: authorized() and read_saved(self.params, PARAM_KEY, MAX_BYTES) == (expected_layout, True)): + failed.append("Rotate with steering") + failed += self._save_display(display, rows, session_valid) return {**self.snapshot(), "failed": failed} def disable_map(self, session_valid: Callable[[], bool]) -> bool: diff --git a/openpilot/starpilot/galaxy/tests/test_onroad_layout.mjs b/openpilot/starpilot/galaxy/tests/test_onroad_layout.mjs index 19e2129db3..00ea1ab629 100644 --- a/openpilot/starpilot/galaxy/tests/test_onroad_layout.mjs +++ b/openpilot/starpilot/galaxy/tests/test_onroad_layout.mjs @@ -457,6 +457,75 @@ assert.equal(wheelEditor.state.draft.layouts.large.steering_wheel.size, 240) wheelEditor.resetLayout() assert.equal(wheelEditor.layout.steering_wheel.size, 50) assert.equal(wheelEditor.state.draft.layouts.large.steering_wheel.size, 240) +function rotationSnapshot() { + const sample = snapshot() + sample.metadata.profiles.large.widgets.steering_wheel.rotateToggle = true + sample.metadata.profiles.large.widgets.steering_wheel.default.rotate = false + sample.defaults.layouts.large.steering_wheel.rotate = false + return sample +} + +{ + const sample = rotationSnapshot() + assert.equal(validSnapshot(sample), true, "Version 16 documents may omit the new opt-in") + const wheel = sample.document.layouts.large.steering_wheel + wheel.rotate = true + assert.equal(validSnapshot(sample), true) + assert.equal(previewDocument(sample.document).layouts.large.steering_wheel.rotate, true) + for (const invalid of [null, "true", 1]) { + wheel.rotate = invalid + assert.equal(validSnapshot(sample), false) + } + wheel.rotate = false + sample.document.layouts.compact.steering_wheel.rotate = false + assert.equal(validSnapshot(sample), false) + delete sample.document.layouts.compact.steering_wheel.rotate + sample.metadata.profiles.compact.widgets.steering_wheel.rotateToggle = true + assert.equal(validSnapshot(sample), false) + delete sample.metadata.profiles.compact.widgets.steering_wheel.rotateToggle + sample.document.layouts.large.driver_monitor.rotate = true + assert.equal(validSnapshot(sample), false) + delete sample.document.layouts.large.driver_monitor.rotate + delete sample.metadata.profiles.large.widgets.steering_wheel.rotateToggle + assert.equal(validSnapshot(sample), false, "Capability metadata is required for the new field") +} + +{ + const { vm, calls } = editor() + vm.state.data = rotationSnapshot() + vm.state.data.supportedProfiles = ["large", "compact"] + vm.state.draft = copy(vm.state.data.document) + vm.state.selected = "steering_wheel" + assert.equal(vm.canRotateWheel, true) + vm.setWheelRotation("On") + assert.equal(vm.layout.steering_wheel.rotate, true) + vm.undo() + assert.equal(vm.layout.steering_wheel.rotate, undefined) + vm.redo() + vm.save() + assert.equal(calls.at(-1).layouts.large.steering_wheel.rotate, true) + vm.selectProfile("compact") + vm.state.selected = "steering_wheel" + assert.equal(vm.canRotateWheel, false) + vm.setWheelRotation("On") + assert.equal(vm.layout.steering_wheel.rotate, undefined) + vm.resetLayout() + assert.equal(vm.state.draft.layouts.large.steering_wheel.rotate, true) + vm.selectProfile("large") + vm.state.selected = "steering_wheel" + vm.state.data.metadata.projection = true + assert.equal(vm.canRotateWheel, false) + vm.setWheelRotation("Off") + assert.equal(vm.layout.steering_wheel.rotate, true) + delete vm.state.data.metadata.projection + vm.setWheelRotation("Off") + assert.equal(vm.layout.steering_wheel.rotate, false) + vm.setWheelRotation("On") + vm.resetLayout() + assert.equal(vm.layout.steering_wheel.rotate, false) + assert.match(ONROAD_LAYOUT_TEMPLATE, /v-if="canRotateWheel"[^\n]*Rotate with steering/) +} + const dragWheel = editor() dragWheel.vm.state.selected = "steering_wheel" dragWheel.vm.resizeSelected({ target: { value: "240" } }) diff --git a/openpilot/starpilot/galaxy/tests/test_onroad_layout.py b/openpilot/starpilot/galaxy/tests/test_onroad_layout.py index 361257c99a..1e4ebfbfce 100644 --- a/openpilot/starpilot/galaxy/tests/test_onroad_layout.py +++ b/openpilot/starpilot/galaxy/tests/test_onroad_layout.py @@ -5,6 +5,7 @@ from pathlib import Path import tempfile import threading import unittest +from unittest.mock import patch from openpilot.common.params import Params from openpilot.starpilot.galaxy.access import GalaxyAccessOwner @@ -43,6 +44,43 @@ class TestOnroadLayoutOwner(unittest.TestCase): self.assertEqual(self.params.get(PARAM_KEY), compact['document']) self.assertNotEqual(initial['revision'], result['revision']) + def test_rotation_is_local_and_never_changes_layout_bytes(self): + initial = self.owner.snapshot() + document = initial['document'] + wheel = document['layouts']['large']['steering_wheel'] + wheel['rotate'] = True + enabled = self.owner.save({'revision': initial['revision'], 'document': document}, session_valid=lambda: True) + self.assertIsNone(self.params.get(PARAM_KEY)) + self.assertTrue(enabled['document']['layouts']['large']['steering_wheel']['rotate']) + self.assertNotEqual(initial['revision'], enabled['revision']) + with self.assertRaises(LayoutChanged): + self.owner.save({'revision': initial['revision'], 'document': document}, session_valid=lambda: True) + + document['roadColors']['large']['pathMode'] = 'rainbow' + wheel.update(x=1300, y=100) + updated = self.owner.save({'revision': enabled['revision'], 'document': document}, session_valid=lambda: True) + raw = Path(self.params.get_param_path(PARAM_KEY)).read_bytes() + self.assertNotIn('rotate', json.loads(raw)['layouts']['large']['steering_wheel']) + self.assertEqual(json.loads(raw)['roadColors']['large']['pathMode'], 'rainbow') + wheel['rotate'] = False + disabled = self.owner.save({'revision': updated['revision'], 'document': document}, session_valid=lambda: True) + self.assertFalse(disabled['document']['layouts']['large']['steering_wheel'].get('rotate', False)) + self.assertEqual(Path(self.params.get_param_path(PARAM_KEY)).read_bytes(), raw) + + def test_rotation_save_failure_is_visible_without_claiming_it_applied(self): + initial = self.owner.snapshot() + initial['document']['layouts']['large']['steering_wheel']['rotate'] = True + payload = {key: initial[key] for key in ('revision', 'document')} + self.parked = False + with self.assertRaises(LayoutChanged): + self.owner.save(payload, session_valid=lambda: True) + self.parked = True + with patch('openpilot.starpilot.galaxy.onroad_layout.write_rotation', return_value=False): + failed = self.owner.save(payload, session_valid=lambda: True) + self.assertEqual(failed['failed'], ['Rotate with steering']) + self.assertFalse(failed['document']['layouts']['large']['steering_wheel'].get('rotate', False)) + self.assertIsNone(self.params.get(PARAM_KEY)) + def test_disable_map_turns_only_the_big_screen_map_off_and_only_when_it_was_on(self): self.assertFalse(self.owner.disable_map(lambda: True), 'nothing saved yet') payload = self.changed() diff --git a/openpilot/starpilot/galaxy/tests/test_toggle_backup.py b/openpilot/starpilot/galaxy/tests/test_toggle_backup.py index 9835770b1e..1a45ee353d 100644 --- a/openpilot/starpilot/galaxy/tests/test_toggle_backup.py +++ b/openpilot/starpilot/galaxy/tests/test_toggle_backup.py @@ -45,6 +45,19 @@ class ToggleBackupTest(unittest.TestCase): self.assertGreater(result['unchanged'], 20) self.assertEqual(self.fixture.params.get('GithubSshKeys'), 'private') + def test_portable_layout_excludes_rotation_and_restore_disables_it(self): + snapshot = self.layout.snapshot() + wheel = snapshot['document']['layouts']['large']['steering_wheel'] + wheel.update(x=1300, y=100, rotate=True) + saved = self.layout.save({key: snapshot[key] for key in ('document', 'revision')}, session_valid=lambda: True) + self.assertTrue(saved['document']['layouts']['large']['steering_wheel']['rotate']) + backup = self.owner.export() + self.assertNotIn('rotate', backup['layout']['layouts']['large']['steering_wheel']) + self.assertTrue(self.restore(backup)['complete']) + restored = self.layout.snapshot()['document']['layouts']['large']['steering_wheel'] + self.assertFalse(restored.get('rotate', False)) + self.assertEqual((restored['x'], restored['y']), (1300, 100)) + def test_restore_uses_existing_owner_and_validates_before_writes(self): self.fixture.params.put_bool('AlwaysAllowUploads', False, block=True) backup = self.owner.export() diff --git a/openpilot/starpilot/galaxy/toggle_backup.py b/openpilot/starpilot/galaxy/toggle_backup.py index 496f4b0ba6..b8720a3c39 100644 --- a/openpilot/starpilot/galaxy/toggle_backup.py +++ b/openpilot/starpilot/galaxy/toggle_backup.py @@ -6,6 +6,7 @@ from openpilot.starpilot.analytics.settings import _eligible, _value from openpilot.starpilot.galaxy.settings import PAGES, SettingsChanged from openpilot.starpilot.galaxy.onroad_layout import LayoutChanged from openpilot.starpilot.ui.onroad_customization import validate_document +from openpilot.starpilot.ui.wheel_rotation import take_rotation FORMAT = 'galaxy-toggles' MAX_BYTES = 256 * 1024 @@ -33,6 +34,8 @@ class ToggleBackup: values = [{'page': page, 'key': row.key, 'value': row.value} for page, row in self._rows(ctx) if _value(row, row.value) is not None] layout = self.layout.snapshot() + if layout['valid']: + take_rotation(layout['document']) result = {'format': FORMAT, 'version': 1, 'createdAt': datetime.now(UTC).isoformat(), 'metric': ctx.metric, 'vehicle': getattr(ctx.cp, 'carFingerprint', None), 'settings': values, 'layout': layout['document'] if layout['valid'] else None} @@ -60,6 +63,8 @@ class ToggleBackup: len(json.dumps(payload, allow_nan=False).encode()) > MAX_BYTES): raise ValueError('Invalid toggle backup') document = validate_document(payload['layout']) if payload['layout'] is not None else None + if document is not None: + take_rotation(document) # Portable backups never apply device-local rotation. ctx = self.settings.context.sample() if not authorized() or not ctx.parked: raise SettingsChanged('Park the vehicle before restoring toggles') @@ -115,7 +120,9 @@ class ToggleBackup: if document is not None: try: revision = self.layout.snapshot()['revision'] - self.layout.save({'revision': revision, 'document': document}, session_valid=authorized) + result = self.layout.save({'revision': revision, 'document': document}, session_valid=authorized) + if result['failed']: + raise LayoutChanged('Could not apply: ' + ', '.join(result['failed'])) except (LayoutChanged, OSError, RuntimeError) as error: return {'complete': False, 'restored': restored, 'unchanged': unchanged, 'skipped': skipped, 'error': f'Toggles restored, but the layout could not be restored: {error}'} diff --git a/openpilot/starpilot/galaxy/web/js/onroad-layout-document.js b/openpilot/starpilot/galaxy/web/js/onroad-layout-document.js index 62732ba994..7caf9f7378 100644 --- a/openpilot/starpilot/galaxy/web/js/onroad-layout-document.js +++ b/openpilot/starpilot/galaxy/web/js/onroad-layout-document.js @@ -8,6 +8,8 @@ export const PATH_MODES = ["default", "color", "rainbow", "acceleration"] export const HEX = /^#[0-9a-fA-F]{8}$/ const keysEqual = (value, keys) => value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key)) +const largeWheel = (widget, profile, projection) => !projection && profile === "large" && widget?.kind === "steering_wheel" +export const wheelRotationAvailable = (widget, profile, projection) => largeWheel(widget, profile, projection) && widget.rotateToggle === true const positive = (value) => Number.isFinite(value) && value > 0 && value <= 8192 const object = (value) => value && typeof value === "object" && !Array.isArray(value) const frontmostOrder = (order, profile) => { @@ -175,8 +177,10 @@ export function validDocument(document, metadata) { return keysEqual(layout, Object.keys(profile.widgets)) && Object.entries(layout).every(([id, position]) => { const widget = profile.widgets[id], limits = placementLimits(profile, id, layout) const resizable = widget.resizable, box = widget.box, opacity = widget.opacity + const rotate = wheelRotationAvailable(widget, name, metadata?.projection === true) && object(position) && Object.hasOwn(position, "rotate") return keysEqual(position, ["x", "y", "enabled", ...(resizable ? ["size"] : []), ...(box ? ["width", "height"] : []), - ...(opacity ? ["opacity"] : []), ...(widget.iconSize ? ["display"] : []), ...(widget.backgroundToggle ? ["background"] : []), ...(widget.collapseToggle ? ["collapse"] : []), ...(widget.bluetoothToggle ? ["bluetooth"] : []), ...(widget.wifiNameHeight ? ["wifiName"] : []), ...(widget.sizes ? ["size"] : []), ...(widget.scale ? ["scale"] : [])]) && + ...(opacity ? ["opacity"] : []), ...(widget.iconSize ? ["display"] : []), ...(widget.backgroundToggle ? ["background"] : []), ...(widget.collapseToggle ? ["collapse"] : []), ...(widget.bluetoothToggle ? ["bluetooth"] : []), ...(widget.wifiNameHeight ? ["wifiName"] : []), ...(widget.sizes ? ["size"] : []), ...(widget.scale ? ["scale"] : []), ...(rotate ? ["rotate"] : [])]) && + (!rotate || typeof position.rotate === "boolean") && (!widget.iconSize || ["words", "icons"].includes(position.display)) && (!widget.backgroundToggle || typeof position.background === "boolean") && (!widget.collapseToggle || typeof position.collapse === "boolean") && @@ -210,7 +214,7 @@ export function validSnapshot(data) { new Set(data.metadata.roadColorFields.map((field) => field.id)).size !== ROAD_COLORS.length || !data.metadata.roadColorFields.every((field) => ROAD_COLORS.includes(field.id) && typeof field.label === "string" && HEX.test(field.default)) || (data.activeProfile != null && !profiles.includes(data.activeProfile))) return false - for (const profile of Object.values(data.metadata.profiles)) { + for (const [name, profile] of Object.entries(data.metadata.profiles)) { if (profile.widgetOrder != null && (!Array.isArray(profile.widgetOrder) || profile.widgetOrder.length !== Object.keys(profile.widgets || {}).length || new Set(profile.widgetOrder).size !== profile.widgetOrder.length || @@ -264,6 +268,7 @@ export function validSnapshot(data) { !object(widget.opacity) || ![widget.opacity.min, widget.opacity.max, widget.opacity.default].every(Number.isInteger) || widget.opacity.min < 0 || widget.opacity.max > 100 || widget.opacity.min > widget.opacity.default || widget.opacity.default > widget.opacity.max)) return false + if (Object.hasOwn(widget, "rotateToggle") && !wheelRotationAvailable(widget, name, projection)) return false if (widget.collapseToggle != null && (!projection || widget.kind !== "now_playing" || widget.collapseToggle !== true)) return false if (widget.bluetoothToggle != null && (widget.kind !== "network_signal" || widget.bluetoothToggle !== true)) return false if (widget.wifiNameHeight != null && (widget.kind !== "network_signal" || !positive(widget.wifiNameHeight))) return false diff --git a/openpilot/starpilot/galaxy/web/js/onroad-layout-template.js b/openpilot/starpilot/galaxy/web/js/onroad-layout-template.js index 5d9360cc61..b32158690f 100644 --- a/openpilot/starpilot/galaxy/web/js/onroad-layout-template.js +++ b/openpilot/starpilot/galaxy/web/js/onroad-layout-template.js @@ -287,6 +287,8 @@ export const ONROAD_LAYOUT_TEMPLATE = ` :disabled="!editAvailable || !!state.drag || !!state.layerDrag" :save-value="(index, value) => setSpeedSources('speedSourcesCard', value === 'On')" />
Working…
{{ legacy ? 'Replace your saved layout and colors?' : 'Apply the compatible saved toggles, layout and colors from this backup? Unavailable settings will be skipped.' }} Keep the vehicle parked.
+{{ legacy ? 'Replace your saved layout and colors?' : 'Apply the compatible saved toggles, layout and colors from this backup? Unavailable settings will be skipped.' }} Keep the vehicle parked. Restoring a layout turns off Big UI steering wheel rotation.