StarPort: Cover Wash music widget with big and small sizes

Co-authored-by: Peter Nguyen <trung791997@gmail.com>
This commit is contained in:
Danny
2026-11-11 09:37:18 -08:00
parent f061b1f2a9
commit d2260cf6d6
21 changed files with 1529 additions and 92 deletions
@@ -0,0 +1 @@
{"flmUxBrowser":{"checks":[],"failure":"Error: FLM browser check deadline exceeded\nError: spawn chromedriver ENOENT\n at ChildProcess._handle.onexit (node:internal/child_process:285:19)\n at onErrorNT (node:internal/child_process:483:16)\n at process.processTicksAndRejections (node:internal/process/task_queues:89:21)\n at until (file:///Users/danny/Git/openpilot/openpilot/starpilot/galaxy/tests/test_flm_ux_browser.mjs:128:9)\n at async file:///Users/danny/Git/openpilot/openpilot/starpilot/galaxy/tests/test_flm_ux_browser.mjs:205:3","screenshots":[],"cleanup":{"driver_exit_code":-2,"driver_signal":null,"driver_reaped":true,"server_closed":true}}}
@@ -2,7 +2,7 @@ import assert from "node:assert/strict"
import { compile } from "../web/vendor/vue/vue.esm-browser.js"
import { snapshot } from "./test_onroad_layout.mjs"
import { editorSnapshot, projectionPayload } from "../web/js/projection-layout.js"
import { LayoutWidgetPreview, OnroadLayoutFeed, OnroadLayoutPage, validSnapshot, validDocument } from "../web/js/onroad-layout.js"
import { LayoutWidgetPreview, OnroadLayoutFeed, OnroadLayoutPage, validSnapshot, validDocument, widgetSize } from "../web/js/onroad-layout.js"
const copy = (v) => JSON.parse(JSON.stringify(v))
const native = snapshot()
@@ -276,3 +276,44 @@ assert.deepEqual(orderedSnapshot.document.widgetOrder.large, orderedRaw.document
assert.deepEqual(projectionPayload({revision: raw.revision, document: orderedSnapshot.document}, orderedSnapshot.metadata).document,
orderedRaw.document)
console.log('Projection layers survive editor translation and save payload')
// Now playing: big or small, mirroring projection_layout's metadata; layouts saved before the choice are small.
{
const npMetadata = copy(metadata)
npMetadata.widgets.now_playing = { label: "Now playing", kind: "now_playing", width: 520, height: 96, colors: {},
opacity: { min: 0, max: 100, default: 85 }, collapseToggle: true, sizes: { small: [520, 96], big: [640, 264] },
default: { x: 2330, y: 954, enabled: true, opacity: 85, collapse: false, size: "small" } }
npMetadata.widgetOrder = [...metadata.widgetOrder.filter(id => id !== "car_exit"), "now_playing", "car_exit"]
const npDoc = copy(doc)
npDoc.widgets.now_playing = { ...npMetadata.widgets.now_playing.default }
const npData = editorSnapshot({ ...raw, metadata: npMetadata, document: npDoc, defaults: copy(npDoc) })
assert.equal(validSnapshot(npData), true)
const npProfile = npData.metadata.profiles.large
assert.deepEqual(widgetSize(npProfile.widgets.now_playing, npData.document.layouts.large.now_playing), [520, 96])
assert.deepEqual(widgetSize(npProfile.widgets.now_playing, { ...npData.document.layouts.large.now_playing, size: "big" }), [640, 264])
for (const size of ["medium", undefined, 1]) {
const broken = copy(npData.document)
broken.layouts.large.now_playing.size = size
assert.equal(validDocument(broken, npData.metadata), false)
}
const badSizes = copy(npData)
badSizes.metadata.profiles.large.widgets.now_playing.sizes.big = [640]
assert.equal(validSnapshot(badSizes), false)
const sizeChanges = []
const sizeVm = { editable: true, finishColorEdit() {}, recordChange: before => sizeChanges.push(before),
state: { draft: copy(npData.document), drag: null, layerDrag: null, notice: "", selected: "now_playing" } }
Object.defineProperty(sizeVm, "layout", { get: () => sizeVm.state.draft.layouts.large })
sizeVm.selectedWidget = npProfile.widgets.now_playing
Object.defineProperty(sizeVm, "selectedPosition", { get: () => sizeVm.layout.now_playing })
sizeVm.limitProfile = npProfile
OnroadLayoutPage.methods.setWidgetSize.call(sizeVm, "big")
const grown = sizeVm.layout.now_playing
assert.equal(grown.size, "big")
assert.ok(grown.x + 640 <= npProfile.bounds.x + npProfile.bounds.width && grown.y + 264 <= npProfile.bounds.y + npProfile.bounds.height,
"a bigger card slides back on screen")
assert.equal(sizeChanges.length, 1)
assert.equal(validDocument(sizeVm.state.draft, npData.metadata), true)
OnroadLayoutPage.methods.setWidgetSize.call(sizeVm, "huge")
assert.equal(grown.size, "big")
assert.match(OnroadLayoutPage.template, /setWidgetSize\(size\)/)
}
@@ -42,6 +42,7 @@ export const withAlpha = (color, factor) => color.slice(0, 7) + Math.floor(parse
// Steering wheels resize as a square ("size"); box widgets such as the Android Auto map take a width and height.
export function widgetSize(widget, position) {
if (widget.iconSize && position?.display === "icons") return [widget.iconSize, widget.iconSize]
if (widget.sizes && Array.isArray(widget.sizes[position?.size])) return [...widget.sizes[position.size]]
if (widget.box) return [position?.width ?? widget.width, position?.height ?? widget.height]
if (widget.resizable) return [position?.size ?? widget.width, position?.size ?? widget.height]
return [widget.width, widget.height]
@@ -173,10 +174,11 @@ export function validDocument(document, metadata) {
const widget = profile.widgets[id], limits = placementLimits(profile, id, layout)
const resizable = widget.resizable, box = widget.box, opacity = widget.opacity
return keysEqual(position, ["x", "y", "enabled", ...(resizable ? ["size"] : []), ...(box ? ["width", "height"] : []),
...(opacity ? ["opacity"] : []), ...(widget.iconSize ? ["display"] : []), ...(widget.backgroundToggle ? ["background"] : []), ...(widget.collapseToggle ? ["collapse"] : [])]) &&
...(opacity ? ["opacity"] : []), ...(widget.iconSize ? ["display"] : []), ...(widget.backgroundToggle ? ["background"] : []), ...(widget.collapseToggle ? ["collapse"] : []), ...(widget.sizes ? ["size"] : [])]) &&
(!widget.iconSize || ["words", "icons"].includes(position.display)) &&
(!widget.backgroundToggle || typeof position.background === "boolean") &&
(!widget.collapseToggle || typeof position.collapse === "boolean") &&
(!widget.sizes || Object.hasOwn(widget.sizes, position.size)) &&
(!opacity || (Number.isInteger(position.opacity) && position.opacity >= opacity.min && position.opacity <= opacity.max)) &&
(!resizable || (Number.isInteger(position.size) && position.size >= resizable.min && position.size <= resizable.max)) &&
(!box || (Number.isInteger(position.width) && position.width >= box.minWidth && position.width <= box.maxWidth &&
@@ -259,6 +261,9 @@ export function validSnapshot(data) {
widget.opacity.min < 0 || widget.opacity.max > 100 || widget.opacity.min > widget.opacity.default ||
widget.opacity.default > widget.opacity.max)) return false
if (widget.collapseToggle != null && (!projection || widget.kind !== "now_playing" || widget.collapseToggle !== true)) return false
if (widget.sizes != null && (!projection || widget.kind !== "now_playing" || !object(widget.sizes) ||
!Object.values(widget.sizes).every(size => Array.isArray(size) && size.length === 2 && size.every(positive) &&
size[0] <= area.width && size[1] <= area.height))) return false
if (widget.backgroundToggle != null && (!projection || !["nav_home", "nav_work", "bookmark", "car_exit"].includes(widget.kind) ||
widget.backgroundToggle !== true || !widget.opacity)) return false
if (widget.resizable && (!["steering_wheel", "driver_monitor"].includes(widget.kind) || !Number.isInteger(widget.resizable.min) ||
@@ -248,6 +248,15 @@ export const ONROAD_LAYOUT_TEMPLATE = `
</template>
<GalaxySettingRow feedback="draft" v-if="selectedWidget.backgroundToggle" :row="switchRow('Show background', selectedPosition.background === true)" :index="0"
:disabled="!editAvailable || !!state.drag || !!state.layerDrag" :save-value="(index, value) => setWidgetBackground(value)" />
<div v-if="projection && selectedWidget.sizes" class="gx-layout__favorite-display">
<span>Size</span>
<div class="gx-segment" role="group" :aria-label="selectedWidget.label + ' size'">
<button v-for="size in ['big', 'small']" :key="size" class="gx-btn" type="button"
:class="selectedPosition.size === size ? 'gx-btn--primary' : 'gx-btn--tonal'"
:aria-pressed="selectedPosition.size === size" :disabled="!editAvailable || !!state.drag || !!state.layerDrag"
@click="setWidgetSize(size)">{{ size === 'big' ? 'Big' : 'Small' }}</button>
</div>
</div>
<GalaxySettingRow v-if="selectedWidget.collapseToggle" :row="switchRow('Collapse when paused', selectedPosition.collapse === true)" :index="0"
:disabled="!editAvailable || !!state.drag || !!state.layerDrag" :save-value="(index, value) => setWidgetCollapse(value)" />
<p v-if="selectedWidget.defaultAnchor === 'driver_side'" class="gx-note">The default position follows the driver’s side. A moved position stays where you place it.</p>
@@ -210,15 +210,39 @@ export const LayoutWidgetPreview = {
:font-size="profile === 'large' ? 48 : 21" font-weight="600"
style="filter: drop-shadow(2px 2px 1px #000000aa)">{{ clock24Hour ? '18:00' : '12:00 PM' }}</text>
</template>
<g v-else-if="widget.kind === 'now_playing' && widget.size === 'big'">
<defs><linearGradient id="gx-np-wash" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#8a3a52" /><stop offset=".45" stop-color="#5a2350" /><stop offset="1" stop-color="#22143f" /></linearGradient></defs>
<rect x="0" y="0" :width="widget.width" :height="widget.height" rx="40" fill="url(#gx-np-wash)" :fill-opacity="(widget.opacity ?? 85) / 100" />
<rect x="40" y="20" width="138" height="36" rx="18" fill="#000000" fill-opacity=".35" stroke="#ffffff" stroke-opacity=".12" />
<path d="M61 47 V29 H69 V32 H63.6 V45" fill="#c7aef7" /><circle cx="61" cy="46" r="4.3" fill="#c7aef7" />
<text x="82" y="44" font-size="18" font-weight="600" fill="#f5f2fc">StarPilot</text>
<text :x="widget.width - 40" y="44" text-anchor="end" font-size="18" fill="#d6d2e0">Spotify</text>
<text :x="widget.width / 2" y="92" text-anchor="middle" font-size="30" font-weight="600" fill="#f5f2fc">Midnight City<tspan font-weight="400" fill="#d6d2e0"> • M83</tspan></text>
<rect x="40" y="112" :width="widget.width - 80" height="10" rx="5" fill="#ffffff" fill-opacity=".18" />
<rect x="40" y="112" :width="(widget.width - 80) * .38" height="10" rx="5" fill="#ffffff" />
<text x="40" y="144" font-size="16" fill="#b8b2c8">1:32</text>
<text :x="widget.width - 40" y="144" text-anchor="end" font-size="16" fill="#b8b2c8">4:03</text>
<g :transform="'translate(' + (widget.width / 2 - 192) + ' 208)'" fill="none" stroke="#d6d2e0" stroke-width="3.5" stroke-linecap="round">
<path d="M-16 -10 C0 -10 0 10 18 10 M-16 10 C0 10 0 -10 18 -10 M13 -16 L19 -10 L13 -4 M13 4 L19 10 L13 16" />
</g>
<g :transform="'translate(' + (widget.width / 2 - 96) + ' 208)'"><circle r="32" fill="#ffffff" fill-opacity=".14" /><path d="M9 -12 L9 12 L-9 0 Z M-14 -12 H-9 V12 H-14 Z" fill="#f5f2fc" /></g>
<g :transform="'translate(' + widget.width / 2 + ' 208)'"><circle r="36" fill="#f5f2fc" /><path d="M-10 -13 H-3 V13 H-10 Z M3 -13 H10 V13 H3 Z" fill="#0f0d17" /></g>
<g :transform="'translate(' + (widget.width / 2 + 96) + ' 208)'"><circle r="32" fill="#ffffff" fill-opacity=".14" /><path d="M-9 -12 L-9 12 L9 0 Z M9 -12 H14 V12 H9 Z" fill="#f5f2fc" /></g>
<g :transform="'translate(' + (widget.width / 2 + 192) + ' 208)'" fill="none" stroke="#d6d2e0" stroke-width="4" stroke-linecap="round">
<path d="M-14 -9 H12 M14 9 H-12 M-16 -11 V4 M16 11 V-4" /><path d="M10 -16 L19 -9 L10 -2 Z M-10 16 L-19 9 L-10 2 Z" fill="#d6d2e0" stroke="none" />
</g>
</g>
<g v-else-if="widget.kind === 'now_playing'">
<rect x="0" y="0" :width="widget.width" :height="widget.height" :rx="widget.height / 2" fill="#0f0d17" :fill-opacity="(widget.opacity ?? 85) / 100 * .92" />
<circle :cx="widget.height / 2" :cy="widget.height / 2" r="30" fill="#c7aef7" />
<rect :x="widget.height / 2 - 9" :y="widget.height / 2 - 12" width="6" height="24" rx="3" fill="#0f0d17" />
<rect :x="widget.height / 2 + 3" :y="widget.height / 2 - 12" width="6" height="24" rx="3" fill="#0f0d17" />
<text :x="widget.height + 4" y="40" font-size="30" font-weight="600" fill="#f5f2fc">Midnight City</text>
<text :x="widget.height + 4" y="68" font-size="22" fill="#b8b2c8">M83</text>
<rect :x="widget.height + 4" :y="widget.height - 16" :width="widget.width - widget.height * 1.5 - 4" height="4" rx="2" fill="#ffffff" fill-opacity=".2" />
<rect :x="widget.height + 4" :y="widget.height - 16" :width="(widget.width - widget.height * 1.5 - 4) * .38" height="4" rx="2" fill="#c7aef7" />
<defs><linearGradient id="gx-np-wash-small" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#8a3a52" /><stop offset=".45" stop-color="#5a2350" /><stop offset="1" stop-color="#22143f" /></linearGradient></defs>
<rect x="0" y="0" :width="widget.width" :height="widget.height" :rx="widget.height / 2" fill="url(#gx-np-wash-small)" :fill-opacity="(widget.opacity ?? 85) / 100" />
<circle :cx="widget.height / 2" :cy="widget.height / 2" r="36" fill="#f5f2fc" />
<rect :x="widget.height / 2 - 10" :y="widget.height / 2 - 13" width="7" height="26" rx="3" fill="#0f0d17" />
<rect :x="widget.height / 2 + 3" :y="widget.height / 2 - 13" width="7" height="26" rx="3" fill="#0f0d17" />
<text :x="widget.height + 4" y="42" font-size="26" font-weight="600" fill="#f5f2fc">Midnight City</text>
<text :x="widget.height + 4" y="71" font-size="19" fill="#d6d2e0">M83</text>
<g :transform="'translate(' + (widget.width - 42) + ' ' + widget.height / 2 + ') scale(1.3)'" fill="#c7aef7">
<path d="M0 7 V-11 H8 V-7.8 H2.6 V7" /><circle cx="-3" cy="7" r="5" />
</g>
</g>
<g v-else-if="widget.kind === 'jetlink_status'">
<rect x="0" y="0" :width="widget.width" :height="widget.height" :rx="widget.height / 2" fill="#0f0d17" :fill-opacity="(widget.opacity ?? 85) / 100 * .92" />
@@ -511,7 +535,8 @@ export const OnroadLayoutPage = {
...widget, width, height, ...(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 } : {})
...(widget.collapseToggle ? { collapse: this.layout[widget.id].collapse } : {}),
...(widget.sizes ? { size: this.layout[widget.id].size } : {})
}
})
},
@@ -1141,6 +1166,17 @@ export const OnroadLayoutPage = {
this.recordChange(before)
this.state.notice = ""
},
setWidgetSize(size) {
if (!this.editable || this.state.drag || this.state.layerDrag || !this.selectedWidget?.sizes ||
!Object.hasOwn(this.selectedWidget.sizes, size)) return
this.finishColorEdit()
const before = clone(this.state.draft)
this.selectedPosition.size = size
Object.assign(this.selectedPosition, clampPlacement(this.limitProfile, this.state.selected,
this.selectedPosition.x, this.selectedPosition.y, this.layout))
this.recordChange(before)
this.state.notice = ""
},
setWidgetCollapse(value) {
if (!this.editable || this.state.drag || this.state.layerDrag || !this.selectedWidget?.collapseToggle) return
this.finishColorEdit()
+50 -9
View File
@@ -5,9 +5,13 @@ import json
import time
from pathlib import Path
from typing import Any
from urllib.parse import urlsplit
from openpilot.starpilot.soloist.client import ARTWORK_HOSTS, REPEATS
MAX_TEXT = 120
STALE_SECONDS = 10.0
ELSEWHERE = 'elsewhere'
def _text(value: Any) -> str:
@@ -18,13 +22,24 @@ def _whole(value: Any, limit: int = 86400000) -> int | None:
return int(value) if type(value) in (int, float) and 0 <= value < limit else None
def artwork_url(value: Any) -> str:
if not isinstance(value, str) or len(value) > 512:
return ''
parts = urlsplit(value)
ok = parts.scheme == 'https' and parts.hostname in ARTWORK_HOSTS and not parts.username and parts.port is None
return value if ok else ''
def snapshot(source: str, status: str, title: str, artist: str, album: str, duration_ms: int | None,
position: dict | None) -> dict | None:
position: dict | None, shuffle: bool | None = None, artwork: Any = '', repeat: Any = None,
device: Any = '') -> dict | None:
"""``shuffle`` and ``repeat`` are None when the player cannot report or change them."""
title = _text(title)
if not title or status not in ('playing', 'paused'):
return None
return {'source': source, 'status': status, 'title': title, 'artist': _text(artist), 'album': _text(album),
'durationMs': duration_ms, 'position': position}
'durationMs': duration_ms, 'position': position, 'shuffle': shuffle, 'artwork': artwork_url(artwork),
'repeat': repeat if repeat in REPEATS else None, 'device': _text(device)[:40]}
def from_spotify(player: dict | None) -> dict | None:
@@ -34,10 +49,12 @@ def from_spotify(player: dict | None) -> dict | None:
if not isinstance(track, dict) or player.get('status') not in ('playing', 'paused') or not player.get('active'):
return None
return snapshot('spotify', player['status'], track.get('title'), track.get('artists'), track.get('album'),
_whole(track.get('durationMs')), player.get('position'))
_whole(track.get('durationMs')), player.get('position'), player.get('shuffle') is True,
track.get('artwork'), player.get('repeat') if player.get('repeat') in REPEATS else 'off',
player.get('deviceName'))
def from_phone(props: dict | None, now_ms: int | None = None) -> dict | None:
def from_phone(props: dict | None, now_ms: int | None = None, device: str = '') -> dict | None:
"""BlueZ MediaPlayer1 properties: Track {Title, Artist, Album, Duration ms}, Status, Position ms."""
if not isinstance(props, dict) or not isinstance(props.get('Track'), dict):
return None
@@ -51,7 +68,7 @@ def from_phone(props: dict | None, now_ms: int | None = None) -> dict | None:
'speed': 1.0 if status == 'playing' else 0.0}
duration = _whole(track.get('Duration'))
return snapshot('phone', status or '', track.get('Title'), track.get('Artist'), track.get('Album'),
duration if duration else None, anchor)
duration if duration else None, anchor, device=device)
def elapsed_ms(now_playing: dict, now_ms: float | None = None) -> int:
@@ -63,12 +80,36 @@ def elapsed_ms(now_playing: dict, now_ms: float | None = None) -> int:
return int(max(0, min(duration if duration else value, value)))
def read(path: Path, now: float | None = None) -> dict | None:
"""The supervisor's published snapshot; None when missing, malformed or the supervisor stopped updating."""
def _published(path: Path, now: float | None) -> dict | None:
try:
if (time.time() if now is None else now) - path.stat().st_mtime > STALE_SECONDS: # noqa: TID251 compared with mtime
return None
found = json.loads(path.read_text()).get('nowPlaying')
except (OSError, ValueError, AttributeError):
found = json.loads(path.read_text())
except (OSError, ValueError):
return None
return found if isinstance(found, dict) else None
def _song(status: dict | None) -> dict | None:
found = status.get('nowPlaying') if status is not None else None
return found if isinstance(found, dict) and found.get('title') and found.get('status') in ('playing', 'paused') else None
def read(path: Path, now: float | None = None) -> dict | None:
"""The supervisor's published snapshot; None when missing, malformed or the supervisor stopped updating."""
return _song(_published(path, now))
def elsewhere(player: dict | None) -> dict | None:
"""Spotify is signed in here and another device is playing or paused on a track; ``device`` is this player's own name."""
if not isinstance(player, dict) or not (player.get('connected') and player.get('loggedIn')) or player.get('active'):
return None
if player.get('status') not in ('playing', 'paused') or not isinstance(player.get('track'), dict):
return None
return {'source': 'spotify', 'status': ELSEWHERE, 'title': '', 'device': _text(player.get('deviceName'))[:40]}
def read_card(path: Path, now: float | None = None) -> dict | None:
"""For the car screen: the song, or the take-over offer while Spotify plays on another device."""
status = _published(path, now)
return _song(status) or (elsewhere(status.get('player')) if status is not None else None)
+2 -1
View File
@@ -187,7 +187,8 @@ class Supervisor:
if state == 'running' and player is not None:
state = ('connecting' if not player['connected'] else 'waiting' if not player['loggedIn'] else
'playing' if player['status'] == 'playing' and player['active'] else 'ready')
now_playing = (now_playing_module.from_phone(self.phone_track) if self.phone_prefs is not None and self.player is not None
phone = self.phone_prefs if self.player is not None else None
now_playing = (now_playing_module.from_phone(self.phone_track, device=phone.phone_name) if phone is not None
else now_playing_module.from_spotify(player))
with self.log_lock:
log = list(self.log)[-20:]
@@ -3,7 +3,7 @@ import json
from openpilot.starpilot.soloist import now_playing
from openpilot.starpilot.system.starport.projection_now_playing import ProjectionNowPlayingFeed
PLAYER = {'loggedIn': True, 'active': True, 'status': 'playing',
PLAYER: dict = {'loggedIn': True, 'active': True, 'status': 'playing',
'track': {'title': 'Midnight City', 'artists': 'M83', 'album': 'Hurry Up', 'durationMs': 243000},
'position': {'ms': 10000, 'at': 1000, 'speed': 1.0}}
@@ -68,3 +68,78 @@ def test_feed_only_reads_while_enabled():
feed.set_enabled(False)
assert feed.snapshot() is None
feed.close()
def test_shuffle_repeat_and_device_come_from_spotify_and_are_unavailable_for_phone_audio():
found = present(now_playing.from_spotify({**PLAYER, 'shuffle': True, 'repeat': 'track', 'deviceName': 'StarPilot'}))
assert (found['shuffle'], found['repeat'], found['device']) == (True, 'track', 'StarPilot')
found = present(now_playing.from_spotify({**PLAYER, 'repeat': 'sometimes'}))
assert (found['shuffle'], found['repeat']) == (False, 'off')
found = present(now_playing.from_phone({'Status': 'playing', 'Track': {'Title': 'Song'}}, device='Pixel 9'))
assert (found['shuffle'], found['repeat'], found['device'], found['artwork']) == (None, None, 'Pixel 9', '')
def test_car_screen_offers_play_here_only_while_spotify_plays_on_another_device(tmp_path):
path = tmp_path / 'status.json'
inactive = {**PLAYER, 'active': False, 'connected': True, 'deviceName': 'StarPilot'}
path.write_text(json.dumps({'nowPlaying': None, 'player': inactive}))
mtime = path.stat().st_mtime
assert now_playing.read(path, now=mtime + 1) is None
assert now_playing.read_card(path, now=mtime + 1) == {'source': 'spotify', 'status': 'elsewhere', 'title': '', 'device': 'StarPilot'}
assert now_playing.read_card(path, now=mtime + 60) is None
for player in ({**inactive, 'loggedIn': False}, {**inactive, 'connected': False}, {**inactive, 'status': 'idle'},
{**inactive, 'track': None}, None):
path.write_text(json.dumps({'nowPlaying': None, 'player': player}))
assert now_playing.read_card(path, now=mtime + 1) is None
path.write_text(json.dumps({'nowPlaying': now_playing.from_spotify(PLAYER), 'player': PLAYER}))
assert present(now_playing.read_card(path, now=mtime + 1))['title'] == 'Midnight City'
def test_spotify_cover_is_kept_only_on_spotify_image_hosts():
cover = 'https://i.scdn.co/image/ab67616d0000b273'
found = present(now_playing.from_spotify({**PLAYER, 'track': {**PLAYER['track'], 'artwork': cover}}))
assert found['artwork'] == cover
for bad in ('http://i.scdn.co/image/a', 'https://evil.example/a.jpg', 'https://i.scdn.co:8443/a', 'https://u@i.scdn.co/a',
'https://i.scdn.co/' + 'a' * 600, None, 7):
assert present(now_playing.from_spotify({**PLAYER, 'track': {**PLAYER['track'], 'artwork': bad}}))['artwork'] == ''
def test_feed_downloads_each_cover_once_and_drops_failures():
from openpilot.starpilot.system.starport import projection_now_playing
value = {'title': 'x', 'artwork': 'https://i.scdn.co/image/a'}
fetched = []
def fetch(url):
fetched.append(url)
if url.endswith('/bad'):
raise OSError('timed out')
return (1, 1, b'\0\0\0\0')
feed = ProjectionNowPlayingFeed(read=lambda: value, fetch=fetch)
feed._enabled = True
feed.poll()
feed.poll()
assert fetched == [value['artwork']] and feed.artwork() == (value['artwork'], (1, 1, b'\0\0\0\0'))
cover, value = value, None
feed.poll() # buffering between songs: the cover stays
assert feed.artwork() == (cover['artwork'], (1, 1, b'\0\0\0\0')) and len(fetched) == 1
value = {'title': 'y', 'artwork': 'https://i.scdn.co/image/bad'}
feed.poll()
feed.poll()
assert feed.artwork() == (value['artwork'], None) and len(fetched) == 2
value = {'title': 'z', 'artwork': ''}
feed.poll()
assert feed.artwork() == ('', None) and len(fetched) == 2
assert projection_now_playing.fetch_artwork('https://evil.example/a.jpg') is None
assert projection_now_playing.image_type(b'\x89PNG\r\n\x1a\n...') == '.png' and projection_now_playing.image_type(b'GIF89a') is None
feed.close()
def test_jpeg_cover_is_decoded_to_a_square_rgba_texture_source():
import io
from PIL import Image
from openpilot.starpilot.system.starport import projection_now_playing
jpeg = io.BytesIO()
Image.new('RGB', (640, 600), (200, 30, 60)).save(jpeg, format='JPEG')
width, height, pixels = projection_now_playing.decode_cover(jpeg.getvalue())
assert (width, height) == (projection_now_playing.ARTWORK_PX,) * 2 and len(pixels) == width * height * 4
assert abs(pixels[0] - 200) < 20 and pixels[3] == 255
@@ -396,12 +396,12 @@ def test_status_publishes_the_spotify_track_for_the_car_screen(layout):
def test_status_publishes_the_phone_track_only_while_phone_audio_runs(layout):
sup, _ = make_supervisor(layout, [])
sup.phone_prefs = object()
sup.phone_prefs = preferences.Preferences(source='phone', phone_name='Pixel 9')
sup.phone_track = {'Status': 'playing', 'Track': {'Title': 'Phone Song', 'Artist': 'Band'}}
assert sup.status()['nowPlaying'] is None
sup.player = object()
found = sup.status()['nowPlaying']
assert found['source'] == 'phone' and found['title'] == 'Phone Song'
assert found['source'] == 'phone' and found['title'] == 'Phone Song' and found['device'] == 'Pixel 9'
def test_supervisor_waits_for_network_before_starting(layout, monkeypatch):
@@ -153,11 +153,11 @@ def music_routed() -> bool:
return paths.enabled() and preferences.load().output == 'starport'
def music_control(action: str) -> None:
def music_control(action: str, args: dict | None = None) -> None:
def worker():
try:
from openpilot.starpilot.galaxy.spotify_setup import SpotifyClient
SpotifyClient().call('control', action=action, args={})
SpotifyClient().call('control', action=action, args=args or {})
except Exception:
pass
threading.Thread(target=worker, name=f'aa_music_{action}', daemon=True).start()
@@ -67,7 +67,7 @@ class MediaStatus:
return None
if feed is None:
from openpilot.starpilot.system.starport.projection_now_playing import ProjectionNowPlayingFeed
feed = ProjectionNowPlayingFeed(read=routed_snapshot)
feed = ProjectionNowPlayingFeed(read=routed_snapshot, fetch=lambda _url: None)
feed.set_enabled(True)
return cls(session, channel, feed, log, **kwargs)
@@ -33,6 +33,7 @@ CAR_EXIT_SIZE = (96, 96)
CAR_EXIT_MIN_OPACITY = 25
NOW_PLAYING_WIDGET = 'now_playing'
NOW_PLAYING_SIZE = (520, 96)
NOW_PLAYING_SIZES = {'small': NOW_PLAYING_SIZE, 'big': (640, 264)}
NOW_PLAYING_OPACITY = (0, 100, 85)
JETLINK_SIZE = (420, 84)
JETLINK_OPACITY = (0, 100, 85)
@@ -112,11 +113,11 @@ def layout_metadata_for_viewport(viewport):
'default': {'x': width - 30 - FAVORITE_SIZE[0], 'y': 155, 'enabled': False, 'display': 'words'}}
widgets[NOW_PLAYING_WIDGET] = {'label': 'Now playing', 'kind': NOW_PLAYING_WIDGET,
'width': NOW_PLAYING_SIZE[0], 'height': NOW_PLAYING_SIZE[1], 'colors': {},
'note': 'The song playing from Spotify or your phone over Bluetooth. Opacity sets the card background.',
'note': 'Music from Spotify or your phone. Big adds the seek bar, skip, shuffle and repeat. Opacity sets the card background.',
'opacity': {'min': NOW_PLAYING_OPACITY[0], 'max': NOW_PLAYING_OPACITY[1], 'default': NOW_PLAYING_OPACITY[2]},
'collapseToggle': True,
'collapseToggle': True, 'sizes': {name: list(size) for name, size in NOW_PLAYING_SIZES.items()},
'default': {'x': width - 30 - NOW_PLAYING_SIZE[0], 'y': height - 30 - NOW_PLAYING_SIZE[1],
'enabled': True, 'opacity': NOW_PLAYING_OPACITY[2], 'collapse': False}}
'enabled': True, 'opacity': NOW_PLAYING_OPACITY[2], 'collapse': False, 'size': 'small'}}
widgets[JETLINK_WIDGET] = {'label': 'Jetlink status', 'kind': JETLINK_WIDGET,
'width': JETLINK_SIZE[0], 'height': JETLINK_SIZE[1], 'colors': {},
'note': 'Shown while Jetlink is on: connection, device and host processing time. Opacity sets the card background.',
@@ -191,7 +192,14 @@ def default_layout_for_viewport(viewport, display=None):
return result
def now_playing_size(placement):
"""The card's (width, height); layouts saved before the size choice are small."""
return NOW_PLAYING_SIZES.get((placement or {}).get('size'), NOW_PLAYING_SIZE)
def placement_size(key, widget, placement):
if key == NOW_PLAYING_WIDGET:
return now_playing_size(placement)
if key in DISPLAY_WIDGETS and placement.get('display') == 'icons':
return FAVORITE_ICON_SIZE, FAVORITE_ICON_SIZE
if widget.get('resizable'):
@@ -264,6 +272,7 @@ def validate_layout_for_viewport(value, viewport, *, _legacy_geometry=False):
placement.setdefault('opacity', CARD_WIDGETS[key][2])
if key == NOW_PLAYING_WIDGET and type(placement) is dict:
placement.setdefault('collapse', False)
placement.setdefault('size', 'small')
if key == 'driver_monitor' and type(placement) is dict and 'size' not in placement:
for axis in ('x', 'y'):
if type(placement.get(axis)) in (int, float):
@@ -276,7 +285,7 @@ def validate_layout_for_viewport(value, viewport, *, _legacy_geometry=False):
({'display'} if key in DISPLAY_WIDGETS else set()) |
({'opacity', 'background'} if key in ACTION_WIDGETS else set()) |
({'opacity'} if key == 'cruise_limits' or key in CARD_WIDGETS else set()) |
({'collapse'} if key == NOW_PLAYING_WIDGET else set()) |
({'collapse', 'size'} if key == NOW_PLAYING_WIDGET else set()) |
({'width', 'height', 'opacity'} if key == NAV_MAP else set()))
if type(placement) is not dict or set(placement) != fields or type(placement['enabled']) is not bool:
raise ValueError('Invalid projection widget')
@@ -294,6 +303,8 @@ def validate_layout_for_viewport(value, viewport, *, _legacy_geometry=False):
raise ValueError('Invalid card opacity')
if key == NOW_PLAYING_WIDGET and type(placement['collapse']) is not bool:
raise ValueError('Invalid now playing collapse setting')
if key == NOW_PLAYING_WIDGET and (type(placement['size']) is not str or placement['size'] not in NOW_PLAYING_SIZES):
raise ValueError('Invalid now playing size')
if key == CAR_EXIT and placement['opacity'] < CAR_EXIT_MIN_OPACITY:
raise ValueError('Exit to car opacity must be at least 25%')
if widget.get('resizable'):
@@ -320,6 +331,11 @@ def validate_layout_for_viewport(value, viewport, *, _legacy_geometry=False):
type(placement[axis]) in (int, float) and math.isfinite(placement[axis]) and
bounds[axis] <= placement[axis] <= bounds[axis] + bounds[extent] - dimension
for (axis, extent), dimension in zip((('x', 'width'), ('y', 'height')), pair, strict=True))), dimensions)
if key == NOW_PLAYING_WIDGET:
# A larger card size may overhang a saved spot; pull it back in.
for (axis, extent), dimension in zip((('x', 'width'), ('y', 'height')), dimensions, strict=True):
if type(placement[axis]) in (int, float) and math.isfinite(placement[axis]):
placement[axis] = min(placement[axis], bounds[axis] + bounds[extent] - dimension)
for (axis, extent), dimension in zip((('x', 'width'), ('y', 'height')), dimensions, strict=True):
number = placement[axis]
if (type(number) not in (int, float) or not math.isfinite(number) or
@@ -1,14 +1,55 @@
"""Read-only now-playing snapshot for the car screen, polled away from Android Auto's drawing thread."""
"""Read-only now-playing snapshot for the car screen, polled away from Android Auto's drawing thread.
Cover art download and the 'elsewhere' take-over state are adapted from Peter Nguyen's now-playing card.
"""
import io
import threading
import urllib.request
from openpilot.starpilot.soloist import now_playing
from openpilot.starpilot.soloist.paths import Layout
MAX_ARTWORK_BYTES = 512 * 1024
ARTWORK_TIMEOUT = 4.0
ARTWORK_PX = 480
IMAGE_TYPES = ((b'\xff\xd8\xff', '.jpg'), (b'\x89PNG\r\n\x1a\n', '.png'))
def image_type(data):
return next((kind for magic, kind in IMAGE_TYPES if data.startswith(magic)), None)
def decode_cover(data):
"""(side, side, RGBA bytes): the cover's centre square, at most ARTWORK_PX wide, ready for a texture."""
from PIL import Image
with Image.open(io.BytesIO(data)) as image:
image = image.convert('RGBA')
side = min(image.size)
left, top = (image.width - side) // 2, (image.height - side) // 2
image = image.crop((left, top, left + side, top + side))
if side > ARTWORK_PX:
image = image.resize((ARTWORK_PX, ARTWORK_PX), Image.Resampling.BILINEAR)
return image.width, image.height, image.tobytes()
def fetch_artwork(url):
"""The decoded cover, or None. Only Spotify's image hosts, at most 512 KB, JPEG or PNG."""
if not now_playing.artwork_url(url):
return None
request = urllib.request.Request(url, headers={'User-Agent': 'starpilot-car-screen'})
with urllib.request.urlopen(request, timeout=ARTWORK_TIMEOUT) as response:
if not now_playing.artwork_url(response.geturl()):
return None
data = response.read(MAX_ARTWORK_BYTES + 1)
return decode_cover(data) if len(data) <= MAX_ARTWORK_BYTES and image_type(data) else None
class ProjectionNowPlayingFeed:
"""Only poll while placed. The renderer takes immutable snapshots without file IO."""
def __init__(self, read=None):
self.read = read or (lambda: now_playing.read(Layout.default().status))
"""Only poll while placed. The renderer takes immutable snapshots without file or network IO."""
def __init__(self, read=None, fetch=None):
self.read = read or (lambda: now_playing.read_card(Layout.default().status))
self.fetch = fetch or fetch_artwork
self._artwork = ('', None)
self._lock = threading.Lock()
self._stop = threading.Event()
self._thread = None
@@ -35,11 +76,26 @@ class ProjectionNowPlayingFeed:
with self._lock:
if self._enabled:
self._value = value
held = self._artwork[0]
url = (value or {}).get('artwork') or ''
if value is not None and url != held:
# One try per cover; a failed download keeps the plain card until the song changes.
try:
data = self.fetch(url) if url else None
except Exception:
data = None
with self._lock:
self._artwork = (url, data)
def snapshot(self):
with self._lock:
return self._value
def artwork(self):
"""(url, (width, height, RGBA bytes) or None) for the current cover."""
with self._lock:
return self._artwork
def _run(self):
while not self._stop.is_set():
self.poll()
@@ -91,6 +91,7 @@ def native_dependencies():
from openpilot.starpilot.ui.shell import ShellMode
from openpilot.starpilot.system.starport.projection_favorites import ProjectionFavorites
from openpilot.starpilot.system.starport.projection_now_playing import ProjectionNowPlayingFeed
from openpilot.starpilot.system.starport.media_audio import music_control
from openpilot.starpilot.models.jetlink_status import JetlinkStatusFeed
class ProjectionRoadCamera(AugmentedRoadView):
@@ -150,7 +151,7 @@ def native_dependencies():
pip_rect=Rect, pip_widgets=CAMERA_WIDGETS, placement=placement, widget_size=widget_size,
alert=OnroadAlert, alert_size=AlertSize, map_overlay=MapOverlay, map_feed=MapFeed,
favorites=ProjectionFavorites, standby_logo=standby_logo, now_playing_feed=ProjectionNowPlayingFeed,
jetlink_feed=JetlinkStatusFeed)
now_playing_control=music_control, jetlink_feed=JetlinkStatusFeed)
class ProjectionOnroad:
@@ -199,6 +200,10 @@ class ProjectionOnroad:
if getattr(native, 'now_playing_feed', None) is not None:
self.now_playing_feed = native.now_playing_feed()
self._resources.callback(self.now_playing_feed.close)
self.now_playing_touch = None
if self.now_playing_feed is not None and getattr(native, 'now_playing_control', None) is not None:
from openpilot.starpilot.ui.onroad_now_playing import NowPlayingTouch
self.now_playing_touch = NowPlayingTouch(native.now_playing_control, getattr(self.onroad, 'now_playing', None))
self.jetlink_feed = None
if getattr(native, 'jetlink_feed', None) is not None:
self.jetlink_feed = native.jetlink_feed()
@@ -355,6 +360,7 @@ class ProjectionOnroad:
placed = (self.customization or {}).get('widgets', {}).get('now_playing', {})
self.now_playing_feed.set_enabled(bool(placed.get('enabled')))
self.onroad.now_playing.track = self.now_playing_feed.snapshot()
self.onroad.now_playing.artwork = self.now_playing_feed.artwork()
if self.jetlink_feed is not None:
placed = (self.customization or {}).get('widgets', {}).get('jetlink_status', {})
self.jetlink_feed.set_enabled(bool(placed.get('enabled') and self.native.ui_state.started))
@@ -582,6 +588,10 @@ class ProjectionOnroad:
if self.favorites is not None:
self.favorites.cancel()
continue
if self._now_playing_touch(event.kind, x, y):
if self.favorites is not None:
self.favorites.cancel()
continue
if self.favorites is None:
continue
if self._state is None or not self.native.ui_state.started:
@@ -589,6 +599,14 @@ class ProjectionOnroad:
continue
self.favorites.touch(event.kind, x, y, self._state, self.native.ui_state.started_frame)
def _now_playing_touch(self, kind, x, y) -> bool:
touch = self.now_playing_touch
if touch is None:
return False
state = self._state if self.native.ui_state.started else None
placed = state.customization['layouts']['large'].get('now_playing') if state is not None else None
return touch.touch(kind, x, y, state, placed, self.onroad.now_playing.showing())
def _slc_touch(self, kind, x, y) -> bool:
"""Speed-limit confirmation taps; True while one owns the touch."""
gesture = self._slc_input
@@ -611,6 +629,8 @@ class ProjectionOnroad:
def cancel_touch(self):
self.exit.cancel()
if self.now_playing_touch is not None:
self.now_playing_touch.cancel()
if self._slc_input is not None:
self._slc_input.cancel()
if self.favorites is not None:
@@ -535,7 +535,37 @@ class TestNowPlayingWidget(unittest.TestCase):
self.assertTrue(placement['enabled'])
self.assertEqual(placement['opacity'], 85)
self.assertFalse(placement['collapse'])
self.assertEqual(set(placement), {'x', 'y', 'enabled', 'opacity', 'collapse'})
self.assertEqual(placement['size'], 'small')
self.assertEqual(set(placement), {'x', 'y', 'enabled', 'opacity', 'collapse', 'size'})
def test_size_is_validated_and_older_layouts_stay_small_in_place(self):
document = default_layout(SCREEN)
metadata = layout_metadata(SCREEN)
self.assertEqual(metadata['widgets']['now_playing']['sizes'], {'small': [520, 96], 'big': [640, 264]})
for bad in ('medium', 1, None, True):
broken = copy.deepcopy(document)
broken['widgets']['now_playing']['size'] = bad
with self.assertRaises(ValueError):
validate_layout(broken, SCREEN)
bounds = metadata['bounds']
old = copy.deepcopy(document)
del old['widgets']['now_playing']['size']
old['widgets']['now_playing'].update(x=bounds['x'] + bounds['width'] - 520, y=bounds['y'] + bounds['height'] - 96)
placed = validate_layout(old, SCREEN)['widgets']['now_playing']
self.assertEqual((placed['size'], placed['x'], placed['y']),
('small', bounds['x'] + bounds['width'] - 520, bounds['y'] + bounds['height'] - 96))
def test_saved_spot_slides_back_on_screen_when_the_card_grows(self):
document = default_layout(SCREEN)
bounds = layout_metadata(SCREEN)['bounds']
right, bottom = bounds['x'] + bounds['width'], bounds['y'] + bounds['height']
document['widgets']['now_playing'].update(x=right - 520, y=bottom - 96, size='big')
placed = validate_layout(document, SCREEN)['widgets']['now_playing']
self.assertEqual((placed['x'], placed['y']), (right - 640, bottom - 264))
self.assertEqual(placement_size('now_playing', layout_metadata(SCREEN)['widgets']['now_playing'], placed), (640, 264))
document['widgets']['now_playing'].update(x=bounds['x'], y=bounds['y'])
placed = validate_layout(document, SCREEN)['widgets']['now_playing']
self.assertEqual((placed['x'], placed['y']), (bounds['x'], bounds['y']))
def test_opacity_is_validated_and_old_layouts_gain_the_card(self):
document = default_layout(SCREEN)
@@ -102,6 +102,86 @@ class TestProjectionOnroad(unittest.TestCase):
owner.cancel.assert_called_once()
self.assertEqual(owner.touch.call_count, 1)
def touch_view(self, display, size='big', track=None):
"""The card bottom-right on the 1860x1116 canvas, with Home, Work and Bookmark enabled."""
from openpilot.starpilot.system.starport.projection_favorites import ProjectionFavorites
from openpilot.starpilot.system.starport.projection_layout import (default_layout_for_viewport, projection_customization,
validate_layout_for_viewport)
from openpilot.starpilot.ui.onroad_customization import default_document
native, _ = self.dependencies()
owner = Mock()
owner.read.return_value = {'revision': 'r1', 'enabled': True, 'token': 't', 'destination': None,
'favorites': [{'id': 'h', 'label': 'home'}, {'id': 'w', 'label': 'work'}]}
native.favorites = lambda authorized: ProjectionFavorites(authorized, owner)
track = track or {'status': 'playing', 'title': 'Song', 'artist': 'Artist', 'shuffle': False, 'repeat': 'off', 'source': 'spotify'}
native.now_playing_feed = lambda: Mock(snapshot=Mock(return_value=track), artwork=Mock(return_value=('', None)))
native.now_playing_control = Mock()
layout = default_layout_for_viewport((1860, 1116))
widgets = layout['widgets']
widgets['now_playing'].update(enabled=True, x=1310, y=990, size=size)
for key, (x, y) in {'nav_home': (1340, 100), 'nav_work': (1460, 100), 'bookmark': (270, 976)}.items():
widgets[key].update(enabled=True, display=display)
if display == 'icons':
widgets[key].update(x=x, y=y)
layout = validate_layout_for_viewport(layout, (1860, 1116))
view = projection.ProjectionOnroad(dependencies=native, viewport=(1860, 1116), customization=layout)
self.addCleanup(view.close)
view.favorites.bookmark = Mock(return_value=True)
native.ui_state.started = True
view._state = SimpleNamespace(customization=projection_customization(layout, default_document()), alert=SimpleNamespace(size='none'),
viewport_width=1860)
view.onroad.now_playing = SimpleNamespace(track=track, showing=lambda: track)
view.now_playing_touch.feedback = None
return view, native, owner
def tap(self, view, x, y):
view.handle_touches([SimpleNamespace(kind='down', x=x / 1860, y=y / 1116), SimpleNamespace(kind='up', x=x / 1860, y=y / 1116)])
def test_each_big_now_playing_button_responds_to_touch(self):
from openpilot.starpilot.ui.onroad_now_playing import CONTROLS, card_layout
view, native, _ = self.touch_view('icons')
placed = view._state.customization['layouts']['large']['now_playing']
card, buttons = card_layout(placed, view.onroad.now_playing.track, 1860)
self.assertEqual((card.width, card.height), (640, 264))
self.assertLessEqual(card.x + card.width, 1830) # the saved small spot slid back so the big card stays on screen
for name in CONTROLS:
native.now_playing_control.reset_mock()
box = buttons[name]
self.tap(view, box.x + box.width / 2, box.y + box.height / 2)
expected = {'shuffle': ('shuffle', {'enabled': True}), 'repeat': ('repeat', {'mode': 'context'})}.get(name, (name, {}))
native.now_playing_control.assert_called_once_with(*expected)
native.now_playing_control.reset_mock()
self.tap(view, card.x + 300, card.y + 40)
native.now_playing_control.assert_not_called()
def test_play_on_starpilot_sends_activate(self):
from openpilot.starpilot.ui.onroad_now_playing import card_layout
track = {'source': 'spotify', 'status': 'elsewhere', 'title': '', 'device': 'StarPilot'}
for size in ('big', 'small'):
with self.subTest(size=size):
view, native, _ = self.touch_view('icons', size=size, track=track)
box = card_layout(view._state.customization['layouts']['large']['now_playing'], track, 1860)[1]['play_here']
self.tap(view, box.x + box.width / 2, box.y + box.height / 2)
native.now_playing_control.assert_called_once_with('activate', {})
def test_home_work_and_bookmark_respond_to_touch_beside_the_now_playing_card(self):
from openpilot.starpilot.system.starport.projection_layout import FAVORITE_ICON_SIZE, FAVORITE_SIZE
for display in ('icons', 'words'):
with self.subTest(display=display):
view, native, owner = self.touch_view(display)
layouts = view._state.customization['layouts']['large']
width, height = (FAVORITE_ICON_SIZE,) * 2 if display == 'icons' else FAVORITE_SIZE
card = layouts['now_playing']
for key in ('nav_home', 'nav_work', 'bookmark'):
placed = layouts[key]
apart = (placed['x'] + width <= card['x'] or placed['x'] >= card['x'] + 640 or
placed['y'] + height <= card['y'] or placed['y'] >= card['y'] + 264)
self.assertTrue(apart, f'{key} overlaps the now-playing card')
self.tap(view, placed['x'] + width / 2, placed['y'] + height / 2)
self.assertEqual([c.args[0]['label'] for c in owner.select.call_args_list], ['home', 'work'])
view.favorites.bookmark.assert_called_once_with()
native.now_playing_control.assert_not_called()
def test_car_escape_control_remains_active_on_standby(self):
from openpilot.starpilot.system.starport.projection_layout import CAR_EXIT, default_layout_for_viewport
native, _ = self.dependencies()
@@ -229,7 +229,8 @@ class _Canvas:
from openpilot.starpilot.system.starport.projection_exit import ProjectionExit
self.view.projection_exit_layer = ProjectionExit(rl).render
self.view.now_playing.track = {'source': 'spotify', 'status': 'playing', 'title': 'Midnight City', 'artist': 'M83', 'album': '',
'durationMs': 243000, 'position': {'ms': 92000, 'at': 0, 'speed': 0.0}}
'durationMs': 243000, 'position': {'ms': 92000, 'at': 0, 'speed': 0.0},
'shuffle': False, 'repeat': 'off', 'artwork': '', 'device': 'StarPilot'}
if profile == Profile.LARGE:
from openpilot.starpilot.ui.onroad_map import MapOverlay, SampleTileReader
self.map = MapOverlay(reader=SampleTileReader(), fonts=self.fonts)
+2
View File
@@ -597,6 +597,8 @@ class OnroadView:
gui_app.remove_render_prepare(self.torque_bar.prepare)
self.torque_bar.close()
self.navigation.close()
if now_playing := getattr(self, "now_playing", None):
now_playing.close()
if self.fonts.profile == Profile.LARGE:
self.unified_speed.close()
self.steering_wheel.close()
+580 -44
View File
@@ -1,67 +1,603 @@
"""The Android Auto now-playing card; both live rendering and previews use this drawing."""
"""The Android Auto now-playing card; both live rendering and previews use this drawing.
Hit boxes, NowPlayingTouch, cover art, TrackText, scrolling names, the control glyphs and the
'Play on StarPilot' take-over are adapted from Peter Nguyen's now-playing card.
"""
import math
import time
import unicodedata
from functools import cache
from importlib.resources import as_file, files
import numpy as np
from openpilot.starpilot.ui.raylib import rl
from openpilot.starpilot.soloist.now_playing import elapsed_ms
from openpilot.starpilot.system.starport.projection_layout import NOW_PLAYING_SIZE, NOW_PLAYING_WIDGET
from openpilot.starpilot.ui.presentation import FontRole
from openpilot.starpilot.soloist.now_playing import ELSEWHERE, elapsed_ms
from openpilot.starpilot.system.starport.projection_layout import NOW_PLAYING_WIDGET, now_playing_size
from openpilot.starpilot.ui import clip
from openpilot.starpilot.ui.presentation import FontRole, TextSize
PRIMARY = rl.Color(157, 114, 255, 255)
BT_BLUE = rl.Color(96, 165, 250, 255)
ACCENT = rl.Color(199, 174, 247, 255)
INK = rl.Color(15, 13, 23, 255)
TEXT = rl.Color(245, 242, 252, 255)
MUTED = rl.Color(184, 178, 200, 255)
BUTTON_R = 30
MUTED = rl.Color(214, 210, 224, 255)
TIMES = rl.Color(184, 178, 200, 255)
DIM = rl.Color(214, 210, 224, 77)
DISC = rl.Color(255, 255, 255, 36)
CHIP = rl.Color(0, 0, 0, 89)
BORDER = rl.Color(255, 255, 255, 31)
WASH = (27, 20, 56)
COVER_TINT = (80, 78, 92)
CONTROLS = ('shuffle', 'previous', 'play_pause', 'next', 'repeat')
REPEAT_NEXT = {'off': 'context', 'context': 'track', 'track': 'off'}
BIG_RADIUS = 40
PAD = 40
SLOT = 96
ROW_TOP = 160
ROW_Y = 208
BUTTON_R = 32
PLAY_R = 36
COLLAPSED = 96
PLAY_HERE = (320, 64)
SCROLL_SPEED = 40
SCROLL_GAP = 60
SCROLL_PAUSE = 2.0
HOLD = 4.0
PENDING = 3.0
PRESS_FADE = .35
PRESS_MAX = 2.0
TRACK_FONTS = {FontRole.SEMI_BOLD: 'Inter-SemiBold.ttf', FontRole.NORMAL: 'Inter-Regular.ttf'}
TRACK_FONT_PX = 48
ASCII = range(32, 127)
def _play_pause(center: rl.Vector2, playing: bool) -> None:
"""An accent disc with the pause bars while playing, else the play triangle."""
rl.draw_circle_v(center, BUTTON_R, ACCENT)
if playing:
for dx in (-9, 3):
rl.draw_rectangle_rounded(rl.Rectangle(center.x + dx, center.y - 12, 6, 24), .5, 4, INK)
def _kind(placed, track):
if track['status'] == ELSEWHERE:
return 'elsewhere'
if track['status'] != 'playing' and placed.get('collapse'):
return 'collapsed'
return 'big' if placed.get('size') == 'big' else 'small'
def card_layout(placed, track, viewport_width):
"""(card rect, {control: hit rect}) for what is drawn, or None. Rendering and taps share it."""
if not placed or not placed['enabled'] or not track:
return None
rect = rl.Rectangle(placed['x'], placed['y'], *now_playing_size(placed))
kind, big = _kind(placed, track), placed.get('size') == 'big'
if kind == 'elsewhere':
if not big:
return rect, {'play_here': rect}
button = rl.Rectangle(rect.x + (rect.width - PLAY_HERE[0]) / 2, rect.y + 140, *PLAY_HERE)
return rect, {'play_here': button}
if kind == 'collapsed':
right = rect.x + rect.width / 2 > viewport_width / 2
button = rl.Rectangle(rect.x + rect.width - COLLAPSED if right else rect.x, rect.y + rect.height - COLLAPSED, COLLAPSED, COLLAPSED)
return button, {'play_pause': button}
if kind == 'small':
return rect, {'play_pause': rl.Rectangle(rect.x, rect.y, rect.height, rect.height)}
left = rect.x + rect.width / 2 - SLOT * len(CONTROLS) / 2
return rect, {name: rl.Rectangle(left + index * SLOT, rect.y + ROW_TOP, SLOT, rect.height - ROW_TOP)
for index, name in enumerate(CONTROLS)}
def _alpha(color, alpha: float) -> rl.Color:
return rl.Color(color.r, color.g, color.b, round(color.a * alpha))
def _center(box: rl.Rectangle) -> rl.Vector2:
return rl.Vector2(box.x + box.width / 2, box.y + box.height / 2)
def _play(c: rl.Vector2, k: float, color) -> None:
rl.draw_triangle(rl.Vector2(c.x - 8 * k, c.y - 14 * k), rl.Vector2(c.x - 8 * k, c.y + 14 * k), rl.Vector2(c.x + 14 * k, c.y), color)
def _pause(c: rl.Vector2, k: float, color) -> None:
for dx in (-10, 3):
rl.draw_rectangle_rounded(rl.Rectangle(c.x + dx * k, c.y - 13 * k, 7 * k, 26 * k), .5, 4, color)
def _spinner(c: rl.Vector2, k: float, now: float, color) -> None:
start = now * 360 % 360
rl.draw_ring(c, 13 * k, 17 * k, start, start + 270, 24, color)
def _play_pause(c: rl.Vector2, r: float, playing: bool, busy_at: float | None = None) -> None:
"""A white disc with a dark play or pause glyph; a turning arc while the player is busy."""
rl.draw_circle_v(c, r, TEXT)
k = r / PLAY_R
if busy_at is not None:
_spinner(c, k, busy_at, INK)
elif playing:
_pause(c, k, INK)
else:
rl.draw_triangle(rl.Vector2(center.x - 7, center.y - 13), rl.Vector2(center.x - 7, center.y + 13), rl.Vector2(center.x + 13, center.y), INK)
_play(c, k, INK)
def _skip(c: rl.Vector2, forward: bool) -> None:
rl.draw_circle_v(c, BUTTON_R, DISC)
d = 1 if forward else -1
tip, back = c.x + 9 * d, c.x - 9 * d
points = (rl.Vector2(back, c.y - 12), rl.Vector2(back, c.y + 12), rl.Vector2(tip, c.y))
rl.draw_triangle(*(points if forward else (points[1], points[0], points[2])), TEXT)
rl.draw_rectangle_rounded(rl.Rectangle(tip + (0 if forward else -5), c.y - 12, 5, 24), .5, 4, TEXT)
def _toggle_color(state, on):
return DIM if state is None else ACCENT if on else MUTED
def _bezier(p0, p1, p2, p3, steps=8):
return tuple(tuple((1 - t) ** 3 * a + 3 * (1 - t) ** 2 * t * b + 3 * (1 - t) * t * t * c + t ** 3 * d
for a, b, c, d in zip(p0, p1, p2, p3, strict=True))
for t in (i / steps for i in range(steps + 1)))
SHUFFLE_PATHS = tuple(path for y0, y1 in ((-10, 10), (10, -10))
for path in (_bezier((-16, y0), (0, y0), (0, y1), (18, y1)), ((13, y1 - 6), (19, y1), (13, y1 + 6))))
def _stroke(points, thick, color) -> None:
for a, b in zip(points, points[1:], strict=False):
rl.draw_line_ex(a, b, thick, color)
for point in points[::len(points) - 1]:
rl.draw_circle_v(point, thick / 2, color)
def _shuffle(c: rl.Vector2, state) -> None:
color = _toggle_color(state, state)
for path in SHUFFLE_PATHS:
_stroke([rl.Vector2(c.x + dx, c.y + dy) for dx, dy in path], 3.5, color)
if state:
rl.draw_circle_v(rl.Vector2(c.x, c.y + 26), 3, color)
def _repeat(c: rl.Vector2, state) -> None:
color = _toggle_color(state, state in ('context', 'track'))
x, y = c.x, c.y
rl.draw_line_ex(rl.Vector2(x - 14, y - 9), rl.Vector2(x + 12, y - 9), 4, color)
rl.draw_line_ex(rl.Vector2(x + 14, y + 9), rl.Vector2(x - 12, y + 9), 4, color)
rl.draw_line_ex(rl.Vector2(x - 16, y - 11), rl.Vector2(x - 16, y + 4), 4, color)
rl.draw_line_ex(rl.Vector2(x + 16, y + 11), rl.Vector2(x + 16, y - 4), 4, color)
rl.draw_triangle(rl.Vector2(x + 10, y - 16), rl.Vector2(x + 10, y - 2), rl.Vector2(x + 19, y - 9), color)
rl.draw_triangle(rl.Vector2(x - 10, y + 16), rl.Vector2(x - 10, y + 2), rl.Vector2(x - 19, y + 9), color)
if state == 'track':
rl.draw_rectangle_rounded(rl.Rectangle(x - 2, y - 5, 4, 10), .5, 4, color)
if state in ('context', 'track'):
rl.draw_circle_v(rl.Vector2(x, y + 26), 3, color)
def _bluetooth(c: rl.Vector2, k: float, color) -> None:
top, bottom, side, thick = rl.Vector2(c.x, c.y - 11 * k), rl.Vector2(c.x, c.y + 11 * k), 6 * k, 2.4 * k
_stroke([rl.Vector2(c.x - side, c.y - 6 * k), rl.Vector2(c.x + side, c.y + 5.5 * k), bottom, top,
rl.Vector2(c.x + side, c.y - 5.5 * k), rl.Vector2(c.x - side, c.y + 6 * k)], thick, color)
def _note(c: rl.Vector2, k: float, color) -> None:
rl.draw_circle_v(rl.Vector2(c.x - 3 * k, c.y + 7 * k), 5 * k, color)
rl.draw_rectangle_rec(rl.Rectangle(c.x, c.y - 11 * k, 2.6 * k, 18 * k), color)
rl.draw_rectangle_rec(rl.Rectangle(c.x, c.y - 11 * k, 8 * k, 3.2 * k), color)
def _speaker(c: rl.Vector2, k: float, color) -> None:
x, y = c.x - 3 * k, c.y
rl.draw_rectangle_rec(rl.Rectangle(x - 10 * k, y - 5 * k, 5 * k, 10 * k), color)
a, b, cc, d = (rl.Vector2(x - 5 * k, y - 5 * k), rl.Vector2(x + 4 * k, y - 12 * k),
rl.Vector2(x + 4 * k, y + 12 * k), rl.Vector2(x - 5 * k, y + 5 * k))
rl.draw_triangle(a, d, cc, color)
rl.draw_triangle(a, cc, b, color)
rl.draw_ring(rl.Vector2(x + 6 * k, y), 6 * k, 8.5 * k, -50, 50, 10, color)
def _source_glyph(c: rl.Vector2, k: float, source: str) -> None:
if source == 'phone':
_bluetooth(c, k, BT_BLUE)
else:
_note(c, k, ACCENT)
def clock_text(ms):
seconds = max(0, int(ms // 1000))
return f'{seconds // 60}:{seconds % 60:02d}'
def scroll_offset(text_width, width, seconds):
"""How far a too-wide line has scrolled left: still for SCROLL_PAUSE, then one pass to where its repeat starts."""
if text_width <= width:
return 0.0
travel = text_width + SCROLL_GAP
return min(travel, max(0.0, seconds % (SCROLL_PAUSE + travel / SCROLL_SPEED) - SCROLL_PAUSE) * SCROLL_SPEED)
@cache
def pill_rows(height, r, step=2):
"""(y, height, inset) strips that fill a rounded rect, so the cover takes the card's shape without a shader."""
r = min(r, height / 2)
rows = []
for top in (True, False):
if not top and height > 2 * r:
rows.append((r, height - 2 * r, 0.0))
y = 0.0
while y < r:
h = min(step, r - y)
dy = r - (y + h / 2)
rows.append(((y if top else height - y - h), h, r - math.sqrt(r * r - dy * dy)))
y += h
return tuple(rows)
def nfc(text):
return unicodedata.normalize('NFC', text)
class TrackText:
"""Song and device names. The bitmap atlases hold ASCII only, so other names are drawn from the Inter TTF
cut to ASCII plus that name's letters, one atlas per slot, replaced when the name changes."""
def __init__(self, fonts):
self.fonts = fonts
self._cut = {}
def _font(self, text, role, slot):
covers = getattr(self.fonts, 'covers', None)
if covers is None or role not in TRACK_FONTS:
return None
key = (role, slot)
cut = self._cut.get(key)
if cut is None or cut[0] != text:
self._unload(key)
self._cut[key] = (text, None if covers(text, role) else self._load(text, role))
return self._cut[key][1]
@staticmethod
def _load(text, role):
codepoints = sorted({*ASCII, *map(ord, text)})
glyphs = np.array(codepoints, dtype=np.int32)
with as_file(files("openpilot.selfdrive").joinpath("assets/fonts", TRACK_FONTS[role])) as path:
font = rl.load_font_ex(str(path), TRACK_FONT_PX, glyphs, len(codepoints))
if font.texture.id in (0, rl.get_font_default().texture.id) or font.glyphCount == 0:
return None
rl.gen_texture_mipmaps(font.texture)
rl.set_texture_filter(font.texture, rl.TextureFilter.TEXTURE_FILTER_TRILINEAR)
return font
def _unload(self, key):
cut = self._cut.pop(key, None)
if cut is not None and cut[1] is not None and rl.is_window_ready():
rl.rl_draw_render_batch_active() # draws already queued with this atlas
rl.unload_font(cut[1])
def close(self):
for key in list(self._cut):
self._unload(key)
def measure(self, text, role, size, slot=None):
if (font := self._font(text, role, slot)) is None:
return self.fonts.measure(text, role, size)
measured = rl.measure_text_ex(font, text, size * self.fonts.profile.font_scale, 0) # noqa: TID251
return TextSize(measured.x, measured.y)
def draw(self, text, role, size, x, y, color, slot=None):
if (font := self._font(text, role, slot)) is None:
self.fonts.draw(text, role, size, x, y, color)
return
draw = getattr(rl, "_orig_draw_text_ex", rl.draw_text_ex)
draw(font, text, rl.Vector2(x, y), size * self.fonts.profile.font_scale, 0, color)
def _song_key(track):
return track.get('title'), track.get('artist'), track.get('status'), track.get('position')
class NowPlayingWidget:
def __init__(self, fonts, clock=time.time): # noqa: TID251 epoch-ms track anchors
def __init__(self, fonts, clock=time.time, ticks=time.monotonic): # noqa: TID251 epoch-ms track anchors
self.fonts = fonts
self.text = TrackText(fonts)
self.clock = clock
self.ticks = ticks
self.track = None
self.artwork: tuple[str, tuple[int, int, bytes] | None] = ('', None)
self._cover = None # (url, texture or None)
self._scroll = {}
self._shown = None
self._press = None
self._pending = None
def _fit(self, text, role, size, width):
measured = self.fonts.measure(text, role, size)
return size * width / measured.width if measured.width > width else size
def press(self, name):
self._press = (name, self.ticks(), None)
def release(self, fired):
now = self.ticks()
if self._press is not None:
self._press = (self._press[0], self._press[1], now)
if fired in ('previous', 'next', 'play_pause', 'play_here') and (track := self.showing()):
self._pending = (_song_key(track), now)
def showing(self):
"""The feed's song, or the last one for HOLD seconds so a skip does not blink the card out."""
if self.track:
return self.track
if self._shown is not None and self.ticks() - self._shown[1] < HOLD:
return self._shown[0]
return None
def close(self):
self._drop_cover()
self.text.close()
def _drop_cover(self):
if self._cover is not None and self._cover[1] is not None and rl.is_window_ready():
rl.rl_draw_render_batch_active()
rl.unload_texture(self._cover[1])
self._cover = None
def _cover_texture(self):
url, data = self.artwork
if not url and self.track is None and self._cover is not None:
return self._cover[1] # between songs: keep the last cover rather than flash the plain card
if self._cover is not None and self._cover[0] == url:
return self._cover[1]
self._drop_cover()
texture = None
if url and data:
width, height, pixels = data
texture = rl.load_texture_from_image(rl.Image(None, width, height, 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8))
if texture.id:
rl.update_texture(texture, pixels)
rl.set_texture_filter(texture, rl.TextureFilter.TEXTURE_FILTER_BILINEAR)
else:
texture = None
self._cover = (url, texture)
return texture
def _busy(self, track, now):
if track is not self.track:
return True
if self._pending is not None and (_song_key(track) != self._pending[0] or now - self._pending[1] >= PENDING):
self._pending = None
return self._pending is not None
def _pressed(self, name, now):
"""1 while held on ``name``, fading after the lift, else 0."""
if self._press is None or self._press[0] != name:
return 0.0
down, up = self._press[1:]
if up is None:
return 1.0 if now - down < PRESS_MAX else 0.0
return max(0.0, 1 - (now - up) / PRESS_FADE)
def _scrolling(self, slot, text, line_width, draw, x, y, width, height):
"""``draw(left)`` once when the line fits ``width``; otherwise scroll it left inside a clip, then repeat."""
if line_width <= width:
draw(x)
return
now = self.ticks()
held = self._scroll.get(slot)
if held is None or held[0] != text:
held = self._scroll[slot] = (text, now)
offset = scroll_offset(line_width, width, now - held[1])
clip.begin_scissor_mode(x, y, width, height)
try:
for start in (x - offset, x - offset + line_width + SCROLL_GAP):
if start < x + width:
draw(start)
finally:
clip.end_scissor_mode()
def _line(self, text, role, size, x, cy, width, color, slot):
"""One name, vertically centered on ``cy``, scrolling when wider than ``width``."""
measured = self.text.measure(text, role, size, slot)
top = cy - measured.height / 2
self._scrolling(slot, text, measured.width, lambda left: self.text.draw(text, role, size, left, top, color, slot),
x, top - 4, width, measured.height + 8)
def _background(self, rect, radius, opacity, texture):
if texture is None:
rl.draw_rectangle_rounded(rect, min(1.0, 2 * radius / min(rect.width, rect.height)), 24, rl.Color(*WASH, round(255 * opacity)))
return
tint = rl.Color(*COVER_TINT, round(255 * opacity))
band = texture.height * rect.height / rect.width
scale = texture.width / rect.width
top = (texture.height - band) / 2
for y, height, inset in pill_rows(rect.height, radius):
rl.draw_texture_pro(texture, rl.Rectangle(inset * scale, top + y * scale, (rect.width - 2 * inset) * scale, height * scale),
rl.Rectangle(rect.x + inset, rect.y + y, rect.width - 2 * inset, height), rl.Vector2(0, 0), 0, tint)
def _press_disc(self, center, r, name, now):
if (pressed := self._pressed(name, now)) > 0:
rl.draw_circle_v(center, r + 8, rl.Color(255, 255, 255, round(60 * pressed)))
def render(self, state):
placed = state.customization['layouts']['large'].get(NOW_PLAYING_WIDGET)
track = self.track
if not placed or not placed['enabled'] or not track or state.alert.size != 'none':
now = self.ticks()
if self.track:
self._shown = (self.track, now) if self.track['status'] != ELSEWHERE else None
track = self.showing()
if state.alert.size != 'none' or (shape := card_layout(placed, track, getattr(state, 'viewport_width', 0))) is None:
return
rect = rl.Rectangle(placed['x'], placed['y'], *NOW_PLAYING_SIZE)
h = rect.height
background = rl.Color(15, 13, 23, round(235 * placed.get('opacity', 85) / 100))
playing = track['status'] == 'playing'
if not playing and placed.get('collapse'):
# Paused: just the play button, at whichever end of the card sits nearer the screen edge.
right = rect.x + rect.width / 2 > getattr(state, 'viewport_width', 0) / 2
button = rl.Rectangle(rect.x + rect.width - h if right else rect.x, rect.y, h, h)
rl.draw_rectangle_rounded(button, 1.0, 16, background)
_play_pause(rl.Vector2(button.x + h / 2, button.y + h / 2), False)
return
rl.draw_rectangle_rounded(rect, 1.0, 16, background)
_play_pause(rl.Vector2(rect.x + h / 2, rect.y + h / 2), playing)
left = rect.x + h + 4
width = rect.x + rect.width - h / 2 - left
rows = ((track['title'], FontRole.SEMI_BOLD, 30, 12, TEXT), (track['artist'] or track['album'], FontRole.NORMAL, 22, 46, MUTED))
for text, role, size, y, color in rows:
if text:
self.fonts.draw(text, role, self._fit(text, role, size, width), left, rect.y + y, color)
rect, buttons = shape
opacity = placed.get('opacity', 85) / 100
kind = _kind(placed, track)
if kind == 'collapsed':
center = _center(rect)
rl.draw_circle_v(center, rect.width / 2, rl.Color(*WASH, round(255 * opacity)))
self._press_disc(center, PLAY_R, 'play_pause', now)
_play_pause(center, PLAY_R, False, now if self._busy(track, now) else None)
elif kind == 'elsewhere':
self._elsewhere(rect, buttons['play_here'], track, opacity, now, placed.get('size') == 'big')
elif kind == 'small':
self._small(rect, track, opacity, now)
else:
self._big(rect, buttons, track, opacity, now)
def _source_label(self, track):
return 'Phone' if track.get('source') == 'phone' else nfc(track.get('device') or 'StarPilot')
def _chip(self, x, cy, track):
label = self._source_label(track)
measured = self.text.measure(label, FontRole.SEMI_BOLD, 18, 'chip')
chip = rl.Rectangle(x, cy - 18, 14 + 20 + 8 + measured.width + 14, 36)
rl.draw_rectangle_rounded(chip, 1.0, 16, CHIP)
rl.draw_rectangle_rounded_lines_ex(chip, 1.0, 16, 1, BORDER)
_source_glyph(rl.Vector2(x + 24, cy), .85, track.get('source'))
self.text.draw(label, FontRole.SEMI_BOLD, 18, x + 42, cy - measured.height / 2, TEXT, 'chip')
def _big(self, rect, buttons, track, opacity, now):
texture = self._cover_texture() if track.get('source') == 'spotify' else None
self._background(rect, BIG_RADIUS, opacity, texture)
self._chip(rect.x + PAD, rect.y + 38, track)
service = 'Spotify' if track.get('source') == 'spotify' else nfc(track.get('device') or 'Bluetooth')
service_size = self.text.measure(service, FontRole.NORMAL, 18, 'service')
self.text.draw(service, FontRole.NORMAL, 18, rect.x + rect.width - PAD - service_size.width, rect.y + 38 - service_size.height / 2,
MUTED, 'service')
self._title_line(rect, track)
self._seek_bar(rect, track)
row = {name: rl.Vector2(_center(buttons[name]).x, rect.y + ROW_Y) for name in CONTROLS}
for name, center in row.items():
self._press_disc(center, PLAY_R if name == 'play_pause' else BUTTON_R, name, now)
_shuffle(row['shuffle'], track.get('shuffle'))
_skip(row['previous'], False)
_play_pause(row['play_pause'], PLAY_R, track['status'] == 'playing', now if self._busy(track, now) else None)
_skip(row['next'], True)
_repeat(row['repeat'], track.get('repeat'))
def _title_line(self, rect, track):
""""Title • Artist" centered on one line; the artist regular and muted. A line too wide scrolls."""
title, artist = nfc(track['title']), nfc(track.get('artist') or track.get('album') or '')
size, dot = 30, 32
title_size = self.text.measure(title, FontRole.SEMI_BOLD, size, 'title')
artist_width = self.text.measure(artist, FontRole.NORMAL, size, 'artist').width if artist else 0
line_width = title_size.width + (dot + artist_width if artist else 0)
width = rect.width - 2 * PAD
cy = rect.y + 82
top = cy - title_size.height / 2
def draw(x):
self.text.draw(title, FontRole.SEMI_BOLD, size, x, top, TEXT, 'title')
if artist:
rl.draw_circle_v(rl.Vector2(x + title_size.width + dot / 2, cy), 3.5, MUTED)
self.text.draw(artist, FontRole.NORMAL, size, x + title_size.width + dot, top, MUTED, 'artist')
left = rect.x + PAD if line_width > width else rect.x + rect.width / 2 - line_width / 2
self._scrolling('line', f'{title}\n{artist}', line_width, draw, left, top - 4, width, title_size.height + 8)
def _seek_bar(self, rect, track):
left, right, y = rect.x + PAD, rect.x + rect.width - PAD, rect.y + 112
rl.draw_rectangle_rounded(rl.Rectangle(left, y, right - left, 10), 1.0, 8, rl.Color(255, 255, 255, 46))
duration = track.get('durationMs')
if duration and track.get('position'):
bar = rl.Rectangle(left, rect.y + h - 16, width, 4)
rl.draw_rectangle_rounded(bar, 1.0, 4, rl.Color(255, 255, 255, 50))
done = min(1.0, elapsed_ms(track, self.clock() * 1000) / duration)
if done > 0:
rl.draw_rectangle_rounded(rl.Rectangle(bar.x, bar.y, max(bar.height, bar.width * done), bar.height), 1.0, 4, ACCENT)
if not duration:
return
elapsed = min(duration, elapsed_ms(track, self.clock() * 1000) if track.get('position') else 0)
done = (right - left) * elapsed / duration
if done > 0:
rl.draw_rectangle_rounded(rl.Rectangle(left, y, max(10, done), 10), 1.0, 8, TEXT)
total = clock_text(duration)
self.fonts.draw(clock_text(elapsed), FontRole.NORMAL, 16, left, y + 16, TIMES)
self.fonts.draw(total, FontRole.NORMAL, 16, right - self.fonts.measure(total, FontRole.NORMAL, 16).width, y + 16, TIMES)
def _small(self, rect, track, opacity, now):
texture = self._cover_texture() if track.get('source') == 'spotify' else None
h = rect.height
self._background(rect, h / 2, opacity, texture)
disc = rl.Vector2(rect.x + h / 2, rect.y + h / 2)
self._press_disc(disc, PLAY_R, 'play_pause', now)
_play_pause(disc, PLAY_R, track['status'] == 'playing', now if self._busy(track, now) else None)
left = rect.x + h + 4
width = rect.x + rect.width - 20 - 44 - 12 - left
self._line(nfc(track['title']), FontRole.SEMI_BOLD, 26, left, rect.y + 33, width, TEXT, 'title')
artist = nfc(track.get('artist') or track.get('album') or '')
if artist:
self._line(artist, FontRole.NORMAL, 19, left, rect.y + 64, width, MUTED, 'artist')
_source_glyph(rl.Vector2(rect.x + rect.width - 20 - 22, rect.y + h / 2), 1.3, track.get('source'))
def _elsewhere(self, rect, button, track, opacity, now, big):
name = nfc(track.get('device') or 'StarPilot')
busy = self._busy(track, now)
pressed = self._pressed('play_here', now)
if not big:
h = rect.height
self._background(rect, h / 2, opacity, None)
if pressed > 0:
rl.draw_rectangle_rounded(rect, 1.0, 24, rl.Color(255, 255, 255, round(40 * pressed)))
disc = rl.Vector2(rect.x + h / 2, rect.y + h / 2)
rl.draw_circle_v(disc, PLAY_R, TEXT)
if busy:
_spinner(disc, 1, now, INK)
else:
_speaker(disc, 1.1, INK)
width = rect.x + rect.width - 24 - (rect.x + h + 4)
self._line('Spotify is on another device', FontRole.SEMI_BOLD, 24, rect.x + h + 4, rect.y + 34, width, TEXT, 'title')
self._line(f'Tap to play on {name}', FontRole.NORMAL, 18, rect.x + h + 4, rect.y + 64, width, MUTED, 'artist')
return
self._background(rect, BIG_RADIUS, opacity, None)
for text, role, size, cy, color, slot in (('Spotify is on another device', FontRole.SEMI_BOLD, 30, 70, TEXT, 'title'),
(f'Tap to move the music to {name}', FontRole.NORMAL, 22, 108, MUTED, 'artist')):
measured = self.text.measure(text, role, size, slot)
x = rect.x + max(PAD, (rect.width - measured.width) / 2)
self._line(text, role, size, x, rect.y + cy, rect.width - 2 * PAD, color, slot)
rl.draw_rectangle_rounded(button, 1.0, 24, PRIMARY)
if pressed > 0:
rl.draw_rectangle_rounded(button, 1.0, 24, rl.Color(255, 255, 255, round(50 * pressed)))
label = f'Play on {name}'
room = button.width - 2 * 24 - 40
content = 40 + min(room, self.text.measure(label, FontRole.SEMI_BOLD, 24, 'button').width)
glyph = rl.Vector2(button.x + (button.width - content) / 2 + 14, button.y + button.height / 2)
if busy:
_spinner(glyph, .9, now, TEXT)
else:
_speaker(glyph, 1, TEXT)
self._line(label, FontRole.SEMI_BOLD, 24, glyph.x + 26, glyph.y, room, TEXT, 'button')
class NowPlayingTouch:
"""A control fires when the finger lifts on the control it went down on. Taps on the card never fall through."""
def __init__(self, send, feedback=None):
self.send = send
self.feedback = feedback
self.pressed = None
def cancel(self):
self._lift(None)
def _lift(self, fired):
if self.pressed is not None and self.feedback is not None:
self.feedback.release(fired)
self.pressed = None
def touch(self, kind, x, y, state, placed, track) -> bool:
"""True while the card owns the touch."""
shape = None if kind == 'cancel' or state is None or state.alert.size != 'none' else card_layout(placed, track, state.viewport_width)
if shape is None:
claimed = self.pressed is not None
self._lift(None)
return claimed
point = rl.Vector2(x, y)
hit = next((name for name, box in shape[1].items() if rl.check_collision_point_rec(point, box)), None)
if kind == 'down':
self.pressed = hit
if hit is not None and self.feedback is not None:
self.feedback.press(hit)
return hit is not None or rl.check_collision_point_rec(point, shape[0])
if kind == 'up':
pressed, fired = self.pressed, None
if pressed is not None and pressed == hit:
if pressed == 'shuffle':
if track.get('shuffle') is not None:
self.send('shuffle', {'enabled': not track['shuffle']})
elif pressed == 'repeat':
if track.get('repeat') in REPEAT_NEXT:
self.send('repeat', {'mode': REPEAT_NEXT[track['repeat']]})
elif pressed == 'play_here':
self.send('activate', {})
fired = pressed
else:
self.send(pressed, {})
fired = pressed
self._lift(fired)
return pressed is not None or rl.check_collision_point_rec(point, shape[0])
return self.pressed is not None
+10
View File
@@ -118,6 +118,7 @@ class BitmapFonts:
self._vertical_ink: dict[tuple, tuple[float, float]] = {}
self._horizontal_ink: dict[tuple, tuple[float, float]] = {}
self._glyph_ink: dict[str, dict[int, tuple[int, int] | None]] = {}
self._codepoints: dict[str, frozenset[int]] = {}
default_texture_id = rl.get_font_default().texture.id
try:
for filename in dict.fromkeys(font_filename(self.profile, role) for role in FontRole):
@@ -195,6 +196,14 @@ class BitmapFonts:
self._measurements[key] = TextSize(measured.x * width_scale + (weight if text else 0), measured.y)
return self._measurements[key]
def covers(self, text: str, role: FontRole) -> bool:
"""Whether the bitmap atlas has a glyph for every character."""
filename = font_filename(self.profile, role)
if filename not in self._codepoints:
font = self.font(role)
self._codepoints[filename] = frozenset(font.glyphs[index].value for index in range(font.glyphCount))
return all(ord(char) in self._codepoints[filename] for char in text)
def vertical_ink(self, text: str, role: FontRole, size: float) -> tuple[float, float]:
"""Visible glyph top/bottom, independent of the font's padded line box."""
text = native_text(tr(text)) if role != FontRole.BRAND else text
@@ -288,6 +297,7 @@ class BitmapFonts:
self._vertical_ink.clear()
self._horizontal_ink.clear()
self._glyph_ink.clear()
self._codepoints.clear()
self._measurements.clear()
def __enter__(self):
@@ -3,7 +3,13 @@ from types import SimpleNamespace
import pytest
TRACK = {'source': 'spotify', 'status': 'playing', 'title': 'Midnight City', 'artist': 'M83', 'album': '',
'durationMs': 200000, 'position': {'ms': 50000, 'at': 0, 'speed': 0.0}}
'durationMs': 200000, 'position': {'ms': 50000, 'at': 0, 'speed': 0.0}, 'shuffle': False, 'repeat': 'off',
'artwork': '', 'device': 'StarPilot'}
PHONE = {**TRACK, 'source': 'phone', 'shuffle': None, 'repeat': None, 'device': 'Pixel 9'}
ELSEWHERE = {'source': 'spotify', 'status': 'elsewhere', 'title': '', 'device': 'StarPilot'}
# Big card at x 10, y 20: centres of shuffle, previous, play/pause, next and repeat, and the row's centre line.
BUTTONS = {'shuffle': 138, 'previous': 234, 'play_pause': 330, 'next': 426, 'repeat': 522}
ROW = 228
@pytest.fixture
@@ -11,36 +17,113 @@ def widget(monkeypatch):
from openpilot.starpilot.ui import onroad_now_playing
from openpilot.starpilot.ui.onroad_now_playing import NowPlayingWidget
drawn = []
for name in ('draw_rectangle_rounded', 'draw_triangle', 'draw_circle_v'):
for name in ('draw_rectangle_rounded', 'draw_rectangle_rounded_lines_ex', 'draw_triangle', 'draw_circle_v', 'draw_line_ex', 'draw_ring',
'draw_texture_pro', 'draw_rectangle_rec'):
monkeypatch.setattr(onroad_now_playing.rl, name, lambda *args, name=name: drawn.append((name, args)))
texts = []
fonts = SimpleNamespace(measure=lambda text, role, size: SimpleNamespace(width=len(text) * size * .5),
fonts = SimpleNamespace(measure=lambda text, role, size: SimpleNamespace(width=len(text) * size * .5, height=size * 1.2),
draw=lambda text, *args: texts.append(text))
return NowPlayingWidget(fonts, clock=lambda: 0.0), drawn, texts
def state(enabled=True, opacity=85, alert='none'):
return SimpleNamespace(alert=SimpleNamespace(size=alert),
customization={'layouts': {'large': {'now_playing': {'x': 10, 'y': 20, 'enabled': enabled, 'opacity': opacity}}}})
def state(enabled=True, opacity=85, alert='none', collapse=False, x=10, size='big'):
placed = {'x': x, 'y': 20, 'enabled': enabled, 'opacity': opacity, 'collapse': collapse, 'size': size}
return SimpleNamespace(alert=SimpleNamespace(size=alert), viewport_width=1860,
customization={'layouts': {'large': {'now_playing': placed}}})
def test_draws_text_and_background_with_the_chosen_opacity(widget):
def placed_of(current):
return current.customization['layouts']['large']['now_playing']
def count(drawn, kind):
return sum(name == kind for name, _ in drawn)
def test_big_card_draws_source_service_song_and_times_over_the_chosen_opacity(widget):
card, drawn, texts = widget
card.track = TRACK
card.render(state(opacity=50))
assert texts == ['StarPilot', 'Spotify', 'Midnight City', 'M83', '0:50', '3:20']
assert drawn[0][0] == 'draw_rectangle_rounded' and drawn[0][1][0].height == 264 and drawn[0][1][3].a == round(255 * .5)
def test_phone_audio_is_labelled_phone_and_names_the_phone(widget):
card, _, texts = widget
card.track = PHONE
card.render(state())
assert texts[:2] == ['Phone', 'Pixel 9']
def test_small_card_is_a_pill_with_title_over_artist(widget):
card, drawn, texts = widget
card.track = TRACK
card.render(state(size='small'))
assert texts == ['Midnight City', 'M83']
assert drawn[0][0] == 'draw_rectangle_rounded' and drawn[0][1][3].a == round(235 * .5)
background = drawn[0][1]
assert (background[0].width, background[0].height, background[1]) == (520, 96, 1.0)
def test_paused_shows_a_play_mark_and_playing_shows_pause_bars(widget):
card, drawn, _ = widget
card.track = {**TRACK, 'status': 'paused'}
card.render(state())
assert any(name == 'draw_triangle' for name, _ in drawn)
paused = count(drawn, 'draw_triangle')
drawn.clear()
card.track = TRACK
card.render(state())
assert not any(name == 'draw_triangle' for name, _ in drawn)
assert count(drawn, 'draw_triangle') == paused - 1
def test_shuffle_and_repeat_are_dim_when_the_player_cannot_do_them(widget):
from openpilot.starpilot.ui.onroad_now_playing import DIM
card, drawn, _ = widget
card.track = PHONE
card.render(state())
dims = [args for name, args in drawn if name == 'draw_line_ex' and args[-1] is DIM]
assert dims # shuffle strokes and repeat lines
drawn.clear()
card.track = TRACK
card.render(state())
assert not any(args[-1] is DIM for name, args in drawn if name == 'draw_line_ex')
def test_shuffle_dot_only_when_on(widget):
card, drawn, _ = widget
card.track = TRACK
card.render(state())
off = count(drawn, 'draw_circle_v')
drawn.clear()
card.track = {**TRACK, 'shuffle': True}
card.render(state())
assert count(drawn, 'draw_circle_v') == off + 1
def test_repeat_shows_a_dot_when_on_and_a_bar_for_one_song(widget):
card, drawn, _ = widget
shown = {}
for mode in ('off', 'context', 'track'):
drawn.clear()
card.track = {**TRACK, 'repeat': mode}
card.render(state())
shown[mode] = (count(drawn, 'draw_circle_v'), count(drawn, 'draw_rectangle_rounded'))
assert shown['context'] == (shown['off'][0] + 1, shown['off'][1])
assert shown['track'] == (shown['off'][0] + 1, shown['off'][1] + 1)
def test_seek_bar_without_a_length_has_no_times(widget):
card, _, texts = widget
card.track = {**TRACK, 'durationMs': 0}
card.render(state())
assert texts == ['StarPilot', 'Spotify', 'Midnight City', 'M83']
@pytest.mark.parametrize('size', ['big', 'small'])
def test_collapsed_paused_card_is_just_the_play_button(widget, size):
card, drawn, texts = widget
card.track = {**TRACK, 'status': 'paused'}
card.render(state(collapse=True, size=size))
assert texts == [] and count(drawn, 'draw_triangle') == 1
@pytest.mark.parametrize('current', [state(enabled=False), state(alert='full')])
@@ -55,3 +138,397 @@ def test_nothing_drawn_without_a_track(widget):
card, drawn, texts = widget
card.render(state())
assert drawn == [] and texts == []
def test_big_buttons_sit_in_a_centered_row_in_order():
from openpilot.starpilot.ui.onroad_now_playing import CONTROLS, card_layout
rect, buttons = card_layout(placed_of(state()), TRACK, 1860)
assert (rect.width, rect.height) == (640, 264) and tuple(buttons) == CONTROLS
assert [round(box.x + box.width / 2) for box in buttons.values()] == list(BUTTONS.values())
assert all(box.y == 20 + 160 and box.y + box.height == 20 + 264 for box in buttons.values())
def test_small_card_only_has_play_pause():
from openpilot.starpilot.ui.onroad_now_playing import card_layout
rect, buttons = card_layout(placed_of(state(size='small')), TRACK, 1860)
assert (rect.width, rect.height) == (520, 96) and list(buttons) == ['play_pause']
assert (buttons['play_pause'].x, buttons['play_pause'].width) == (10, 96)
def test_saved_layout_without_a_size_is_small():
from openpilot.starpilot.ui.onroad_now_playing import card_layout
placed = placed_of(state())
del placed['size']
rect, _ = card_layout(placed, TRACK, 1860)
assert (rect.width, rect.height) == (520, 96)
@pytest.mark.parametrize('x, size, expected', [(10, 'big', (10, 188)), (1210, 'big', (1754, 188)),
(10, 'small', (10, 20)), (1330, 'small', (1754, 20))])
def test_collapsed_play_button_sits_in_the_bottom_corner_nearer_the_edge(x, size, expected):
from openpilot.starpilot.ui.onroad_now_playing import card_layout
rect, buttons = card_layout(placed_of(state(collapse=True, x=x, size=size)), {**TRACK, 'status': 'paused'}, 1860)
assert list(buttons) == ['play_pause'] and (rect.x, rect.y, rect.width, rect.height) == (*expected, 96, 96)
def tap(touch, current, track, x, y, lift=None):
placed = placed_of(current)
down = touch.touch('down', x, y, current, placed, track)
up = touch.touch('up', *(lift or (x, y)), current, placed, track)
return down, up
@pytest.mark.parametrize('action', list(BUTTONS))
def test_tap_sends_the_button_under_the_finger(action):
from openpilot.starpilot.ui.onroad_now_playing import NowPlayingTouch
sent = []
touch = NowPlayingTouch(lambda *call: sent.append(call))
assert tap(touch, state(), TRACK, BUTTONS[action], ROW) == (True, True)
args = {'shuffle': {'enabled': True}, 'repeat': {'mode': 'context'}}.get(action, {})
assert sent == [(action, args)]
def test_shuffle_and_repeat_are_inert_for_phone_audio():
from openpilot.starpilot.ui.onroad_now_playing import NowPlayingTouch
sent = []
touch = NowPlayingTouch(lambda *call: sent.append(call))
assert tap(touch, state(), PHONE, BUTTONS['shuffle'], ROW) == (True, True)
assert tap(touch, state(), PHONE, BUTTONS['repeat'], ROW) == (True, True)
tap(touch, state(), PHONE, BUTTONS['next'], ROW)
assert sent == [('next', {})]
def test_shuffle_tap_toggles_off_and_repeat_cycles():
from openpilot.starpilot.ui.onroad_now_playing import NowPlayingTouch
sent = []
touch = NowPlayingTouch(lambda *call: sent.append(call))
tap(touch, state(), {**TRACK, 'shuffle': True}, BUTTONS['shuffle'], ROW)
for mode in ('context', 'track'):
tap(touch, state(), {**TRACK, 'repeat': mode}, BUTTONS['repeat'], ROW)
assert sent == [('shuffle', {'enabled': False}), ('repeat', {'mode': 'track'}), ('repeat', {'mode': 'off'})]
def test_small_card_plays_from_its_disc_and_swallows_the_rest():
from openpilot.starpilot.ui.onroad_now_playing import NowPlayingTouch
sent = []
touch = NowPlayingTouch(lambda *call: sent.append(call))
assert tap(touch, state(size='small'), TRACK, 58, 68) == (True, True)
assert tap(touch, state(size='small'), TRACK, 300, 68) == (True, True) # the title: claimed, no action
assert tap(touch, state(size='small'), TRACK, 500, 68) == (True, True) # the source glyph: a label only
assert sent == [('play_pause', {})]
def test_card_swallows_taps_but_only_fires_on_the_same_button():
from openpilot.starpilot.ui.onroad_now_playing import NowPlayingTouch
sent = []
touch = NowPlayingTouch(lambda *call: sent.append(call))
assert tap(touch, state(), TRACK, 300, 90) == (True, True)
assert tap(touch, state(), TRACK, BUTTONS['next'], ROW, lift=(BUTTONS['previous'], ROW)) == (True, True)
assert tap(touch, state(), TRACK, 900, ROW) == (False, False)
assert sent == []
def test_collapsed_button_resumes_and_the_rest_of_the_card_rect_falls_through():
from openpilot.starpilot.ui.onroad_now_playing import NowPlayingTouch
sent = []
touch = NowPlayingTouch(lambda *call: sent.append(call))
paused = {**TRACK, 'status': 'paused'}
assert tap(touch, state(collapse=True), paused, 300, 90) == (False, False)
assert tap(touch, state(collapse=True), paused, 58, 236) == (True, True)
assert sent == [('play_pause', {})]
def test_alert_or_missing_card_releases_the_touch():
from openpilot.starpilot.ui.onroad_now_playing import NowPlayingTouch
sent = []
touch = NowPlayingTouch(lambda *call: sent.append(call))
placed = placed_of(state())
assert touch.touch('down', BUTTONS['next'], ROW, state(), placed, TRACK)
assert touch.touch('up', BUTTONS['next'], ROW, state(alert='full'), placed, TRACK)
assert not touch.touch('down', BUTTONS['next'], ROW, None, placed, TRACK)
assert sent == []
def test_scroll_holds_then_runs_one_pass_and_restarts():
from openpilot.starpilot.ui.onroad_now_playing import SCROLL_GAP, SCROLL_PAUSE, SCROLL_SPEED, scroll_offset
assert scroll_offset(100, 200, 5.0) == 0.0
assert scroll_offset(300, 200, SCROLL_PAUSE - .1) == 0.0
assert scroll_offset(300, 200, SCROLL_PAUSE + 1) == pytest.approx(SCROLL_SPEED)
cycle = SCROLL_PAUSE + (300 + SCROLL_GAP) / SCROLL_SPEED
assert scroll_offset(300, 200, cycle + .5) == 0.0
def test_long_song_line_scrolls_inside_a_clip_and_short_one_does_not(widget, monkeypatch):
from openpilot.starpilot.ui import onroad_now_playing
card, _, texts = widget
clips = []
monkeypatch.setattr(onroad_now_playing.clip, 'begin_scissor_mode', lambda *args: clips.append(args))
monkeypatch.setattr(onroad_now_playing.clip, 'end_scissor_mode', lambda: clips.append('end'))
card.track = TRACK
card.render(state())
assert clips == []
card.track = {**TRACK, 'artist': 'A very long list of featured artists on this one track'}
line = [card.track['title'], card.track['artist']]
now = [100.0]
card.ticks = lambda: now[0]
texts.clear()
card.render(state())
assert texts[2:-2] == line and clips[-1] == 'end'
now[0] += onroad_now_playing.SCROLL_PAUSE + 14
texts.clear()
card.render(state())
assert texts[2:-2] == line * 2
assert clips[0][0] == 10 + 40 and clips[0][2] == 640 - 2 * 40
def test_card_shape_strips_cover_the_card_and_round_its_corners():
from openpilot.starpilot.ui.onroad_now_playing import pill_rows
for height, radius in ((264, 40), (96, 48)):
rows = sorted(pill_rows(height, radius))
assert sum(h for _, h, _ in rows) == pytest.approx(height)
assert all(a[0] + a[1] == pytest.approx(b[0]) for a, b in zip(rows, rows[1:], strict=False))
assert rows[0][2] > radius * .6 and min(inset for *_, inset in rows) < .5
@pytest.mark.parametrize('ms, shown', [(0, '0:00'), (58_900, '0:58'), (269_000, '4:29'), (3_725_000, '62:05')])
def test_times(ms, shown):
from openpilot.starpilot.ui.onroad_now_playing import clock_text
assert clock_text(ms) == shown
@pytest.fixture
def textures(monkeypatch):
from openpilot.starpilot.ui import onroad_now_playing
rl = onroad_now_playing.rl
loads, unloads, uploads = [], [], []
monkeypatch.setattr(rl, 'Image', lambda *args: SimpleNamespace(args=args))
monkeypatch.setattr(rl, 'load_texture_from_image', lambda image: loads.append(image.args[1:3]) or
SimpleNamespace(id=len(loads), width=image.args[1], height=image.args[2]))
monkeypatch.setattr(rl, 'update_texture', lambda texture, pixels: uploads.append(len(pixels)))
monkeypatch.setattr(rl, 'set_texture_filter', lambda *args: None)
monkeypatch.setattr(rl, 'is_window_ready', lambda: True)
monkeypatch.setattr(rl, 'rl_draw_render_batch_active', lambda: None)
monkeypatch.setattr(rl, 'unload_texture', lambda texture: unloads.append(texture.id))
return loads, unloads, uploads
@pytest.mark.parametrize('size, height', [('big', 264), ('small', 96)])
def test_cover_is_uploaded_once_and_drawn_in_the_card_shape(widget, textures, size, height):
loads, unloads, uploads = textures
card, drawn, _ = widget
card.track = TRACK
card.artwork = ('https://i.scdn.co/image/a', (480, 480, b'\0' * 480 * 480 * 4))
card.render(state(size=size))
strips = [args for name, args in drawn if name == 'draw_texture_pro']
card.render(state(size=size))
assert loads == [(480, 480)] and uploads == [480 * 480 * 4]
assert sum(dest.height for _, _, dest, *_ in strips) == pytest.approx(height) and min(dest.x for _, _, dest, *_ in strips) == pytest.approx(10, abs=.5)
sources = [src for _, src, *_ in strips]
band = 480 * height / (640 if size == 'big' else 520)
assert min(src.y for src in sources) == pytest.approx((480 - band) / 2)
assert not any(name == 'draw_rectangle_rounded' and args[0].height == height for name, args in drawn)
card.track, card.artwork = None, ('', None)
card.render(state(size=size)) # held song between tracks keeps its cover
assert unloads == []
card.track = TRACK
card.render(state(size=size))
assert unloads == [1]
card.close()
def test_phone_audio_never_draws_a_cover(widget, textures):
loads, _, _ = textures
card, drawn, _ = widget
card.track = PHONE
card.artwork = ('https://i.scdn.co/image/a', (4, 4, b'\0' * 64))
card.render(state())
assert loads == [] and count(drawn, 'draw_texture_pro') == 0
class CoveringFonts:
profile = SimpleNamespace(font_scale=1.0)
def __init__(self):
self.drawn = []
def covers(self, text, role):
return text.isascii()
def measure(self, text, role, size):
return SimpleNamespace(width=len(text) * size * .5, height=size)
def draw(self, text, *args):
self.drawn.append(text)
@pytest.fixture
def cut_fonts(monkeypatch):
from openpilot.starpilot.ui import onroad_now_playing
loads, unloads, ttf_drawn = [], [], []
monkeypatch.setattr(onroad_now_playing.TrackText, '_load', staticmethod(lambda text, role: loads.append((text, role)) or f'font:{text}'))
monkeypatch.setattr(onroad_now_playing.rl, 'is_window_ready', lambda: True)
monkeypatch.setattr(onroad_now_playing.rl, 'unload_font', unloads.append)
monkeypatch.setattr(onroad_now_playing.rl, 'rl_draw_render_batch_active', lambda: None)
monkeypatch.setattr(onroad_now_playing.rl, 'draw_text_ex', lambda font, text, *args: ttf_drawn.append(text))
monkeypatch.setattr(onroad_now_playing.rl, 'measure_text_ex', lambda font, text, size, spacing: SimpleNamespace(x=len(text) * size * .5, y=size))
monkeypatch.delattr(onroad_now_playing.rl, '_orig_draw_text_ex', raising=False)
return onroad_now_playing.TrackText(CoveringFonts()), loads, unloads, ttf_drawn
def test_ascii_names_stay_on_the_bitmap_atlas(cut_fonts):
from openpilot.starpilot.ui.presentation import FontRole
text, loads, _, ttf_drawn = cut_fonts
text.draw('Midnight City', FontRole.SEMI_BOLD, 30, 0, 0, None)
assert text.fonts.drawn == ['Midnight City'] and loads == [] and ttf_drawn == []
def test_accented_name_is_cut_from_the_ttf_once_and_freed_on_the_next_song(cut_fonts):
from openpilot.starpilot.ui.presentation import FontRole
text, loads, unloads, ttf_drawn = cut_fonts
title = 'Em Về Tinh Khôi'
for _ in range(3):
text.measure(title, FontRole.SEMI_BOLD, 30)
text.draw(title, FontRole.SEMI_BOLD, 30, 0, 0, None)
assert loads == [(title, FontRole.SEMI_BOLD)] and ttf_drawn == [title] * 3 and text.fonts.drawn == []
text.draw('Midnight City', FontRole.SEMI_BOLD, 30, 0, 0, None)
assert unloads == [f'font:{title}'] and text.fonts.drawn == ['Midnight City']
text.draw('Nắng Ấm Xa Dần', FontRole.NORMAL, 22, 0, 0, None)
text.close()
assert unloads == [f'font:{title}', 'font:Nắng Ấm Xa Dần']
def test_failed_ttf_load_falls_back_to_the_atlas(cut_fonts, monkeypatch):
from openpilot.starpilot.ui import onroad_now_playing
from openpilot.starpilot.ui.presentation import FontRole
text, _, unloads, _ = cut_fonts
monkeypatch.setattr(onroad_now_playing.TrackText, '_load', staticmethod(lambda text, role: None))
text.draw('Khôi', FontRole.SEMI_BOLD, 30, 0, 0, None)
text.close()
assert text.fonts.drawn == ['Khôi'] and unloads == []
def test_decomposed_accents_are_composed_before_drawing(widget):
card, _, texts = widget
card.track = {**TRACK, 'title': 'Về', 'artist': 'Khôi'}
card.render(state())
assert texts[2:4] == ['Về', 'Khôi']
class Clock:
def __init__(self):
self.now = 100.0
def __call__(self):
return self.now
@pytest.fixture
def timed(widget):
card, drawn, texts = widget
card.ticks = clock = Clock()
return card, drawn, texts, clock
def spinning(drawn):
return sum(name == 'draw_ring' and args[4] - args[3] == 270 for name, args in drawn) == 1
def test_card_holds_the_last_song_while_the_player_buffers_the_next(timed):
card, drawn, texts, clock = timed
card.track = TRACK
card.render(state())
card.track = None
clock.now += 1
texts.clear()
drawn.clear()
card.render(state())
assert 'Midnight City' in texts and spinning(drawn) and card.showing() is TRACK
clock.now += 4
drawn.clear()
card.render(state())
assert drawn == [] and card.showing() is None
def test_play_button_spins_until_the_player_answers_a_skip(timed):
from openpilot.starpilot.ui.onroad_now_playing import NowPlayingTouch
card, drawn, _, clock = timed
card.track = TRACK
touch = NowPlayingTouch(lambda *call: None, card)
tap(touch, state(), TRACK, BUTTONS['next'], ROW)
card.render(state())
assert spinning(drawn)
card.track = {**TRACK, 'title': 'Wait'}
drawn.clear()
card.render(state())
assert not spinning(drawn)
tap(touch, state(), card.track, BUTTONS['play_pause'], ROW)
clock.now += 3
drawn.clear()
card.render(state())
assert not spinning(drawn)
def test_a_pressed_button_lights_and_fades_after_the_lift(timed):
from openpilot.starpilot.ui.onroad_now_playing import BUTTON_R, NowPlayingTouch
card, drawn, _, clock = timed
card.track = TRACK
placed = placed_of(state())
touch = NowPlayingTouch(lambda *call: None, card)
def lit():
return [args for name, args in drawn if name == 'draw_circle_v' and args[1] == BUTTON_R + 8 and abs(args[0].x - BUTTONS['previous']) < 1]
touch.touch('down', BUTTONS['previous'], ROW, state(), placed, TRACK)
card.render(state())
assert lit()[0][2].a == 60
touch.touch('up', BUTTONS['previous'], ROW, state(), placed, TRACK)
clock.now += .2
drawn.clear()
card.render(state())
assert 0 < lit()[0][2].a < 60
clock.now += .2
drawn.clear()
card.render(state())
assert lit() == []
@pytest.mark.parametrize('size', ['big', 'small'])
def test_play_on_starpilot_shows_while_spotify_plays_elsewhere(timed, size):
card, drawn, texts, _ = timed
card.track = ELSEWHERE
card.render(state(size=size, collapse=True))
assert texts[0] == 'Spotify is on another device'
assert texts[-1] == ('Play on StarPilot' if size == 'big' else 'Tap to play on StarPilot')
assert not spinning(drawn)
@pytest.mark.parametrize('size', ['big', 'small'])
def test_play_on_starpilot_tap_activates_spotify_here_and_spins_until_the_song_arrives(timed, size):
from openpilot.starpilot.ui.onroad_now_playing import NowPlayingTouch, card_layout
card, drawn, texts, clock = timed
card.track = ELSEWHERE
sent = []
touch = NowPlayingTouch(lambda *call: sent.append(call), card)
box = card_layout(placed_of(state(size=size)), ELSEWHERE, 1860)[1]['play_here']
assert tap(touch, state(size=size), ELSEWHERE, box.x + box.width / 2, box.y + box.height / 2) == (True, True)
assert sent == [('activate', {})]
card.render(state(size=size))
assert spinning(drawn)
card.track = TRACK
texts.clear()
card.render(state(size=size))
assert 'Midnight City' in texts
card.track = ELSEWHERE
clock.now += 1
card.render(state(size=size))
card.track = None
assert card.showing() is None
def test_big_play_on_starpilot_only_fires_from_its_button(timed):
from openpilot.starpilot.ui.onroad_now_playing import NowPlayingTouch
card, _, _, _ = timed
sent = []
touch = NowPlayingTouch(lambda *call: sent.append(call), card)
assert tap(touch, state(), ELSEWHERE, 60, 60) == (True, True)
assert sent == []