Gearslip apps: apps written for Gearslip's own protocol show in the launcher, and Gearslip draws their lists, grids, panes and messages with its own car keyboard, car info and music controls

This commit is contained in:
Seb3thehacker committed 2026-11-29 21:55:23 -08:00
1 parent 8c73aa83bd
commit fb865d98e4
16 files changed
+900 -7

No files matched your search

+20 -5
View File
@@ -254,7 +254,7 @@ Gearslip drops these altogether:
## Gearslip apps
This section specifies protocol version 1. Gearslip does not yet implement it.
This section specifies protocol version 1.
A Gearslip app describes a screen and lets Gearslip render it in Compose, using the car's theme,
the driver's chosen scale and the current day or night state. Your app draws nothing and receives
@@ -293,8 +293,20 @@ no state that a rebind cannot rebuild.
### The interface
Copy these three files into `src/main/aidl/app/seb3thehacker/gearslip/api/`. A published artifact
will replace them.
The [Gearslip SDK](https://github.com/twinksoftware/gearslip-sdk) holds these three files, a base
service that answers the handshake, and builders for the screen model. It is licensed under
Apache-2.0, so a closed-source app can use it too. Add it from JitPack:
```kotlin
// settings.gradle.kts: repositories { maven("https://jitpack.io") }
implementation("com.github.twinksoftware:gearslip-sdk:1.0.0")
```
Then extend `GearslipAppService` and return a screen from `onGetScreen`. The SDK's sample app
uses every part of version 1.
To write the binder side yourself, copy these files into
`src/main/aidl/app/seb3thehacker/gearslip/api/`.
```aidl
// IGearslipApp.aidl
@@ -414,8 +426,9 @@ actions and emphasises the primary one.
`check`, `error`. Version 1 carries no images. Gearslip drops an unknown name and renders the
row without a glyph.
Gearslip truncates any list past the limits in [Content limits](#content-limits) and shortens
long strings. Send a screen that fits, rather than one Gearslip has to cut.
Gearslip shows at most 12 items, or 4 in a pane, and cuts the rest. It shortens a title past 80
characters, a subtitle past 120, and a message past 500, and it ignores an answer larger than
64 KB. Send a screen that fits, rather than one Gearslip has to cut.
### Reading the car
@@ -450,6 +463,8 @@ stale or missing, which includes tunnels and car parks.
{ "title": "Sleepwalk", "artist": "Santo & Johnny", "playing": true, "durationMs": 142000 }
```
It returns `{}` when nothing is playing.
`mediaCommand` sends one of `play`, `pause`, `toggle`, `next` or `previous` to that app. Both
work regardless of which app is playing, so use them to put transport controls on your own
screen. Ship audio through a media app instead of driving these.
+2
View File
@@ -208,6 +208,8 @@ dependencies {
// Lottie, Apache 2.0: plays the animated Meteocons weather icons in assets/meteocons (MIT).
implementation(libs.lottie.compose)
testImplementation(libs.junit)
// Android's own org.json is a stub in unit tests; the real one parses Gearslip app screens there.
testImplementation(libs.org.json)
}
tasks.withType<KotlinJvmCompile>().configureEach {
+4
View File
@@ -108,6 +108,10 @@
them away (UsageStats.osName). -->
<package android:name="app.grapheneos.setupwizard" />
<package android:name="foundation.e.apps" />
<!-- Apps written for Gearslip's own app protocol (docs/BUILDING_APPS.md, "Gearslip apps"). -->
<intent>
<action android:name="app.seb3thehacker.gearslip.APP" />
</intent>
<intent>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@@ -0,0 +1,20 @@
// IGearslipApp.aidl
package app.seb3thehacker.gearslip.api;
import app.seb3thehacker.gearslip.api.IGearslipHost;
import app.seb3thehacker.gearslip.api.IScreenCallback;
interface IGearslipApp {
/** Return the highest version both sides speak. Gearslip passes the version it offers. */
int negotiate(int hostVersion);
void onCreate(IGearslipHost host);
void onStart();
void onStop();
/** Describe the current screen. Answer through the callback, on any thread. */
void getScreen(IScreenCallback callback);
void onAction(String actionId);
void onTextInput(String fieldId, String text);
}
@@ -0,0 +1,19 @@
// IGearslipHost.aidl
package app.seb3thehacker.gearslip.api;
interface IGearslipHost {
/** Tell Gearslip the screen changed. It calls getScreen again. */
void invalidate();
/** Open the car keyboard. The result arrives at onTextInput. */
void requestTextInput(String fieldId, String prompt, String initialText);
String getEnvironment();
String getNowPlaying();
/** One of play, pause, toggle, next, previous. */
void mediaCommand(String command);
/** Leave the app and return to the launcher. */
void finish();
}
@@ -0,0 +1,7 @@
// IScreenCallback.aidl
package app.seb3thehacker.gearslip.api;
interface IScreenCallback {
void onScreen(String screenJson);
void onError(String message);
}
@@ -44,7 +44,7 @@ object CarApps {
},
)
fun find(id: String): CarApp? = all.firstOrNull { it.id == id } ?: nativeApp(id)
fun find(id: String): CarApp? = all.firstOrNull { it.id == id } ?: nativeApp(id) ?: gearslipApp(id)
/** A phone app shown through Shizuku, known by [NATIVE_APP_PREFIX] and its package (issue #124). */
private fun nativeApp(id: String): CarApp? {
@@ -53,6 +53,14 @@ object CarApps {
return CarApp(id, label, 0, Icons.Filled.Share) { NativePhoneAppScreen(pkg) }
}
/** An app that speaks the Gearslip app protocol, known by [GEARSLIP_APP_PREFIX] and its service. */
private fun gearslipApp(id: String): CarApp? {
if (!id.startsWith(GEARSLIP_APP_PREFIX)) return null
val component = android.content.ComponentName.unflattenFromString(id.removePrefix(GEARSLIP_APP_PREFIX)) ?: return null
val label = LauncherCache.entries?.firstOrNull { it.componentId == id }?.label ?: component.packageName
return CarApp(id, label, 0, Icons.Filled.Share) { GearslipAppScreen(component, label) }
}
/** The screens [BuiltInApps.entries] offers here, so a choice list never names a hidden one. */
fun shown(launcher: Boolean, canCall: Boolean): List<CarApp> {
val ids = BuiltInApps.entries(launcher, canCall).mapNotNull { (it.builtIn?.screen as? CarScreen.App)?.id }.toSet()
@@ -99,15 +99,19 @@ internal class Entry(
val media: MediaApp? = null,
val builtIn: BuiltInApp? = null,
val messaging: MessagingApp? = null,
/** An app that speaks the Gearslip app protocol rather than Android Auto's. */
val gearslip: app.seb3thehacker.gearslip.host.GearslipAppInfo? = null,
) {
/** What a pin or a nav-bar shortcut remembers this entry as; null for nothing pinnable. */
val componentId: String?
get() = builtIn?.let { BUILT_IN_PREFIX + it.id }
?: messaging?.let { MESSAGING_PREFIX + it.packageName }
?: gearslip?.let { GEARSLIP_APP_PREFIX + it.component.flattenToString() }
?: (template?.component ?: media?.component)?.flattenToString()
val packageName: String?
get() = template?.component?.packageName ?: media?.component?.packageName ?: messaging?.packageName
?: gearslip?.component?.packageName
}
/** A messaging app has no component of its own to open, so its pin carries the package instead. */
@@ -150,11 +154,16 @@ internal object LauncherCache {
}
}
}
// Apps written for Gearslip itself: one tile per service, under the name it chose.
val gearslipApps = app.seb3thehacker.gearslip.host.GearslipAppCatalog.installed(context).map { app ->
val icon = app.icon?.let { runCatching { it.toBitmap(128, 128).asImageBitmap() }.getOrNull() }
Entry(app.label, icon, gearslip = app)
}
CarSettings.hideOnFirstSight(tiles.mapNotNull { entry ->
val pkg = (entry.template?.component ?: entry.media?.component)?.packageName ?: entry.messaging?.packageName
entry.componentId?.takeIf { pkg != null && KnownApps.startsHidden(context, pkg, entry.messaging != null) }
})
return tiles.sortedBy { it.label.lowercase() }.also { flow.value = it }
return (tiles + gearslipApps).sortedBy { it.label.lowercase() }.also { flow.value = it }
}
}
@@ -284,6 +293,7 @@ internal fun launchEntry(entry: Entry, navigator: CarNavigator, frame: CarEnviro
}
entry.media?.let { CarServices.openMedia(it); navigator.media() }
entry.messaging?.let { navigator.messages(it.packageName, it.label) }
entry.componentId?.takeIf { entry.gearslip != null }?.let { navigator.open(it) }
}
/** The app launcher: every app as an icon grid, grouped Phone, Maps, Music, Messaging, Web, Screen sharing, Settings. */
@@ -0,0 +1,310 @@
package app.seb3thehacker.gearslip.car
import android.content.ComponentName
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.Place
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import app.seb3thehacker.gearslip.R
import app.seb3thehacker.gearslip.car.theme.GsButton
import app.seb3thehacker.gearslip.car.theme.GsColors
import app.seb3thehacker.gearslip.car.theme.GsIconBox
import app.seb3thehacker.gearslip.car.theme.GsTone
import app.seb3thehacker.gearslip.host.GearslipAppSession
import app.seb3thehacker.gearslip.host.GearslipScreen
/** A Gearslip app's id on the launcher and the trail: this prefix and its service's component. */
internal const val GEARSLIP_APP_PREFIX = "gsapp:"
/**
* An app that speaks the Gearslip app protocol, drawn from the screens it describes. The app is
* bound while this is on screen and let go when the driver leaves, as docs/BUILDING_APPS.md says.
*/
@Composable
fun GearslipAppScreen(component: ComponentName, label: String) {
val context = LocalContext.current
val navigator = LocalCarNavigator.current
// A fresh session each time the screen opens; [GearslipAppSession.stop] can't be undone.
val session = remember(component) { GearslipAppSession(context, component) }
DisposableEffect(session) {
session.start()
onDispose { session.stop() }
}
val state by session.state.collectAsState()
val screen by session.screen.collectAsState()
val asked by session.textRequest.collectAsState()
LaunchedEffect(state) { if (state == GearslipAppSession.State.Finished) navigator.back() }
// The field being typed into: one the app asked for, or an input row the driver tapped.
var typing by remember { mutableStateOf<GearslipAppSession.TextRequest?>(null) }
LaunchedEffect(asked) { asked?.let { typing = it } }
fun closeKeyboard() {
typing = null
session.closeKeyboard()
}
// A tapped field's keyboard goes when the app moves to a screen without that field. One the
// app asked for through requestTextInput stays until the driver closes it.
LaunchedEffect(screen) {
val field = typing ?: return@LaunchedEffect
if (field != asked && screen?.items?.none { it.input && it.id == field.fieldId } == true) closeKeyboard()
}
Column(Modifier.fillMaxSize()) {
Column(Modifier.weight(1f).padding(start = 24.dp, end = 24.dp, top = 16.dp)) {
val shown = screen
ScreenHeader(shown?.title?.ifEmpty { null } ?: label) {
if (shown != null && shown.type != GearslipScreen.Type.PANE && shown.type != GearslipScreen.Type.MESSAGE) {
shown.actions.forEach { AppAction(it, compact = true) { session.action(it.id) } }
}
}
Spacer(Modifier.height(8.dp))
Box(Modifier.fillMaxSize()) {
when {
state is GearslipAppSession.State.Failed ->
Problem((state as GearslipAppSession.State.Failed).reason, label)
shown == null -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
else -> AppContent(shown, session::action) { item ->
typing = GearslipAppSession.TextRequest(item.id, item.title, item.value)
}
}
}
}
typing?.let { field ->
var text by remember(field) { mutableStateOf(field.text) }
Row(
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
SearchField(text, field.prompt, Modifier.weight(1f), onClear = {
text = ""
session.textInput(field.fieldId, "")
}, searchIcon = false)
}
CarKeyboard(
text = text,
onTextChange = {
text = it.take(GearslipScreen.MAX_VALUE)
session.textInput(field.fieldId, text)
},
onSubmit = ::closeKeyboard,
submitIcon = false,
submitImage = Icons.Filled.Check,
onDismiss = ::closeKeyboard,
)
}
}
}
@Composable
private fun AppContent(
screen: GearslipScreen,
onAction: (String) -> Unit,
onInput: (GearslipScreen.Item) -> Unit,
) {
fun tap(item: GearslipScreen.Item) = if (item.input) onInput(item) else onAction(item.id)
when (screen.type) {
GearslipScreen.Type.LIST -> LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(bottom = 8.dp)) {
items(screen.items, key = { it.id }) { item ->
AppRow(item, item.value) { tap(item) }
}
}
GearslipScreen.Type.GRID -> LazyVerticalGrid(
columns = GridCells.Adaptive(120.dp),
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(bottom = 8.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
items(screen.items, key = { it.id }) { item -> AppTile(item) { tap(item) } }
}
GearslipScreen.Type.PANE -> Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(16.dp)) {
Column(Modifier.weight(1f)) {
screen.items.forEach { item -> AppRow(item, item.value, large = true) { tap(item) } }
}
if (screen.actions.isNotEmpty()) {
Column(Modifier.widthIn(min = 160.dp, max = 240.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
screen.actions.forEach { AppAction(it, Modifier.fillMaxWidth()) { onAction(it.id) } }
}
}
}
GearslipScreen.Type.MESSAGE -> Column(
Modifier.fillMaxSize().padding(horizontal = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(20.dp, Alignment.CenterVertically),
) {
Text(screen.text, style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center, maxLines = 6, overflow = TextOverflow.Ellipsis)
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
screen.actions.forEach { AppAction(it) { onAction(it.id) } }
}
}
}
}
/** One row, drawn like a templated app's list row. An input row shows its text, or its subtitle as a hint. */
@Composable
private fun AppRow(item: GearslipScreen.Item, value: String?, large: Boolean = false, onClick: () -> Unit) {
val clickable = item.enabled
Row(
Modifier
.fillMaxWidth()
.let { if (clickable) it.clickable(onClick = onClick) else it.alpha(0.5f) }
.padding(horizontal = 14.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
item.icon?.vector()?.let {
Icon(it, contentDescription = null, Modifier.size(28.dp))
Spacer(Modifier.width(12.dp))
}
Column(Modifier.weight(1f)) {
Text(item.title, style = ChromeType.title, maxLines = if (large) 2 else 1, overflow = TextOverflow.Ellipsis)
val second = if (item.input) value?.ifEmpty { null } ?: item.subtitle else item.subtitle
if (second.isNotEmpty()) {
Text(
second,
style = ChromeType.body,
color = if (item.input && !value.isNullOrEmpty()) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = if (large) 2 else 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
@Composable
private fun AppTile(item: GearslipScreen.Item, onClick: () -> Unit) {
val scheme = MaterialTheme.colorScheme
GsIconBox(
onClick = onClick,
modifier = Modifier.height(120.dp),
colors = GsColors(scheme.surfaceVariant, scheme.onSurfaceVariant),
enabled = item.enabled,
shape = MaterialTheme.shapes.extraLarge,
) {
Column(
Modifier.fillMaxSize().padding(8.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
item.icon?.vector()?.let {
Icon(it, contentDescription = null, Modifier.size(44.dp))
Spacer(Modifier.height(8.dp))
}
Text(item.title, style = ChromeType.label, textAlign = TextAlign.Center, maxLines = 2, overflow = TextOverflow.Ellipsis)
if (item.subtitle.isNotEmpty()) {
Text(item.subtitle, style = ChromeType.label, color = scheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
}
/** An app's action: filled when it's the primary one. [compact] is the header's size. */
@Composable
private fun AppAction(action: GearslipScreen.Action, modifier: Modifier = Modifier, compact: Boolean = false, onClick: () -> Unit) {
GsButton(
onClick = onClick,
modifier = modifier,
tone = if (action.primary) GsTone.Primary else GsTone.Neutral,
contentPadding = if (compact) PaddingValues(horizontal = 16.dp, vertical = 8.dp) else PaddingValues(horizontal = 24.dp, vertical = 14.dp),
) {
action.icon?.vector()?.let {
Icon(it, contentDescription = null, Modifier.size(20.dp))
Spacer(Modifier.width(8.dp))
}
Text(action.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
/** Why the app isn't on screen, with a way back. */
@Composable
private fun Problem(reason: GearslipAppSession.Reason, label: String) {
val navigator = LocalCarNavigator.current
val text = when (reason) {
GearslipAppSession.Reason.NO_SERVICE -> stringResource(R.string.gsapp_no_service, label)
GearslipAppSession.Reason.NEWER_VERSION -> stringResource(R.string.gsapp_newer, label)
GearslipAppSession.Reason.CRASHED -> stringResource(R.string.gsapp_crashed, label)
GearslipAppSession.Reason.NOT_ANSWERING -> stringResource(R.string.gsapp_not_answering, label)
GearslipAppSession.Reason.BAD_SCREEN -> stringResource(R.string.gsapp_bad_screen, label)
}
Column(
Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(20.dp, Alignment.CenterVertically),
) {
Icon(Icons.Filled.Warning, contentDescription = null, Modifier.size(40.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant)
Text(text, style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center)
GsButton(onClick = navigator::back, tone = GsTone.Neutral) { Text(stringResource(R.string.back)) }
}
}
private fun GearslipScreen.Glyph.vector(): ImageVector = when (this) {
GearslipScreen.Glyph.PLAY -> Icons.Filled.PlayArrow
GearslipScreen.Glyph.PAUSE -> MediaIcons.Pause
GearslipScreen.Glyph.NEXT -> MediaIcons.Next
GearslipScreen.Glyph.PREVIOUS -> MediaIcons.Previous
GearslipScreen.Glyph.SEARCH -> Icons.Filled.Search
GearslipScreen.Glyph.SETTINGS -> Icons.Filled.Settings
GearslipScreen.Glyph.HOME -> Icons.Filled.Home
GearslipScreen.Glyph.APPS -> MediaIcons.Apps
GearslipScreen.Glyph.NOTIFICATIONS -> Icons.Filled.Notifications
GearslipScreen.Glyph.INFO -> Icons.Filled.Info
GearslipScreen.Glyph.SHARE -> Icons.Filled.Share
GearslipScreen.Glyph.PLACE -> Icons.Filled.Place
GearslipScreen.Glyph.FAVORITE -> Icons.Filled.Favorite
GearslipScreen.Glyph.ADD -> Icons.Filled.Add
GearslipScreen.Glyph.REMOVE -> MediaIcons.Remove
GearslipScreen.Glyph.REFRESH -> Icons.Filled.Refresh
GearslipScreen.Glyph.CHECK -> Icons.Filled.Check
GearslipScreen.Glyph.ERROR -> Icons.Filled.Warning
}
@@ -398,6 +398,8 @@ internal object MediaIcons {
val Next = icon("SkipNext", "M6,18l8.5,-6L6,6v12zM16,6v12h2V6h-2z")
/** The 3x3 app grid; not in material-icons-core. */
val Apps = icon("Apps", "M4,8h4L8,4L4,4v4zM10,20h4v-4h-4v4zM4,20h4v-4L4,16v4zM4,14h4v-4L4,10v4zM10,14h4v-4h-4v4zM16,4v4h4L20,4h-4zM10,8h4L14,4h-4v4zM16,14h4v-4h-4v4zM16,20h4v-4h-4v4z")
/** A minus sign, for an app's "remove" glyph; not in material-icons-core. */
val Remove = icon("Remove", "M19,13H5v-2h14v2z")
val Previous = icon("SkipPrevious", "M6,6h2v12L6,18zM9.5,12l8.5,6V6z")
val Equalizer = icon("Equalizer", "M10,20h4L14,4h-4v16zM4,20h4v-8L4,12v8zM16,9v11h4L20,9h-4z")
val Shuffle = icon("Shuffle", "M10.59,9.17L5.41,4 4,5.41l5.17,5.17 1.42,-1.41zM14.5,4l2.04,2.04L4,18.59 5.41,20 17.96,7.46 20,9.5L20,4h-5.5zM14.83,13.41l-1.41,1.41 3.13,3.13L14.5,20L20,20v-5.5l-2.04,2.04 -3.13,-3.13z")
@@ -0,0 +1,273 @@
package app.seb3thehacker.gearslip.host
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import app.seb3thehacker.gearslip.api.IGearslipApp
import app.seb3thehacker.gearslip.api.IGearslipHost
import app.seb3thehacker.gearslip.api.IScreenCallback
import app.seb3thehacker.gearslip.car.CarEnvironment
import app.seb3thehacker.gearslip.car.CarServices
import app.seb3thehacker.gearslip.notify.CarMotion
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.json.JSONObject
/** An installed app that speaks the Gearslip app protocol (docs/BUILDING_APPS.md, "Gearslip apps"). */
class GearslipAppInfo(val component: ComponentName, val label: String, val icon: Drawable?)
/** Finds the services that declare the Gearslip app action and a version Gearslip speaks. */
object GearslipAppCatalog {
const val ACTION = "app.seb3thehacker.gearslip.APP"
private const val META_VERSION = "app.seb3thehacker.gearslip.version"
private const val META_LABEL = "app.seb3thehacker.gearslip.label"
private const val META_ICON = "app.seb3thehacker.gearslip.icon"
fun installed(context: Context): List<GearslipAppInfo> {
val pm = context.packageManager
val found = runCatching {
pm.queryIntentServices(Intent(ACTION), PackageManager.ResolveInfoFlags.of(PackageManager.GET_META_DATA.toLong()))
}.getOrDefault(emptyList())
return found.mapNotNull { info ->
val service = info.serviceInfo ?: return@mapNotNull null
if (!service.exported || service.packageName == context.packageName) return@mapNotNull null
val meta = service.metaData
// android:value="1" arrives as an Int; a string "1" is taken too.
val version = meta?.get(META_VERSION)?.toString()?.toIntOrNull() ?: return@mapNotNull null
if (version < 1) return@mapNotNull null
val app = service.applicationInfo
val res by lazy { runCatching { pm.getResourcesForApplication(app) }.getOrNull() }
val label = meta.get(META_LABEL)?.let { value ->
when (value) {
is Int -> runCatching { res?.getString(value) }.getOrNull()
else -> value.toString()
}
}?.trim()?.takeIf { it.isNotEmpty() }?.take(40) ?: app.loadLabel(pm).toString()
val iconRes = meta.getInt(META_ICON, 0)
val icon = (if (iconRes != 0) runCatching { pm.getDrawable(service.packageName, iconRes, app) }.getOrNull() else null)
?: runCatching { app.loadIcon(pm) }.getOrNull()
GearslipAppInfo(ComponentName(service.packageName, service.name), label, icon)
}.distinctBy { it.component }
}
}
/**
* One open Gearslip app: binds its service, negotiates, and keeps the screen it last described.
*
* Every call into the app runs on one worker thread, in order, since a slow app blocks the call
* that reached it. The app's calls back to Gearslip arrive on binder threads and only post state;
* after [stop] they do nothing, so an app that kept the host interface can't reach Gearslip
* again until the driver opens it again.
*/
class GearslipAppSession(context: Context, val component: ComponentName) {
sealed interface State {
data object Connecting : State
data object Ready : State
/** The app left on its own (finish) or the driver can't use it; [reason] names which. */
data class Failed(val reason: Reason) : State
data object Finished : State
}
enum class Reason { NO_SERVICE, NEWER_VERSION, CRASHED, NOT_ANSWERING, BAD_SCREEN }
/** The car keyboard the app asked for. */
data class TextRequest(val fieldId: String, val prompt: String, val text: String)
private val context = context.applicationContext
private val worker = Executors.newSingleThreadExecutor { Thread(it, "gearslip-app").apply { isDaemon = true } }
private val main = Handler(Looper.getMainLooper())
private val alive = AtomicBoolean(true)
private val refreshQueued = AtomicBoolean(false)
private val request = AtomicInteger(0)
@Volatile private var app: IGearslipApp? = null
@Volatile private var bound = false
private val stateFlow = MutableStateFlow<State>(State.Connecting)
val state: StateFlow<State> = stateFlow
private val screenFlow = MutableStateFlow<GearslipScreen?>(null)
val screen: StateFlow<GearslipScreen?> = screenFlow
private val textFlow = MutableStateFlow<TextRequest?>(null)
val textRequest: StateFlow<TextRequest?> = textFlow
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
val remote = IGearslipApp.Stub.asInterface(binder)
runCatching { binder.linkToDeath({ fail(Reason.CRASHED) }, 0) }
worker.execute { begin(remote) }
}
override fun onServiceDisconnected(name: ComponentName) = fail(Reason.CRASHED)
override fun onBindingDied(name: ComponentName) = fail(Reason.CRASHED)
override fun onNullBinding(name: ComponentName) = fail(Reason.NO_SERVICE)
}
fun start() {
val intent = Intent(GearslipAppCatalog.ACTION).setComponent(component)
bound = runCatching { context.bindService(intent, connection, Context.BIND_AUTO_CREATE) }.getOrDefault(false)
if (!bound) fail(Reason.NO_SERVICE)
// A first screen that never comes gets a message instead of an endless spinner.
main.postDelayed({ if (alive.get() && screenFlow.value == null && stateFlow.value !is State.Failed) fail(Reason.NOT_ANSWERING) }, ANSWER_MS)
}
/** Tells the app it's leaving and lets go of it. Safe to call twice. */
fun stop() {
if (!alive.getAndSet(false)) return
main.removeCallbacksAndMessages(null)
worker.execute {
app?.let { a -> call("onStop") { a.onStop() } }
app = null
main.post { if (bound) runCatching { context.unbindService(connection) }; bound = false }
}
worker.shutdown()
}
fun action(id: String) = send("onAction") { it.onAction(id) }
fun textInput(fieldId: String, text: String) = send("onTextInput") { it.onTextInput(fieldId, text) }
fun closeKeyboard() { textFlow.value = null }
private fun begin(remote: IGearslipApp) {
if (!alive.get()) return
val version = call("negotiate") { remote.negotiate(GearslipScreen.PROTOCOL) } ?: return fail(Reason.CRASHED)
if (version != GearslipScreen.PROTOCOL) return fail(Reason.NEWER_VERSION)
app = remote
call("onCreate") { remote.onCreate(host) } ?: return fail(Reason.CRASHED)
call("onStart") { remote.onStart() } ?: return fail(Reason.CRASHED)
stateFlow.value = State.Ready
refresh()
}
/** Asks for the screen again; repeated asks before the worker gets to it count once. */
private fun refresh() {
if (!alive.get() || !refreshQueued.compareAndSet(false, true)) return
runCatching { worker.execute(::askForScreen) }
}
private fun askForScreen() {
run {
refreshQueued.set(false)
val remote = app ?: return
val mine = request.incrementAndGet()
call("getScreen") {
remote.getScreen(object : IScreenCallback.Stub() {
override fun onScreen(screenJson: String?) {
// An answer to an older ask, overtaken by a newer one, is dropped.
if (!alive.get() || mine != request.get()) return
val parsed = GearslipScreen.parse(screenJson)
if (parsed == null) {
Log.w(TAG, "${component.packageName} sent a screen Gearslip can't read")
if (screenFlow.value == null) fail(Reason.BAD_SCREEN)
return
}
screenFlow.value = parsed
}
override fun onError(message: String?) {
if (!alive.get()) return
Log.w(TAG, "${component.packageName} couldn't describe its screen: ${message?.take(200)}")
if (screenFlow.value == null) fail(Reason.BAD_SCREEN)
}
})
}
}
}
private fun send(what: String, block: (IGearslipApp) -> Unit) {
if (!alive.get()) return
runCatching { worker.execute { app?.let { a -> call(what) { block(a) } } } }
}
/** One call into the app; null when it threw, which a dead app's binder does. */
private fun <T> call(what: String, block: () -> T): T? = try {
block()
} catch (e: Exception) {
Log.w(TAG, "${component.packageName} $what failed: ${e.javaClass.simpleName}")
null
}
private fun fail(reason: Reason) {
if (!alive.get() || stateFlow.value == State.Finished) return
stateFlow.value = State.Failed(reason)
}
private val host = object : IGearslipHost.Stub() {
override fun invalidate() = refresh()
override fun requestTextInput(fieldId: String?, prompt: String?, initialText: String?) {
if (!alive.get() || fieldId.isNullOrEmpty()) return
textFlow.value = TextRequest(
fieldId.take(GearslipScreen.MAX_ID),
prompt.orEmpty().take(GearslipScreen.MAX_TITLE),
initialText.orEmpty().take(GearslipScreen.MAX_VALUE),
)
}
override fun getEnvironment(): String = if (!alive.get()) "{}" else environment()
override fun getNowPlaying(): String {
if (!alive.get()) return "{}"
val now = CarServices.mediaOrNull()?.now?.value ?: return "{}"
if (!now.hasTrack) return "{}"
return JSONObject()
.put("title", now.title)
.put("artist", now.artist)
.put("playing", now.playing)
.put("durationMs", now.durationMs)
.toString()
}
override fun mediaCommand(command: String?) {
if (!alive.get()) return
main.post {
val media = CarServices.mediaOrNull() ?: return@post
when (command) {
"play" -> media.play()
"pause" -> media.pause()
"toggle" -> media.togglePlay()
"next" -> media.next()
"previous" -> media.previous()
}
}
}
override fun finish() {
if (alive.get()) stateFlow.value = State.Finished
}
}
companion object {
private const val TAG = "GearslipApp"
private const val ANSWER_MS = 10_000L
/** The car's state for getEnvironment, in the shape the doc gives. */
fun environment(): String {
val frame = CarEnvironment.frame.value
val battery = CarEnvironment.battery.value
return JSONObject()
.put("protocol", GearslipScreen.PROTOCOL)
.put("darkOutside", CarEnvironment.darkOutside.value)
.put("moving", CarMotion.moving)
.put("frameWidth", frame.width)
.put("frameHeight", frame.height)
.put("densityDpi", frame.densityDpi)
.put("batteryPercent", battery.percent)
.put("charging", battery.charging)
.put("vehicle", CarEnvironment.vehicle.value)
.toString()
}
}
}
@@ -0,0 +1,134 @@
package app.seb3thehacker.gearslip.host
import org.json.JSONArray
import org.json.JSONObject
/**
* One screen a Gearslip app described, as docs/BUILDING_APPS.md ("The screen model") specifies.
* Built only through [parse], which trims the app's answer to what the car UI can show, so the
* renderer never has to second-guess it.
*/
data class GearslipScreen(
val type: Type,
val title: String,
val items: List<Item>,
val actions: List<Action>,
val text: String,
) {
enum class Type { LIST, GRID, PANE, MESSAGE }
data class Item(
val id: String,
val title: String,
val subtitle: String,
val icon: Glyph?,
val enabled: Boolean,
/** A text field: tapping it opens the car keyboard, and [value] is what it holds. */
val input: Boolean,
val value: String,
)
data class Action(val id: String, val title: String, val icon: Glyph?, val primary: Boolean)
/** The built-in glyphs an app may name. Anything else is dropped. */
enum class Glyph(val wire: String) {
PLAY("play"), PAUSE("pause"), NEXT("next"), PREVIOUS("previous"), SEARCH("search"),
SETTINGS("settings"), HOME("home"), APPS("apps"), NOTIFICATIONS("notifications"),
INFO("info"), SHARE("share"), PLACE("place"), FAVORITE("favorite"), ADD("add"),
REMOVE("remove"), REFRESH("refresh"), CHECK("check"), ERROR("error");
companion object {
private val byWire = entries.associateBy { it.wire }
fun of(name: String?): Glyph? = name?.let { byWire[it] }
}
}
companion object {
/** The version of the protocol this file speaks. */
const val PROTOCOL = 1
/** Rows in a list or tiles in a grid, as [Content limits] in the doc. */
const val MAX_ITEMS = 12
const val MAX_PANE_ITEMS = 4
const val MAX_ACTIONS = 2
const val MAX_ID = 64
const val MAX_TITLE = 80
const val MAX_SUBTITLE = 120
const val MAX_TEXT = 500
const val MAX_VALUE = 300
/** The most JSON Gearslip reads from one answer; a bigger one is refused, not parsed. */
const val MAX_JSON = 64 * 1024
/**
* The screen in [json], or null when it isn't one: not an object, an unknown type, a
* protocol other than [PROTOCOL], or too big. Long lists and strings are cut, items
* without an id or a title are left out, and so are repeated ids.
*/
fun parse(json: String?): GearslipScreen? {
if (json == null || json.length > MAX_JSON) return null
val root = runCatching { JSONObject(json) }.getOrNull() ?: return null
if (root.optInt("protocol", PROTOCOL) != PROTOCOL) return null
val type = when (root.optString("type")) {
"list" -> Type.LIST
"grid" -> Type.GRID
"pane" -> Type.PANE
"message" -> Type.MESSAGE
else -> return null
}
val limit = if (type == Type.PANE) MAX_PANE_ITEMS else MAX_ITEMS
val items = if (type == Type.MESSAGE) emptyList() else items(root.optJSONArray("items"), limit)
return GearslipScreen(
type = type,
title = root.text("title", MAX_TITLE),
items = items,
actions = actions(root.optJSONArray("actions")),
text = if (type == Type.MESSAGE) root.text("text", MAX_TEXT) else "",
)
}
private fun items(array: JSONArray?, limit: Int): List<Item> {
val seen = HashSet<String>()
return objects(array).mapNotNull { o ->
val id = o.text("id", MAX_ID)
val title = o.text("title", MAX_TITLE)
if (id.isEmpty() || title.isEmpty() || !seen.add(id)) return@mapNotNull null
Item(
id = id,
title = title,
subtitle = o.text("subtitle", MAX_SUBTITLE),
icon = Glyph.of(o.optString("icon").takeIf { it.isNotEmpty() }),
enabled = o.optBoolean("enabled", true),
input = o.optString("type") == "input",
value = o.text("value", MAX_VALUE),
)
}.take(limit)
}
private fun actions(array: JSONArray?): List<Action> {
val seen = HashSet<String>()
val all = objects(array).mapNotNull { o ->
val id = o.text("id", MAX_ID)
val title = o.text("title", MAX_TITLE)
if (id.isEmpty() || title.isEmpty() || !seen.add(id)) return@mapNotNull null
Action(id, title, Glyph.of(o.optString("icon").takeIf { it.isNotEmpty() }), o.optBoolean("primary", false))
}.take(MAX_ACTIONS)
// One primary at most: the first one the app marked.
val primary = all.indexOfFirst { it.primary }
return all.mapIndexed { i, a -> if (a.primary && i != primary) a.copy(primary = false) else a }
}
private fun objects(array: JSONArray?): List<JSONObject> {
if (array == null) return emptyList()
// A page of rows at most is read; the rest would be cut anyway.
return (0 until minOf(array.length(), MAX_ITEMS * 4)).mapNotNull { array.optJSONObject(it) }
}
/** A string field, trimmed and cut to [max] characters; empty when missing or not a string. */
private fun JSONObject.text(name: String, max: Int): String {
val value = opt(name) as? String ?: return ""
val clean = value.replace(Regex("[\\p{Cc}&&[^\\n]]"), "").trim()
return if (clean.length <= max) clean else clean.take(max - 1).trimEnd() + "…"
}
}
}
@@ -615,6 +615,7 @@ class CarMedia(private val context: Context) {
* as soon as the microphone let go. A real pause tells the app to stay stopped.
*/
fun pause() = controller?.transportControls?.pause()
fun play() = controller?.transportControls?.play()
fun next() = controller?.transportControls?.skipToNext()
fun previous() = controller?.transportControls?.skipToPrevious()
fun seek(ms: Long) = controller?.transportControls?.seekTo(ms)
+6
View File
@@ -1112,4 +1112,10 @@
<string name="cert_link_again">Download again</string>
<string name="cert_link_done">Downloaded and converted. It\'s used from the next connection.</string>
<string name="cert_link_failed">Couldn\'t use it. %1$s</string>
<!-- An app written for Gearslip's own app protocol couldn't be shown. %1$s is the app's name. -->
<string name="gsapp_no_service">%1$s didn\'t start.</string>
<string name="gsapp_newer">%1$s needs a newer Gearslip.</string>
<string name="gsapp_crashed">%1$s stopped.</string>
<string name="gsapp_not_answering">%1$s isn\'t answering.</string>
<string name="gsapp_bad_screen">%1$s sent a screen Gearslip can\'t show.</string>
</resources>
@@ -0,0 +1,80 @@
package app.seb3thehacker.gearslip
import app.seb3thehacker.gearslip.host.GearslipScreen
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class GearslipScreenTest {
@Test
fun readsTheDocsExample() {
val screen = GearslipScreen.parse(
"""
{"protocol":1,"type":"list","title":"Stations","items":[
{"id":"r6","title":"BBC Radio 6","subtitle":"Music","icon":"play"},
{"id":"r4","title":"BBC Radio 4","subtitle":"Speech","icon":"play"}],
"actions":[{"id":"refresh","title":"Refresh","icon":"refresh","primary":true}]}
""",
)!!
assertEquals(GearslipScreen.Type.LIST, screen.type)
assertEquals("Stations", screen.title)
assertEquals(listOf("r6", "r4"), screen.items.map { it.id })
assertEquals(GearslipScreen.Glyph.PLAY, screen.items[0].icon)
assertTrue(screen.actions.single().primary)
}
@Test
fun refusesWhatIsNotAScreen() {
assertNull(GearslipScreen.parse(null))
assertNull(GearslipScreen.parse("not json"))
assertNull(GearslipScreen.parse("""{"type":"carousel"}"""))
assertNull(GearslipScreen.parse("""{"protocol":2,"type":"list"}"""))
assertNull(GearslipScreen.parse("{\"type\":\"list\",\"title\":\"" + "x".repeat(GearslipScreen.MAX_JSON) + "\"}"))
}
@Test
fun cutsToTheLimits() {
val rows = (1..30).joinToString(",") { """{"id":"$it","title":"Row $it"}""" }
val actions = (1..5).joinToString(",") { """{"id":"a$it","title":"A $it","primary":true}""" }
val list = GearslipScreen.parse("""{"type":"list","items":[$rows],"actions":[$actions]}""")!!
assertEquals(GearslipScreen.MAX_ITEMS, list.items.size)
assertEquals(GearslipScreen.MAX_ACTIONS, list.actions.size)
assertEquals(1, list.actions.count { it.primary })
val pane = GearslipScreen.parse("""{"type":"pane","items":[$rows]}""")!!
assertEquals(GearslipScreen.MAX_PANE_ITEMS, pane.items.size)
val long = GearslipScreen.parse("""{"type":"list","title":"${"t".repeat(200)}"}""")!!
assertEquals(GearslipScreen.MAX_TITLE, long.title.length)
assertTrue(long.title.endsWith("…"))
}
@Test
fun dropsBadItemsAndUnknownGlyphs() {
val screen = GearslipScreen.parse(
"""{"type":"grid","items":[
{"id":"a","title":"A","icon":"rocket"},
{"id":"","title":"No id"},
{"id":"b"},
{"id":"a","title":"Again"},
{"id":"c","title":"C","enabled":false},
{"id":"q","title":"Search","type":"input","value":"jazz"}]}""",
)!!
assertEquals(listOf("a", "c", "q"), screen.items.map { it.id })
assertNull(screen.items[0].icon)
assertFalse(screen.items[1].enabled)
assertTrue(screen.items[2].input)
assertEquals("jazz", screen.items[2].value)
}
@Test
fun aMessageKeepsItsTextAndDropsItems() {
val screen = GearslipScreen.parse(
"""{"type":"message","text":"Signed out.\u0007","items":[{"id":"x","title":"X"}],"actions":[{"id":"in","title":"Sign in"}]}""",
)!!
assertEquals("Signed out.", screen.text)
assertTrue(screen.items.isEmpty())
assertEquals("in", screen.actions.single().id)
}
}
+2
View File
@@ -4,6 +4,7 @@ agp = "9.1.1"
kotlin = "2.4.0"
coreKtx = "1.19.0"
junit = "4.13.2"
orgJson = "20240303"
junitVersion = "1.3.0"
espressoCore = "3.7.0"
lifecycleRuntimeKtx = "2.10.0"
@@ -26,6 +27,7 @@ lottie = "6.7.1"
maplibre-android = { group = "org.maplibre.gl", name = "android-sdk", version.ref = "maplibre" }
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
junit = { group = "junit", name = "junit", version.ref = "junit" }
org-json = { group = "org.json", name = "json", version.ref = "orgJson" }
androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycleRuntimeKtx" }