From 602b54181c4879460eaaf9342b0a28c2d1af3d32 Mon Sep 17 00:00:00 2001 From: Danny Date: Fri, 20 Nov 2026 19:07:48 -0600 Subject: [PATCH] Widgets: Load Faster, Keep Scenes in Sync, Tighter Speed Outline, Fix Clicking on Desktop --- openpilot/starpilot/galaxy/batch_routes.py | 7 ++ openpilot/starpilot/galaxy/http_server.py | 2 +- .../galaxy/tests/browser/layout-scenes.cjs | 6 +- .../galaxy/tests/browser/widget-layers.cjs | 16 +++- .../galaxy/tests/test_layout_preview.mjs | 12 +++ .../galaxy/tests/test_layout_preview_http.py | 51 ++++++++-- .../tests/test_native_navigation_widgets.mjs | 2 +- .../galaxy/tests/test_onroad_layout.mjs | 28 +++++- .../galaxy/tests/test_widget_art.mjs | 40 +++++++- .../starpilot/galaxy/web/js/layout-preview.js | 94 +++++++++++++++---- .../galaxy/web/js/onroad-layout-template.js | 14 +-- .../starpilot/galaxy/web/js/onroad-layout.js | 59 +++++++----- .../system/starport/projection_layout.py | 1 + .../starpilot/ui/layout_preview_renderer.py | 54 +++++++++-- .../ui/tests/test_layout_preview_renderer.py | 27 ++++++ .../ui/tests/test_layout_preview_transport.py | 4 +- .../ui/tests/test_layout_widget_art.py | 21 ++++- prebuilt.json | 2 +- 18 files changed, 357 insertions(+), 83 deletions(-) diff --git a/openpilot/starpilot/galaxy/batch_routes.py b/openpilot/starpilot/galaxy/batch_routes.py index de33961457..a16db9274d 100644 --- a/openpilot/starpilot/galaxy/batch_routes.py +++ b/openpilot/starpilot/galaxy/batch_routes.py @@ -1,5 +1,7 @@ """Galaxy stored-record, layout-preview and drive-state HTTP routes.""" +import hashlib + from openpilot.starpilot.galaxy.crash_reports import CrashChanged, CrashMissing, CrashUnavailable from openpilot.starpilot.galaxy.settings import SettingsChanged, SettingsUnavailable from openpilot.starpilot.galaxy.sentry_events import ID as SENTRY_EVENT_ID, SentryEventsUnavailable @@ -108,6 +110,11 @@ def preview_layout(self, payload, projection_layout_owner, layout_owner, layout_ else: headers, cache = {}, None if payload.get('art') is True: + digest = hashlib.sha256(image).hexdigest() + if self.headers.get('X-Widget-Digest') == digest: + self.respond(204, b'', cache_control='no-store') + return + headers['X-Widget-Digest'] = digest # Proxies that re-encode PNGs drop the tEXt chunk, so the sprite sheet also rides in a header. header = widget_art_header(image) if header: diff --git a/openpilot/starpilot/galaxy/http_server.py b/openpilot/starpilot/galaxy/http_server.py index 08dec20e0c..359b5122e1 100644 --- a/openpilot/starpilot/galaxy/http_server.py +++ b/openpilot/starpilot/galaxy/http_server.py @@ -236,7 +236,7 @@ class _LocalHTTPHandler(BaseHTTPRequestHandler): def respond(self, status, body, content_type='application/json', cookie=None, *, asset_headers=None, cache_control=None): self.send_response(status) self.send_header('Content-Type', content_type) - if status != 304: + if status not in (204, 304): self.send_header('Content-Length', str(len(body))) self.send_header('Cache-Control', cache_control or ('private, max-age=0, must-revalidate' if asset_headers else 'no-store')) for key, value in (asset_headers or {}).items(): diff --git a/openpilot/starpilot/galaxy/tests/browser/layout-scenes.cjs b/openpilot/starpilot/galaxy/tests/browser/layout-scenes.cjs index d220dc3bd4..81ad2f123a 100644 --- a/openpilot/starpilot/galaxy/tests/browser/layout-scenes.cjs +++ b/openpilot/starpilot/galaxy/tests/browser/layout-scenes.cjs @@ -53,8 +53,10 @@ print(json.dumps(dict(native=native,projection=projection))) // Choose scenes through the real accessible dropdown. await page.getByRole('combobox', { name: 'Preview scene', exact: true }).click() await page.getByRole('option', { name: scene.label, exact: true }).click() - // After the first render, a scene switch keeps native artwork up instead of falling back to outlines. - if (nativeArt && scene !== scenes[0]) assert.equal(await page.locator('[data-preview-source="placeholder"]').count(), 0, `${target}/${scene.id}: no outlines while loading`) + if (!nativeArt) { + assert.equal(await page.locator('.gx-layout__widget [data-preview-source="sketch"]').count(), + await page.evaluate(() => window.editor.renderWidgets.filter(w => !window.editor.profile.runtimePreviewWidgets.includes(w.id)).length), `${target}/${scene.id}: each widget has artwork without a device render`) + } if (nativeArt) await page.waitForFunction(() => window.editor.state.backdrop.scene === window.editor.state.scene && window.editor.state.backdrop.status === 'ready' && window.editor.state.art.scene === window.editor.state.scene && window.editor.state.art.status === 'ready') const state = await page.evaluate(() => ({ scene: window.editor.state.scene, border: window.editor.sceneBorder, diff --git a/openpilot/starpilot/galaxy/tests/browser/widget-layers.cjs b/openpilot/starpilot/galaxy/tests/browser/widget-layers.cjs index a6260cd99d..260982c54e 100644 --- a/openpilot/starpilot/galaxy/tests/browser/widget-layers.cjs +++ b/openpilot/starpilot/galaxy/tests/browser/widget-layers.cjs @@ -35,6 +35,16 @@ const projection = JSON.parse(execFileSync(process.env.PYTHON || 'python3', ['-c await page.goto('http://layers.test/') const rows = page.locator('.gx-layout__layer') await rows.first().waitFor() + const speed = page.locator('.gx-layout__widget[aria-label^="Current speed,"]') + await speed.click() + await page.getByRole('combobox', {name:/^Selected widget/}).waitFor() + assert.equal(await speed.getAttribute('aria-pressed'), 'true') + assert.equal(await page.evaluate(() => window.editor.state.selected), 'current_speed') + const preview = page.locator('svg.gx-layout__preview') + const previewBox = await preview.boundingBox() + await preview.click({position:{x:previewBox.width / 2, y:previewBox.height - 10}}) + assert.equal(await speed.getAttribute('aria-pressed'), 'false') + await page.getByRole('button', {name:'Widgets', exact:true}).click() const initial = await rows.locator('.gx-layout__layer-name').allTextContents() const initialIds = await rows.evaluateAll(elements => elements.map(row => row.dataset.layerId)) assert.match(initialIds[0], /^pip_/, 'side cameras start locked in front') @@ -209,7 +219,7 @@ const projection = JSON.parse(execFileSync(process.env.PYTHON || 'python3', ['-c assert.equal(await page.evaluate(() => window.editor.state.draft.layouts.large.nav_work.display), 'words') const homePreview = page.locator('svg.gx-layout__preview .gx-layout__widget').filter({has:page.locator('.gx-layout__hit[width="110"]')}) assert.equal(await homePreview.count(), 1) - assert.equal(await homePreview.locator('.gx-layout-widget-art path').count(), 1) + assert.equal(await homePreview.locator('[data-preview-source="sketch"]').count(), 0) assert.equal(await homePreview.locator('.gx-layout-widget-art text').count(), 0) await page.getByRole('button', {name:'Undo', exact:true}).click() assert.equal(await page.evaluate(() => window.editor.state.draft.layouts.large.nav_home.display), 'words') @@ -234,8 +244,8 @@ const projection = JSON.parse(execFileSync(process.env.PYTHON || 'python3', ['-c await opacity.dispatchEvent('change') const bookmarkPreview = page.locator('.gx-layout__widget[aria-label^="Bookmark"] .gx-layout-widget-art') assert.equal(await bookmarkPreview.locator('rect').count(), 0) - assert.equal(await bookmarkPreview.locator('path').count(), 1) - assert.equal(await bookmarkPreview.locator('g[opacity="0.45"]').count(), 1) + assert.equal(await bookmarkPreview.locator('[data-preview-source="sketch"]').count(), 0) + assert.equal(await page.evaluate(() => window.editor.layout.bookmark.opacity), 45) assert.equal(await page.evaluate(() => window.editor.layout.nav_work.opacity), 100) await page.getByRole('button', {name:'Undo', exact:true}).click() assert.equal(await opacity.inputValue(), '100') diff --git a/openpilot/starpilot/galaxy/tests/test_layout_preview.mjs b/openpilot/starpilot/galaxy/tests/test_layout_preview.mjs index 6a21b7f9fe..e45b8ea402 100644 --- a/openpilot/starpilot/galaxy/tests/test_layout_preview.mjs +++ b/openpilot/starpilot/galaxy/tests/test_layout_preview.mjs @@ -128,7 +128,19 @@ backdrop.feed.update(moved, "large", "aol", false, { palette: document.palette } assert.equal(backdrop.timers.size, 0) backdrop.feed.update(moved, "large", "braking", false, { palette: document.palette }) assert.equal(backdrop.timers.size, 1) +backdrop.tick() +await backdrop.reply(1) +assert.deepEqual([backdrop.updates.at(-1).scene, backdrop.updates.at(-1).profile], ["braking", "large"]) +const aolScreen = backdrop.feed.artCache.get("large\naol").url +backdrop.feed.update(moved, "large", "aol", false, { palette: document.palette }) +assert.equal(backdrop.timers.size, 0, "returning to a scene reuses its screen") +assert.equal(backdrop.requests.length, 2) +assert.equal(backdrop.updates.findLast(update => update.url !== undefined).url, aolScreen) +assert.equal(backdrop.updates.at(-1).status, "ready") +backdrop.feed.start() +assert.ok(backdrop.feed.artCache.has("large\nbraking"), "restarting keeps the screens") backdrop.feed.stop() +assert.equal(backdrop.feed.artCache.size, 0) const late = fixture() late.feed.start(); late.feed.update(document, "large", "engaged"); late.tick(); late.feed.stop(); await late.reply(0) diff --git a/openpilot/starpilot/galaxy/tests/test_layout_preview_http.py b/openpilot/starpilot/galaxy/tests/test_layout_preview_http.py index deff32054f..dfb54d9cf5 100644 --- a/openpilot/starpilot/galaxy/tests/test_layout_preview_http.py +++ b/openpilot/starpilot/galaxy/tests/test_layout_preview_http.py @@ -1,3 +1,5 @@ +import base64 +import hashlib import http.client import json from pathlib import Path @@ -5,12 +7,13 @@ import tempfile import threading import time import unittest -from typing import TypedDict +from typing import NotRequired, TypedDict from openpilot.common.params import Params from openpilot.starpilot.galaxy.access import GalaxyAccessOwner from openpilot.starpilot.galaxy.onroad_layout import OnroadLayoutOwner -from openpilot.starpilot.galaxy.server import make_server +from openpilot.starpilot.galaxy.remote import RemotePairing +from openpilot.starpilot.galaxy.server import make_remote_server, make_server from openpilot.starpilot.ui.layout_preview_transport import PreviewService from openpilot.starpilot.ui.onroad_customization import PARAM_KEY, default_document from openpilot.starpilot.ui.tests.test_layout_preview_transport import png @@ -20,6 +23,7 @@ class PreviewPayload(TypedDict): document: dict profile: str scene: str + art: NotRequired[bool] class TestLayoutPreviewHttp(unittest.TestCase): @@ -31,12 +35,13 @@ class TestLayoutPreviewHttp(unittest.TestCase): self.params = Params(str(root / 'params')) self.parked = True self.owner = OnroadLayoutOwner(self.params, lambda: self.parked) + self.pairing = RemotePairing(root / 'pairing') self.rendered = [] self.preview = PreviewService(lambda payload: self.rendered.append(payload) or png(), lambda: self.parked, self.socket_path, active_profile='large') self.preview.start() self.addCleanup(self.preview.close) - self.server = make_server(port=0, owner=GalaxyAccessOwner(root / 'access'), layouts=self.owner, + self.server = make_server(port=0, owner=GalaxyAccessOwner(root / 'access'), layouts=self.owner, remote_pairing=self.pairing, layout_preview_socket=self.socket_path) self.worker = threading.Thread(target=self.server.serve_forever, kwargs={'poll_interval': .01}, daemon=True) self.worker.start() @@ -48,12 +53,17 @@ class TestLayoutPreviewHttp(unittest.TestCase): self.worker.join(timeout=2) self.server.server_close() - def request(self, path, payload=None, cookie='', *, origin=None, raw=None): - connection = http.client.HTTPConnection('127.0.0.1', self.server.server_port, timeout=4) + def request(self, path, payload=None, cookie='', *, origin=None, raw=None, server=None, host=None, digest=None): + port = (server or self.server).server_port + connection = http.client.HTTPConnection('127.0.0.1', port, timeout=4) headers = {'Cookie': cookie} + if digest: + headers['X-Widget-Digest'] = digest + if host: + headers['Host'] = host body = raw if raw is not None else json.dumps(payload) if payload is not None else None if body is not None: - headers.update({'Content-Type': 'application/json', 'Origin': origin or f'http://127.0.0.1:{self.server.server_port}'}) + headers.update({'Content-Type': 'application/json', 'Origin': origin or f'http://127.0.0.1:{port}'}) try: connection.request('POST' if body is not None else 'GET', path, body=body, headers=headers) response = connection.getresponse() @@ -66,9 +76,9 @@ class TestLayoutPreviewHttp(unittest.TestCase): self.assertEqual(status, 200) return headers['Set-Cookie'].split(';', 1)[0] - def preview_with_pump(self, cookie): + def preview_with_pump(self, cookie, path='/api/ui/layout/preview', **kwargs): outcome = {} - client = threading.Thread(target=lambda: outcome.setdefault('response', self.request('/api/ui/layout/preview', self.payload, cookie))) + client = threading.Thread(target=lambda: outcome.setdefault('response', self.request(path, self.payload, cookie, **kwargs))) client.start() deadline = time.monotonic() + 4 while client.is_alive() and time.monotonic() < deadline: @@ -77,6 +87,31 @@ class TestLayoutPreviewHttp(unittest.TestCase): self.assertFalse(client.is_alive()) return outcome['response'] + def test_firestar_widget_sheet_preserves_pixels_and_metadata(self): + slug = self.pairing.pair(hashlib.sha256(b'preview-password').hexdigest()) + record = self.pairing.read() + assert record is not None + cookie = f"galaxy_session={slug}%3A{record['session']}" + metadata = {'version': 1, 'width': 1, 'height': 1, 'sprites': {'current_speed': {'x': 0, 'y': 0, 'width': 1, 'height': 1}}} + image = png(1, 1, widget_art=metadata) + self.preview.renderer = lambda _: image + self.payload['art'] = True + with make_remote_server(self.server, port=0) as remote: + worker = threading.Thread(target=remote.serve_forever, kwargs={'poll_interval': .01}, daemon=True) + worker.start() + try: + status, body, headers = self.preview_with_pump(cookie, f'/{slug}/api/ui/layout/preview', server=remote, + host='galaxy.firestar.link', origin='https://galaxy.firestar.link') + repeat = self.preview_with_pump(cookie, f'/{slug}/api/ui/layout/preview', server=remote, + host='galaxy.firestar.link', origin='https://galaxy.firestar.link', digest=headers['X-Widget-Digest']) + self.assertEqual(repeat[:2], (204, b'')) + finally: + remote.shutdown() + worker.join(timeout=2) + self.assertEqual((status, body), (200, image)) + self.assertEqual(headers['Cache-Control'], 'no-store, no-transform') + self.assertEqual(json.loads(base64.b64decode(headers['X-Widget-Art'])), metadata) + def test_live_profile_png_and_no_saved_write(self): cookie = self.login() status, body, _ = self.request('/api/ui/layout', cookie=cookie) diff --git a/openpilot/starpilot/galaxy/tests/test_native_navigation_widgets.mjs b/openpilot/starpilot/galaxy/tests/test_native_navigation_widgets.mjs index b2f7eb6ecb..cc6d7cb705 100644 --- a/openpilot/starpilot/galaxy/tests/test_native_navigation_widgets.mjs +++ b/openpilot/starpilot/galaxy/tests/test_native_navigation_widgets.mjs @@ -190,7 +190,7 @@ function previewText(node) { for (const size of ["ring", "horizontal", "vertical"]) { for (const bluetooth of [true, false]) { const tree = renderSignal({ widget: { kind: "network_signal", size, width: 268, height: 196, bluetooth }, - palette: {}, profile: "large", scene: "engaged", native: false, art: null }, []) + palette: {}, profile: "large", scene: "engaged", sprite: null, native: false }, []) const text = previewText(tree) assert.equal(text.includes("iPhone 15"), bluetooth, `${size} Bluetooth preview follows the toggle`) if (!bluetooth) assert(!text.includes("Connected") && !text.includes("AirPods")) diff --git a/openpilot/starpilot/galaxy/tests/test_onroad_layout.mjs b/openpilot/starpilot/galaxy/tests/test_onroad_layout.mjs index 00ea1ab629..4b6f6dc102 100644 --- a/openpilot/starpilot/galaxy/tests/test_onroad_layout.mjs +++ b/openpilot/starpilot/galaxy/tests/test_onroad_layout.mjs @@ -267,9 +267,9 @@ for (const pointerType of ["mouse", "touch"]) { assert.equal(soft.state.drag, null, "a cancelled press never grabs later") soft.state.touchArmed = "current_speed" soft.state.selected = "current_speed" - soft.previewClick({ target: { closest: () => ({}) } }) + soft.previewPointerDown({ button: 0, target: { closest: () => ({}) } }) assert.equal(soft.state.selected, "current_speed", "tapping a widget keeps it selected") - soft.previewClick({ target: { closest: () => null } }) + soft.previewPointerDown({ button: 0, target: { closest: () => null } }) assert.equal(soft.state.selected, null, "tapping empty preview space lets go of the widget") assert.equal(soft.state.touchArmed, null) } @@ -937,7 +937,29 @@ assert.equal(OnroadLayoutPage.template, ONROAD_LAYOUT_TEMPLATE, "the page uses t assert.equal(OnroadLayoutPage.components.LayoutWidgetPreview, LayoutWidgetPreview, "the template preview uses the actual component") assert.match(OnroadLayoutPage.template, / + OnroadLayoutPage.computed.layers.call({ projection: false, state: { profile, art, backdrop }, + artFeed: { artCache }, backdropFeed: { artCache: screens } }) + const art = { url: "blob:art-engaged", sprites: { sprites: { a: 1 } }, scene: "engaged", profile: "large", status: "ready" } + const backdrop = { url: "blob:screen-pending", scene: "slc_pending", profile: "large", status: "ready" } + const matched = { ...backdrop, scene: "engaged" } + assert.deepEqual(layers(art, matched), { art, backdrop: matched }, "a matched pair is shown as is") + const sheets = new Map([["large\nslc_pending", { url: "blob:art-pending", sprites: { sprites: { b: 2 } }, scene: "slc_pending" }]]) + const fromSheet = layers(art, backdrop, sheets) + assert.deepEqual([fromSheet.art.url, fromSheet.art.scene, fromSheet.backdrop.url], ["blob:art-pending", "slc_pending", "blob:screen-pending"]) + const screens = new Map([["large\nengaged", { url: "blob:screen-engaged", scene: "engaged" }]]) + const fromScreen = layers(art, backdrop, new Map(), screens) + assert.deepEqual([fromScreen.art.url, fromScreen.backdrop.url, fromScreen.backdrop.scene], ["blob:art-engaged", "blob:screen-engaged", "engaged"]) + const neither = layers(art, backdrop) + assert.equal(neither.art.url, null, "never draw one scene's widgets over another scene's screen") + assert.equal(neither.art.sprites, null) + const otherProfile = { ...backdrop, profile: "compact" } + assert.deepEqual(layers(art, otherProfile), { art, backdrop: otherProfile }, "a screen from another layout is not paired") + assert.deepEqual(layers({ ...art, url: null }, backdrop).backdrop, backdrop) +} assert.doesNotMatch(editorSource, /devicePreviewOpen|gx-layout__device|selectPreview/) assert.doesNotMatch(OnroadLayoutPage.template, /devicePreviewOpen|gx-layout__device|selectPreview/) const loadedCatalog = await loadCatalog({ fetcher: async (url) => ({ ok: true, diff --git a/openpilot/starpilot/galaxy/tests/test_widget_art.mjs b/openpilot/starpilot/galaxy/tests/test_widget_art.mjs index 290431337e..fa10e4aa1f 100644 --- a/openpilot/starpilot/galaxy/tests/test_widget_art.mjs +++ b/openpilot/starpilot/galaxy/tests/test_widget_art.mjs @@ -176,10 +176,44 @@ assert(artUrl) page.state.data.editable=false assert.equal(page.artFeed.active,false);assert.equal(page.state.art.url,null,'Parked authority changes clear artwork') page.artFeed.stop() -assert.equal(OnroadLayoutPage.methods.runtimeWidget.call({profile:{runtimePreviewWidgets:['conditional_mode']}},'conditional_mode'),true) -assert.equal(OnroadLayoutPage.methods.runtimeWidget.call({profile:{}},'conditional_mode'),false) assert.match(LayoutWidgetPreview.template,/data-preview-source="runtime"/) -assert.match(LayoutWidgetPreview.template,/data-preview-source="placeholder"/) +assert.match(LayoutWidgetPreview.template,/data-preview-source="sketch"/) assert.doesNotMatch(LayoutWidgetPreview.template,/scene === 'experimental' \? 'E' : 'C'/) assert.doesNotMatch(LayoutWidgetPreview.template,/M38 78 Q96 107 154 78/) console.log('Canonical widget art: metadata, races, retained refreshes, profile/mode switches, retries, auth and cleanup passed') + +{ + const entries = new Map() + const store = {load: async key => entries.get(key), save: async (key, value) => { entries.set(key, value) }, remove: async key => { entries.delete(key) }} + for (const revisit of [false, true]) { + const page = fixture() + const feed = new LayoutPreviewFeed({...page.options, store}) + feed.start() + feed.update(document, 'compact', 'general') + page.tick() + for (let i=0; i<20 && !page.requests.length; i++) await new Promise(resolve=>setTimeout(resolve, 5)) + const request = page.requests[0] + assert.equal(request.options.headers['X-Widget-Digest'], revisit ? 'same-sheet' : undefined) + if (revisit) assert.deepEqual(page.updates.at(-1).sprites, meta, 'Saved sheet shows before the device answers') + else assert.equal(page.updates.some(update => update.sprites), false) + request.resolve(revisit ? new Response(null, {status:204}) : + new Response(image(), {headers:{'Content-Type':'image/png','X-Widget-Digest':'same-sheet'}})) + for (let i=0; i<20 && page.updates.at(-1).status !== 'ready'; i++) await new Promise(resolve=>setTimeout(resolve, 5)) + assert.equal(page.updates.at(-1).status, 'ready') + assert.deepEqual(page.updates.at(-1).sprites, meta) + for (let i=0; i<20 && !entries.size; i++) await new Promise(resolve=>setTimeout(resolve, 5)) + assert.equal([...entries.values()][0].digest, 'same-sheet') + feed.stop() + } +} +{ + const page = fixture() + const feed = new LayoutPreviewFeed({...page.options, store: {load: async () => ({digest: 'bad', art: null, png: new ArrayBuffer(4)}), + save: async () => {}, remove: async () => { page.removed = true }}}) + feed.start(); feed.update(document, 'compact', 'general'); page.tick() + for (let i=0; i<20 && !page.requests.length; i++) await new Promise(resolve=>setTimeout(resolve, 5)) + assert.equal(page.requests[0].options.headers['X-Widget-Digest'], undefined, 'A corrupt saved sheet is dropped, not revalidated') + assert.equal(page.removed, true) + feed.stop() +} +console.log('Saved widget sheets: instant revisit, digest revalidation and corrupt-entry cleanup passed') diff --git a/openpilot/starpilot/galaxy/web/js/layout-preview.js b/openpilot/starpilot/galaxy/web/js/layout-preview.js index c88a32322f..571b2b76a0 100644 --- a/openpilot/starpilot/galaxy/web/js/layout-preview.js +++ b/openpilot/starpilot/galaxy/web/js/layout-preview.js @@ -84,18 +84,43 @@ export class PreviewQueue { release() { this.running = false; this.next() } } +// Saved widget sheets per device path, profile and scene. +export function widgetArtStore(indexedDB = globalThis.indexedDB) { + if (!indexedDB) return null + let opened = null + const database = () => opened ||= new Promise((resolve, reject) => { + const request = indexedDB.open("galaxy-widget-art", 1) + request.onupgradeneeded = () => request.result.createObjectStore("sheets") + request.onsuccess = () => resolve(request.result) + request.onerror = () => reject(request.error) + request.onblocked = () => reject(new Error("Widget art storage is blocked")) + }) + const run = (mode, action) => database().then(db => new Promise((resolve, reject) => { + const transaction = db.transaction("sheets", mode) + const request = action(transaction.objectStore("sheets")) + transaction.oncomplete = () => resolve(request.result) + transaction.onerror = transaction.onabort = () => reject(transaction.error) + })) + return { + load: key => run("readonly", store => store.get(key)), + save: (key, value) => run("readwrite", store => store.put(value, key)), + remove: key => run("readwrite", store => store.delete(key)), + } +} + export class LayoutPreviewFeed { constructor({ publish, unauthorized = () => {}, fetcher = (...args) => fetch(...args), later = (fn, ms) => setTimeout(fn, ms), cancelTimer = (id) => clearTimeout(id), - urls = URL, art = false, backdrop = false, queue = null }) { - Object.assign(this, { publish, unauthorized, fetcher, later, cancelTimer, urls, art, backdrop, queue }) + urls = URL, art = false, backdrop = false, queue = null, + store = art && typeof window !== "undefined" ? widgetArtStore(window.indexedDB) : null }) { + Object.assign(this, { publish, unauthorized, fetcher, later, cancelTimer, urls, art, backdrop, queue, store }) this.active = false this.version = 0 this.timer = null this.request = null this.currentUrl = null this.pending = null - // Keep one native sheet per profile and scene, so returning to either is instant. + // Keep one image per profile and scene, so returning to either is instant. this.artCache = new Map() // The sheet last shown for a profile stands in for a scene that has not rendered yet. this.latestArt = new Map() @@ -132,7 +157,7 @@ export class LayoutPreviewFeed { this.publish({ url: null, ...(this.art ? {sprites: null} : {}) }) } - start() { if (this.art) this.pause(); else this.stop(); this.active = true } + start() { if (this.art || this.backdrop) this.pause(); else this.stop(); this.active = true } // `key` stands in for the document when only part of it changes the image (the backdrop ignores positions). update(document, profile, scene, dragging = false, key = document) { @@ -142,7 +167,7 @@ export class LayoutPreviewFeed { if (inputKey === this.inputKey) return this.inputKey = inputKey // Picking a scene or screen is one discrete change, so only document edits are debounced. - const debounce = documentKey === this.documentKey ? 0 : 200 + const debounce = this.documentKey && documentKey !== this.documentKey ? 200 : 0 this.documentKey = documentKey this.version++ if (this.timer !== null) this.cancelTimer(this.timer) @@ -152,12 +177,12 @@ export class LayoutPreviewFeed { if (dragging) { this.publish({ status: "editing", error: "" }); return } const renderKey = JSON.stringify([documentKey, profile, scene]) if (renderKey !== this.failureKey) { this.failureKey = renderKey; this.failures = 0 } - if (this.art) { + if (this.art || this.backdrop) { const cacheKey = profile + "\n" + scene, cached = this.artCache.get(cacheKey) if (cached) this.latestArt.set(profile, cacheKey) const shown = cached || this.artCache.get(this.latestArt.get(profile)) this.currentUrl = shown?.url || null - this.publish({ url: this.currentUrl, sprites: shown?.sprites || null, scene: shown?.scene || null, profile }) + this.publish({ url: this.currentUrl, ...(this.art ? {sprites: shown?.sprites || null} : {}), scene: shown?.scene || null, profile }) if (cached?.key === renderKey) { this.publish({ status: "ready", error: "" }) return @@ -189,28 +214,61 @@ export class LayoutPreviewFeed { request.signal.addEventListener("abort", rejectAborted, { once: true }) let failure = "Preview is unavailable. Reconnecting automatically…" let denied = false, busy = false + const stale = () => !this.active || item.version !== this.version || request.signal.aborted const work = (async () => { + const cacheKey = item.profile + "\n" + item.scene + const slot = this.store && (typeof location !== "undefined" ? location.pathname : "") + "\n" + cacheKey + let saved = null + if (slot) { + try { + const record = await Promise.race([this.store.load(slot), new Promise(resolve => setTimeout(resolve, 500))]) + if (record?.digest && record.png instanceof ArrayBuffer) saved = { ...record, blob: new Blob([record.png], { type: "image/png" }) } + } catch { /* Browser storage is optional in private sessions. */ } + if (stale()) return + // Show the last saved sheet at once; the device confirms or replaces it below. + if (saved && !this.artCache.has(cacheKey)) { + const sprites = await widgetArtMetadata(saved.blob, saved.art).catch(() => null) + if (stale()) return + if (sprites) { + const url = this.urls.createObjectURL(saved.blob) + this.artCache.set(cacheKey, { key: null, url, sprites, scene: item.scene }) + this.latestArt.set(item.profile, cacheKey) + this.currentUrl = url + this.publish({ url, sprites, scene: item.scene, profile: item.profile }) + } else { + saved = null + this.store.remove(slot).catch(() => {}) + } + } + } const held = !!this.queue && await this.queue.acquire(this.art ? 0 : 1, request.signal).then(() => true) try { timeout = this.later(() => request.abort(), PREVIEW_TIMEOUT_MS) + const digest = saved?.digest const response = await this.fetcher("./api/ui/layout/preview", { method: "POST", credentials: "same-origin", - cache: "no-store", headers: { "Content-Type": "application/json" }, + cache: "no-store", headers: { "Content-Type": "application/json", ...(digest ? {"X-Widget-Digest": digest} : {}) }, body: JSON.stringify({ document: item.document, profile: item.profile, scene: item.scene, ...(this.art ? {art: true} : this.backdrop ? {art: "backdrop"} : {}) }), signal: request.signal }) - if (!this.active || item.version !== this.version || request.signal.aborted) return + if (stale()) return if (response.status === 401) { this.stop(); this.unauthorized(); return } if (response.status === 403) { denied = true; failure = "Turn off the vehicle to preview this layout."; throw new Error() } if (response.status === 429) { busy = true; failure = "Preview is busy. Retrying automatically…"; throw new Error() } - if (!response.ok) { const detail = await response.json().catch(() => null); failure = detail?.error || failure; throw new Error() } - if (!response.headers.get("Content-Type")?.toLowerCase().startsWith("image/png")) throw new Error("Preview is unavailable. Reconnecting automatically…") - const blob = await response.blob() - if (!this.active || item.version !== this.version || request.signal.aborted) return + const reuse = response.status === 204 && !!saved + if (!reuse && !response.ok) { const detail = await response.json().catch(() => null); failure = detail?.error || failure; throw new Error() } + if (!reuse && !response.headers.get("Content-Type")?.toLowerCase().startsWith("image/png")) throw new Error("Preview is unavailable. Reconnecting automatically…") + const blob = reuse ? saved.blob : await response.blob() + if (stale()) return if (!blob.size || blob.size > 4 * 1024 * 1024) throw new Error("Preview is unavailable. Reconnecting automatically…") - const sprites = this.art ? await widgetArtMetadata(blob, response.headers.get("X-Widget-Art")) : null - if (!this.active || item.version !== this.version || request.signal.aborted) return - const cacheKey = item.profile + "\n" + item.scene - const previousUrl = this.art ? this.artCache.get(cacheKey)?.url : this.currentUrl + const art = reuse ? saved.art : response.headers.get("X-Widget-Art") + const sprites = this.art ? await widgetArtMetadata(blob, art) : null + if (stale()) return + const newDigest = !reuse && slot && response.headers.get("X-Widget-Digest") + if (newDigest) { + blob.arrayBuffer().then(png => this.store.save(slot, { digest: newDigest, art, png })).catch(() => {}) + } + const cached = this.art || this.backdrop + const previousUrl = cached ? this.artCache.get(cacheKey)?.url : this.currentUrl this.currentUrl = this.urls.createObjectURL(blob) - if (this.art) { + if (cached) { this.artCache.set(cacheKey, { key: item.renderKey, url: this.currentUrl, sprites, scene: item.scene }) this.latestArt.set(item.profile, cacheKey) } diff --git a/openpilot/starpilot/galaxy/web/js/onroad-layout-template.js b/openpilot/starpilot/galaxy/web/js/onroad-layout-template.js index b32158690f..a633a3ba9c 100644 --- a/openpilot/starpilot/galaxy/web/js/onroad-layout-template.js +++ b/openpilot/starpilot/galaxy/web/js/onroad-layout-template.js @@ -71,10 +71,10 @@ export const ONROAD_LAYOUT_TEMPLATE = ` - + - Loading Widgets + - - + + @@ -160,7 +162,7 @@ export const ONROAD_LAYOUT_TEMPLATE = ` :x1="guide.axis === 'x' ? guide.value + previewShift(state.drag?.id) : 0" :x2="guide.axis === 'x' ? guide.value + previewShift(state.drag?.id) : profile.width" :y1="guide.axis === 'y' ? guide.value : 0" :y2="guide.axis === 'y' ? guide.value : profile.height" vector-effect="non-scaling-stroke" /> - + diff --git a/openpilot/starpilot/galaxy/web/js/onroad-layout.js b/openpilot/starpilot/galaxy/web/js/onroad-layout.js index 6f9ee46191..41e73cd425 100644 --- a/openpilot/starpilot/galaxy/web/js/onroad-layout.js +++ b/openpilot/starpilot/galaxy/web/js/onroad-layout.js @@ -166,12 +166,13 @@ export async function loadNavLook(fetcher = (...args) => fetch(...args)) { } export const LayoutWidgetPreview = { - props: ["widget", "palette", "profile", "scene", "clock24Hour", "native", "art"], + props: ["widget", "palette", "profile", "scene", "clock24Hour", "art", "native"], computed: { nav() { return navLook }, googleMap() { return navLook.map === "google" }, googleRoutes() { return navLook.routes === "google" }, roadNameSize() { return Math.max(18, Math.min(this.widget.width, this.widget.height) * .075) }, + sprite() { return this.art?.url && this.art.sprites?.sprites?.[this.widget.id] }, }, methods: { withAlpha, @@ -184,20 +185,14 @@ export const LayoutWidgetPreview = { }, template: ` `, } @@ -626,8 +621,21 @@ export const OnroadLayoutPage = { return [id, narrow] })) } }, + artLoading() { return this.mode === 'local' && !!this.state.data?.editable && !this.layers.art.url && this.state.art.status !== 'unavailable' }, + // Widget art and the backdrop always come from the same scene, so a half-switched pair never overlaps. + layers() { + const { art, backdrop } = this.state, profile = this.projection ? "projection" : this.state.profile + if (!art.url || !backdrop.url || art.profile !== profile || backdrop.profile !== profile || art.scene === backdrop.scene) return { art, backdrop } + const cached = (feed, scene) => feed.artCache.get(profile + "\n" + scene) + const sheet = cached(this.artFeed, backdrop.scene) + if (sheet) return { art: { ...art, url: sheet.url, sprites: sheet.sprites, scene: sheet.scene }, backdrop } + const screen = cached(this.backdropFeed, art.scene) + if (screen) return { art, backdrop: { ...backdrop, url: screen.url, scene: screen.scene } } + return { art: { ...art, url: null, sprites: null }, backdrop } + }, + previewDenied() { return [this.state.art, this.state.backdrop].some(feed => feed.status === 'unavailable' && feed.denied) }, // The last screen for this profile stays up while the next scene renders, instead of flashing the sketch. - nativeBackdropReady() { return !!this.state.backdrop.url && this.state.backdrop.profile === (this.projection ? "projection" : this.state.profile) }, + nativeBackdropReady() { return !!this.layers.backdrop.url && this.layers.backdrop.profile === (this.projection ? "projection" : this.state.profile) }, layout() { return this.state.draft?.layouts[this.state.profile] }, projectionHasPipWidget() { return ["pip_left", "pip_right"].some(id => this.state.draft?.layouts?.large?.[id]?.enabled === true) @@ -655,8 +663,7 @@ export const OnroadLayoutPage = { const widget = this.renderWidgets.find(widget => widget.id === this.state.selected) if (!widget) return null return { - x: this.previewX(this.state.selected), y: this.selectedPosition.y - widget.visualInsetTop, - width: widget.width, height: widget.height + widget.visualInsetTop + widget.visualInsetBottom + ...widget.outline, x: this.previewX(this.state.selected) + widget.outline.x, y: this.selectedPosition.y + widget.outline.y } }, // On touch, a magnified copy of the area around the dragged widget sits clear of the finger. @@ -696,8 +703,14 @@ export const OnroadLayoutPage = { visualInsetBottom: below ? item.visualInsetTop : 0, visualHeaderY: below ? item.height + 8 : -(item.visualInsetTop || 0) } const [width, height] = widgetSize(widget, this.layout[widget.id]) + const sprite = this.layers?.art?.sprites?.sprites?.[item.id] + const ink = sprite?.ink + const outline = Array.isArray(ink) && ink.length === 4 && ink.every(Number.isInteger) && + ink[0] >= 0 && ink[1] >= 0 && ink[2] > 0 && ink[3] > 0 && ink[0] + ink[2] <= sprite.width && ink[1] + ink[3] <= sprite.height + ? { x: (sprite.offsetX || 0) + ink[0] - 2, y: (sprite.offsetY || 0) + ink[1] - 2, width: ink[2] + 4, height: ink[3] + 4 } + : { x: 0, y: -widget.visualInsetTop, width, height: height + widget.visualInsetTop + widget.visualInsetBottom } return { - ...widget, width, height, ...(widget.iconSize ? { display: this.layout[widget.id].display } : {}), + ...widget, width, height, outline, ...(widget.iconSize ? { display: this.layout[widget.id].display } : {}), ...(widget.opacity ? { opacity: this.layout[widget.id].opacity } : {}), ...(widget.backgroundToggle ? { background: this.layout[widget.id].background } : {}), ...(widget.collapseToggle ? { collapse: this.layout[widget.id].collapse } : {}), @@ -807,7 +820,6 @@ export const OnroadLayoutPage = { .map(target => ({ ...target, value: target.value - (target.axis === "x" ? shift : 0) })) }, switchRow, - runtimeWidget(id) { return this.profile?.runtimePreviewWidgets?.includes(id) === true }, toggleSnap() { if (this.state.drag || this.state.layerDrag) return this.state.snapEnabled = !this.state.snapEnabled @@ -855,8 +867,9 @@ export const OnroadLayoutPage = { this.state.selected = null this.state.touchArmed = null }, - previewClick(event) { - if (!event.target?.closest?.(".gx-layout__widget")) this.deselectWidget() + previewPointerDown(event) { + // Pointer capture retargets the subsequent click to the canvas. + if (event.button === 0 && !event.target?.closest?.(".gx-layout__widget")) this.deselectWidget() }, openEditPanel() { if (this.state.selected == null) this.state.selected = this.activeWidgets?.[0]?.id || this.widgets?.[0]?.id || null diff --git a/openpilot/starpilot/system/starport/projection_layout.py b/openpilot/starpilot/system/starport/projection_layout.py index c99df400c0..8108332bb9 100644 --- a/openpilot/starpilot/system/starport/projection_layout.py +++ b/openpilot/starpilot/system/starport/projection_layout.py @@ -151,6 +151,7 @@ def layout_metadata_for_viewport(viewport): cameras = ('pip_left', 'pip_right') profile["widgetOrder"] = [NAV_MAP, *[key for key in profile["widgetOrder"] if key not in (NAV_MAP, NAV_CARD, STOPPED_TIMER_WIDGET, *cameras)], STOPPED_TIMER_WIDGET, NAV_CARD, *DISPLAY_WIDGETS, NOW_PLAYING_WIDGET, JETLINK_WIDGET, *cameras, CAR_EXIT] + profile["runtimePreviewWidgets"].extend(key for key in SPRITE_WIDGETS if key in widgets and key not in profile["runtimePreviewWidgets"]) return profile diff --git a/openpilot/starpilot/ui/layout_preview_renderer.py b/openpilot/starpilot/ui/layout_preview_renderer.py index 6afc78bdd9..4927285527 100644 --- a/openpilot/starpilot/ui/layout_preview_renderer.py +++ b/openpilot/starpilot/ui/layout_preview_renderer.py @@ -1,5 +1,6 @@ """Parked onroad layout preview using the same native view as the driving UI.""" +from collections import OrderedDict from typing import cast from pathlib import Path @@ -139,10 +140,14 @@ def _chunk(kind: bytes, data: bytes) -> bytes: def _straight_rgba(pixels: bytes) -> bytes: """PNG uses straight alpha; the transparent GL scratch target stores premultiplied RGB.""" - values = np.frombuffer(pixels, dtype=np.uint8).reshape(-1, 4).astype(np.uint16) - alpha = values[:, 3:4] - values[:, :3] = np.where(alpha > 0, np.minimum(255, (values[:, :3] * 255 + alpha // 2) // np.maximum(alpha, 1)), 0) - return values.astype(np.uint8).tobytes() + values = np.frombuffer(pixels, dtype=np.uint8).reshape(-1, 4).copy() + alpha = values[:, 3] + values[alpha == 0, :3] = 0 + translucent = (alpha > 0) & (alpha < 255) + colors = values[translucent, :3].astype(np.uint16) + coverage = alpha[translucent, None].astype(np.uint16) + values[translucent, :3] = np.minimum(255, (colors * 255 + coverage // 2) // coverage) + return values.tobytes() def _png_rgba(width: int, height: int, pixels: bytes, *, widget_art: dict | None = None) -> bytes: @@ -402,9 +407,10 @@ class _Canvas: rl.end_texture_mode() image = rl.load_image_from_texture(self.target.texture) try: + # The render texture is bottom-up. Crop first so only the sprite is flipped. + rl.image_crop(image, rl.Rectangle(crop_x, canvas_height - crop_y - height, width, height)) rl.image_format(image, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8) rl.image_flip_vertical(image) - rl.image_crop(image, rl.Rectangle(crop_x, crop_y, width, height)) data = _straight_rgba(bytes(image.data[:width * height * 4])) finally: rl.unload_image(image) @@ -415,6 +421,18 @@ class _Canvas: x, y, row_height = 0, y + row_height, 0 sprites[key] = {'x': x, 'y': y, 'width': width, 'height': height, 'offsetX': offset_x, 'offsetY': offset_y, 'visible': any(data[3::4])} + if key in ('cruise_limits', 'speed_limit', 'current_speed') and sprites[key]['visible']: + alpha = np.frombuffer(data, dtype=np.uint8).reshape(height, width, 4)[:, :, 3] + cols = np.flatnonzero(alpha.any(axis=0)) + rows = np.flatnonzero(alpha.any(axis=1)) + left, right = int(cols[0]), int(cols[-1] + 1) + if key == 'current_speed' and self.fonts is not None: + # Room for a three-digit km/h speed, centered like the HUD draws it + for text, role, size in (('888', FontRole.SPEED, 176), ('000', FontRole.SPEED, 176), ('km/h', FontRole.NORMAL, 28)): + start = (width - self.fonts.measure(text, role, size).width) / 2 + ink_left, ink_right = self.fonts.horizontal_ink(text, role, size) + left, right = min(left, max(0, math.floor(start + ink_left))), max(right, min(width, math.ceil(start + ink_right))) + sprites[key]['ink'] = [left, int(rows[0]), right - left, int(rows[-1] - rows[0] + 1)] x += width row_height = max(row_height, height) captures.append((key, data)) @@ -484,10 +502,14 @@ class _Canvas: self.fonts = None +SHEET_CACHE_SIZE = 8 # widget sheets and backdrops for the last few scenes + + class LayoutPreviewRenderer: def __init__(self): self._canvas: _Canvas | None = None self._last_use = 0.0 + self._sheets: OrderedDict[str, bytes] = OrderedDict() @property def has_resources(self) -> bool: @@ -498,6 +520,12 @@ class LayoutPreviewRenderer: raise ValueError("Invalid layout preview request") if "art" in payload and not (payload["art"] is True or payload["art"] == "backdrop"): raise ValueError("Invalid widget art request") + sheet_key = None + if 'art' in payload: + sheet_key = json.dumps(payload, sort_keys=True, separators=(',', ':'), allow_nan=False) + if sheet_key in self._sheets: + self._sheets.move_to_end(sheet_key) + return self._sheets[sheet_key] viewport = None if payload['profile'] == 'projection': from openpilot.starpilot.system.starport.projection_layout import projection_customization @@ -533,15 +561,20 @@ class LayoutPreviewRenderer: self.close() self._canvas = _Canvas(profile, viewport) self._last_use = time.monotonic() - if payload.get('art') is True: + if sheet_key is None: + return self._canvas.render(state, scene) + if payload['art'] is True: positions = payload['document']['layout']['widgets'] if viewport else document['layouts'][str(profile)] - return self._canvas.render_widget_art(state, positions, general=scene == 'general') - if payload.get('art') == 'backdrop': + image = self._canvas.render_widget_art(state, positions, general=scene == 'general') + else: # Everything the car draws except the movable widgets, which the editor places over it. # A non-empty order that names no widget keeps the ordered path and draws none of them. order = {**state.customization.get('widgetOrder', {}), str(profile): ['backdrop']} - return self._canvas.render(replace(state, customization={**state.customization, 'widgetOrder': order}), scene) - return self._canvas.render(state, scene) + image = self._canvas.render(replace(state, customization={**state.customization, 'widgetOrder': order}), scene) + self._sheets[sheet_key] = image + if len(self._sheets) > SHEET_CACHE_SIZE: + self._sheets.popitem(last=False) + return image def expire(self) -> None: if self._canvas is not None and time.monotonic() - self._last_use >= IDLE_SECONDS: @@ -551,3 +584,4 @@ class LayoutPreviewRenderer: if self._canvas is not None: self._canvas.close() self._canvas = None + self._sheets.clear() diff --git a/openpilot/starpilot/ui/tests/test_layout_preview_renderer.py b/openpilot/starpilot/ui/tests/test_layout_preview_renderer.py index f45795183f..d12442b2e1 100644 --- a/openpilot/starpilot/ui/tests/test_layout_preview_renderer.py +++ b/openpilot/starpilot/ui/tests/test_layout_preview_renderer.py @@ -36,6 +36,9 @@ class LayoutPreviewRendererTests(unittest.TestCase): self.assertEqual(canvas.render.call_args.args[0].viewport_width, width) renderer({**payload, 'art': True}) self.assertEqual(canvas.render_widget_art.call_args.args[0].viewport_width, width) + renders = canvas.render_widget_art.call_count + renderer({**payload, 'art': True}) + self.assertEqual(canvas.render_widget_art.call_count, renders) self.assertEqual(payload['document']['developerSidebar'], sidebar) def test_canvas_omits_sample_sidebar_when_hidden(self): @@ -336,3 +339,27 @@ def test_native_preview_draws_independent_camera_circles_without_camera_input(): assert circle.call_count == ring.call_count == 1 assert circle.call_args.args[0].x == right_center.x assert circle.call_args.args[0].y == right_center.y + + +def test_closing_the_renderer_forgets_cached_widget_sheets(): + renderer = LayoutPreviewRenderer() + renderer._sheets['sheet'] = b'png' + renderer.close() + assert not renderer._sheets + + +def test_backdrops_are_reused_per_scene_like_widget_sheets(): + canvas = Mock(profile=Profile.LARGE, viewport=None) + canvas.render.side_effect = lambda state, scene: scene.encode() + canvas.render_widget_art.return_value = b'sheet' + renderer = LayoutPreviewRenderer() + renderer._canvas = canvas + document = default_document() + with patch('openpilot.starpilot.ui.layout_preview_renderer.rl.is_window_ready', return_value=True): + for scene in ('engaged', 'slc_pending', 'engaged'): + assert renderer({'document': document, 'profile': 'large', 'scene': scene, 'art': 'backdrop'}) == scene.encode() + assert renderer({'document': document, 'profile': 'large', 'scene': 'engaged', 'art': True}) == b'sheet' + assert renderer({'document': document, 'profile': 'large', 'scene': 'engaged'}) == b'engaged' + renderer({'document': document, 'profile': 'large', 'scene': 'engaged'}) + assert [c.args[1] for c in canvas.render.call_args_list] == ['engaged', 'slc_pending', 'engaged', 'engaged'] + assert canvas.render_widget_art.call_count == 1 diff --git a/openpilot/starpilot/ui/tests/test_layout_preview_transport.py b/openpilot/starpilot/ui/tests/test_layout_preview_transport.py index 10cdee3c3a..f7443329f0 100644 --- a/openpilot/starpilot/ui/tests/test_layout_preview_transport.py +++ b/openpilot/starpilot/ui/tests/test_layout_preview_transport.py @@ -1,3 +1,4 @@ +import json from pathlib import Path import struct import tempfile @@ -12,11 +13,12 @@ from openpilot.starpilot.ui.layout_preview_transport import ( from openpilot.starpilot.ui.onroad_customization import default_document -def png(width=2, height=1): +def png(width=2, height=1, *, widget_art=None): def chunk(tag, data): return struct.pack('!I', len(data)) + tag + data + struct.pack('!I', zlib.crc32(tag + data)) pixels = b''.join(b'\x00' + b'\x00\x00\x00\xff' * width for _ in range(height)) return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!IIBBBBB', width, height, 8, 6, 0, 0, 0)) + + (chunk(b'tEXt', b'starpilot-widget-art\0' + json.dumps(widget_art).encode()) if widget_art is not None else b'') + chunk(b'IDAT', zlib.compress(pixels)) + chunk(b'IEND', b'')) diff --git a/openpilot/starpilot/ui/tests/test_layout_widget_art.py b/openpilot/starpilot/ui/tests/test_layout_widget_art.py index 7fb81d081b..691706666d 100644 --- a/openpilot/starpilot/ui/tests/test_layout_widget_art.py +++ b/openpilot/starpilot/ui/tests/test_layout_widget_art.py @@ -39,12 +39,12 @@ def test_native_preview_sidebar_choice_is_strict_and_does_not_change_saved_layou def test_widget_art_registry_is_shared_with_native_and_projection_metadata(): - from openpilot.starpilot.system.starport.projection_layout import layout_metadata_for_viewport + from openpilot.starpilot.system.starport.projection_layout import SPRITE_WIDGETS, layout_metadata_for_viewport metadata = customization_metadata()['profiles'] for profile, ids in RUNTIME_PREVIEW_WIDGETS.items(): assert metadata[profile]['runtimePreviewWidgets'] == list(ids) assert all(key in metadata[profile]['widgets'] for key in ids) - assert layout_metadata_for_viewport((2880, 1080))['runtimePreviewWidgets'] == list(RUNTIME_PREVIEW_WIDGETS['large']) + assert layout_metadata_for_viewport((2880, 1080))['runtimePreviewWidgets'] == list(dict.fromkeys((*RUNTIME_PREVIEW_WIDGETS['large'], *SPRITE_WIDGETS))) @pytest.mark.parametrize('profile', ['large', 'compact']) @@ -79,6 +79,20 @@ def test_native_prompt_art_parses_in_galaxy_and_reports_obscured_widgets(profile png = canvas.render_widget_art(sample_state(scene, document), document['layouts'][profile]) with Image.open(io.BytesIO(png)) as image: native = json.loads(image.info['starpilot-widget-art']) + for key in ('speed_limit' if profile == 'compact' else 'cruise_limits', 'current_speed'): + sign = native['sprites'].get(key) + if sign is None: + continue + x, y = sign['x'], sign['y'] + bounds = image.crop((x, y, x + sign['width'], y + sign['height'])).getchannel('A').getbbox() + if bounds: + left, top, right, bottom = bounds + if key == 'current_speed': + ink_left, ink_top, ink_width, ink_height = sign['ink'] + assert [ink_top, ink_height] == [top, bottom - top] and ink_left <= left and ink_left + ink_width >= right + assert ink_width > (right - left) * 1.3, "room for a three-digit speed" + else: + assert sign['ink'] == [left, top, right - left, bottom - top], (scene, key) assert len(native['sprites']) == len(RUNTIME_PREVIEW_WIDGETS[profile]) for key in (obscured, 'clock', 'driving_mode_descriptions'): assert native['sprites'][key]['visible'] is visible, (scene, key) @@ -209,7 +223,8 @@ def test_large_wheel_art_is_drawn_inside_its_crop_with_or_without_sidebar(monkey drawn = rl.draw_texture_pro.call_args.args[2] crop = rl.image_crop.call_args.args[1] assert crop.x <= drawn.x < drawn.x + drawn.width <= crop.x + crop.width - assert crop.y <= drawn.y < drawn.y + drawn.height <= crop.y + crop.height + top = (viewport or Profile.LARGE.size)[1] - crop.y - crop.height + assert top <= drawn.y < drawn.y + drawn.height <= top + crop.height color = rl.draw_texture_pro.call_args.args[-1] assert (color.r, color.g, color.b) == (255, 0, 0), 'The braking wheel must remain visible and red' diff --git a/prebuilt.json b/prebuilt.json index e736f247f9..18f025208a 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "f7b554f3afffab7bb90aa74b865f5081b69aa98f1a02094966978c62e2cf87b5", "schema_version": 1} +{"protected_inventory_sha256": "774c3d90a22e068dafe383f454e58a1c799499b702b56b363ffb63fcee109889", "schema_version": 1}