voice: saved places, so "navigate home" or "take me to work" works in any map app

Home, Work and three named places live in the Car card on Home, under Saved places. Type an
address or save where you're standing.
This commit is contained in:
Seb3thehacker committed 2026-10-27 00:05:15 -07:00
1 parent 57803988d4
commit 2f49559600
22 files changed
+579 -3

No files matched your search

@@ -95,7 +95,12 @@ object AssistantCommands {
heard: String,
): String? {
// "use Organic Maps to get to X", "open OsmAnd and navigate to X": the app comes first.
var text = heard
// "take me home", "go home": no "to", so no trigger would catch them.
var text = if (Regex("^(?:(?:take|bring|get|drive) me|go|drive|head|get|directions|go back|head back) home$").matches(heard)) {
"navigate to home"
} else {
heard
}
var leadingApp: String? = null
Regex("^(?:use|using|with|open|in|on) (.+?) (?:to |and )(.+)$").find(text)?.let { m ->
if (after(m.groupValues[2], NAVIGATE_TRIGGERS) != null) {
@@ -135,6 +140,20 @@ object AssistantCommands {
val (place, nearby) = plainPlace(destination)
destination = place
if (destination.isBlank()) return "Where to?"
// "home", "work", or a name from Saved places: its address is the search.
var spoken: String? = null
SavedPlaces.match(context, destination)?.let { (slot, saved) ->
val name = when (slot) {
SavedPlaces.HOME -> "home"
SavedPlaces.WORK -> "work"
else -> saved.label
}
if (saved.address.isBlank()) {
return "You haven't saved a $name address yet. Add it under Saved places in Gearslip's settings on your phone."
}
destination = saved.address
spoken = if (slot == SavedPlaces.HOME) "home" else "to $name"
}
val chosen = chosenApp ?: when {
navApps.size == 1 -> navApps.first()
@@ -144,6 +163,7 @@ object AssistantCommands {
CarServices.connectNav(template, frame, destination)
navigator.home()
spoken?.let { return "Navigating $it with ${chosen.label}." }
return if (nearby) "Finding the nearest $destination with ${chosen.label}." else "Navigating to $destination with ${chosen.label}."
}
@@ -0,0 +1,114 @@
package app.seb3thehacker.gearslip.car
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.Geocoder
import android.location.Location
import android.location.LocationManager
import app.seb3thehacker.gearslip.AppSettings
import app.seb3thehacker.gearslip.GearslipLog
import java.util.Locale
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import org.json.JSONArray
import org.json.JSONObject
import kotlin.coroutines.resume
/** One saved place. Home and Work keep a blank [label]; their names come from strings.xml. */
data class SavedPlace(val label: String = "", val address: String = "")
/**
* Up to [COUNT] places a driver can name by voice in any map app: slot [HOME], slot [WORK],
* then three they name themselves. "Navigate home" sends the saved address as the search.
*/
object SavedPlaces {
const val COUNT = 5
const val HOME = 0
const val WORK = 1
private const val KEY = "saved_places"
private val HOME_WORDS = setOf("home", "house", "place", "home address", "my home", "my house", "my place")
private val WORK_WORDS = setOf("work", "office", "job", "work address", "my work", "my office", "my job", "the office")
fun all(context: Context): List<SavedPlace> {
val saved = runCatching {
val array = JSONArray(AppSettings.getString(context, KEY, "[]"))
List(array.length()) { i ->
array.getJSONObject(i).let { SavedPlace(it.optString("label"), it.optString("address")) }
}
}.getOrDefault(emptyList())
return List(COUNT) { saved.getOrNull(it) ?: SavedPlace() }
}
fun set(context: Context, index: Int, place: SavedPlace) {
val next = all(context).toMutableList().also { it[index] = place }
val array = JSONArray()
next.forEach { array.put(JSONObject().put("label", it.label).put("address", it.address)) }
AppSettings.putString(context, KEY, array.toString())
}
/**
* The slot [spoken] names, if any: "home", "my house", "work", or a custom label. Returns the
* slot even when its address is blank, so the assistant can say it isn't set yet.
*/
fun match(context: Context, spoken: String): Pair<Int, SavedPlace>? {
val said = spoken.lowercase().trim()
val places = all(context)
if (said in HOME_WORDS) return HOME to places[HOME]
if (said in WORK_WORDS) return WORK to places[WORK]
val squashed = squash(said.removePrefix("my ").removePrefix("the "))
if (squashed.isEmpty()) return null
places.forEachIndexed { i, place ->
if (i > WORK && place.label.isNotBlank() && squash(place.label) == squashed) return i to place
}
return null
}
private fun squash(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
fun hasLocationPermission(context: Context) =
context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
/** Where the phone is now, as a street address, or as coordinates when there's no geocoder. Null if unknown. */
suspend fun here(context: Context): String? = withContext(Dispatchers.IO) {
val location = locate(context) ?: return@withContext null
val address = runCatching {
if (!Geocoder.isPresent()) return@runCatching null
@Suppress("DEPRECATION")
Geocoder(context, Locale.getDefault()).getFromLocation(location.latitude, location.longitude, 1)
?.firstOrNull()?.getAddressLine(0)
}.getOrNull()
address ?: "%.6f,%.6f".format(Locale.US, location.latitude, location.longitude)
}
private suspend fun locate(context: Context): Location? {
if (!hasLocationPermission(context)) return null
val manager = context.getSystemService(LocationManager::class.java) ?: return null
val provider = listOf(LocationManager.FUSED_PROVIDER, LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER)
.firstOrNull { it in manager.allProviders && manager.isProviderEnabled(it) }
// A fresh fix: saving the spot you're standing on wants better than an hour-old one.
val fresh = provider?.let {
withTimeoutOrNull(FIX_TIMEOUT_MS) {
suspendCancellableCoroutine { done ->
runCatching {
manager.getCurrentLocation(it, null, context.mainExecutor) { fix -> done.resume(fix) }
}.onFailure { e ->
GearslipLog.w("places: fix failed: ${e.message}")
done.resume(null)
}
}
}
}
return fresh ?: manager.allProviders
.mapNotNull { runCatching { manager.getLastKnownLocation(it) }.getOrNull() }
.maxByOrNull { it.time }
}
private const val FIX_TIMEOUT_MS = 15_000L
}
@@ -43,7 +43,7 @@ import app.seb3thehacker.gearslip.BuildConfig
import app.seb3thehacker.gearslip.CertProvider
import app.seb3thehacker.gearslip.stats.UsageStats
private enum class Screen { HOME, LOGS, SETTINGS, CAR_PREVIEW, CERT_SETUP, SETUP_GUIDE, USAGE_NOTES, HELP, WHATS_NEW, RECOMMENDED_APPS, CAR_GROUP }
private enum class Screen { HOME, LOGS, SETTINGS, CAR_PREVIEW, CERT_SETUP, SETUP_GUIDE, USAGE_NOTES, HELP, WHATS_NEW, RECOMMENDED_APPS, CAR_GROUP, SAVED_PLACES }
/** Three screens and a back stack of depth one: no navigation library needed. */
@Composable
@@ -127,7 +127,13 @@ fun GearslipApp(onDisconnect: () -> Unit, onRequestCallScreening: () -> Unit) {
onOpenCarPreview = { backTo = Screen.HOME; screen = Screen.CAR_PREVIEW },
onOpenLogs = { backTo = Screen.HOME; screen = Screen.LOGS },
onDisconnect = onDisconnect,
onOpenCarGroup = { carGroup = it; screen = Screen.CAR_GROUP },
onOpenCarGroup = {
if (it == CarGroup.PLACES) {
screen = Screen.SAVED_PLACES
} else {
carGroup = it; screen = Screen.CAR_GROUP
}
},
)
Screen.CAR_GROUP -> CarGroupScreen(carGroup, onBack = { screen = Screen.HOME })
Screen.WHATS_NEW -> WhatsNewScreen(onBack = { screen = backTo })
@@ -139,6 +145,7 @@ fun GearslipApp(onDisconnect: () -> Unit, onRequestCallScreening: () -> Unit) {
atUsageNotes = settingsAtUsageNotes,
)
Screen.RECOMMENDED_APPS -> RecommendedAppsScreen(onBack = { screen = Screen.SETTINGS })
Screen.SAVED_PLACES -> SavedPlacesScreen(onBack = { screen = Screen.HOME })
Screen.CAR_PREVIEW -> CarPreviewScreen(onBack = { screen = backTo })
Screen.HELP -> HelpScreen(
onBack = { screen = backTo },
@@ -46,6 +46,7 @@ enum class CarGroup(@param:StringRes val title: Int) {
SCREEN(R.string.car_group_screen),
NAV_BAR(R.string.car_group_nav_bar),
SOUND(R.string.car_group_sound),
PLACES(R.string.places_title),
WARNINGS(R.string.car_group_warnings),
MORE(R.string.car_group_more),
}
@@ -98,6 +99,8 @@ internal fun HomeCarSettings(onOpen: (CarGroup) -> Unit, modifier: Modifier = Mo
val navBars = navBarChoices()
val context = androidx.compose.ui.platform.LocalContext.current
fun str(id: Int) = context.getString(id)
// Read again each time Home shows, so a place saved a moment ago is listed.
val places = androidx.compose.runtime.remember { app.seb3thehacker.gearslip.car.SavedPlaces.all(context) }
fun summary(group: CarGroup) = when (group) {
CarGroup.SCREEN -> listOf(opens.label(open), sizes.label(scale), themes.label(theme))
CarGroup.NAV_BAR -> listOf(navBars.label(navBar), str(if (playerLeft) R.string.summary_player_left else R.string.summary_player_right))
@@ -105,6 +108,14 @@ internal fun HomeCarSettings(onOpen: (CarGroup) -> Unit, modifier: Modifier = Mo
str(if (pipeAudio) R.string.summary_usb_audio else R.string.summary_bluetooth_audio),
str(if (speakDirections) R.string.summary_directions_on else R.string.summary_directions_off),
)
CarGroup.PLACES -> places.mapIndexedNotNull { i, place ->
when {
place.address.isBlank() -> null
i == app.seb3thehacker.gearslip.car.SavedPlaces.HOME -> str(R.string.places_home)
i == app.seb3thehacker.gearslip.car.SavedPlaces.WORK -> str(R.string.places_work)
else -> place.label.ifBlank { context.getString(R.string.places_other, i - app.seb3thehacker.gearslip.car.SavedPlaces.WORK) }
}
}.ifEmpty { listOf(str(R.string.places_sub)) }
CarGroup.WARNINGS -> listOf(
str(if (bluetoothWarning && !pipeAudio) R.string.summary_bluetooth_on else R.string.summary_bluetooth_off),
str(if (locationWarning) R.string.summary_location_on else R.string.summary_location_off),
@@ -253,6 +264,7 @@ private fun GroupRows(group: CarGroup) {
note = stringResource(R.string.car_phone_speech_note),
)
}
CarGroup.PLACES -> Unit
CarGroup.WARNINGS -> {
if (!pipeAudio) {
Toggle(stringResource(R.string.car_warn_bluetooth), bluetoothWarning, CarSettings::setBluetoothWarning)
@@ -0,0 +1,219 @@
package app.seb3thehacker.gearslip.ui
import android.Manifest
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.Place
import androidx.compose.material.icons.materialIcon
import androidx.compose.material.icons.materialPath
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.unit.dp
import app.seb3thehacker.gearslip.R
import app.seb3thehacker.gearslip.car.SavedPlace
import app.seb3thehacker.gearslip.car.SavedPlaces
import kotlinx.coroutines.launch
/** Home, Work and three named places, each saved the moment it's typed. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SavedPlacesScreen(onBack: () -> Unit) {
val context = LocalContext.current
val places = remember { SavedPlaces.all(context).toMutableList() }
Scaffold(
containerColor = MaterialTheme.colorScheme.background,
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.places_title)) },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
}
},
)
},
) { padding ->
Column(
Modifier
.fillMaxSize()
.padding(padding)
.imePadding()
.padding(horizontal = 24.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
Text(
stringResource(R.string.places_intro),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 16.dp),
)
for (i in 0 until SavedPlaces.COUNT) {
PlaceCard(i, places[i]) { place ->
places[i] = place
SavedPlaces.set(context, i, place)
}
}
Spacer(Modifier.height(16.dp))
}
}
}
@Composable
private fun PlaceCard(index: Int, initial: SavedPlace, onChange: (SavedPlace) -> Unit) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
var label by remember { mutableStateOf(initial.label) }
var address by remember { mutableStateOf(initial.address) }
var finding by remember { mutableStateOf(false) }
var notFound by remember { mutableStateOf(false) }
val custom = index > SavedPlaces.WORK
fun save() = onChange(SavedPlace(if (custom) label.trim() else "", address.trim()))
fun findHere() {
finding = true
notFound = false
scope.launch {
val here = SavedPlaces.here(context)
finding = false
if (here == null) {
notFound = true
} else {
address = here
save()
}
}
}
val askLocation = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
if (SavedPlaces.hasLocationPermission(context)) findHere() else notFound = true
}
SettingsCard {
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Icon(
when (index) {
SavedPlaces.HOME -> Icons.Filled.Home
SavedPlaces.WORK -> Briefcase
else -> Icons.Filled.Place
},
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
)
Text(
when (index) {
SavedPlaces.HOME -> stringResource(R.string.places_home)
SavedPlaces.WORK -> stringResource(R.string.places_work)
else -> label.ifBlank { stringResource(R.string.places_other, index - SavedPlaces.WORK) }
},
style = MaterialTheme.typography.titleMedium,
)
}
if (custom) {
OutlinedTextField(
value = label,
onValueChange = { label = it; save() },
label = { Text(stringResource(R.string.places_name)) },
singleLine = true,
keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Words, imeAction = ImeAction.Next),
modifier = Modifier.fillMaxWidth(),
)
}
OutlinedTextField(
value = address,
onValueChange = { address = it; notFound = false; save() },
label = { Text(stringResource(R.string.places_address)) },
keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Words, imeAction = ImeAction.Done),
modifier = Modifier.fillMaxWidth(),
)
if (notFound) {
Text(
stringResource(R.string.places_not_found),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
)
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(
onClick = {
if (SavedPlaces.hasLocationPermission(context)) {
findHere()
} else {
askLocation.launch(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION))
}
},
enabled = !finding,
) {
if (finding) {
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
} else {
Icon(Icons.Filled.LocationOn, contentDescription = null, modifier = Modifier.size(18.dp))
}
Spacer(Modifier.size(8.dp))
Text(stringResource(if (finding) R.string.places_finding else R.string.places_here))
}
if (address.isNotBlank() || label.isNotBlank()) {
TextButton(onClick = { label = ""; address = ""; notFound = false; save() }) {
Text(stringResource(R.string.places_clear))
}
}
}
}
}
}
/** Material's "work" briefcase, which only ships in the extended icon set. */
private val Briefcase: ImageVector by lazy {
materialIcon("Filled.Work") {
materialPath {
moveTo(20f, 6f); horizontalLineToRelative(-4f); verticalLineTo(4f)
curveToRelative(0f, -1.11f, -0.89f, -2f, -2f, -2f); horizontalLineToRelative(-4f)
curveTo(8.89f, 2f, 8f, 2.89f, 8f, 4f); verticalLineToRelative(2f); horizontalLineTo(4f)
curveToRelative(-1.11f, 0f, -1.99f, 0.89f, -1.99f, 2f); lineTo(2f, 19f)
curveToRelative(0f, 1.11f, 0.89f, 2f, 2f, 2f); horizontalLineToRelative(16f)
curveToRelative(1.11f, 0f, 2f, -0.89f, 2f, -2f); verticalLineTo(8f)
curveToRelative(0f, -1.11f, -0.89f, -2f, -2f, -2f); close()
moveTo(14f, 6f); horizontalLineToRelative(-4f); verticalLineTo(4f); horizontalLineToRelative(4f)
verticalLineToRelative(2f); close()
}
}
}