Navigation: Easy sharing and cleaner pages

This commit is contained in:
Danny
2026-11-09 11:50:26 -08:00
parent d87411b874
commit db98ca20ee
24 changed files with 1476 additions and 256 deletions
+18 -10
View File
@@ -1011,15 +1011,19 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
self.json(400, {'error': 'Invalid map tile'})
return
try:
query = parse_qs(urlsplit(self.path).query, keep_blank_values=True, max_num_fields=1)
theme = query.get('theme', ['light'])[0]
if set(query) - {'theme'} or theme not in ('light', 'dark'):
query = parse_qs(urlsplit(self.path).query, keep_blank_values=True, max_num_fields=2)
theme = query.get('theme', ['light'])
provider = query.get('provider', ['mapbox'])
if (set(query) - {'theme', 'provider'} or len(theme) != 1 or theme[0] not in ('light', 'dark') or
len(provider) != 1 or provider[0] not in ('mapbox', 'google')):
raise ValueError('Invalid map theme')
except ValueError:
self.json(400, {'error': 'Invalid map theme'})
return
try:
tile = navigation_owner().map_tile(*(int(value) for value in match.groups()), theme)
coords = (int(value) for value in match.groups())
tile = (navigation_owner().map_tile(*coords, theme[0], provider='google')
if provider[0] == 'google' else navigation_owner().map_tile(*coords, theme[0]))
except (OSError, ValueError, RuntimeError):
self.json(503, {'error': 'Map tiles are unavailable'})
else:
@@ -1888,15 +1892,16 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
raise ValidationError('Enter a destination to search')
if 'autocomplete' in payload and payload['autocomplete'] is not True:
raise ValidationError('Enter a destination to search')
result = {'results': (navigation_owner().search_places(payload['query'], identity, payload['searchId'], payload['clientId'],
autocomplete='autocomplete' in payload)
if 'searchId' in payload else navigation_owner().search(payload['query']))}
results = (navigation_owner().search_places(payload['query'], identity, payload['searchId'], payload['clientId'],
autocomplete='autocomplete' in payload)
if 'searchId' in payload else navigation_owner().search(payload['query']))
result = {'results': results, 'provider': getattr(results, 'provider', 'mapbox')}
else:
fields = {'configure': {'patch'}, 'select': {'destination'}, 'selectPlace': {'id', 'searchId'},
'cancelSearch': {'searchId'}, 'clear': set(), 'favorite': {'destination'},
'favoritePlace': {'id', 'searchId'}, 'removeFavorite': {'id'}, 'labelFavorite': {'id', 'label'},
'removeRecent': {'id'}, 'clearRecents': set(), 'selectRoute': {'index'}, 'testGoogleKey': set(),
'resolveShare': {'text'}}
'resolveShare': {'text'}, 'share': {'text'}}
action = payload.get('action')
optional = ({'label'} if action in ('favorite', 'favoritePlace') and 'label' in payload else
{'key'} if action == 'testGoogleKey' and 'key' in payload else set())
@@ -1905,7 +1910,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
needs_park = action == 'configure' and isinstance(payload['patch'], dict) and bool({'token', 'googleKey'} & payload['patch'].keys())
def authorized():
return self.settings_session() == identity and (not needs_park or configuration_allowed())
with (nullcontext() if action in ('selectPlace', 'favoritePlace', 'testGoogleKey', 'resolveShare') else effect_lock):
with (nullcontext() if action in ('selectPlace', 'favoritePlace', 'testGoogleKey', 'resolveShare', 'share') else effect_lock):
if not authorized():
raise PermissionError('Park your car before changing a map key' if needs_park else 'Sign in to Galaxy')
nav = navigation_owner()
@@ -1916,6 +1921,8 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
result = dict(nav.snapshot(), googleKeyTest=nav.test_google_key(payload.get('key')))
elif action == 'resolveShare':
result = dict(nav.snapshot(), sharedText=nav.resolve_share(payload['text']))
elif action == 'share':
result = nav.share(payload['text'], **keywords)
elif action == 'selectPlace':
result = nav.select_place(payload['id'], payload['searchId'], identity, **keywords)
elif action == 'cancelSearch':
@@ -1945,7 +1952,8 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
except ConflictError as error:
self.json(409, {'error': str(error)})
except ValidationError as error:
self.json(400, {'error': str(error)})
query = getattr(error, 'query', None)
self.json(400, {'error': str(error), **({'query': query} if query else {})})
except PermissionError as error:
if self.require_session():
self.json(409, {'error': str(error)})
@@ -87,14 +87,14 @@ const status = { enabled: true, hasKey: true, isMetric: true, status: 'noDestina
await page.screenshot({ path: `/private/tmp/navigation-offline-${width}.png`, fullPage: true })
}
await offlineLink.click()
await page.getByText('Map Overlay Roads', { exact: true }).waitFor()
await page.getByText('Offline Map Management', { exact: true }).waitFor()
assert.equal(await page.getByRole('button', { name: 'Offline Maps', exact: true }).getAttribute('aria-pressed'), 'true')
await page.getByRole('button', { name: 'Destination', exact: true }).click()
status.network = 'unknown'
await page.evaluate(() => window.navigation.client.load())
assert.equal(await offlineLink.count(), 0, 'unknown device state must not be presented as offline')
await page.goto('http://navigation.test/?shell=1#/navigation/maps')
await page.getByText('Map Overlay Roads', { exact: true }).waitFor()
await page.getByText('Offline Map Management', { exact: true }).waitFor()
assert.equal(await page.getByRole('button', { name: 'Offline Maps', exact: true }).getAttribute('aria-pressed'), 'true')
await page.getByRole('button', { name: 'Destination', exact: true }).click()
await page.waitForURL('**#/navigation')
@@ -257,4 +257,49 @@ console.log("Local HTTP search UUID fallback passed")
assert.ok(NavigationPage.template.includes('<BluetoothNotice v-if="bluetooth" feature="Map preview"'))
assert.ok(NavigationPage.template.includes('<NavigationMap v-else-if="ready"'))
}
{
// Shared text the comma can't pin down comes back as a 400 with the search to show; navigation turns on for it.
const sent = [], states = []
let off = true
const answers = { share: (body) => body.text.includes("!3d") ? response({ ...snapshot("s"), enabled: true, destination: place, shared: place }) :
body.text === "Atlantis" ? response({ error: "No map location found for Atlantis" }, 400) :
response({ error: "Open StarPilot to search for Starbucks", query: "Starbucks" }, 400),
configure: () => { off = false; return response({ ...snapshot("c"), enabled: true }) } }
const client = new NavigationClient({ publish: (state) => states.push(state), later: () => 0, cancelTimer: () => {},
fetcher: async (url, options) => {
const body = options.body ? JSON.parse(options.body) : null
sent.push({ url, body })
if (url.includes("/search")) return response({ results: [place], provider: "google" })
if (body?.action) return answers[body.action](body)
return response({ ...snapshot(), enabled: !off })
} })
await client.start()
const page = { client, query: "" }
await NavigationPage.methods.openShared.call(page, "Starbucks")
assert.deepEqual(sent.slice(1).map(({ url, body }) => body?.action || url), ["share", "configure", "./api/navigation/search"])
assert.equal(page.query, "Starbucks")
assert.equal(sent.at(-1).body.query, "Starbucks")
const shown = states.at(-1)
assert.deepEqual([shown.results, shown.resultsProvider, shown.error, shown.stale, shown.data.enabled], [[place], "google", "", false, true])
sent.length = 0
await NavigationPage.methods.openShared.call(page, "https://www.google.com/maps/place/Library/data=!3d41!4d-88")
assert.deepEqual(sent.map(({ body }) => body?.action), ["share"])
assert.equal(states.at(-1).data.destination.name, "Library")
sent.length = 0
page.query = ""
await NavigationPage.methods.openShared.call(page, "Atlantis")
assert.deepEqual([sent.length, page.query, states.at(-1).error], [1, "", "No map location found for Atlantis"])
assert.equal(client.refusal, null)
client.stop()
assert.equal(NavigationPage.computed.googlePlaces.call({ data: { routeProvider: "google", hasGoogleKey: true } }), true)
assert.equal(NavigationPage.computed.googlePlaces.call({ data: { routeProvider: "mapbox", hasGoogleKey: true } }), false)
const tests = NavigationPage.computed.googleTests.call({ googleTest: { ok: true, message: "map", routes: { ok: false, failure: "disabled", message: "off" },
places: { ok: false, failure: "budget", message: "used up" } } })
assert.deepEqual(tests.map((row) => [row.name, row.ok, row.missing, row.link?.href]), [["Map Tiles API", true, false, undefined],
["Routes API", false, true, "https://console.cloud.google.com/apis/library/routes.googleapis.com"], ["Places API (New)", false, false, undefined]])
assert.equal(NavigationPage.computed.googleWorking.call({ googleTests: tests }), "2 of 3 APIs working")
assert.ok(NavigationPage.template.includes("Google isn't used until the Mapbox key above is added too."))
console.log("Shared places: comma lookup, 400 query search, navigation turned on, Google source and key test summary passed")
}
await import("./test_navigation_map.mjs")
@@ -169,10 +169,13 @@ class NavigationHttpTest(unittest.TestCase):
status, body, _ = self.action('configure', patch={'googleKey': key, 'mapProvider': 'google'})
self.assertEqual((status, body['hasGoogleKey'], body['mapProvider']), (200, True, 'google'))
self.assertNotIn(key, json.dumps(self.request('/api/navigation/status', cookie=self.local_cookie)[1]))
with patch('openpilot.starpilot.navigation.google_tiles.test_key', return_value={'ok': False, 'message': 'Billing is off'}) as tested:
with (patch('openpilot.starpilot.navigation.google_tiles.test_key', return_value={'ok': False, 'message': 'Billing is off'}) as tested,
patch('openpilot.starpilot.navigation.google_routes.test_routes', return_value={'ok': True, 'failure': None, 'message': 'routes'}),
patch('openpilot.starpilot.navigation.google_places.test_places', return_value={'ok': True, 'failure': None, 'message': 'places'})):
self.parked = False
status, body, _ = self.action('testGoogleKey')
self.assertEqual((status, body['googleKeyTest']['message'], body['hasGoogleKey']), (200, 'Billing is off', True))
self.assertEqual((body['googleKeyTest']['routes']['ok'], body['googleKeyTest']['places']['message']), (True, 'places'))
self.assertEqual(self.action('testGoogleKey', key='AIzaSyOtherKey_0123456789abcdefgh')[0], 200)
self.assertEqual([call.args[0] for call in tested.call_args_list], [key, 'AIzaSyOtherKey_0123456789abcdefgh'])
self.assertEqual(self.action('testGoogleKey', key='bad key')[0], 400)
@@ -186,6 +189,33 @@ class NavigationHttpTest(unittest.TestCase):
resolved.assert_called_once_with('Bellagio https://maps.app.goo.gl/abc123')
self.assertEqual(self.action('resolveShare')[0], 400)
def test_shared_place_turns_navigation_on_and_starts_the_route(self):
self.assertEqual(self.action('share', text='geo:40.5,-89.5')[1], {'error': 'Add your Mapbox access token first'})
self.navigation.configure({'token': 'pk.test'}, self.navigation.read()['revision'], True)
self.assertFalse(self.navigation.snapshot()['enabled'])
status, body, _ = self.action('share', remote=True, text='https://www.google.com/maps/place/Bellagio/data=!3d36.1126!4d-115.1767')
self.assertEqual(status, 200)
self.assertEqual(body['shared'], {'name': 'Bellagio', 'latitude': 36.1126, 'longitude': -115.1767})
self.assertTrue(body['enabled'] and body['hasKey'])
self.assertEqual((body['destination']['latitude'], body['revision']), (36.1126, self.navigation.snapshot()['revision']))
self.assertNotIn('pk.test', json.dumps(body))
feature = {'features': [{'properties': {'name': '3600 S Las Vegas Blvd', 'full_address': '3600 S Las Vegas Blvd, Las Vegas, NV'},
'geometry': {'coordinates': [-115.17, 36.11]}}]}
with patch('openpilot.starpilot.navigation.owner.response_json', return_value=feature) as geocode:
status, body, _ = self.action('share', text='https://www.google.com/maps/place/Bellagio,+3600+S+Las+Vegas+Blvd,+Las+Vegas,+NV/data=!4m2!3m1!1s0x1:0x2')
self.assertEqual((status, body['shared']), (200, {'name': 'Bellagio', 'latitude': 36.11, 'longitude': -115.17}))
self.assertEqual(geocode.call_args.args[2]['q'], '3600 S Las Vegas Blvd, Las Vegas, NV')
with patch('openpilot.starpilot.navigation.owner.response_json', return_value={'features': []}):
self.assertEqual(self.action('share', text='https://maps.google.com/?q=Nowhere,+Atlantis')[1],
{'error': 'No map location found for Nowhere', 'query': 'Nowhere, Atlantis'})
self.assertEqual(self.action('share', text='Starbucks')[:2], (400, {'error': 'Open StarPilot to search for Starbucks', 'query': 'Starbucks'}))
revision = self.navigation.read()['revision']
stale = {'action': 'share', 'revision': '0', 'text': 'geo:40.5,-89.5'}
self.assertEqual(self.request('/api/navigation/action', payload=stale, cookie=self.local_cookie)[0], 409)
self.assertEqual(self.navigation.read()['revision'], revision)
self.assertEqual(self.action('share')[0], 400)
self.assertNotIn('query', self.action('share', text='x' * 8193)[1])
def test_stale_or_invalid_actions_never_overwrite_configuration(self):
self.action('configure', patch={'enabled': True})
before = self.navigation.path.read_bytes()
@@ -233,6 +263,27 @@ class NavigationHttpTest(unittest.TestCase):
self.assertEqual(self.action('clearRecents')[1]['recents'],[])
self.assertEqual(self.action('removeFavorite',id=place)[1]['favorites'],[])
def test_search_names_the_provider_that_found_the_places(self):
self.action('configure', patch={'token':'pk.synthetic','enabled':True})
def search():
return {'query':'bellagio', 'searchId':str(uuid.uuid4()), 'clientId':str(uuid.uuid4())}
suggestion = {'suggestions':[{'mapbox_id':'poi/id','name':'Coffee Shop','feature_type':'poi'}]}
with patch('openpilot.starpilot.navigation.owner.response_json', return_value=suggestion):
self.assertEqual(self.request('/api/navigation/search',payload=search(),cookie=self.local_cookie)[1]['provider'], 'mapbox')
key = 'AIzaSyFixtureKey_0123456789abcdef'
self.action('configure', patch={'googleKey':key, 'routeProvider':'google'})
found = [{'name':'Bellagio','address':'3600 S Las Vegas Blvd','latitude':36.1126,'longitude':-115.1767}]
with patch('openpilot.starpilot.navigation.google_places.text_search', return_value=found) as google:
status, result, _ = self.request('/api/navigation/search',payload=search(),cookie=self.local_cookie)
self.assertEqual((status, result['provider'], result['results'][0]['name']), (200, 'google', 'Bellagio'))
self.assertNotIn('searchId', result['results'][0])
self.assertEqual(google.call_args.args[1], key)
self.assertNotIn(key, json.dumps(result))
from openpilot.starpilot.navigation.google_places import GooglePlacesFailed
with (patch('openpilot.starpilot.navigation.google_places.text_search', side_effect=GooglePlacesFailed('budget')),
patch('openpilot.starpilot.navigation.owner.response_json', return_value=suggestion)):
self.assertEqual(self.request('/api/navigation/search',payload=search(),cookie=self.local_cookie)[1]['provider'], 'mapbox')
def test_temporary_search_result_cannot_be_saved(self):
self.action('configure', patch={'token':'pk.synthetic','enabled':True})
search = {'query':'coffee', 'searchId':str(uuid.uuid4()), 'clientId':str(uuid.uuid4())}
@@ -186,3 +186,33 @@ console.log('Follow, pinch and double-tap zoom passed')
globalThis.requestAnimationFrame = originalRaf; globalThis.cancelAnimationFrame = originalCancelRaf
}
console.log('Live map theme changes: correct requests, cache disposal, late-response isolation, camera preservation and observer cleanup passed')
{
// Switching mapProvider between Mapbox and Google clears cached tiles, appends provider=google, and crops 256px parent tiles.
const savedFetch = globalThis.fetch, savedBitmap = globalThis.createImageBitmap
globalThis.requestAnimationFrame = fn => { frames.set(++frameId, fn); return frameId }
globalThis.cancelAnimationFrame = id => frames.delete(id)
const urls = []
let closed = 0
globalThis.fetch = async url => { urls.push(url); return { ok: true, blob: async () => ({}) } }
globalThis.createImageBitmap = async () => ({ width: 256, close() { closed++ } })
const switched = new RasterMap(canvas)
switched.draw = () => {}
switched.update({ mapProvider: 'mapbox', hasGoogleKey: true }, false)
await switched.load('1/0/0')
assert.ok(urls.at(-1).endsWith('1/0/0.png?theme=dark'))
assert.equal(switched.tiles.size, 1)
const crop = switched.placeholder(2, 1, 1)
assert.deepEqual(crop.slice(1), [128, 128, 128], '256px Google/custom tiles crop using their actual bitmap width')
switched.update({ mapProvider: 'google', hasGoogleKey: true }, false)
assert.equal(switched.tiles.size, 0, 'switching map provider clears cached tiles from the previous provider')
assert.equal(closed, 1)
await switched.load('1/0/0')
assert.ok(urls.at(-1).endsWith('1/0/0.png?theme=dark&provider=google'))
switched.update({ mapProvider: 'google', hasGoogleKey: true, googleMap: { failure: 'Quota reached' } }, false)
assert.equal(switched.provider, 'mapbox', 'a Google map failure falls back to Mapbox tiles')
switched.close()
globalThis.fetch = savedFetch; globalThis.createImageBitmap = savedBitmap
globalThis.requestAnimationFrame = originalRaf; globalThis.cancelAnimationFrame = originalCancelRaf
}
console.log('Map provider switching: Google tile URL, cache invalidation, fallback, and 256px placeholder cropping passed')
@@ -1390,7 +1390,7 @@ background: var(--surface-container-high); color: var(--on-surface-variant); bor
.gx-starport-pill:has(> i)::before { display: none; }
.gx-starport-pill--ready { color: var(--success); border-color: color-mix(in srgb, var(--success) 40%, transparent); background: color-mix(in srgb, var(--success) 12%, transparent); }
.gx-starport-pill--soon { color: var(--warning); border-color: color-mix(in srgb, var(--warning) 40%, transparent); background: color-mix(in srgb, var(--warning) 12%, transparent); }
.gx-starport-pill--expired, .gx-starport-pill--broken { color: var(--error); border-color: color-mix(in srgb, var(--error) 40%, transparent); background: color-mix(in srgb, var(--error) 12%, transparent); }
.gx-starport-pill--expired, .gx-starport-pill--broken, .gx-starport-pill--danger, .gx-starport-pill--error { color: var(--error); border-color: color-mix(in srgb, var(--error) 40%, transparent); background: color-mix(in srgb, var(--error) 12%, transparent); }
.gx-starport-list { list-style: none; margin: 0; padding: 0; display: grid; border: 1px solid var(--outline); border-radius: var(--radius-md); overflow: hidden; }
.gx-starport-list > .gx-starport-row + .gx-starport-row { border-top: 1px solid var(--outline); }
.gx-starport-row { display: flex; align-items: center; gap: var(--sp-3); min-width: 0; margin: 0; padding: var(--sp-3) var(--sp-4); }
@@ -122,6 +122,67 @@
.gx-navigation__token-link { margin-bottom: var(--sp-4); }
.gx-navigation__gps { scroll-margin-top: 100px; }
.gx-navigation__gps li { margin-block: var(--sp-2); line-height: 1.5; }
.gx-navigation__gps summary { cursor: pointer; min-height: 44px; display: list-item; align-content: center; }
.gx-navigation__gps { scroll-margin-top: 100px; display: grid; gap: var(--sp-3); }
.gx-navigation__gps li { margin-block: var(--sp-1); line-height: 1.45; }
.gx-navigation__gps summary { cursor: pointer; min-height: 44px; display: flex; align-items: center; }
.gx-navigation__gps-status { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); margin: 0; }
.gx-navigation__gps-guides { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: var(--sp-3); margin-top: var(--sp-3); }
.gx-navigation__gps-card { display: grid; gap: var(--sp-2); align-content: start; padding: var(--sp-3) var(--sp-4); border: 1px solid var(--outline); border-radius: var(--radius-md); background: var(--surface-container); }
.gx-navigation__gps-card > strong { display: inline-flex; align-items: center; gap: var(--sp-2); color: var(--on-surface); }
.gx-navigation__gps-card > strong .bi { color: var(--primary); }
.gx-navigation__prefs { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--sp-3); padding-top: var(--sp-3); margin-top: var(--sp-2); border-top: 1px solid var(--outline); }
.gx-navigation__prefs-head { display: grid; gap: 2px; min-width: 200px; flex: 1 1 220px; }
.gx-navigation__pref-chips { display: flex; flex-wrap: wrap; gap: var(--sp-2); }
.gx-navigation__pref { display: inline-flex; align-items: center; gap: var(--sp-2); min-height: 40px; padding: 0 14px; border-radius: var(--radius-full); border: 1px solid var(--outline); background: var(--surface-container); color: var(--on-surface); font-size: .88rem; font-weight: var(--fw-medium); cursor: pointer; user-select: none; transition: background var(--motion-fast), border-color var(--motion-fast), color var(--motion-fast); }
.gx-navigation__pref > i { font-size: .95rem; color: var(--text-muted); }
.gx-navigation__pref--on { background: color-mix(in srgb, var(--primary) 16%, var(--surface-container)); border-color: var(--primary); color: var(--primary); }
.gx-navigation__pref--on > i { color: var(--primary); }
.gx-navigation__pref:has(input:focus-visible) { outline: 2px solid var(--primary); outline-offset: 3px; }
.gx-navigation__pref--disabled { opacity: .55; cursor: default; }
.gx-navigation__step-title { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); margin-bottom: var(--sp-1); }
.gx-navigation__step-title h3 { margin: 0; }
.gx-navigation__step-title .gx-starport-pill { padding: 2px 10px; font-size: .75rem; }
/* Setup choices: compact M3 choice buttons with an expandable info popover. */
.gx-choice { border: 0; margin: 0; padding: 0; min-width: 0; display: grid; gap: var(--sp-2); }
.gx-choice__head { display: flex; align-items: center; gap: var(--sp-2); }
.gx-choice__legend { padding: 0; font-weight: var(--fw-medium); float: left; }
.gx-choice__info-btn { display: inline-grid; place-items: center; width: 32px; height: 32px; min-height: 32px !important; padding: 0; border: 0; border-radius: 50%; background: transparent; color: var(--text-muted); font-size: .95rem; cursor: pointer; transition: background var(--motion-fast), color var(--motion-fast); }
.gx-choice__info-btn:hover, .gx-choice__info-btn[aria-expanded="true"] { background: var(--surface-container-high); color: var(--primary); }
.gx-choice__hint { margin: 0; color: var(--text-muted); font-size: .85rem; }
.gx-choice__grid { display: flex; flex-wrap: wrap; gap: var(--sp-2); }
.gx-choice__card { flex: 1 1 160px; display: flex; align-items: center; min-height: 44px; padding: 8px 14px; border: 1px solid var(--outline);
border-radius: var(--radius-md); background: var(--surface-container); cursor: pointer; min-width: 0; transition: background var(--motion-fast), border-color var(--motion-fast); }
.gx-choice__card--on { border-color: var(--primary); background: color-mix(in srgb, var(--primary) 14%, var(--surface-container)); box-shadow: 0 0 0 1px var(--primary); }
.gx-choice__card--off { opacity: .6; cursor: default; }
.gx-choice__card:has(input:focus-visible) { outline: 2px solid var(--primary); outline-offset: 3px; }
.gx-choice__title { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); width: 100%; min-width: 0; line-height: 1.3; }
.gx-choice__title strong { flex: 1 1 auto; min-width: 0; font-size: .9rem; }
.gx-choice__title .bi { flex: 0 0 auto; color: var(--text-muted); font-size: 1rem; }
.gx-choice__card--on .gx-choice__title .bi { color: var(--primary); }
.gx-choice__title .gx-starport-pill { padding: 2px 8px; font-size: .72rem; margin-left: auto; }
.gx-choice__active-summary { margin: 0; color: var(--text-muted); font-size: .83rem; line-height: 1.4; }
.gx-choice__popover { display: grid; gap: var(--sp-2); padding: var(--sp-3) var(--sp-4); border: 1px solid var(--outline); border-radius: var(--radius-md); background: var(--surface-container-high, var(--surface-container)); font-size: .85rem; }
.gx-choice__popover-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); }
.gx-choice__popover-close { display: inline-grid; place-items: center; width: 28px; height: 28px; min-height: 28px !important; padding: 0; border: 0; border-radius: 50%; background: transparent; color: var(--text-muted); cursor: pointer; }
.gx-choice__popover-close:hover { background: var(--glass-active-bg); color: var(--on-surface); }
.gx-choice__popover-list { margin: 0; display: grid; gap: var(--sp-2); }
.gx-choice__popover-item { display: grid; gap: 2px; padding-top: var(--sp-2); border-top: 1px solid var(--outline); }
.gx-choice__popover-item dt { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); }
.gx-choice__popover-item dt .gx-starport-pill { padding: 1px 8px; font-size: .7rem; }
.gx-choice__popover-item dd { margin: 0; color: var(--on-surface-variant, var(--text-muted)); line-height: 1.45; }
.gx-choice__limit { color: var(--text-muted); font-size: .82rem; line-height: 1.4; }
.gx-compare { display: grid; margin-top: var(--sp-3); border: 1px solid var(--outline); border-radius: var(--radius-md); overflow: hidden; }
.gx-compare__row { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr) minmax(0, 1fr); gap: var(--sp-3); padding: var(--sp-2) var(--sp-3); font-size: .85rem; }
.gx-compare__row + .gx-compare__row { border-top: 1px solid var(--outline); }
.gx-compare__row--head { font-weight: var(--fw-medium); background: var(--surface-container); }
.gx-compare__row > :first-child { color: var(--text-muted); }
.gx-compare__row--head > :first-child { color: inherit; }
.gx-navigation__sources { display: flex; flex-wrap: wrap; gap: var(--sp-2); list-style: none; margin: 0; padding: 0; }
.gx-navigation__sources .gx-navigation__chip { text-decoration: none; border: 1px solid var(--outline); }
.gx-navigation__power .gx-row__info { display: grid; gap: 2px; }
.gx-navigation .gx-starport-step__body { padding-left: 0; }
@media (min-width: 640px) { .gx-navigation .gx-starport-step__body { padding-left: calc(36px + var(--sp-4)); } }
@media (max-width: 540px) { .gx-compare__row { grid-template-columns: 1fr; gap: 2px; } .gx-compare__row--head { display: none; } .gx-compare__row > :nth-child(2)::before { content: "Mapbox: "; } .gx-compare__row > :nth-child(3)::before { content: "Google: "; } }
@@ -1,26 +1,28 @@
/* Offline road maps for the Android Auto overlay (#/navigation, Offline Maps tab). */
.gx-navigation__offline { display: grid; gap: 16px; padding: 0 0 96px; }
.gx-offline-roads { padding: 24px; display: grid; gap: 14px; }
/* Keep the section header flush with the card's rounded top like every other Galaxy card. */
.gx-offline-roads > .gx-section__header { margin: -24px -24px 0; }
.gx-offline-roads__stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 10px; }
.gx-offline-roads__stat { display: grid; gap: 2px; padding: 12px 14px; border-radius: 14px; background: color-mix(in srgb, currentColor 6%, transparent); }
.gx-offline-roads__stat span { font-size: .78rem; opacity: .7; }
.gx-navigation__offline { display: grid; gap: var(--sp-4, 16px); padding: 0 0 96px; }
.gx-offline-roads { padding: var(--panel-padding, 20px); display: grid; gap: var(--sp-4, 16px); min-width: 0; }
.gx-offline-roads__head { display: flex; align-items: flex-start; gap: var(--sp-4, 16px); min-width: 0; }
.gx-offline-roads__head > div { flex: 1; min-width: 0; }
.gx-offline-roads__head .gx-note { margin: 0; line-height: 1.45; }
.gx-offline-roads__stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: var(--sp-3, 12px); }
.gx-offline-roads__stat { display: grid; gap: 2px; padding: var(--sp-3, 12px) var(--sp-4, 16px); border-radius: var(--radius-md, 14px); border: 1px solid var(--outline); background: var(--surface-container); }
.gx-offline-roads__stat span { font-size: .78rem; color: var(--text-muted); }
.gx-offline-roads__stat strong { font-size: 1.05rem; }
.gx-offline-roads__stat small { opacity: .7; font-size: .76rem; display: flex; flex-wrap: wrap; gap: 4px 12px; }
.gx-offline-roads__stat small { color: var(--text-muted); font-size: .76rem; display: flex; flex-wrap: wrap; gap: 4px 12px; }
.gx-offline-roads__stat--wide { grid-column: 1 / -1; }
.gx-offline-roads__bar { display: flex; height: 8px; border-radius: 6px; overflow: hidden; background: color-mix(in srgb, currentColor 12%, transparent); margin: 6px 0 2px; }
.gx-offline-roads__bar i { display: block; height: 100%; transition: width .4s ease; }
.gx-offline-roads__legend { display: inline-flex; align-items: center; gap: 6px; }
.gx-offline-roads__legend b { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
.gx-offline-roads__picker { display: grid; grid-template-columns: minmax(0, 2fr) minmax(240px, 1fr); gap: 14px; align-items: start; }
.gx-offline-roads__picker { display: grid; grid-template-columns: minmax(0, 1.8fr) minmax(240px, 1fr); gap: var(--sp-3, 12px); align-items: start; }
@media (max-width: 760px) { .gx-offline-roads__picker { grid-template-columns: 1fr; } }
.gx-offline-roads__map { position: relative; border-radius: 16px; overflow: hidden; background: #0e0e1a; height: 340px; }
.gx-offline-roads__map { position: relative; border-radius: var(--radius-md, 16px); border: 1px solid var(--outline); overflow: hidden; background: var(--navigation-land, #191a1a); height: clamp(260px, 42svh, 360px); }
.gx-offline-roads__map canvas { width: 100%; height: 100%; display: block; cursor: crosshair; touch-action: none; }
.gx-offline-roads__provider { position: absolute; left: 10px; top: 10px; padding: 4px 10px; border-radius: var(--radius-full, 20px); border: 1px solid var(--glass-border); background: var(--glass-bg); color: var(--glass-text); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); font-size: .75rem; font-weight: var(--fw-medium, 500); pointer-events: none; }
.gx-offline-roads__map .gx-navigation-map__controls { position: absolute; right: 10px; top: 10px; display: grid; gap: 6px; }
.gx-offline-roads__hint { position: absolute; left: 12px; bottom: 10px; padding: 6px 10px; border-radius: 10px; background: #0e0e1acc; color: #e8e6f5; font-size: .8rem; pointer-events: none; }
.gx-offline-roads__form { display: grid; gap: 8px; }
.gx-offline-roads__hint { position: absolute; left: 10px; right: 10px; bottom: 10px; width: fit-content; max-width: calc(100% - 20px); padding: 6px 12px; border-radius: 10px; border: 1px solid var(--glass-border); background: var(--glass-bg); color: var(--glass-text); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); font-size: .8rem; pointer-events: none; }
.gx-offline-roads__form { display: grid; gap: 8px; padding: var(--sp-3, 12px); border: 1px solid var(--outline); border-radius: var(--radius-md, 14px); background: var(--surface-container); }
.gx-offline-roads__areas { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
.gx-offline-roads__areas li { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 12px 14px; border-radius: 14px; background: color-mix(in srgb, currentColor 5%, transparent); }
.gx-offline-roads__area { display: grid; gap: 2px; min-width: 0; flex: 1; }
.gx-offline-roads__area small { opacity: .72; }
.gx-offline-roads__areas li { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 12px; padding: 12px 14px; border-radius: var(--radius-md, 14px); border: 1px solid var(--outline); background: var(--surface-container); }
.gx-offline-roads__area { display: grid; gap: 2px; min-width: 160px; flex: 1; }
.gx-offline-roads__area small { color: var(--text-muted); }
@@ -143,7 +143,7 @@
"name": "Setup",
"path": "/navigation/setup",
"tab": "setup",
"description": "Configure navigation and Mapbox",
"description": "Keys, map and route sources, and GPS",
"icon": "bi-gear"
}
]
@@ -139,6 +139,11 @@ export class RasterMap {
const theme = value === 'light' ? 'light' : 'dark'
if (this.closed || this.theme === theme) return
this.theme = theme
this.clearTiles()
this.changed('')
this.draw()
}
clearTiles() {
for (const controller of this.pending.values()) controller.abort()
this.pending.clear()
for (const image of this.tiles.values()) image.close()
@@ -147,8 +152,6 @@ export class RasterMap {
this.failures = 0
clearTimeout(this.retryTimer)
this.retryTimer = null
this.changed('')
this.draw()
}
pause() {
if (this.follow) { this.follow = false; this.changed() }
@@ -206,6 +209,9 @@ export class RasterMap {
if (data?.location && (this.locationFresh || data.location.lastKnown === true && !this.lastLocation)) {
this.lastLocation = { ...data.location, bearing: Number.isFinite(data.location.bearing) ? data.location.bearing : this.lastLocation?.bearing }
}
const provider = data?.mapProvider === 'google' && data?.hasGoogleKey && !data?.googleMap?.failure ? 'google' : 'mapbox'
if (this.provider && this.provider !== provider) this.clearTiles()
this.provider = provider
this.data = data || {}
this.stale = stale
// A newly chosen route is shown whole once; Recenter returns to following the car.
@@ -253,7 +259,7 @@ export class RasterMap {
for (let up = 1; up <= 5 && zoom - up >= 0; up++) {
const image = this.tiles.get(`${zoom - up}/${x >> up}/${y >> up}`)
if (image) {
const span = SIZE / 2 ** up
const span = (image.width || SIZE) / 2 ** up
return [image, (x - ((x >> up) << up)) * span, (y - ((y >> up) << up)) * span, span]
}
}
@@ -348,8 +354,9 @@ export class RasterMap {
timedOut = true;
controller.abort()
}, 8000)
const providerQuery = this.provider === 'google' ? '&provider=google' : ''
try {
const response = await fetch(`./api/navigation/map/tiles/${key}.png?theme=${this.theme}`, {
const response = await fetch(`./api/navigation/map/tiles/${key}.png?theme=${this.theme}${providerQuery}`, {
credentials: 'same-origin', signal: controller.signal
});
if (!response.ok) throw new Error('Map tiles unavailable')
@@ -359,22 +366,26 @@ export class RasterMap {
return
}
this.tiles.set(key, image);
this.failed.delete(key);
this.failures = 0
while (this.tiles.size > TILE_BITMAPS) {
const oldest = this.tiles.keys().next().value;
this.tiles.get(oldest).close();
this.tiles.delete(oldest)
}
if (!this.failed.size) this.changed('')
this.changed('')
if (this.failed.size && !this.retryTimer) {
this.retryTimer = setTimeout(() => { this.retryTimer = null; this.retry() }, 400)
}
} catch (error) {
if (this.pending.get(key) === controller && (timedOut || !controller.signal.aborted)) {
this.failed.add(key);
if (this.failed.size > 64) this.failed.delete(this.failed.values().next().value);
// A quick refusal (a busy moment) is retried quickly and silently; a hung request or a run of failures is reported.
this.failures = (this.failures || 0) + 1
const persistent = timedOut || this.failures >= 6
const persistent = timedOut || this.failures >= 8
if (persistent) this.changed('Map tiles unavailable. Check the saved key and connection. Reconnecting automatically…')
this.retryTimer ??= setTimeout(() => { this.retryTimer = null; this.retry() }, persistent ? 5000 : 800)
this.retryTimer ??= setTimeout(() => { this.retryTimer = null; this.retry() }, persistent ? 3000 : 600)
}
} finally {
clearTimeout(timer);
@@ -410,6 +421,9 @@ export const NavigationMap = {
props: ['data', 'stale'], data: () => ({
error: '', map: null, locationFresh: false, lastLocation: null, following: true
}),
computed: {
googleMap() { return this.data?.mapProvider === 'google' && !!this.data?.hasGoogleKey && !this.data?.googleMap?.failure },
},
mounted() {
this.map = markRaw(new RasterMap(this.$refs.canvas, (error) => {
if (error !== undefined) this.error = error
@@ -447,9 +461,12 @@ export const NavigationMap = {
<button type="button" class="gx-navigation-map__control" :class="{'gx-navigation-map__control--active':!following}" @click="map.recenter()" :aria-pressed="following" aria-label="Recenter and follow"><i class="bi bi-crosshair" aria-hidden="true"></i></button>
</div>
<GxNotice v-if="error" tone="danger">{{error}}</GxNotice>
<a class="gx-navigation-map__logo" href="https://www.mapbox.com/" target="_blank" rel="noopener noreferrer" aria-label="Mapbox">
<a v-if="!googleMap" class="gx-navigation-map__logo" href="https://www.mapbox.com/" target="_blank" rel="noopener noreferrer" aria-label="Mapbox">
</a>
<div class="gx-navigation-map__credits">
<div v-if="googleMap" class="gx-navigation-map__credits">
<a class="gx-link" href="https://www.google.com/maps" target="_blank" rel="noopener noreferrer">Google Maps</a> · <span>{{ data?.googleMap?.copyright || 'Map data © Google' }}</span> · <a class="gx-link" href="https://www.google.com/intl/en-US_US/help/terms_maps/" target="_blank" rel="noopener noreferrer">Terms</a>
</div>
<div v-else class="gx-navigation-map__credits">
<a class="gx-link" href="https://www.mapbox.com/about/maps/" target="_blank" rel="noopener noreferrer">© Mapbox</a> · <a class="gx-link" href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener noreferrer">© OpenStreetMap</a> · <a class="gx-link" href="https://apps.mapbox.com/feedback/" target="_blank" rel="noopener noreferrer">Improve this map</a>
</div>
</section>`
@@ -0,0 +1,81 @@
// Pieces of the navigation setup page: a compact M3 choice group with an info popover and the Mapbox/Google comparison.
export const ChoiceGroup = {
name: "ChoiceGroup",
props: { label: { type: String, required: true }, hint: { type: String, default: "" }, modelValue: { type: String, default: "" },
options: { type: Array, required: true }, disabled: { type: Boolean, default: false } },
emits: ["update:modelValue"],
data() { return { infoOpen: false } },
computed: {
selectedOption() { return this.options.find((option) => option.value === this.modelValue) || this.options[0] || null },
},
methods: {
pick(event, option) {
event.target.checked = this.modelValue === option.value
if (!option.disabled && !this.disabled) this.$emit("update:modelValue", option.value)
},
},
template: `
<fieldset class="gx-choice" :disabled="disabled">
<div class="gx-choice__head">
<legend class="gx-choice__legend">{{ label }}</legend>
<button type="button" class="gx-choice__info-btn" :aria-expanded="infoOpen" :aria-label="'More info about ' + label"
:title="'More info about ' + label" @click="infoOpen = !infoOpen">
<i class="bi" :class="infoOpen ? 'bi-info-circle-fill' : 'bi-info-circle'" aria-hidden="true"></i>
</button>
</div>
<p v-if="hint" class="gx-choice__hint">{{ hint }}</p>
<div class="gx-choice__grid">
<label v-for="option in options" :key="option.value" class="gx-choice__card"
:class="{ 'gx-choice__card--on': modelValue === option.value, 'gx-choice__card--off': option.disabled }">
<input type="radio" class="gx-sr-only" :name="label" :value="option.value" :checked="modelValue === option.value"
:disabled="option.disabled || disabled" @change="pick($event, option)">
<span class="gx-choice__title">
<i class="bi" :class="modelValue === option.value ? 'bi-check-circle-fill' : 'bi-circle'" aria-hidden="true"></i>
<strong>{{ option.label }}</strong>
<span v-if="option.badge" class="gx-starport-pill gx-starport-pill--soon">{{ option.badge }}</span>
</span>
</label>
</div>
<p v-if="selectedOption?.detail && !infoOpen" class="gx-choice__active-summary">{{ selectedOption.detail }}</p>
<div v-if="infoOpen" class="gx-choice__popover" role="region" :aria-label="label + ' details'">
<div class="gx-choice__popover-head">
<strong>{{ label }} options</strong>
<button type="button" class="gx-choice__popover-close" aria-label="Close details" @click="infoOpen = false">
<i class="bi bi-x-lg" aria-hidden="true"></i>
</button>
</div>
<dl class="gx-choice__popover-list">
<div v-for="option in options" :key="option.value" class="gx-choice__popover-item">
<dt><strong>{{ option.label }}</strong> <span v-if="option.badge" class="gx-starport-pill gx-starport-pill--soon">{{ option.badge }}</span></dt>
<dd>{{ option.detail }} <span v-if="option.limit" class="gx-choice__limit">{{ option.limit }}</span></dd>
</div>
</dl>
</div>
</fieldset>`,
}
// What each service does and where it stops. Mapbox always does search and offline roads.
export const COMPARE_ROWS = [
["Place search and addresses", "Yes", "No, Mapbox does this"],
["Offline road maps", "Yes", "No, Google tiles can't be saved"],
["Lane arrows on the turn card", "Yes", "No"],
["Traffic in route times", "Yes", "Yes, with a correction every 7½ minutes"],
["Map picture", "Road lines", "Street map with traffic colors"],
["Needs", "Mapbox token", "Google key with billing on"],
["Free monthly allowance", "Set by Mapbox; counted for this comma", "100,000 map tiles, 10,000 routes, 5,000 traffic routes"],
["When the allowance runs out", "Typing suggestions, address lookups and offline downloads pause until the 1st", "The comma stops at 99% and uses Mapbox until it resets"],
]
export const SourceCompare = {
name: "SourceCompare",
data() { return { rows: COMPARE_ROWS } },
template: `
<details class="gx-starport-wiki"><summary>Compare Mapbox and Google</summary>
<div class="gx-compare" role="table" aria-label="Mapbox compared with Google">
<div class="gx-compare__row gx-compare__row--head" role="row"><span role="columnheader">What you get</span><span role="columnheader">Mapbox</span><span role="columnheader">Google</span></div>
<div v-for="row in rows" :key="row[0]" class="gx-compare__row" role="row">
<span role="rowheader">{{ row[0] }}</span><span role="cell">{{ row[1] }}</span><span role="cell">{{ row[2] }}</span></div>
</div>
<p class="gx-note">Counts cover this comma only. Mapbox and Google bill everything that uses your key, including other apps.</p>
</details>`,
}
+226 -130
View File
@@ -1,4 +1,4 @@
import { SHORT_MAP_LINK, isMapLink, parseSharedDestination } from "./share-destination.js"
import { isMapLink } from "./share-destination.js"
import { GxNotice } from "./notice.js"
import { BluetoothNotice, bluetoothConnection } from "./bluetooth-notice.js"
import { connectionError } from "./polling.js"
@@ -7,6 +7,7 @@ import { MapOperationsPanel } from "./map-operations.js"
import { OfflineRoadMapsPanel } from "./offline-road-maps.js"
import { GalaxySelect } from "./galaxy-select.js"
import { reportSave } from "./save-feedback.js"
import { ChoiceGroup, SourceCompare } from "./navigation-setup.js"
export function searchUuid() {
if (typeof crypto.randomUUID === "function") return crypto.randomUUID()
@@ -24,8 +25,10 @@ export function remainingLocationLease(lease, requestStarted, now = performance.
const STATUS = new Set(["disabled", "needsKey", "noDestination", "waitingForLocation", "routing", "guiding", "arrived", "routeUnavailable", "stale"])
const ROUTE_AVOIDANCES = [{ key: "avoidTolls", label: "Avoid tolls" }, { key: "avoidHighways", label: "Avoid highways" },
{ key: "avoidFerries", label: "Avoid ferries" }]
const GPS_MODES = [{ value: "backup", label: "Phone GPS as backup" }, { value: "comma", label: "Comma and car GPS only" },
{ value: "phone", label: "Prefer phone GPS" }]
const GPS_MODES = [
{ value: "backup", label: "Comma and car, phone as backup", hint: "Uses the comma's or car's GPS. The phone fills in only when neither has a fix." },
{ value: "comma", label: "Comma and car only", hint: "Never uses the phone. Choose this if you don't share phone GPS." },
{ value: "phone", label: "Phone first", hint: "Uses the phone whenever it has a recent fix, otherwise the comma or car." }]
const GPS_NAMES = { comma: "Comma", car: "Car", phone: "Phone" }
const coordinate = (value) => !!value && Number.isFinite(value.latitude) && Math.abs(value.latitude) <= 90 &&
Number.isFinite(value.longitude) && Math.abs(value.longitude) <= 180
@@ -94,10 +97,11 @@ export class NavigationClient {
this.busy = false
this.error = ""
this.stale = false
this.refusal = null
}
emit() { this.publish({ data: this.data, results: this.results, searched: this.searched, busy: this.busy, error: this.error, stale: this.stale,
suggestions: this.suggestions }) }
suggestions: this.suggestions, resultsProvider: this.resultsProvider, suggestionsProvider: this.suggestionsProvider }) }
stop() {
if (this.searchId && this.data) {
this.fetcher("./api/navigation/action", { method: "POST", credentials: "same-origin", cache: "no-store",
@@ -179,6 +183,7 @@ export class NavigationClient {
this.suggestions = []
} else {
this.suggestions = payload.results
this.suggestionsProvider = payload.provider
this.suggestionResultsQuery = text
}
this.emit()
@@ -205,6 +210,7 @@ export class NavigationClient {
}
async run(operation, body = null) {
this.refusal = null
if (!this.active || this.busy) return null
this.controller?.abort()
if (this.timer !== null) this.cancelTimer(this.timer)
@@ -217,7 +223,7 @@ export class NavigationClient {
if (operation !== "status") this.error = ""
this.emit()
const deadline = this.later(() => controller.abort(), operation === "search" ? 24000 : operation === "action" && body?.action === "selectPlace" ? 12000 :
operation === "action" && body?.action === "testGoogleKey" ? 45000 : operation === "action" && body?.action === "resolveShare" ? 20000 : 4000)
operation === "action" && body?.action === "testGoogleKey" ? 45000 : operation === "action" && body?.action === "resolveShare" ? 20000 : operation === "action" && body?.action === "share" ? 30000 : 4000)
try {
// Status polls name the route lines they already hold; the comma then leaves them out.
const query = operation === "status" && this.data?.routeKey ? `?routeKey=${this.data.routeKey}` : ""
@@ -232,12 +238,17 @@ export class NavigationClient {
if (response.status === 401 || response.status === 503 && ["access_unavailable", "setup_required"].includes(payload?.code)) {
this.stop(); this.unauthorized(); return null
}
if (!response.ok) throw new Error(payload?.error || "Navigation could not complete this request.")
if (!response.ok) {
// A shared place the comma could not pin down comes back with the search to show instead.
if (response.status === 400 && body?.action === "share" && typeof payload?.query === "string") { this.refusal = payload; return null }
throw new Error(payload?.error || "Navigation could not complete this request.")
}
this.error = ""
if (operation === "search") {
if (!Array.isArray(payload.results) || payload.results.length > 20 || !payload.results.every(validSearchResult))
throw new Error("Search results could not be read.")
this.results = payload.results
this.resultsProvider = payload.provider
this.searched = true
} else {
if (payload?.routeUnchanged === true) {
@@ -260,7 +271,7 @@ export class NavigationClient {
}
if (!sameSnapshot(payload, this.data)) this.data = payload
this.stale = false
if (operation === "action" && ["select", "selectPlace", "clear"].includes(body.action)) { this.results = []; this.searched = false }
if (operation === "action" && ["select", "selectPlace", "clear", "share"].includes(body.action)) { this.results = []; this.searched = false }
}
return payload
} catch (error) {
@@ -295,15 +306,33 @@ export const FavoriteChoices = {
export const NavigationPage = {
name: "NavigationPage",
components: { GxNotice, BluetoothNotice, MapOperationsPanel, NavigationMap, OfflineRoadMapsPanel, FavoriteChoices, GalaxySelect },
components: { GxNotice, BluetoothNotice, MapOperationsPanel, NavigationMap, OfflineRoadMapsPanel, FavoriteChoices, GalaxySelect, ChoiceGroup, SourceCompare },
props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true },
go: { type: Function, default: null }, initialTab: { type: String, default: "route" }, tabs: { type: Array, required: true } },
data() { return { bluetooth: bluetoothConnection(), data: null, results: [], busy: false, error: "", stale: false, tab: this.initialTab, gpsGuide: "android", query: "", token: "", googleKey: "", googleTest: null, searched: false,
suggestions: [], suggestOpen: false, savedSuggestionPlaces: {}, favoritePicker: null, searchPending: false } },
data() { return { bluetooth: bluetoothConnection(), data: null, results: [], busy: false, error: "", stale: false, tab: this.initialTab, gpsGuide: "android", query: "", token: "", googleKey: "", googleTest: null, mapboxOpen: false, googleOpen: false, searched: false,
suggestions: [], suggestOpen: false, savedSuggestionPlaces: {}, favoritePicker: null, searchPending: false, resultsProvider: null, suggestionsProvider: null } },
watch: { initialTab(value) { this.tab = value } },
computed: {
routeAvoidances() { return ROUTE_AVOIDANCES },
gpsModes() { return GPS_MODES },
googleReady() { return !!this.data?.hasGoogleKey },
mapChoices() {
return [{ value: "mapbox", label: "Mapbox", detail: "Road lines, drawn from saved or live Mapbox data.", limit: "Works offline once roads are saved." },
{ value: "google", label: "Google", detail: "Google's street map with traffic colors.", disabled: !this.googleReady, badge: this.googleReady ? "" : "Needs key",
limit: "Needs internet and the Mapbox key. Google tiles can't be saved offline." }]
},
routeChoices() {
return [{ value: "mapbox", label: "Mapbox", detail: "Turn-by-turn with lane arrows.", limit: "Counted against your Mapbox allowance." },
{ value: "google", label: "Google", detail: "Routes that follow live traffic, and place search by Google.", disabled: !this.googleReady, badge: this.googleReady ? "" : "Needs key",
limit: "Needs the Mapbox key too. No lane arrows. Falls back to Mapbox when its limits run out." }]
},
gpsChoices() { return GPS_MODES.map((mode) => ({ value: mode.value, label: mode.label, detail: mode.hint })) },
destinationWays() {
return [{ icon: "bi-search", title: "Search here", detail: "Type an address or place on the Destination page." },
{ icon: "bi-link-45deg", title: "Paste a Google Maps link", detail: "Paste a place link into search, short links included." },
{ icon: "bi-android2", title: "Share from Android", detail: "Google Maps → Share → StarPilot. The route starts on your comma." },
{ icon: "bi-apple", title: "Share from iPhone", detail: "Google Maps or Apple Maps → Share → StarPilot. The route starts on your comma." }]
},
gpsLabel() {
if (this.mode !== "local" || !this.ready || this.stale) return "GPS Source"
const source = this.data?.location?.lastKnown ? null : GPS_NAMES[this.data?.location?.source]
@@ -336,9 +365,33 @@ export const NavigationPage = {
return [["searchSessions", "Searches"], ["geocoding", "Address lookups"], ["directions", "Routes"], ["staticTiles", "Map views"]]
.filter(([key]) => usage[key]).map(([key, label]) => ({ key, label, ...usage[key] }))
},
// Place search follows the Directions choice, as on the comma.
googlePlaces() { return this.data?.routeProvider === "google" && !!this.data?.hasGoogleKey },
sources() {
if (!this.data) return []
const google = (value) => value === "google" && !!this.data.hasGoogleKey ? "Google" : "Mapbox"
return [{ label: "Map", value: google(this.data.mapProvider), icon: "bi-map" },
{ label: "Directions", value: google(this.data.routeProvider), icon: "bi-signpost-split" },
{ label: "Places", value: google(this.data.routeProvider), icon: "bi-geo-alt" },
{ label: "Position", value: this.gpsLabel.replace("GPS: ", ""), icon: "bi-crosshair" }]
},
googleUsage() { return this.data?.googleMap?.usage || null },
googleRouteUsage() { return this.data?.googleRoutes?.usage || null },
googleEssentialUsage() { return this.data?.googleRoutes?.essentials || null },
googlePlaceUsage() { return this.data?.googlePlaces?.usage || null },
googleSuggestionUsage() { return this.data?.googlePlaces?.suggestions || null },
googleTests() {
const test = this.googleTest
if (!test) return []
return [["Map Tiles API", test, "tile.googleapis.com"], ["Routes API", test.routes, "routes.googleapis.com"], ["Places API (New)", test.places, "places.googleapis.com"]]
.filter(([, result]) => result).map(([name, result, api]) => ({ name, ok: !!result.ok, message: result.message, missing: !result.ok && result.failure !== "budget",
link: result.failure === "billing" ? { href: "https://console.cloud.google.com/billing", label: "Turn on billing" } :
["key", "disabled"].includes(result.failure) ? { href: `https://console.cloud.google.com/apis/library/${api}`, label: `Open ${name} in Google Cloud` } : null }))
},
googleWorking() {
const rows = this.googleTests
return rows.length ? `${rows.length - rows.filter((row) => row.missing).length} of ${rows.length} APIs working` : ""
},
path() { return routePath(this.data?.route) },
summary() {
const instruction = this.data?.instruction, route = this.data?.alternatives?.[this.data?.selectedRoute || 0]
@@ -384,17 +437,15 @@ export const NavigationPage = {
this.tab = tab
this.go?.(tab === 'route' ? '/navigation' : `/navigation/${tab}`)
},
// The comma opens the link, looks the place up, turns navigation on and starts the route.
async openShared(text) {
let parsed = parseSharedDestination(text)
// A Google Maps short link is followed on the comma to the full link, which carries the coordinates.
if (!parsed.destination && SHORT_MAP_LINK.test(text)) {
const resolved = (await this.client.action('resolveShare', { text: String(text).slice(0, 8192) }))?.sharedText
if (resolved) parsed = parseSharedDestination(resolved)
}
if (parsed.destination) { await this.client.action('select', { destination: parsed.destination }); return }
if (await this.client.action('share', { text: String(text).slice(0, 8192) })) return
const query = this.client.refusal?.query
if (!query) return
// Text shares can be ambiguous ("Starbucks"); show the results and let the driver pick.
this.query = parsed.query
await this.client.search(parsed.query)
if (!this.client.data?.enabled && !await this.client.action('configure', { patch: { enabled: true } })) return
this.query = query
await this.client.search(query)
},
async search() {
if (this.searchPending) return
@@ -485,132 +536,175 @@ export const NavigationPage = {
template: `
<div class="gx-view gx-navigation" :inert="busy || searchPending" :aria-busy="busy || searchPending || undefined">
<header class="gx-settings__header gx-page-header"><div><h2>Navigation</h2>
<p>Set a destination, prepare offline maps, and configure navigation and Mapbox.</p></div></header>
<p>Pick a destination, save maps for offline use, and choose where maps, directions and position come from.</p></div></header>
<ul v-if="sources.length" class="gx-navigation__sources" aria-label="Current sources">
<li v-for="source in sources" :key="source.label"><a class="gx-navigation__chip" href="#/navigation/setup" @click.prevent="selectTab('setup')"><i class="bi" :class="source.icon" aria-hidden="true"></i><span>{{ source.label }}: {{ source.value }}</span></a></li>
</ul>
<div class="gx-tabs gx-actions" role="group" aria-label="Navigation tools">
<button v-for="item in tabs" :key="item.tab"
type="button" class="gx-btn" :class="tab === item.tab ? '' : 'gx-btn--tonal'" :aria-pressed="tab === item.tab" @click="selectTab(item.tab)">{{ item.name }}</button>
<button type="button" class="gx-btn gx-btn--tonal" @click="openGpsSetup">{{ gpsLabel }}</button>
</div>
<div v-if="tab === 'maps'" class="gx-navigation__offline">
<OfflineRoadMapsPanel :mode="mode" :unauthorized="unauthorized" :has-key="!!data?.hasKey" :metric="data?.isMetric !== false" />
<MapOperationsPanel :mode="mode" :unauthorized="unauthorized" />
</div>
<template v-else-if="tab === 'setup'">
<p v-if="mode !== 'local'" class="gx-note">Connect to your comma to set up navigation and choose a destination.</p>
<p v-if="mode !== 'local'" class="gx-note">Connect to your comma to set up navigation.</p>
<GxNotice tone="danger" v-if="error">{{ error }}</GxNotice>
<section class="gx-card gx-navigation__section">
<div class="gx-section__header"><i class="bi bi-compass" aria-hidden="true"></i><span class="gx-section__title">Navigation</span></div>
<p>Show directions on your comma. Navigation works with every driving model. Route guidance helps prepare for turns; steering and speed control follow your normal engagement settings.</p>
<div v-if="data" class="gx-row gx-row--borderless"><span class="gx-row__info gx-row__label">Navigation</span>
<label class="gx-switch"><input type="checkbox" role="switch" aria-label="Navigation" :checked="data.enabled" :disabled="!controlsAvailable"
<section class="gx-card gx-navigation__section gx-navigation__power">
<div class="gx-row gx-row--borderless"><span class="gx-row__info"><strong class="gx-row__label">Navigation</strong><small class="gx-note">Turn-by-turn guidance on your comma. It works with every driving model and never steers for you.</small></span>
<label v-if="data" class="gx-switch"><input type="checkbox" role="switch" aria-label="Navigation" :checked="data.enabled" :disabled="!controlsAvailable"
@change="$event.target.checked=data.enabled; reportSave(() => client.action('configure', {patch: {enabled: !data.enabled}}))"><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
</section>
<section ref="gpsSetup" tabindex="-1" class="gx-card gx-navigation__section gx-navigation__gps" aria-labelledby="navigation-gps-heading">
<h3 id="navigation-gps-heading">GPS Source</h3>
<p>Choose where your comma gets its position for navigation and map speed limits. Phone GPS comes from the StarPilot app over Bluetooth or local Wi-Fi.</p>
<div class="gx-row gx-row--stack gx-row--borderless">
<span class="gx-row__label" id="navigation-gps-mode">Use</span>
<GalaxySelect class="gx-field gx-field--full" aria-labeledby="navigation-gps-mode" :value="data?.gpsSource || 'backup'" :disabled="!available || !data"
@change="client.action('configure', {patch: {gpsSource: $event.target.value}})">
<option v-for="option in gpsModes" :key="option.value" :value="option.value">{{ option.label }}</option>
</GalaxySelect>
</div>
<p v-if="data?.phoneGps">Phone updates: {{ data.phoneGps.usable ? 'usable' : 'waiting for a usable fix' }}.
Last update {{ Math.round(data.phoneGps.receivedAgeMs / 1000) }} seconds ago.
<span v-if="!data.phoneGps.accepted">{{ ({poorAccuracy: 'Position accuracy is too low.', outOfOrder: 'An older or repeated update was ignored.', delayed: 'An update arrived too late.'})[data.phoneGps.reason] || 'The last update was invalid.' }}</span>
</p>
<h4>Set up GPS sharing</h4>
<div class="gx-actions" role="group" aria-label="GPS setup guides">
<button v-for="source in [{id:'android',label:'Android App'},{id:'iphone',label:'iPhone'}]" :key="source.id"
type="button" class="gx-btn" :class="gpsGuide === source.id ? '' : 'gx-btn--tonal'" :aria-pressed="gpsGuide === source.id"
@click="gpsGuide = source.id">{{ source.label }}</button>
</div>
<div v-if="gpsGuide === 'android'">
<ol><li>Open the StarPilot companion app and connect to your comma over Bluetooth or Galaxy Wi-Fi.</li>
<li>Open Connections → Phone GPS → <strong>Share phone GPS with comma</strong>.</li>
<li>Allow precise location. Keep the app’s GPS-sharing notification active while driving.</li></ol>
<p>To stop, open Connections and select <strong>Stop sharing phone GPS</strong>.</p>
</div>
<div v-else>
<ol><li>Open the StarPilot iPhone companion app and connect to your comma over Bluetooth or Wi-Fi.</li>
<li>On the app’s main Settings page, turn on <strong>Share Phone Location</strong>.</li>
<li>Set location access to <strong>Always</strong> and enable Precise Location in iPhone Settings. The app continues sharing in the background while the switch is on.</li></ol>
<p>Turn off <strong>Share Phone Location</strong> on the app’s main Settings page to stop sharing.</p>
</div>
<details><summary>About phone GPS and switching phones</summary>
<p>The GPS source you choose is used for navigation and for map-based speed limits and curves. The phone must reach the comma over Bluetooth or local Wi-Fi; the remote tunnel doesn't carry GPS.</p>
<p>To change phones, stop GPS sharing in the old app and enable it in the other app. Both apps need a version with phone GPS support, and your comma must support receiving it.</p>
</details>
</section>
<section class="gx-card gx-navigation__section">
<div class="gx-section__header"><i class="bi bi-signpost-split" aria-hidden="true"></i><span class="gx-section__title">Route preferences</span></div>
<p>Apply to new routes and automatic reroutes. Changing a preference recalculates your current route.</p>
<div v-for="option in routeAvoidances" :key="option.key" class="gx-row">
<span class="gx-row__info gx-row__label">{{ option.label }}</span>
<label class="gx-switch"><input type="checkbox" role="switch" :aria-label="option.label" :checked="!!data?.[option.key]"
:disabled="!available" @change="reportSave(() => client.action('configure', {patch: {[option.key]: $event.target.checked}}))"><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label>
<div class="gx-navigation__prefs" role="group" aria-label="Route preferences">
<div class="gx-navigation__prefs-head">
<strong class="gx-row__label">Route preferences</strong>
<small class="gx-note">Applies to new routes and reroutes, and recalculates your current route.</small>
</div>
<div class="gx-navigation__pref-chips">
<label v-for="option in routeAvoidances" :key="option.key" class="gx-navigation__pref" :class="{ 'gx-navigation__pref--on': !!data?.[option.key], 'gx-navigation__pref--disabled': !available }">
<input type="checkbox" role="switch" class="gx-sr-only" :aria-label="option.label" :checked="!!data?.[option.key]"
:disabled="!available" @change="reportSave(() => client.action('configure', {patch: {[option.key]: $event.target.checked}}))">
<i class="bi" :class="data?.[option.key] ? 'bi-check-lg' : 'bi-slash-circle'" aria-hidden="true"></i>
<span>{{ option.label }}</span>
</label>
</div>
</div>
</section>
<section class="gx-card gx-navigation__section">
<div class="gx-section__header"><i class="bi bi-map" aria-hidden="true"></i><span class="gx-section__title">Mapbox</span></div>
<p>One public Mapbox access token (starting with pk.) handles the map, place and address search, and routes. A separate secret token is not needed.</p>
<p>Save your token while parked. Galaxy keeps it on your comma and never displays it after saving. Address searches use temporary geocoding. Search suggestions are temporary and used only for the current route. Favorites and recent destinations are also kept on your comma; going to one skips search, so it uses none of your search allowance. URL-restricted keys may reject map requests.</p>
<p class="gx-note">Typing suggestions, address lookups and offline road maps stop just short of their free monthly allowances and resume on the 1st. Routes, full place searches and map views are counted but not limited. These counts cover this comma only; Mapbox bills total account usage, including other apps and devices.</p>
<dl v-if="usageRows.length" class="gx-navigation__usage" aria-label="Mapbox use this month">
<template v-for="row in usageRows" :key="row.key"><dt>{{ row.label }}</dt><dd>{{ row.used.toLocaleString() }} of {{ row.limit.toLocaleString() }} free this month</dd></template>
</dl>
<a class="gx-btn gx-btn--tonal gx-navigation__token-link" href="https://account.mapbox.com/access-tokens/" target="_blank" rel="noopener noreferrer">Get a Mapbox access token</a>
<p v-if="data?.hasKey" class="gx-note">A Mapbox key is saved.</p>
<div class="gx-field-group"><label for="navigation-token">Public Mapbox access token</label>
<form @submit.prevent="saveKey(false)" class="gx-navigation__search">
<input id="navigation-token" class="gx-field" type="password" autocomplete="off" v-model="token" placeholder="pk.…" maxlength="2048" required :disabled="!controlsAvailable">
<button class="gx-btn" type="submit" :disabled="!controlsAvailable || !token.trim()">{{ data?.hasKey ? 'Replace key' : 'Save key' }}</button>
</form></div>
<section class="gx-card gx-starport-step" :class="{ 'gx-starport-step--done': data?.hasKey }">
<div class="gx-starport-step__head">
<span class="gx-starport-step__num" aria-hidden="true"><i v-if="data?.hasKey" class="bi bi-check-lg"></i><template v-else>1</template></span>
<div>
<div class="gx-navigation__step-title"><h3>Mapbox key</h3><span class="gx-starport-pill" :class="data?.hasKey ? 'gx-starport-pill--ready' : 'gx-starport-pill--soon'" role="status">{{ data?.hasKey ? 'Key saved' : 'Needs a key' }}</span></div>
<p>Required, with or without Google. Finds places, saves offline roads, plans routes and backs up Google.</p>
</div>
<button v-if="data?.hasKey" type="button" class="gx-btn gx-btn--tonal" :aria-expanded="mapboxOpen" aria-controls="navigation-mapbox" @click="mapboxOpen = !mapboxOpen">{{ mapboxOpen ? 'Hide' : 'Manage' }}</button>
</div>
<div id="navigation-mapbox" v-show="!data?.hasKey || mapboxOpen" class="gx-starport-step__body">
<form @submit.prevent="saveKey(false)" class="gx-navigation__search">
<label for="navigation-token" class="gx-sr-only">Public Mapbox access token</label>
<input id="navigation-token" class="gx-field" type="password" autocomplete="off" v-model="token" placeholder="pk.…" maxlength="2048" required :disabled="!controlsAvailable">
<button class="gx-btn" type="submit" :disabled="!controlsAvailable || !token.trim()">{{ data?.hasKey ? 'Replace key' : 'Save key' }}</button>
</form>
<div class="gx-actions"><a class="gx-btn gx-btn--tonal" href="https://account.mapbox.com/access-tokens/" target="_blank" rel="noopener noreferrer">Get a Mapbox token</a></div>
<dl v-if="usageRows.length" class="gx-navigation__usage" aria-label="Mapbox use this month">
<template v-for="row in usageRows" :key="row.key"><dt>{{ row.label }}</dt><dd>{{ row.used.toLocaleString() }} of {{ row.limit.toLocaleString() }} free</dd></template>
</dl>
<details class="gx-starport-wiki"><summary>About the token and your allowance</summary>
<p>Use the public token that starts with pk. A secret token isn't needed, and URL-restricted tokens may be rejected. Galaxy keeps the token on your comma and never shows it again.</p>
<p>Typing suggestions, address lookups and offline road maps stop just short of their free monthly allowances and resume on the 1st. Routes, full searches and map views are counted but not limited. Saved places and recents skip search entirely.</p>
</details>
</div>
</section>
<section class="gx-card gx-navigation__section">
<div class="gx-section__header"><i class="bi bi-globe-americas" aria-hidden="true"></i><span class="gx-section__title">Google map and routes</span></div>
<p>Show Google's road map with live traffic in the map widget, and route with Google's traffic, using your own Google Maps Platform key. Mapbox still handles search and offline road maps, its road lines show wherever a Google tile hasn't loaded, and it routes whenever Google can't.</p>
<div class="gx-row gx-row--stack gx-row--borderless">
<span class="gx-row__label" id="navigation-map-style">Map style</span>
<GalaxySelect class="gx-field gx-field--full" aria-labeledby="navigation-map-style" :value="data?.mapProvider || 'mapbox'" :disabled="!available || !data"
@change="reportSave(() => client.action('configure', {patch: {mapProvider: $event.target.value}}))">
<option value="mapbox">Mapbox road lines</option>
<option value="google" :disabled="!data?.hasGoogleKey">Google map</option>
</GalaxySelect>
<section class="gx-card gx-starport-step" :class="{ 'gx-starport-step--done': data?.hasGoogleKey }">
<div class="gx-starport-step__head">
<span class="gx-starport-step__num" aria-hidden="true"><i v-if="data?.hasGoogleKey" class="bi bi-check-lg"></i><template v-else>2</template></span>
<div>
<div class="gx-navigation__step-title"><h3>Google key</h3><span class="gx-starport-pill" :class="data?.hasGoogleKey ? 'gx-starport-pill--ready' : ''" role="status">{{ data?.hasGoogleKey ? (googleWorking ? 'Key saved · ' + googleWorking : 'Key saved') : 'Optional' }}</span></div>
<p>Added on top of the Mapbox key. Unlocks Google's street &amp; traffic map, live-traffic routes and place search.</p>
</div>
<button type="button" class="gx-btn gx-btn--tonal" :aria-expanded="googleOpen" aria-controls="navigation-google" @click="googleOpen = !googleOpen">{{ googleOpen ? 'Hide' : data?.hasGoogleKey ? 'Manage' : 'Add key' }}</button>
</div>
<div class="gx-row gx-row--stack gx-row--borderless">
<span class="gx-row__label" id="navigation-route-provider">Routes</span>
<GalaxySelect class="gx-field gx-field--full" aria-labeledby="navigation-route-provider" :value="data?.routeProvider || 'mapbox'" :disabled="!available || !data"
@change="reportSave(() => client.action('configure', {patch: {routeProvider: $event.target.value}}))">
<option value="mapbox">Mapbox (with lane arrows)</option>
<option value="google" :disabled="!data?.hasGoogleKey">Google traffic routes</option>
</GalaxySelect>
<GxNotice v-if="data?.hasGoogleKey && !data?.hasKey" tone="warn">Google isn't used until the Mapbox key above is added too.</GxNotice>
<div id="navigation-google" v-show="googleOpen" class="gx-starport-step__body">
<form @submit.prevent="saveGoogleKey" class="gx-navigation__search">
<label for="navigation-google-key" class="gx-sr-only">Google Maps Platform API key</label>
<input id="navigation-google-key" class="gx-field" type="password" autocomplete="off" v-model="googleKey" placeholder="AIza…" maxlength="128" required :disabled="!controlsAvailable">
<button class="gx-btn" type="submit" :disabled="!controlsAvailable || !googleKey.trim()">{{ data?.hasGoogleKey ? 'Replace key' : 'Save key' }}</button>
</form>
<div class="gx-actions"><button type="button" class="gx-btn gx-btn--tonal" :disabled="!available || !googleKey.trim() && !data?.hasGoogleKey" @click="testGoogleKey">Test key</button></div>
<p v-if="googleWorking && !data?.hasGoogleKey" class="gx-note" role="status"><strong>{{ googleWorking }}</strong></p>
<GxNotice v-for="row in googleTests" :key="row.name" :tone="row.ok ? 'success' : 'warn'">{{ row.name }}: {{ row.message }}
<a v-if="row.link" :href="row.link.href" target="_blank" rel="noopener noreferrer">{{ row.link.label }}</a></GxNotice>
<GxNotice v-if="data?.googleMap?.failure" tone="warn">{{ data.googleMap.failure }}</GxNotice>
<GxNotice v-if="data?.googleRoutes?.failure" tone="warn">{{ data.googleRoutes.failure }}</GxNotice>
<dl v-if="googleUsage" class="gx-navigation__usage" aria-label="Google use">
<dt>Map tiles this month</dt><dd>{{ googleUsage.monthUsed.toLocaleString() }} of {{ googleUsage.monthLimit.toLocaleString() }} free</dd>
<dt>Map tiles today</dt><dd>{{ googleUsage.dayUsed.toLocaleString() }} of {{ googleUsage.dayLimit.toLocaleString() }} free</dd>
<template v-if="googleEssentialUsage"><dt>Routes this month</dt><dd>{{ googleEssentialUsage.monthUsed.toLocaleString() }} of {{ googleEssentialUsage.monthLimit.toLocaleString() }} free</dd></template>
<template v-if="googleRouteUsage"><dt>Traffic routes this month</dt><dd>{{ googleRouteUsage.monthUsed.toLocaleString() }} of {{ googleRouteUsage.monthLimit.toLocaleString() }} free</dd></template>
<template v-if="googlePlaceUsage"><dt>Place searches this month</dt><dd>{{ googlePlaceUsage.monthUsed.toLocaleString() }} of {{ googlePlaceUsage.monthLimit.toLocaleString() }} free</dd></template>
<template v-if="googleSuggestionUsage"><dt>Typing suggestions this month</dt><dd>{{ googleSuggestionUsage.monthUsed.toLocaleString() }} of {{ googleSuggestionUsage.monthLimit.toLocaleString() }} free</dd></template>
</dl>
<details class="gx-starport-wiki"><summary>Get a Google key (about 10 minutes, once)</summary>
<ol><li>Sign in to <a href="https://console.cloud.google.com/projectcreate" target="_blank" rel="noopener noreferrer">Google Cloud</a> and create a project.</li>
<li><a href="https://console.cloud.google.com/billing" target="_blank" rel="noopener noreferrer">Turn on billing</a>. Google asks for a card even though the comma stays inside the free allowance.</li>
<li>Enable the <a href="https://console.cloud.google.com/apis/library/tile.googleapis.com" target="_blank" rel="noopener noreferrer">Map Tiles API</a> for the map, the <a href="https://console.cloud.google.com/apis/library/routes.googleapis.com" target="_blank" rel="noopener noreferrer">Routes API</a> for routes and <a href="https://console.cloud.google.com/apis/library/places.googleapis.com" target="_blank" rel="noopener noreferrer">Places API (New)</a> for place search.</li>
<li><a href="https://console.cloud.google.com/apis/credentials" target="_blank" rel="noopener noreferrer">Create an API key</a> and limit it to those three APIs. Leave application restrictions off; the comma's address changes on cellular.</li>
<li>Keep your Mapbox key; Google works alongside it. Paste the Google key here while parked, then press <strong>Test key</strong>. It checks all three APIs.</li></ol>
</details>
<details class="gx-starport-wiki"><summary>How the Google limits work</summary>
<p>The comma stops at 99% of Google's free allowance: 100,000 map tiles a month (15,000 a day), 10,000 routes, 5,000 traffic routes, 5,000 place searches (shared places included) and 10,000 typing suggestions. Every route and reroute uses live traffic, and one more request every 7½ minutes corrects the arrival time.</p>
<p>Past 20 reroutes in an hour, or when traffic routes run out, routes ignore traffic. Past both limits the comma uses Mapbox until they reset. Google routes have no lane arrows. Place search uses Google when Google gives directions, and Mapbox if Google can't answer.</p>
</details>
</div>
</section>
<section class="gx-card gx-starport-step">
<div class="gx-starport-step__head">
<span class="gx-starport-step__num" aria-hidden="true">3</span>
<div><h3>Choose your sources</h3><p>Google choices need both keys. Each one falls back to Mapbox if it can't work.</p></div>
</div>
<div class="gx-starport-step__body">
<ChoiceGroup label="Map picture" :model-value="data?.mapProvider || 'mapbox'" :options="mapChoices" :disabled="!available || !data"
@update:model-value="reportSave(() => client.action('configure', {patch: {mapProvider: $event}}))" />
<ChoiceGroup label="Directions" :model-value="data?.routeProvider || 'mapbox'" :options="routeChoices" :disabled="!available || !data"
@update:model-value="reportSave(() => client.action('configure', {patch: {routeProvider: $event}}))" />
<div ref="gpsSetup" tabindex="-1" class="gx-navigation__gps">
<ChoiceGroup label="Position" :model-value="data?.gpsSource || 'backup'" :options="gpsChoices" :disabled="!available || !data"
@update:model-value="reportSave(() => client.action('configure', {patch: {gpsSource: $event}}))" />
<p v-if="data?.phoneGps" class="gx-navigation__gps-status" role="status">
<span class="gx-starport-pill" :class="data.phoneGps.usable ? 'gx-starport-pill--ready' : 'gx-starport-pill--soon'">
Phone GPS: {{ data.phoneGps.usable ? 'Receiving updates' : 'Waiting for a usable fix' }} · {{ Math.round(data.phoneGps.receivedAgeMs / 1000) }}s ago
</span>
<small v-if="!data.phoneGps.accepted" class="gx-note">{{ ({poorAccuracy: 'Accuracy is too low.', outOfOrder: 'An older update was ignored.', delayed: 'An update arrived late.'})[data.phoneGps.reason] || 'The last update was invalid.' }}</small>
</p>
<details class="gx-starport-wiki">
<summary>How to share phone GPS from the StarPilot app</summary>
<p class="gx-note">Reaches your comma over Bluetooth or local Wi-Fi, never the remote tunnel.</p>
<div class="gx-navigation__gps-guides">
<div class="gx-navigation__gps-card">
<strong><i class="bi bi-android2" aria-hidden="true"></i> Android</strong>
<ol class="gx-starport-mirror-steps">
<li>Open the StarPilot app and connect to your comma.</li>
<li>Open <strong>Connections → Phone GPS</strong> and turn on <strong>Share phone GPS with comma</strong>.</li>
<li>Allow precise location and leave the sharing notification on while driving.</li>
</ol>
</div>
<div class="gx-navigation__gps-card">
<strong><i class="bi bi-apple" aria-hidden="true"></i> iPhone</strong>
<ol class="gx-starport-mirror-steps">
<li>Open the StarPilot app and connect to your comma.</li>
<li>On the main Settings page, turn on <strong>Share Phone Location</strong>.</li>
<li>Set location access to <strong>Always</strong> and turn on <strong>Precise Location</strong> in iPhone Settings.</li>
</ol>
</div>
</div>
<p class="gx-note"><strong>Switching phones:</strong> stop sharing in the old app before turning it on in the new one.</p>
</details>
</div>
<SourceCompare />
</div>
</section>
<section class="gx-card gx-starport-step">
<div class="gx-starport-step__head">
<span class="gx-starport-step__num" aria-hidden="true"><i class="bi bi-send"></i></span>
<div><h3>Ways to send a destination</h3><p>Start a trip from Galaxy or share a place straight from your phone.</p></div>
</div>
<div class="gx-starport-step__body">
<ul class="gx-starport-list" aria-label="Ways to set a destination">
<li v-for="way in destinationWays" :key="way.title" class="gx-starport-row"><i class="bi" :class="way.icon" aria-hidden="true"></i>
<span class="gx-starport-row__text"><strong>{{ way.title }}</strong><small>{{ way.detail }}</small></span></li>
</ul>
<details class="gx-starport-wiki"><summary>How to share a place from your phone</summary>
<p><strong>Android:</strong> open a place in Google Maps, tap Share, then choose StarPilot.</p>
<p><strong>iPhone:</strong> open a place in Google Maps or Apple Maps, tap Share, then choose StarPilot. The first time, scroll the app row to More and turn on StarPilot.</p>
<p>Your comma turns on navigation and starts the route. Places without coordinates are looked up on your comma with your chosen route provider. A name alone opens the StarPilot app as a search.</p>
<p>Both need the latest StarPilot app, a Mapbox key above, and a way to reach your comma: Bluetooth, local Wi-Fi or the remote route. If your comma can't be reached, the phone keeps the place and sends it when it next connects, within 12 hours.</p>
</details>
</div>
<details><summary>Get a Google key (about 10 minutes, once)</summary>
<ol><li>Sign in to <a href="https://console.cloud.google.com/projectcreate" target="_blank" rel="noopener noreferrer">Google Cloud</a> and create a project.</li>
<li><a href="https://console.cloud.google.com/billing" target="_blank" rel="noopener noreferrer">Turn on billing</a> for it. Google asks for a card even though the comma stays inside the free allowance.</li>
<li>Enable the <a href="https://console.cloud.google.com/apis/library/tile.googleapis.com" target="_blank" rel="noopener noreferrer">Map Tiles API</a>, and the <a href="https://console.cloud.google.com/apis/library/routes.googleapis.com" target="_blank" rel="noopener noreferrer">Routes API</a> for Google routes.</li>
<li><a href="https://console.cloud.google.com/apis/credentials" target="_blank" rel="noopener noreferrer">Create an API key</a> and restrict it to those APIs. Leave application restrictions off; the comma's address changes on cellular.</li>
<li>Paste the key below while parked, then press <strong>Test key</strong>.</li></ol>
</details>
<p class="gx-note">The comma stops at 99% of Google's free 100,000 map tiles a month and 15,000 a day, and at 99% of Google's free routes: 10,000 a month without traffic, and 5,000 traffic requests. Every route, including a reroute, uses live traffic (one traffic request each), and every 7½ minutes one more corrects the arrival time. Past 20 reroutes in an hour, or once traffic requests run out, routes ignore traffic; past both limits the comma uses Mapbox until they reset. Google routes have no lane arrows. These counts cover this comma only; Google bills everything that uses the key.</p>
<dl v-if="googleUsage" class="gx-navigation__usage" aria-label="Google map use">
<dt>Map tiles this month</dt><dd>{{ googleUsage.monthUsed.toLocaleString() }} of {{ googleUsage.monthLimit.toLocaleString() }} free</dd>
<dt>Map tiles today</dt><dd>{{ googleUsage.dayUsed.toLocaleString() }} of {{ googleUsage.dayLimit.toLocaleString() }} free</dd>
<template v-if="googleEssentialUsage"><dt>Routes this month</dt><dd>{{ googleEssentialUsage.monthUsed.toLocaleString() }} of {{ googleEssentialUsage.monthLimit.toLocaleString() }} free</dd></template>
<template v-if="googleRouteUsage"><dt>Traffic requests this month</dt><dd>{{ googleRouteUsage.monthUsed.toLocaleString() }} of {{ googleRouteUsage.monthLimit.toLocaleString() }} free</dd></template>
</dl>
<GxNotice v-if="data?.googleMap?.failure" tone="warn">{{ data.googleMap.failure }}</GxNotice>
<GxNotice v-if="data?.googleRoutes?.failure" tone="warn">{{ data.googleRoutes.failure }}</GxNotice>
<p v-if="data?.hasGoogleKey" class="gx-note">A Google key is saved.</p>
<div class="gx-field-group"><label for="navigation-google-key">Google Maps Platform API key</label>
<form @submit.prevent="saveGoogleKey" class="gx-navigation__search">
<input id="navigation-google-key" class="gx-field" type="password" autocomplete="off" v-model="googleKey" placeholder="AIza…" maxlength="128" required :disabled="!controlsAvailable">
<button class="gx-btn" type="submit" :disabled="!controlsAvailable || !googleKey.trim()">{{ data?.hasGoogleKey ? 'Replace key' : 'Save key' }}</button>
</form></div>
<div class="gx-actions"><button type="button" class="gx-btn gx-btn--tonal" :disabled="!available || !googleKey.trim() && !data?.hasGoogleKey" @click="testGoogleKey">Test key</button></div>
<GxNotice v-if="googleTest" :tone="googleTest.ok ? 'success' : 'warn'">Map: {{ googleTest.message }}</GxNotice>
<GxNotice v-if="googleTest?.routes" :tone="googleTest.routes.ok ? 'success' : 'warn'">Routes: {{ googleTest.routes.message }}</GxNotice>
</section>
</template>
<template v-else>
@@ -629,7 +723,7 @@ export const NavigationPage = {
<div class="gx-navigation__field">
<i class="bi bi-search" aria-hidden="true"></i>
<label for="navigation-search" class="gx-sr-only">Search destinations</label>
<input id="navigation-search" ref="search" v-model="query" placeholder="Address or place name" minlength="2" maxlength="200" required
<input id="navigation-search" ref="search" v-model="query" placeholder="Address, place or Google Maps link" minlength="2" maxlength="200" required
autocomplete="off" enterkeyhint="search" :disabled="!controlsAvailable" role="searchbox"
@input="typed" @focus="suggestOpen = true" @keydown.escape="closeSuggestions">
<button v-if="query || results.length" type="button" class="gx-navigation__icon" aria-label="Clear search" @mousedown.prevent @click="clearQuery"><i class="bi bi-x-lg" aria-hidden="true"></i></button>
@@ -662,6 +756,7 @@ export const NavigationPage = {
<button type="button" class="gx-navigation__icon" :aria-label="'Save ' + place.name" :aria-expanded="favoritePicker === favoriteKey(place)" :disabled="!controlsAvailable || place.temporary" :title="place.temporary ? 'Search for an address to save this place' : undefined" @click="openFavorite(place)"><i class="bi" :class="isFavorite(place) ? 'bi-star-fill' : 'bi-star'" aria-hidden="true"></i></button>
<FavoriteChoices v-if="favoritePicker === favoriteKey(place)" :available="controlsAvailable" @choose="saveAs(place, $event)" />
</div>
<div v-if="suggestions.length && googlePlaces" class="gx-navigation__group"><span>{{ suggestionsProvider === 'google' ? 'Suggestions from Google' : 'Suggestions from Mapbox, Google unavailable' }}</span></div>
<div v-for="place in suggestions" :key="place.id" class="gx-navigation__row">
<button type="button" class="gx-navigation__suggestion" :disabled="!controlsAvailable" @click="pick(place)">
<i class="bi bi-geo-alt-fill" aria-hidden="true"></i><span><strong><span translate="no">{{ place.name }}</span></strong><small v-if="place.description">{{ place.description }}</small></span></button>
@@ -705,6 +800,7 @@ export const NavigationPage = {
<template v-else>
<p v-if="busy || searchPending" role="status" class="gx-navigation__busy">{{ searchPending ? 'Searching…' : 'Working…' }}</p>
<p v-if="searched && !busy && !error && results.length === 0" class="gx-card gx-navigation__section gx-note">No places found. Try a nearby town or a more specific address.</p>
<p v-if="results.length && googlePlaces" class="gx-note" role="status">{{ resultsProvider === 'google' ? 'Places found with Google.' : "Google couldn't search just now, so these places are from Mapbox." }}</p>
<ul v-if="results.length" class="gx-navigation__places" aria-label="Search results">
<li v-for="place in results" :key="place.id" class="gx-navigation__row">
<button type="button" class="gx-navigation__suggestion" :disabled="!controlsAvailable" @click="pick(place)" :aria-label="'Start navigation to ' + place.name">
@@ -51,13 +51,15 @@ export function areaLabel(area) {
const progress = area.progress
if (!progress) return "Waiting for the downloader"
const percent = progress.total ? Math.floor(progress.done / progress.total * 100) : 0
return ({ queued: "Queued", downloading: `Downloading · ${percent}%`, waiting_wifi: `Waiting for Wi-Fi · ${percent}%`,
complete: "Saved for offline", incomplete: `${progress.failed} tiles missing · retries later`, no_space: "Storage full" })[progress.state]
return ({
queued: "Queued", downloading: `Downloading · ${percent}%`, waiting_wifi: `Waiting for Wi-Fi · ${percent}%`,
complete: "Saved for offline", incomplete: `${progress.failed} tiles missing · retries later`, no_space: "Storage full"
})[progress.state]
}
export class OfflineRoadsClient {
constructor({ publish, unauthorized = () => {}, fetcher = (...args) => fetch(...args),
later = (fn, ms) => setTimeout(fn, ms), cancel = (id) => clearTimeout(id) }) {
constructor({ publish, unauthorized = () => { }, fetcher = (...args) => fetch(...args),
later = (fn, ms) => setTimeout(fn, ms), cancel = (id) => clearTimeout(id) }) {
Object.assign(this, { publish, unauthorized, fetcher, later, cancel })
this.data = null
this.busy = false
@@ -76,9 +78,11 @@ export class OfflineRoadsClient {
const generation = ++this.generation, controller = this.controller = new AbortController()
const deadline = this.later(() => controller.abort(), 10000)
try {
const response = await this.fetcher("./api/navigation/offline", { credentials: "same-origin", cache: "no-store",
const response = await this.fetcher("./api/navigation/offline", {
credentials: "same-origin", cache: "no-store",
signal: controller.signal,
...(body === null ? {} : { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }) })
...(body === null ? {} : { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })
})
const payload = await response.json().catch(() => null)
if (!this.active || generation !== this.generation) return null
if (controller.signal.aborted) throw new Error("Offline maps did not respond. Try again shortly.")
@@ -120,8 +124,10 @@ export class OfflineRoadsClient {
export const OfflineRoadMapsPanel = {
name: "OfflineRoadMapsPanel",
components: { GxNotice, BluetoothNotice, GalaxySettingRow },
props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true },
hasKey: { type: Boolean, default: false }, metric: { type: Boolean, default: true } },
props: {
mode: { type: String, required: true }, unauthorized: { type: Function, required: true },
hasKey: { type: Boolean, default: false }, metric: { type: Boolean, default: true }
},
data: () => ({ bluetooth: bluetoothConnection(), data: null, busy: false, error: "", point: null, name: "", radius: null, confirmDelete: null, notice: "" }),
created() { this.client = new OfflineRoadsClient({ publish: (update) => Object.assign(this.$data, update), unauthorized: this.unauthorized }) },
mounted() {
@@ -179,7 +185,7 @@ export const OfflineRoadMapsPanel = {
formatBytes, areaLabel, radiusLabel, switchRow,
ensureMap() {
if (this.bluetooth || this.map || !this.hasKey || !this.$refs.canvas) return
this.map = markRaw(new RasterMap(this.$refs.canvas, () => {}))
this.map = markRaw(new RasterMap(this.$refs.canvas, () => { }))
this.map.onTap = (point) => this.pick({ ...point, name: "" })
this.map.update({}, false)
if (this.data?.position) { this.map.center = this.data.position; this.map.zoom = START_ZOOM; this.map.initialized = true }
@@ -204,8 +210,10 @@ export const OfflineRoadMapsPanel = {
},
drawOverlays() {
if (!this.map) return
const saved = (this.data?.areas || []).map((area) => ({ ...area, stroke: area.progress?.state === "complete" ? "#34c778" : "#9d72ff",
fill: area.progress?.state === "complete" ? "#34c77822" : "#9d72ff1f" }))
const saved = (this.data?.areas || []).map((area) => ({
...area, stroke: area.progress?.state === "complete" ? "#34c778" : "#9d72ff",
fill: area.progress?.state === "complete" ? "#34c77822" : "#9d72ff1f"
}))
const draft = this.point ? [{ ...this.point, radiusKm: this.radiusKm, stroke: "#f5b642", fill: "#f5b64226", dash: [8, 6], width: 3 }] : []
const overlays = [...saved, ...draft], signature = JSON.stringify(overlays)
if (signature === this.overlaySignature) return // polls usually change nothing on the map
@@ -226,12 +234,20 @@ export const OfflineRoadMapsPanel = {
},
template: `
<section class="gx-card gx-offline-roads" aria-label="Offline road maps" :inert="busy" :aria-busy="busy || undefined">
<div class="gx-section__header"><i class="bi bi-signpost-split"></i><span class="gx-section__title">Map Overlay Roads</span></div>
<p class="gx-note">Road lines for the Android Auto map overlay. Saved areas stay on your comma, so the overlay keeps drawing roads with no signal. Downloads happen on Wi-Fi.</p>
<div class="gx-offline-roads__head">
<span class="gx-starport-step__num" aria-hidden="true"><i class="bi bi-cloud-download"></i></span>
<div>
<div class="gx-navigation__step-title">
<h3 class="gx-section__title">Offline Map Management</h3>
<span class="gx-starport-pill gx-starport-pill--danger">Mapbox only</span>
</div>
<p class="gx-note">Saves Mapbox road lines on your comma so the map overlay keeps drawing roads with no cell signal. Google Maps tiles require internet and can't be saved offline, so these road lines always back them up. Downloads happen on Wi-Fi.</p>
</div>
</div>
<p v-if="mode !== 'local'" class="gx-note">Connect to your comma to manage offline road maps.</p>
<template v-else>
<GxNotice tone="danger" v-if="error">{{ error }}</GxNotice>
<GxNotice tone="warn" v-if="!hasKey">Add your Mapbox key in Setup. Road maps download with the same key.</GxNotice>
<GxNotice tone="warn" v-if="!hasKey">Add your Mapbox key in Setup. Offline road maps download with that key.</GxNotice>
<GxNotice tone="warn" v-else-if="service.failure === 'key'">Mapbox rejected the saved key for map tiles. Check that it is a public (pk.) key without URL restrictions.</GxNotice>
<GxNotice tone="warn" v-if="service.failure === 'budget'">This comma's Mapbox road tile allowance is used up, so downloads pause until the 1st.</GxNotice>
<GxNotice tone="warn" v-if="service.noSpace">The comma's storage is nearly full, so new map areas are paused. Delete an area or free space.</GxNotice>
@@ -247,9 +263,10 @@ export const OfflineRoadMapsPanel = {
:index="0" :busy="busy" :disabled="!data" :save-value="(index, value) => setSaveDriven(value === 'On')" />
<div class="gx-offline-roads__picker">
<BluetoothNotice v-if="bluetooth" feature="Offline area map preview">Saved map settings remain available.</BluetoothNotice>
<div v-else-if="hasKey" class="gx-offline-roads__map"><canvas ref="canvas" tabindex="0" aria-label="Map. Tap or press Enter to center a new offline area; drag or use arrow keys to pan."></canvas>
<div class="gx-navigation-map__controls"><button class="gx-btn" type="button" @click="zoom(1)" aria-label="Zoom in">+</button>
<button class="gx-btn" type="button" @click="zoom(-1)" aria-label="Zoom out">−</button></div>
<div v-else-if="hasKey" class="gx-offline-roads__map"><canvas ref="canvas" tabindex="0" aria-label="Mapbox map. Tap or press Enter to center a new offline area; drag or use arrow keys to pan."></canvas>
<span class="gx-offline-roads__provider">Mapbox preview</span>
<div class="gx-navigation-map__controls"><button class="gx-navigation-map__control" type="button" @click="zoom(1)" aria-label="Zoom in"><i class="bi bi-plus-lg" aria-hidden="true"></i></button>
<button class="gx-navigation-map__control" type="button" @click="zoom(-1)" aria-label="Zoom out"><i class="bi bi-dash-lg" aria-hidden="true"></i></button></div>
<span class="gx-offline-roads__hint">{{ point ? 'Adjust the radius, name it, then save.' : 'Tap the map to center a new area.' }}</span></div>
<div class="gx-offline-roads__form">
<button type="button" class="gx-btn gx-btn--tonal" :disabled="!data?.position" @click="useLocation"><i class="bi bi-crosshair"></i> Around my car</button>
@@ -149,9 +149,23 @@ export class OnroadLayoutFeed {
}
}
// Which map and route provider the comma uses, so the navigation previews match what it draws.
export const navLook = reactive({ map: "mapbox", routes: "mapbox" })
export async function loadNavLook(fetcher = (...args) => fetch(...args)) {
try {
const response = await fetcher("./api/navigation/status", { credentials: "same-origin", cache: "no-store" })
const data = response.ok ? await response.json() : null
navLook.map = data?.mapProvider === "google" && data.hasGoogleKey ? "google" : "mapbox"
navLook.routes = data?.routeProvider === "google" && data.hasGoogleKey ? "google" : "mapbox"
} catch { /* The Mapbox look stays when navigation is unreachable. */ }
}
export const LayoutWidgetPreview = {
props: ["widget", "palette", "profile", "scene", "clock24Hour", "native", "art"],
computed: {
nav() { return navLook },
googleMap() { return navLook.map === "google" },
googleRoutes() { return navLook.routes === "google" },
roadNameSize() { return Math.max(18, Math.min(this.widget.width, this.widget.height) * .075) },
},
methods: {
@@ -280,8 +294,9 @@ export const LayoutWidgetPreview = {
</g>
<g v-else-if="widget.kind === 'nav_card'">
<rect x="1" y="1" :width="widget.width - 2" :height="widget.height - 2" rx="39" fill="#0f0d17f5" stroke="#a07edcbe" stroke-width="2" />
<text x="24" y="66" font-size="54" font-weight="700" fill="white">500 ft</text>
<text x="24" y="100" font-size="30" font-weight="600" fill="#ded6f4">Turn right onto Las Vegas Blvd</text>
<text v-if="!googleRoutes" x="24" y="66" font-size="54" font-weight="700" fill="white">500 ft</text>
<text v-if="!googleRoutes" x="24" y="100" font-size="30" font-weight="600" fill="#ded6f4">Turn right onto Las Vegas Blvd</text>
<template v-if="!googleRoutes">
<g v-for="(lane, i) in [['S', 0], ['S', 0], ['S', 0], ['R', 1], ['R', 1]]" :key="i" :transform="'translate(' + ((widget.width - 320) / 2 + i * 66) + ' 116)'">
<rect width="56" height="44" rx="13" :fill="lane[1] ? '#4e3e80' : '#222030'" />
<g transform="translate(28 22)" fill="none" :stroke="lane[1] ? '#ffffff' : '#70688a'" stroke-width="4.5" stroke-linecap="round" stroke-linejoin="round">
@@ -289,6 +304,13 @@ export const LayoutWidgetPreview = {
<path v-else d="M-8 13 V0 Q-8 -7 -1 -7 H10 M4 -13 L10 -7 L4 -1" />
</g>
</g>
</template>
<template v-else>
<g transform="translate(24 28)" fill="none" stroke="white" stroke-width="9" stroke-linecap="round" stroke-linejoin="round"><path d="M12 56 V28 Q12 18 22 18 H48 M34 4 L48 18 L34 32" /></g>
<text x="104" y="66" font-size="54" font-weight="700" fill="white">500 ft</text>
<text x="104" y="100" font-size="30" font-weight="600" fill="#ded6f4">Las Vegas Blvd</text>
<text :x="widget.width - 24" y="150" text-anchor="end" font-size="27" font-weight="500" fill="#d6d2e2">2.4 mi | 6 min</text>
</template>
<rect x="24" y="171" :width="widget.width - 48 - 190" height="6" rx="3" fill="#a07edc3c" />
<rect x="24" y="171" :width="(widget.width - 48 - 190) * .35" height="6" rx="3" fill="#b296ff" />
<text :x="widget.width - 24" y="182" text-anchor="end" font-size="22" font-weight="600" fill="#ebe1ff">ETA 3:51 PM</text>
@@ -300,6 +322,15 @@ export const LayoutWidgetPreview = {
</defs>
<g mask="url(#gx-nav-map-mask)" :transform="'scale(' + widget.width / 600 + ' ' + widget.height / 450 + ')'" fill="none" stroke-linecap="round" stroke-linejoin="round">
<g :opacity="(widget.opacity ?? 50) / 100">
<template v-if="googleMap">
<rect width="600" height="450" fill="#e8eaed" />
<path d="M440 -20 L640 -20 L640 200 Q540 170 440 -20 Z" fill="#aadaff" />
<path d="M-20 120 Q200 150 640 90 M90 -20 L130 480 M430 -20 Q400 200 470 480 M-20 330 L640 360 M260 -20 L250 480" stroke="#ffffff" stroke-width="12" vector-effect="non-scaling-stroke" />
<path d="M-20 120 Q200 150 640 90" stroke="#34a853" stroke-width="5" vector-effect="non-scaling-stroke" />
<path d="M-20 330 L640 360" stroke="#ea4335" stroke-width="5" vector-effect="non-scaling-stroke" />
<path d="M260 -20 L250 480" stroke="#fbbc04" stroke-width="5" vector-effect="non-scaling-stroke" />
</template>
<template v-else>
<rect width="600" height="450" fill="#0b0f16" opacity=".45" />
<g stroke="#000000a8" vector-effect="non-scaling-stroke">
<path d="M-20 120 Q200 150 640 90 M90 -20 L130 480 M430 -20 Q400 200 470 480 M-20 330 L640 360 M260 -20 L250 480" stroke-width="11" vector-effect="non-scaling-stroke" />
@@ -307,6 +338,7 @@ export const LayoutWidgetPreview = {
<path d="M-20 120 Q200 150 640 90 M-20 330 L640 360" stroke="#ebf0f5" stroke-width="6" vector-effect="non-scaling-stroke" />
<path d="M90 -20 L130 480 M430 -20 Q400 200 470 480" stroke="#bec8d2" stroke-width="4" vector-effect="non-scaling-stroke" />
<path d="M260 -20 L250 480" stroke="#ffc45c" stroke-width="8" vector-effect="non-scaling-stroke" />
</template>
</g>
<path d="M300 330 Q258 300 254 250 L262 -20" stroke="#8f6bff55" stroke-width="20" vector-effect="non-scaling-stroke" />
<path d="M300 330 Q258 300 254 250 L262 -20" stroke="#a98bff" stroke-width="9" vector-effect="non-scaling-stroke" />
@@ -318,6 +350,7 @@ export const LayoutWidgetPreview = {
<rect :x="-roadNameSize * 4.4" y="0" :width="roadNameSize * 8.8" :height="roadNameSize * 1.55" :rx="roadNameSize * .78" fill="#080c14be" />
<text x="0" :y="roadNameSize * 1.12" text-anchor="middle" :font-size="roadNameSize" fill="#eceef6">Desert Inn Road</text>
</g>
<text v-if="googleMap" x="16" :y="widget.height - 12" :font-size="Math.max(14, Math.min(widget.width, widget.height) * .04)" font-weight="600" fill="#f0f2fa">Google Maps</text>
</g>
<template v-else>
<rect :width="widget.width" :height="widget.height" :fill="palette.cardFill" :stroke="palette.cardBorder" />
@@ -566,7 +599,7 @@ export const OnroadLayoutPage = {
stockConfidence() { return this.displayValue("StockConfidenceBallWidget") === "Off" },
},
mounted() {
if (this.mode === "local") this.feed.start()
if (this.mode === "local") { this.feed.start(); loadNavLook() }
this._stopUnloadGuard = guardUnload(() => this.dirty || this.state.status === "saving")
// Double-tap zoom stays off across the whole page, app bar included, while a maker page is open.
if (makerPagesOpen++ === 0) document.documentElement.classList.add("gx-maker-open")
@@ -0,0 +1,141 @@
"""Place lookups with Places API (New) on the user's own Google key: Text Search, Autocomplete and Place Details."""
from __future__ import annotations
import json
import math
from pathlib import Path
from urllib.parse import quote
import requests
from openpilot.starpilot.navigation.google_tiles import FAILURE_BUDGET, FAILURE_NETWORK, FAILURE_SERVER, GoogleBudget, _body, classify
SEARCH_URL = "https://places.googleapis.com/v1/places:searchText"
AUTOCOMPLETE_URL = "https://places.googleapis.com/v1/places:autocomplete"
DETAILS_URL = "https://places.googleapis.com/v1/places/"
FIELD_MASK = "places.displayName,places.formattedAddress,places.location"
DETAILS_MASK = "location,formattedAddress" # Place Details Essentials; displayName would bill as Pro
FREE_SEARCHES = 5_000 # Text Search Pro: the SKU for name, address and location
# Autocomplete Requests. A session ends in at most one Place Details Essentials (also 10,000 free), so this cap covers both.
FREE_SUGGESTIONS = 10_000
BIAS_RADIUS_M = 50_000.0
TIMEOUT = (3.0, 8.0)
MAX_RESPONSE = 256 * 1024
MESSAGES = {
"key": "Google rejected the key for Places API (New). Check that it was copied whole and that its API restrictions allow Places API (New).",
"billing": "Billing is not turned on for this Google Cloud project. Add a billing account, then test again.",
"disabled": "Places API (New) is off for this key. Enable it in Google Cloud and allow it in the key's API restrictions, then test again.",
FAILURE_SERVER: "Google could not look up this place just now.",
FAILURE_NETWORK: "The comma could not reach Google.",
FAILURE_BUDGET: "This month's free Google place lookups are used up.",
}
class GooglePlacesFailed(Exception):
def __init__(self, failure: str):
super().__init__(failure)
self.failure = failure
def places_budget(root: Path | None = None) -> GoogleBudget:
return GoogleBudget(root, file="places-usage.json", month_free=FREE_SEARCHES, day_free=None)
def suggestions_budget(root: Path | None = None) -> GoogleBudget:
return GoogleBudget(root, file="places-autocomplete-usage.json", month_free=FREE_SUGGESTIONS, day_free=None)
def _bias(proximity: tuple[float, float] | None) -> dict:
if proximity is None:
return {}
return {"locationBias": {"circle": {"center": {"latitude": proximity[1], "longitude": proximity[0]}, "radius": BIAS_RADIUS_M}}}
def _request(send, budget: GoogleBudget | None) -> dict:
if budget is not None and not budget.spend():
raise GooglePlacesFailed(FAILURE_BUDGET)
try:
with send() as response:
status, raw = response.status_code, _body(response, MAX_RESPONSE)
except requests.RequestException:
raise GooglePlacesFailed(FAILURE_NETWORK) from None
except ValueError:
raise GooglePlacesFailed(FAILURE_SERVER) from None
failure = classify(status, raw)
if failure is not None:
raise GooglePlacesFailed(failure)
try:
value = json.loads(raw)
except ValueError:
raise GooglePlacesFailed(FAILURE_SERVER) from None
if not isinstance(value, dict):
raise GooglePlacesFailed(FAILURE_SERVER)
return value
def _location(row: dict) -> tuple[float, float]:
latitude, longitude = float(row["location"]["latitude"]), float(row["location"]["longitude"])
if not math.isfinite(latitude) or not math.isfinite(longitude):
raise ValueError
return latitude, longitude
def text_search(http, key: str, query: str, budget: GoogleBudget, proximity: tuple[float, float] | None = None, timeout=TIMEOUT,
limit: int = 1) -> list[dict]:
"""Google's places for the text as [{name, address, latitude, longitude}], best first."""
body = {"textQuery": query, "pageSize": limit, **_bias(proximity)}
value = _request(lambda: http.post(SEARCH_URL, json=body, headers={"X-Goog-Api-Key": key, "X-Goog-FieldMask": FIELD_MASK},
timeout=timeout, stream=True), budget)
try:
places = []
for row in value.get("places", [])[:limit]:
latitude, longitude = _location(row)
places.append({"name": str(row.get("displayName", {}).get("text") or row.get("formattedAddress") or query),
"address": row.get("formattedAddress"), "latitude": latitude, "longitude": longitude})
return places
except (ValueError, TypeError, KeyError, AttributeError):
raise GooglePlacesFailed(FAILURE_SERVER) from None
def autocomplete(http, key: str, query: str, session: str, budget: GoogleBudget, proximity: tuple[float, float] | None = None,
timeout=TIMEOUT) -> list[dict]:
"""Typing suggestions as [{id, name, description}]; the session token bills them with the Place Details that ends it."""
body = {"input": query, "sessionToken": session, **_bias(proximity)}
value = _request(lambda: http.post(AUTOCOMPLETE_URL, json=body, headers={"X-Goog-Api-Key": key}, timeout=timeout, stream=True), budget)
suggestions = value.get("suggestions")
rows = []
for item in suggestions if isinstance(suggestions, list) else []:
try:
prediction = item["placePrediction"]
identity = prediction["placeId"]
structured = prediction.get("structuredFormat") or {}
name = (structured.get("mainText") or {}).get("text") or prediction["text"]["text"]
description = (structured.get("secondaryText") or {}).get("text") or ""
except (TypeError, KeyError, AttributeError):
continue
if (isinstance(identity, str) and 1 <= len(identity) <= 256 and isinstance(name, str) and 1 <= len(name.strip()) <= 256 and
isinstance(description, str)):
rows.append({"id": identity, "name": name.strip(), "description": description.strip()[:512]})
return rows[:8]
def place_details(http, key: str, identity: str, session: str, timeout=TIMEOUT) -> dict:
"""Coordinates and address of a suggested place; ends its autocomplete session."""
value = _request(lambda: http.get(DETAILS_URL + quote(identity, safe=""), params={"sessionToken": session},
headers={"X-Goog-Api-Key": key, "X-Goog-FieldMask": DETAILS_MASK}, timeout=timeout, stream=True), None)
try:
latitude, longitude = _location(value)
except (ValueError, TypeError, KeyError):
raise GooglePlacesFailed(FAILURE_SERVER) from None
return {"address": value.get("formattedAddress"), "latitude": latitude, "longitude": longitude}
def test_places(key: str, http=requests, budget: GoogleBudget | None = None) -> dict:
"""One place lookup, the same request a search uses."""
try:
text_search(http, key, "Googleplex, 1600 Amphitheatre Pkwy, Mountain View, CA", budget or places_budget())
except GooglePlacesFailed as error:
return {"ok": False, "failure": error.failure, "message": MESSAGES.get(error.failure, MESSAGES[FAILURE_SERVER])}
return {"ok": True, "failure": None, "message": "Google place search works with this key."}
@@ -44,9 +44,9 @@ MANEUVERS = {
MESSAGES = {
"key": "Google rejected the key for routing. Check that its restrictions allow the Routes API.",
"key": "Google rejected the key for the Routes API. Check that it was copied whole and that its API restrictions allow the Routes API.",
"billing": "Billing is not turned on for this Google Cloud project. Add a billing account, then test again.",
"disabled": "The Routes API is not enabled for this key's project. Enable it in Google Cloud, then test again.",
"disabled": "The Routes API is off for this key. Enable it in Google Cloud and allow it in the key's API restrictions, then test again.",
FAILURE_SERVER: "Google could not find a route just now, so Mapbox routed this trip.",
FAILURE_NETWORK: "The comma could not reach Google, so Mapbox routed this trip.",
FAILURE_BUDGET: "This month's free Google routes are used up. Mapbox routes until they reset.",
@@ -244,7 +244,7 @@ def test_routes(key: str, http=requests, budget: GoogleBudget | None = None) ->
"""One short free (Essentials) route, the same request a trip starts with."""
budget = budget or essentials_budget(google_root())
if not budget.spend():
return {"ok": False, "message": MESSAGES[FAILURE_BUDGET]}
return {"ok": False, "failure": FAILURE_BUDGET, "message": MESSAGES[FAILURE_BUDGET]}
body = request_body((-122.0840, 37.4220), {"latitude": 37.4275, "longitude": -122.1697}, None, (), alternatives=False)
try:
compute_routes(http, key, body, TEST_TIMEOUT)
@@ -252,5 +252,5 @@ def test_routes(key: str, http=requests, budget: GoogleBudget | None = None) ->
message = MESSAGES.get(error.failure, MESSAGES[FAILURE_SERVER])
if error.failure in (FAILURE_SERVER, FAILURE_NETWORK):
message = message.split(", so")[0] + "."
return {"ok": False, "message": message}
return {"ok": True, "message": "Google routing works with this key."}
return {"ok": False, "failure": error.failure, "message": message}
return {"ok": True, "failure": None, "message": "Google routing works with this key."}
+58 -9
View File
@@ -72,13 +72,16 @@ def _wall() -> float:
return time.time() # noqa: TID251 - expiry and calendar days are wall-clock
def session_body(language: str = "en-US", region: str = "US") -> dict:
return {"mapType": "roadmap", "language": language, "region": region, "imageFormat": "png", "layerTypes": ["layerTraffic"],
"styles": DARK_STYLE}
def session_body(language: str = "en-US", region: str = "US", theme: str = "dark") -> dict:
body = {"mapType": "roadmap", "language": language, "region": region, "imageFormat": "png", "layerTypes": ["layerTraffic"]}
if theme != "light":
body["styles"] = DARK_STYLE
return body
def key_digest(api_key: str) -> str:
return hashlib.sha256(f"{api_key}\n{STYLE_VERSION}".encode()).hexdigest()[:24]
def key_digest(api_key: str, theme: str = "dark") -> str:
suffix = "\nlight" if theme == "light" else ""
return hashlib.sha256(f"{api_key}\n{STYLE_VERSION}{suffix}".encode()).hexdigest()[:24]
# ---------------------------------------------------------------- planning
@@ -297,9 +300,9 @@ def classify(status: int, body: bytes) -> str | None:
MESSAGES = {
FAILURE_KEY: "Google rejected the key. Check that it was copied whole and that its restrictions allow the Map Tiles API.",
FAILURE_KEY: "Google rejected the key for the Map Tiles API. Check that it was copied whole and that its API restrictions allow the Map Tiles API.",
FAILURE_BILLING: "Billing is not turned on for this Google Cloud project. Add a billing account, then test again.",
FAILURE_DISABLED: "The Map Tiles API is not enabled for this key's project. Enable it in Google Cloud, then test again.",
FAILURE_DISABLED: "The Map Tiles API is off for this key. Enable it in Google Cloud and allow it in the key's API restrictions, then test again.",
FAILURE_SERVER: "Google is busy or refused the request. Try again in a minute.",
FAILURE_NETWORK: "The comma could not reach Google. Check its internet connection.",
FAILURE_BUDGET: "This month's or today's free Google tiles are used up. The map uses Mapbox road lines until they reset.",
@@ -307,8 +310,8 @@ MESSAGES = {
}
def _post_session(http, api_key: str, timeout=REQUEST_TIMEOUT) -> tuple[int, bytes]:
with http.post(SESSION_URL, json=session_body(), headers={"X-Goog-Api-Key": api_key}, timeout=timeout, stream=True) as response:
def _post_session(http, api_key: str, timeout=REQUEST_TIMEOUT, theme: str = "dark") -> tuple[int, bytes]:
with http.post(SESSION_URL, json=session_body(theme=theme), headers={"X-Goog-Api-Key": api_key}, timeout=timeout, stream=True) as response:
return response.status_code, _body(response, 64 * 1024)
@@ -368,6 +371,52 @@ def viewport_copyright(http, api_key: str, session: str, position: tuple[float,
return " ".join(text.split())[:160] if isinstance(text, str) else ""
def fetch_tile(api_key: str, z: int, x: int, y: int, theme: str = "dark", *, http=requests, root: Path | None = None,
wall: Callable[[], float] = _wall) -> bytes:
"""One 2D Google map tile for Galaxy's preview map, sharing the disk store and free-allowance budget."""
root = Path(root) if root is not None else google_root()
store = GoogleTileStore(root)
budget = GoogleBudget(root, wall)
digest = key_digest(api_key, theme)
key = TileKey(z, x, y)
now = wall()
cached = store.read(digest, key, now)
if cached is not None:
return cached
session_file = root / ("session.json" if theme != "light" else "session-light.json")
saved = read_json(session_file, 4096)
session = None
if isinstance(saved, dict) and saved.get("digest") == digest:
try:
if float(saved["expiry"]) - now > SESSION_RENEW_S and isinstance(saved["session"], str):
session = saved["session"]
except (KeyError, TypeError, ValueError):
pass
if session is None:
status, body = _post_session(http, api_key, REQUEST_TIMEOUT, theme=theme)
failure = classify(status, body)
if failure is not None:
raise ValueError(MESSAGES[failure])
parsed = dict(parse_session(body, now), digest=digest)
root.mkdir(parents=True, exist_ok=True)
_write_atomic(session_file, parsed, 0o600)
session = parsed["session"]
if not budget.spend():
raise ValueError(MESSAGES[FAILURE_BUDGET])
with http.get(TILE_URL.format(z=z, x=x, y=y), params={"session": session}, headers={"X-Goog-Api-Key": api_key},
timeout=REQUEST_TIMEOUT, stream=True) as response:
status, body, lifetime = response.status_code, _body(response, MAX_TILE_BYTES), cache_lifetime(response.headers)
failure = classify(status, body)
if failure is not None:
if failure in (FAILURE_KEY, FAILURE_BILLING, FAILURE_DISABLED):
session_file.unlink(missing_ok=True)
raise ValueError(MESSAGES[failure])
if not body or not body.startswith(b"\x89PNG\r\n\x1a\n"):
raise ValueError(MESSAGES[FAILURE_SERVER])
store.write(digest, key, body, lifetime, now)
return body
# ---------------------------------------------------------------- navtilesd's side
class GoogleTiles:
+202 -41
View File
@@ -34,8 +34,8 @@ MAX_SEARCHES = 32
TILE_CACHE_TTL = 15 * 60
TILE_CACHE_ENTRIES = 256
TILE_CACHE_BYTES = 32 * 1024 * 1024
TILE_SLOTS = 6
TILE_SLOT_WAIT_S = 3.0 # a panned-away request still holds its slot until Mapbox answers; wait instead of failing
TILE_SLOTS = 16
TILE_SLOT_WAIT_S = 5.0 # a panned-away request still holds its slot until Mapbox answers; wait instead of failing
AUTOCOMPLETE_TYPES = {'poi', 'address', 'street', 'place', 'neighborhood', 'locality'}
SUGGESTS_PER_SESSION = 50 # Mapbox starts a new billable session after this many suggestions
MAX_FAVORITES = 100
@@ -65,10 +65,24 @@ class ValidationError(ValueError):
pass
class ShareQueryError(ValidationError):
"""A shared place the driver has to pick from search results."""
def __init__(self, message: str, query: str):
super().__init__(message)
self.query = query
class ConflictError(ValueError):
pass
class PlaceResults(list):
"""Search results that name the provider that found them."""
def __init__(self, rows, provider: str):
super().__init__(rows)
self.provider = provider
def destination(value: dict) -> dict:
if not isinstance(value, dict):
raise ValidationError('Choose a destination')
@@ -128,13 +142,22 @@ def response_json(session, url: str, params: dict) -> dict:
raise ValidationError('The map service could not complete this request') from None
def _pooled_session() -> requests.Session:
session = requests.Session()
adapter = requests.adapters.HTTPAdapter(pool_connections=8, pool_maxsize=24)
session.mount('https://', adapter)
session.mount('http://', adapter)
return session
class NavigationOwner:
def __init__(self, root: Path | None = None, runtime_source=None, session=requests, transient_root: Path | None = None):
def __init__(self, root: Path | None = None, runtime_source=None, session=None, transient_root: Path | None = None):
self.root = Path(root) if root is not None else starpilot_storage_root() / 'navigation'
self.path = self.root / 'settings.json'
self.position_store = LastPositionStore(self.root)
self.google_root = self.root / 'google-tiles'
self.runtime_source, self.session = runtime_source, session
self.runtime_source = runtime_source
self.session = _pooled_session() if session is None or session is requests else session
self._tile_slots = threading.BoundedSemaphore(TILE_SLOTS)
from openpilot.starpilot.navigation.mapbox_budget import MonthlyBudget
self.search_budget = MonthlyBudget('searchSessions', self.root / 'mapbox-usage')
@@ -362,13 +385,18 @@ class NavigationOwner:
result['mapProvider'] = document['mapProvider']
result['hasGoogleKey'] = bool(document['googleKey'])
from openpilot.starpilot.navigation.google_tiles import MESSAGES, GoogleBudget, read_status
failure = read_status(self.google_root).get('failure') if document['mapProvider'] == 'google' else None
result['googleMap'] = {'usage': GoogleBudget(self.google_root).snapshot(), 'failure': MESSAGES.get(failure)}
google_status = read_status(self.google_root)
failure = google_status.get('failure') if document['mapProvider'] == 'google' else None
copyright_text = google_status.get('copyright')
result['googleMap'] = {'usage': GoogleBudget(self.google_root).snapshot(), 'failure': MESSAGES.get(failure),
**({'copyright': copyright_text} if isinstance(copyright_text, str) and copyright_text else {})}
from openpilot.starpilot.navigation.google_routes import essentials_budget, read_route_failure, route_budget
result['routeProvider'] = document['routeProvider']
google_routing = document['routeProvider'] == 'google' and bool(document['googleKey'])
result['googleRoutes'] = {'usage': route_budget(self.google_root).snapshot(), 'essentials': essentials_budget(self.google_root).snapshot(),
'failure': read_route_failure(self.google_root) if google_routing else None}
from openpilot.starpilot.navigation.google_places import places_budget, suggestions_budget
result['googlePlaces'] = {'usage': places_budget(self.google_root).snapshot(), 'suggestions': suggestions_budget(self.google_root).snapshot()}
result['alternatives'] = [dict(row, geometry=rounded(row['geometry'])) for row in self.route_options(document['revision'])]
result['selectedRoute'] = document.get('routeChoice', 0)
result.update(hasKey=bool(document['token']), status=status, instruction=None, route=[], isMetric=self._is_metric(), location=None,
@@ -444,14 +472,32 @@ class NavigationOwner:
(self.transient_root / 'routes.cache').write_text(json.dumps(value, allow_nan=False))
return self.snapshot()
def map_tile(self, z: int, x: int, y: int, theme: str = 'light') -> bytes:
if theme not in MAP_STYLES:
def map_tile(self, z: int, x: int, y: int, theme: str = 'light', *, provider: str = 'mapbox') -> bytes:
if theme not in MAP_STYLES or provider not in ('mapbox', 'google'):
raise ValidationError('Invalid map theme')
if any(type(v) is not int for v in (z, x, y)) or not 0 <= z <= 18 or not 0 <= x < 2 ** z or not 0 <= y < 2 ** z:
raise ValidationError('Invalid map tile')
token = self.read()['token']
settings = self.read()
token = settings['token']
if not token:
raise ValidationError('Save a Mapbox key to view the map')
google_key = settings.get('googleKey', '') if provider == 'google' and settings.get('mapProvider') == 'google' else ''
if google_key:
if not self._tile_slots.acquire(timeout=TILE_SLOT_WAIT_S):
raise ValidationError('Map is busy; try again')
try:
from openpilot.starpilot.navigation.google_tiles import fetch_tile
tile = fetch_tile(google_key, z, x, y, theme, http=self.session, root=self.google_root)
current = self.read()
if current.get('googleKey', '') != google_key or current.get('mapProvider') != 'google':
raise ValidationError('Map key changed; try again')
return tile
except ValidationError:
raise
except (requests.RequestException, ValueError, OSError):
pass
finally:
self._tile_slots.release()
key = hashlib.sha256(token.encode()).digest()
coordinates = (theme, z, x, y)
with self._tile_lock:
@@ -469,13 +515,13 @@ class NavigationOwner:
try:
started = time.monotonic()
with self.session.get(f'https://api.mapbox.com/styles/v1/{MAP_STYLES[theme]}/tiles/512/{z}/{x}/{y}.png',
params={'access_token': token}, timeout=(2, 2), stream=True, allow_redirects=False) as response:
params={'access_token': token}, timeout=(3.05, 5.0), stream=True, allow_redirects=False) as response:
if response.status_code != 200 or response.headers.get('Content-Type', '').split(';')[0] != 'image/png':
raise ValidationError('Map tiles are unavailable')
raw = bytearray()
for chunk in response.iter_content(64 * 1024):
raw.extend(chunk)
if len(raw) > 2 * 1024 * 1024 or time.monotonic() - started > 5:
if len(raw) > 2 * 1024 * 1024 or time.monotonic() - started > 7:
raise ValidationError('Map tile exceeded the request limit')
if bytes(raw[:8]) != b'\x89PNG\r\n\x1a\n' or bytes(raw[12:16]) != b'IHDR' or bytes(raw[16:24]) != b'\x00\x00\x02\x00' * 2:
raise ValidationError('Invalid map tile response')
@@ -545,19 +591,18 @@ class NavigationOwner:
return result
def test_google_key(self, key=None) -> dict:
"""Tries the typed key, or the saved one, the same way the map will use it."""
settings = self.read()
key = settings['googleKey'] if key is None else key
"""Tries the typed key, or the saved one, on all three Google APIs: one tile, one route and one place lookup."""
key = self.read()['googleKey'] if key is None else key
if not isinstance(key, str) or not key or not valid_google_key(key):
raise ValidationError('Enter a valid Google Maps API key')
from concurrent.futures import ThreadPoolExecutor
from openpilot.starpilot.navigation.google_tiles import GoogleBudget, test_key
from openpilot.starpilot.navigation.google_routes import essentials_budget, test_routes
if settings['routeProvider'] != 'google':
return test_key(key, self.session, GoogleBudget(self.google_root))
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as pool:
from openpilot.starpilot.navigation.google_places import places_budget, test_places
with ThreadPoolExecutor(max_workers=3) as pool:
routes = pool.submit(test_routes, key, self.session, essentials_budget(self.google_root))
return dict(test_key(key, self.session, GoogleBudget(self.google_root)), routes=routes.result())
places = pool.submit(test_places, key, self.session, places_budget(self.google_root))
return dict(test_key(key, self.session, GoogleBudget(self.google_root)), routes=routes.result(), places=places.result())
def resolve_share(self, text) -> str:
"""A shared Google Maps short link followed to the full link, which carries the place's coordinates."""
@@ -582,6 +627,74 @@ class NavigationOwner:
current = following
return text.replace(match.group(0), current) if current != match.group(0) else text
def share(self, text, expected_revision: str, authorized) -> dict:
"""A place shared from a phone: turns navigation on and starts the route."""
if not isinstance(text, str) or not text.strip() or len(text) > 8192:
raise ValidationError('The shared text could not be read')
current = self.read()
if not current['token']:
raise ValidationError('Add your Mapbox access token first')
if not isinstance(expected_revision, str) or current['revision'] != expected_revision:
raise ConflictError('Navigation changed; refresh and try again')
if not (authorized() if callable(authorized) else authorized is True):
raise PermissionError('Navigation changes are not available right now')
from openpilot.starpilot.navigation.share import map_link_query, search_text, shared_coordinates
text = self.resolve_share(text)
shared = shared_coordinates(text)
if shared is None:
query = map_link_query(text)
if query is None:
query = search_text(text)
if not query:
raise ValidationError('This map link could not be opened')
raise ShareQueryError(f'Open StarPilot to search for {query}', query)
shared = self._geocode_share(query)
selected = destination(shared)
def update(doc):
self._reject_temporary_promotion(doc, selected)
doc['enabled'] = True
self._navigate(doc, selected)
result = self._change(update, expected_revision, authorized)
return dict(result, shared={key: selected[key] for key in ('name', 'latitude', 'longitude')})
def _geocode_share(self, query: str) -> dict:
from openpilot.starpilot.navigation.share import place
name, _, rest = query.partition(',')
found = self._google_text_search(self.read(), query, 1)
if found == []:
raise ShareQueryError(f'No map location found for {name.strip() or query}', query[:200])
if found:
top = found[0]
return place(top['name'], top['latitude'], top['longitude'], top['address'] or top['name'])
# Geocoding finds addresses, not names: "Name, 123 Main St, City" tries the street address first.
attempts = ([rest.strip()] if any(ch.isdigit() for ch in rest.split(',')[0]) else []) + [query]
for attempt in attempts:
results = self.search(attempt) if len(attempt.strip()) >= 2 else []
if results:
top = results[0]
return place(name.strip() or query, top['latitude'], top['longitude'], top.get('address') or top['name'])
raise ShareQueryError(f'No map location found for {name.strip() or query}', query[:200])
@staticmethod
def _google_places_key(settings) -> str:
"""Places are found with Google when Google gives directions."""
return settings['googleKey'] if settings['routeProvider'] == 'google' else ''
def _proximity(self):
proximity = self._search_context().get('proximity')
return tuple(float(value) for value in proximity.split(',')) if proximity else None
def _google_text_search(self, settings, query: str, limit: int) -> list[dict] | None:
"""Google's places for the text; None when Google is not chosen or can't answer, so Mapbox looks instead."""
key = self._google_places_key(settings)
if not key:
return None
from openpilot.starpilot.navigation.google_places import GooglePlacesFailed, places_budget, text_search
try:
return text_search(self.session, key, query.strip(), places_budget(self.google_root), self._proximity(), limit=limit)
except GooglePlacesFailed:
return None
def search(self, query: str) -> list[dict]:
if not isinstance(query, str) or not 2 <= len(query.strip()) <= 256:
raise ValidationError('Enter at least two characters to search')
@@ -653,6 +766,16 @@ class NavigationOwner:
current = self.read()
if not current['token']:
raise ValidationError('Add your Mapbox access token first')
if not autocomplete:
found = self._google_text_search(current, query, 8)
if found is not None:
results = []
for row in found:
try:
results.append(destination(row))
except ValidationError:
continue
return PlaceResults(results, 'google')
key = (caller, search_id)
from openpilot.starpilot.navigation.mapbox_budget import BudgetExhausted
with self._lock:
@@ -671,7 +794,7 @@ class NavigationOwner:
entry = previous
entry['expires'] = now + SEARCH_TTL
entry['suggests'] = entry.get('suggests', 0) + 1
if entry['suggests'] % SUGGESTS_PER_SESSION == 0:
if entry['provider'] == 'mapbox' and entry['suggests'] % SUGGESTS_PER_SESSION == 0:
try:
self.search_budget.spend()
except BudgetExhausted as error:
@@ -679,13 +802,16 @@ class NavigationOwner:
else:
if len(self._searches) >= MAX_SEARCHES or sum(key[0] == caller for key in self._searches) >= 8:
raise ValidationError('Too many destination searches; try again shortly')
provider = 'google' if autocomplete and self._google_places_key(current) else 'mapbox'
# The Search button keeps upstream's behavior (counted, never refused); typing suggestions stop at the cap.
try:
self.search_budget.spend(enforce=autocomplete)
if provider == 'mapbox':
self.search_budget.spend(enforce=autocomplete)
except BudgetExhausted as error:
raise ValidationError(str(error)) from None
entry = {'client_id':client_id, 'session':str(uuid.uuid4()), 'expires':now + SEARCH_TTL, 'revision':current['revision'],
'token_digest':hashlib.sha256(current['token'].encode()).digest(), 'ids':set(), 'autocomplete':autocomplete}
'token_digest':hashlib.sha256(current['token'].encode()).digest(), 'ids':set(), 'autocomplete':autocomplete,
'provider':provider, 'google':{}, 'google_session':str(uuid.uuid4())}
self._searches[key] = entry
try:
context = self._search_context()
@@ -693,23 +819,15 @@ class NavigationOwner:
if (self._searches.get(key) is not entry or entry['expires'] <= time.monotonic() or
self.read()['token'] != current['token']):
raise ValidationError('Start a new destination search')
data = response_json(self.session, 'https://api.mapbox.com/search/searchbox/v1/suggest',
{'q':query.strip(), 'access_token':current['token'], 'session_token':entry['session'],
'types':','.join(sorted(AUTOCOMPLETE_TYPES)) if autocomplete else 'poi', 'limit':8, **context})
suggestions = data.get('suggestions')
if not isinstance(suggestions, list):
raise ValidationError('The map service returned invalid search results')
results = []
for item in suggestions[:8]:
if not isinstance(item, dict):
continue
identity, name = item.get('mapbox_id'), item.get('name')
kinds = AUTOCOMPLETE_TYPES if autocomplete else {'poi'}
if (item.get('feature_type') in kinds and isinstance(identity, str) and 1 <= len(identity) <= 256 and
isinstance(name, str) and 1 <= len(name.strip()) <= 256):
description = item.get('full_address') or item.get('place_formatted') or ''
description = description.strip()[:512] if isinstance(description, str) else ''
results.append({'id':identity, 'name':name.strip(), 'description':description, 'searchId':search_id, 'temporary':True})
results = self._google_suggest(entry, current, query, search_id, context) if entry['provider'] == 'google' else None
if results is None:
data = response_json(self.session, 'https://api.mapbox.com/search/searchbox/v1/suggest',
{'q':query.strip(), 'access_token':current['token'], 'session_token':entry['session'],
'types':','.join(sorted(AUTOCOMPLETE_TYPES)) if autocomplete else 'poi', 'limit':8, **context})
suggestions = data.get('suggestions')
if not isinstance(suggestions, list):
raise ValidationError('The map service returned invalid search results')
results = self._mapbox_suggestions(suggestions, search_id, autocomplete)
with self._lock:
if (self._searches.get(key) is not entry or entry['expires'] <= time.monotonic() or
self.read()['token'] != current['token']):
@@ -717,20 +835,55 @@ class NavigationOwner:
# Any suggestion shown during this typing session can still be chosen.
entry['ids'] = (entry['ids'] if autocomplete else set()) | {item['id'] for item in results}
if results or autocomplete:
return results
return PlaceResults(results, entry['provider'])
except ValidationError:
with self._lock:
if (self._searches.get(key) is not entry or entry['expires'] <= time.monotonic() or
self.read()['token'] != current['token']):
raise ValidationError('Start a new destination search') from None
if autocomplete:
return [] # suggestions are best effort; typing never spends address lookups
return PlaceResults([], entry['provider']) # suggestions are best effort; typing never spends address lookups
self.cancel_search(caller, search_id)
# Address search remains available if place search is unavailable.
return self.search(query)
self.cancel_search(caller, search_id)
return self.search(query)
def _google_suggest(self, entry, current, query, search_id, context) -> list[dict] | None:
"""Google's typing suggestions; None after Google fails, and the session continues on Mapbox."""
from openpilot.starpilot.navigation.google_places import GooglePlacesFailed, autocomplete, suggestions_budget
from openpilot.starpilot.navigation.mapbox_budget import BudgetExhausted
proximity = tuple(float(value) for value in context['proximity'].split(',')) if context.get('proximity') else None
try:
rows = autocomplete(self.session, current['googleKey'], query.strip(), entry['google_session'], suggestions_budget(self.google_root), proximity)
except GooglePlacesFailed:
with self._lock:
entry['provider'] = 'mapbox'
try:
self.search_budget.spend(enforce=True)
except BudgetExhausted as error:
raise ValidationError(str(error)) from None
return None
results = [dict(row, searchId=search_id, temporary=True) for row in rows]
with self._lock:
entry['google'].update({row['id']: row for row in results})
return results
@staticmethod
def _mapbox_suggestions(suggestions, search_id, autocomplete) -> list[dict]:
results = []
for item in suggestions[:8]:
if not isinstance(item, dict):
continue
identity, name = item.get('mapbox_id'), item.get('name')
kinds = AUTOCOMPLETE_TYPES if autocomplete else {'poi'}
if (item.get('feature_type') in kinds and isinstance(identity, str) and 1 <= len(identity) <= 256 and
isinstance(name, str) and 1 <= len(name.strip()) <= 256):
description = item.get('full_address') or item.get('place_formatted') or ''
description = description.strip()[:512] if isinstance(description, str) else ''
results.append({'id':identity, 'name':name.strip(), 'description':description, 'searchId':search_id, 'temporary':True})
return results
def _retrieve(self, identity, search_id, caller, expected_revision, authorized) -> dict:
"""Temporary coordinates for the selected route."""
if not isinstance(identity, str) or not isinstance(search_id, str):
@@ -744,6 +897,14 @@ class NavigationOwner:
raise ValidationError('Search again before choosing this place')
if not (authorized() if callable(authorized) else authorized is True):
raise PermissionError('Navigation changes are not available right now')
suggested = entry.get('google', {}).get(identity)
if suggested is not None:
from openpilot.starpilot.navigation.google_places import GooglePlacesFailed, place_details
try:
found = place_details(self.session, current['googleKey'], identity, entry['google_session'])
except GooglePlacesFailed:
raise ValidationError('Google could not open this place; search again') from None
return destination(dict(found, name=suggested['name'], address=found['address'] or suggested['description']))
data = response_json(self.session, 'https://api.mapbox.com/search/searchbox/v1/retrieve/' + quote(identity, safe=''),
{'access_token':current['token'], 'session_token':entry['session']})
try:
+55
View File
@@ -0,0 +1,55 @@
import re
from urllib.parse import parse_qs, unquote_plus, urlsplit
# Same rules as galaxy/web/js/share-destination.js: destination coordinates before Google's viewport (@lat,lng).
NUMBER = r'(-?\d+(?:\.\d+)?)'
COORDINATES = (re.compile(rf'!3d{NUMBER}!4d{NUMBER}'), re.compile(rf'[?&:](?:q|query|daddr|destination|ll|coordinate)={NUMBER},\s*{NUMBER}'),
re.compile(rf'geo:{NUMBER},\s*{NUMBER}'), re.compile(rf'@{NUMBER},\s*{NUMBER}'))
QUERY = re.compile(r'[?&:](?:q|query|daddr|destination)=([^&#]+)')
QUERY_KEYS = ('q', 'query', 'daddr', 'destination')
LINK = re.compile(r'https://[^\s<>"]+')
MAP_HOST = re.compile(r'(?:[a-z0-9-]+\.)*google\.com|(?:maps\.app\.)?goo\.gl|maps\.apple(?:\.com)?')
def place(label: str, latitude: float, longitude: float, address: str | None = None) -> dict:
name, _, rest = label.partition(',')
return {'name': name.strip()[:256] or 'Shared destination', 'latitude': latitude, 'longitude': longitude,
'address': address or rest.strip() or None}
def shared_coordinates(text: str) -> dict | None:
decoded = unquote_plus(text.strip())
for pattern in COORDINATES:
match = pattern.search(decoded)
if match is None:
continue
latitude, longitude = float(match[1]), float(match[2])
if abs(latitude) > 90 or abs(longitude) > 180:
continue
# geo:0,0?q=an address is a search, not a destination in the ocean.
if match[0].startswith('geo:0,0') and re.search(r'[?&:]q=', decoded):
continue
label = (re.search(r'\(([^()]{1,120})\)', decoded) or re.search(r'/place/([^/?#&\n]+)', decoded) or
re.search(r'[?&](?:name|q)=([^&#\n]*[^\d\s,.&#-][^&#\n]*)', decoded))
return place(label[1] if label else 'Shared destination', latitude, longitude)
return None
def map_link_query(text: str) -> str | None:
"""The place a Google or Apple Maps link names, for links without coordinates."""
for link in LINK.findall(text):
parts = urlsplit(link)
if not MAP_HOST.fullmatch(parts.hostname or ''):
continue
named = re.search(r'/place/([^/]+)', parts.path)
values = parse_qs(parts.query)
query = unquote_plus(named[1]) if named else next((values[key][0] for key in QUERY_KEYS if key in values), '')
query = ' '.join(query.split())
if query:
return query[:256]
return None
def search_text(text: str) -> str:
match = QUERY.search(unquote_plus(text.strip()))
return ' '.join((match[1] if match else LINK.sub(' ', text)).split())[:200]
@@ -176,7 +176,7 @@ def test_key_test_reports_routes_plainly(tmp_path):
assert http.calls[0][1]["json"]["routingPreference"] == "TRAFFIC_UNAWARE"
failed = gr.test_routes(KEY, Http(error=requests.Timeout()), budget(tmp_path))
assert not failed["ok"] and "Mapbox" not in failed["message"]
assert "Routes API is not enabled" in gr.test_routes(KEY, Http(403, b"SERVICE_DISABLED"), budget(tmp_path))["message"]
assert "Routes API is off" in gr.test_routes(KEY, Http(403, b"SERVICE_DISABLED"), budget(tmp_path))["message"]
def google_runtime(tmp_path, google_fetch):
@@ -0,0 +1,136 @@
import json
import uuid
from contextlib import nullcontext
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from openpilot.starpilot.navigation.google_places import places_budget, suggestions_budget
from openpilot.starpilot.navigation.owner import NavigationOwner, ValidationError
KEY = 'AIzaSyFixtureKey_0123456789abcdef'
BELLAGIO = {'displayName': {'text': 'Bellagio'}, 'formattedAddress': '3600 S Las Vegas Blvd, Las Vegas, NV',
'location': {'latitude': 36.1126, 'longitude': -115.1767}}
CAESARS = {'displayName': {'text': 'Caesars Palace'}, 'formattedAddress': '3570 S Las Vegas Blvd', 'location': {'latitude': 36.1162, 'longitude': -115.1745}}
PREDICTION = {'placePrediction': {'placeId': 'ChIJbellagio', 'text': {'text': 'Bellagio, Las Vegas'},
'structuredFormat': {'mainText': {'text': 'Bellagio'}, 'secondaryText': {'text': 'Las Vegas Blvd, Las Vegas, NV'}}}}
MAPBOX = {'features': [{'properties': {'name': 'Mapbox Place', 'full_address': '1 Main St'}, 'geometry': {'coordinates': [-90., 40.]}}]}
class Google:
def __init__(self, status=200, places=(), suggestions=(), details=None):
self.status, self.places, self.suggestions, self.details, self.calls = status, list(places), list(suggestions), details, []
def _answer(self, value):
refusal = {'error': {'message': 'Places API (New) has not been used in project 1 before or it is disabled.'}}
body = json.dumps(value if self.status == 200 else refusal).encode()
return nullcontext(SimpleNamespace(status_code=self.status, iter_content=lambda size: [body]))
def post(self, url, **kwargs):
self.calls.append(('post', url, kwargs))
return self._answer({'places': self.places} if url.endswith(':searchText') else {'suggestions': self.suggestions})
def get(self, url, **kwargs):
self.calls.append(('get', url, kwargs))
return self._answer(self.details)
@pytest.fixture
def owner(tmp_path):
result = NavigationOwner(tmp_path / 'saved', runtime_source=lambda: None, transient_root=tmp_path / 'boot')
saved = result.configure({'enabled': True, 'token': 'pk.synthetic', 'googleKey': KEY}, '0', True)
result.configure({'routeProvider': 'google'}, saved['revision'], True)
with patch.object(result, '_search_context', return_value={'proximity': '-115.200000,36.200000'}):
yield result
def search(owner, query='bellagio', autocomplete=False, search_id=None, client=None):
return owner.search_places(query, 'caller', search_id or str(uuid.uuid4()), client or str(uuid.uuid4()), autocomplete=autocomplete)
def test_full_search_uses_google_text_search_when_google_gives_directions(owner):
owner.session = Google(places=[BELLAGIO, CAESARS])
with patch('openpilot.starpilot.navigation.owner.response_json') as mapbox:
results = search(owner)
mapbox.assert_not_called()
assert results.provider == 'google'
assert [(row['name'], row['address'], row['latitude']) for row in results] == [
('Bellagio', '3600 S Las Vegas Blvd, Las Vegas, NV', 36.1126), ('Caesars Palace', '3570 S Las Vegas Blvd', 36.1162)]
assert all('searchId' not in row and 'temporary' not in row for row in results), "plain select and favorite take these"
_, url, request = owner.session.calls[0]
assert url.endswith('places:searchText') and request['json']['pageSize'] == 8 and request['json']['textQuery'] == 'bellagio'
assert request['json']['locationBias']['circle']['center'] == {'latitude': 36.2, 'longitude': -115.2}
assert places_budget(owner.google_root).snapshot()['monthUsed'] == 1
saved = owner.favorite(results[0], owner.read()['revision'], True)
assert saved['favorites'][0]['name'] == 'Bellagio'
assert owner.select(results[1], saved['revision'], True)['destination']['name'] == 'Caesars Palace'
owner.session = Google()
empty = search(owner, 'nowhere')
assert empty == [] and empty.provider == 'google', "Google finding nothing is an answer, not a reason to ask Mapbox"
def test_full_search_falls_back_to_mapbox_when_google_refuses_or_runs_out(owner):
owner.session = Google(status=403)
with patch('openpilot.starpilot.navigation.owner.response_json', return_value={'suggestions': []}), \
patch.object(owner, 'search', return_value=[{'id': 'x', 'name': 'Mapbox Place', 'latitude': 40., 'longitude': -90.}]) as geocode:
results = search(owner)
assert getattr(results, 'provider', 'mapbox') == 'mapbox' and results[0]['name'] == 'Mapbox Place'
geocode.assert_called_once_with('bellagio')
owner.session = Google(places=[BELLAGIO])
with patch('openpilot.starpilot.navigation.google_places.GoogleBudget.spend', return_value=False):
assert getattr(search(owner), 'provider', 'mapbox') == 'mapbox'
assert not owner.session.calls, "a used-up allowance never reaches Google"
def test_mapbox_directions_keep_mapbox_search(owner):
owner.configure({'routeProvider': 'mapbox'}, owner.read()['revision'], True)
owner.session = Google(places=[BELLAGIO])
with patch('openpilot.starpilot.navigation.owner.response_json', return_value=MAPBOX | {'suggestions': []}):
results = search(owner)
assert results[0]['name'] == 'Mapbox Place' and not owner.session.calls
def test_typing_uses_one_google_session_and_choosing_ends_it_with_location_only_details(owner):
owner.session = Google(suggestions=[PREDICTION], details={'location': {'latitude': 36.1126, 'longitude': -115.1767},
'formattedAddress': '3600 S Las Vegas Blvd, Las Vegas, NV 89109'})
search_id, client = str(uuid.uuid4()), str(uuid.uuid4())
with patch('openpilot.starpilot.navigation.owner.response_json') as mapbox:
first = search(owner, 'bel', True, search_id, client)
second = search(owner, 'bella', True, search_id, client)
mapbox.assert_not_called()
assert first.provider == 'google' and second[0] == {'id': 'ChIJbellagio', 'name': 'Bellagio', 'description': 'Las Vegas Blvd, Las Vegas, NV',
'searchId': search_id, 'temporary': True}
tokens = [call[2]['json']['sessionToken'] for call in owner.session.calls]
assert len(tokens) == 2 and tokens[0] == tokens[1] and 'X-Goog-FieldMask' not in owner.session.calls[0][2]['headers']
assert suggestions_budget(owner.google_root).snapshot()['monthUsed'] == 2
status = owner.select_place('ChIJbellagio', search_id, 'caller', owner.read()['revision'], True)
assert status['destination']['name'] == 'Bellagio' and status['destination']['address'] == '3600 S Las Vegas Blvd, Las Vegas, NV 89109'
method, url, request = owner.session.calls[-1]
assert (method, url) == ('get', 'https://places.googleapis.com/v1/places/ChIJbellagio')
assert request['params'] == {'sessionToken': tokens[0]} and request['headers']['X-Goog-FieldMask'] == 'location,formattedAddress'
with pytest.raises(ValidationError, match='cannot be saved'):
owner.favorite_place('ChIJbellagio', search_id, 'caller', status['revision'], True)
def test_typing_continues_on_mapbox_when_google_fails(owner):
owner.session = Google(status=403)
search_id, client = str(uuid.uuid4()), str(uuid.uuid4())
poi = {'mapbox_id': 'poi/b', 'name': 'Bellagio Mapbox', 'feature_type': 'poi'}
with patch('openpilot.starpilot.navigation.owner.response_json', return_value={'suggestions': [poi]}) as mapbox:
first = search(owner, 'bel', True, search_id, client)
second = search(owner, 'bell', True, search_id, client)
assert first.provider == second.provider == 'mapbox' and second[0]['name'] == 'Bellagio Mapbox'
assert len(owner.session.calls) == 1, "after one refusal the session stays on Mapbox"
assert mapbox.call_args_list[0].args[2]['session_token'] == mapbox.call_args_list[1].args[2]['session_token']
owner.session = Google(suggestions=[PREDICTION])
with patch('openpilot.starpilot.navigation.google_places.GoogleBudget.spend', return_value=False), \
patch('openpilot.starpilot.navigation.owner.response_json', return_value={'suggestions': [poi]}):
assert search(owner, 'bel', True).provider == 'mapbox'
assert not owner.session.calls
def test_snapshot_reports_google_place_use_without_the_key(owner):
places = owner.snapshot()['googlePlaces']
assert places['usage']['monthLimit'] == 4950 and places['suggestions']['monthLimit'] == 9900
assert KEY not in json.dumps(owner.snapshot())
@@ -254,3 +254,18 @@ def test_a_clock_running_behind_never_zeroes_the_counts(tmp_path):
assert budget.spend() and budget.snapshot()["monthUsed"] == 501 and budget.snapshot()["dayUsed"] == 501
clock[0] = WALL
assert budget.snapshot()["monthUsed"] == 501
def test_fetch_tile_caches_and_separates_light_and_dark_themes(tmp_path):
http = Http()
root = tmp_path / "google"
assert gt.fetch_tile(KEY, 12, 655, 1583, "light", http=http, root=root, wall=lambda: WALL) == PNG
assert gt.fetch_tile(KEY, 12, 655, 1583, "light", http=http, root=root, wall=lambda: WALL) == PNG
posts = [call for call in http.calls if call[0] == "post"]
assert len(posts) == 1 and "styles" not in posts[0][2]["json"]
assert len([call for call in http.calls if "2dtiles/12/655/1583" in call[1]]) == 1
assert gt.fetch_tile(KEY, 12, 655, 1583, "dark", http=http, root=root, wall=lambda: WALL) == PNG
posts = [call for call in http.calls if call[0] == "post"]
assert len(posts) == 2 and "styles" in posts[1][2]["json"]
assert gt.GoogleBudget(root, lambda: WALL).snapshot()["dayUsed"] == 2
@@ -177,3 +177,27 @@ def test_theme_tiles_have_separate_cache_entries(tmp_path):
with pytest.raises(ValidationError, match='Invalid map theme'):
owner.map_tile(2, 3, 1, 'custom/style')
assert len(provider.calls) == 2
def test_google_map_provider_serves_google_tiles_and_falls_back_to_mapbox(tmp_path, monkeypatch):
google_png = PNG + b'-google'
calls = []
def fake_fetch_tile(api_key, z, x, y, theme='dark', *, http=None, root=None):
calls.append((api_key, z, x, y, theme))
if theme == 'dark':
raise ValueError('quota reached')
return google_png
monkeypatch.setattr('openpilot.starpilot.navigation.google_tiles.fetch_tile', fake_fetch_tile)
provider = Provider()
owner = tile_owner(tmp_path, provider)
owner.read = lambda: {'token': 'pk.fixture', 'googleKey': 'AIzaSyTestKey123456', 'mapProvider': 'google'}
assert owner.map_tile(4, 2, 5, 'light', provider='google') == google_png
assert calls == [('AIzaSyTestKey123456', 4, 2, 5, 'light')]
assert not provider.calls
assert owner.map_tile(4, 2, 5, 'light') == PNG, 'offline maps and unflagged requests always use Mapbox even when Google is selected'
assert len(provider.calls) == 1
assert owner.map_tile(4, 2, 5, 'dark', provider='google') == PNG
assert len(provider.calls) == 2
assert '/mapbox/dark-v11/tiles/512/4/2/5.png' in provider.calls[1][0]
@@ -126,19 +126,50 @@ def test_older_settings_files_read_with_google_defaults(owner):
assert settings['mapProvider'] == 'mapbox' and settings['googleKey'] == ''
def test_google_key_test_uses_typed_or_saved_key(owner):
def test_google_key_test_checks_all_three_apis_whatever_the_route_provider(owner):
with (patch('openpilot.starpilot.navigation.google_tiles.test_key', return_value={'ok': True}) as tested,
patch('openpilot.starpilot.navigation.google_routes.test_routes', return_value={'ok': False}) as routed):
patch('openpilot.starpilot.navigation.google_routes.test_routes', return_value={'ok': False}) as routed,
patch('openpilot.starpilot.navigation.google_places.test_places', return_value={'ok': True, 'message': 'works'}) as placed):
with pytest.raises(ValidationError):
owner.test_google_key()
assert owner.test_google_key(GOOGLE_KEY) == {'ok': True}
both = {'ok': True, 'routes': {'ok': False}, 'places': {'ok': True, 'message': 'works'}}
assert owner.test_google_key(GOOGLE_KEY) == both
saved = owner.configure({'googleKey': GOOGLE_KEY}, '0', True)
owner.test_google_key()
assert not routed.called
assert owner.read()['routeProvider'] == 'mapbox' and owner.test_google_key() == both
owner.configure({'routeProvider': 'google'}, saved['revision'], True)
assert owner.test_google_key() == {'ok': True, 'routes': {'ok': False}}
assert [call.args[0] for call in tested.call_args_list] == [GOOGLE_KEY] * 3
assert [call.args[0] for call in routed.call_args_list] == [GOOGLE_KEY]
assert owner.test_google_key() == both
for mock in (tested, routed, placed):
assert [call.args[0] for call in mock.call_args_list] == [GOOGLE_KEY] * 3
class GoogleRefusal:
def __init__(self, status, text):
self.status, self.text = status, text
def _answer(self, *args, **kwargs):
from contextlib import nullcontext
from types import SimpleNamespace
return nullcontext(SimpleNamespace(status_code=self.status, iter_content=lambda size: [json.dumps({'error': {'message': self.text}}).encode()]))
post = get = _answer
@pytest.mark.parametrize('status, text, failure, words', [
(403, 'Places API (New) has not been used in project 1 before or it is disabled.', 'disabled',
"Enable it in Google Cloud and allow it in the key's API restrictions"),
(403, 'Requests to this API are blocked. API_KEY_SERVICE_BLOCKED', 'disabled', "allow it in the key's API restrictions"),
(400, 'API key not valid. Please pass a valid API key.', 'key', 'copied whole'),
(403, 'This API method requires billing to be enabled.', 'billing', 'Add a billing account')])
def test_google_key_test_names_each_api_and_what_to_fix(tmp_path, status, text, failure, words):
from openpilot.starpilot.navigation.google_places import places_budget, test_places
from openpilot.starpilot.navigation.google_routes import essentials_budget, test_routes
from openpilot.starpilot.navigation.google_tiles import GoogleBudget, test_key
http = GoogleRefusal(status, text)
results = {'Map Tiles API': test_key(GOOGLE_KEY, http, GoogleBudget(tmp_path)), 'Routes API': test_routes(GOOGLE_KEY, http, essentials_budget(tmp_path)),
'Places API (New)': test_places(GOOGLE_KEY, http, places_budget(tmp_path))}
for api, result in results.items():
assert result['ok'] is False and result['failure'] == failure and words in result['message']
assert failure == 'billing' or api in result['message']
def test_route_provider_is_saved_and_reports_google_route_use(owner):
@@ -179,3 +210,170 @@ def test_shared_short_link_follows_google_redirects_only(owner):
assert owner.resolve_share('Starbucks') == 'Starbucks' and not owner.session.calls
with pytest.raises(ValidationError):
owner.resolve_share(None)
def geocoded(places):
def respond(session, url, params):
assert url.endswith('/geocode/v6/forward')
hit = places.get(params['q'])
return {'features': [{'properties': {'name': hit[0], 'full_address': hit[1]}, 'geometry': {'coordinates': [hit[3], hit[2]]}}] if hit else []}
return patch('openpilot.starpilot.navigation.owner.response_json', side_effect=respond)
@pytest.fixture
def keyed(owner):
owner.configure({'token': 'pk.synthetic'}, owner.read()['revision'], True)
return owner
def test_share_with_coordinates_turns_navigation_on_and_routes(keyed):
with geocoded({}) as provider:
status = keyed.share('https://www.google.com/maps/place/Bellagio,+3600+S+Las+Vegas+Blvd/@36.2,-115.2,17z/data=!3d36.1126!4d-115.1767',
keyed.read()['revision'], True)
provider.assert_not_called()
assert status['enabled'] is True
assert status['shared'] == {'name': 'Bellagio', 'latitude': 36.1126, 'longitude': -115.1767}
assert status['destination']['address'] == '3600 S Las Vegas Blvd'
assert keyed.read()['destination']['latitude'] == 36.1126
geo = keyed.share('geo:40.5,-89.5?q=40.5,-89.5(Library)', status['revision'], True)
assert geo['shared'] == {'name': 'Library', 'latitude': 40.5, 'longitude': -89.5}
apple = keyed.share('https://maps.apple.com/?ll=41.25,-88.75&q=Park', geo['revision'], True)
assert apple['shared'] == {'name': 'Park', 'latitude': 41.25, 'longitude': -88.75}
apple = keyed.share('https://maps.apple.com/place?coordinate=41.5,-88.5&name=Apple+Park&place-id=I1', apple['revision'], True)
assert apple['shared'] == {'name': 'Apple Park', 'latitude': 41.5, 'longitude': -88.5}
plain = keyed.share('https://maps.google.com/?q=41.75,-88.25', apple['revision'], True)
assert plain['shared']['name'] == 'Shared destination'
def test_share_geocodes_place_links_without_coordinates(keyed):
places = {'3600 S Las Vegas Blvd, Las Vegas, NV 89109': ('3600 S Las Vegas Blvd', '3600 S Las Vegas Blvd, Las Vegas, NV 89109', 36.11, -115.17),
'Springfield Library, Springfield, IL 62701': ('Springfield', 'Springfield, Illinois', 39.8, -89.6),
'123 Main St, Springfield, IL 62701': ('123 Main St', '123 Main St, Springfield, IL 62701', 39.7, -89.7)}
with geocoded(places) as provider:
status = keyed.share('Bellagio\nhttps://www.google.com/maps/place/Bellagio,+3600+S+Las+Vegas+Blvd,+Las+Vegas,+NV+89109/data=!4m2!3m1!1s0x80c8:0x1',
keyed.read()['revision'], True)
assert [call.args[2]['q'] for call in provider.call_args_list] == ['3600 S Las Vegas Blvd, Las Vegas, NV 89109']
assert status['shared'] == {'name': 'Bellagio', 'latitude': 36.11, 'longitude': -115.17}
assert status['destination']['address'] == '3600 S Las Vegas Blvd, Las Vegas, NV 89109' and status['enabled']
provider.reset_mock()
status = keyed.share('https://maps.google.com/?q=Springfield+Library,+Springfield,+IL+62701&ftid=0x1:0x2', status['revision'], True)
assert [call.args[2]['q'] for call in provider.call_args_list] == ['Springfield Library, Springfield, IL 62701']
assert status['shared']['name'] == 'Springfield Library'
provider.reset_mock()
status = keyed.share('https://www.google.com/maps/place/123+Main+St,+Springfield,+IL+62701/data=!4m2', status['revision'], True)
assert [call.args[2]['q'] for call in provider.call_args_list] == ['123 Main St, Springfield, IL 62701']
assert status['shared']['name'] == '123 Main St'
provider.reset_mock()
with pytest.raises(ValidationError, match='No map location found for Nowhere') as error:
keyed.share('https://www.google.com/maps/place/Nowhere,+1+Lost+Rd,+Atlantis/data=!4m2', status['revision'], True)
assert error.value.query == 'Nowhere, 1 Lost Rd, Atlantis'
assert [call.args[2]['q'] for call in provider.call_args_list] == ['1 Lost Rd, Atlantis', 'Nowhere, 1 Lost Rd, Atlantis']
def test_share_without_a_map_place_asks_for_a_search(keyed):
revision = keyed.read()['revision']
with geocoded({}) as provider:
with pytest.raises(ValidationError, match='Open StarPilot to search for Starbucks') as error:
keyed.share('Starbucks', revision, True)
assert error.value.query == 'Starbucks'
with pytest.raises(ValidationError) as error:
keyed.share('geo:0,0?q=1600+Amphitheatre+Pkwy', revision, True)
assert error.value.query == '1600 Amphitheatre Pkwy'
provider.assert_not_called()
keyed.session = Redirects({})
with pytest.raises(ValidationError, match='could not be opened') as error:
keyed.share('https://maps.app.goo.gl/abc123', revision, True)
assert not hasattr(error.value, 'query')
assert keyed.read()['revision'] == revision and not keyed.read()['enabled']
def test_share_follows_short_links_and_checks_token_revision_and_authority(owner):
with pytest.raises(ValidationError, match='Mapbox access token'):
owner.share('geo:40.5,-89.5', owner.read()['revision'], True)
revision = owner.configure({'token': 'pk.synthetic'}, owner.read()['revision'], True)['revision']
with pytest.raises(ConflictError):
owner.share('geo:40.5,-89.5', '0', True)
with pytest.raises(PermissionError):
owner.share('geo:40.5,-89.5', revision, lambda: False)
with pytest.raises(ValidationError):
owner.share('', revision, True)
owner.session = Redirects({'https://maps.app.goo.gl/abc123': 'https://www.google.com/maps/place/X/data=!3d36.1!4d-115.1'})
status = owner.share('X https://maps.app.goo.gl/abc123', revision, True)
assert status['shared'] == {'name': 'X', 'latitude': 36.1, 'longitude': -115.1} and status['enabled']
class GooglePlaces:
def __init__(self, status=200, places=()):
self.status, self.places, self.posts = status, list(places), []
def post(self, url, **kwargs):
from contextlib import nullcontext
from types import SimpleNamespace
self.posts.append((url, kwargs))
body = json.dumps({'places': self.places} if self.status == 200 else {'error': {'status': 'PERMISSION_DENIED',
'message': 'Places API (New) has not been used in project 1 before or it is disabled.'}}).encode()
return nullcontext(SimpleNamespace(status_code=self.status, iter_content=lambda size: [body]))
@pytest.fixture
def google(keyed):
keyed.configure({'routeProvider': 'google', 'googleKey': GOOGLE_KEY}, keyed.read()['revision'], True)
with patch.object(keyed, '_search_context', return_value={'proximity': '-115.200000,36.200000'}):
yield keyed
def test_share_with_google_routing_looks_the_place_up_with_google(google):
google.session = GooglePlaces(places=[{'displayName': {'text': 'Bellagio Hotel & Casino'}, 'formattedAddress': '3600 S Las Vegas Blvd, Las Vegas, NV 89109',
'location': {'latitude': 36.1126, 'longitude': -115.1767}}])
with geocoded({}) as mapbox:
status = google.share('https://www.google.com/maps/place/Bellagio,+3600+S+Las+Vegas+Blvd,+Las+Vegas,+NV+89109/data=!4m2!3m1!1s0x1:0x2',
google.read()['revision'], True)
mapbox.assert_not_called()
assert status['shared'] == {'name': 'Bellagio Hotel & Casino', 'latitude': 36.1126, 'longitude': -115.1767} and status['enabled']
assert status['destination']['address'] == '3600 S Las Vegas Blvd, Las Vegas, NV 89109'
url, request = google.session.posts[0]
assert url == 'https://places.googleapis.com/v1/places:searchText'
assert request['json']['textQuery'] == 'Bellagio, 3600 S Las Vegas Blvd, Las Vegas, NV 89109' and request['json']['pageSize'] == 1
assert request['json']['locationBias']['circle']['center'] == {'latitude': 36.2, 'longitude': -115.2}
assert request['headers'] == {'X-Goog-Api-Key': GOOGLE_KEY, 'X-Goog-FieldMask': 'places.displayName,places.formattedAddress,places.location'}
google.session = GooglePlaces()
with pytest.raises(ValidationError, match='No map location found for Nowhere') as error:
google.share('https://maps.google.com/?q=Nowhere', status['revision'], True)
assert error.value.query == 'Nowhere'
google.session = GooglePlaces(places=[{'location': {'latitude': 1.5, 'longitude': 2.5}}])
assert google.share('geo:40.5,-89.5', status['revision'], True)['shared']['latitude'] == 40.5
assert not google.session.posts
def test_share_falls_back_to_mapbox_when_google_lookup_is_refused(google):
google.session = GooglePlaces(status=403)
with geocoded({'Springfield Library': ('Springfield Library', 'Springfield, IL', 39.8, -89.6)}) as mapbox:
status = google.share('https://maps.google.com/?q=Springfield+Library', google.read()['revision'], True)
assert len(google.session.posts) == 1 and mapbox.call_args.args[2]['q'] == 'Springfield Library'
assert status['shared'] == {'name': 'Springfield Library', 'latitude': 39.8, 'longitude': -89.6}
from openpilot.starpilot.navigation.google_places import places_budget
budget = places_budget(google.google_root)
assert budget.snapshot()['monthUsed'] == 1 and budget.month_limit == 4950
with patch('openpilot.starpilot.navigation.google_places.GoogleBudget.spend', return_value=False):
google.session = GooglePlaces(places=[{'location': {'latitude': 1.5, 'longitude': 2.5}}])
with geocoded({'Springfield Library': ('Springfield Library', 'Springfield, IL', 39.8, -89.6)}):
assert google.share('https://maps.google.com/?q=Springfield+Library', status['revision'], True)['shared']['latitude'] == 39.8
assert not google.session.posts
def test_share_with_google_only_setup_still_needs_the_mapbox_token_routing_uses(owner):
owner.configure({'routeProvider': 'google', 'googleKey': GOOGLE_KEY, 'mapProvider': 'google'}, owner.read()['revision'], True)
owner.session = GooglePlaces(places=[{'location': {'latitude': 1.5, 'longitude': 2.5}}])
with pytest.raises(ValidationError, match='Add your Mapbox access token first') as error:
owner.share('https://maps.google.com/?q=Bellagio', owner.read()['revision'], True)
assert not hasattr(error.value, 'query') and not owner.session.posts
assert owner.snapshot()['status'] == 'disabled' and not owner.snapshot()['hasKey']
def test_google_place_lookup_test_reports_disabled_api():
from openpilot.starpilot.navigation.google_places import places_budget, test_places
import tempfile
with tempfile.TemporaryDirectory() as root:
assert test_places(GOOGLE_KEY, GooglePlaces(status=403), places_budget(root)) == {'ok': False, 'failure': 'disabled',
'message': "Places API (New) is off for this key. Enable it in Google Cloud and allow it in the key's API restrictions, then test again."}
assert test_places(GOOGLE_KEY, GooglePlaces(places=[{'location': {'latitude': 1.5, 'longitude': 2.5}}]), places_budget(root))['ok']