Add KDE Plasma Mobile desktop option

This commit is contained in:
xXJsonDeruloXx committed 2026-09-26 08:30:19 -04:00
1 parent dc1816612c
commit 70d3d1f6a4
29 files changed
+1177 -83

No files matched your search

+18
View File
@@ -115,6 +115,19 @@
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
<!-- A second compositor and Linux session need their own process-global JNI state and
runtime sockets, while the handheld's current session remains in the main process. -->
<activity
android:name=".ExternalSessionActivity"
android:process=":externalDisplay"
android:exported="false"
android:launchMode="singleTop"
android:theme="@style/SessionTheme"
android:preferMinimalPostProcessing="true"
android:screenOrientation="sensorLandscape"
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
<!--
Owns the session - gamescope, the Steam client, audio - so it survives the activity
going away. Without it Android demotes the process as soon as the last visible
@@ -125,6 +138,11 @@
android:name=".session.SessionService"
android:exported="false"
android:stopWithTask="false" />
<service
android:name=".session.ExternalSessionService"
android:process=":externalDisplay"
android:exported="false"
android:stopWithTask="false" />
<!-- Hands a zipped session folder to the share sheet; nothing else is exposed. -->
<provider
android:name="androidx.core.content.FileProvider"
@@ -22,6 +22,7 @@ add_library(bannerwayland SHARED
generated/xdg-shell-protocol.c
generated/linux-dmabuf-v1-protocol.c
generated/viewporter-protocol.c
generated/single-pixel-buffer-v1-protocol.c
generated/banner-desktop-v1-protocol.c
generated/presentation-time-protocol.c
generated/pointer-constraints-unstable-v1-protocol.c
@@ -0,0 +1,25 @@
/* Protocol description for wp_single_pixel_buffer_manager_v1. */
#include <stddef.h>
#include "wayland-util.h"
extern const struct wl_interface wl_buffer_interface;
static const struct wl_interface *single_pixel_buffer_types[] = {
&wl_buffer_interface,
NULL,
NULL,
NULL,
NULL,
};
static const struct wl_message single_pixel_buffer_requests[] = {
{ "destroy", "", NULL },
{ "create_u32_rgba_buffer", "nuuuu", single_pixel_buffer_types },
};
WL_EXPORT const struct wl_interface wp_single_pixel_buffer_manager_v1_interface = {
"wp_single_pixel_buffer_manager_v1", 1,
2, single_pixel_buffer_requests,
0, NULL,
};
@@ -0,0 +1,24 @@
#ifndef SINGLE_PIXEL_BUFFER_V1_SERVER_PROTOCOL_H
#define SINGLE_PIXEL_BUFFER_V1_SERVER_PROTOCOL_H
#include <stdint.h>
#include "wayland-server.h"
#ifdef __cplusplus
extern "C" {
#endif
struct wp_single_pixel_buffer_manager_v1_interface {
void (*destroy)(struct wl_client *client, struct wl_resource *resource);
void (*create_u32_rgba_buffer)(struct wl_client *client, struct wl_resource *resource,
uint32_t id, uint32_t red, uint32_t green,
uint32_t blue, uint32_t alpha);
};
extern const struct wl_interface wp_single_pixel_buffer_manager_v1_interface;
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="single_pixel_buffer_v1">
<copyright>
Copyright © 2022 Simon Ser
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
</copyright>
<description summary="single pixel buffer factory">
Create one-pixel buffers that clients can scale with the viewporter protocol.
</description>
<interface name="wp_single_pixel_buffer_manager_v1" version="1">
<request name="destroy" type="destructor">
<description summary="destroy the manager">Child buffers are unaffected.</description>
</request>
<request name="create_u32_rgba_buffer">
<description summary="create a 1x1 buffer from 32-bit RGBA values">
Channel values are premultiplied and range from 0 to 0xffffffff.
</description>
<arg name="id" type="new_id" interface="wl_buffer"/>
<arg name="r" type="uint"/>
<arg name="g" type="uint"/>
<arg name="b" type="uint"/>
<arg name="a" type="uint"/>
</request>
</interface>
</protocol>
@@ -41,6 +41,7 @@
#include "sc_layer.h"
#include "ahb_swapchain.h"
#include "viewporter-server-protocol.h"
#include "single-pixel-buffer-v1-server-protocol.h"
#include "banner-desktop-v1-server-protocol.h"
#include "presentation-time-server-protocol.h"
#include "pointer-constraints-unstable-v1-server-protocol.h"
@@ -749,6 +750,23 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
if (ci && ci->asked_feedback) ci->shm_frames++; /* since it asked for GPU buffers */
}
static int get_single_pixel_buffer(struct wl_resource *buffer, uint32_t *pixel);
/* Copy a wp_single_pixel_buffer into the surface's image and release the resource. */
static void take_single_pixel(struct surface *s, uint32_t pixel,
struct wl_resource *resource) {
if (s->shm_img && (vkp_image_width(s->shm_img) != 1 || vkp_image_height(s->shm_img) != 1)) {
vkp_image_destroy(s->shm_img);
s->shm_img = NULL;
}
if (!s->shm_img) s->shm_img = vkp_image_create_shm(1, 1);
if (s->shm_img) vkp_image_upload_shm(s->shm_img, &pixel, 4);
wl_buffer_send_release(resource);
s->buf_w = 1;
s->buf_h = 1;
s->has_content = s->shm_img != NULL;
}
/* The window the app's performance HUD follows: the latest one at least as big as the last to
* start presenting GPU frames (take_dmabuf) (X11 binds the HUD to the _MESA_DRV window and counts X presents instead). JNI upcalls. */
static struct surface *g_hud_surface;
@@ -999,6 +1017,8 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
if (s->pending_attach) {
struct wl_resource *buffer = s->pending_buffer;
struct dmabuf_buffer *db = get_dmabuf(buffer);
uint32_t pixel = 0;
int has_single_pixel = get_single_pixel_buffer(buffer, &pixel);
struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL;
/* The previous content is replaced before reaching the screen. */
@@ -1018,6 +1038,8 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
cursor_publish_hidden(); /* wlroots clears its cursor surface to hide the pointer */
} else if (shm) {
cursor_publish_shm(shm, g_cursor_hx, g_cursor_hy);
} else if (has_single_pixel) {
cursor_publish_pixels((const uint8_t *)&pixel, 1, 1, 4, g_cursor_hx, g_cursor_hy);
} else if (db && db->n_planes >= 1 && db->width * db->height <= CURSOR_MAX_PX) {
if (!db->img && !db->import_failed) {
db->img = vkp_image_from_dmabuf(db->fd[0], db->format, db->modifier, db->width, db->height,
@@ -1037,6 +1059,9 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
} else if (shm) {
drop_dmabuf(s, 1);
take_shm(s, shm, buffer);
} else if (has_single_pixel) {
drop_dmabuf(s, 1);
take_single_pixel(s, pixel, buffer);
} else {
drop_dmabuf(s, 1);
s->has_content = 0;
@@ -1332,6 +1357,80 @@ static void bind_viewporter(struct wl_client *c, void *data, uint32_t ver, uint3
wl_resource_set_implementation(r, &viewporter_impl, NULL, NULL);
}
/* ---------------------------------------------------------------- wp_single_pixel_buffer_manager_v1
* KWin's nested Wayland backend uses one-pixel buffers for its output background. */
struct single_pixel_buffer {
uint32_t pixel;
};
static void single_pixel_buffer_destroy_req(struct wl_client *c, struct wl_resource *r) {
wl_resource_destroy(r);
}
static const struct wl_buffer_interface single_pixel_buffer_impl = {
.destroy = single_pixel_buffer_destroy_req,
};
static int get_single_pixel_buffer(struct wl_resource *buffer, uint32_t *pixel) {
if (!buffer || !wl_resource_instance_of(buffer, &wl_buffer_interface, &single_pixel_buffer_impl))
return 0;
struct single_pixel_buffer *single = wl_resource_get_user_data(buffer);
if (!single) return 0;
*pixel = single->pixel;
return 1;
}
static void single_pixel_buffer_resource_destroy(struct wl_resource *r) {
free(wl_resource_get_user_data(r));
}
static void single_pixel_manager_destroy(struct wl_client *c, struct wl_resource *r) {
wl_resource_destroy(r);
}
static uint32_t single_pixel_channel(uint32_t value) {
return (uint32_t)(((uint64_t)value * 255u + UINT32_MAX / 2u) / UINT32_MAX);
}
static void single_pixel_create_buffer(struct wl_client *c, struct wl_resource *r, uint32_t id,
uint32_t red, uint32_t green, uint32_t blue, uint32_t alpha) {
struct single_pixel_buffer *buffer = calloc(1, sizeof(*buffer));
if (!buffer) {
wl_client_post_no_memory(c);
return;
}
/* wl_shm's ARGB8888 word layout is 0xAARRGGBB. */
buffer->pixel = (single_pixel_channel(alpha) << 24)
| (single_pixel_channel(red) << 16)
| (single_pixel_channel(green) << 8)
| single_pixel_channel(blue);
struct wl_resource *resource = wl_resource_create(c, &wl_buffer_interface, 1, id);
if (!resource) {
free(buffer);
wl_client_post_no_memory(c);
return;
}
wl_resource_set_implementation(resource, &single_pixel_buffer_impl, buffer,
single_pixel_buffer_resource_destroy);
}
static const struct wp_single_pixel_buffer_manager_v1_interface single_pixel_manager_impl = {
.destroy = single_pixel_manager_destroy,
.create_u32_rgba_buffer = single_pixel_create_buffer,
};
static void bind_single_pixel_manager(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
struct wl_resource *r = wl_resource_create(c, &wp_single_pixel_buffer_manager_v1_interface, ver, id);
if (!r) {
wl_client_post_no_memory(c);
return;
}
wl_resource_set_implementation(r, &single_pixel_manager_impl, NULL, NULL);
}
/* ------------------------------------------------------------------ xdg_shell */
static void xdg_toplevel_destroy_req(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
@@ -3641,6 +3740,7 @@ int banner_wayland_run(void) {
wl_global_create(display, &wl_compositor_interface, 6, NULL, bind_compositor);
wl_global_create(display, &wl_subcompositor_interface, 1, NULL, bind_subcompositor);
wl_global_create(display, &wp_viewporter_interface, 1, NULL, bind_viewporter);
wl_global_create(display, &wp_single_pixel_buffer_manager_v1_interface, 1, NULL, bind_single_pixel_manager);
wl_display_init_shm(display); /* wl_shm global + pool/buffer handling */
/* libdecor binds wl_output at 4; a lower version is a protocol error for the client. */
wl_global_create(display, &wl_output_interface, 4, NULL, bind_output);
@@ -0,0 +1,4 @@
package com.droiddeck.launcher
/** SessionActivity hosted in its own process so the external display gets an independent compositor. */
class ExternalSessionActivity : SessionActivity()
@@ -111,6 +111,8 @@ class MainActivity : ComponentActivity() {
private var pkgStage by mutableStateOf<String?>(null)
private var pkgPercent by mutableIntStateOf(-1)
private var desktopInstalled by mutableStateOf(false)
private var plasmaMobileInstalled by mutableStateOf(false)
private var desktopEnvironment by mutableStateOf(SessionPrefs.DESKTOP_ENV_LXQT)
private var offlineAccount by mutableStateOf<String?>(null)
private var offline by mutableStateOf(false)
private var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
@@ -712,6 +714,8 @@ class MainActivity : ComponentActivity() {
forceFullscreen = if (mode == SessionService.MODE_STEAM) forceFullscreen else null,
mic = if (mode == SessionService.MODE_STEAM) mic else null,
renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null,
desktopEnvironment = if (mode == SessionService.MODE_DESKTOP) desktopEnvironment else null,
plasmaMobileInstalled = plasmaMobileInstalled,
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
storageOptions = storageOptions,
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
@@ -760,6 +764,10 @@ class MainActivity : ComponentActivity() {
}
},
onRenderer = { r -> SessionPrefs.setDesktopRenderer(this, r); renderer = r },
onDesktopEnvironment = { value ->
SessionPrefs.setDesktopEnvironment(this, value)
desktopEnvironment = SessionPrefs.desktopEnvironment(this)
},
onGameStorage = { path, label -> setGameStorage(path, label) },
onPickGameStorageFolder = {
pickGameStorage.launch(InAppFilePicker.buildDirIntent(this, "Choose the game storage folder", gameStorage.ifEmpty { null }))
@@ -1073,6 +1081,8 @@ class MainActivity : ComponentActivity() {
private fun refresh() {
desktopInstalled = DesktopCatalog.desktopInstalled(this)
plasmaMobileInstalled = DesktopCatalog.plasmaMobileInstalled(this)
desktopEnvironment = SessionPrefs.desktopEnvironment(this)
offlineAccount = OfflineMode.account(this)
offline = OfflineMode.enabled(this)
installed = LinuxRuntimeInstaller.installedVersion(this)
@@ -54,6 +54,7 @@ import com.droiddeck.launcher.session.SessionArtifacts
import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.session.SessionProcess
import com.droiddeck.launcher.wayland.HdrSupport
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
@@ -82,7 +83,7 @@ import kotlin.math.abs
* since it is input rather than a menu), and one Compose layer on top for everything else -
* the HUD line, the loading overlay, the drawer and its dialogs.
*/
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
open class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private lateinit var surfaceView: SurfaceView
private lateinit var sessionOverlay: ComposeView
private lateinit var loading: LoadingState
@@ -210,7 +211,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
surfaceView.holder.addCallback(this)
root.addView(surfaceView)
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this, SessionProcess.isExternalDisplay(this)), "dev/input"))
padBridge = bridge
// A player on the pad or the on-screen controls has no use for the mouse arrow; the next
// touchpad or mouse move brings it back (showCursor), once the pad has been quiet a moment.
@@ -230,10 +231,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
loading = LoadingState(this)
if (!SessionState.running) {
val requestedMode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
val needRuntime = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(this) == null
val needDesktop = intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_DESKTOP &&
val desktopMode = requestedMode == SessionService.MODE_DESKTOP || requestedMode == SessionService.MODE_PLASMA_MOBILE
val needDesktop = desktopMode &&
!com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this)
if (needRuntime || needDesktop) installThenStart(needRuntime, needDesktop)
val wantsPlasma = requestedMode == SessionService.MODE_PLASMA_MOBILE ||
(requestedMode == SessionService.MODE_DESKTOP &&
SessionPrefs.desktopEnvironment(this) == SessionPrefs.DESKTOP_ENV_PLASMA_MOBILE)
val plasmaInstalled = com.droiddeck.launcher.runtime.DesktopCatalog.plasmaMobileInstalled(this)
val needPlasma = wantsPlasma && !plasmaInstalled && requestedMode == SessionService.MODE_DESKTOP
if (requestedMode == SessionService.MODE_PLASMA_MOBILE && (!plasmaInstalled || needDesktop || needRuntime)) {
loading.showEnded("Open Desktop with KDE Plasma Mobile once before selecting it for the second screen.")
} else if (needRuntime || needDesktop || needPlasma) {
installThenStart(needRuntime, needDesktop, needPlasma)
}
}
hud = PerfHud(this)
hud.onPresentingWindowChanged = {
@@ -291,6 +303,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
secondScreenMode = secondScreenMode,
secondScreenDisplays = secondScreenDisplays,
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
plasmaMobileInstalled = com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this@SessionActivity) &&
com.droiddeck.launcher.runtime.DesktopCatalog.plasmaMobileInstalled(this@SessionActivity),
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
onFillScreen = { on -> SessionPrefs.setForceFullscreen(this@SessionActivity, on); fillScreen = on },
onFrameGenPick = { engine, multiplier ->
@@ -472,16 +486,28 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
* are downloaded and unpacked here, on the loading screen's own line and bar, and the session
* starts when they are in. Nothing else changes.
*/
private fun installThenStart(runtime: Boolean, desktop: Boolean) {
private fun installThenStart(runtime: Boolean, desktop: Boolean, plasmaMobile: Boolean) {
if (SessionState.stopRequested) return
installingRuntime = true
SessionState.installing = if (runtime) "runtime" else "desktop"
SessionState.installing = when {
runtime -> "runtime"
desktop -> "desktop"
else -> "plasma-mobile"
}
SessionEvents.transition(
SessionPhase.INSTALLING_RUNTIME,
if (runtime) "runtime.installing" else "desktop.installing",
when (SessionState.installing) {
"runtime" -> "runtime.installing"
"desktop" -> "desktop.installing"
else -> "plasma-mobile.installing"
},
mapOf("component" to SessionState.installing),
)
loading.step = if (runtime) "downloading the Linux runtime" else "downloading the desktop"
loading.step = when (SessionState.installing) {
"runtime" -> "downloading the Linux runtime"
"desktop" -> "downloading the desktop"
else -> "installing KDE Plasma Mobile"
}
loading.percent = -1
Thread({
var failedComponent: String? = null
@@ -496,6 +522,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
problem = installDesktop()
if (problem == null) SessionEvents.record("desktop.ready") else failedComponent = "desktop"
}
if (problem == null && plasmaMobile && !SessionState.stopRequested) {
SessionState.installing = "plasma-mobile"
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "plasma-mobile.installing", mapOf("component" to "plasma-mobile"))
problem = installPlasmaMobile()
if (problem == null) SessionEvents.record("plasma-mobile.ready") else failedComponent = "plasma-mobile"
}
uiHandler.post {
installingRuntime = false
SessionState.installing = null
@@ -507,7 +539,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return@post
}
if (problem != null) {
val code = if (failedComponent == "runtime") "RUNTIME_INSTALL_FAILED" else "DESKTOP_INSTALL_FAILED"
val code = when (failedComponent) {
"runtime" -> "RUNTIME_INSTALL_FAILED"
"plasma-mobile" -> "PLASMA_MOBILE_INSTALL_FAILED"
else -> "DESKTOP_INSTALL_FAILED"
}
SessionEvents.fail(code, problem)
collectStartArtifacts("session start failed")
loading.showEnded(problem)
@@ -561,12 +597,25 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return problem?.let { "The desktop did not install ($it). Check the connection and press Desktop again." }
}
private fun installPlasmaMobile(): String? {
uiHandler.post { loading.percent = -1; loading.step = "installing KDE Plasma Mobile packages" }
val problem = com.droiddeck.launcher.runtime.PlasmaMobileInstaller.install(
this,
com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.ProgressListener { stage, percent ->
uiHandler.post { loading.percent = percent; loading.step = stage }
},
)
return problem?.let { "KDE Plasma Mobile did not install: $it. Press Desktop again to retry." }
}
override fun surfaceCreated(holder: SurfaceHolder) {
if (installingRuntime || SessionState.stopRequested) return
if (!SessionState.running) {
SessionState.mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
}
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
val externalDisplay = SessionProcess.isExternalDisplay(this)
val runtimeDir = File(filesDir, if (externalDisplay) ".wayland-rt-external-display" else ".wayland-rt").apply { mkdirs() }
// The compositor hands this keymap to wl_keyboard clients, which is how the guest reads
// the evdev codes we inject.
FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb"))
@@ -762,7 +811,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun onSessionEnded(status: Int) {
closeSecondScreen(reset = true)
closeSecondScreen(reset = true, stopPlasma = true)
if (status == 0) {
runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
@@ -1107,26 +1156,30 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
secondScreenDisplays = candidates
val newIds = candidates.map { it.id }.toSet()
if (secondScreenMode != SecondScreenMode.NONE && oldIds.isNotEmpty() && selectedSecondScreenDisplay !in newIds) {
closeSecondScreen(reset = true)
closeSecondScreen(reset = true, stopPlasma = true)
return
}
if (selectedSecondScreenDisplay !in newIds) selectedSecondScreenDisplay = candidates.firstOrNull()?.id ?: -1
if (secondScreenMode != SecondScreenMode.NONE && candidates.isEmpty()) closeSecondScreen(reset = true)
if (secondScreenMode != SecondScreenMode.NONE && candidates.isEmpty()) closeSecondScreen(reset = true, stopPlasma = true)
}
private fun selectSecondScreenDisplay(displayId: Int) {
if (secondScreenDisplays.none { it.id == displayId }) return
val movePlasma = secondScreenMode == SecondScreenMode.PLASMA_MOBILE && selectedSecondScreenDisplay != displayId
if (movePlasma) closeSecondScreen(reset = true, stopPlasma = true)
selectedSecondScreenDisplay = displayId
if (secondScreenMode != SecondScreenMode.NONE) showSecondScreen(secondScreenMode)
if (movePlasma) {
uiHandler.postDelayed({ if (displayId in secondScreenDisplays.map { it.id }) showSecondScreen(SecondScreenMode.PLASMA_MOBILE) }, 700)
} else if (secondScreenMode != SecondScreenMode.NONE) showSecondScreen(secondScreenMode)
}
private fun selectSecondScreenMode(mode: SecondScreenMode) {
if (mode == SecondScreenMode.NONE) {
closeSecondScreen(reset = true)
closeSecondScreen(reset = true, stopPlasma = true)
return
}
if (secondScreenDisplays.isEmpty()) {
secondScreenMode = SecondScreenMode.NONE
closeSecondScreen(reset = true, stopPlasma = true)
return
}
if (selectedSecondScreenDisplay !in secondScreenDisplays.map { it.id }) {
@@ -1138,10 +1191,39 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun showSecondScreen(mode: SecondScreenMode) {
val target = displayManager.getDisplay(selectedSecondScreenDisplay)
if (target == null || !target.isValid || (target.flags and Display.FLAG_PRESENTATION) == 0) {
closeSecondScreen(reset = true)
closeSecondScreen(reset = true, stopPlasma = true)
refreshSecondScreenDisplays()
return
}
if (mode == SecondScreenMode.PLASMA_MOBILE) {
if (!com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this) ||
!com.droiddeck.launcher.runtime.DesktopCatalog.plasmaMobileInstalled(this)) {
secondScreenMode = SecondScreenMode.NONE
Toast.makeText(this, "Open Desktop with KDE Plasma Mobile once to install it.", Toast.LENGTH_LONG).show()
return
}
secondScreenPresentation?.closeControls()
secondScreenPresentation = null
try {
val launch = Intent(this, ExternalSessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_PLASMA_MOBILE)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
val options = android.app.ActivityOptions.makeBasic()
.setLaunchDisplayId(target.displayId)
.toBundle()
startActivity(launch, options)
secondScreenMode = mode
} catch (e: Exception) {
Log.w(TAG, "could not open Plasma Mobile on ${target.name}", e)
Toast.makeText(this, "Could not open KDE Plasma Mobile on ${target.name}.", Toast.LENGTH_LONG).show()
secondScreenMode = SecondScreenMode.NONE
}
return
}
if (secondScreenMode == SecondScreenMode.PLASMA_MOBILE) {
SessionService.stopExternalDisplaySession(this)
secondScreenMode = SecondScreenMode.NONE
}
var presentation = secondScreenPresentation
if (presentation?.display?.displayId != target.displayId) {
presentation?.closeControls()
@@ -1187,7 +1269,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
private fun closeSecondScreen(reset: Boolean) {
private fun closeSecondScreen(reset: Boolean, stopPlasma: Boolean = false) {
if (stopPlasma && secondScreenMode == SecondScreenMode.PLASMA_MOBILE) {
SessionService.stopExternalDisplaySession(this)
}
secondScreenPresentation?.closeControls()
secondScreenPresentation = null
if (reset) secondScreenMode = SecondScreenMode.NONE
@@ -1287,7 +1372,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// Auto: the touch pad when there is no controller - except on the desktop, where the
// screen is a touchpad for the pointer and a pad over it would be in the way. A game
// started from the rail, or Steam, gets it; the drawer turns it on anywhere.
else -> !PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP
else -> !PadBridge.anyControllerConnected() &&
SessionState.mode != SessionService.MODE_DESKTOP && SessionState.mode != SessionService.MODE_PLASMA_MOBILE
}
if (show == (controls.visibility == View.VISIBLE)) return
if (!show) controls.releaseAll()
@@ -1305,13 +1391,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
super.onStart()
displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper()))
refreshSecondScreenDisplays()
if (secondScreenMode != SecondScreenMode.NONE) showSecondScreen(secondScreenMode)
// The external activity owns Plasma Mobile on the second display. Reopening it whenever
// this activity returns caused a failed guest to relaunch in a loop.
if (secondScreenMode != SecondScreenMode.NONE && secondScreenMode != SecondScreenMode.PLASMA_MOBILE) {
showSecondScreen(secondScreenMode)
}
SessionService.setActivityVisible(this, true)
}
override fun onStop() {
displayManager.unregisterDisplayListener(displayListener)
closeSecondScreen(reset = true)
if (secondScreenMode != SecondScreenMode.PLASMA_MOBILE) closeSecondScreen(reset = true)
SessionService.setActivityVisible(this, false)
super.onStop()
}
@@ -8,6 +8,7 @@ import com.droiddeck.launcher.core.FileUtils;
import com.droiddeck.launcher.core.SessionPart;
import com.droiddeck.launcher.core.HostProcess;
import com.droiddeck.launcher.core.TarZst;
import com.droiddeck.launcher.session.SessionProcess;
import java.io.File;
import java.io.InputStream;
@@ -50,7 +51,8 @@ public class PulseAudioComponent extends SessionPart {
/** As above, with a microphone fed from {@code micFifoPath}; null for output only. */
public PulseAudioComponent(Context context, String micFifoPath) {
this.workingDir = new File(context.getFilesDir(), "pulseaudio");
this.workingDir = new File(context.getFilesDir(),
SessionProcess.INSTANCE.isExternalDisplay(context) ? "pulseaudio-external-display" : "pulseaudio");
this.micFifoPath = micFifoPath;
}
@@ -52,7 +52,12 @@ object DeviceReport {
b.append("DroidDeck session report\n")
b.append("========================\n")
k("Written", SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz", Locale.US).format(Date()))
k("Session mode", when (mode) { SessionService.MODE_DESKTOP -> "desktop (labwc/LXQt)"; SessionService.MODE_RUN -> "a program under gamescope"; else -> "Steam client (gamescope)" })
k("Session mode", when (mode) {
SessionService.MODE_DESKTOP -> if (SessionPrefs.desktopEnvironment(context) == SessionPrefs.DESKTOP_ENV_PLASMA_MOBILE) "desktop (KDE Plasma Mobile)" else "desktop (labwc/LXQt)"
SessionService.MODE_PLASMA_MOBILE -> "secondary desktop (KDE Plasma Mobile)"
SessionService.MODE_RUN -> "a program under gamescope"
else -> "Steam client (gamescope)"
})
h("App")
runCatching {
@@ -8,6 +8,7 @@ enum class SecondScreenMode(val id: String, val label: String) {
NONE("none", "None"),
KEYBOARD_TRACKPAD("keyboard-trackpad", "Keyboard + trackpad"),
TERMINAL("terminal", "Terminal"),
PLASMA_MOBILE("plasma-mobile", "KDE Plasma Mobile"),
}
data class SecondScreenDisplay(val id: Int, val label: String)
@@ -62,6 +62,19 @@ object DesktopCatalog {
fun desktopInstalled(context: Context): Boolean =
File(LinuxRuntime.rootDir(context), "usr/bin/labwc").isFile
/** Plasma Mobile lives in a copied Arch root so its package updates never touch Steam's root. */
fun plasmaMobileInstalled(context: Context): Boolean {
val root = LinuxRuntime.plasmaRootDir(context)
return LinuxRuntime.isPlasmaRootCurrent(context) &&
plasmaMobileMarker(context).isFile &&
File(root, "usr/bin/kwin_wayland").isFile &&
File(root, "usr/bin/plasmashell").isFile &&
File(root, "usr/share/plasma/shells/org.kde.plasma.mobileshell").isDirectory
}
internal fun plasmaMobileMarker(context: Context): File =
File(context.filesDir, ".droiddeck-plasma-mobile-installed")
/** Downloads, verifies and installs one package. Returns null on success, else a message. */
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
val root = LinuxRuntime.rootDir(context)
@@ -2,16 +2,22 @@ package com.droiddeck.launcher.runtime;
import android.content.Context;
import android.os.Process;
import android.os.StatFs;
import android.system.ErrnoException;
import android.system.Os;
import android.system.StructStat;
import android.system.StructUtsname;
import com.droiddeck.launcher.core.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
@@ -48,6 +54,167 @@ public final class LinuxRuntime {
return new File(context.getFilesDir(), DIR);
}
/** Isolated Arch root used by Plasma Mobile, so its rolling package update cannot change Steam's rootfs. */
public static File plasmaRootDir(Context context) {
return new File(context.getFilesDir(), DIR + "-plasma-mobile");
}
/**
* Creates an independent package root from the installed runtime. This must be a real copy:
* package hooks can edit installed files in place, which would modify the Steam root through
* hard links. Volatile state and the user's home are kept separate.
*/
public static String preparePlasmaRoot(Context context, LinuxRuntimeInstaller.ProgressListener listener) {
File source = rootDir(context);
File destination = plasmaRootDir(context);
if (!isInstalled(context)) return "The Linux runtime is not installed";
if (!new File(source, "usr/bin/labwc").isFile()) return "The Linux desktop package is not installed";
String sourceStamp = plasmaSourceStamp(context);
File stamp = new File(destination, ".droiddeck-source");
if (new File(destination, "usr/bin/gamescope").isFile()
&& stamp.isFile() && sourceStamp.equals(FileUtils.readString(stamp))) return null;
File staging = new File(context.getFilesDir(), DIR + "-plasma-mobile.new");
FileUtils.delete(staging);
FileUtils.delete(destination);
long sourceBytes;
try {
sourceBytes = measurePlasmaTree(context, source, source);
} catch (Exception e) {
android.util.Log.e("LinuxRuntime", "could not measure runtime for Plasma Mobile", e);
return "Could not read the Linux runtime files for KDE";
}
long reserve = Math.max(64L * 1024L * 1024L, sourceBytes / 20L);
long available = new StatFs(context.getFilesDir().getPath()).getAvailableBytes();
if (available < sourceBytes + reserve) {
return "KDE needs about " + FileUtils.sizeToString(sourceBytes + reserve)
+ " of free storage to make an isolated Linux runtime";
}
if (!staging.mkdirs()) return "Could not create the isolated KDE runtime directory";
listenerProgress(listener, "Copying an isolated Linux runtime for KDE", -1);
try {
copyPlasmaTree(context, source, staging, source);
FileUtils.writeString(new File(staging, ".droiddeck-source"), sourceStamp);
if (!staging.renameTo(destination)) {
FileUtils.delete(staging);
return "Could not finish preparing the isolated KDE runtime";
}
return null;
} catch (Exception e) {
android.util.Log.e("LinuxRuntime", "could not prepare Plasma Mobile root", e);
FileUtils.delete(staging);
return "Could not prepare the isolated KDE runtime: " + e.getMessage();
}
}
/** Measures without following links and skips app-private bind targets before opening them. */
private static long measurePlasmaTree(Context context, File root, File current) throws IOException {
String name = root.toPath().relativize(current.toPath()).toString().replace(File.separatorChar, '/');
if (isPlasmaExcludedDirectory(context, name)) return 0L;
BasicFileAttributes attrs = Files.readAttributes(current.toPath(), BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
if (attrs.isSymbolicLink() || !attrs.isDirectory()) return attrs.size();
File[] children = current.listFiles();
if (children == null) throw new IOException("could not list " + current);
long bytes = 0L;
for (File child : children) bytes += measurePlasmaTree(context, root, child);
return bytes;
}
/** Copies without following links and checks bind targets before listing their source dirs. */
private static void copyPlasmaTree(Context context, File root, File destinationRoot, File current) throws IOException {
String name = root.toPath().relativize(current.toPath()).toString().replace(File.separatorChar, '/');
Path sourcePath = current.toPath();
Path targetPath = destinationRoot.toPath().resolve(root.toPath().relativize(sourcePath));
if (isPlasmaExcludedDirectory(context, name)) {
Files.createDirectories(targetPath);
return;
}
BasicFileAttributes attrs = Files.readAttributes(sourcePath, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
if (attrs.isSymbolicLink()) {
Files.createDirectories(targetPath.getParent());
Files.createSymbolicLink(targetPath, Files.readSymbolicLink(sourcePath));
return;
}
if (!attrs.isDirectory()) {
Files.createDirectories(targetPath.getParent());
Files.copy(sourcePath, targetPath, StandardCopyOption.COPY_ATTRIBUTES);
return;
}
Files.createDirectories(targetPath);
File[] children = current.listFiles();
if (children == null) throw new IOException("could not list " + current);
for (File child : children) copyPlasmaTree(context, root, destinationRoot, child);
try {
Files.setPosixFilePermissions(targetPath, Files.getPosixFilePermissions(sourcePath));
} catch (UnsupportedOperationException ignored) {
// App-private Linux rootfs storage normally supports POSIX modes; keep the copy usable
// on filesystems that do not expose them.
}
}
private static String plasmaSourceStamp(Context context) {
String version = FileUtils.readString(new File(rootDir(context), ".version"));
String desktop = FileUtils.readString(new File(rootDir(context), ".droiddeck-pkg-desktop"));
return (version == null ? "" : version.trim()) + "\n" + (desktop == null ? "" : desktop.trim());
}
private static boolean isPlasmaExcludedDirectory(Context context, String name) {
if (name.equals("dev") || name.equals("proc") || name.equals("sys") ||
name.equals("root") || name.equals("run") || name.equals("tmp") ||
name.equals("storage") || name.startsWith("storage/") ||
name.equals("mnt/bannerlator-sd") || name.startsWith("mnt/bannerlator-sd/") ||
name.equals("var/cache") || name.startsWith("var/cache/") ||
name.equals("var/tmp") || name.startsWith("var/tmp/")) return true;
// PRoot binds these host directories into the guest at their same absolute paths. Earlier
// sessions can leave those mount-point directories inside the source root; copying them
// would walk back into filesDir and recursively encounter linuxfs itself.
List<String> guestPaths = new ArrayList<>();
for (File bind : new File[]{context.getFilesDir(), context.getCacheDir()}) {
guestPaths.add(bind.getAbsolutePath());
}
// Android may return /data/data/<package> from Context while the guest bind target is
// /data/user/<id>/<package>, or vice versa. Include both spellings plus dataDir's actual
// files/cache locations so the runtime copy never descends into an app-private bind.
String dataDir = context.getApplicationInfo().dataDir;
if (dataDir != null) {
guestPaths.add(new File(dataDir, "files").getAbsolutePath());
guestPaths.add(new File(dataDir, "cache").getAbsolutePath());
}
String packageName = context.getPackageName();
int userId = Process.myUid() / 100000;
guestPaths.add("/data/user/" + userId + "/" + packageName + "/files");
guestPaths.add("/data/user/" + userId + "/" + packageName + "/cache");
guestPaths.add("/data/data/" + packageName + "/files");
guestPaths.add("/data/data/" + packageName + "/cache");
for (String path : guestPaths) {
if (!path.startsWith(File.separator)) continue;
String guestPath = path.substring(1).replace(File.separatorChar, '/');
if (name.equals(guestPath) || name.startsWith(guestPath + "/")) return true;
}
// The host path can be exposed through an alias that differs from both Context and
// ApplicationInfo. In the guest root, DroidDeck's bind targets are still identifiable by
// the package directory followed by files/ or cache/.
String packageMarker = "/" + context.getPackageName() + "/";
int packageIndex = name.indexOf(packageMarker);
if (packageIndex >= 0) {
String bindTarget = name.substring(packageIndex + packageMarker.length());
if (bindTarget.equals("files") || bindTarget.startsWith("files/") ||
bindTarget.equals("cache") || bindTarget.startsWith("cache/")) return true;
}
return false;
}
private static void listenerProgress(LinuxRuntimeInstaller.ProgressListener listener, String stage, int percent) {
if (listener != null) listener.onProgress(stage, percent);
}
/** Whether the copy still matches the installed runtime and desktop package. */
public static boolean isPlasmaRootCurrent(Context context) {
File stamp = new File(plasmaRootDir(context), ".droiddeck-source");
return stamp.isFile() && plasmaSourceStamp(context).equals(FileUtils.readString(stamp));
}
/**
* The session's own small tree beside the rootfs: the fake evdev nodes and their rings. In
* Bannerlator these lived in the Wine imagefs; here there is no Wine, so the session owns them.
@@ -57,6 +224,11 @@ public final class LinuxRuntime {
return new File(context.getFilesDir(), "session");
}
/** Per-session input and PTY files for the compositor hosted on an external display. */
public static File sessionRoot(Context context, boolean externalDisplay) {
return new File(context.getFilesDir(), externalDisplay ? "session-external-display" : "session");
}
/** Where the runtime carries the host-side proot; see tools/linuxfs/prebuilt/proot/README.md. */
private static final String HOST_DIR = "opt/android-host";
@@ -89,7 +261,11 @@ public final class LinuxRuntime {
/** The Vulkan ICD manifest the rootfs ships for the device GPU, or null when it has none. */
public static File vulkanIcd(Context context) {
File icdDir = new File(rootDir(context), "usr/share/vulkan/icd.d");
return vulkanIcd(rootDir(context));
}
public static File vulkanIcd(File root) {
File icdDir = new File(root, "usr/share/vulkan/icd.d");
File[] manifests = icdDir.listFiles((dir, name) -> name.endsWith(".json"));
if (manifests == null) return null;
for (File manifest : manifests) {
@@ -114,7 +290,19 @@ public final class LinuxRuntime {
public static List<String> command(Context context, File sessionRoot, File runtimeDir,
File externalStorage, List<String> extraBinds,
List<String> guestCommand) {
File root = rootDir(context);
return commandForRoot(context, rootDir(context), sessionRoot, runtimeDir, externalStorage, extraBinds, guestCommand);
}
public static List<String> commandForRoot(Context context, File root, File sessionRoot, File runtimeDir,
File externalStorage, List<String> extraBinds,
List<String> guestCommand) {
return commandForRoot(context, root, sessionRoot, runtimeDir, externalStorage, extraBinds, guestCommand, false);
}
/** As above, optionally giving package installers PRoot's fake-root identity inside the guest. */
public static List<String> commandForRoot(Context context, File root, File sessionRoot, File runtimeDir,
File externalStorage, List<String> extraBinds,
List<String> guestCommand, boolean fakeRoot) {
List<String> cmd = new ArrayList<>();
cmd.add(prootBinary(context).getPath());
cmd.add("--kill-on-exit");
@@ -124,9 +312,13 @@ public final class LinuxRuntime {
// setgid()/setuid() before it execs xkbcomp and _exit(127)s when they fail, so without
// this the keymap never compiles and Xwayland dies. -i makes proot answer those calls
// itself while still reporting our real ids, so nothing inside sees a different user.
int uid = Process.myUid();
cmd.add("-i");
cmd.add(uid + ":" + uid);
if (fakeRoot) {
cmd.add("-0");
} else {
int uid = Process.myUid();
cmd.add("-i");
cmd.add(uid + ":" + uid);
}
cmd.add("-r");
cmd.add(root.getPath());
cmd.add("-w");
@@ -258,7 +450,10 @@ public final class LinuxRuntime {
/** X access control and Steam look the session user up by uid: the app uid is root inside. */
public static void writeAccounts(Context context) throws IOException {
File root = rootDir(context);
writeAccounts(context, rootDir(context));
}
public static void writeAccounts(Context context, File root) throws IOException {
int uid = Process.myUid();
Files.write(new File(root, "etc/passwd").toPath(),
("root:x:" + uid + ":" + uid + ":root:/root:/bin/bash\n").getBytes(StandardCharsets.UTF_8));
@@ -0,0 +1,165 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.core.FileUtils
import java.io.File
import java.io.BufferedReader
import java.io.InputStreamReader
import java.nio.file.Files
/** Installs the optional Plasma Mobile shell into its isolated Arch Linux ARM package root. */
object PlasmaMobileInstaller {
@Synchronized
fun install(context: Context, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
if (!LinuxRuntime.isInstalled(context)) return "The Linux runtime is not installed"
if (!DesktopCatalog.desktopInstalled(context)) return "The Linux desktop package is not installed"
listener?.onProgress("Preparing an isolated Linux runtime for KDE", -1)
LinuxRuntime.preparePlasmaRoot(context, listener)?.let { return it }
val root = LinuxRuntime.plasmaRootDir(context)
if (!File(root, "usr/bin/pacman").isFile) return "This Linux runtime has no pacman package manager"
val pacmanConfig = File(root, "etc/pacman.conf")
if (!pacmanConfig.isFile) return "This Linux runtime has no pacman configuration"
val originalPacmanConfig = try {
pacmanConfig.readText()
} catch (e: Exception) {
return "Could not read the pacman configuration: ${e.message ?: e.javaClass.simpleName}"
}
val sessionRoot = File(context.filesDir, "plasma-install-session").apply { mkdirs() }
val runtimeDir = File(context.filesDir, ".plasma-install-rt").apply { mkdirs() }
val packageLock = File(root, "var/lib/pacman/db.lck")
if (packageLock.exists()) {
val age = System.currentTimeMillis() - packageLock.lastModified()
if (age < 60_000L) return "The isolated package manager is still active; wait a moment and retry"
if (!packageLock.delete()) return "Could not clear the stale isolated package-manager lock"
}
prepareKeyringPermissions(File(root, "etc/pacman.d/gnupg"))?.let {
return "Could not make the isolated Arch package keyring writable: $it"
}
val guest = listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root",
"PATH=/usr/local/bin:/usr/bin:/bin", "LANG=C.UTF-8", "TERM=xterm",
// The isolated root inherits sync databases from the runtime image. Force fresh
// repository databases so the rolling package filenames match the live mirrors.
// Replace only paths present in incoming packages when the cloned runtime has
// unowned files from its base image; the Steam root remains untouched.
"/bin/sh", "-c",
"/usr/bin/pacman-key --init && /usr/bin/pacman-key --populate archlinuxarm && " +
"exec /usr/bin/pacman -Syyu --needed --noconfirm --overwrite '*' plasma-mobile",
)
val command = LinuxRuntime.commandForRoot(
context, root, sessionRoot, runtimeDir, null, null, guest, true,
)
return try {
pacmanConfig.writeText(withInstallerDownloadSettings(originalPacmanConfig))
listener?.onProgress("Preparing KDE Plasma Mobile", -1)
val builder = ProcessBuilder(command).redirectErrorStream(true)
builder.directory(root)
val hostEnv = builder.environment()
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(context).path
hostEnv["PROOT_TMP_DIR"] = context.cacheDir.path
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let {
hostEnv["LD_LIBRARY_PATH"] = it
}
val process = builder.start()
val tail = ArrayDeque<String>()
BufferedReader(InputStreamReader(process.inputStream)).use { reader ->
while (true) {
val line = reader.readLine() ?: break
if (line.isNotBlank()) {
if (tail.size == 5) tail.removeFirst()
tail.addLast(line.take(180))
val lower = line.lowercase()
listener?.onProgress(
when {
"synchronizing" in lower || "database" in lower -> "Refreshing KDE package list"
"downloading" in lower || "retrieving" in lower -> "Downloading KDE Plasma Mobile packages"
"installing" in lower || "checking" in lower -> "Installing KDE Plasma Mobile"
else -> "Installing KDE Plasma Mobile"
},
-1,
)
}
}
}
val status = process.waitFor()
if (status != 0) {
val detail = tail.joinToString(" · ")
return "pacman exited with status $status" + if (detail.isNotEmpty()) ": $detail" else ""
}
val packageMarker = DesktopCatalog.plasmaMobileMarker(context)
FileUtils.writeString(packageMarker, "archlinuxarm\n")
if (!packageMarker.isFile) return "Plasma Mobile packages installed, but DroidDeck could not save the installation marker"
if (!DesktopCatalog.plasmaMobileInstalled(context)) {
packageMarker.delete()
return "pacman finished, but the Plasma Mobile shell was not found in the runtime"
}
null
} catch (e: Exception) {
"Could not install KDE Plasma Mobile: ${e.message ?: e.javaClass.simpleName}"
} finally {
try {
pacmanConfig.writeText(originalPacmanConfig)
} catch (e: Exception) {
android.util.Log.e("PlasmaMobileInstaller", "could not restore pacman config", e)
}
}
}
/** Pacman downloads as its caller, without Landlock, inside the confined guest root. */
private fun withInstallerDownloadSettings(config: String): String {
val lines = config.lines().toMutableList()
val optionsIndex = lines.indexOfFirst { it.trim().equals("[options]", ignoreCase = true) }
if (optionsIndex < 0) {
lines.add(0, "[options]")
lines.add(1, "#DownloadUser =")
lines.add(2, "DisableSandbox = true")
return lines.joinToString("\n")
}
var sectionEnd = optionsIndex + 1
while (sectionEnd < lines.size) {
val line = lines[sectionEnd].trim()
if (line.startsWith("[") && line.endsWith("]")) break
sectionEnd++
}
val overrides = listOf("DownloadUser" to "#DownloadUser =", "DisableSandbox" to "DisableSandbox = true")
for ((name, setting) in overrides) {
val matcher = Regex("^\\s*#?\\s*${name}\\s*=.*$", RegexOption.IGNORE_CASE)
var replaced = false
for (index in optionsIndex + 1 until sectionEnd) {
if (matcher.matches(lines[index])) {
lines[index] = setting
replaced = true
break
}
}
if (!replaced) lines.add(sectionEnd++, setting)
}
return lines.joinToString("\n")
}
/** Keep GnuPG's private keyring writable by this app-private PRoot root. */
private fun prepareKeyringPermissions(directory: File): String? {
if (!directory.exists() && !directory.mkdirs()) return directory.path
if (Files.isSymbolicLink(directory.toPath()) || !directory.isDirectory) return directory.path
fun makeOwnerWritable(file: File): String? {
if (Files.isSymbolicLink(file.toPath())) return file.path
val ok = if (file.isDirectory) {
file.setReadable(true, true) && file.setWritable(true, true) &&
file.setExecutable(true, true)
} else {
file.setReadable(true, true) && file.setWritable(true, true)
}
if (!ok) return file.path
if (file.isDirectory) {
val children = file.listFiles() ?: return file.path
for (child in children) makeOwnerWritable(child)?.let { return it }
}
return null
}
return makeOwnerWritable(directory)
}
}
@@ -35,7 +35,7 @@ object CrashHandler {
worker.join(8000)
}
// The session's tree would outlive us otherwise, and block the next launch.
OrphanReaper.reap("app crash")
OrphanReaper.reap("app crash", context)
} catch (e: Throwable) {
// Nothing more to do for a crash inside the crash handler.
} finally {
@@ -0,0 +1,4 @@
package com.droiddeck.launcher.session
/** Separate service process for a full Linux desktop running on an external Android display. */
class ExternalSessionService : SessionService()
@@ -1,29 +1,57 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.Log
import java.io.File
/**
* Kills every process of this app's uid other than the app itself.
* Kills leftover Linux processes owned by this app while preserving live DroidDeck process trees.
*
* A session is a tree of processes under proot, and proot dies with the app only when the app's
* own teardown runs. When the app is killed or crashes instead, the tree stays: proot holding the
* rootfs, gamescope holding the GPU, Steam holding its lock file - and the next session never
* comes up, or comes up beside a client that is already running. A user on a Thor Pro had to
* force-stop the app before every launch. Everything of ours that should be alive between
* sessions is inside the app process, so at session start anything else under our uid is a
* leftover, and this sweeps it. Each pid is checked by uid at kill time, never by name.
* sessions lives in Android processes, so another active session can own Linux children under
* the same uid. Those process trees are preserved; remaining same-uid processes are swept. Each
* pid is checked by uid at kill time, never by name.
*/
object OrphanReaper {
private const val TAG = "OrphanReaper"
fun reap(reason: String): Int {
fun reap(reason: String, context: Context): Int {
if (SessionProcess.hasSiblingProcess(context)) {
Log.i(TAG, "skipped process sweep while a sibling app process is active - $reason")
return 0
}
val packageName = context.packageName
val me = android.os.Process.myPid()
val uid = android.os.Process.myUid()
val appProcesses = File("/proc").listFiles().orEmpty().mapNotNull { entry ->
val pid = entry.name.toIntOrNull() ?: return@mapNotNull null
if (pid == me) return@mapNotNull null
val name = try { File(entry, "cmdline").readText().substringBefore('\u0000') } catch (_: Exception) { "" }
if (name == packageName || name.startsWith("$packageName:")) pid else null
}.toSet()
// Keep every other DroidDeck process and its Linux children. Main and external-display
// sessions intentionally run side by side in separate Android processes.
val parents = HashMap<Int, MutableList<Int>>()
File("/proc").listFiles().orEmpty().forEach { entry ->
val pid = entry.name.toIntOrNull() ?: return@forEach
val parent = parentOf(pid) ?: return@forEach
parents.getOrPut(parent) { ArrayList() }.add(pid)
}
val protected = HashSet<Int>()
val queue = ArrayDeque<Int>().apply { addAll(appProcesses) }
while (queue.isNotEmpty()) {
val pid = queue.removeFirst()
if (!protected.add(pid)) continue
(parents[pid] ?: continue).forEach(queue::addLast)
}
var killed = 0
File("/proc").listFiles()?.forEach { entry ->
val pid = entry.name.toIntOrNull() ?: return@forEach
if (pid == me || pid <= 1) return@forEach
if (pid == me || pid <= 1 || pid in protected) return@forEach
if (uidOf(pid) != uid) return@forEach
val name = try { File(entry, "cmdline").readText().substringBefore('\u0000') } catch (e: Exception) { "?" }
try {
@@ -48,4 +76,12 @@ object OrphanReaper {
-1
}
}
private fun parentOf(pid: Int): Int? {
val stat = try { File("/proc/$pid/stat").readText() } catch (_: Exception) { return null }
val close = stat.lastIndexOf(')')
if (close < 0 || close + 2 >= stat.length) return null
val fields = stat.substring(close + 2).trim().split(Regex("\\s+"))
return fields.getOrNull(1)?.toIntOrNull()
}
}
@@ -59,6 +59,7 @@ object SessionFiles {
// staging them into a runtime without it would make the desktop look present when it is not.
val desktop = arrayOf(
"usr/local/bin/droiddeck-desktop" to "usr/local/bin/droiddeck-desktop",
"usr/local/bin/droiddeck-plasma-mobile" to "usr/local/bin/droiddeck-plasma-mobile",
// Games and emulators from the menu, full screen in a gamescope of their own.
"usr/local/bin/droiddeck-gpu" to "usr/local/bin/droiddeck-gpu",
"usr/local/bin/droiddeck-desktop-gpu" to "usr/local/bin/droiddeck-desktop-gpu",
@@ -41,7 +41,8 @@ object SessionPaths {
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
val parent = if (SessionPrefs.logsEnabled(context)) SessionFiles.logDirectory(context)
else File(context.cacheDir, "session-logs")
val baseName = "session-$stamp"
val scope = if (SessionProcess.isExternalDisplay(context)) "external-" else ""
val baseName = "session-$scope$stamp"
var made = File(parent, baseName)
var suffix = 2
while (made.exists()) made = File(parent, "$baseName-${suffix++}")
@@ -387,6 +387,25 @@ object SessionPrefs {
java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.droiddeck-renderer-failed").delete()
}
const val DESKTOP_ENV_LXQT = "lxqt"
const val DESKTOP_ENV_PLASMA_MOBILE = "plasma-mobile"
val desktopEnvironmentChoices = listOf(
DESKTOP_ENV_LXQT to "LXQt",
DESKTOP_ENV_PLASMA_MOBILE to "KDE Plasma Mobile",
)
/** Shell used when the user opens the primary Desktop button. LXQt remains the default. */
fun desktopEnvironment(context: Context): String =
prefs(context).getString("desktopEnvironment", DESKTOP_ENV_LXQT)
?.takeIf { value -> desktopEnvironmentChoices.any { it.first == value } }
?: DESKTOP_ENV_LXQT
fun setDesktopEnvironment(context: Context, environment: String) {
val value = environment.takeIf { candidate -> desktopEnvironmentChoices.any { it.first == candidate } }
?: DESKTOP_ENV_LXQT
prefs(context).edit().putString("desktopEnvironment", value).apply()
}
/**
* HDR10 output for MODE_STEAM / MODE_DESKTOP. Off by default. Honoured only when the panel
* lists HDR10 (HdrSupport), and decided when the compositor starts, which is once per app
@@ -402,7 +421,11 @@ object SessionPrefs {
* The mode whose per-mode settings apply: a program run under gamescope (MODE_RUN) is a
* fullscreen session like Steam's, so it takes Steam's display, driver and HDR choices.
*/
fun prefMode(mode: String): String = if (mode == SessionService.MODE_RUN) SessionService.MODE_STEAM else mode
fun prefMode(mode: String): String = when (mode) {
SessionService.MODE_RUN -> SessionService.MODE_STEAM
SessionService.MODE_PLASMA_MOBILE -> SessionService.MODE_DESKTOP
else -> mode
}
fun suspendPolicy(context: Context, mode: String): String =
prefs(context).getString("suspendPolicy.${prefMode(mode)}", SUSPEND_MANUAL)
@@ -0,0 +1,124 @@
package com.droiddeck.launcher.session
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Build
import android.util.Log
import java.io.File
import java.io.RandomAccessFile
import java.nio.channels.FileLock
import java.nio.channels.OverlappingFileLockException
/** Identifies the dedicated Android process used to host a second-display Linux session. */
object SessionProcess {
private const val TAG = "SessionProcess"
private const val SECONDARY_SUFFIX = ":externalDisplay"
private const val MAIN_SESSION_LOCK = ".droiddeck-main-session.lock"
private const val EXTERNAL_SESSION_LOCK = ".droiddeck-external-session.lock"
@Volatile private var heldLock: FileLock? = null
@Volatile private var heldLockFile: RandomAccessFile? = null
fun isExternalDisplay(context: Context): Boolean = processName(context) == context.packageName + SECONDARY_SUFFIX
/**
* Keeps the sibling session discoverable even when Android restricts cross-process /proc
* reads. The service holds this process-specific file lock for the whole Linux session.
*/
@Synchronized
fun acquireSessionLock(context: Context): Boolean {
if (heldLock?.isValid == true) return true
val path = File(context.filesDir, ownLockName(context))
val file = RandomAccessFile(path, "rw")
val lock = try {
file.channel.tryLock()
} catch (e: OverlappingFileLockException) {
Log.w(TAG, "another session process already owns ${path.path}", e)
null
} catch (e: Exception) {
Log.e(TAG, "could not lock ${path.path}", e)
null
}
if (lock == null) {
file.close()
return false
}
heldLockFile = file
heldLock = lock
return true
}
@Synchronized
fun releaseSessionLock() {
try {
heldLock?.release()
} catch (e: Exception) {
Log.w(TAG, "could not release the session lock", e)
}
try {
heldLockFile?.close()
} catch (e: Exception) {
Log.w(TAG, "could not close the session lock file", e)
}
heldLock = null
heldLockFile = null
}
/** A sibling lock means its guest process tree must not be swept as an orphan. */
fun hasSiblingSession(context: Context): Boolean = isLocked(File(context.filesDir, siblingLockName(context)))
/** Includes an idle app process during display handoff, so legacy name-based sweeps stay safe. */
fun hasSiblingProcess(context: Context): Boolean {
if (hasSiblingSession(context)) return true
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager ?: return true
val processes = try {
manager.runningAppProcesses ?: return true
} catch (e: Exception) {
Log.w(TAG, "could not inspect sibling app processes; skipping cleanup", e)
return true
}
return processes.any { process ->
process.pid != android.os.Process.myPid() &&
(process.processName == context.packageName || process.processName.startsWith(context.packageName + ":"))
}
}
private fun isLocked(file: File): Boolean {
val probe = try {
RandomAccessFile(file, "rw")
} catch (e: Exception) {
Log.w(TAG, "could not inspect sibling session lock ${file.path}; skipping cleanup", e)
return true
}
return try {
val lock = probe.channel.tryLock()
if (lock == null) true else {
lock.release()
false
}
} catch (_: OverlappingFileLockException) {
true
} catch (e: Exception) {
Log.w(TAG, "could not inspect sibling session lock ${file.path}; skipping cleanup", e)
true
} finally {
try { probe.close() } catch (_: Exception) { }
}
}
private fun ownLockName(context: Context): String =
if (isExternalDisplay(context)) EXTERNAL_SESSION_LOCK else MAIN_SESSION_LOCK
private fun siblingLockName(context: Context): String =
if (isExternalDisplay(context)) MAIN_SESSION_LOCK else EXTERNAL_SESSION_LOCK
private fun processName(context: Context): String =
if (Build.VERSION.SDK_INT >= 28) Application.getProcessName() else readCommandLine(android.os.Process.myPid())
private fun readCommandLine(pid: Int): String = try {
File("/proc/$pid/cmdline").readText().substringBefore('\u0000')
} catch (_: Exception) {
""
}
}
@@ -23,6 +23,7 @@ import android.os.PowerManager
import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.ExternalSessionActivity
import com.droiddeck.launcher.audio.DirectAudioRelayComponent
import com.droiddeck.launcher.audio.PulseAudioComponent
import com.droiddeck.launcher.core.CpuCores
@@ -55,7 +56,7 @@ import java.util.Locale
*
* The activity comes and goes on top of this; see [com.droiddeck.launcher.wayland.CompositorHost].
*/
class SessionService : Service() {
open class SessionService : Service() {
private val components = java.util.concurrent.CopyOnWriteArrayList<SessionPart>()
private var wakeLock: PowerManager.WakeLock? = null
private var wifiLock: WifiManager.WifiLock? = null
@@ -160,14 +161,14 @@ class SessionService : Service() {
return START_NOT_STICKY
}
}
startForeground(NOTIFICATION_ID, buildNotification())
if (!SessionState.running) SessionState.mode = intent?.getStringExtra(EXTRA_MODE) ?: MODE_STEAM
startForeground(notificationId(), buildNotification())
if (SessionState.running) return START_NOT_STICKY
if (SessionState.stopRequested) {
SessionState.running = true
stopSession(0)
return START_NOT_STICKY
}
SessionState.mode = intent?.getStringExtra(EXTRA_MODE) ?: MODE_STEAM
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
activityVisible = true
screenOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: true
@@ -196,12 +197,21 @@ class SessionService : Service() {
// replaces can report its own exit in the gap between the two, and that exit must not
// be taken as this one's.
val gen = ++sessionGen
if (!SessionProcess.acquireSessionLock(this)) {
SessionState.running = false
Log.e(TAG, "another ${if (SessionProcess.isExternalDisplay(this)) "external" else "handheld"} session already owns its process lock")
SessionEvents.fail("SESSION_ALREADY_RUNNING", "Another DroidDeck session is already running", -1)
SessionState.notifyEnded(-1)
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
return START_NOT_STICKY
}
acquireLocks()
Thread({
// A tree the last session left behind (the app was killed or crashed, so its teardown
// never ran) would hold the rootfs, the GPU and Steam's lock: nothing of ours should
// be alive between sessions outside this process.
OrphanReaper.reap("session starting")
OrphanReaper.reap("session starting", this)
runSession(gen)
}, "session-start").start()
// The activity or the notification stops us; the system must not resurrect a session whose
@@ -226,6 +236,26 @@ class SessionService : Service() {
}
}
private fun readPlasmaShellPid(directory: File?): Int {
val pidFile = directory?.let { File(it, "plasma-shell.pid") } ?: return -1
return runCatching { pidFile.readText().trim().toInt() }.getOrDefault(-1)
}
/** Plasma can outlive KWin when PRoot tears down, so stop this session's recorded shell. */
private fun stopPlasmaShell(pid: Int, directory: File?) {
if (pid < 2 || directory == null) return
val proc = File("/proc/$pid")
val command = runCatching {
File(proc, "cmdline").readBytes().toString(Charsets.UTF_8).replace('\u0000', ' ')
}.getOrDefault("")
val environment = runCatching {
File(proc, "environ").readBytes().toString(Charsets.UTF_8)
}.getOrDefault("")
if (!command.contains("plasmashell") || !environment.contains(directory.name)) return
android.os.Process.killProcess(pid)
Log.i(TAG, "stopped Plasma Mobile shell process $pid")
}
private fun extraEnv(): List<String> {
val file = File(Environment.getExternalStorageDirectory(), ENV_SWITCH).takeIf { it.isFile } ?: return emptyList()
val lines = FileUtils.readString(file)?.lines().orEmpty()
@@ -249,18 +279,27 @@ class SessionService : Service() {
private fun runSession(gen: Int) {
SessionTerminal.clear()
val externalDisplay = SessionProcess.isExternalDisplay(this)
val plasmaDesktop = externalDisplay || SessionState.mode == MODE_PLASMA_MOBILE ||
(SessionState.mode == MODE_DESKTOP &&
SessionPrefs.desktopEnvironment(this) == SessionPrefs.DESKTOP_ENV_PLASMA_MOBILE)
val root = if (plasmaDesktop) LinuxRuntime.plasmaRootDir(this) else LinuxRuntime.rootDir(this)
if (plasmaDesktop && !com.droiddeck.launcher.runtime.DesktopCatalog.plasmaMobileInstalled(this)) {
Log.e(TAG, "Plasma Mobile's isolated runtime is not installed or is out of date")
stopSession(-1)
return
}
try {
LinuxRuntime.writeAccounts(this)
LinuxRuntime.writeAccounts(this, root)
} catch (e: Exception) {
Log.e(TAG, "could not write the guest's passwd/group", e)
stopSession(-1)
return
}
val root = LinuxRuntime.rootDir(this)
val sessionRoot = LinuxRuntime.sessionRoot(this).apply { mkdirs() }
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
killStragglers()
val sessionRoot = LinuxRuntime.sessionRoot(this, externalDisplay).apply { mkdirs() }
val runtimeDir = File(filesDir, if (externalDisplay) ".wayland-rt-external-display" else ".wayland-rt").apply { mkdirs() }
if (!SessionProcess.hasSiblingProcess(this)) killStragglers()
SessionFiles.stage(this, root)
// One folder per session, claimed by whoever started first - the activity starts the
@@ -299,7 +338,7 @@ class SessionService : Service() {
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
guest.add("GALLIUM_DRIVER=zink")
guest.add("LIBGL_KOPPER_DRI2=true")
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
LinuxRuntime.vulkanIcd(root)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
// An imported glibc Turnip for this mode, when the user chose one: the session script checks
// the manifest and its library from inside and points the loader at it with VK_DRIVER_FILES,
// so the runtime's own driver above stays untouched and is what a bad import falls back to.
@@ -371,7 +410,7 @@ class SessionService : Service() {
// top, and the helper only opens an input stream when asked - so a user who wants game
// sound but no recording gets exactly that, and Android's recording indicator stays off.
val wantsDirectAudio = SessionState.mode == MODE_STEAM && SessionPrefs.directAudio(this)
val wantsMic = SessionPrefs.micEnabled(this) &&
val wantsMic = SessionState.mode == MODE_STEAM && SessionPrefs.micEnabled(this) &&
checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
// Both paths sit under the app's files directory, which the session binds at its own path,
// so the same string is valid on both sides and nothing has to be translated.
@@ -410,6 +449,11 @@ class SessionService : Service() {
guest.add("BL_WIDTH=" + size.first)
guest.add("BL_HEIGHT=" + size.second)
if (SessionState.mode == MODE_DESKTOP) {
guest.add("BL_DESKTOP_ENV=" + SessionPrefs.desktopEnvironment(this))
} else if (SessionState.mode == MODE_PLASMA_MOBILE) {
guest.add("BL_DESKTOP_ENV=" + SessionPrefs.DESKTOP_ENV_PLASMA_MOBILE)
}
if (SessionState.hdr) {
// The activity opened the compositor's HDR gate: gamescope offers HDR to its clients
// and DXVK takes the HDR10 swapchain when a game asks for one.
@@ -504,7 +548,7 @@ class SessionService : Service() {
// Android has no /dev/shm; the cache stands in for it and, unlike the real thing, keeps
// whatever a session leaves behind. The client abandons tens of megabytes of streams a run.
FileUtils.clear(File(cacheDir, "shm"))
FileUtils.clear(File(cacheDir, if (externalDisplay) "shm-external-display" else "shm"))
val binds = ArrayList<String>()
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
@@ -525,8 +569,10 @@ class SessionService : Service() {
// tree and could not find the phone at all. The same storage is placed under home as
// well, and the ROMs folder chosen on the main screen beside it; a bind rather than a
// link, so a folder on an SD card works the same.
val home = File(LinuxRuntime.rootDir(this), "root")
val home = if (externalDisplay) File(filesDir, "plasma-mobile-home") else File(LinuxRuntime.rootDir(this), "root")
home.mkdirs()
File(home, "Storage").mkdirs()
if (externalDisplay) binds.add("${home.path}:/root")
binds.add(Environment.getExternalStorageDirectory().path + ":/root/Storage")
// A second Steam library: the storage chosen in the Steam cog, at the path the runtime's
// bannerlator-steam-library registers with the client. Nothing bound = the script removes
@@ -535,7 +581,7 @@ class SessionService : Service() {
if (library != null) {
val problem = GameStorage.prepare(library.path)
if (problem == null) {
File(LinuxRuntime.rootDir(this), "mnt/bannerlator-sd").mkdirs()
File(root, "mnt/bannerlator-sd").mkdirs()
binds.add("${library.path}:/mnt/bannerlator-sd")
Log.i(TAG, "game storage: ${library.path} -> /mnt/bannerlator-sd (\"${library.label}\")")
} else {
@@ -546,13 +592,13 @@ class SessionService : Service() {
}
// The user's own games folder (the Steam cog's "Added games"), bound at a fixed place so
// the shortcuts the app writes point somewhere whatever storage the folder is on.
for (root in com.droiddeck.launcher.frontend.AddedGames.roots(this)) {
if (root.host.isDirectory && root.host.canRead()) {
File(LinuxRuntime.rootDir(this), root.guest.removePrefix("/")).mkdirs()
binds.add(root.host.path + ":" + root.guest)
Log.i(TAG, "added games: ${root.host} -> ${root.guest}")
for (addedRoot in com.droiddeck.launcher.frontend.AddedGames.roots(this)) {
if (addedRoot.host.isDirectory && addedRoot.host.canRead()) {
File(root, addedRoot.guest.removePrefix("/")).mkdirs()
binds.add(addedRoot.host.path + ":" + addedRoot.guest)
Log.i(TAG, "added games: ${addedRoot.host} -> ${addedRoot.guest}")
} else {
Log.w(TAG, "added games: ${root.host} is not a readable folder this session")
Log.w(TAG, "added games: ${addedRoot.host} is not a readable folder this session")
}
}
val roms = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }?.let { File(it) }
@@ -564,8 +610,8 @@ class SessionService : Service() {
Log.w(TAG, "roms: $roms is not a readable folder; /root/ROMs not offered this session")
}
val command = LinuxRuntime.command(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
val command = LinuxRuntime.commandForRoot(
this, root, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, guest,
)
val hostEnv = HostEnvironment()
@@ -582,8 +628,8 @@ class SessionService : Service() {
val prootLibs = LinuxRuntime.prootLibraryPath(this)
if (prootLibs.isNotEmpty()) hostEnv["LD_LIBRARY_PATH"] = prootLibs
val terminalCommand = LinuxRuntime.command(
this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, shellGuest,
val terminalCommand = LinuxRuntime.commandForRoot(
this, root, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds, shellGuest,
)
val terminalHostEnvironment = LinkedHashMap(System.getenv())
hostEnv.asArray().forEach { entry ->
@@ -840,6 +886,7 @@ class SessionService : Service() {
SessionEvents.fail(code, message, failureStatus)
}
SessionState.notifyEnded(status)
SessionProcess.releaseSessionLock()
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
@@ -847,6 +894,7 @@ class SessionService : Service() {
private fun stopSession(status: Int) {
if (!SessionState.running) return
if (!SessionProcess.isExternalDisplay(this)) stopExternalDisplaySession(this)
SessionState.running = false
SessionState.stopRequested = false
SessionEvents.record("guest.exited", mapOf("status" to status))
@@ -875,6 +923,7 @@ class SessionService : Service() {
// dump the crash buffer. That was about four and a half seconds of blocked main thread,
// and Android ANR'd the app for it: the desktop session that would not let go.
val ended = SessionPaths.take()
val plasmaShellPid = readPlasmaShellPid(ended)
if (ended != null) Thread({ collectSessionArtifacts(ended) }, "session-collect").start()
components.reversed().forEach {
try {
@@ -890,9 +939,11 @@ class SessionService : Service() {
Thread({
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
stopPlasmaShell(plasmaShellPid, ended)
finishSessionStop(status)
}, "session-teardown").start()
} else {
stopPlasmaShell(plasmaShellPid, ended)
finishSessionStop(status)
}
}
@@ -912,6 +963,7 @@ class SessionService : Service() {
override fun onDestroy() {
stopSession(0)
if (!SessionState.running) SessionProcess.releaseSessionLock()
if (screenReceiverRegistered) {
unregisterReceiver(screenReceiver)
screenReceiverRegistered = false
@@ -973,8 +1025,9 @@ class SessionService : Service() {
private fun buildNotification(): Notification {
val manager = getSystemService(NotificationManager::class.java)
val channelId = notificationChannelId()
// IMPORTANCE_LOW: it must never make a sound or push a heads-up over a game.
val channel = NotificationChannel(CHANNEL_ID, getString(R.string.session_channel),
val channel = NotificationChannel(channelId, getString(R.string.session_channel),
NotificationManager.IMPORTANCE_LOW).apply {
description = getString(R.string.session_channel_description)
setShowBadge(false)
@@ -984,23 +1037,23 @@ class SessionService : Service() {
manager?.createNotificationChannel(channel)
val open = PendingIntent.getActivity(
this, 0,
Intent(this, SessionActivity::class.java)
this, notificationId(),
Intent(this, sessionActivityClass())
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_IMMUTABLE,
)
val stop = PendingIntent.getService(
this, 1, Intent(this, SessionService::class.java).setAction(ACTION_STOP),
this, notificationId() + 1, Intent(this, sessionServiceClass()).setAction(ACTION_STOP),
PendingIntent.FLAG_IMMUTABLE,
)
val resume = PendingIntent.getActivity(
this, 2,
Intent(this, SessionActivity::class.java)
this, notificationId() + 2,
Intent(this, sessionActivityClass())
.setAction(ACTION_RESUME)
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_IMMUTABLE,
)
return Notification.Builder(this, CHANNEL_ID)
return Notification.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(if (SessionState.suspended) R.string.session_notification_paused else R.string.session_notification))
@@ -1018,9 +1071,20 @@ class SessionService : Service() {
}
private fun refreshNotification() {
getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, buildNotification())
getSystemService(NotificationManager::class.java)?.notify(notificationId(), buildNotification())
}
private fun notificationId(): Int = if (SessionProcess.isExternalDisplay(this)) EXTERNAL_NOTIFICATION_ID else NOTIFICATION_ID
private fun notificationChannelId(): String =
if (SessionProcess.isExternalDisplay(this)) EXTERNAL_CHANNEL_ID else CHANNEL_ID
private fun sessionActivityClass(): Class<*> =
if (SessionProcess.isExternalDisplay(this)) ExternalSessionActivity::class.java else SessionActivity::class.java
private fun sessionServiceClass(): Class<*> =
if (SessionProcess.isExternalDisplay(this)) ExternalSessionService::class.java else SessionService::class.java
companion object {
private const val TAG = "SessionService"
/** Downloads file whose contents become TU_DEBUG inside the session, e.g. "sysmem". */
@@ -1029,6 +1093,8 @@ class SessionService : Service() {
private const val ENV_SWITCH = "Download/droiddeck-env"
private const val CHANNEL_ID = "session"
private const val NOTIFICATION_ID = 1001
private const val EXTERNAL_CHANNEL_ID = "session-external-display"
private const val EXTERNAL_NOTIFICATION_ID = 1002
const val ACTION_STOP = "com.droiddeck.launcher.STOP_SESSION"
const val ACTION_RESUME = "com.droiddeck.launcher.RESUME_SESSION"
const val ACTION_HOME_GUIDE = "com.droiddeck.launcher.HOME_GUIDE"
@@ -1041,7 +1107,7 @@ class SessionService : Service() {
private const val ACTION_AUXILIARY_EXITED = "com.droiddeck.launcher.AUXILIARY_EXITED"
private const val EXTRA_AUXILIARY_PID = "auxiliaryPid"
/** Command lines that can only belong to a session of ours. */
private val STRAGGLERS = listOf("bannerlator-session", "gamescope", "Xwayland", "steamrtarm64",
private val STRAGGLERS = listOf("bannerlator-session", "gamescope", "Xwayland", "kwin_wayland", "kwin_x11", "plasmashell", "steamrtarm64",
"steamwebhelper", "linuxfs/opt/android-host/proot", "/libproot.so", "pulseaudio/libpulseaudio.so")
/** How long proot gets to run its own cleanup before it is killed outright. */
private const val GRACE_MS = 1200L
@@ -1051,6 +1117,7 @@ class SessionService : Service() {
const val EXTRA_MODE = "mode"
const val MODE_STEAM = "steam"
const val MODE_DESKTOP = "lxqt"
const val MODE_PLASMA_MOBILE = "plasma-mobile"
/** A program inside the runtime, fullscreen under gamescope (EXTRA_PROGRAM = its path). */
const val MODE_RUN = "run"
const val EXTRA_PROGRAM = "program"
@@ -1061,11 +1128,16 @@ class SessionService : Service() {
const val EXTRA_STEAM_UI = "steamUi"
const val EXTRA_STEAM_URL = "steamUrl"
private fun serviceClass(mode: String): Class<*> =
if (mode == MODE_PLASMA_MOBILE) ExternalSessionService::class.java else SessionService::class.java
private fun currentServiceClass(): Class<*> = serviceClass(SessionState.mode)
fun start(
context: Context, mode: String = MODE_STEAM, program: String? = null,
steamUi: String? = null, steamUrl: String? = null, programArgs: Array<String>? = null,
) {
val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode)
val intent = Intent(context, serviceClass(mode)).putExtra(EXTRA_MODE, mode)
if (program != null) intent.putExtra(EXTRA_PROGRAM, program)
if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs)
if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi)
@@ -1075,29 +1147,33 @@ class SessionService : Service() {
}
fun stop(context: Context) {
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP))
context.startService(Intent(context, currentServiceClass()).setAction(ACTION_STOP))
}
/** Stops the independent Linux desktop hosted on the other Android display, if running. */
fun stopExternalDisplaySession(context: Context): Boolean =
context.stopService(Intent(context, ExternalSessionService::class.java))
fun setActivityVisible(context: Context, visible: Boolean) {
if (!SessionState.running) return
val action = if (visible) ACTION_ACTIVITY_VISIBLE else ACTION_ACTIVITY_HIDDEN
context.startService(Intent(context, SessionService::class.java).setAction(action))
context.startService(Intent(context, currentServiceClass()).setAction(action))
}
fun resume(context: Context) {
if (!SessionState.running) return
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_RESUME))
context.startService(Intent(context, currentServiceClass()).setAction(ACTION_RESUME))
}
fun suspendPolicyChanged(context: Context) {
if (!SessionState.running) return
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SUSPEND_POLICY_CHANGED))
context.startService(Intent(context, currentServiceClass()).setAction(ACTION_SUSPEND_POLICY_CHANGED))
}
/** Let the session service clean up the PTY's proot tree if the control screen closes. */
fun stopTerminalProcess(context: Context, pid: Int) {
if (pid > 1) context.startService(
Intent(context, SessionService::class.java)
Intent(context, currentServiceClass())
.setAction(ACTION_STOP_AUXILIARY)
.putExtra(EXTRA_AUXILIARY_PID, pid),
)
@@ -1105,7 +1181,7 @@ class SessionService : Service() {
fun registerTerminalProcess(context: Context, pid: Int) {
if (pid > 1) context.startService(
Intent(context, SessionService::class.java)
Intent(context, currentServiceClass())
.setAction(ACTION_TRACK_AUXILIARY)
.putExtra(EXTRA_AUXILIARY_PID, pid),
)
@@ -1113,7 +1189,7 @@ class SessionService : Service() {
fun terminalProcessExited(context: Context, pid: Int) {
if (pid > 1) context.startService(
Intent(context, SessionService::class.java)
Intent(context, currentServiceClass())
.setAction(ACTION_AUXILIARY_EXITED)
.putExtra(EXTRA_AUXILIARY_PID, pid),
)
@@ -59,6 +59,8 @@ class ModeSettings(
val clientDirectAudio: Boolean = false,
val mic: Boolean?,
val renderer: String?,
val desktopEnvironment: String? = null,
val plasmaMobileInstalled: Boolean = false,
val gameStorage: String? = null,
val storageOptions: List<Pair<String, String>> = emptyList(),
val fexPreset: String? = null,
@@ -114,6 +116,7 @@ class ModeSettingsActions(
val onClientDirectAudio: (Boolean) -> Unit = {},
val onMic: (Boolean) -> Unit,
val onRenderer: (String) -> Unit,
val onDesktopEnvironment: (String) -> Unit = {},
val onGameStorage: (path: String, label: String) -> Unit = { _, _ -> },
val onPickGameStorageFolder: () -> Unit = {},
val onFexPreset: (String) -> Unit = {},
@@ -220,6 +223,19 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
checked = s.hdr && s.hdrReason == null, enabled = s.hdrReason == null, onChange = a.onHdr,
)
}
if (s.desktopEnvironment != null) SettingsGroup("Desktop environment") {
ChoiceRow(
host, "desktop-environment", "Desktop", null,
SessionPrefs.desktopEnvironmentChoices, s.desktopEnvironment,
note = "KDE Plasma Mobile installs on first launch and can also run on a second screen.",
onPick = a.onDesktopEnvironment,
)
SettingsRow(
"KDE Plasma Mobile",
if (s.plasmaMobileInstalled) "Installed and ready."
else "Downloads packages from Arch Linux ARM the first time you open Desktop.",
) { }
}
SettingsGroup("Drivers") {
SettingsRow("Runtime driver", (if (steam) "Used by Steam and games." else "Used by desktop apps.") + " Applies next session.") {
ValueChip(
@@ -113,6 +113,7 @@ class SecondScreenPresentation(
SecondScreenMode.KEYBOARD_TRACKPAD -> renderKeyboardAndTrackpad()
SecondScreenMode.TERMINAL -> renderTerminal()
SecondScreenMode.NONE -> Unit
SecondScreenMode.PLASMA_MOBILE -> Unit
}
}
@@ -216,6 +216,7 @@ class DrawerActions(
val secondScreenMode: SecondScreenMode,
val secondScreenDisplays: List<SecondScreenDisplay>,
val selectedSecondScreenDisplay: Int,
val plasmaMobileInstalled: Boolean = false,
val onHud: (Boolean) -> Unit,
val onFrameGenPick: (engine: String, multiplier: Int) -> Unit,
/** The Android keyboard (text, turned into key presses). */
@@ -457,8 +458,10 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
}
}
if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup("Second screen") {
ChoiceRow(host, "second-screen-mode", "Controls", null,
listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL).map { it to it.label },
val secondScreenModes = listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) +
if (a.plasmaMobileInstalled) listOf(SecondScreenMode.PLASMA_MOBILE) else emptyList()
ChoiceRow(host, "second-screen-mode", "Mode", null,
secondScreenModes.map { it to it.label },
a.secondScreenMode, chipModifier = focus.track(page, "second-screen-mode"), onPick = a.onSecondScreenMode)
if (a.secondScreenDisplays.size > 1) ChoiceRow(host, "second-screen-display", "Display", null,
a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,