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')" />
Show set speed
+ "gx-layout-preview-visibility-v2:" + (projection ? "starport" : "comma") @@ -712,6 +712,10 @@ export const OnroadLayoutPage = { (!this.layout[id].enabled || (this.state.drag?.fromTray && this.state.drag.id === id))) }, availableProfiles() { return this.state.data?.supportedProfiles || (this.state.data?.activeProfile ? [this.state.data.activeProfile] : []) }, selectedWidget() { return this.profile?.widgets[this.state.selected] }, + canRotateWheel() { + return wheelRotationAvailable(this.selectedWidget, this.state.profile, + this.projection || this.state.data?.metadata?.projection === true) + }, sizeChoice() { const signal = this.selectedWidget?.kind === 'network_signal' return { label: signal ? 'Style' : 'Size', options: signal ? Object.keys(this.selectedWidget.sizes) : ['big', 'small'] } @@ -1424,6 +1428,17 @@ export const OnroadLayoutPage = { this.selectedPosition.opacity = value this.recordChange(before, this.state.profile + ":" + this.state.selected + ":opacity") }, + setWheelRotation(value) { + if (!this.editable || this.state.drag || this.state.layerDrag || !this.canRotateWheel || + !this.selectedPosition?.enabled || !["On", "Off"].includes(value)) return + const rotate = value === "On" + if ((this.selectedPosition.rotate === true) === rotate) return + this.finishColorEdit() + const before = clone(this.state.draft) + this.selectedPosition.rotate = rotate + this.recordChange(before) + this.state.notice = "" + }, setWidgetBackground(value) { if (!this.editable || this.state.drag || this.state.layerDrag || !this.selectedWidget?.backgroundToggle) return this.finishColorEdit() diff --git a/openpilot/starpilot/galaxy/web/js/toggle-backup.js b/openpilot/starpilot/galaxy/web/js/toggle-backup.js index 56781edc86..f4a55f3fa0 100644 --- a/openpilot/starpilot/galaxy/web/js/toggle-backup.js +++ b/openpilot/starpilot/galaxy/web/js/toggle-backup.js @@ -86,8 +86,11 @@ export const ToggleBackup = { if (legacy) { const current = await this.request("./api/ui/layout") if (current.editable !== true) throw new Error("Park the vehicle before restoring the layout.") + const wheel = draft.layouts?.large?.steering_wheel + if (wheel && typeof wheel === "object") delete wheel.rotate const result = await this.request("./api/ui/layout", { revision: current.revision, document: draft }) if (!result.valid) throw new Error("Layout restore could not be verified.") + if (result.failed?.length) throw new Error("Layout restored, but these options did not change: " + result.failed.join(", ")) this.notice = "Layout and colors restored." } else { const result = await this.request("./api/settings/restore", draft) @@ -108,7 +111,7 @@ export const ToggleBackup = { {{ notice }}{{ error }}

Restore {{ legacy ? 'layout' : 'toggles' }}?

-

{{ 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.

diff --git a/openpilot/starpilot/saved_document.py b/openpilot/starpilot/saved_document.py index dfef04f3c4..5a90bdfb2e 100644 --- a/openpilot/starpilot/saved_document.py +++ b/openpilot/starpilot/saved_document.py @@ -34,7 +34,7 @@ class WriteResult: def commit_exact(params, *, key: str, max_bytes: int, raw: bytes, expected: bytes | None, - authorized: Callable[[], bool], temp_prefix: str) -> WriteResult: + authorized: Callable[[], bool], temp_prefix: str, lock_root: Path | None = None) -> WriteResult: """Stage outside the lock; recheck authority and source before replacement.""" if not authorized(): return WriteResult(False, False) @@ -46,7 +46,7 @@ def commit_exact(params, *, key: str, max_bytes: int, raw: bytes, expected: byte committed = False try: destination = Path(params.get_param_path(key)) - root = destination.parent.parent + root = destination.parent.parent if lock_root is None else lock_root with tempfile.NamedTemporaryFile(prefix=temp_prefix, dir=root, delete=False) as stage: temporary = stage.name stage.write(raw) diff --git a/openpilot/starpilot/ui/README.md b/openpilot/starpilot/ui/README.md index 3027a820c8..5e1c1f2a1d 100644 --- a/openpilot/starpilot/ui/README.md +++ b/openpilot/starpilot/ui/README.md @@ -53,6 +53,14 @@ mounting position on actual hardware before treating a design as validated. - Reduce Quick Select motion is available for Large UI in native Appearance and Galaxy Colors & Layout. The optional `reduceMotion` boolean uses the existing validated layout document without a version bump. See [the design notes](QUICK_SELECT_DESIGN.md). +- Large UI steering wheel rotation is an opt-in widget option in Galaxy's comma + layout editor. It is stored as a device-local sidecar, starts off by default, + and is reset to off when restoring a portable layout backup. Saved layouts and + backups retain the old schema so older builds can still read them. + Only the artwork rotates, with Small UI's negative steering-angle sign; the + background and touch target stay fixed. Missing, invalid, stale, previous-drive + or offroad carState samples render upright. No additional service subscription + or polling is needed. Small UI and StarPort layouts are unchanged. - `ui_state.py` in `selfdrive/ui` follows hardwared's effective started state. Physical ignition remains separate. Camera reception, model filters and transition updates must continue when a settled opaque settings page skips diff --git a/openpilot/starpilot/ui/onroad_customization.py b/openpilot/starpilot/ui/onroad_customization.py index df999cfec8..ac533584c3 100644 --- a/openpilot/starpilot/ui/onroad_customization.py +++ b/openpilot/starpilot/ui/onroad_customization.py @@ -44,6 +44,7 @@ class WidgetPlacement(TypedDict): opacity: NotRequired[int] bluetooth: NotRequired[bool] wifiName: NotRequired[bool] + rotate: NotRequired[bool] scale: NotRequired[int] @@ -69,6 +70,7 @@ class Widget(TypedDict): sizes: NotRequired[dict[str, list[int]]] scale: NotRequired[dict[str, int]] bluetoothToggle: NotRequired[bool] + rotateToggle: NotRequired[bool] wifiNameHeight: NotRequired[int] anchorShift: NotRequired[float] expandable: NotRequired[bool] @@ -113,6 +115,8 @@ PROFILES: dict[str, LayoutProfile] = { "steering_wheel": _widget("Steering wheel", "steering_wheel", 50, 50, 21, 176), "driver_monitor": _widget("Driver monitoring", "driver_monitor", 60, 60, 16, 10)}}} +PROFILES['large']['widgets']['steering_wheel']['rotateToggle'] = True + for _profile in PROFILES: _owner = 'cruise_limits' if _profile == 'large' else 'speed_limit' PROFILES[_profile]['widgets'][_owner]['confirmation'] = confirmation_footprint(_profile) @@ -642,6 +646,9 @@ def validate_document(value): placement['y'] = bounds['y'] + bounds['height'] - JETLINK_SIZE[1] scalable = key == 'driver_monitor' or key == 'steering_wheel' and value['version'] >= 4 expected = {"x", "y", "enabled"} | ({"size"} if scalable else set()) + has_rotation = widget.get('rotateToggle') and type(placement) is dict and 'rotate' in placement + if has_rotation: + expected.add('rotate') if widget.get("box"): expected |= {"width", "height", "opacity"} elif widget.get("opacity"): @@ -652,6 +659,8 @@ def validate_document(value): expected |= {"scale", "bluetooth", "wifiName"} if type(placement) is not dict or set(placement) != expected or type(placement["enabled"]) is not bool: raise ValueError("Invalid widget placement") + if has_rotation and type(placement['rotate']) is not bool: + raise ValueError('Invalid wheel rotation setting') if widget.get("box"): validate_map_box(placement, widget) elif widget.get("opacity"): diff --git a/openpilot/starpilot/ui/onroad_large_widgets.py b/openpilot/starpilot/ui/onroad_large_widgets.py index 6865868336..3c51002c3a 100644 --- a/openpilot/starpilot/ui/onroad_large_widgets.py +++ b/openpilot/starpilot/ui/onroad_large_widgets.py @@ -7,10 +7,11 @@ retain their native anchors. See the adjacent UI LICENSE for retained source. from pathlib import Path import hashlib import json +import math from openpilot.starpilot.ui.raylib import rl -from openpilot.starpilot.ui.onroad_customization import offset, rgba, widget_size +from openpilot.starpilot.ui.onroad_customization import offset, placement, rgba, widget_size from openpilot.starpilot.ui.onroad_state import OnroadState, manual_slc_confirmation, slc_action_occludes from openpilot.starpilot.ui.onroad_widget_style import draw_control_card from openpilot.starpilot.ui.presentation import BitmapFonts, FontRole, Profile @@ -168,9 +169,15 @@ class SteeringWheelWidget: rl.draw_ring(rl.Vector2(x + radius, y + radius), radius - 3, radius, 0, 360, 64, border) feedback = self._feedback.update(state.wheel_acceleration, state.appearance.wheel_pedal_feedback, state.observed_ns, state.drive_frame) color = rl.Color(*feedback, 255) - rl.draw_texture_pro(self._texture, rl.Rectangle(0, 0, 144, 144), - rl.Rectangle(x + size / 8, y + size / 8, size * .75, size * .75), - rl.Vector2(0, 0), 0, color) + rotation = state.wheel_rotation if placement(state.customization, 'large', 'steering_wheel').get('rotate', False) else 0.0 + rotation = rotation if math.isfinite(rotation) else 0.0 + # Keep the upright draw path identical; rotate only the art around its center. + destination = rl.Rectangle(x + size / 8, y + size / 8, size * .75, size * .75) + origin = rl.Vector2(0, 0) + if rotation: + destination.x, destination.y = x + radius, y + radius + origin = rl.Vector2(size * .375, size * .375) + rl.draw_texture_pro(self._texture, rl.Rectangle(0, 0, 144, 144), destination, origin, rotation, color) def close(self) -> None: if self._texture is not None and rl.is_window_ready(): diff --git a/openpilot/starpilot/ui/onroad_state.py b/openpilot/starpilot/ui/onroad_state.py index 36978aa4cb..46361f9a77 100644 --- a/openpilot/starpilot/ui/onroad_state.py +++ b/openpilot/starpilot/ui/onroad_state.py @@ -220,6 +220,7 @@ class OnroadState: lead_indicator_source_fresh: bool = False customization: dict = field(default_factory=default_document) wheel_acceleration: float | None = None + wheel_rotation: float = 0.0 torque_source_available: bool = True torque_drive_frame: int | None = None experimental_action_token: str = "" diff --git a/openpilot/starpilot/ui/runtime_snapshot.py b/openpilot/starpilot/ui/runtime_snapshot.py index 6956a27947..f4d9896ed6 100644 --- a/openpilot/starpilot/ui/runtime_snapshot.py +++ b/openpilot/starpilot/ui/runtime_snapshot.py @@ -32,6 +32,7 @@ from openpilot.starpilot.ui.traffic_status import TrafficDisplayProjector from openpilot.starpilot.ui.drive_mode_notice import DriveModeNotice from openpilot.starpilot.controllers.mode_actions import SwitchbackStatusOwner from openpilot.starpilot.ui.wheel_feedback import observe_wheel_acceleration +from openpilot.starpilot.ui.wheel_rotation import observe_wheel_rotation, read_rotation from openpilot.starpilot.ui.torque_feedback import observe_torque_feedback from openpilot.starpilot.ui.live_developer_sidebar import DeveloperMetrics @@ -426,6 +427,10 @@ class RuntimeSnapshotAdapter: if (self._appearance_read_ns is None or now_ns < self._appearance_read_ns or now_ns - self._appearance_read_ns >= 1_000_000_000): self._customization_value = read_customization(self.ui_state.params) + rotation_raw, rotation_readable = read_rotation(self.ui_state.params) + self._customization_value['layouts']['large']['steering_wheel'].pop('rotate', None) + if rotation_readable and rotation_raw == b'1': + self._customization_value['layouts']['large']['steering_wheel']['rotate'] = True self._appearance_value = onroad_appearance(self.ui_state.params) self._navigation_enabled = _flag(self.ui_state.params, "NavigationEnabled") self._show_curve_status = _flag(self.ui_state.params, "ShowCSCStatus") @@ -749,6 +754,7 @@ class RuntimeSnapshotAdapter: torque_is_demand=torque.source == "lateral_acceleration_demand", torque_drive_frame=after if started else None, drive_frame=after if started else None, observed_ns=now_ns, wheel_acceleration=observe_wheel_acceleration(display_car), + wheel_rotation=observe_wheel_rotation(display_car), aol_latched=aol_latched, aol_armed_at_stop=armed_at_stop, lateral_active=display_lat_active, longitudinal_active=display_long_active, longitudinal_overridden=longitudinal_overridden, diff --git a/openpilot/starpilot/ui/tests/test_wheel_rotation.py b/openpilot/starpilot/ui/tests/test_wheel_rotation.py new file mode 100644 index 0000000000..e6cc4b1337 --- /dev/null +++ b/openpilot/starpilot/ui/tests/test_wheel_rotation.py @@ -0,0 +1,124 @@ +"""Large-wheel opt-in rotation, qualified samples, saved compatibility and draw geometry.""" +from dataclasses import replace +import json +from pathlib import Path +from types import SimpleNamespace as NS +from unittest.mock import Mock, patch + +import pytest + +from openpilot.common.params import Params + +from openpilot.starpilot.ui.onroad_customization import customization_metadata, default_document, decode_document, validate_document +from openpilot.starpilot.ui.onroad_large_widgets import SteeringWheelWidget +from openpilot.starpilot.ui.onroad_state import OnroadState, SpeedLimitObservation, _inside_widget +from openpilot.starpilot.ui.raylib import rl +from openpilot.starpilot.ui.runtime_snapshot import RuntimeSnapshotAdapter +from openpilot.starpilot.ui.shell import ShellMode +from openpilot.starpilot.ui.tests.test_runtime_snapshot import NOW, ui_fake +from openpilot.starpilot.ui.wheel_rotation import observe_wheel_rotation, write_rotation + + +def test_opt_in_roundtrip_and_legacy_default(): + document = default_document() + wheel = document['layouts']['large']['steering_wheel'] + old = json.dumps(document) + assert not decode_document(old)['layouts']['large']['steering_wheel'].get('rotate', False) + assert 'rotate' not in wheel # Validation must not mutate the supplied document. + wheel['rotate'] = True + assert decode_document(json.dumps(document)) == document + assert customization_metadata()['profiles']['large']['widgets']['steering_wheel']['rotateToggle'] is True + assert 'rotateToggle' not in customization_metadata()['profiles']['compact']['widgets']['steering_wheel'] + for bad in (None, 1, 'true', [], {}): + wheel['rotate'] = bad + with pytest.raises(ValueError): + validate_document(document) + wheel['rotate'] = False + for profile, key in (('compact', 'steering_wheel'), ('large', 'driver_monitor')): + other = default_document() + other['layouts'][profile][key]['rotate'] = True + with pytest.raises(ValueError): + validate_document(other) + + +def test_only_finite_valid_can_angle_uses_small_ui_sign(): + for angle in (-720., -45, 0, 45., 720): + assert observe_wheel_rotation(NS(canValid=True, canTimeout=False, steeringAngleDeg=angle)) == -angle + for angle in (None, True, '45', float('nan'), float('inf'), -float('inf')): + assert observe_wheel_rotation(NS(canValid=True, canTimeout=False, steeringAngleDeg=angle)) == 0 + for car in (None, NS(), NS(canValid=False, canTimeout=False, steeringAngleDeg=45), + NS(canValid=True, canTimeout=True, steeringAngleDeg=45)): + assert observe_wheel_rotation(car) == 0 + + +def test_runtime_rejects_stale_previous_drive_invalid_and_offroad_samples(): + ui = ui_fake() + vars(ui.sm.messages['carState']).update(canValid=True, canTimeout=False, steeringAngleDeg=45.) + adapter = RuntimeSnapshotAdapter(ui) + + def rotation(): + return adapter.build(ShellMode.ONROAD, now_ns=NOW).onroad.wheel_rotation + + assert rotation() == -45 + ui.sm.logMonoTime['carState'] = NOW - 201_000_000 + assert rotation() == 0 + ui.sm.logMonoTime['carState'] = NOW + ui.sm.recv_frame['carState'] = ui.started_frame + assert rotation() == 0 + ui.sm.recv_frame['carState'] = ui.started_frame + 1 + ui.sm.valid['carState'] = False + assert rotation() == 0 + ui.sm.valid['carState'] = True + ui.started = False + assert rotation() == 0 + + +def test_runtime_reloads_sidecar_at_existing_appearance_refresh(tmp_path): + ui = ui_fake() + ui.params = Params(str(tmp_path)) + adapter = RuntimeSnapshotAdapter(ui) + + def configured(): + return adapter.build(ShellMode.ONROAD, now_ns=NOW).onroad.customization['layouts']['large']['steering_wheel'].get('rotate', False) + + assert not configured() + assert write_rotation(ui.params, True, None, lambda: True) + assert not configured() # No extra poll between existing refreshes. + adapter.invalidate_appearance() + assert configured() + assert write_rotation(ui.params, False, b'1', lambda: True) + adapter.invalidate_appearance() + assert not configured() + + +@pytest.mark.parametrize('size', [144, 192, 240]) +def test_native_center_pivot_default_geometry_and_hit_target(size): + state = OnroadState(True, True, 10, None, SpeedLimitObservation(), wheel_rotation=-45.) + saved = state.customization['layouts']['large']['steering_wheel'] + saved.update(x=900, y=200, size=size) + wheel = SteeringWheelWidget(Path('/unused')) + wheel._texture = Mock() + with patch.object(rl, 'draw_circle') as background, patch.object(rl, 'draw_texture_pro') as draw: + wheel.render(rl.Rectangle(30, 30, 1800, 1020), state) + upright = draw.call_args.args + circle = background.call_args + assert upright[4] == 0 + assert (upright[2].x, upright[2].y) == (900 + size / 8, 200 + size / 8) + assert (upright[3].x, upright[3].y) == (0, 0) + hit_before = [_inside_widget(x, y, state, 'steering_wheel', (1588, 75, 1780, 267)) + for x, y in ((899, 200), (900, 200), (900 + size, 200 + size), (901 + size, 200))] + saved['rotate'] = True + for angle in (-45., 45., 0., float('nan')): + wheel.render(rl.Rectangle(30, 30, 1800, 1020), replace(state, wheel_rotation=angle)) + args = draw.call_args.args + assert background.call_args.args[:3] == circle.args[:3] + assert tuple(getattr(background.call_args.args[3], c) for c in 'rgba') == tuple(getattr(circle.args[3], c) for c in 'rgba') + assert tuple(getattr(args[-1], channel) for channel in 'rgba') == tuple(getattr(upright[-1], channel) for channel in 'rgba') + if angle in (-45., 45.): + assert args[4] == angle + assert (args[2].x, args[2].y) == (900 + size / 2, 200 + size / 2) + assert (args[3].x, args[3].y) == (size * .375, size * .375) + else: + assert args[4] == 0 + assert hit_before == [_inside_widget(x, y, state, 'steering_wheel', (1588, 75, 1780, 267)) + for x, y in ((899, 200), (900, 200), (900 + size, 200 + size), (901 + size, 200))] diff --git a/openpilot/starpilot/ui/wheel_rotation.py b/openpilot/starpilot/ui/wheel_rotation.py new file mode 100644 index 0000000000..6fc2d0eb43 --- /dev/null +++ b/openpilot/starpilot/ui/wheel_rotation.py @@ -0,0 +1,51 @@ +"""Display-only rotation from freshness-qualified carState, matching Small UI's sign.""" + +from collections.abc import Callable +import math +from pathlib import Path +from typing import Any + +from openpilot.starpilot.saved_document import commit_exact +from openpilot.starpilot.saved_source import read_saved + +_ROTATION_KEY = 'LargeWheelRotation' + + +class _RotationPath: + def __init__(self, params: Any): + namespace = Path(params.get_param_path('OnroadCustomizations')).parent + self.root = namespace.parent + self.destination = self.root / f'.starpilot-{namespace.name}-large-wheel-rotation' + + def get_param_path(self, key: str) -> Path: + if key != _ROTATION_KEY: + raise ValueError('Unknown wheel preference') + return self.destination + + +def read_rotation(params: Any) -> tuple[bytes | None, bool]: + try: + return read_saved(_RotationPath(params), _ROTATION_KEY, 1) + except (AttributeError, OSError, TypeError, ValueError): + return None, False + + +def write_rotation(params: Any, rotate: bool, expected: bytes | None, authorized: Callable[[], bool]) -> bool: + path = _RotationPath(params) + result = commit_exact(path, key=_ROTATION_KEY, max_bytes=1, raw=b'1' if rotate else b'0', + expected=expected, authorized=authorized, temp_prefix='.wheel-rotation-', lock_root=path.root) + return result.committed and result.verified + + +def take_rotation(document: dict) -> bool: + """Remove the device-local option from a validated editor copy before writing/exporting.""" + return document['layouts']['large']['steering_wheel'].pop('rotate', False) is True + + +def observe_wheel_rotation(car_state: Any) -> float: + """Caller owns transport freshness and drive identity; unusable samples stay upright.""" + if (car_state is None or getattr(car_state, 'canValid', None) is not True or + getattr(car_state, 'canTimeout', None) is not False): + return 0.0 + angle = getattr(car_state, 'steeringAngleDeg', None) + return -float(angle) if (type(angle) is int or type(angle) is float) and math.isfinite(angle) else 0.0 diff --git a/prebuilt.json b/prebuilt.json index 33303e6d8b..87473f3dd1 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "41a1258c0d45d18aa15940182224afd0a4c2513129a9c12cfe8ad6aa4df14d04", "schema_version": 1} +{"protected_inventory_sha256": "4cbdca3c7e2114e85118e6e4aa315af417f9fdec04c94549233755b212793fc9", "schema_version": 1}