With Shizuku, any phone app opens on the car screen at the car's own size, from a Phone apps section on the launcher

This commit is contained in:
Seb3thehacker committed 2026-11-24 00:38:46 -08:00
1 parent 24880edc9b
commit 12fee1e311
7 files changed
+404 -6

No files matched your search

@@ -1,5 +1,9 @@
package app.seb3thehacker.gearslip.shizuku; package app.seb3thehacker.gearslip.shizuku;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Surface;
// The part of Gearslip that Shizuku runs as the shell user, with the same powers as adb. // The part of Gearslip that Shizuku runs as the shell user, with the same powers as adb.
interface IShellService { interface IShellService {
// Shizuku's own transaction code for ending the service process. // Shizuku's own transaction code for ending the service process.
@@ -7,4 +11,19 @@ interface IShellService {
// Runs a shell command and returns its exit code. Only Gearslip's own fixed commands. // Runs a shell command and returns its exit code. Only Gearslip's own fixed commands.
int run(String command) = 1; int run(String command) = 1;
// A display drawn into [surface] that any app can be started on. Returns its id, or -1.
int createDisplay(in Surface surface, int width, int height, int densityDpi) = 2;
// Starts [component] (package/activity) on the display. Returns am's exit code.
int launch(String component, int displayId) = 3;
// The package whose activity is on top of the display, or null when it's empty.
String topPackage(int displayId) = 4;
oneway void injectMotion(in MotionEvent event, int displayId) = 5;
oneway void injectKey(in KeyEvent event, int displayId) = 6;
void releaseDisplay(int displayId) = 7;
} }
@@ -44,7 +44,14 @@ object CarApps {
}, },
) )
fun find(id: String): CarApp? = all.firstOrNull { it.id == id } fun find(id: String): CarApp? = all.firstOrNull { it.id == id } ?: nativeApp(id)
/** A phone app shown through Shizuku, known by [NATIVE_APP_PREFIX] and its package (issue #124). */
private fun nativeApp(id: String): CarApp? {
val pkg = id.removePrefix(NATIVE_APP_PREFIX).takeIf { id.startsWith(NATIVE_APP_PREFIX) && it.isNotEmpty() } ?: return null
val label = app.seb3thehacker.gearslip.mirror.PhoneApps.cached()?.firstOrNull { it.packageName == pkg }?.label ?: pkg
return CarApp(id, label, 0, Icons.Filled.Share) { NativePhoneAppScreen(pkg) }
}
/** The screens [BuiltInApps.entries] offers here, so a choice list never names a hidden one. */ /** The screens [BuiltInApps.entries] offers here, so a choice list never names a hidden one. */
fun shown(launcher: Boolean, canCall: Boolean): List<CarApp> { fun shown(launcher: Boolean, canCall: Boolean): List<CarApp> {
@@ -313,6 +313,9 @@ fun CarLauncher() {
val appOrder by CarSettings.appOrder.collectAsState() val appOrder by CarSettings.appOrder.collectAsState()
val hidden by CarSettings.hiddenApps.collectAsState() val hidden by CarSettings.hiddenApps.collectAsState()
val tiles = launcherOrder(all, showVehicleData, appOrder, hidden).map(::tileOf) val tiles = launcherOrder(all, showVehicleData, appOrder, hidden).map(::tileOf)
val shizukuReady = app.seb3thehacker.gearslip.shizuku.ShizukuSetup.state.collectAsState().value ==
app.seb3thehacker.gearslip.shizuku.ShizukuSetup.State.READY
val phoneApps = rememberPhoneApps(shizukuReady)
// With the knob, the first move on this screen lands on the app opened last rather than on // With the knob, the first move on this screen lands on the app opened last rather than on
// the first button anywhere on screen (issue #74). After that the knob moves as usual, out to // the first button anywhere on screen (issue #74). After that the knob moves as usual, out to
@@ -350,7 +353,37 @@ fun CarLauncher() {
verticalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(12.dp),
) { ) {
itemsIndexed(tiles) { i, tile -> AppTile(tile, if (i == lastIndex) Modifier.focusRequester(lastFocus) else Modifier) } itemsIndexed(tiles) { i, tile -> AppTile(tile, if (i == lastIndex) Modifier.focusRequester(lastFocus) else Modifier) }
if (shizukuReady && phoneApps.isNotEmpty()) {
item(span = { GridItemSpan(maxLineSpan) }) {
Text(
stringResource(R.string.launcher_phone_apps),
Modifier.padding(top = 12.dp, start = 4.dp),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
} }
items(phoneApps, key = { "native:" + it.packageName }) { app ->
AppTile(Tile(app.label, app.icon) { navigator.open(NATIVE_APP_PREFIX + app.packageName) })
}
}
}
}
/**
* Every phone app, for the launcher's Phone apps section (issue #124). Empty until Shizuku is
* running and allowed, since only Shizuku can put them on the car screen.
*/
@Composable
private fun rememberPhoneApps(ready: Boolean): List<app.seb3thehacker.gearslip.mirror.PhoneApp> {
val context = LocalContext.current
val apps by androidx.compose.runtime.produceState(app.seb3thehacker.gearslip.mirror.PhoneApps.cached().orEmpty(), ready) {
if (ready && value.isEmpty()) {
value = withContext(Dispatchers.IO) {
app.seb3thehacker.gearslip.mirror.PhoneApps.installed(context).also { app.seb3thehacker.gearslip.mirror.PhoneApps.warm(context) }
}
}
}
return if (ready) apps else emptyList()
} }
/** A red disc with a white X: marks a tile known not to work with Gearslip yet. */ /** A red disc with a white X: marks a tile known not to work with Gearslip yet. */
@@ -0,0 +1,140 @@
package app.seb3thehacker.gearslip.car
import android.annotation.SuppressLint
import android.os.SystemClock
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
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.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import app.seb3thehacker.gearslip.GearslipLog
import app.seb3thehacker.gearslip.R
import app.seb3thehacker.gearslip.shizuku.ShellBridge
/** What [CarApps.find] answers to for a phone app opened through Shizuku. */
internal const val NATIVE_APP_PREFIX = "native:"
/**
* A phone app on the car screen, drawn at the car's own size on a display the shell creates
* (issue #124). Needs Shizuku. The app draws into this screen's SurfaceView; touches on it go to
* the app, and so does the nav bar's Back, until the app has nothing left to go back to.
* Leaving the screen closes the display, and the app with it.
*/
@SuppressLint("ClickableViewAccessibility")
@Composable
fun NativePhoneAppScreen(packageName: String) {
val context = LocalContext.current
val navigator = LocalCarNavigator.current
val density = CarEnvironment.frame.value.densityDpi
var displayId by remember { mutableStateOf(-1) }
var failed by remember { mutableStateOf(false) }
val log = remember { GearslipLog.tagged("phone-app") }
val component = remember(packageName) {
context.packageManager.getLaunchIntentForPackage(packageName)?.component?.flattenToString()
}
DisposableEffect(packageName) {
ShellBridge.acquire(context)
onDispose {
val id = displayId
if (id >= 0) ShellBridge.call { it.releaseDisplay(id) }
ShellBridge.release()
}
}
// Back walks the app's own screens; once it has gone back past its first one, the display
// is empty and Back leaves for the launcher like anywhere else.
DisposableEffect(displayId) {
val id = displayId
if (id >= 0) {
navigator.backInterceptor = {
ShellBridge.call { shell ->
sendKey(shell, KeyEvent.KEYCODE_BACK, id)
Thread.sleep(BACK_SETTLE_MS)
if (shell.topPackage(id) == null) {
android.os.Handler(android.os.Looper.getMainLooper()).post {
navigator.backInterceptor = null
navigator.back()
}
}
}
true
}
}
onDispose { navigator.backInterceptor = null }
}
Box(Modifier.fillMaxSize()) {
if (component == null || failed) {
Text(
stringResource(R.string.native_app_failed),
Modifier.align(Alignment.Center).padding(32.dp),
style = MaterialTheme.typography.titleMedium,
)
return@Box
}
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { ctx ->
SurfaceView(ctx).apply {
var requested = false
holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) = Unit
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
if (requested) return
requested = true
val surface = holder.surface
ShellBridge.call { shell ->
val id = shell.createDisplay(surface, width, height, density)
if (id < 0) {
log.e("the shell could not create a display for $packageName")
post { failed = true }
return@call
}
val code = shell.launch(component, id)
log.i("started $packageName on display $id (${width}x$height @ ${density}dpi): exit $code")
post { displayId = id }
}
}
override fun surfaceDestroyed(holder: SurfaceHolder) = Unit
})
setOnTouchListener { _, event ->
val id = displayId
if (id >= 0) {
val copy = MotionEvent.obtain(event)
ShellBridge.now { it.injectMotion(copy, id) }
}
true
}
}
},
)
}
}
private fun sendKey(shell: app.seb3thehacker.gearslip.shizuku.IShellService, code: Int, displayId: Int) {
val now = SystemClock.uptimeMillis()
shell.injectKey(KeyEvent(now, now, KeyEvent.ACTION_DOWN, code, 0), displayId)
shell.injectKey(KeyEvent(now, now, KeyEvent.ACTION_UP, code, 0), displayId)
}
/** Long enough for an app to finish its last activity after Back, before checking what's left. */
private const val BACK_SETTLE_MS = 400L
@@ -0,0 +1,81 @@
package app.seb3thehacker.gearslip.shizuku
import android.content.ComponentName
import android.content.Context
import android.content.ServiceConnection
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import app.seb3thehacker.gearslip.BuildConfig
import app.seb3thehacker.gearslip.GearslipLog
import java.util.concurrent.Executors
import rikka.shizuku.Shizuku
/**
* Keeps [ShellService] running while a phone app is on the car screen, and runs calls to it off
* the main thread, one at a time, in the order they were made. Starting the service takes a
* moment, so calls made before it's up wait for it.
*/
object ShellBridge {
private val log = GearslipLog.tagged("shizuku")
private val main = Handler(Looper.getMainLooper())
private val worker = Executors.newSingleThreadExecutor { Thread(it, "gearslip-shell").apply { isDaemon = true } }
@Volatile private var shell: IShellService? = null
private var users = 0
private var args: Shizuku.UserServiceArgs? = null
private val waiting = mutableListOf<(IShellService) -> Unit>()
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
val service = binder?.let { IShellService.Stub.asInterface(it) } ?: return
shell = service
val queued = synchronized(waiting) { waiting.toList().also { waiting.clear() } }
queued.forEach { call -> worker.execute { runCatching { call(service) }.onFailure { log.e("shell call failed", it) } } }
}
override fun onServiceDisconnected(name: ComponentName?) {
shell = null
}
}
/** A screen that needs the shell came up. Pair with [release]. */
fun acquire(context: Context) = main.post {
users++
if (users > 1) return@post
val a = Shizuku.UserServiceArgs(ComponentName(context.applicationContext, ShellService::class.java))
.daemon(false)
.processNameSuffix("shell")
.debuggable(BuildConfig.DEBUG)
.version(BuildConfig.VERSION_CODE)
args = a
runCatching { Shizuku.bindUserService(a, connection) }.onFailure { log.e("could not start the shell service", it) }
}
fun release() = main.post {
users = (users - 1).coerceAtLeast(0)
if (users > 0) return@post
val a = args ?: return@post
args = null
shell = null
synchronized(waiting) { waiting.clear() }
runCatching { Shizuku.unbindUserService(a, connection, true) }
}
/** Runs [call] on the shell's thread, now or once the service is up. */
fun call(call: (IShellService) -> Unit) {
val service = shell
if (service != null) {
worker.execute { runCatching { call(service) }.onFailure { log.e("shell call failed", it) } }
} else {
synchronized(waiting) { waiting += call }
}
}
/** For touches: dropped rather than queued when the service isn't up, since a late touch is worse than none. */
fun now(call: (IShellService) -> Unit) {
val service = shell ?: return
runCatching { call(service) }
}
}
@@ -1,23 +1,139 @@
package app.seb3thehacker.gearslip.shizuku package app.seb3thehacker.gearslip.shizuku
import android.annotation.SuppressLint
import android.content.AttributionSource
import android.content.Context
import android.content.ContextWrapper
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.view.InputEvent
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.Surface
import androidx.annotation.Keep import androidx.annotation.Keep
import kotlin.system.exitProcess import kotlin.system.exitProcess
/** /**
* Runs in a process Shizuku starts as the shell user, so a command here has the same powers it * Runs in a process Shizuku starts as the shell user, so a command here has the same powers it
* would have typed over adb. Nothing in this class may touch the rest of Gearslip: it lives in a * would have typed over adb. Nothing in this class may touch the rest of Gearslip: it lives in a
* different process, with a different user, and only sees what [run] is handed. * different process, with a different user, and only sees what it's handed.
*
* Besides commands, it puts phone apps on the car screen (issue #124). An ordinary app may only
* show its own activities on a display it creates; the shell may create a trusted display that
* any app can be started on, the way scrcpy's new-display mode works. The app then draws at the
* car's own size instead of being a copy of the phone's screen.
*/ */
@Keep @Keep
class ShellService : IShellService.Stub() { class ShellService() : IShellService.Stub() {
private var context: Context? = null
/** Shizuku 13 passes a context when the class has this constructor. */
@Keep
constructor(context: Context) : this() {
this.context = context
}
private val displays = mutableMapOf<Int, VirtualDisplay>()
override fun destroy() { override fun destroy() {
displays.values.forEach { runCatching { it.release() } }
exitProcess(0) exitProcess(0)
} }
override fun run(command: String): Int { override fun run(command: String): Int = exec(command).first
@SuppressLint("WrongConstant")
override fun createDisplay(surface: Surface, width: Int, height: Int, densityDpi: Int): Int {
val base = context ?: return -1
return runCatching {
// The display service checks the caller's package against its uid, which is the shell's.
val manager = DisplayManager::class.java.getDeclaredConstructor(Context::class.java)
.apply { isAccessible = true }
.newInstance(ShellContext(base))
val display = manager.createVirtualDisplay("gearslip-phone-app", width, height, densityDpi, surface, DISPLAY_FLAGS)
synchronized(displays) { displays[display.display.displayId] = display }
display.display.displayId
}.getOrElse {
System.err.println("gearslip shell: createDisplay failed: $it")
-1
}
}
override fun launch(component: String, displayId: Int): Int =
exec("am start --display $displayId -f 0x10000000 -n ${quote(component)}").first
override fun topPackage(displayId: Int): String? {
// Each display's block starts "Display #N"; its resumed activity names the package.
var inDisplay = false
for (line in exec("dumpsys activity activities").second.lineSequence()) {
val trimmed = line.trim()
if (trimmed.startsWith("Display #")) {
inDisplay = trimmed.startsWith("Display #$displayId ") || trimmed == "Display #$displayId"
continue
}
if (!inDisplay) continue
if (trimmed.startsWith("mResumedActivity") || trimmed.startsWith("topResumedActivity") || trimmed.startsWith("ResumedActivity")) {
return Regex("""\s([\w.]+)/""").find(trimmed)?.groupValues?.get(1)
}
}
return null
}
override fun injectMotion(event: MotionEvent, displayId: Int) {
inject(event, displayId)
event.recycle()
}
override fun injectKey(event: KeyEvent, displayId: Int) {
inject(event, displayId)
}
override fun releaseDisplay(displayId: Int) {
synchronized(displays) { displays.remove(displayId) }?.let { runCatching { it.release() } }
}
private fun inject(event: InputEvent, displayId: Int) {
runCatching {
InputEvent::class.java.getMethod("setDisplayId", Int::class.javaPrimitiveType).invoke(event, displayId)
val input = inputManager
input.javaClass.getMethod("injectInputEvent", InputEvent::class.java, Int::class.javaPrimitiveType)
.invoke(input, event, INJECT_ASYNC)
}.onFailure { System.err.println("gearslip shell: inject failed: $it") }
}
/** InputManagerGlobal from Android 14, InputManager before it. */
private val inputManager: Any by lazy {
runCatching { Class.forName("android.hardware.input.InputManagerGlobal").getMethod("getInstance").invoke(null)!! }
.getOrElse { Class.forName("android.hardware.input.InputManager").getMethod("getInstance").invoke(null)!! }
}
private fun exec(command: String): Pair<Int, String> {
val process = ProcessBuilder("sh", "-c", command).redirectErrorStream(true).start() val process = ProcessBuilder("sh", "-c", command).redirectErrorStream(true).start()
process.inputStream.readBytes() val out = process.inputStream.bufferedReader().readText()
return process.waitFor() return process.waitFor() to out
}
private fun quote(s: String) = "'" + s.replace("'", "'\\''") + "'"
/** Answers to the shell's package, which is what the shell user's uid belongs to. */
private class ShellContext(base: Context) : ContextWrapper(base) {
override fun getPackageName() = SHELL
override fun getOpPackageName() = SHELL
override fun getAttributionSource(): AttributionSource =
AttributionSource.Builder(SHELL_UID).setPackageName(SHELL).build()
override fun getApplicationContext(): Context = this
}
private companion object {
const val SHELL = "com.android.shell"
const val SHELL_UID = 2000
const val INJECT_ASYNC = 0
// DisplayManager's flags, several of them hidden: public, own content only, supports
// touch, rotates with content, destroys its apps when released, trusted, its own display
// group, always unlocked, and no touch feedback.
const val DISPLAY_FLAGS = (1 shl 0) or (1 shl 3) or (1 shl 6) or (1 shl 7) or (1 shl 8) or
(1 shl 10) or (1 shl 11) or (1 shl 12) or (1 shl 13)
} }
} }
+2
View File
@@ -736,6 +736,8 @@
<string name="web_plain_http">This page isn\'t encrypted. Anyone on the same network can see what you send it.</string> <string name="web_plain_http">This page isn\'t encrypted. Anyone on the same network can see what you send it.</string>
<string name="web_plain_http_stop">Don\'t warn for this site</string> <string name="web_plain_http_stop">Don\'t warn for this site</string>
<string name="web_plain_http_hide">Hide warning</string> <string name="web_plain_http_hide">Hide warning</string>
<string name="launcher_phone_apps">Phone apps</string>
<string name="native_app_failed">This app couldn\'t open on the car screen. Check that Shizuku is running, then try again.</string>
<string name="shizuku_set_up">Set up with Shizuku</string> <string name="shizuku_set_up">Set up with Shizuku</string>
<string name="shizuku_working">Setting up…</string> <string name="shizuku_working">Setting up…</string>
<string name="shizuku_done">Set up through Shizuku. Nothing more to do here.</string> <string name="shizuku_done">Set up through Shizuku. Nothing more to do here.</string>