mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bec08e2134 | ||
|
|
941a6c3ef9 | ||
|
|
fe84c050ad | ||
|
|
f13c885fec | ||
|
|
a67c5cd3b2 | ||
|
|
5771cb89a2 | ||
|
|
b15bdd5739 | ||
|
|
4dfb9a5ae9 | ||
|
|
6c25bb1cd5 | ||
|
|
7d3fe09b01 | ||
|
|
f1d5dcd505 | ||
|
|
3f6fd9b40f | ||
|
|
70d3d1f6a4 |
No files matched your search
@@ -118,6 +118,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
|
||||
@@ -128,6 +141,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" />
|
||||
<!-- Holds the process in the foreground while the Linux runtime downloads and unpacks. -->
|
||||
<service
|
||||
android:name=".runtime.RuntimeInstallService"
|
||||
|
||||
@@ -24,6 +24,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>
|
||||
@@ -42,6 +42,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"
|
||||
@@ -745,6 +746,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;
|
||||
@@ -1081,6 +1099,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. */
|
||||
@@ -1099,10 +1119,12 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
* rather than composited, so it survives the zero-copy and HDR layer paths. */
|
||||
if (!buffer) {
|
||||
cursor_publish_hidden(); /* wlroots clears its cursor surface to hide the pointer */
|
||||
} else if (has_single_pixel) {
|
||||
cursor_publish_pixels((const uint8_t *)&pixel, 1, 1, 4, g_cursor_hx, g_cursor_hy);
|
||||
} else {
|
||||
cursor_publish_buffer(s, buffer);
|
||||
wl_buffer_send_release(buffer);
|
||||
}
|
||||
if (buffer) wl_buffer_send_release(buffer);
|
||||
} else if (s->role == ROLE_NONE) {
|
||||
/* Role-less surface: never drawn, but its buffer is kept for a set_cursor to come. */
|
||||
if (buffer) surface_hold_idle(s, buffer);
|
||||
@@ -1111,6 +1133,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;
|
||||
@@ -1414,6 +1439,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); }
|
||||
@@ -3464,6 +3563,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);
|
||||
|
||||
@@ -16,6 +16,7 @@ class App : Application() {
|
||||
CrashHandler.install(this)
|
||||
// Before anything else touches the session prefs: a new install's first read decides it.
|
||||
com.droiddeck.launcher.session.SessionPrefs.settleDeckModeDefault(this)
|
||||
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
||||
GpuClockPin.clearLeftover(this)
|
||||
BwrapSpawner.start(this)
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
|
||||
var compCatalog by mutableStateOf<List<ComponentsManager.CatalogItem>>(emptyList())
|
||||
var compCatalogAt by mutableStateOf(0L)
|
||||
var compProton by mutableStateOf<String?>(null)
|
||||
var compComp by mutableStateOf("dxvk")
|
||||
var compComp by mutableStateOf(com.droiddeck.launcher.ui.GPU_TAB)
|
||||
var compChecking by mutableStateOf(false)
|
||||
var compBusy by mutableStateOf<String?>(null)
|
||||
var compDownloads by mutableStateOf<Map<String, Int>>(emptyMap())
|
||||
|
||||
@@ -10,6 +10,10 @@ import android.util.Log
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import com.droiddeck.launcher.gpu.DriverBundle
|
||||
import com.droiddeck.launcher.gpu.DriverPairs
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
@@ -17,11 +21,16 @@ import com.droiddeck.launcher.gpu.TurnipReleases
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.ui.DriverRow
|
||||
import com.droiddeck.launcher.ui.GpuDriversState
|
||||
import com.droiddeck.launcher.ui.PairRow
|
||||
import com.droiddeck.launcher.wayland.CompositorHost
|
||||
|
||||
/**
|
||||
* The Linux and Android driver menus: the drivers each can pick from, the release downloads the
|
||||
* last check found, and what each mode is set to. The launcher screen keeps one and hands its
|
||||
* rows to the mode settings dialog.
|
||||
* The GPU drivers: what this GPU is, the matched driver pairs the release repos offer for it, and
|
||||
* - in Auto, the default - keeping the recommended pair installed and set. Under Advanced, the
|
||||
* Linux (runtime) and Android (display) lists as before, each picked on its own - except a
|
||||
* bundle's two halves (DriverBundle), which are always picked, and deleted, together. The launcher
|
||||
* screen keeps one and hands it to the Components page's GPU drivers tab.
|
||||
*/
|
||||
internal class DriverMenus(private val activity: Activity, private val ui: Handler) {
|
||||
var linuxRows by mutableStateOf<List<DriverRow>>(emptyList())
|
||||
@@ -33,17 +42,42 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
var canRestoreBundled by mutableStateOf(false)
|
||||
/** Asset name -> download percent, while it downloads. */
|
||||
private val releaseProgress = HashMap<String, Int>()
|
||||
var linuxSteam by mutableStateOf("")
|
||||
var linuxDesktop by mutableStateOf("")
|
||||
var linuxSelected by mutableStateOf("")
|
||||
val gpu: GpuInfo = GpuInfo.detect()
|
||||
// Read in refreshDrivers/ensureAuto: the activity has no context yet while its fields are made.
|
||||
var mode by mutableStateOf(SessionPrefs.GPU_DRIVERS_AUTO)
|
||||
var pairRows by mutableStateOf<List<PairRow>>(emptyList())
|
||||
/** The pair being installed, and how far along. */
|
||||
var pairBusy by mutableStateOf<String?>(null)
|
||||
var pairPercent by mutableIntStateOf(-1)
|
||||
/** What Auto last did or found, for the line under the pair in use. */
|
||||
var autoStatus by mutableStateOf("")
|
||||
/** The bundle both drivers are set to, as "DD-Turnip 0.1.0", or null when they are not one. */
|
||||
var activeBundle by mutableStateOf<String?>(null)
|
||||
private var autoCheckedThisProcess = false
|
||||
|
||||
fun state() = GpuDriversState(
|
||||
gpuName = gpu.name, gpuFamily = gpu.family.label, soc = gpu.soc, supportText = gpu.supportText,
|
||||
supported = gpu.support == GpuInfo.Support.TESTED, unsupported = gpu.support == GpuInfo.Support.UNSUPPORTED,
|
||||
auto = mode == SessionPrefs.GPU_DRIVERS_AUTO, pairs = pairRows, busy = pairBusy, percent = pairPercent,
|
||||
autoStatus = autoStatus, releaseStatus = releaseStatus, checking = releaseChecking,
|
||||
linuxRows = linuxRows, linuxSelected = linuxSelected, androidRows = androidRows, androidSelected = androidSelected,
|
||||
linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, canRestoreBundled = canRestoreBundled,
|
||||
activeBundle = activeBundle,
|
||||
)
|
||||
var androidRows by mutableStateOf<List<DriverRow>>(emptyList())
|
||||
var androidSelected by mutableStateOf("")
|
||||
|
||||
fun refreshDrivers() {
|
||||
val lm = LinuxVulkanDriverManager(activity)
|
||||
fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
|
||||
val bundles = DriverBundle.all(activity)
|
||||
fun bundleRow(id: String, linux: Boolean) = bundles.firstOrNull { (if (linux) it.linuxId else it.androidId) == id }?.let {
|
||||
DriverRow(id, it.label, "Android + Linux: sets the ${if (linux) "display" else "runtime"} driver with it", true, DriverRow.BUNDLE)
|
||||
}
|
||||
linuxRows = LinuxVulkanDriver.optionValues(activity).map { id ->
|
||||
if (id.isEmpty()) DriverRow("", "Runtime default", "the Turnip built into the runtime", false)
|
||||
else DriverRow(
|
||||
else bundleRow(id, linux = true) ?: DriverRow(
|
||||
id, lm.getDriverName(id),
|
||||
listOfNotNull(
|
||||
lm.getDriverVersion(id).takeIf { it.isNotEmpty() },
|
||||
@@ -52,8 +86,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
true, origin(id),
|
||||
)
|
||||
}
|
||||
linuxSteam = SessionPrefs.linuxDriver(activity, SessionService.MODE_STEAM)
|
||||
linuxDesktop = SessionPrefs.linuxDriver(activity, SessionService.MODE_DESKTOP)
|
||||
linuxSelected = SessionPrefs.linuxDriver(activity)
|
||||
mode = SessionPrefs.gpuDriverMode(activity)
|
||||
val td = TurnipDriver(activity)
|
||||
val auto = td.autoId()
|
||||
androidRows = buildList {
|
||||
@@ -63,23 +97,211 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
false,
|
||||
))
|
||||
for (id in td.visibleBundled()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, DriverRow.BUNDLED))
|
||||
for (id in td.enumerateImported()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, origin(id)))
|
||||
for (id in td.enumerateImported()) add(bundleRow(id, linux = false) ?: DriverRow(id, td.displayName(id), td.driverVersion(id), true, origin(id)))
|
||||
}
|
||||
canRestoreBundled = td.hiddenBundled().isNotEmpty()
|
||||
androidSelected = SessionPrefs.androidDriver(activity)
|
||||
activeBundle = DriverBundle.active(activity)?.label
|
||||
refreshReleaseRows()
|
||||
refreshPairs()
|
||||
}
|
||||
|
||||
/** One line for the settings row that opens this: "Auto · WinNative · Balanced". */
|
||||
fun summary(): String {
|
||||
val active = pairRows.firstOrNull { it.active }?.name ?: activeBundle
|
||||
return (if (mode == SessionPrefs.GPU_DRIVERS_AUTO) "Auto" else "Manual") + (active?.let { " · $it" } ?: "")
|
||||
}
|
||||
|
||||
/** The pairs the last check found, with what is installed and in use; this GPU's first. */
|
||||
fun refreshPairs() {
|
||||
val lm = LinuxVulkanDriverManager(activity)
|
||||
val td = TurnipDriver(activity)
|
||||
val pairs = DriverPairs.from(TurnipReleases.cached(activity))
|
||||
val recommended = DriverPairs.recommendedKey(gpu, pairs)
|
||||
pairRows = pairs.map { p ->
|
||||
val bundle = p.bundle?.let { installedBundle(it) }
|
||||
val displayId = if (p.bundle != null) bundle?.androidId else p.display?.let { TurnipReleases.installedId(activity, it, td::isInstalled) }
|
||||
val linuxId = if (p.bundle != null) bundle?.linuxId else p.linux?.let { TurnipReleases.installedId(activity, it, lm::isInstalled) }
|
||||
val mb = p.assets.sumOf { it.size } / 1_048_576.0
|
||||
PairRow(
|
||||
key = p.key, name = p.name, version = p.version,
|
||||
detail = if (!p.complete) "Only one half is published right now" else "%.0f MB for both".format(mb),
|
||||
recommended = p.key == recommended, suits = p.suits(gpu), complete = p.complete,
|
||||
installed = displayId != null && linuxId != null,
|
||||
active = displayId != null && linuxId != null &&
|
||||
SessionPrefs.androidDriver(activity) == displayId && SessionPrefs.linuxDriver(activity) == linuxId,
|
||||
)
|
||||
}.sortedByDescending { it.recommended }
|
||||
}
|
||||
|
||||
fun setMode(auto: Boolean) {
|
||||
mode = if (auto) SessionPrefs.GPU_DRIVERS_AUTO else SessionPrefs.GPU_DRIVERS_MANUAL
|
||||
SessionPrefs.setGpuDriverMode(activity, mode)
|
||||
autoStatus = ""
|
||||
if (auto) ensureAuto(force = false)
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto: make the recommended pair for this GPU the one installed and set. Looks online when
|
||||
* [force]d (refresh), or when the last check is a day old - Banners-Turnip rebuilds hourly, and
|
||||
* a new pair a day is plenty - otherwise works from the last check. Once per app start on its
|
||||
* own; the pair it replaces is removed, anything the user imported or picked is left alone.
|
||||
*/
|
||||
fun ensureAuto(force: Boolean) {
|
||||
mode = SessionPrefs.gpuDriverMode(activity)
|
||||
if (mode != SessionPrefs.GPU_DRIVERS_AUTO || pairBusy != null || releaseChecking) return
|
||||
if (!force && autoCheckedThisProcess) return
|
||||
autoCheckedThisProcess = true
|
||||
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
|
||||
autoStatus = "No drivers to set: ${gpu.supportText.lowercase()}"
|
||||
return
|
||||
}
|
||||
releaseChecking = true
|
||||
autoStatus = "Checking for the latest drivers…"
|
||||
Thread({
|
||||
val cached = TurnipReleases.cached(activity)
|
||||
val stale = cached == null || System.currentTimeMillis() - cached.checkedAt > 24 * 3_600_000L ||
|
||||
cached.assets.none { it.pair.isNotEmpty() }
|
||||
val problem = if (force || stale) runCatching { TurnipReleases.refresh(activity) }.exceptionOrNull()?.message else null
|
||||
ui.post {
|
||||
releaseChecking = false
|
||||
refreshReleaseRows()
|
||||
refreshPairs()
|
||||
val pairs = DriverPairs.from(TurnipReleases.cached(activity))
|
||||
val key = DriverPairs.recommendedKey(gpu, pairs)
|
||||
val pair = pairs.firstOrNull { it.key == key }
|
||||
val row = pairRows.firstOrNull { it.key == key }
|
||||
when {
|
||||
row?.active == true -> autoStatus = "Up to date" + (problem?.let { " (couldn't check: $it)" } ?: "")
|
||||
pair == null || !pair.complete ->
|
||||
autoStatus = problem?.let { "Couldn't check: $it" } ?: "The recommended drivers aren't published right now"
|
||||
else -> installPair(pair, auto = true)
|
||||
}
|
||||
}
|
||||
}, "gpu-driver-auto").start()
|
||||
}
|
||||
|
||||
/** Manual: install (if need be) and set both halves of a pair. */
|
||||
fun selectPair(key: String) {
|
||||
if (pairBusy != null) return
|
||||
val pair = DriverPairs.from(TurnipReleases.cached(activity)).firstOrNull { it.key == key && it.complete } ?: return
|
||||
installPair(pair, auto = false)
|
||||
}
|
||||
|
||||
/**
|
||||
* Download what is missing of [pair], then set both halves - only once both are in, so a
|
||||
* failed download never leaves a half-changed pair. Auto's own downloads are recorded, and the
|
||||
* ones the new pair replaces are removed.
|
||||
*/
|
||||
private fun installPair(pair: DriverPairs.DriverPair, auto: Boolean) {
|
||||
if (!pair.complete) return
|
||||
pairBusy = pair.key
|
||||
pairPercent = 0
|
||||
if (auto) autoStatus = "Downloading ${pair.name} ${pair.version}…"
|
||||
Thread({
|
||||
val lm = LinuxVulkanDriverManager(activity)
|
||||
val td = TurnipDriver(activity)
|
||||
var downloaded = false
|
||||
val result = runCatching {
|
||||
val zips = pair.assets
|
||||
val ids = zips.mapIndexed { i, asset ->
|
||||
installedIdOf(asset)
|
||||
?: installAsset(asset) { pct -> ui.post { pairPercent = (i * 100 + pct) / zips.size } }.also { downloaded = true }
|
||||
}
|
||||
if (pair.bundle != null) DriverBundle.get(activity, ids[0])!!.let { listOf(it.androidId, it.linuxId) } else ids
|
||||
}
|
||||
ui.post {
|
||||
pairBusy = null
|
||||
pairPercent = -1
|
||||
result.onSuccess { (displayId, linuxId) ->
|
||||
val displayChanged = SessionPrefs.androidDriver(activity) != displayId
|
||||
SessionPrefs.setAndroidDriver(activity, displayId)
|
||||
SessionPrefs.setLinuxDriver(activity, linuxId)
|
||||
val restart = if (displayChanged && CompositorHost.isStarted) " The display driver applies after DroidDeck restarts." else ""
|
||||
if (auto) {
|
||||
val previous = SessionPrefs.gpuAutoInstalled(activity)
|
||||
for (id in previous - setOf(displayId, linuxId)) {
|
||||
val bundle = DriverBundle.containing(activity, id, lm.isInstalled(id))
|
||||
when {
|
||||
bundle != null -> { DriverBundle.remove(activity, bundle); TurnipReleases.forget(activity, bundle.id) }
|
||||
lm.isInstalled(id) -> lm.removeDriver(id)
|
||||
else -> td.remove(id)
|
||||
}
|
||||
TurnipReleases.forget(activity, id)
|
||||
}
|
||||
SessionPrefs.setGpuAutoInstalled(activity, setOf(displayId, linuxId))
|
||||
autoStatus = (if (downloaded) "Updated to" else "Switched to") + " ${pair.name} ${pair.version}.$restart"
|
||||
} else {
|
||||
android.widget.Toast.makeText(activity, "Using ${pair.name} ${pair.version}.$restart", android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}.onFailure { e ->
|
||||
Log.w(TAG, "driver pair ${pair.key}", e)
|
||||
val why = if (e is IllegalArgumentException) e.message else "Download failed: ${e.message}"
|
||||
if (auto) autoStatus = why ?: "Download failed"
|
||||
else android.widget.Toast.makeText(activity, why, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
refreshDrivers()
|
||||
}
|
||||
}, "gpu-driver-pair").start()
|
||||
}
|
||||
|
||||
/** The bundle a release bundle was downloaded as, while both its halves are installed. */
|
||||
private fun installedBundle(asset: TurnipReleases.Asset): DriverBundle.Bundle? =
|
||||
TurnipReleases.installedId(activity, asset) { DriverBundle.get(activity, it) != null }?.let { DriverBundle.get(activity, it) }
|
||||
|
||||
/** The id a release asset was installed as (a bundle's id for a bundle), or null when it is not installed. */
|
||||
private fun installedIdOf(asset: TurnipReleases.Asset): String? = when {
|
||||
asset.bundle -> installedBundle(asset)?.id
|
||||
asset.linux -> TurnipReleases.installedId(activity, asset, LinuxVulkanDriverManager(activity)::isInstalled)
|
||||
else -> TurnipReleases.installedId(activity, asset, TurnipDriver(activity)::isInstalled)
|
||||
}
|
||||
|
||||
/**
|
||||
* One release asset, downloaded, checked and installed through the importer; returns its id,
|
||||
* a bundle's id for a bundle.
|
||||
*/
|
||||
private fun installAsset(asset: TurnipReleases.Asset, progress: (Int) -> Unit): String {
|
||||
var file: File? = null
|
||||
try {
|
||||
file = TurnipReleases.download(activity, asset, progress)
|
||||
val uri = Uri.fromFile(file)
|
||||
val id = when {
|
||||
asset.bundle -> DriverBundle.install(activity, uri).id
|
||||
asset.linux -> LinuxVulkanDriverManager(activity).installDriver(uri, asset.name)
|
||||
else -> TurnipDriver(activity).installFromZip(uri, asset.name)
|
||||
}
|
||||
TurnipReleases.recordDownload(activity, asset, id)
|
||||
return id
|
||||
} finally {
|
||||
file?.let { com.droiddeck.launcher.core.FileUtils.delete(it) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Import off the main thread - a driver zip is a few MB and the glibc check reads the whole
|
||||
* library - then say what happened. A refusal's message is the user-facing reason.
|
||||
* library - then say what happened. A refusal's message is the user-facing reason. A bundle,
|
||||
* from any import, installs both halves and is set as both drivers at once. [linux] null (the
|
||||
* tab's own Import .zip) takes a single driver to whichever list its libc belongs in.
|
||||
*/
|
||||
fun importDriver(uri: Uri, linux: Boolean) {
|
||||
fun importDriver(uri: Uri, linux: Boolean?) {
|
||||
val name = activity.displayNameOf(uri)
|
||||
Thread({
|
||||
var bundle: DriverBundle.Bundle? = null
|
||||
val problem = try {
|
||||
if (linux) LinuxVulkanDriverManager(activity).installDriver(uri, name)
|
||||
else TurnipDriver(activity).installFromZip(uri, name)
|
||||
when {
|
||||
DriverBundle.isBundle(activity, uri) -> bundle = DriverBundle.install(activity, uri)
|
||||
linux == true -> LinuxVulkanDriverManager(activity).installDriver(uri, name)
|
||||
linux == false -> TurnipDriver(activity).installFromZip(uri, name)
|
||||
else -> try {
|
||||
TurnipDriver(activity).installFromZip(uri, name)
|
||||
} catch (display: IllegalArgumentException) {
|
||||
try {
|
||||
LinuxVulkanDriverManager(activity).installDriver(uri, name)
|
||||
} catch (runtime: IllegalArgumentException) {
|
||||
throw IllegalArgumentException("Not a driver zip: neither an AdrenoTools driver, a -Linux Turnip nor an Android + Linux bundle")
|
||||
}
|
||||
}
|
||||
}
|
||||
null
|
||||
} catch (e: IllegalArgumentException) {
|
||||
e.message
|
||||
@@ -88,26 +310,57 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
"Import failed: ${e.message}"
|
||||
}
|
||||
ui.post {
|
||||
val done = bundle?.let { useBundle(it) } ?: "Imported ${name ?: "driver"}"
|
||||
android.widget.Toast.makeText(
|
||||
activity, problem ?: "Imported ${name ?: "driver"}",
|
||||
if (problem != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT,
|
||||
activity, problem ?: done,
|
||||
if (problem != null || bundle != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT,
|
||||
).show()
|
||||
refreshDrivers()
|
||||
}
|
||||
}, "import-driver").start()
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick one driver from a list, which is Manual (Auto would put its pair back). A bundle's half
|
||||
* sets the bundle's other half in the other list as well.
|
||||
*/
|
||||
fun selectDriver(id: String, linux: Boolean) {
|
||||
val bundle = DriverBundle.containing(activity, id, linux)
|
||||
when {
|
||||
bundle != null -> useBundle(bundle)
|
||||
linux -> SessionPrefs.setLinuxDriver(activity, id)
|
||||
else -> SessionPrefs.setAndroidDriver(activity, id)
|
||||
}
|
||||
setMode(false)
|
||||
refreshDrivers()
|
||||
}
|
||||
|
||||
/** Set both halves of [bundle] as the drivers in use; returns what to tell the user. */
|
||||
private fun useBundle(bundle: DriverBundle.Bundle): String {
|
||||
val displayChanged = SessionPrefs.androidDriver(activity) != bundle.androidId
|
||||
DriverBundle.select(activity, bundle)
|
||||
if (mode == SessionPrefs.GPU_DRIVERS_AUTO) setMode(false)
|
||||
return "Using ${bundle.label} as both the runtime and display driver." +
|
||||
if (displayChanged && CompositorHost.isStarted) " The display driver applies after DroidDeck restarts." else ""
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an imported or downloaded driver. A mode still set to it goes back to its default, so a
|
||||
* session never starts on a driver that is gone; a release download is forgotten, so the menu
|
||||
* offers it again.
|
||||
*/
|
||||
fun deleteDriver(id: String, linux: Boolean) {
|
||||
val bundle = DriverBundle.containing(activity, id, linux)
|
||||
if (bundle != null) {
|
||||
DriverBundle.remove(activity, bundle)
|
||||
TurnipReleases.forget(activity, bundle.id)
|
||||
android.widget.Toast.makeText(activity, "Deleted ${bundle.label} (both drivers)", android.widget.Toast.LENGTH_SHORT).show()
|
||||
refreshDrivers()
|
||||
return
|
||||
}
|
||||
if (linux) {
|
||||
LinuxVulkanDriverManager(activity).removeDriver(id)
|
||||
for (mode in listOf(SessionService.MODE_STEAM, SessionService.MODE_DESKTOP)) {
|
||||
if (SessionPrefs.linuxDriver(activity, mode) == id) SessionPrefs.setLinuxDriver(activity, mode, "")
|
||||
}
|
||||
if (SessionPrefs.linuxDriver(activity) == id) SessionPrefs.setLinuxDriver(activity, "")
|
||||
} else {
|
||||
val td = TurnipDriver(activity)
|
||||
if (id in TurnipDriver.BUNDLED) td.hideBundled(id) else td.remove(id)
|
||||
@@ -121,11 +374,9 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
/** The download entries and the refresh line, from what the last check found. */
|
||||
fun refreshReleaseRows() {
|
||||
val check = TurnipReleases.cached(activity)
|
||||
val lm = LinuxVulkanDriverManager(activity)
|
||||
val td = TurnipDriver(activity)
|
||||
fun rows(linux: Boolean) = check?.assets.orEmpty()
|
||||
.filter { it.linux == linux }
|
||||
.filter { a -> TurnipReleases.installedId(activity, a) { id -> if (linux) lm.isInstalled(id) else td.isInstalled(id) } == null }
|
||||
.filter { it.bundle || it.linux == linux }
|
||||
.filter { a -> installedIdOf(a) == null }
|
||||
.map { a ->
|
||||
val mb = "%.1f MB".format(a.size / 1_048_576.0)
|
||||
com.droiddeck.launcher.ui.DownloadRow(a.name, "${a.source} ${a.tag}", "${a.label} · $mb", releaseProgress[a.name])
|
||||
@@ -154,7 +405,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
fun checkLatestTurnip() {
|
||||
if (releaseChecking) return
|
||||
releaseChecking = true
|
||||
releaseStatus = "Checking Banners-Turnip and WinNative…"
|
||||
releaseStatus = "Checking Banners-Turnip, WinNative and DroidDeck…"
|
||||
Thread({
|
||||
val problem = try { TurnipReleases.refresh(activity); null } catch (e: Exception) {
|
||||
Log.w(TAG, "latest Turnip check", e); e.message ?: "check failed"
|
||||
@@ -162,6 +413,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
ui.post {
|
||||
releaseChecking = false
|
||||
refreshReleaseRows()
|
||||
refreshPairs()
|
||||
if (problem != null) releaseStatus = "Couldn't check: $problem"
|
||||
}
|
||||
}, "turnip-release-check").start()
|
||||
@@ -174,28 +426,20 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
releaseProgress[assetName] = 0
|
||||
refreshReleaseRows()
|
||||
Thread({
|
||||
var file: java.io.File? = null
|
||||
val problem = try {
|
||||
file = TurnipReleases.download(activity, asset) { pct ->
|
||||
ui.post { releaseProgress[assetName] = pct; refreshReleaseRows() }
|
||||
}
|
||||
val uri = Uri.fromFile(file)
|
||||
val id = if (asset.linux) LinuxVulkanDriverManager(activity).installDriver(uri, asset.name)
|
||||
else TurnipDriver(activity).installFromZip(uri, asset.name)
|
||||
TurnipReleases.recordDownload(activity, asset, id)
|
||||
installAsset(asset) { pct -> ui.post { releaseProgress[assetName] = pct; refreshReleaseRows() } }
|
||||
null
|
||||
} catch (e: IllegalArgumentException) {
|
||||
e.message
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "release driver download", e)
|
||||
"Download failed: ${e.message}"
|
||||
} finally {
|
||||
file?.let { com.droiddeck.launcher.core.FileUtils.delete(it) }
|
||||
}
|
||||
ui.post {
|
||||
releaseProgress.remove(assetName)
|
||||
val pick = if (asset.bundle) "pick it in either list to set both drivers" else "pick it in the menu"
|
||||
android.widget.Toast.makeText(
|
||||
activity, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - pick it in the menu",
|
||||
activity, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - $pick",
|
||||
android.widget.Toast.LENGTH_LONG,
|
||||
).show()
|
||||
refreshDrivers()
|
||||
|
||||
@@ -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()
|
||||
@@ -125,6 +125,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 showPerformance by mutableStateOf(false)
|
||||
@@ -160,6 +162,9 @@ class MainActivity : ComponentActivity() {
|
||||
private val pickAndroidDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = false) }
|
||||
}
|
||||
private val pickAnyDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = null) }
|
||||
}
|
||||
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
|
||||
}
|
||||
@@ -657,11 +662,11 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
/** On the Components page the pad's LB / RB step through FEX, DXVK and VKD3D-Proton, wrapping around. */
|
||||
/** On the Components page the pad's LB / RB step through GPU drivers, FEX, DXVK and VKD3D-Proton, wrapping around. */
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
val all = ComponentsManager.COMPONENTS
|
||||
val all = listOf(com.droiddeck.launcher.ui.GPU_TAB) + ComponentsManager.COMPONENTS
|
||||
val step = if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else all.size - 1
|
||||
components.compComp = all[(all.indexOf(components.compComp).coerceAtLeast(0) + step) % all.size]
|
||||
}
|
||||
@@ -681,6 +686,8 @@ class MainActivity : ComponentActivity() {
|
||||
syncLossless()
|
||||
// Opening the app and coming back from a session both land here.
|
||||
updates.onResume()
|
||||
// Auto keeps this GPU's recommended driver pair installed and set: once per app start.
|
||||
drivers.ensureAuto(force = false)
|
||||
// Swaps queued while a game ran on that Proton go in once nothing uses it (usually the
|
||||
// session has just ended). Cheap when nothing is queued.
|
||||
if (!SessionState.running) Thread({
|
||||
@@ -807,14 +814,16 @@ class MainActivity : ComponentActivity() {
|
||||
)
|
||||
}
|
||||
|
||||
private fun openComponents(focusContent: Boolean = true) {
|
||||
private fun openComponents(focusContent: Boolean = true, tab: String? = null) {
|
||||
focusComponentsContent = focusContent
|
||||
if (tab != null) components.compComp = tab
|
||||
settingsMode = null
|
||||
showPerformance = false
|
||||
showProtons = false
|
||||
showMapping = false
|
||||
showComponents = true
|
||||
components.refreshComponents(snapshotFirst = true)
|
||||
drivers.refreshDrivers()
|
||||
}
|
||||
|
||||
private fun importComponent(uri: Uri) {
|
||||
@@ -849,6 +858,22 @@ class MainActivity : ComponentActivity() {
|
||||
onRefresh = { components.refreshComponentCatalog() },
|
||||
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, "Choose a component package (-linux .wcp)")) },
|
||||
onBack = { showComponents = false },
|
||||
gpu = drivers.state(),
|
||||
gpuActions = com.droiddeck.launcher.ui.GpuDriversActions(
|
||||
onAuto = { on -> drivers.setMode(on) },
|
||||
onPair = { key -> drivers.selectPair(key) },
|
||||
onRefresh = { if (drivers.mode == SessionPrefs.GPU_DRIVERS_AUTO) drivers.ensureAuto(force = true) else drivers.checkLatestTurnip() },
|
||||
// Picking one driver on its own is Manual: Auto would put its pair back.
|
||||
onSelectLinux = { id -> drivers.selectDriver(id, linux = true) },
|
||||
onSelectAndroid = { id -> drivers.selectDriver(id, linux = false) },
|
||||
onRemoveLinux = { id -> drivers.deleteDriver(id, linux = true) },
|
||||
onRemoveAndroid = { id -> drivers.deleteDriver(id, linux = false) },
|
||||
onDownloadDriver = { name -> drivers.downloadReleaseDriver(name) },
|
||||
onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip or Android + Linux bundle)")) },
|
||||
onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip or Android + Linux bundle)")) },
|
||||
onImportZip = { pickAnyDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a driver zip or an Android + Linux bundle")) },
|
||||
onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() },
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -916,9 +941,7 @@ class MainActivity : ComponentActivity() {
|
||||
ModeSettings(
|
||||
mode = mode, resolutionCap = resolutionCap, customResolution = customResolution, shapeMode = shapeMode,
|
||||
hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit,
|
||||
linuxRows = drivers.linuxRows,
|
||||
linuxSelected = if (mode == SessionService.MODE_STEAM) drivers.linuxSteam else drivers.linuxDesktop,
|
||||
androidRows = drivers.androidRows, androidSelected = drivers.androidSelected,
|
||||
gpuDrivers = drivers.summary(),
|
||||
touchMode = touchMode,
|
||||
suspendPolicy = suspendPolicy,
|
||||
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
|
||||
@@ -928,6 +951,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,
|
||||
@@ -939,8 +964,6 @@ class MainActivity : ComponentActivity() {
|
||||
addedGamesDirs = if (mode == SessionService.MODE_STEAM) addedGamesDirs else null,
|
||||
addedGames = if (mode == SessionService.MODE_STEAM) addedGames else emptyList(),
|
||||
addedGamesArt = addedGamesArt,
|
||||
linuxDownloads = drivers.linuxDownloads, androidDownloads = drivers.androidDownloads, releaseStatus = drivers.releaseStatus,
|
||||
releaseChecking = drivers.releaseChecking, canRestoreBundled = drivers.canRestoreBundled,
|
||||
deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null,
|
||||
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyReleases.firstOrNull() else null,
|
||||
deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent,
|
||||
@@ -951,16 +974,8 @@ class MainActivity : ComponentActivity() {
|
||||
onCustomResolution = { size -> SessionPrefs.setCustomResolution(this, mode, size); customResolution = size },
|
||||
onShape = { shape -> SessionPrefs.setShapeMode(this, shape); shapeMode = shape },
|
||||
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
|
||||
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
|
||||
onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps },
|
||||
onSelectLinux = { id -> SessionPrefs.setLinuxDriver(this, mode, id); drivers.refreshDrivers() },
|
||||
onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip)")) },
|
||||
onRemoveLinux = { id -> drivers.deleteDriver(id, linux = true) },
|
||||
onRefreshReleases = { drivers.checkLatestTurnip() },
|
||||
onDownloadDriver = { name -> drivers.downloadReleaseDriver(name) },
|
||||
onRestoreBundled = { TurnipDriver(this).restoreBundled(); drivers.refreshDrivers() },
|
||||
onSelectAndroid = { id -> SessionPrefs.setAndroidDriver(this, id); drivers.refreshDrivers() },
|
||||
onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip)")) },
|
||||
onRemoveAndroid = { id -> drivers.deleteDriver(id, linux = false) },
|
||||
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
|
||||
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
|
||||
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
||||
@@ -981,6 +996,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 }))
|
||||
@@ -1143,6 +1162,8 @@ class MainActivity : ComponentActivity() {
|
||||
private fun refresh() {
|
||||
if (!busy && LinuxRuntimeInstaller.isInstalling()) followInstall { LinuxRuntimeInstaller.attach(it) }
|
||||
desktopInstalled = DesktopCatalog.desktopInstalled(this)
|
||||
plasmaMobileInstalled = DesktopCatalog.plasmaMobileInstalled(this)
|
||||
desktopEnvironment = SessionPrefs.desktopEnvironment(this)
|
||||
offlineAccount = OfflineMode.account(this)
|
||||
offline = OfflineMode.enabled(this)
|
||||
installed = LinuxRuntimeInstaller.installedVersion(this)
|
||||
|
||||
@@ -58,6 +58,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
|
||||
@@ -88,7 +89,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
|
||||
@@ -262,7 +263,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
|
||||
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
|
||||
@Suppress("DEPRECATION")
|
||||
@@ -287,12 +288,23 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
loading = LoadingState(this, steam = loadingMode() == SessionService.MODE_STEAM)
|
||||
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)
|
||||
val needProton = (intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) == SessionService.MODE_STEAM &&
|
||||
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
|
||||
val needProton = requestedMode == SessionService.MODE_STEAM &&
|
||||
com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this)
|
||||
if (needRuntime || needDesktop || needProton) installThenStart(needRuntime, needDesktop, needProton)
|
||||
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 || needProton) {
|
||||
installThenStart(needRuntime, needDesktop, needPlasma, needProton)
|
||||
}
|
||||
}
|
||||
hud = PerfHud(this)
|
||||
hud.onPresentingWindowChanged = {
|
||||
@@ -309,6 +321,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
floodColor = it
|
||||
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(it))
|
||||
}
|
||||
}
|
||||
sessionOverlay = createSessionOverlay()
|
||||
root.addView(sessionOverlay)
|
||||
setContentView(root)
|
||||
@@ -392,11 +405,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
frameGen = frameGen,
|
||||
lossless = lossless,
|
||||
oscMode = oscMode, suspendPolicy = suspendPolicy, touchMode = touchMode,
|
||||
directTouchOnly = SessionProcess.isExternalDisplay(this@SessionActivity),
|
||||
touchAuto = if (usingTouchpad()) "touchpad" else "direct",
|
||||
shapeMode = shapeMode, fexPreset = fexPreset,
|
||||
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 = { mode ->
|
||||
@@ -482,6 +498,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun refreshHomeApp() {
|
||||
isHomeApp = HomeApp.isDefault(this)
|
||||
androidApps = if (isHomeApp) HomeApp.launchableApps(this) else emptyList()
|
||||
@@ -612,7 +629,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun readPrefs() {
|
||||
hudOn = SessionPrefs.hudEnabled(this)
|
||||
fillScreen = SessionPrefs.forceFullscreen(this)
|
||||
touchMode = SessionPrefs.touchMode(this)
|
||||
touchMode = if (SessionProcess.isExternalDisplay(this)) SessionPrefs.TOUCH_DIRECT
|
||||
else SessionPrefs.touchMode(this)
|
||||
frameGen = FrameGen.mode(this)
|
||||
fexPreset = SessionPrefs.fexPreset(this)
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
|
||||
@@ -636,17 +654,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
* dialog, download or client restart. Not being able to fetch it stops nothing: the session
|
||||
* then asks the client for it after sign-in, as it always has.
|
||||
*/
|
||||
private fun installThenStart(runtime: Boolean, desktop: Boolean, proton: Boolean = false) {
|
||||
private fun installThenStart(runtime: Boolean, desktop: Boolean, plasmaMobile: Boolean, proton: Boolean) {
|
||||
if (SessionState.stopRequested) return
|
||||
installingRuntime = true
|
||||
SessionState.installing = if (runtime) "runtime" else if (desktop) "desktop" else "proton"
|
||||
SessionState.installing = when {
|
||||
runtime -> "runtime"
|
||||
desktop -> "desktop"
|
||||
plasmaMobile -> "plasma-mobile"
|
||||
else -> "proton"
|
||||
}
|
||||
SessionEvents.transition(
|
||||
SessionPhase.INSTALLING_RUNTIME,
|
||||
"${SessionState.installing}.installing",
|
||||
mapOf("component" to SessionState.installing),
|
||||
)
|
||||
loading.step = if (runtime) "downloading the Linux runtime" else if (desktop) "downloading the desktop"
|
||||
else "downloading Proton Experimental (ARM64)"
|
||||
loading.step = when {
|
||||
runtime -> "downloading the Linux runtime"
|
||||
desktop -> "downloading the desktop"
|
||||
plasmaMobile -> "installing KDE Plasma Mobile"
|
||||
else -> "downloading Proton Experimental (ARM64)"
|
||||
}
|
||||
loading.percent = -1
|
||||
Thread({
|
||||
var failedComponent: String? = null
|
||||
@@ -661,6 +688,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"
|
||||
}
|
||||
if (problem == null && proton && !SessionState.stopRequested) {
|
||||
SessionState.installing = "proton"
|
||||
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "proton.installing", mapOf("component" to "proton"))
|
||||
@@ -668,6 +701,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (protonProblem == null) SessionEvents.record("proton.ready")
|
||||
else SessionEvents.record("proton.skipped", mapOf("reason" to protonProblem))
|
||||
}
|
||||
}
|
||||
uiHandler.post {
|
||||
installingRuntime = false
|
||||
SessionState.installing = null
|
||||
@@ -679,7 +713,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)
|
||||
@@ -734,6 +772,17 @@ 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." }
|
||||
}
|
||||
|
||||
/** Null when the ARM64 Proton is in, else why not; the session goes on either way. */
|
||||
private fun installProton(): String? {
|
||||
uiHandler.post { loading.percent = -1; loading.step = "downloading Proton Experimental (ARM64)" }
|
||||
@@ -742,13 +791,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
?: return "catalog unreachable"
|
||||
return catalog.install(this, entry, progressFor("Proton Experimental (ARM64)", entry.size / 1_000_000))
|
||||
}
|
||||
}
|
||||
|
||||
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"))
|
||||
@@ -865,6 +917,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
val panelW = maxOf(bounds.width(), bounds.height()).toFloat()
|
||||
val panelH = minOf(bounds.width(), bounds.height()).toFloat()
|
||||
// Plasma Mobile on a secondary display is a full external desktop. Use that display's
|
||||
// logical panel size directly; the handheld's saved 16:9 floor and 720p cap otherwise
|
||||
// leave large bars on the external screen.
|
||||
if (SessionProcess.isExternalDisplay(this)) {
|
||||
return Pair(panelW.toInt() and 1.inv(), panelH.toInt() and 1.inv())
|
||||
}
|
||||
// Never narrower than 16:9. A foldable's inner panel is nearly square, and a game handed a
|
||||
// square display draws for the frame it was made for and cuts the sides off itself.
|
||||
// Wider than 16:9 is fine - games and the client cope with a phone's 20:9 - so the
|
||||
@@ -973,7 +1031,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
|
||||
@@ -1352,29 +1410,38 @@ 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)
|
||||
// A choice kept while its display was away (asleep, waking): back as soon as it is.
|
||||
else if (started && secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||
if (secondScreenMode != SecondScreenMode.NONE && candidates.isEmpty()) {
|
||||
closeSecondScreen(reset = true, stopPlasma = true)
|
||||
} else if (started && secondScreenMode != SecondScreenMode.NONE &&
|
||||
secondScreenMode != SecondScreenMode.PLASMA_MOBILE && secondScreenPresentation == null) {
|
||||
// A regular presentation can be restored when its display returns. Plasma Mobile owns
|
||||
// a separate activity and is deliberately not relaunched from display callbacks.
|
||||
showSecondScreen(secondScreenMode)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
SessionState.secondScreenDisplay = 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 }) {
|
||||
@@ -1386,11 +1453,49 @@ 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) {
|
||||
// Not there right now - a panel still waking, say. The choice is kept; the display
|
||||
// listener shows it again when the display comes back (refreshSecondScreenDisplays).
|
||||
closeSecondScreen(reset = false)
|
||||
if (mode == SecondScreenMode.PLASMA_MOBILE) {
|
||||
closeSecondScreen(reset = true, stopPlasma = true)
|
||||
refreshSecondScreenDisplays()
|
||||
} else {
|
||||
// A regular presentation may be restored when its display wakes or returns.
|
||||
closeSecondScreen(reset = false)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (mode == SecondScreenMode.PLASMA_MOBILE) {
|
||||
if (!com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this) ||
|
||||
!com.droiddeck.launcher.runtime.DesktopCatalog.plasmaMobileInstalled(this)) {
|
||||
secondScreenMode = SecondScreenMode.NONE
|
||||
SessionState.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
|
||||
SessionState.secondScreenMode = mode
|
||||
SessionState.secondScreenDisplay = selectedSecondScreenDisplay
|
||||
} 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
|
||||
SessionState.secondScreenMode = SecondScreenMode.NONE
|
||||
}
|
||||
return
|
||||
}
|
||||
if (secondScreenMode == SecondScreenMode.PLASMA_MOBILE) {
|
||||
SessionService.stopExternalDisplaySession(this)
|
||||
secondScreenMode = SecondScreenMode.NONE
|
||||
SessionState.secondScreenMode = SecondScreenMode.NONE
|
||||
}
|
||||
var presentation = secondScreenPresentation
|
||||
if (presentation?.display?.displayId != target.displayId) {
|
||||
presentation?.closeControls()
|
||||
@@ -1438,7 +1543,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) {
|
||||
@@ -1447,11 +1555,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
|
||||
/** Touchpad on the desktop, direct in Steam, unless the drawer says otherwise. */
|
||||
private fun usingTouchpad(): Boolean = when (SessionPrefs.touchMode(this)) {
|
||||
SessionPrefs.TOUCH_PAD -> true
|
||||
SessionPrefs.TOUCH_DIRECT -> false
|
||||
else -> SessionState.mode != SessionService.MODE_STEAM || SessionState.steamUi == "desktop"
|
||||
/** Direct touch on external desktops; otherwise use the user's touch setting. */
|
||||
private fun usingTouchpad(): Boolean {
|
||||
if (SessionProcess.isExternalDisplay(this)) return false
|
||||
return when (SessionPrefs.touchMode(this)) {
|
||||
SessionPrefs.TOUCH_PAD -> true
|
||||
SessionPrefs.TOUCH_DIRECT -> false
|
||||
else -> SessionState.mode != SessionService.MODE_STEAM || SessionState.steamUi == "desktop"
|
||||
}
|
||||
}
|
||||
|
||||
/** The picture's rectangle inside the view: where the pointer may go. */
|
||||
@@ -1541,7 +1652,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()
|
||||
@@ -1560,7 +1672,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
started = true
|
||||
displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper()))
|
||||
refreshSecondScreenDisplays()
|
||||
if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) 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 &&
|
||||
secondScreenPresentation == null) {
|
||||
showSecondScreen(secondScreenMode)
|
||||
}
|
||||
SessionService.setActivityVisible(this, true)
|
||||
}
|
||||
|
||||
@@ -1568,8 +1685,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
started = false
|
||||
displayManager.unregisterDisplayListener(displayListener)
|
||||
// Closed while the session is out of sight (sleep, a closed lid, another app), and kept:
|
||||
// onStart puts it back.
|
||||
closeSecondScreen(reset = false)
|
||||
// onStart puts a regular presentation back. Plasma Mobile runs in its own activity.
|
||||
if (secondScreenMode != SecondScreenMode.PLASMA_MOBILE) closeSecondScreen(reset = false)
|
||||
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 {
|
||||
@@ -113,19 +118,24 @@ object DeviceReport {
|
||||
k("Foldable", context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle"))
|
||||
|
||||
h("Drivers")
|
||||
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
|
||||
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
|
||||
k("Driver mode", SessionPrefs.gpuDriverMode(context) +
|
||||
(com.droiddeck.launcher.gpu.DriverPairs.recommendedKey(gpu, com.droiddeck.launcher.gpu.DriverPairs.from(
|
||||
com.droiddeck.launcher.gpu.TurnipReleases.cached(context)))?.let { " (recommended pair: $it)" } ?: ""))
|
||||
val turnip = TurnipDriver(context)
|
||||
val androidChoice = SessionPrefs.androidDriver(context)
|
||||
k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> ${turnip.autoId()}" else androidChoice)
|
||||
k(" name / version", "${turnip.displayName(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)} ${turnip.driverVersion(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)}".trim())
|
||||
k(" imported available", turnip.enumerateImported().ifEmpty { listOf("none") }.joinToString(", "))
|
||||
val lm = LinuxVulkanDriverManager(context)
|
||||
for (m in listOf(SessionService.MODE_STEAM, SessionService.MODE_DESKTOP)) {
|
||||
val id = SessionPrefs.linuxDriver(context, m)
|
||||
run {
|
||||
val id = SessionPrefs.linuxDriver(context)
|
||||
val label = if (id.isEmpty()) "runtime default (the Turnip built into the runtime)"
|
||||
else "${lm.getDriverName(id)} ${lm.getDriverVersion(id)}".trim() +
|
||||
lm.getMinGlibc(id).let { if (it.isEmpty()) "" else " (glibc $it+)" } +
|
||||
if (lm.isInstalled(id)) "" else " [MISSING - falls back to the runtime's own]"
|
||||
k("Linux driver ($m)", label)
|
||||
k("Linux driver", label)
|
||||
}
|
||||
k("Runtime's own ICD", LinuxRuntime.vulkanIcd(context)?.path)
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ import java.util.zip.CRC32
|
||||
/** Windows game folders shared with the Steam session. */
|
||||
object AddedGames {
|
||||
private const val TAG = "AddedGames"
|
||||
private const val LIBRARY = "/mnt/droiddeck-sd"
|
||||
private const val LEGACY_LIBRARY = "/mnt/bannerlator-sd"
|
||||
|
||||
class Game(
|
||||
val folder: File, val name: String, val exe: File, val guestExe: String, val guestDir: String,
|
||||
@@ -65,7 +67,7 @@ object AddedGames {
|
||||
if (path.startsWith("$roms/")) return "/root/ROMs/" + path.removePrefix("$roms/")
|
||||
}
|
||||
GameStorage.effective(context)?.let { lib ->
|
||||
if (path.startsWith("${lib.path}/")) return "/mnt/bannerlator-sd/" + path.removePrefix("${lib.path}/")
|
||||
if (path.startsWith("${lib.path}/")) return "$LIBRARY/" + path.removePrefix("${lib.path}/")
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -108,7 +110,8 @@ object AddedGames {
|
||||
if (guestExe == null) { Log.w(TAG, "${folder.name}: the session cannot see ${exe.path}"); return }
|
||||
val guestDir = guestPath(context, exe.parentFile ?: folder) ?: return
|
||||
val name = folder.name
|
||||
val crc = CRC32().apply { update(("\"$guestExe\"" + name).toByteArray()) }.value
|
||||
// Keyed by the pre-rename path so shortcut ids, and the prefixes and saves under them, stay put.
|
||||
val crc = CRC32().apply { update(("\"${guestExe.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + name).toByteArray()) }.value
|
||||
val appId = crc or 0x80000000L
|
||||
val steamRoot = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
|
||||
val steamId = steamRoute(steamRoot, appId)
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.util.zip.ZipInputStream
|
||||
|
||||
/**
|
||||
* An all-in-one driver package: one zip carrying both halves of a matched pair, the display
|
||||
* (Android, bionic) driver in one directory and the runtime (Linux, glibc) driver in another,
|
||||
* indexed by a root `manifest.json` - DroidDeck's own DD-Turnip releases (Droid-Deck/Drivers):
|
||||
*
|
||||
* ```
|
||||
* manifest.json {"package", "version", "drivers": {"android": {"path"}, "linux": {"path"}}}
|
||||
* android/ meta.json (AdrenoTools) + libvulkan_freedreno.so
|
||||
* linux/ meta.json + libvulkan_freedreno.so
|
||||
* ```
|
||||
*
|
||||
* Installing one puts each half through its own importer, with that importer's checks, and
|
||||
* remembers the two as one bundle: picking either half sets both, and deleting either deletes both,
|
||||
* so a bundle is always used whole. Zips of the older kind, one driver each, never reach this.
|
||||
*/
|
||||
object DriverBundle {
|
||||
private const val TAG = "DriverBundle"
|
||||
private const val PREFS = "driver_bundles"
|
||||
private const val MANIFEST = "manifest.json"
|
||||
/** Refuses a zip that unpacks to more than this: both halves together are about 30 MB. */
|
||||
private const val MAX_BYTES = 512L shl 20
|
||||
|
||||
class Manifest(val name: String, val version: String, val tag: String, val androidPath: String, val linuxPath: String)
|
||||
|
||||
/** An installed bundle: [androidId] in TurnipDriver's list, [linuxId] in LinuxVulkanDriverManager's. */
|
||||
class Bundle(val id: String, val name: String, val version: String, val androidId: String, val linuxId: String) {
|
||||
/** "DD-Turnip 0.1.0". */
|
||||
val label: String get() = if (version.isEmpty()) name else "$name $version"
|
||||
}
|
||||
|
||||
/** The manifest of a bundle, or null when [json] is not one (both halves, in two directories). */
|
||||
fun parseManifest(json: JSONObject): Manifest? {
|
||||
val drivers = json.optJSONObject("drivers") ?: return null
|
||||
val android = cleanPath(drivers.optJSONObject("android")?.optString("path").orEmpty()) ?: return null
|
||||
val linux = cleanPath(drivers.optJSONObject("linux")?.optString("path").orEmpty()) ?: return null
|
||||
if (android == linux) return null
|
||||
return Manifest(
|
||||
json.optString("package").ifEmpty { "Driver bundle" }, json.optString("version"),
|
||||
json.optString("tag"), android, linux,
|
||||
)
|
||||
}
|
||||
|
||||
private fun cleanPath(path: String): String? {
|
||||
val p = path.trim().trim('/')
|
||||
return p.takeIf { it.isNotEmpty() && it.split('/').none { part -> part.isEmpty() || part == "." || part == ".." } }
|
||||
}
|
||||
|
||||
/** True when the zip at [uri] is a bundle rather than a single driver. */
|
||||
fun isBundle(context: Context, uri: Uri): Boolean = try {
|
||||
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
ZipInputStream(input).use { zip ->
|
||||
generateSequence { zip.nextEntry }.firstOrNull { !it.isDirectory && it.name == MANIFEST }
|
||||
?.let { parseManifest(JSONObject(zip.readBytes().toString(Charsets.UTF_8))) } != null
|
||||
}
|
||||
} ?: false
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "reading $uri as a bundle", e)
|
||||
false
|
||||
}
|
||||
|
||||
/**
|
||||
* Install both halves of the bundle at [uri]. Both or neither: a half that is refused removes
|
||||
* the one already in. Throws [IllegalArgumentException] with a user-facing reason when the zip
|
||||
* is not a usable bundle, [IOException] on read failures.
|
||||
*/
|
||||
fun install(context: Context, uri: Uri): Bundle {
|
||||
val work = File(context.cacheDir, "bundle-${System.nanoTime()}")
|
||||
val td = TurnipDriver(context)
|
||||
val lm = LinuxVulkanDriverManager(context)
|
||||
var androidId: String? = null
|
||||
try {
|
||||
unzip(context, uri, work)
|
||||
val manifest = File(work, MANIFEST).takeIf { it.isFile }
|
||||
?.let { runCatching { parseManifest(JSONObject(FileUtils.readString(it))) }.getOrNull() }
|
||||
?: throw IllegalArgumentException("Not a driver bundle: no manifest.json naming an android and a linux driver")
|
||||
val androidDir = File(work, manifest.androidPath)
|
||||
val linuxDir = File(work, manifest.linuxPath)
|
||||
|
||||
val androidStage = td.newStagingDir()
|
||||
androidId = try {
|
||||
androidDir.listFiles()?.filter { it.isFile }?.forEach { it.copyTo(File(androidStage, it.name)) }
|
||||
td.adopt(androidStage, manifest.name)
|
||||
} catch (e: Exception) {
|
||||
FileUtils.delete(androidStage)
|
||||
throw e
|
||||
}
|
||||
|
||||
val linuxStage = lm.newStagingDir()
|
||||
val linuxId = try {
|
||||
val library = linuxDir.listFiles()?.firstOrNull { it.isFile && it.name.startsWith("libvulkan_freedreno") && it.name.endsWith(".so") }
|
||||
library?.copyTo(File(linuxStage, LinuxVulkanDriverManager.LIB_NAME))
|
||||
val meta = File(linuxDir, LinuxVulkanDriverManager.META_NAME).takeIf { it.isFile }
|
||||
?.let { runCatching { JSONObject(FileUtils.readString(it)) }.getOrNull() }
|
||||
lm.adopt(linuxStage, library?.name, meta, manifest.name)
|
||||
} catch (e: Exception) {
|
||||
FileUtils.delete(linuxStage)
|
||||
throw e
|
||||
}
|
||||
|
||||
val base = LinuxVulkanDriverManager.sanitizeId(manifest.tag.ifEmpty { "${manifest.name}-${manifest.version}" })
|
||||
val saved = registry(context)
|
||||
var id = base
|
||||
var n = 2
|
||||
while (saved.contains(id)) id = "$base-${n++}"
|
||||
val bundle = Bundle(id, manifest.name, manifest.version, androidId, linuxId)
|
||||
saved.edit().putString(id, JSONObject().put("name", bundle.name).put("version", bundle.version)
|
||||
.put("android", androidId).put("linux", linuxId).toString()).apply()
|
||||
Log.i(TAG, "installed bundle $id: display $androidId, runtime $linuxId")
|
||||
return bundle
|
||||
} catch (e: Exception) {
|
||||
androidId?.let { td.remove(it) }
|
||||
throw e
|
||||
} finally {
|
||||
FileUtils.delete(work)
|
||||
}
|
||||
}
|
||||
|
||||
private fun unzip(context: Context, uri: Uri, dest: File) {
|
||||
val root = dest.canonicalFile
|
||||
var total = 0L
|
||||
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
ZipInputStream(input).use { zip ->
|
||||
for (entry in generateSequence { zip.nextEntry }) {
|
||||
if (entry.isDirectory) continue
|
||||
val out = File(root, entry.name).canonicalFile
|
||||
if (!out.path.startsWith(root.path + File.separator)) throw IllegalArgumentException("Not a driver bundle: ${entry.name} points outside it")
|
||||
out.parentFile?.mkdirs()
|
||||
out.outputStream().use { sink ->
|
||||
val buf = ByteArray(1 shl 16)
|
||||
while (true) {
|
||||
val r = zip.read(buf)
|
||||
if (r <= 0) break
|
||||
total += r
|
||||
if (total > MAX_BYTES) throw IllegalArgumentException("Not a driver bundle: it unpacks to more than ${MAX_BYTES shr 20} MB")
|
||||
sink.write(buf, 0, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} ?: throw IOException("cannot open $uri")
|
||||
}
|
||||
|
||||
/** Every installed bundle whose two halves are both still there. */
|
||||
fun all(context: Context): List<Bundle> {
|
||||
val td = TurnipDriver(context)
|
||||
val lm = LinuxVulkanDriverManager(context)
|
||||
return registry(context).all.mapNotNull { (id, raw) ->
|
||||
runCatching {
|
||||
val j = JSONObject(raw as String)
|
||||
Bundle(id, j.getString("name"), j.optString("version"), j.getString("android"), j.getString("linux"))
|
||||
}.getOrNull()
|
||||
}.filter { td.isInstalled(it.androidId) && lm.isInstalled(it.linuxId) }.sortedBy { it.id }
|
||||
}
|
||||
|
||||
fun get(context: Context, id: String): Bundle? = all(context).firstOrNull { it.id == id }
|
||||
|
||||
/** The bundle [driverId] is a half of, in the runtime list when [linux], else the display list. */
|
||||
fun containing(context: Context, driverId: String, linux: Boolean): Bundle? =
|
||||
all(context).firstOrNull { (if (linux) it.linuxId else it.androidId) == driverId }
|
||||
|
||||
/** The bundle both drivers are set to right now, if they are one. */
|
||||
fun active(context: Context): Bundle? {
|
||||
val android = SessionPrefs.androidDriver(context)
|
||||
val linux = SessionPrefs.linuxDriver(context)
|
||||
return all(context).firstOrNull { it.androidId == android && it.linuxId == linux }
|
||||
}
|
||||
|
||||
/** Set both halves as the drivers in use. */
|
||||
fun select(context: Context, bundle: Bundle) {
|
||||
SessionPrefs.setAndroidDriver(context, bundle.androidId)
|
||||
SessionPrefs.setLinuxDriver(context, bundle.linuxId)
|
||||
}
|
||||
|
||||
/** Delete both halves; a driver still set to either goes back to its default. */
|
||||
fun remove(context: Context, bundle: Bundle) {
|
||||
TurnipDriver(context).remove(bundle.androidId)
|
||||
LinuxVulkanDriverManager(context).removeDriver(bundle.linuxId)
|
||||
if (SessionPrefs.linuxDriver(context) == bundle.linuxId) SessionPrefs.setLinuxDriver(context, "")
|
||||
registry(context).edit().remove(bundle.id).apply()
|
||||
Log.i(TAG, "removed bundle ${bundle.id}")
|
||||
}
|
||||
|
||||
private fun registry(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import com.droiddeck.launcher.gpu.GpuInfo.Family
|
||||
|
||||
/**
|
||||
* The release drivers as matched pairs: a display build (the app's compositor, bionic) and a Linux
|
||||
* build (the runtime, glibc) that were made to run together. Mixing a runtime driver carrying a
|
||||
* patch with a display driver that lacks it is where the hard-to-read bugs come from, so the app
|
||||
* installs and selects both halves of one pair at once.
|
||||
*
|
||||
* - Banners-Turnip publishes each variant as a set in every release (`Turnip-<tag><variant>.zip`
|
||||
* and `...-Linux.zip`), rebuilt from upstream Mesa as it moves: the pair is one variant of the
|
||||
* newest release that carries both halves.
|
||||
* - WinNative ships its display (`v1.x`) and Linux (`linux-v0.x`) builds as two release lines with
|
||||
* their own numbers: the pair is the newest of each, of one flavour (Balanced or Performance).
|
||||
* - DroidDeck's DD-Turnip ships both halves in one zip per release (DriverBundle): the pair is the
|
||||
* newest bundle, and it can never be mixed.
|
||||
*/
|
||||
object DriverPairs {
|
||||
const val BANNER = "banner"
|
||||
const val BANNER_A8XX = "banner-a8xx"
|
||||
const val BANNER_710 = "banner-710-720-test"
|
||||
const val BANNER_ONEUI = "banner-8g2-oneui"
|
||||
const val WN_BALANCED = "wn-b"
|
||||
const val WN_PERFORMANCE = "wn-p"
|
||||
const val DD_TURNIP = "dd-turnip"
|
||||
/** Each DD-Turnip release is its own pair: "dd-turnip:DD-Turnip-v0.1.0". */
|
||||
fun ddTurnip(tag: String) = "$DD_TURNIP:$tag"
|
||||
|
||||
class DriverPair(
|
||||
val key: String,
|
||||
/** "Banners-Turnip · Adreno 6xx/7xx", "WinNative · Balanced". */
|
||||
val name: String,
|
||||
/** The families the pair is built for; the list only offers it on those unless asked. */
|
||||
val families: Set<Family>,
|
||||
val display: TurnipReleases.Asset?,
|
||||
val linux: TurnipReleases.Asset?,
|
||||
/** Both halves in one zip, instead of [display] and [linux]. */
|
||||
val bundle: TurnipReleases.Asset? = null,
|
||||
) {
|
||||
val complete: Boolean get() = bundle != null || (display != null && linux != null)
|
||||
/** The zips to download for the pair: the bundle, or the two halves. */
|
||||
val assets: List<TurnipReleases.Asset> get() = listOfNotNull(bundle ?: display, if (bundle == null) linux else null)
|
||||
/** "r4 · 1.19 + 0.1.2": the build of each half. */
|
||||
val version: String
|
||||
get() = listOfNotNull(bundle?.tag, display?.tag, linux?.tag).distinct().joinToString(" + ") { it.removePrefix("linux-").removePrefix("DD-Turnip-") }
|
||||
fun suits(gpu: GpuInfo) = gpu.family in families ||
|
||||
(gpu.family == Family.ADRENO_UNKNOWN && (Family.A7XX in families || Family.A8XX in families))
|
||||
}
|
||||
|
||||
private val ALL_ADRENO = setOf(Family.A6XX, Family.A7XX, Family.A7XX_LOW, Family.A8XX, Family.ADRENO_UNKNOWN)
|
||||
|
||||
private fun describe(key: String): Pair<String, Set<Family>> = when {
|
||||
key.startsWith(DD_TURNIP) -> "DroidDeck · DD-Turnip" to ALL_ADRENO
|
||||
else -> describeFixed(key)
|
||||
}
|
||||
|
||||
private fun describeFixed(key: String): Pair<String, Set<Family>> = when (key) {
|
||||
BANNER -> "Banners-Turnip · Adreno 6xx/7xx" to setOf(Family.A6XX, Family.A7XX)
|
||||
BANNER_A8XX -> "Banners-Turnip · Adreno 8xx" to setOf(Family.A8XX)
|
||||
BANNER_710 -> "Banners-Turnip · Adreno 710/720/722 (test)" to setOf(Family.A7XX_LOW)
|
||||
BANNER_ONEUI -> "Banners-Turnip · 8 Gen 2 on One UI" to setOf(Family.A7XX)
|
||||
WN_BALANCED -> "WinNative · Balanced" to ALL_ADRENO
|
||||
WN_PERFORMANCE -> "WinNative · Performance" to ALL_ADRENO
|
||||
else -> key to ALL_ADRENO
|
||||
}
|
||||
|
||||
/** Every pair the last release check found, in the order the list shows them. */
|
||||
fun from(check: TurnipReleases.Check?): List<DriverPair> {
|
||||
val assets = check?.assets.orEmpty().filter { it.pair.isNotEmpty() }
|
||||
val order = listOf(DD_TURNIP, BANNER, BANNER_A8XX, BANNER_ONEUI, BANNER_710, WN_BALANCED, WN_PERFORMANCE)
|
||||
return assets.map { it.pair }.distinct()
|
||||
.sortedBy { key -> order.indexOf(key.substringBefore(':')).let { i -> if (i < 0) order.size else i } }
|
||||
.map { key ->
|
||||
val (name, families) = describe(key)
|
||||
val halves = assets.filter { it.pair == key }
|
||||
halves.firstOrNull { it.bundle }?.let { return@map DriverPair(key, name, families, null, null, it) }
|
||||
// The list keeps the newest release of each half; for Banners-Turnip the two halves
|
||||
// must come from the same release, so a set missing one half in its newest release
|
||||
// is offered incomplete rather than mixed with an older one.
|
||||
val display = halves.firstOrNull { !it.linux }
|
||||
val linux = halves.firstOrNull { it.linux }
|
||||
val sameRelease = !key.startsWith(BANNER) || display?.tag == linux?.tag
|
||||
DriverPair(key, name, families, display, if (sameRelease) linux else null)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The pair Auto sets for [gpu], among the [pairs] the last release check found: the newest
|
||||
* official DD-Turnip release on the Adreno 840 (840 and 840v2), WinNative Balanced on the other
|
||||
* 8xx (Banners' A8xx builds still break on some first boots) and on an 840 while no DD-Turnip
|
||||
* release is listed, the OneUI build for an 8 Gen 2 under One UI, the patched test builds for
|
||||
* the 710/720/722, and upstream Banners-Turnip for the rest. Null when nothing fits (not Adreno).
|
||||
*/
|
||||
fun recommendedKey(gpu: GpuInfo, pairs: List<DriverPair>): String? = when (gpu.family) {
|
||||
Family.NOT_ADRENO -> null
|
||||
Family.A8XX -> if (gpu.model == 840) newestDdTurnip(pairs) ?: WN_BALANCED else WN_BALANCED
|
||||
Family.A7XX_LOW -> BANNER_710
|
||||
Family.A7XX -> if (gpu.oneUi8Gen2) BANNER_ONEUI else BANNER
|
||||
Family.A6XX -> BANNER
|
||||
// KGSL gave no model: Android 16 arrived with the 8xx, so a device that new is taken as one.
|
||||
Family.ADRENO_UNKNOWN -> if (android.os.Build.VERSION.SDK_INT >= 36) WN_BALANCED else BANNER
|
||||
}
|
||||
|
||||
/** The complete DD-Turnip pair with the highest version, or null when none is listed. */
|
||||
fun newestDdTurnip(pairs: List<DriverPair>): String? = pairs
|
||||
.filter { it.key.startsWith("$DD_TURNIP:") && it.complete }
|
||||
.maxByOrNull { p ->
|
||||
Regex("""(\d+)\.(\d+)\.(\d+)$""").find(p.key)?.destructured
|
||||
?.let { (major, minor, patch) -> major.toLong() * 1_000_000_000_000 + minor.toLong() * 1_000_000 + patch.toLong() } ?: -1L
|
||||
}?.key
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.os.Build
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* What GPU this is, in the terms the driver lists are sorted by. KGSL names the model
|
||||
* ("Adreno740v2", "Adreno825"); the family decides which Turnip builds run on it at all, and the
|
||||
* support level is what the app has actually been tested on (Adreno 725 and up) - an Adreno 610
|
||||
* may start, but it is not "supported" just because it is a Qualcomm chip.
|
||||
*/
|
||||
data class GpuInfo(
|
||||
/** "Adreno 740", or the vendor's own name when this is not an Adreno. */
|
||||
val name: String,
|
||||
/** The three-digit Adreno model (740, 825), or 0 when KGSL does not say. */
|
||||
val model: Int,
|
||||
val family: Family,
|
||||
/** The SoC as the device reports it ("SM8550", "QCS8550"), or "" when it does not. */
|
||||
val soc: String,
|
||||
/** Samsung's One UI on an 8 Gen 2: its Turnip needs the OneUI build, or frames tear and flicker. */
|
||||
val oneUi8Gen2: Boolean,
|
||||
) {
|
||||
enum class Family(val label: String) {
|
||||
A8XX("Adreno 8xx"),
|
||||
/** Adreno 710/720/722: gen 7 cores cut down enough to need their own patches. */
|
||||
A7XX_LOW("Adreno 710/720/722"),
|
||||
A7XX("Adreno 7xx"),
|
||||
A6XX("Adreno 6xx"),
|
||||
/** An Adreno whose model KGSL does not give: treated as the newest family it could be. */
|
||||
ADRENO_UNKNOWN("Adreno"),
|
||||
NOT_ADRENO("Not an Adreno GPU"),
|
||||
}
|
||||
|
||||
enum class Support { TESTED, UNTESTED, UNSUPPORTED }
|
||||
|
||||
val support: Support
|
||||
get() = when {
|
||||
family == Family.NOT_ADRENO -> Support.UNSUPPORTED
|
||||
family == Family.A8XX -> Support.TESTED
|
||||
family == Family.A7XX && model >= 725 -> Support.TESTED
|
||||
else -> Support.UNTESTED
|
||||
}
|
||||
|
||||
/** One line for the device card and the system check. */
|
||||
val supportText: String
|
||||
get() = when (support) {
|
||||
Support.TESTED -> "Supported"
|
||||
Support.UNTESTED -> if (family == Family.A7XX_LOW) "Experimental: its drivers are test builds"
|
||||
else "Below tested hardware (Adreno 725 and newer): it may not run"
|
||||
Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun detect(): GpuInfo {
|
||||
val adreno = File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
|
||||
val raw = listOf("/sys/class/kgsl/kgsl-3d0/gpu_model", "/sys/class/kgsl/kgsl-3d0/gpu_chipid")
|
||||
.firstNotNullOfOrNull { FileUtils.readString(File(it))?.trim()?.takeIf(String::isNotEmpty) }
|
||||
val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN }.orEmpty() else ""
|
||||
val model = raw?.let { Regex("""(\d{3})""").find(it)?.groupValues?.get(1)?.toIntOrNull() } ?: 0
|
||||
val family = familyOf(adreno, model)
|
||||
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
|
||||
return GpuInfo(
|
||||
name = if (!adreno) Build.HARDWARE.ifBlank { "this GPU" } else if (model > 0) "Adreno $model" else "Adreno",
|
||||
model = model, family = family, soc = soc,
|
||||
oneUi8Gen2 = samsung && model == 740,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun familyOf(adreno: Boolean, model: Int): Family = when {
|
||||
!adreno -> Family.NOT_ADRENO
|
||||
model == 0 -> Family.ADRENO_UNKNOWN
|
||||
model >= 800 -> Family.A8XX
|
||||
model in listOf(710, 720, 722) -> Family.A7XX_LOW
|
||||
model >= 700 -> Family.A7XX
|
||||
model >= 600 -> Family.A6XX
|
||||
else -> Family.ADRENO_UNKNOWN
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -126,9 +126,7 @@ public class LinuxVulkanDriverManager {
|
||||
* Linux driver; {@link IOException} on read/extract failures.
|
||||
*/
|
||||
public String installDriver(Uri zipUri, String displayName) throws IOException {
|
||||
File tmpDir = new File(rootDir, ".tmp-" + System.currentTimeMillis());
|
||||
FileUtils.delete(tmpDir);
|
||||
if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir);
|
||||
File tmpDir = newStagingDir();
|
||||
boolean keep = false;
|
||||
try {
|
||||
String soName = null;
|
||||
@@ -156,9 +154,32 @@ public class LinuxVulkanDriverManager {
|
||||
}
|
||||
}
|
||||
// The zip's own freedreno_icd.aarch64.json is dropped on purpose: its
|
||||
// library_path is relative to itself, and we write an absolute one below.
|
||||
// library_path is relative to itself, and adopt() writes an absolute one.
|
||||
}
|
||||
}
|
||||
String id = adopt(tmpDir, soName, zipMeta, displayName);
|
||||
keep = true;
|
||||
return id;
|
||||
} finally {
|
||||
if (!keep) FileUtils.delete(tmpDir);
|
||||
}
|
||||
}
|
||||
|
||||
/** An empty directory beside the installed drivers, for a driver's files before {@link #adopt}. */
|
||||
File newStagingDir() throws IOException {
|
||||
File tmpDir = new File(rootDir, ".tmp-" + System.nanoTime());
|
||||
FileUtils.delete(tmpDir);
|
||||
if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir);
|
||||
return tmpDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a staged driver ({@link #LIB_NAME} in {@code tmpDir}, copied from {@code soName} in
|
||||
* the zip), write its manifest and meta.json, and move it in. Returns the id; the caller
|
||||
* deletes {@code tmpDir} when this throws.
|
||||
*/
|
||||
String adopt(File tmpDir, String soName, JSONObject zipMeta, String displayName) throws IOException {
|
||||
try {
|
||||
if (soName == null) {
|
||||
throw new IllegalArgumentException("No libvulkan_freedreno*.so in this zip. An Android "
|
||||
+ "(AdrenoTools) or -Wayland Turnip zip is not a Linux runtime driver.");
|
||||
@@ -212,13 +233,10 @@ public class LinuxVulkanDriverManager {
|
||||
if (!FileUtils.writeString(new File(tmpDir, META_NAME), meta.toString(2))) throw new IOException("cannot write meta.json");
|
||||
|
||||
if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir);
|
||||
keep = true;
|
||||
Log.i(TAG, "imported Linux Vulkan driver " + id + " (" + soName + ", minGlibc=" + minGlibc + ") -> " + dir);
|
||||
return id;
|
||||
} catch (org.json.JSONException e) {
|
||||
throw new IOException("manifest write failed: " + e.getMessage());
|
||||
} finally {
|
||||
if (!keep) FileUtils.delete(tmpDir);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -179,10 +179,7 @@ public final class TurnipDriver {
|
||||
* {@link IOException} on read/extract failures.
|
||||
*/
|
||||
public String installFromZip(Uri zipUri, String displayName) throws IOException {
|
||||
if (!contentDir.exists()) contentDir.mkdirs();
|
||||
File tmpDir = new File(contentDir, ".tmp-" + System.currentTimeMillis());
|
||||
FileUtils.delete(tmpDir);
|
||||
if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir);
|
||||
File tmpDir = newStagingDir();
|
||||
boolean keep = false;
|
||||
try {
|
||||
try (InputStream is = context.getContentResolver().openInputStream(zipUri);
|
||||
@@ -198,26 +195,44 @@ public final class TurnipDriver {
|
||||
Files.copy(zis, new File(tmpDir, base).toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
String rejected = rejectionReason(tmpDir);
|
||||
if (rejected != null) throw new IllegalArgumentException("Not an AdrenoTools driver: " + rejected);
|
||||
|
||||
JSONObject meta = readMetaFile(new File(tmpDir, "meta.json"));
|
||||
String name = meta != null ? meta.optString("name", "") : "";
|
||||
if (name.isEmpty()) {
|
||||
name = displayName != null ? displayName : "adrenotools-driver";
|
||||
if (name.toLowerCase().endsWith(".zip")) name = name.substring(0, name.length() - 4);
|
||||
}
|
||||
String id = uniqueId(LinuxVulkanDriverManager.sanitizeId(name));
|
||||
File dir = new File(contentDir, id);
|
||||
if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir);
|
||||
String id = adopt(tmpDir, displayName);
|
||||
keep = true;
|
||||
Log.i(TAG, "imported AdrenoTools driver " + id + " (" + (meta != null ? meta.optString("libraryName", "") : "?") + ") -> " + dir);
|
||||
return id;
|
||||
} finally {
|
||||
if (!keep) FileUtils.delete(tmpDir);
|
||||
}
|
||||
}
|
||||
|
||||
/** An empty directory beside the installed drivers, for a driver's files before {@link #adopt}. */
|
||||
File newStagingDir() throws IOException {
|
||||
if (!contentDir.exists()) contentDir.mkdirs();
|
||||
File tmpDir = new File(contentDir, ".tmp-" + System.nanoTime());
|
||||
FileUtils.delete(tmpDir);
|
||||
if (!tmpDir.mkdirs()) throw new IOException("cannot create " + tmpDir);
|
||||
return tmpDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a staged driver (meta.json and its library, flat) and move it in as a new driver.
|
||||
* Returns the id; the caller deletes {@code tmpDir} when this throws.
|
||||
*/
|
||||
String adopt(File tmpDir, String displayName) throws IOException {
|
||||
String rejected = rejectionReason(tmpDir);
|
||||
if (rejected != null) throw new IllegalArgumentException("Not an AdrenoTools driver: " + rejected);
|
||||
|
||||
JSONObject meta = readMetaFile(new File(tmpDir, "meta.json"));
|
||||
String name = meta != null ? meta.optString("name", "") : "";
|
||||
if (name.isEmpty()) {
|
||||
name = displayName != null ? displayName : "adrenotools-driver";
|
||||
if (name.toLowerCase().endsWith(".zip")) name = name.substring(0, name.length() - 4);
|
||||
}
|
||||
String id = uniqueId(LinuxVulkanDriverManager.sanitizeId(name));
|
||||
File dir = new File(contentDir, id);
|
||||
if (!tmpDir.renameTo(dir)) throw new IOException("cannot move into " + dir);
|
||||
Log.i(TAG, "imported AdrenoTools driver " + id + " (" + (meta != null ? meta.optString("libraryName", "") : "?") + ") -> " + dir);
|
||||
return id;
|
||||
}
|
||||
|
||||
private static JSONObject readMetaFile(File metaFile) {
|
||||
try {
|
||||
return new JSONObject(FileUtils.readString(metaFile));
|
||||
|
||||
@@ -29,12 +29,20 @@ object TurnipReleases {
|
||||
|
||||
/** [label] names the variant for the menu: the GPUs it is for, and a build flavour. */
|
||||
/** [sha256] is the release asset's digest from GitHub; empty for a list cached before it was kept. */
|
||||
/**
|
||||
* [pair] names the matched set an asset belongs to (DriverPairs): a display build and a Linux
|
||||
* build of the same pair are made to run together. "" for a list cached before pairs were kept.
|
||||
*/
|
||||
/** [bundle]: one zip holding both halves of the pair (DriverBundle); [linux] is false for it. */
|
||||
class Asset(val source: String, val tag: String, val name: String, val url: String, val size: Long, val linux: Boolean, val label: String,
|
||||
val sha256: String = "")
|
||||
val sha256: String = "", val pair: String = "", val bundle: Boolean = false)
|
||||
/** [latest] = each source's newest release tag, for the refresh line. */
|
||||
class Check(val assets: List<Asset>, val latest: List<Pair<String, String>>, val failed: List<String>, val checkedAt: Long)
|
||||
|
||||
private class Source(val label: String, val repo: String, val classify: (name: String, tag: String) -> Pair<Boolean, String>?)
|
||||
/** What an asset is: a Linux build or not, the menu label, and the pair it belongs to. */
|
||||
private class Kind(val linux: Boolean, val label: String, val pair: String, val bundle: Boolean = false)
|
||||
|
||||
private class Source(val label: String, val repo: String, val classify: (name: String, tag: String) -> Kind?)
|
||||
|
||||
private val SOURCES = listOf(
|
||||
// Turnip-<tag>[-variant][-Linux|-Wayland].zip; -Wayland is for a path this app does not have.
|
||||
@@ -45,12 +53,14 @@ object TurnipReleases {
|
||||
if (variant.endsWith("-Wayland")) return@Source null
|
||||
val linux = variant.endsWith("-Linux")
|
||||
variant = variant.removeSuffix("-Linux")
|
||||
linux to when {
|
||||
val label = when {
|
||||
variant.isEmpty() -> "Adreno 6xx/7xx"
|
||||
variant == "-A8xx" -> "Adreno 8xx"
|
||||
variant.startsWith("-710-720") -> "Adreno 710/720" + if (variant.contains("Test")) " (test)" else ""
|
||||
variant.contains("OneUI", ignoreCase = true) -> "8 Gen 2 on One UI"
|
||||
else -> variant.trimStart('-')
|
||||
}
|
||||
Kind(linux, label, "banner" + variant.lowercase())
|
||||
},
|
||||
// WN-Turnip-<ver>-<b|p>_Axxx.zip (Android) and WN-Linux-Turnip-<ver>-<b|p>_Axxx.zip (Linux):
|
||||
// b = Balanced, p = Performance, Axxx = every Adreno.
|
||||
@@ -58,7 +68,13 @@ object TurnipReleases {
|
||||
val m = Regex("""^WN-(Linux-)?Turnip-[^-]+-([a-z]+)_(\w+)\.zip$""").find(name) ?: return@Source null
|
||||
val flavour = when (m.groupValues[2]) { "b" -> "Balanced"; "p" -> "Performance"; else -> m.groupValues[2] }
|
||||
val gpus = if (m.groupValues[3] == "Axxx") "all Adreno" else m.groupValues[3]
|
||||
(m.groupValues[1].isNotEmpty()) to "$gpus · $flavour"
|
||||
Kind(m.groupValues[1].isNotEmpty(), "$gpus · $flavour", "wn-" + m.groupValues[2])
|
||||
},
|
||||
// DD-Turnip-v<ver>.zip: DroidDeck's own all-in-one build, both halves in one zip, published
|
||||
// to Drivers-CI (releases only). Every release is offered, not just the newest, each its own pair.
|
||||
Source("DroidDeck", "Droid-Deck/Drivers-CI") { name, tag ->
|
||||
if (!Regex("""^DD-Turnip-v\d+\.\d+\.\d+\.zip$""").matches(name)) return@Source null
|
||||
Kind(false, "Android + Linux · all Adreno", DriverPairs.ddTurnip(tag), bundle = true)
|
||||
},
|
||||
)
|
||||
|
||||
@@ -91,14 +107,19 @@ object TurnipReleases {
|
||||
for (j in 0 until list.length()) {
|
||||
val a = list.getJSONObject(j)
|
||||
val name = a.getString("name")
|
||||
val (linux, label) = src.classify(name, tag) ?: continue
|
||||
val kind = src.classify(name, tag) ?: continue
|
||||
// A bundle is only offered from an official release, never a pre-release.
|
||||
if (kind.bundle && r.optBoolean("prerelease")) continue
|
||||
val linux = kind.linux
|
||||
val label = kind.label
|
||||
// Only assets GitHub has a sha256 for are offered: the download is checked against it.
|
||||
val sha = Hashes.githubSha256(a.optString("digest")) ?: continue
|
||||
// Newest first: the first release carrying a variant is the one offered.
|
||||
if (!seen.add("$linux|$label")) continue
|
||||
if (!seen.add(if (kind.bundle) kind.pair else "$linux|$label")) continue
|
||||
assets.put(JSONObject().put("source", src.label).put("tag", tag).put("name", name)
|
||||
.put("url", a.getString("browser_download_url")).put("size", a.optLong("size"))
|
||||
.put("linux", linux).put("label", label).put("sha256", sha))
|
||||
.put("linux", linux).put("label", label).put("sha256", sha).put("pair", kind.pair)
|
||||
.put("bundle", kind.bundle))
|
||||
}
|
||||
}
|
||||
if (newest != null) latest.put(JSONObject().put("source", src.label).put("tag", newest))
|
||||
@@ -136,7 +157,8 @@ object TurnipReleases {
|
||||
for (i in 0 until list.length()) {
|
||||
val a = list.getJSONObject(i)
|
||||
out.add(Asset(a.getString("source"), a.getString("tag"), a.getString("name"), a.getString("url"),
|
||||
a.optLong("size"), a.getBoolean("linux"), a.getString("label"), a.optString("sha256", "")))
|
||||
a.optLong("size"), a.getBoolean("linux"), a.getString("label"), a.optString("sha256", ""), a.optString("pair", ""),
|
||||
a.optBoolean("bundle", false)))
|
||||
}
|
||||
val latest = ArrayList<Pair<String, String>>()
|
||||
val l = json.optJSONArray("latest") ?: JSONArray()
|
||||
|
||||
@@ -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"),
|
||||
/** The Steam Deck controller's back grips and trackpads; offered while the pad is one. */
|
||||
DECK_CONTROLS("deck-controls", "Deck grips + trackpads"),
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ import java.io.File
|
||||
*/
|
||||
object DesktopCatalog {
|
||||
private const val TAG = "DesktopCatalog"
|
||||
/** Advance this when the Plasma root's required package set changes. */
|
||||
internal const val PLASMA_MOBILE_PACKAGE_REVISION = "archlinuxarm-plasma-apps-v2"
|
||||
const val CATALOG_URL = "https://raw.githubusercontent.com/The412Banner/winlator-contents/main/desktop.json"
|
||||
/**
|
||||
* Valve's Proton Experimental (ARM64) with its appmanifest, laid out as the client keeps it.
|
||||
@@ -78,6 +80,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) &&
|
||||
FileUtils.readString(plasmaMobileMarker(context))?.trim() == PLASMA_MOBILE_PACKAGE_REVISION &&
|
||||
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)
|
||||
|
||||
@@ -89,7 +89,12 @@ 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));
|
||||
}
|
||||
|
||||
/** The Vulkan ICD manifest under a selected rootfs, or null when it has none. */
|
||||
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,11 +119,25 @@ 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);
|
||||
List<String> binds = binds(context, sessionRoot, runtimeDir, externalStorage, extraBinds);
|
||||
return commandForRoot(context, rootDir(context), sessionRoot, runtimeDir, externalStorage, extraBinds,
|
||||
guestCommand, false);
|
||||
}
|
||||
|
||||
/** Builds a command for a selected rootfs; installers may also request PRoot's fake-root identity. */
|
||||
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);
|
||||
}
|
||||
|
||||
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> binds = binds(context, root, sessionRoot, runtimeDir, externalStorage, extraBinds);
|
||||
// A session's binds are the view its programs have; a one-off command's are not recorded.
|
||||
if (sessionRoot != null) lastBinds = binds;
|
||||
List<String> cmd = prootPrefix(context, root, "/root");
|
||||
List<String> cmd = prootPrefix(context, root, "/root", fakeRoot);
|
||||
for (String spec : binds) bind(cmd, spec);
|
||||
cmd.addAll(guestCommand);
|
||||
return cmd;
|
||||
@@ -172,7 +191,12 @@ public final class LinuxRuntime {
|
||||
/** The {@code host:guest} (or same-path) bind specs of a session; see {@link #command}. */
|
||||
public static List<String> binds(Context context, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> extraBinds) {
|
||||
File root = rootDir(context);
|
||||
return binds(context, rootDir(context), sessionRoot, runtimeDir, externalStorage, extraBinds);
|
||||
}
|
||||
|
||||
/** As above, using the selected rootfs for files prepared inside the guest. */
|
||||
public static List<String> binds(Context context, File root, File sessionRoot, File runtimeDir,
|
||||
File externalStorage, List<String> extraBinds) {
|
||||
List<String> cmd = new ArrayList<>();
|
||||
bind(cmd, "/dev");
|
||||
bind(cmd, "/proc");
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
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 {
|
||||
private val packages = listOf("plasma-mobile", "plasma-settings", "angelfish")
|
||||
|
||||
@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 && " +
|
||||
"/usr/bin/pacman -Syyu --needed --noconfirm --overwrite '*' ${packages.joinToString(" ")} && " +
|
||||
// Keep Firefox and Discover out of the Plasma-only clone even if the base root
|
||||
// already installed them; the original desktop root remains unchanged.
|
||||
"for excluded in firefox discover; do " +
|
||||
"if /usr/bin/pacman -Qq \"\$excluded\" >/dev/null 2>&1; then " +
|
||||
"/usr/bin/pacman -Rns --noconfirm \"\$excluded\" || exit; fi; done",
|
||||
)
|
||||
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, "${DesktopCatalog.PLASMA_MOBILE_PACKAGE_REVISION}\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,22 +1,22 @@
|
||||
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.
|
||||
*
|
||||
* The one exception is work the app started outside any session and is still waiting on - a
|
||||
* Flatpak install from the store - registered with [keep]: that process and everything under it
|
||||
* are left to finish.
|
||||
* sessions lives in Android processes, so another active session can own Linux children under
|
||||
* the same uid. Those trees are protected by skipping the sweep while a sibling app process is
|
||||
* active. Work started outside a session and still waiting - such as a Flatpak install - is
|
||||
* registered with [keep] and its process tree is spared. Each pid is checked by uid at kill time,
|
||||
* never by name.
|
||||
*/
|
||||
object OrphanReaper {
|
||||
private const val TAG = "OrphanReaper"
|
||||
@@ -27,7 +27,11 @@ object OrphanReaper {
|
||||
|
||||
fun release(pid: Int) { kept.remove(pid) }
|
||||
|
||||
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 me = android.os.Process.myPid()
|
||||
val uid = android.os.Process.myUid()
|
||||
val spared = descendants(kept)
|
||||
@@ -78,4 +82,5 @@ object OrphanReaper {
|
||||
-1
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -69,6 +69,13 @@ 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",
|
||||
// Plasma Mobile 6.7.5 backports: populate the Folio app catalog without a Wayland
|
||||
// connection handle and reset the native mobile task switcher's gesture state.
|
||||
"usr/lib/qt6/plugins/plasma/applets/org.kde.plasma.mobile.homescreen.folio.so" to "usr/lib/qt6/plugins/plasma/applets/org.kde.plasma.mobile.homescreen.folio.so",
|
||||
"usr/lib/qt6/qml/org/kde/plasma/private/mobileshell/taskswitcherplugin/libmobiletaskswitcherplugin.so" to "usr/lib/qt6/qml/org/kde/plasma/private/mobileshell/taskswitcherplugin/libmobiletaskswitcherplugin.so",
|
||||
"usr/share/kwin/effects/mobiletaskswitcher/contents/ui/FlickContainer.qml" to "usr/share/kwin/effects/mobiletaskswitcher/contents/ui/FlickContainer.qml",
|
||||
"usr/share/kwin/effects/mobiletaskswitcher/contents/ui/TaskSwitcher.qml" to "usr/share/kwin/effects/mobiletaskswitcher/contents/ui/TaskSwitcher.qml",
|
||||
// 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++}")
|
||||
|
||||
@@ -112,15 +112,52 @@ object SessionPrefs {
|
||||
}
|
||||
|
||||
/**
|
||||
* The imported glibc Turnip a mode draws with inside the runtime, keyed by
|
||||
* SessionService.MODE_STEAM / MODE_DESKTOP so Steam and the desktop can differ; "" = the
|
||||
* driver built into the runtime. Resolved by LinuxVulkanDriver at session start.
|
||||
* The imported glibc Turnip every session draws with inside the runtime - Steam, its games and
|
||||
* the desktop alike, as they run on the same GPU; "" = the driver built into the runtime.
|
||||
* Resolved by LinuxVulkanDriver at session start. It was once chosen per mode: the Steam
|
||||
* session's choice, the one nearly everyone set, carries over.
|
||||
*/
|
||||
fun linuxDriver(context: Context, mode: String): String =
|
||||
prefs(context).getString("linuxDriver.$mode", "") ?: ""
|
||||
fun linuxDriver(context: Context): String =
|
||||
prefs(context).getString("linuxDriver", null)
|
||||
?: prefs(context).getString("linuxDriver.steam", null)
|
||||
?: prefs(context).getString("linuxDriver.desktop", "") ?: ""
|
||||
|
||||
fun setLinuxDriver(context: Context, mode: String, id: String) {
|
||||
prefs(context).edit().putString("linuxDriver.$mode", id).apply()
|
||||
fun setLinuxDriver(context: Context, id: String) {
|
||||
prefs(context).edit().putString("linuxDriver", id).apply()
|
||||
}
|
||||
|
||||
const val GPU_DRIVERS_AUTO = "auto"
|
||||
const val GPU_DRIVERS_MANUAL = "manual"
|
||||
|
||||
/**
|
||||
* Who picks the GPU drivers: [GPU_DRIVERS_AUTO] (the app, the matched pair recommended for
|
||||
* this GPU, kept current - DriverPairs) or [GPU_DRIVERS_MANUAL] (the user). Auto for new
|
||||
* installs; see settleGpuDriverMode.
|
||||
*/
|
||||
fun gpuDriverMode(context: Context): String =
|
||||
prefs(context).getString("gpuDriverMode", GPU_DRIVERS_AUTO) ?: GPU_DRIVERS_AUTO
|
||||
|
||||
fun setGpuDriverMode(context: Context, mode: String) {
|
||||
prefs(context).edit().putString("gpuDriverMode", mode).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto arrived after people had picked drivers by hand: an install that chose either driver
|
||||
* keeps its choice (Manual), everyone else is Auto. Decided once, at process start.
|
||||
*/
|
||||
fun settleGpuDriverMode(context: Context) {
|
||||
val p = prefs(context)
|
||||
if (p.contains("gpuDriverMode")) return
|
||||
val chosen = androidDriver(context).isNotEmpty() || linuxDriver(context).isNotEmpty()
|
||||
p.edit().putString("gpuDriverMode", if (chosen) GPU_DRIVERS_MANUAL else GPU_DRIVERS_AUTO).apply()
|
||||
}
|
||||
|
||||
/** Drivers Auto downloaded: the only ones it removes when a newer pair replaces them. */
|
||||
fun gpuAutoInstalled(context: Context): Set<String> =
|
||||
prefs(context).getStringSet("gpuAutoInstalled", emptySet()).orEmpty()
|
||||
|
||||
fun setGpuAutoInstalled(context: Context, ids: Set<String>) {
|
||||
prefs(context).edit().putStringSet("gpuAutoInstalled", ids.toSet()).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -515,6 +552,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
|
||||
@@ -546,7 +602,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)
|
||||
@@ -562,7 +622,7 @@ object SessionPrefs {
|
||||
// ── Game storage ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* A second Steam library on this device: the folder bound at /mnt/bannerlator-sd and
|
||||
* A second Steam library on this device: the folder bound at /mnt/droiddeck-sd and
|
||||
* registered with the client, which then asks where to install every game and shows both
|
||||
* on its Storage page. "" = automatic: the SD card when one is in the phone (the default,
|
||||
* so the choice is made inside the client like anywhere else); GAME_STORAGE_OFF = internal
|
||||
|
||||
@@ -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
|
||||
@@ -56,7 +57,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>()
|
||||
/** The Steam Deck controller's sysfs binds (SteamDeckPad), when this session has one. */
|
||||
private var deckBinds: List<String> = emptyList()
|
||||
@@ -164,14 +165,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
|
||||
@@ -200,12 +201,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
|
||||
@@ -230,6 +240,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()
|
||||
@@ -253,18 +283,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)
|
||||
|
||||
val sessionDir = openSessionFolder()
|
||||
@@ -277,12 +316,17 @@ class SessionService : Service() {
|
||||
// The desktop's Steam launchers start the client there (bannerlator-steam-launch), through the
|
||||
// same set-up as a Steam session: it gets what the client and its games are started with.
|
||||
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
|
||||
addClientEnvironment(guest, runtimeDir, steamHere)
|
||||
addClientEnvironment(guest, runtimeDir, steamHere, root)
|
||||
|
||||
val pulse = startAudio(guest, sessionDir)
|
||||
|
||||
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.
|
||||
@@ -360,12 +404,12 @@ 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 = sessionBinds(controllersOn, fakeInputDir)
|
||||
val binds = sessionBinds(controllersOn, fakeInputDir, root, externalDisplay)
|
||||
|
||||
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()
|
||||
@@ -382,8 +426,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 ->
|
||||
@@ -483,7 +527,7 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
/** The guest's base environment: paths, the display, the GL/Vulkan stack and the client's switches. */
|
||||
private fun addClientEnvironment(guest: MutableList<String>, runtimeDir: File, steamHere: Boolean) {
|
||||
private fun addClientEnvironment(guest: MutableList<String>, runtimeDir: File, steamHere: Boolean, root: File) {
|
||||
guest.add("/usr/bin/env")
|
||||
guest.add("-i")
|
||||
guest.add("HOME=/root")
|
||||
@@ -502,16 +546,13 @@ 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) }
|
||||
// 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.
|
||||
// A program from the rail is one of the desktop's emulators, so it draws with the desktop's
|
||||
// Linux driver, not the Steam session's: the driver's shader cache is keyed on the driver
|
||||
// build, and with two drivers every emulator compiled its shaders twice - once per way of
|
||||
// starting it (RPCS3's 6650 interpreter variants on each first boot).
|
||||
val driverMode = if (SessionState.mode == MODE_RUN) MODE_DESKTOP else SessionPrefs.prefMode(SessionState.mode)
|
||||
val linuxDriverId = SessionPrefs.linuxDriver(this, driverMode)
|
||||
LinuxRuntime.vulkanIcd(root)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
|
||||
// An imported glibc Turnip, when one is set (by the user, or by Auto): 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. One driver for every session: the driver's shader cache is keyed on
|
||||
// its build, and with one per mode every emulator compiled its shaders twice.
|
||||
val linuxDriverId = SessionPrefs.linuxDriver(this)
|
||||
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
|
||||
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
|
||||
// Turnip's own debug switches, for the runtime's driver and everything on it. The file in
|
||||
@@ -579,7 +620,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.
|
||||
@@ -669,7 +710,7 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
/** What proot binds into the guest: the pads, the battery, storage, the game library, added games and ROMs. */
|
||||
private fun sessionBinds(controllersOn: Boolean, fakeInputDir: File): ArrayList<String> {
|
||||
private fun sessionBinds(controllersOn: Boolean, fakeInputDir: File, root: File, externalDisplay: Boolean): ArrayList<String> {
|
||||
val binds = ArrayList<String>()
|
||||
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
|
||||
if (controllersOn) binds.addAll(deckBinds)
|
||||
@@ -690,8 +731,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(root, "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
|
||||
@@ -700,9 +743,12 @@ 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/droiddeck-sd").mkdirs()
|
||||
binds.add("${library.path}:/mnt/droiddeck-sd")
|
||||
// Links, prefixes and Steam entries made before the rename still name the old path.
|
||||
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}\")")
|
||||
Log.i(TAG, "game storage: ${library.path} -> /mnt/droiddeck-sd (\"${library.label}\")")
|
||||
} else {
|
||||
Log.w(TAG, "game storage: $problem; internal only this session")
|
||||
}
|
||||
@@ -711,13 +757,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) }
|
||||
@@ -973,6 +1019,7 @@ class SessionService : Service() {
|
||||
SessionEvents.fail(code, message, failureStatus)
|
||||
}
|
||||
SessionState.notifyEnded(status)
|
||||
SessionProcess.releaseSessionLock()
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
@@ -1004,6 +1051,7 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
private fun stopSession(status: Int) {
|
||||
if (!SessionProcess.isExternalDisplay(this)) stopExternalDisplaySession(this)
|
||||
synchronized(stopLock) {
|
||||
if (!SessionState.running) return
|
||||
SessionState.running = false
|
||||
@@ -1037,6 +1085,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 {
|
||||
@@ -1054,10 +1103,12 @@ class SessionService : Service() {
|
||||
if (prootPid > 1 && steamClientMayRun) askSteamToExit(prootPid)
|
||||
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
|
||||
if (prootPid > 1) teardown(prootPid)
|
||||
stopPlasmaShell(plasmaShellPid, ended)
|
||||
killGuestLeftovers()
|
||||
finishSessionStop(status, stoppedGen)
|
||||
}, "session-teardown").start()
|
||||
} else {
|
||||
stopPlasmaShell(plasmaShellPid, ended)
|
||||
finishSessionStop(status, stoppedGen)
|
||||
}
|
||||
}
|
||||
@@ -1077,6 +1128,7 @@ class SessionService : Service() {
|
||||
|
||||
override fun onDestroy() {
|
||||
stopSession(0)
|
||||
if (!SessionState.running) SessionProcess.releaseSessionLock()
|
||||
if (screenReceiverRegistered) {
|
||||
unregisterReceiver(screenReceiver)
|
||||
screenReceiverRegistered = false
|
||||
@@ -1138,8 +1190,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)
|
||||
@@ -1149,23 +1202,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))
|
||||
@@ -1183,9 +1236,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"
|
||||
/** proot's tracer: above everything in the guest, under the compositor thread's -8. */
|
||||
@@ -1196,6 +1260,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"
|
||||
@@ -1208,7 +1274,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
|
||||
@@ -1224,6 +1290,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"
|
||||
@@ -1234,11 +1301,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)
|
||||
@@ -1252,29 +1324,33 @@ class SessionService : Service() {
|
||||
SessionState.stopRequested = true
|
||||
return
|
||||
}
|
||||
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),
|
||||
)
|
||||
@@ -1282,7 +1358,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),
|
||||
)
|
||||
@@ -1290,7 +1366,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),
|
||||
)
|
||||
|
||||
@@ -102,6 +102,9 @@ fun ComponentsPage(
|
||||
onImport: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
requestInitialFocus: Boolean = true,
|
||||
/** The GPU drivers tab ([GPU_TAB]): what it shows and does. */
|
||||
gpu: GpuDriversState = GpuDriversState(),
|
||||
gpuActions: GpuDriversActions = GpuDriversActions(),
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
@@ -112,23 +115,55 @@ fun ComponentsPage(
|
||||
var about by remember { mutableStateOf(false) }
|
||||
var protonMenu by remember { mutableStateOf(false) }
|
||||
fun ask(title: String, body: String, action: () -> Unit) { confirmTitle = title; confirm = body to action }
|
||||
// The GPU drivers tab's Advanced pages: one driver list on its own, full page.
|
||||
var driverPage by remember { mutableStateOf<String?>(null) }
|
||||
val gpuTab = comp == GPU_TAB
|
||||
when (driverPage) {
|
||||
"rt" -> {
|
||||
DriverPage(
|
||||
title = "Runtime driver", hint = "Steam, its games and the desktop draw with it. Applies next session.",
|
||||
rows = gpu.linuxRows, selected = gpu.linuxSelected, downloads = gpu.linuxDownloads,
|
||||
status = gpu.releaseStatus, checking = gpu.checking, importLabel = "Import Turnip zip…", canRestore = false,
|
||||
onSelect = gpuActions.onSelectLinux, onDelete = gpuActions.onRemoveLinux, onRefresh = gpuActions.onRefresh,
|
||||
onDownload = gpuActions.onDownloadDriver, onImport = gpuActions.onImportLinux, onRestore = {}, onBack = { driverPage = null },
|
||||
)
|
||||
return
|
||||
}
|
||||
"panel" -> {
|
||||
DriverPage(
|
||||
title = "Display driver", hint = "Puts frames on the screen in both modes. Restart the app to apply.",
|
||||
rows = gpu.androidRows, selected = gpu.androidSelected, downloads = gpu.androidDownloads,
|
||||
status = gpu.releaseStatus, checking = gpu.checking, importLabel = "Import an AdrenoTools zip…",
|
||||
canRestore = gpu.canRestoreBundled,
|
||||
onSelect = gpuActions.onSelectAndroid, onDelete = gpuActions.onRemoveAndroid, onRefresh = gpuActions.onRefresh,
|
||||
onDownload = gpuActions.onDownloadDriver, onImport = gpuActions.onImportAndroid, onRestore = gpuActions.onRestoreBundled,
|
||||
onBack = { driverPage = null },
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
val views = snapshot?.protons ?: emptyList()
|
||||
val view = views.firstOrNull { it.proton.id == protonId } ?: views.firstOrNull()
|
||||
val label = ComponentsManager.LABEL[comp] ?: comp
|
||||
val checked = if (catalogAt > 0) DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(catalogAt * 1000)) else "never"
|
||||
val nightlies = if (busy != null) "$busy…" else "Nightlies checked $checked"
|
||||
val nightlies = if (gpuTab) gpu.releaseStatus else if (busy != null) "$busy…" else "Nightlies checked $checked"
|
||||
|
||||
Column(Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
|
||||
// ---- title, and the one thing that goes online -----------------------------------------
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"Components", fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground,
|
||||
maxLines = 1, modifier = Modifier.weight(1f),
|
||||
maxLines = 1,
|
||||
)
|
||||
if (!narrow) Text(nightlies, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
ToolIcon(Icons.Outlined.Info, "About Components") { about = true }
|
||||
ToolIcon(Icons.Outlined.Refresh, "Check the Nightlies for new packages", busy = checking, enabled = !checking, onClick = onRefresh)
|
||||
// The status gives way to the title, not the other way round.
|
||||
if (!narrow) Text(
|
||||
nightlies, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
textAlign = androidx.compose.ui.text.style.TextAlign.End, modifier = Modifier.weight(1f),
|
||||
) else Spacer(Modifier.weight(1f))
|
||||
if (!gpuTab) ToolIcon(Icons.Outlined.Info, "About Components") { about = true }
|
||||
if (gpuTab) ToolIcon(Icons.Outlined.Refresh, "Check for new drivers", busy = gpu.checking, enabled = !gpu.checking && gpu.busy == null, onClick = gpuActions.onRefresh)
|
||||
else ToolIcon(Icons.Outlined.Refresh, "Check the Nightlies for new packages", busy = checking, enabled = !checking, onClick = onRefresh)
|
||||
}
|
||||
if (narrow) Text(nightlies, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
|
||||
@@ -138,7 +173,7 @@ fun ComponentsPage(
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 12.dp),
|
||||
) {
|
||||
if (view != null) Box {
|
||||
if (view != null && !gpuTab) Box {
|
||||
ValueChip(view.proton.name, protonMenu, modifier = Modifier.widthIn(max = 300.dp).heightIn(min = 44.dp)) { protonMenu = !protonMenu }
|
||||
AnchoredMenu(protonMenu, onDismiss = { protonMenu = false }, title = "Proton",
|
||||
note = "Valve's own Proton is replaced when Steam updates it; its originals are kept per build.") { first ->
|
||||
@@ -152,11 +187,12 @@ fun ComponentsPage(
|
||||
}
|
||||
}
|
||||
}
|
||||
TabStrip(comps.map { ComponentsManager.LABEL.getValue(it) }, comps.indexOf(comp).coerceAtLeast(0), { onComp(comps[it]) })
|
||||
val tabs = listOf(GPU_TAB) + comps
|
||||
TabStrip(tabs.map { ComponentsManager.LABEL[it] ?: "GPU drivers" }, tabs.indexOf(comp).coerceAtLeast(0), { onComp(tabs[it]) })
|
||||
}
|
||||
|
||||
// ---- what is in use -----------------------------------------------------------------------
|
||||
if (view != null) {
|
||||
if (view != null && !gpuTab) {
|
||||
val st = view.components.getValue(comp)
|
||||
val fixedAt = if (view.reappliedAt > 0) " · re-applied at launch " + DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(view.reappliedAt * 1000)) else ""
|
||||
Row(
|
||||
@@ -179,6 +215,12 @@ fun ComponentsPage(
|
||||
|
||||
// ---- the lists ------------------------------------------------------------------------------
|
||||
when {
|
||||
gpuTab -> Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
|
||||
GpuDriversPanel(gpu, gpuActions) { driverPage = it }
|
||||
Row(modifier = Modifier.padding(top = 14.dp)) {
|
||||
SmallButton("Import .zip", onClick = gpuActions.onImportZip)
|
||||
}
|
||||
}
|
||||
snapshot == null -> Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(16.dp)) {
|
||||
CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(12.dp))
|
||||
@@ -432,3 +474,6 @@ private fun AvailableLine(d: CatalogItem, progress: Int?, enabled: Boolean, onDo
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
}
|
||||
|
||||
/** The Components page's tab for the GPU drivers, before the Proton components' own. */
|
||||
const val GPU_TAB = "gpu"
|
||||
@@ -141,6 +141,7 @@ fun DriverPage(
|
||||
text = {
|
||||
Text(
|
||||
if (row.tag == DriverRow.BUNDLED) "It is built into the app, so this removes its unpacked files and hides it. \"Restore built-in drivers\" brings it back, and Auto still uses it on a GPU that needs it."
|
||||
else if (row.tag == DriverRow.BUNDLE) "It is one half of an Android + Linux bundle, so its runtime and display drivers are both removed. A driver in use goes back to the default."
|
||||
else "Its files are removed from the app." + if (row.id == selected) " It is the driver in use, so the default takes its place." else "",
|
||||
fontSize = 13.sp,
|
||||
)
|
||||
|
||||
@@ -153,7 +153,9 @@ internal fun SetupPanel(
|
||||
}
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val gpuOk = remember { DeviceSupport.adreno() }
|
||||
// Tested hardware passes; an Adreno below it (a 610, say) warns rather than claiming support.
|
||||
val gpu = remember { com.droiddeck.launcher.gpu.GpuInfo.detect() }
|
||||
val gpuOk = gpu.support == com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED
|
||||
val gpuName = remember { DeviceSupport.gpuName() }
|
||||
val limitBlocks = PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
val signedIn = s.offlineAccount != null
|
||||
@@ -195,8 +197,16 @@ internal fun SetupPanel(
|
||||
Column(modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
|
||||
CheckRow(
|
||||
if (gpuOk) CheckState.OK else CheckState.WARN,
|
||||
if (gpuOk) "Device supported" else "GPU not supported",
|
||||
if (gpuOk) gpuName else "Steam draws with an Adreno driver; $gpuName may show a black screen",
|
||||
when (gpu.support) {
|
||||
com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> "Device supported"
|
||||
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> "Untested GPU"
|
||||
else -> "GPU not supported"
|
||||
},
|
||||
when (gpu.support) {
|
||||
com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> "${gpu.name} · $gpuName"
|
||||
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> "${gpu.name}: ${gpu.supportText.replaceFirstChar { it.lowercase() }}"
|
||||
else -> "Steam draws with an Adreno driver; $gpuName may show a black screen"
|
||||
},
|
||||
)
|
||||
CheckRow(
|
||||
when { s.busy -> CheckState.BUSY; !s.ready -> CheckState.WARN; else -> CheckState.OK },
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.AutoAwesome
|
||||
import androidx.compose.material.icons.outlined.Memory
|
||||
import androidx.compose.material.icons.outlined.Tune
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/** One matched driver pair in the list (DriverPairs), and what this device makes of it. */
|
||||
class PairRow(
|
||||
val key: String,
|
||||
val name: String,
|
||||
val version: String,
|
||||
val detail: String,
|
||||
val recommended: Boolean,
|
||||
/** Built for this GPU's family; the others only show when asked. */
|
||||
val suits: Boolean,
|
||||
val complete: Boolean,
|
||||
val installed: Boolean,
|
||||
val active: Boolean,
|
||||
)
|
||||
|
||||
class GpuDriversState(
|
||||
val gpuName: String = "",
|
||||
val gpuFamily: String = "",
|
||||
val soc: String = "",
|
||||
val supportText: String = "",
|
||||
val supported: Boolean = true,
|
||||
val unsupported: Boolean = false,
|
||||
val auto: Boolean = true,
|
||||
val pairs: List<PairRow> = emptyList(),
|
||||
/** The pair key being installed, and how far along (-1 = unknown). */
|
||||
val busy: String? = null,
|
||||
val percent: Int = -1,
|
||||
val autoStatus: String = "",
|
||||
val releaseStatus: String = "",
|
||||
val checking: Boolean = false,
|
||||
// Advanced: each driver on its own.
|
||||
val linuxRows: List<DriverRow> = emptyList(),
|
||||
val linuxSelected: String = "",
|
||||
val androidRows: List<DriverRow> = emptyList(),
|
||||
val androidSelected: String = "",
|
||||
val linuxDownloads: List<DownloadRow> = emptyList(),
|
||||
val androidDownloads: List<DownloadRow> = emptyList(),
|
||||
val canRestoreBundled: Boolean = false,
|
||||
/** The Android + Linux bundle both drivers are set to ("DD-Turnip 0.1.0"), or null. */
|
||||
val activeBundle: String? = null,
|
||||
) {
|
||||
/** The pair both drivers are set to, if they make one. */
|
||||
val activePair: PairRow? get() = pairs.firstOrNull { it.active }
|
||||
}
|
||||
|
||||
class GpuDriversActions(
|
||||
val onAuto: (Boolean) -> Unit = {},
|
||||
val onPair: (String) -> Unit = {},
|
||||
val onRefresh: () -> Unit = {},
|
||||
val onSelectLinux: (String) -> Unit = {},
|
||||
val onSelectAndroid: (String) -> Unit = {},
|
||||
val onRemoveLinux: (String) -> Unit = {},
|
||||
val onRemoveAndroid: (String) -> Unit = {},
|
||||
val onDownloadDriver: (String) -> Unit = {},
|
||||
val onImportLinux: () -> Unit = {},
|
||||
val onImportAndroid: () -> Unit = {},
|
||||
/** The tab's own import: a bundle, or a single driver of either kind. */
|
||||
val onImportZip: () -> Unit = {},
|
||||
val onRestoreBundled: () -> Unit = {},
|
||||
)
|
||||
|
||||
/**
|
||||
* The GPU drivers tab: this GPU, and the drivers it draws with - a runtime (Linux) driver for the
|
||||
* games and a display (Android) driver for the screen, set together as one matched pair. Auto keeps
|
||||
* the pair recommended for the GPU installed and current; Manual picks a pair from the list; the
|
||||
* two lists each on their own, and imports, are under Advanced.
|
||||
*/
|
||||
@Composable
|
||||
internal fun GpuDriversPanel(s: GpuDriversState, a: GpuDriversActions, onAdvanced: (String) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var showAll by rememberSaveable { mutableStateOf(false) }
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 12.dp)) {
|
||||
DeviceCard(s)
|
||||
if (!s.unsupported) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
ModeCard(Icons.Outlined.AutoAwesome, "Auto", "The best pair for this GPU, kept up to date", s.auto, Modifier.weight(1f)) { a.onAuto(true) }
|
||||
ModeCard(Icons.Outlined.Tune, "Manual", "Pick a pair yourself", !s.auto, Modifier.weight(1f)) { a.onAuto(false) }
|
||||
}
|
||||
if (s.auto) AutoCard(s)
|
||||
else {
|
||||
val shown = s.pairs.filter { it.suits || showAll }
|
||||
if (shown.isEmpty()) Text(
|
||||
if (s.checking) "Checking for drivers…" else "No drivers listed yet. Tap refresh to look for them.",
|
||||
fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 8.dp),
|
||||
)
|
||||
for (p in shown) PairLine(p, s.busy == p.key, s.percent, enabled = s.busy == null) { a.onPair(p.key) }
|
||||
if (s.pairs.any { !it.suits }) FocusText(
|
||||
if (showAll) "Hide drivers for other GPUs" else "Show drivers for other GPUs", pal.signal,
|
||||
) { showAll = !showAll }
|
||||
}
|
||||
}
|
||||
SettingsGroup("Advanced") {
|
||||
val together = s.activeBundle?.let { "Set together with the %s driver: $it carries both." }
|
||||
SettingsRow("Runtime driver", together?.format("display") ?: "Games and the desktop draw with it.") {
|
||||
DriverDropdown(s.linuxRows, s.linuxSelected, "Runtime default", a.onSelectLinux) { onAdvanced("rt") }
|
||||
}
|
||||
SettingsRow("Display driver", together?.format("runtime") ?: "Puts frames on the screen. Changes apply after DroidDeck restarts.") {
|
||||
DriverDropdown(s.androidRows, s.androidSelected, "Auto - picked by GPU", a.onSelectAndroid) { onAdvanced("panel") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One driver list as a drop-down: the installed drivers to pick from, and the full page for
|
||||
* downloading and deleting them. An Android + Linux bundle's row is tagged, and picking it sets both.
|
||||
*/
|
||||
@Composable
|
||||
private fun DriverDropdown(rows: List<DriverRow>, selected: String, fallback: String, onSelect: (String) -> Unit, onManage: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var open by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
SecondaryButton((rows.firstOrNull { it.id == selected }?.name ?: fallback) + " ▾", compact = true) { open = true }
|
||||
DropdownMenu(open, onDismissRequest = { open = false }, modifier = Modifier.heightIn(max = 360.dp)) {
|
||||
for (row in rows) DropdownMenuItem(
|
||||
leadingIcon = { Radio(row.id == selected) },
|
||||
text = {
|
||||
Column {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(row.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (row.id == selected) pal.signal else colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (row.tag == DriverRow.BUNDLE) Text(row.tag, fontSize = 10.5.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
if (row.detail.isNotEmpty()) Text(row.detail, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
},
|
||||
onClick = { open = false; if (row.id != selected) onSelect(row.id) },
|
||||
)
|
||||
HorizontalDivider(color = pal.line)
|
||||
DropdownMenuItem(text = { Text("Download, import or delete…", fontSize = 14.sp, color = pal.signal) }, onClick = { open = false; onManage() })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DeviceCard(s: GpuDriversState) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val tint = when {
|
||||
s.unsupported -> pal.error
|
||||
s.supported -> pal.good
|
||||
else -> AttentionAmber
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
|
||||
modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(14.dp),
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(44.dp).clip(Shape12).background(tint.copy(alpha = 0.14f))) {
|
||||
Icon(Icons.Outlined.Memory, contentDescription = null, tint = tint, modifier = Modifier.size(24.dp))
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(s.gpuName, fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
Text(listOf(s.soc, s.gpuFamily).filter { it.isNotEmpty() }.joinToString(" · "), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Box(Modifier.size(7.dp).clip(CircleShape).background(tint))
|
||||
Text(s.supportText, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = tint, maxLines = 2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What Auto has set and what it is doing. */
|
||||
@Composable
|
||||
private fun AutoCard(s: GpuDriversState) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val active = s.activePair
|
||||
val recommended = s.pairs.firstOrNull { it.recommended }
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
modifier = Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).padding(14.dp),
|
||||
) {
|
||||
Text("IN USE", fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = colors.onSurfaceVariant)
|
||||
Text(
|
||||
active?.let { "${it.name} ${it.version}" } ?: s.activeBundle ?: "The drivers built into DroidDeck",
|
||||
fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
)
|
||||
Text(
|
||||
if (active != null || s.activeBundle != null) "Runtime and display drivers set together as a matched pair."
|
||||
else recommended?.let { "Recommended for this GPU: ${it.name}." } ?: "Tap refresh to look for drivers for this GPU.",
|
||||
fontSize = 13.sp, color = colors.onSurfaceVariant,
|
||||
)
|
||||
if (s.busy != null) {
|
||||
LinearProgressIndicator(
|
||||
progress = { (s.percent.coerceAtLeast(0)) / 100f },
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(6.dp).clip(CircleShape),
|
||||
)
|
||||
}
|
||||
if (s.autoStatus.isNotEmpty()) Text(s.autoStatus, fontSize = 13.sp, color = colors.onBackground, modifier = Modifier.padding(top = 4.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ModeCard(icon: ImageVector, title: String, hint: String, selected: Boolean, modifier: Modifier, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val fill = if (hot) pal.signal.copy(alpha = 0.14f) else if (selected) pal.signal.copy(alpha = 0.08f) else Color.Transparent
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = modifier.paneItem("gpu-mode:$title").heightIn(min = 56.dp)
|
||||
.clip(Shape14).background(colors.surface).background(fill)
|
||||
.border(if (hot) 2.dp else 1.dp, if (hot || selected) pal.signal else pal.line, Shape14)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick)
|
||||
.padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
) {
|
||||
Icon(icon, contentDescription = null, tint = if (selected) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(22.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
Radio(selected)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PairLine(p: PairRow, busy: Boolean, percent: Int, enabled: Boolean, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val usable = enabled && p.complete && !p.active
|
||||
val fill = if (hot) pal.signal.copy(alpha = 0.14f) else if (p.active) pal.signal.copy(alpha = 0.08f) else Color.Transparent
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().paneItem("pair:${p.key}").heightIn(min = 56.dp)
|
||||
.clip(Shape12).background(colors.surface).background(fill)
|
||||
.border(if (hot) 2.dp else 1.dp, if (hot || p.active) pal.signal else pal.line, Shape12)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = usable, role = Role.RadioButton, onClick = onClick)
|
||||
.controllerConfirm(enabled = usable, onClick = onClick)
|
||||
.padding(horizontal = 14.dp, vertical = 8.dp),
|
||||
) {
|
||||
Radio(p.active)
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(p.name, fontSize = 14.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
|
||||
if (p.recommended) Text(
|
||||
"RECOMMENDED", fontSize = 10.5.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.sp, color = pal.good,
|
||||
modifier = Modifier.clip(RoundedCornerShape(5.dp)).background(pal.good.copy(alpha = 0.12f)).padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
Text("${p.version} · ${p.detail}", fontSize = 12.5.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
when {
|
||||
busy -> Column(horizontalAlignment = Alignment.End, modifier = Modifier.width(96.dp)) {
|
||||
Text(if (percent >= 0) "$percent%" else "…", fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
LinearProgressIndicator(progress = { percent.coerceAtLeast(0) / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 4.dp))
|
||||
}
|
||||
p.active -> Text("In use", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = pal.signal)
|
||||
!p.complete -> Text("Unavailable", fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
p.installed -> Text("Use", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
else -> Text("Download", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Radio(selected: Boolean) {
|
||||
val pal = LocalPalette.current
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(20.dp).clip(CircleShape).border(2.dp, if (selected) pal.signal else pal.line2, CircleShape)) {
|
||||
if (selected) Box(Modifier.size(10.dp).clip(CircleShape).background(pal.signal))
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,8 @@ class DriverRow(val id: String, val name: String, val detail: String, val remova
|
||||
const val BUNDLED = "BUNDLED"
|
||||
const val DOWNLOADED = "DOWNLOADED"
|
||||
const val IMPORTED = "IMPORTED"
|
||||
/** One half of an Android + Linux bundle: picked and deleted together with the other. */
|
||||
const val BUNDLE = "ANDROID + LINUX"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,12 +49,10 @@ class ModeSettings(
|
||||
val shapeMode: String,
|
||||
val hdr: Boolean,
|
||||
val hdrReason: String?,
|
||||
/** The GPU drivers in use, as the row that opens them on the Components page says it. */
|
||||
val gpuDrivers: String = "Auto",
|
||||
/** Frames per second the session is capped at; 0 = none. */
|
||||
val fpsLimit: Int = 0,
|
||||
val linuxRows: List<DriverRow>,
|
||||
val linuxSelected: String,
|
||||
val androidRows: List<DriverRow>,
|
||||
val androidSelected: String,
|
||||
val touchMode: String,
|
||||
val suspendPolicy: String,
|
||||
/** Steam only. */
|
||||
@@ -63,6 +63,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,
|
||||
@@ -83,12 +85,6 @@ class ModeSettings(
|
||||
val addedGames: List<AddedGameRow> = emptyList(),
|
||||
val addedGamesArt: Boolean = true,
|
||||
/** Latest Banners-Turnip release: what each driver menu offers to download, and the refresh line. */
|
||||
val linuxDownloads: List<DownloadRow> = emptyList(),
|
||||
val androidDownloads: List<DownloadRow> = emptyList(),
|
||||
val releaseStatus: String = "Not checked yet - tap refresh to look for new drivers",
|
||||
val releaseChecking: Boolean = false,
|
||||
/** A bundled display driver was deleted: the page offers to restore it. */
|
||||
val canRestoreBundled: Boolean = false,
|
||||
/** Steam only: Decky Loader is managed from the Steam session settings. */
|
||||
val deckyInstalled: String? = null,
|
||||
val deckyLatestRelease: DeckyManager.Release? = null,
|
||||
@@ -108,17 +104,9 @@ class ModeSettingsActions(
|
||||
val onCustomResolution: (Pair<Int, Int>?) -> Unit = {},
|
||||
val onShape: (String) -> Unit,
|
||||
val onHdr: (Boolean) -> Unit,
|
||||
/** Opens the GPU drivers on the Components page: they are shared by every session. */
|
||||
val onGpuDrivers: () -> Unit = {},
|
||||
val onFpsLimit: (Int) -> Unit = {},
|
||||
val onSelectLinux: (String) -> Unit,
|
||||
val onImportLinux: () -> Unit,
|
||||
val onRemoveLinux: (String) -> Unit,
|
||||
val onRefreshReleases: () -> Unit = {},
|
||||
/** Asset name of the release driver to download. */
|
||||
val onDownloadDriver: (String) -> Unit = {},
|
||||
val onRestoreBundled: () -> Unit = {},
|
||||
val onSelectAndroid: (String) -> Unit,
|
||||
val onImportAndroid: () -> Unit,
|
||||
val onRemoveAndroid: (String) -> Unit,
|
||||
val onTouch: (String) -> Unit,
|
||||
val onSuspendPolicy: (String) -> Unit,
|
||||
val onOsc: (String) -> Unit,
|
||||
@@ -127,6 +115,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 = {},
|
||||
@@ -153,51 +142,13 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
val steam = s.mode == SessionService.MODE_STEAM
|
||||
val host = rememberMenuHost()
|
||||
var confirmDeckyRemoval by remember { mutableStateOf(false) }
|
||||
// The two driver lists open as full pages over this one ("rt" = runtime, "panel" = display).
|
||||
// Coming back restores this page as it was left: the same scroll position, and controller focus
|
||||
// on the driver box that opened the page.
|
||||
var driverPage by remember { mutableStateOf<String?>(null) }
|
||||
var returnTo by remember { mutableStateOf<String?>(null) }
|
||||
val pageScroll = androidx.compose.foundation.rememberScrollState()
|
||||
val runtimeChip = remember { androidx.compose.ui.focus.FocusRequester() }
|
||||
val displayChip = remember { androidx.compose.ui.focus.FocusRequester() }
|
||||
val firstChip = remember { androidx.compose.ui.focus.FocusRequester() }
|
||||
fun openDriverPage(key: String) { returnTo = key; driverPage = key }
|
||||
androidx.compose.runtime.LaunchedEffect(driverPage) {
|
||||
if (driverPage == null) {
|
||||
// One frame first: the box has to be laid out before it can take focus. Opened from the
|
||||
// cog, focus starts on the first control (Resolution) so the d-pad works at once; back
|
||||
// from a driver page, it returns to the driver box that opened it.
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
val target = when (returnTo) { "rt" -> runtimeChip; "panel" -> displayChip; else -> firstChip }
|
||||
runCatching { target.requestFocus() }
|
||||
}
|
||||
}
|
||||
when (driverPage) {
|
||||
"rt" -> {
|
||||
DriverPage(
|
||||
title = "Runtime driver",
|
||||
hint = (if (steam) "Used by Steam and games." else "Used by desktop apps.") + " Applies next session.",
|
||||
rows = s.linuxRows, selected = s.linuxSelected, downloads = s.linuxDownloads,
|
||||
status = s.releaseStatus, checking = s.releaseChecking, importLabel = "Import Turnip zip…", canRestore = false,
|
||||
onSelect = a.onSelectLinux, onDelete = a.onRemoveLinux, onRefresh = a.onRefreshReleases,
|
||||
onDownload = a.onDownloadDriver, onImport = a.onImportLinux, onRestore = {}, onBack = { driverPage = null },
|
||||
)
|
||||
return
|
||||
}
|
||||
"panel" -> {
|
||||
DriverPage(
|
||||
title = "Display driver",
|
||||
hint = "Used by the compositor in both modes. Restart the app to apply.",
|
||||
rows = s.androidRows, selected = s.androidSelected, downloads = s.androidDownloads,
|
||||
status = s.releaseStatus, checking = s.releaseChecking, importLabel = "Import an AdrenoTools zip…",
|
||||
canRestore = s.canRestoreBundled,
|
||||
onSelect = a.onSelectAndroid, onDelete = a.onRemoveAndroid, onRefresh = a.onRefreshReleases,
|
||||
onDownload = a.onDownloadDriver, onImport = a.onImportAndroid, onRestore = a.onRestoreBundled,
|
||||
onBack = { driverPage = null },
|
||||
)
|
||||
return
|
||||
}
|
||||
androidx.compose.runtime.LaunchedEffect(Unit) {
|
||||
// One frame first: the box has to be laid out before it can take focus. Opened from the
|
||||
// cog, focus starts on the first control (Resolution) so the d-pad works at once.
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
runCatching { firstChip.requestFocus() }
|
||||
}
|
||||
SettingsPage(
|
||||
host,
|
||||
@@ -243,18 +194,22 @@ 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(
|
||||
s.linuxRows.firstOrNull { it.id == s.linuxSelected }?.name ?: "Runtime default", open = false,
|
||||
modifier = androidx.compose.ui.Modifier.focusRequester(runtimeChip),
|
||||
) { openDriverPage("rt") }
|
||||
}
|
||||
SettingsRow("Display driver", "Used by the compositor in both modes. Restart the app to apply.") {
|
||||
ValueChip(
|
||||
s.androidRows.firstOrNull { it.id == s.androidSelected }?.name ?: "Auto - picked by GPU", open = false,
|
||||
modifier = androidx.compose.ui.Modifier.focusRequester(displayChip),
|
||||
) { openDriverPage("panel") }
|
||||
SettingsRow("GPU drivers", "Shared by Steam and the desktop, on the Components page.") {
|
||||
ValueChip(s.gpuDrivers, open = false) { a.onGpuDrivers() }
|
||||
}
|
||||
}
|
||||
SettingsGroup(if (steam) "Touch & controls" else "Touch") {
|
||||
|
||||
@@ -114,6 +114,7 @@ class SecondScreenPresentation(
|
||||
SecondScreenMode.TERMINAL -> renderTerminal()
|
||||
SecondScreenMode.DECK_CONTROLS -> root.addView(DeckControlsPanel(context, onClose, onSteamMenu, onQam), weightParams())
|
||||
SecondScreenMode.NONE -> Unit
|
||||
SecondScreenMode.PLASMA_MOBILE -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -166,6 +166,7 @@ class DrawerActions(
|
||||
val backActionsInverted: Boolean,
|
||||
val touchMode: String,
|
||||
val touchAuto: String,
|
||||
val directTouchOnly: Boolean,
|
||||
val shapeMode: String,
|
||||
val fexPreset: String,
|
||||
/** Steam only: games stretched to the screen's size, changed live (null = not Steam). */
|
||||
@@ -173,6 +174,7 @@ class DrawerActions(
|
||||
val secondScreenMode: SecondScreenMode,
|
||||
val secondScreenDisplays: List<SecondScreenDisplay>,
|
||||
val selectedSecondScreenDisplay: Int,
|
||||
val plasmaMobileInstalled: Boolean = false,
|
||||
val onHud: (Boolean) -> Unit,
|
||||
val onFrameGenPick: (FrameGen.Mode) -> Unit,
|
||||
val onImportLossless: () -> Unit,
|
||||
@@ -358,7 +360,11 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
|
||||
DRAWER_PAGE_COMPONENTS -> ComponentsDrawerPage(host, a) { key -> focus.track(page, key) }
|
||||
1 -> {
|
||||
SettingsGroup("Controls") {
|
||||
ChoiceRow(host, "touch", "Touch", null,
|
||||
if (a.directTouchOnly) {
|
||||
SettingsRow("Touch", "Direct input to the screen") {
|
||||
Text("Direct", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
}
|
||||
} else ChoiceRow(host, "touch", "Touch", null,
|
||||
listOf(SessionPrefs.TOUCH_AUTO to "Auto (${a.touchAuto})", SessionPrefs.TOUCH_PAD to "Touchpad", SessionPrefs.TOUCH_DIRECT to "Direct"),
|
||||
a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch)
|
||||
ChoiceRow(host, "osc", "On-screen controls", null,
|
||||
@@ -380,10 +386,11 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
|
||||
}
|
||||
}
|
||||
if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup("Second screen") {
|
||||
val secondScreenModes = listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) +
|
||||
(if (com.droiddeck.launcher.session.SessionState.deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()) +
|
||||
(if (a.plasmaMobileInstalled) listOf(SecondScreenMode.PLASMA_MOBILE) else emptyList())
|
||||
ChoiceRow(host, "second-screen-mode", "Shows", null,
|
||||
(listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) +
|
||||
(if (com.droiddeck.launcher.session.SessionState.deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()))
|
||||
.map { it to it.label },
|
||||
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,
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import java.io.File
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipOutputStream
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class DriverBundleTest {
|
||||
private lateinit var context: Context
|
||||
|
||||
@Before fun setUp() {
|
||||
context = RuntimeEnvironment.getApplication()
|
||||
File(context.filesDir, "graphics_driver").deleteRecursively()
|
||||
File(context.filesDir, LinuxVulkanDriverManager.DIR_NAME).deleteRecursively()
|
||||
context.getSharedPreferences("driver_bundles", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
SessionPrefs.setAndroidDriver(context, "")
|
||||
SessionPrefs.setLinuxDriver(context, "")
|
||||
}
|
||||
|
||||
/** Enough of an AArch64 ELF for the importers: the header they read, then the libc they look for. */
|
||||
private fun library(libc: String) = ByteArray(64).also {
|
||||
byteArrayOf(0x7f, 'E'.code.toByte(), 'L'.code.toByte(), 'F'.code.toByte(), 2, 1).copyInto(it)
|
||||
it[18] = 0xB7.toByte()
|
||||
} + libc.toByteArray() + ByteArray(1)
|
||||
|
||||
private val manifest = JSONObject()
|
||||
.put("package", "DD-Turnip").put("version", "0.1.0").put("tag", "DD-Turnip-v0.1.0")
|
||||
.put("drivers", JSONObject()
|
||||
.put("android", JSONObject().put("path", "android"))
|
||||
.put("linux", JSONObject().put("path", "linux")))
|
||||
|
||||
private fun zip(entries: Map<String, ByteArray>): Uri {
|
||||
val file = File.createTempFile("bundle", ".zip", context.cacheDir)
|
||||
ZipOutputStream(file.outputStream()).use { z ->
|
||||
for ((name, data) in entries) { z.putNextEntry(ZipEntry(name)); z.write(data); z.closeEntry() }
|
||||
}
|
||||
return Uri.fromFile(file)
|
||||
}
|
||||
|
||||
private fun bundle(linuxLibc: String = "libc.so.6", extra: Map<String, ByteArray> = emptyMap()) = zip(mapOf(
|
||||
"android/meta.json" to JSONObject().put("name", "DD-Turnip v0.1.0").put("libraryName", "libvulkan_freedreno.so").toString().toByteArray(),
|
||||
"android/libvulkan_freedreno.so" to library("libc.so"),
|
||||
"linux/meta.json" to JSONObject().put("name", "DD-Turnip v0.1.0").put("driverVersion", "DD-Turnip-v0.1.0").toString().toByteArray(),
|
||||
"linux/libvulkan_freedreno.so" to library(linuxLibc),
|
||||
"manifest.json" to manifest.toString().toByteArray(),
|
||||
) + extra)
|
||||
|
||||
@Test fun manifestNeedsBothHalvesInSeparateSafeDirectories() {
|
||||
val m = DriverBundle.parseManifest(manifest)!!
|
||||
assertEquals("android", m.androidPath)
|
||||
assertEquals("linux", m.linuxPath)
|
||||
assertNull(DriverBundle.parseManifest(JSONObject().put("drivers", JSONObject().put("android", JSONObject().put("path", "a")))))
|
||||
val same = JSONObject(manifest.toString()).apply { getJSONObject("drivers").getJSONObject("linux").put("path", "android/") }
|
||||
assertNull(DriverBundle.parseManifest(same))
|
||||
val escape = JSONObject(manifest.toString()).apply { getJSONObject("drivers").getJSONObject("linux").put("path", "../x") }
|
||||
assertNull(DriverBundle.parseManifest(escape))
|
||||
}
|
||||
|
||||
@Test fun singleDriverZipsAreNotBundles() {
|
||||
val legacy = zip(mapOf("meta.json" to "{}".toByteArray(), "libvulkan_freedreno.so" to library("libc.so")))
|
||||
assertFalse(DriverBundle.isBundle(context, legacy))
|
||||
assertTrue(DriverBundle.isBundle(context, bundle()))
|
||||
}
|
||||
|
||||
@Test fun installsBothHalvesAndPicksAndDeletesThemTogether() {
|
||||
val b = DriverBundle.install(context, bundle())
|
||||
assertEquals("DD-Turnip-v0.1.0", b.id)
|
||||
assertEquals("DD-Turnip 0.1.0", b.label)
|
||||
assertTrue(TurnipDriver(context).isInstalled(b.androidId))
|
||||
assertTrue(LinuxVulkanDriverManager(context).isInstalled(b.linuxId))
|
||||
assertEquals(b.id, DriverBundle.containing(context, b.linuxId, linux = true)?.id)
|
||||
assertEquals(b.id, DriverBundle.containing(context, b.androidId, linux = false)?.id)
|
||||
|
||||
assertNull(DriverBundle.active(context))
|
||||
DriverBundle.select(context, b)
|
||||
assertEquals(b.androidId, SessionPrefs.androidDriver(context))
|
||||
assertEquals(b.linuxId, SessionPrefs.linuxDriver(context))
|
||||
assertNotNull(DriverBundle.active(context))
|
||||
|
||||
DriverBundle.remove(context, b)
|
||||
assertFalse(TurnipDriver(context).isInstalled(b.androidId))
|
||||
assertFalse(LinuxVulkanDriverManager(context).isInstalled(b.linuxId))
|
||||
assertEquals("", SessionPrefs.androidDriver(context))
|
||||
assertEquals("", SessionPrefs.linuxDriver(context))
|
||||
assertTrue(DriverBundle.all(context).isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aRefusedHalfLeavesNothingInstalled() {
|
||||
try {
|
||||
DriverBundle.install(context, bundle(linuxLibc = "libc.so"))
|
||||
fail("a bionic library in linux/ must be refused")
|
||||
} catch (e: IllegalArgumentException) {
|
||||
assertTrue(e.message!!.contains("glibc"))
|
||||
}
|
||||
assertTrue(TurnipDriver(context).enumerateImported().isEmpty())
|
||||
assertTrue(LinuxVulkanDriverManager(context).enumerateInstalledDrivers().isEmpty())
|
||||
}
|
||||
|
||||
@Test fun entriesOutsideTheBundleAreRefused() {
|
||||
try {
|
||||
DriverBundle.install(context, bundle(extra = mapOf("../escape.so" to ByteArray(4))))
|
||||
fail("a zip-slip entry must be refused")
|
||||
} catch (e: IllegalArgumentException) {
|
||||
assertTrue(e.message!!.contains("outside"))
|
||||
}
|
||||
assertFalse(File(context.cacheDir.parentFile, "escape.so").exists())
|
||||
}
|
||||
|
||||
@Test fun twoInstallsOfOneReleaseGetTheirOwnIds() {
|
||||
val first = DriverBundle.install(context, bundle())
|
||||
val second = DriverBundle.install(context, bundle())
|
||||
assertEquals("DD-Turnip-v0.1.0-2", second.id)
|
||||
assertEquals(2, DriverBundle.all(context).size)
|
||||
assertFalse(first.androidId == second.androidId)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import com.droiddeck.launcher.gpu.GpuInfo.Family
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DriverPairsTest {
|
||||
private fun gpu(model: Int, adreno: Boolean = true, oneUi: Boolean = false) =
|
||||
GpuInfo("Adreno $model", model, GpuInfo.familyOf(adreno, model), "", oneUi)
|
||||
|
||||
private fun asset(name: String, tag: String, linux: Boolean, pair: String) =
|
||||
TurnipReleases.Asset("src", tag, name, "https://example/$name", 3_000_000, linux, "label", "0".repeat(64), pair)
|
||||
|
||||
@Test
|
||||
fun familiesFollowTheAdrenoModel() {
|
||||
assertEquals(Family.A8XX, GpuInfo.familyOf(true, 825))
|
||||
assertEquals(Family.A8XX, GpuInfo.familyOf(true, 810))
|
||||
assertEquals(Family.A7XX_LOW, GpuInfo.familyOf(true, 722))
|
||||
assertEquals(Family.A7XX, GpuInfo.familyOf(true, 740))
|
||||
assertEquals(Family.A6XX, GpuInfo.familyOf(true, 610))
|
||||
assertEquals(Family.ADRENO_UNKNOWN, GpuInfo.familyOf(true, 0))
|
||||
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, 0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onlyTestedHardwareCountsAsSupported() {
|
||||
assertEquals(GpuInfo.Support.TESTED, gpu(740).support)
|
||||
assertEquals(GpuInfo.Support.TESTED, gpu(825).support)
|
||||
assertEquals(GpuInfo.Support.UNTESTED, gpu(610).support)
|
||||
assertEquals(GpuInfo.Support.UNTESTED, gpu(720).support)
|
||||
assertEquals(GpuInfo.Support.UNSUPPORTED, gpu(0, adreno = false).support)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun autoPicksWinNativeBalancedOn8xxAndBannersElsewhere() {
|
||||
assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(830), emptyList()))
|
||||
assertEquals("840 with no DD-Turnip release listed", DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(840), emptyList()))
|
||||
assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(825), emptyList()))
|
||||
assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(740), emptyList()))
|
||||
assertEquals(DriverPairs.BANNER_ONEUI, DriverPairs.recommendedKey(gpu(740, oneUi = true), emptyList()))
|
||||
assertEquals(DriverPairs.BANNER_710, DriverPairs.recommendedKey(gpu(720), emptyList()))
|
||||
assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(650), emptyList()))
|
||||
assertNull(DriverPairs.recommendedKey(gpu(0, adreno = false), emptyList()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pairsMatchHalvesAndNeverMixBannersReleases() {
|
||||
val check = TurnipReleases.Check(
|
||||
listOf(
|
||||
asset("Turnip-r4.zip", "r4", false, DriverPairs.BANNER),
|
||||
asset("Turnip-r4-Linux.zip", "r4", true, DriverPairs.BANNER),
|
||||
// The A8xx set's newest display build is r4, but its Linux half is only in r3.
|
||||
asset("Turnip-r4-A8xx.zip", "r4", false, DriverPairs.BANNER_A8XX),
|
||||
asset("Turnip-r3-A8xx-Linux.zip", "r3", true, DriverPairs.BANNER_A8XX),
|
||||
asset("WN-Turnip-1.19-b_Axxx.zip", "v1.19", false, DriverPairs.WN_BALANCED),
|
||||
asset("WN-Linux-Turnip-0.1.2-b_Axxx.zip", "linux-v0.1.2", true, DriverPairs.WN_BALANCED),
|
||||
),
|
||||
emptyList(), emptyList(), 0L,
|
||||
)
|
||||
val pairs = DriverPairs.from(check).associateBy { it.key }
|
||||
assertTrue(pairs.getValue(DriverPairs.BANNER).complete)
|
||||
assertFalse("halves from two releases are not a pair", pairs.getValue(DriverPairs.BANNER_A8XX).complete)
|
||||
val wn = pairs.getValue(DriverPairs.WN_BALANCED)
|
||||
assertTrue("WinNative's two release lines pair up", wn.complete)
|
||||
assertEquals("v1.19 + v0.1.2", wn.version)
|
||||
assertTrue(wn.suits(gpu(830)))
|
||||
assertFalse(pairs.getValue(DriverPairs.BANNER).suits(gpu(830)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyBundleReleaseIsACompletePairOnItsOwnNewestFirst() {
|
||||
fun bundle(tag: String) = TurnipReleases.Asset("DroidDeck", tag, "$tag.zip", "https://example/$tag", 6_000_000,
|
||||
false, "Android + Linux", "0".repeat(64), DriverPairs.ddTurnip(tag), bundle = true)
|
||||
val newer = bundle("DD-Turnip-v0.2.0")
|
||||
val older = bundle("DD-Turnip-v0.1.0")
|
||||
val pairs = DriverPairs.from(TurnipReleases.Check(
|
||||
listOf(asset("Turnip-r4.zip", "r4", false, DriverPairs.BANNER), newer, older,
|
||||
asset("Turnip-r4-Linux.zip", "r4", true, DriverPairs.BANNER)),
|
||||
emptyList(), emptyList(), 0L,
|
||||
))
|
||||
assertEquals(listOf(DriverPairs.ddTurnip("DD-Turnip-v0.2.0"), DriverPairs.ddTurnip("DD-Turnip-v0.1.0"), DriverPairs.BANNER), pairs.map { it.key })
|
||||
val dd = pairs.first()
|
||||
assertTrue(dd.complete)
|
||||
assertEquals(listOf(newer), dd.assets)
|
||||
assertEquals("v0.2.0", dd.version)
|
||||
assertEquals("DroidDeck · DD-Turnip", dd.name)
|
||||
assertTrue(dd.suits(gpu(840)))
|
||||
assertTrue(dd.suits(gpu(740)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun adreno840GetsTheNewestOfficialDdTurnip() {
|
||||
fun bundle(tag: String) = TurnipReleases.Asset("DroidDeck", tag, "$tag.zip", "https://example/$tag", 6_000_000,
|
||||
false, "Android + Linux", "0".repeat(64), DriverPairs.ddTurnip(tag), bundle = true)
|
||||
val pairs = DriverPairs.from(TurnipReleases.Check(
|
||||
listOf(bundle("DD-Turnip-v0.9.0"), bundle("DD-Turnip-v1.0.0"), bundle("DD-Turnip-v0.10.1"),
|
||||
asset("WN-Turnip-1.19-b_Axxx.zip", "v1.19", false, DriverPairs.WN_BALANCED),
|
||||
asset("WN-Linux-Turnip-0.1.2-b_Axxx.zip", "linux-v0.1.2", true, DriverPairs.WN_BALANCED)),
|
||||
emptyList(), emptyList(), 0L,
|
||||
))
|
||||
assertEquals(DriverPairs.ddTurnip("DD-Turnip-v1.0.0"), DriverPairs.recommendedKey(gpu(840), pairs))
|
||||
assertEquals("other 8xx keep WinNative", DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(830), pairs))
|
||||
assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(825), pairs))
|
||||
assertEquals(DriverPairs.BANNER, DriverPairs.recommendedKey(gpu(740), pairs))
|
||||
}
|
||||
}
|
||||
@@ -21,16 +21,21 @@ The resulting snapshot is stored under that account's `userdata/<id>/config` and
|
||||
refreshed every 30 seconds while logged in. Title lookups retry every five minutes and
|
||||
when the source changes, so an early network failure does not end the watcher. Changed
|
||||
status and probe failures are written to the session log. Startup and post-exit import
|
||||
use the last successful snapshot for the selected account. A newly identified title
|
||||
therefore starts as a shortcut and becomes a Steam entry after Steam exits and starts
|
||||
again. An unavailable client or offline first launch falls back to shortcuts; existing
|
||||
use the last successful snapshot for the selected account. The client reads manifests
|
||||
and shortcuts only at start, so when a snapshot confirms owned titles that are not yet
|
||||
imported, the watcher restarts the client once (not while a game runs or a download is in
|
||||
progress) and the importer runs between the exit and the next start. An unavailable client or offline first launch falls back to shortcuts; existing
|
||||
snapshots remain usable offline. Steam still enforces the current license at launch.
|
||||
|
||||
For a confirmed game without a manifest, the importer links the source folder into the
|
||||
internal Steam library and writes an installed manifest with `Universe=1` and
|
||||
`StateFlags=4`. Steam ignores manifests without the universe field. This registers
|
||||
existing files; it does not assert a verified build ID or depot manifest. Steam can
|
||||
still require verification, updates or redistributables. Steam updates and uninstall
|
||||
`StateFlags=4`. Steam ignores manifests without the universe field. A manifest without
|
||||
installed depots makes Steam verify every file, so the importer carries the build another
|
||||
client recorded: WinNative's `.winnative-steam/steamapps` manifest beside the game folder,
|
||||
or a completed download's `.DepotDownloader/depot.config` depot manifest IDs. Steam then
|
||||
only downloads what changed since that build. Bare manifests from earlier imports are
|
||||
upgraded while Steam has not touched them. Without either record Steam still verifies.
|
||||
WinNative's manifest also identifies the folder without a store lookup. Steam updates and uninstall
|
||||
operate on the linked game files, so imported folders must be writable. Existing Steam
|
||||
manifests and directories are preserved. Only the exact minimal manifests generated by
|
||||
the earlier importer are migrated, with the matching source symlink still present. If
|
||||
|
||||
@@ -124,6 +124,7 @@ docker run --rm --platform linux/amd64 \
|
||||
[ -f "$f" ] && install -Dm644 "$f" "$d/${f#tools/linuxfs/overlay/}"
|
||||
done
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop "$d/usr/local/bin/droiddeck-desktop"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-plasma-mobile "$d/usr/local/bin/droiddeck-plasma-mobile"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-gpu "$d/usr/local/bin/droiddeck-gpu"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop-gpu "$d/usr/local/bin/droiddeck-desktop-gpu"
|
||||
install -Dm644 tools/linuxfs/desktop/autostart "$d/etc/xdg/labwc/autostart"
|
||||
@@ -158,6 +159,8 @@ docker run --rm --platform linux/amd64 \
|
||||
test -f "$d/usr/local/bin/bannerlator-proton-extra"
|
||||
'
|
||||
|
||||
"${repo_root}/tools/plasma-mobile/build.sh"
|
||||
|
||||
github_repo=${DROIDDECK_GITHUB_REPOSITORY:-}
|
||||
if [[ -z "${github_repo}" ]]; then
|
||||
origin_url=$(git -C "${repo_root}" remote get-url origin)
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
#!/bin/bash
|
||||
# Run Plasma Mobile inside a nested KWin Wayland session.
|
||||
set -u
|
||||
|
||||
export XDG_SESSION_TYPE=wayland
|
||||
export XDG_SESSION_DESKTOP=KDE
|
||||
export XDG_CURRENT_DESKTOP=KDE
|
||||
export QT_QPA_PLATFORM=wayland
|
||||
export QT_QPA_PLATFORMTHEME=KDE
|
||||
export QT_WAYLAND_DISABLE_WINDOWDECORATION=1
|
||||
export EGL_PLATFORM=wayland
|
||||
export QT_QUICK_CONTROLS_STYLE=org.kde.breeze
|
||||
export QT_ENABLE_GLYPH_CACHE_WORKAROUND=1
|
||||
export QT_QUICK_CONTROLS_MOBILE=1
|
||||
export KSCREEN_BACKEND=QScreen
|
||||
export KDE_FULL_SESSION=1
|
||||
export KDE_SESSION_VERSION=6
|
||||
export XDG_MENU_PREFIX=plasma-
|
||||
export PLASMA_INTEGRATION_USE_PORTAL=1
|
||||
export PLASMA_PLATFORM=phone:handset
|
||||
export PLASMA_DEFAULT_SHELL=org.kde.plasma.mobileshell
|
||||
export XDG_CONFIG_DIRS="$HOME/.config/plasma-mobile:/etc/xdg:${XDG_CONFIG_DIRS:-}"
|
||||
export GDK_BACKEND=wayland,x11
|
||||
export SDL_VIDEODRIVER=wayland,x11
|
||||
|
||||
if [ -n "${BL_DEBUG_DIR:-}" ]; then
|
||||
mkdir -p "$BL_DEBUG_DIR" 2>/dev/null || true
|
||||
exec >>"$BL_DEBUG_DIR/desktop.log" 2>&1
|
||||
echo "== droiddeck-plasma-mobile $(date -u '+%Y-%m-%d %H:%M:%S UTC') ${BL_WIDTH:-1280}x${BL_HEIGHT:-720}"
|
||||
fi
|
||||
|
||||
if ! command -v plasmashell >/dev/null 2>&1 || ! command -v dbus-run-session >/dev/null 2>&1; then
|
||||
echo "== Plasma Mobile packages are missing; choose KDE Plasma Mobile in Desktop settings and start Desktop once"
|
||||
exit 66
|
||||
fi
|
||||
|
||||
plasma_log="${BL_DEBUG_DIR:-/tmp}/plasma.log"
|
||||
echo "== Plasma $(plasmashell --version 2>&1)"
|
||||
echo "== Wayland display ${WAYLAND_DISPLAY:-wayland-0}; XDG runtime $XDG_RUNTIME_DIR"
|
||||
mkdir -p /tmp || exit 73
|
||||
chmod 1777 /tmp || echo "== could not set standard temporary-directory permissions"
|
||||
export TMPDIR=/tmp
|
||||
echo "== temporary directories: $(ls -ld /tmp /dev/shm 2>&1)"
|
||||
echo "== preparing the KDE Plasma Mobile Wayland session"
|
||||
: >"$plasma_log"
|
||||
|
||||
# Gamescope's Zink override is for game clients. KWin owns the Plasma Mobile session and presents
|
||||
# one nested Wayland window through Bannerlator's host compositor.
|
||||
export QT_QUICK_BACKEND=software
|
||||
unset MESA_LOADER_DRIVER_OVERRIDE GALLIUM_DRIVER LIBGL_KOPPER_DRI2 ZINK_DESCRIPTORS mesa_glthread MESA_NO_ERROR
|
||||
|
||||
# The PRoot guest has no systemd user manager. Hide only its session-bus activation entry while
|
||||
# KDE starts, and restore it on every exit.
|
||||
systemd_dbus_service=/usr/share/dbus-1/services/org.freedesktop.systemd1.service
|
||||
systemd_dbus_service_disabled="$systemd_dbus_service.droiddeck-disabled"
|
||||
restore_systemd_dbus_service() {
|
||||
if [ -e "$systemd_dbus_service_disabled" ] && [ ! -e "$systemd_dbus_service" ]; then
|
||||
mv "$systemd_dbus_service_disabled" "$systemd_dbus_service" || echo "== could not restore systemd D-Bus service file"
|
||||
fi
|
||||
}
|
||||
restore_systemd_dbus_service
|
||||
if [ -f "$systemd_dbus_service" ]; then
|
||||
mv "$systemd_dbus_service" "$systemd_dbus_service_disabled" || echo "== could not disable session-bus activation for systemd1"
|
||||
fi
|
||||
trap restore_systemd_dbus_service EXIT
|
||||
dbus-run-session -- env XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" plasma_log="$plasma_log" sh -c '
|
||||
export WAYLAND_DISPLAY=wayland-0
|
||||
width=${BL_WIDTH:-1280}
|
||||
height=${BL_HEIGHT:-720}
|
||||
rm -f "$XDG_RUNTIME_DIR/wayland-1" "$XDG_RUNTIME_DIR/wayland-1.lock"
|
||||
# D-Bus activation inherited the outer compositor socket. KDE services activated later must
|
||||
# connect to the nested socket, while KWin itself continues to connect to the outer one.
|
||||
if command -v dbus-update-activation-environment >/dev/null 2>&1; then
|
||||
WAYLAND_DISPLAY=wayland-1 dbus-update-activation-environment WAYLAND_DISPLAY >>"$plasma_log" 2>&1
|
||||
echo "== D-Bus activation Wayland display update status $?"
|
||||
fi
|
||||
if command -v plasma-mobile-envmanager >/dev/null 2>&1; then
|
||||
echo "== applying Plasma Mobile device settings"
|
||||
QT_QPA_PLATFORM=offscreen plasma-mobile-envmanager --apply-settings >>"$plasma_log" 2>&1
|
||||
echo "== Plasma Mobile environment setup status $?"
|
||||
else
|
||||
echo "== plasma-mobile-envmanager is missing"
|
||||
fi
|
||||
# This guest has no interactive login from which the user can set a Linux password. The Plasma
|
||||
# Mobile PIN keypad authenticates that account password, so an idle/lock event can strand a
|
||||
# device user at a screen they cannot unlock. Keep session locking disabled for this embedded
|
||||
# desktop and let Android own the device lock instead.
|
||||
lock_config="${XDG_CONFIG_HOME:-$HOME/.config}/kscreenlockerrc"
|
||||
mkdir -p "$(dirname "$lock_config")"
|
||||
if command -v kwriteconfig6 >/dev/null 2>&1; then
|
||||
kwriteconfig6 --file "$lock_config" --group Daemon --key Autolock false
|
||||
kwriteconfig6 --file "$lock_config" --group Daemon --key LockOnResume false
|
||||
kwriteconfig6 --file "$lock_config" --group Daemon --key RequirePassword false
|
||||
kwriteconfig6 --file "$lock_config" --group Daemon --key Timeout 0
|
||||
echo "== disabled Plasma screen locking in $lock_config"
|
||||
else
|
||||
echo "== kwriteconfig6 is missing; could not disable Plasma screen locking"
|
||||
fi
|
||||
if command -v kbuildsycoca6 >/dev/null 2>&1; then
|
||||
echo "== building KDE service cache"
|
||||
QT_QPA_PLATFORM=offscreen kbuildsycoca6 --noincremental >>"$plasma_log" 2>&1
|
||||
cache_status=$?
|
||||
echo "== KDE service cache status $cache_status"
|
||||
cache_dir=${XDG_CACHE_HOME:-$HOME/.cache}
|
||||
for cache_file in "$cache_dir"/ksycoca6_*; do
|
||||
[ -f "$cache_file" ] || continue
|
||||
# KDE cache files land write-only under this PRoot user and cannot be reopened by service lookups.
|
||||
chmod u+rw "$cache_file" || echo "== could not make KDE cache readable: $cache_file"
|
||||
done
|
||||
else
|
||||
echo "== kbuildsycoca6 is missing"
|
||||
fi
|
||||
effect_config="${XDG_CONFIG_HOME:-$HOME/.config}/kwinrc"
|
||||
if command -v kwriteconfig6 >/dev/null 2>&1; then
|
||||
# The overview control in Plasma Mobile invokes this KWin effect. Keep it explicitly enabled
|
||||
# so the patched state/gesture initialization is active in the embedded session.
|
||||
kwriteconfig6 --file "$effect_config" --group Plugins --key mobiletaskswitcherEnabled true
|
||||
fi
|
||||
if command -v kreadconfig6 >/dev/null 2>&1; then
|
||||
effect_setting=$(kreadconfig6 --file "$effect_config" \
|
||||
--group Plugins --key mobiletaskswitcherEnabled 2>&1 || true)
|
||||
echo "== mobile task-switcher setting in $effect_config: ${effect_setting:-unset}"
|
||||
else
|
||||
echo "== kreadconfig6 is missing; cannot inspect the mobile task-switcher setting"
|
||||
fi
|
||||
echo "== starting nested KWin and Plasma Mobile on wayland-0 (${width}x${height}), socket wayland-1"
|
||||
# The mobile task switcher queries Workspace::activities() while filtering tasks.
|
||||
# Keep KActivities initialized; --no-kactivities makes the overview crash on activation.
|
||||
KWIN_WAYLAND_NO_PERMISSION_CHECKS=1 kwin_wayland \
|
||||
--xwayland \
|
||||
--wayland-display=wayland-0 \
|
||||
--socket=wayland-1 \
|
||||
--width="$width" --height="$height" --fullscreen \
|
||||
--no-lockscreen \
|
||||
--exit-with-session "plasmashell -p org.kde.plasma.mobileshell --replace" \
|
||||
>>"$plasma_log" 2>&1 &
|
||||
kwin_pid=$!
|
||||
cleanup() {
|
||||
if [ -n "$kwin_pid" ]; then kill "$kwin_pid" 2>/dev/null || true; wait "$kwin_pid" 2>/dev/null || true; fi
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
wait "$kwin_pid"
|
||||
' >>"$plasma_log" 2>&1
|
||||
result=$?
|
||||
restore_systemd_dbus_service
|
||||
trap - EXIT
|
||||
echo "== Plasma Mobile session exited (status $result)"
|
||||
exit "$result"
|
||||
@@ -11,7 +11,7 @@ import sys
|
||||
|
||||
HOME = os.environ.get("HOME", "/root")
|
||||
STEAM_ROOT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HOME, ".local/share/Steam")
|
||||
LIBRARIES = ((STEAM_ROOT, "Steam Games"), ("/mnt/bannerlator-sd", "SD Games"))
|
||||
LIBRARIES = ((STEAM_ROOT, "Steam Games"), ("/mnt/droiddeck-sd", "SD Games"))
|
||||
# The client's own tools and runtimes live in steamapps beside the games; they are not titles.
|
||||
NOT_GAMES = {228980, 1493710, 3127680, 4183110, 4427310, 4185400}
|
||||
APPS_DIR = os.path.join(HOME, ".local/share/applications")
|
||||
|
||||
@@ -79,7 +79,7 @@ block=$(printf '%s\n' "$pairs" | awk -F'\t' -v now="$(date +%s)" '
|
||||
for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
|
||||
"$steam_root"/compatibilitytools.d/*/files/share/default_pfx*/system.reg \
|
||||
"$steam_root"/steamapps/compatdata/*/pfx/system.reg \
|
||||
/mnt/bannerlator-sd/steamapps/compatdata/*/pfx/system.reg; do
|
||||
/mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg; do
|
||||
[ -f "$reg" ] || continue
|
||||
seeded=$(dirname "$reg")/.bannerlator-redists
|
||||
[ "$(cat "$seeded" 2>/dev/null)" = "$stamp" ] && continue
|
||||
|
||||
@@ -126,8 +126,17 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
wayland-info >/dev/null 2>&1 && break
|
||||
sleep 0.1
|
||||
done
|
||||
# The desktop (DroidDeck's hosted package) is its own nested compositor, labwc, drawing straight
|
||||
# into the app's: no gamescope in between.
|
||||
# LXQt uses its nested compositor; Plasma Mobile starts a nested KWin session. The selected
|
||||
# primary desktop comes through BL_DESKTOP_ENV, while the independent secondary-display process
|
||||
# starts directly in plasma-mobile mode.
|
||||
if [ "$mode" = lxqt ] && [ "${BL_DESKTOP_ENV:-lxqt}" = plasma-mobile ]; then
|
||||
mode=plasma-mobile
|
||||
fi
|
||||
if [ "$mode" = plasma-mobile ]; then
|
||||
step "starting KDE Plasma Mobile"
|
||||
[ -x /usr/local/bin/droiddeck-plasma-mobile ] || { echo "== Plasma Mobile launcher is missing"; exit 66; }
|
||||
exec /usr/local/bin/droiddeck-plasma-mobile
|
||||
fi
|
||||
if [ "$mode" = lxqt ]; then
|
||||
step "starting the desktop"
|
||||
[ -x /usr/local/bin/droiddeck-desktop ] || { echo "== the desktop package is not installed"; exit 66; }
|
||||
@@ -234,7 +243,7 @@ case $mode in
|
||||
bannerlator-steam-install || exit $?
|
||||
step "Steam client ready"
|
||||
steam_root=$XDG_DATA_HOME/Steam
|
||||
# Register the card library (bound at /mnt/bannerlator-sd) with the client - internal storage is
|
||||
# Register the card library (bound at /mnt/droiddeck-sd) with the client - internal storage is
|
||||
# its main library already - and the ARM64 Proton that lets it launch the Windows ones.
|
||||
# A request left in ~/.bl-proton-extra installs a third-party Proton before the client starts,
|
||||
# so it is in the Compatibility dropdown the first time the user looks. One per line, each the
|
||||
@@ -446,7 +455,7 @@ case $mode in
|
||||
local d
|
||||
[ -e "$compat_stamp" ] && [ "$((beat % 12))" -ne 0 ] || return 0
|
||||
for d in "$steam_root/steamapps" "$steam_root/steamapps/common" "$steam_root/config" \
|
||||
"$steam_root/compatibilitytools.d" /mnt/bannerlator-sd/steamapps; do
|
||||
"$steam_root/compatibilitytools.d" /mnt/droiddeck-sd/steamapps; do
|
||||
[ "$d" -nt "$compat_stamp" ] && return 0
|
||||
done
|
||||
return 1
|
||||
|
||||
@@ -13,6 +13,9 @@ import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
STATE = ".droiddeck-games.json"
|
||||
WINNATIVE = ".winnative-steam/steamapps"
|
||||
LIBRARY = "/mnt/droiddeck-sd"
|
||||
LEGACY_LIBRARY = "/mnt/bannerlator-sd"
|
||||
BASE_ID = 76561197960265728
|
||||
|
||||
|
||||
@@ -40,6 +43,11 @@ def edition_key(name):
|
||||
return title_key(name)
|
||||
|
||||
|
||||
def legacy_path(path):
|
||||
path = str(path)
|
||||
return LEGACY_LIBRARY + path[len(LIBRARY):] if path == LIBRARY or path.startswith(LIBRARY + "/") else path
|
||||
|
||||
|
||||
def source_stamp(game):
|
||||
try:
|
||||
exe = Path(game["exe"])
|
||||
@@ -53,19 +61,23 @@ def source_stamp(game):
|
||||
return None
|
||||
|
||||
|
||||
def manifest_ids(steamapps, name):
|
||||
matches = []
|
||||
for manifest in Path(steamapps).glob("appmanifest_*.acf"):
|
||||
try:
|
||||
install = re.search(r'"installdir"\s*"([^"\\]*)"', manifest.read_text(), re.I)
|
||||
if install and install[1] == name:
|
||||
matches.append(int(manifest.stem.removeprefix("appmanifest_")))
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
return matches
|
||||
|
||||
|
||||
def identify(game):
|
||||
folder = Path(game["folder"])
|
||||
steamapps = folder.parent.parent
|
||||
if folder.parent.name == "common" and steamapps.name == "steamapps":
|
||||
matches = []
|
||||
for manifest in steamapps.glob("appmanifest_*.acf"):
|
||||
try:
|
||||
text = manifest.read_text()
|
||||
install = re.search(r'"installdir"\s*"([^"\\]*)"', text, re.I)
|
||||
if install and install[1] == folder.name:
|
||||
matches.append(int(manifest.stem.removeprefix("appmanifest_")))
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
for library in ([steamapps] if folder.parent.name == "common" and steamapps.name == "steamapps" else []) + [folder.parent / WINNATIVE]:
|
||||
matches = manifest_ids(library, folder.name)
|
||||
if matches:
|
||||
return matches[0] if len(matches) == 1 else None
|
||||
ids = set()
|
||||
@@ -144,6 +156,27 @@ def game_running():
|
||||
return False
|
||||
|
||||
|
||||
def downloads_idle(steam_root):
|
||||
try:
|
||||
return not any(Path(steam_root, "steamapps/downloading").iterdir())
|
||||
except OSError:
|
||||
return True
|
||||
|
||||
|
||||
def request_restart(steam_root):
|
||||
"""The client reads manifests and shortcuts only at start, so an import needs one restart;
|
||||
the session's loop runs the importer between the exit and the next start."""
|
||||
Path(os.environ.get("HOME", "/root"), ".bl-restart-once").touch()
|
||||
subprocess.run([str(Path(steam_root) / "steamrtarm64/steam"), "-shutdown"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
|
||||
|
||||
|
||||
def unimported(steam_root, snapshot, candidates):
|
||||
routes = read_json(Path(steam_root) / "userdata" / snapshot["account"] / "config/.droiddeck-routes.json", {})
|
||||
routed = set(routes.values()) if isinstance(routes, dict) else set()
|
||||
return sorted({appid for appid in candidates.values() if snapshot["owned"].get(str(appid)) is True} - routed)
|
||||
|
||||
|
||||
def watch(steam_root, listing):
|
||||
games = read_json(listing, [])
|
||||
if os.environ.get("BL_STEAM_OFFLINE") == "1" or not games:
|
||||
@@ -158,6 +191,7 @@ def watch(steam_root, listing):
|
||||
# beat (a client that is not logged on fails it for as long as it stays that way), and none
|
||||
# starts while a game is running: the answer can wait, the game's cores cannot.
|
||||
probed, next_probe, failures = None, 0, 0
|
||||
pending, requested = [], []
|
||||
while True:
|
||||
now = time.monotonic()
|
||||
for game in games:
|
||||
@@ -195,6 +229,7 @@ def watch(steam_root, listing):
|
||||
snapshot["candidates"] = candidates
|
||||
snapshot["sources"] = sources
|
||||
save_json(Path(steam_root) / "userdata" / snapshot["account"] / "config" / STATE, snapshot)
|
||||
pending = unimported(steam_root, snapshot, candidates)
|
||||
status = "matched %d/%d games; %d owned" % (len(candidates), len(games), sum(snapshot["owned"].values()))
|
||||
except (OSError, ValueError, KeyError, StopIteration, subprocess.TimeoutExpired) as error:
|
||||
status = "ownership check unavailable: " + str(error)
|
||||
@@ -202,12 +237,51 @@ def watch(steam_root, listing):
|
||||
next_probe = now + min(300, 30 * 2 ** failures)
|
||||
elif candidates:
|
||||
status = last_status
|
||||
if pending and pending != requested and not game_running() and downloads_idle(steam_root):
|
||||
requested = pending
|
||||
print("bannerlator-steam-games: restarting the client once to import %s" % pending, flush=True)
|
||||
try:
|
||||
request_restart(steam_root)
|
||||
except (OSError, subprocess.TimeoutExpired) as error:
|
||||
print("bannerlator-steam-games: restart unavailable: %s" % error, flush=True)
|
||||
if status != last_status:
|
||||
print("bannerlator-steam-games: " + status, flush=True)
|
||||
last_status = status
|
||||
time.sleep(30)
|
||||
|
||||
|
||||
def installed_build(folder, appid, installdir):
|
||||
"""The build another Steam client recorded for these files, so Steam updates from it
|
||||
instead of verifying every file."""
|
||||
try:
|
||||
text = (folder.parent / WINNATIVE / f"appmanifest_{appid}.acf").read_text()
|
||||
install = re.search(r'("installdir"\s*")([^"\\]*)(")', text, re.I)
|
||||
flags = re.search(r'"StateFlags"\s*"(\d+)"', text)
|
||||
if (install and install[2] == folder.name and flags and flags[1] == "4"
|
||||
and re.search(rf'"appid"\s*"{appid}"', text) and '"InstalledDepots"' in text):
|
||||
return text[:install.start(2)] + installdir + text[install.end(2):]
|
||||
except OSError:
|
||||
pass
|
||||
if not (folder / ".download_complete").is_file():
|
||||
return None
|
||||
try:
|
||||
ids = json.loads((folder / ".DepotDownloader/depot.config").read_text())["installedManifestIDs"]
|
||||
depots = sorted((int(depot), int(gid)) for depot, gid in ids.items())
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError):
|
||||
return None
|
||||
if not depots or not all(0 < depot < 0x80000000 and 0 < gid < 0x7FFFFFFFFFFFFFFF for depot, gid in depots):
|
||||
return None
|
||||
return "".join(f' "{depot}"\n {{\n "manifest" "{gid}"\n }}\n' for depot, gid in depots)
|
||||
|
||||
|
||||
def update_not_started(text, steamapps, appid, installdir):
|
||||
fields = dict(re.findall(r'^\s*"(\w+)"\s*"([^"]*)"', text, re.M))
|
||||
return (fields.get("installdir") == installdir and fields.get("buildid", "0") == "0"
|
||||
and fields.get("BytesDownloaded", "0") == "0" and fields.get("BytesStaged", "0") == "0"
|
||||
and re.search(r'"InstalledDepots"\s*\{\s*\}', text) is not None
|
||||
and not (steamapps / "downloading" / str(appid)).exists())
|
||||
|
||||
|
||||
def seed_install(steam_root, game, appid):
|
||||
steamapps = Path(steam_root) / "steamapps"
|
||||
common = steamapps / "common"
|
||||
@@ -215,16 +289,30 @@ def seed_install(steam_root, game, appid):
|
||||
target = common / name
|
||||
source = Path(game["folder"])
|
||||
title = game["name"].replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
|
||||
content = ('"AppState"\n{\n' + f' "appid" "{appid}"\n "Universe" "1"\n "name" "{title}"\n'
|
||||
minimal = ('"AppState"\n{\n' + f' "appid" "{appid}"\n "Universe" "1"\n "name" "{title}"\n'
|
||||
+ f' "StateFlags" "4"\n "installdir" "{name}"\n' + '}\n')
|
||||
legacy = content.replace(' "Universe" "1"\n', '')
|
||||
legacy = minimal.replace(' "Universe" "1"\n', '')
|
||||
build = installed_build(source, appid, name)
|
||||
if build is None:
|
||||
content = minimal
|
||||
elif build.lstrip().startswith('"AppState"'):
|
||||
content = build
|
||||
else:
|
||||
content = minimal[:-2] + ' "InstalledDepots"\n {\n' + build + ' }\n}\n'
|
||||
manifest = steamapps / f"appmanifest_{appid}.acf"
|
||||
for root in [Path(steam_root), Path("/mnt/bannerlator-sd")]:
|
||||
if target.is_symlink() and os.readlink(target) != str(source) and os.readlink(target) == legacy_path(source):
|
||||
relink = target.with_name(name + ".droiddeck")
|
||||
relink.unlink(missing_ok=True)
|
||||
relink.symlink_to(source, target_is_directory=True)
|
||||
os.replace(relink, target)
|
||||
for root in [Path(steam_root), Path(LIBRARY)]:
|
||||
existing = root / "steamapps" / manifest.name
|
||||
if existing.is_file():
|
||||
if (existing == manifest and source.is_dir() and target.is_symlink()
|
||||
and os.readlink(target) == str(source)
|
||||
and existing.read_text() in (legacy, legacy.replace('"StateFlags" "4"', '"StateFlags" "2"'))):
|
||||
and existing.read_text() != content
|
||||
and (existing.read_text() in (minimal, legacy, legacy.replace('"StateFlags" "4"', '"StateFlags" "2"'))
|
||||
or (build is not None and update_not_started(existing.read_text(), steamapps, appid, name)))):
|
||||
temp = manifest.with_suffix(".droiddeck")
|
||||
temp.write_text(content)
|
||||
os.replace(temp, manifest)
|
||||
@@ -256,11 +344,13 @@ def route(steam_root, acct, games):
|
||||
owned, candidates, sources = {}, {}, {}
|
||||
shortcuts, routes = [], {}
|
||||
for game in games:
|
||||
appid = candidates.get(game.get("folder"))
|
||||
folder = game.get("folder", "")
|
||||
appid = candidates.get(folder, candidates.get(legacy_path(folder)))
|
||||
stamp = source_stamp(game)
|
||||
recorded = sources.get(folder, sources.get(legacy_path(folder)))
|
||||
confirmed = (isinstance(appid, int) and 0 < appid < 0x80000000
|
||||
and owned.get(str(appid)) is True and stamp is not None
|
||||
and sources.get(game.get("folder")) == stamp)
|
||||
and recorded in (stamp, [stamp[0], legacy_path(stamp[1])] + stamp[2:]))
|
||||
if confirmed:
|
||||
try:
|
||||
if seed_install(steam_root, game, appid):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/python3
|
||||
# Registers the card the app installs to (bound at /mnt/bannerlator-sd) as a library folder of the
|
||||
# Registers the card the app installs to (bound at /mnt/droiddeck-sd) as a library folder of the
|
||||
# native Steam client, so they show as installed there instead of being downloaded a second time.
|
||||
#
|
||||
# bannerlator-steam-library <steam root>
|
||||
@@ -14,7 +14,7 @@ import sys
|
||||
# The app binds the storage the user chose (Steam cog -> Game storage) at this path and names it
|
||||
# in BL_LIBRARY_LABEL; nothing bound = internal only, and the entry is removed so the client does
|
||||
# not keep offering a place that is not there.
|
||||
LIBRARIES = (("/mnt/bannerlator-sd", os.environ.get("BL_LIBRARY_LABEL", "SD Card")),)
|
||||
LIBRARIES = (("/mnt/droiddeck-sd", os.environ.get("BL_LIBRARY_LABEL", "SD Card")),)
|
||||
# The client calls its own library "Local Drive (/)", which says nothing about where that is.
|
||||
# It is the phone's internal storage, so say so.
|
||||
MAIN_LABEL = "Internal Storage"
|
||||
@@ -66,6 +66,26 @@ def register(steam_root, library, label):
|
||||
|
||||
|
||||
RETIRED = ("/mnt/bannerlator",)
|
||||
RENAMED = (("/mnt/bannerlator-sd", "/mnt/droiddeck-sd"),)
|
||||
|
||||
|
||||
def rename(steam_root, old, new):
|
||||
"""Moves a library registered under an earlier mount point to the current one, keeping its
|
||||
entry (content id, app sizes) rather than registering it anew."""
|
||||
path = os.path.join(steam_root, "steamapps", "libraryfolders.vdf")
|
||||
if not os.path.isfile(path):
|
||||
return
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
text = f.read()
|
||||
old_path = re.compile(r'("path"\s+")%s(")' % re.escape(old))
|
||||
if not old_path.search(text):
|
||||
return
|
||||
if re.search(r'"path"\s+"%s"' % re.escape(new), text):
|
||||
forget(steam_root, old)
|
||||
return
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(old_path.sub(lambda m: m.group(1) + new + m.group(2), text))
|
||||
print("bannerlator-steam-library: moved %s to %s" % (old, new))
|
||||
|
||||
|
||||
def forget(steam_root, library):
|
||||
@@ -152,6 +172,8 @@ def main():
|
||||
steam_root = sys.argv[1]
|
||||
for library in RETIRED:
|
||||
forget(steam_root, library)
|
||||
for old, new in RENAMED:
|
||||
rename(steam_root, old, new)
|
||||
relabel(steam_root, steam_root, MAIN_LABEL)
|
||||
for library, label in LIBRARIES:
|
||||
if os.path.isdir(os.path.join(library, "steamapps")):
|
||||
|
||||
@@ -97,7 +97,7 @@ def write(obj):
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def shortcut(game):
|
||||
def shortcut(game, launch_options=""):
|
||||
appid = int(game["appid"]) & 0xFFFFFFFF
|
||||
return {
|
||||
"appid": struct.unpack("<i", struct.pack("<I", appid))[0],
|
||||
@@ -106,7 +106,7 @@ def shortcut(game):
|
||||
"StartDir": '"%s"' % game["dir"],
|
||||
"icon": (game.get("art") or {}).get("icon", "") or "",
|
||||
"ShortcutPath": "",
|
||||
"LaunchOptions": "",
|
||||
"LaunchOptions": launch_options,
|
||||
"IsHidden": 0,
|
||||
"AllowDesktopConfig": 1,
|
||||
"AllowOverlay": 1,
|
||||
@@ -208,8 +208,22 @@ def main():
|
||||
routing = importlib.util.module_from_spec(spec)
|
||||
loader.exec_module(routing)
|
||||
games, routes = routing.route(steam_root, acct, games)
|
||||
# Steam saves Big Picture's per-shortcut launch options in shortcuts.vdf. Keep them when
|
||||
# refreshing our entries, keyed by the appid that stays stable across session starts.
|
||||
managed = {
|
||||
v.get("appid"): v for v in existing.values()
|
||||
if isinstance(v, dict) and TAG in (v.get("tags") or {}).values()
|
||||
}
|
||||
kept = [v for v in existing.values() if isinstance(v, dict) and TAG not in (v.get("tags") or {}).values()]
|
||||
ours = [shortcut(g) for g in games if g.get("exe") and g.get("name")]
|
||||
ours = []
|
||||
for game in games:
|
||||
if not game.get("exe") or not game.get("name"):
|
||||
continue
|
||||
entry = shortcut(game)
|
||||
previous = managed.get(entry["appid"])
|
||||
if previous and isinstance(previous.get("LaunchOptions"), str):
|
||||
entry["LaunchOptions"] = previous["LaunchOptions"]
|
||||
ours.append(entry)
|
||||
entries = {str(i): v for i, v in enumerate(kept + ours)}
|
||||
tmp = path + ".bannerlator"
|
||||
with open(tmp, "wb") as f:
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
FROM menci/archlinuxarm:base-devel
|
||||
|
||||
# Pacman 7's Landlock sandbox cannot start in this Docker kernel. Package builds still run as the
|
||||
# container user; disable only the unavailable sandbox paths for the dependency-install layer.
|
||||
RUN sed -i \
|
||||
's/^[[:space:]]*#DownloadUser.*/DownloadUser =/; s/^#DisableSandboxFilesystem/DisableSandboxFilesystem/; s/^#DisableSandboxSyscalls/DisableSandboxSyscalls/' \
|
||||
/etc/pacman.conf \
|
||||
&& pacman -Syu --noconfirm --needed \
|
||||
base-devel cmake extra-cmake-modules git ninja pkgconf \
|
||||
plasma-mobile plasma-wayland-protocols vulkan-headers \
|
||||
&& pacman -Scc --noconfirm
|
||||
|
||||
WORKDIR /src
|
||||
@@ -0,0 +1,17 @@
|
||||
# Plasma Mobile 6.7.5 runtime backports
|
||||
|
||||
The Thor root installs Plasma Mobile 6.7.5. The app build backports KDE's
|
||||
[`Use effect caching` change](https://invent.kde.org/plasma/plasma-mobile/-/commit/73c5b4fd2815dc5d845c09cf578f60a9af3e708b)
|
||||
to fix the mobile task switcher state, and removes Folio's requirement for a
|
||||
shared KWayland client connection before it queries installed applications.
|
||||
|
||||
`tools/build_local.sh` stages the checked-in ARM64 modules under the generated
|
||||
`app/src/main/assets/linuxfs` tree. To rebuild those modules, run
|
||||
`tools/plasma-mobile/rebuild.sh`; it builds the affected targets in the Arch
|
||||
Linux ARM environment described by `Dockerfile` and refreshes `prebuilt/`.
|
||||
This keeps the changes isolated to the Plasma runtime; the LXQt/Steam root is
|
||||
not modified. The module sources and patches target tag `v6.7.5`.
|
||||
|
||||
The app-catalog patch currently logs whether Folio receives a KWayland
|
||||
connection and how many KService entries it finds. Those diagnostics are for
|
||||
Thor dogfooding and can be removed after the empty-drawer cause is confirmed.
|
||||
Executable
+46
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
repo_root=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
plasma_version=6.7.5
|
||||
source_dir="${TMPDIR:-/tmp}/plasma-mobile-${plasma_version}"
|
||||
build_dir="${TMPDIR:-/tmp}/plasma-mobile-build-${plasma_version}"
|
||||
asset_root="${repo_root}/app/src/main/assets/linuxfs"
|
||||
|
||||
installed_version=$(pacman -Q plasma-mobile | awk '{print $2}')
|
||||
case "${installed_version}" in
|
||||
"${plasma_version}"-*) ;;
|
||||
*)
|
||||
echo "Expected plasma-mobile ${plasma_version}, found ${installed_version}." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
rm -rf -- "${source_dir}" "${build_dir}"
|
||||
git clone --quiet --depth 1 --branch "v${plasma_version}" \
|
||||
https://invent.kde.org/plasma/plasma-mobile.git "${source_dir}"
|
||||
git -C "${source_dir}" apply --check \
|
||||
"${repo_root}/tools/plasma-mobile/patches/0001-mobile-task-switcher.patch" \
|
||||
"${repo_root}/tools/plasma-mobile/patches/0002-folio-app-model.patch"
|
||||
git -C "${source_dir}" apply \
|
||||
"${repo_root}/tools/plasma-mobile/patches/0001-mobile-task-switcher.patch" \
|
||||
"${repo_root}/tools/plasma-mobile/patches/0002-folio-app-model.patch"
|
||||
|
||||
cmake -S "${source_dir}" -B "${build_dir}" -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
|
||||
cmake --build "${build_dir}" --parallel "${DROIDDECK_PLASMA_BUILD_JOBS:-4}" \
|
||||
--target mobiletaskswitcherplugin org.kde.plasma.mobile.homescreen.folio
|
||||
|
||||
install -Dm644 "${build_dir}/bin/plasma/applets/org.kde.plasma.mobile.homescreen.folio.so" \
|
||||
"${asset_root}/usr/lib/qt6/plugins/plasma/applets/org.kde.plasma.mobile.homescreen.folio.so"
|
||||
install -Dm644 "${build_dir}/kwin/mobiletaskswitcher/plugin/libmobiletaskswitcherplugin.so" \
|
||||
"${asset_root}/usr/lib/qt6/qml/org/kde/plasma/private/mobileshell/taskswitcherplugin/libmobiletaskswitcherplugin.so"
|
||||
install -Dm644 "${source_dir}/kwin/mobiletaskswitcher/package/contents/ui/FlickContainer.qml" \
|
||||
"${asset_root}/usr/share/kwin/effects/mobiletaskswitcher/contents/ui/FlickContainer.qml"
|
||||
install -Dm644 "${source_dir}/kwin/mobiletaskswitcher/package/contents/ui/TaskSwitcher.qml" \
|
||||
"${asset_root}/usr/share/kwin/effects/mobiletaskswitcher/contents/ui/TaskSwitcher.qml"
|
||||
strip --strip-unneeded \
|
||||
"${asset_root}/usr/lib/qt6/plugins/plasma/applets/org.kde.plasma.mobile.homescreen.folio.so" \
|
||||
"${asset_root}/usr/lib/qt6/qml/org/kde/plasma/private/mobileshell/taskswitcherplugin/libmobiletaskswitcherplugin.so"
|
||||
|
||||
echo "Built Plasma Mobile ${plasma_version} app-catalog and task-switcher backports."
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
repo_root=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
source_dir="${repo_root}/tools/plasma-mobile/prebuilt"
|
||||
asset_root="${repo_root}/app/src/main/assets/linuxfs"
|
||||
|
||||
install -Dm644 "${source_dir}/org.kde.plasma.mobile.homescreen.folio.so" \
|
||||
"${asset_root}/usr/lib/qt6/plugins/plasma/applets/org.kde.plasma.mobile.homescreen.folio.so"
|
||||
install -Dm644 "${source_dir}/libmobiletaskswitcherplugin.so" \
|
||||
"${asset_root}/usr/lib/qt6/qml/org/kde/plasma/private/mobileshell/taskswitcherplugin/libmobiletaskswitcherplugin.so"
|
||||
install -Dm644 "${source_dir}/FlickContainer.qml" \
|
||||
"${asset_root}/usr/share/kwin/effects/mobiletaskswitcher/contents/ui/FlickContainer.qml"
|
||||
install -Dm644 "${source_dir}/TaskSwitcher.qml" \
|
||||
"${asset_root}/usr/share/kwin/effects/mobiletaskswitcher/contents/ui/TaskSwitcher.qml"
|
||||
|
||||
echo "Staged the Plasma Mobile 6.7.5 ARM64 backports. Run tools/plasma-mobile/rebuild.sh to rebuild them."
|
||||
@@ -0,0 +1,278 @@
|
||||
diff --git a/kwin/mobiletaskswitcher/package/contents/ui/FlickContainer.qml b/kwin/mobiletaskswitcher/package/contents/ui/FlickContainer.qml
|
||||
index 8f89960..8a80991 100644
|
||||
--- a/kwin/mobiletaskswitcher/package/contents/ui/FlickContainer.qml
|
||||
+++ b/kwin/mobiletaskswitcher/package/contents/ui/FlickContainer.qml
|
||||
@@ -25,10 +25,16 @@ Flickable {
|
||||
|
||||
readonly property real startContentX: (taskSwitcherHelpers.taskWidth + taskSwitcherHelpers.taskSpacing) * tasksCount
|
||||
property bool movingRight: false // TODO needed for flickable not flicking workaround
|
||||
+ property bool resettingPosition: false
|
||||
|
||||
// update position from horizontal flickable movement
|
||||
property real oldContentX
|
||||
onContentXChanged: {
|
||||
+ if (resettingPosition) {
|
||||
+ oldContentX = contentX;
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
// disable if animations are running to prevent bugs
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
|
||||
@@ -43,6 +49,8 @@ Flickable {
|
||||
|
||||
onMovementStarted: {
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
+ oldContentX = contentX;
|
||||
+ movingRight = false;
|
||||
taskSwitcherHelpers.cancelAnimations();
|
||||
}
|
||||
onMovementEnded: {
|
||||
@@ -63,6 +71,8 @@ Flickable {
|
||||
onDraggingChanged: {
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
if (dragging) {
|
||||
+ oldContentX = contentX;
|
||||
+ movingRight = false;
|
||||
taskSwitcherHelpers.cancelAnimations();
|
||||
} else {
|
||||
resetPosition();
|
||||
@@ -70,7 +80,14 @@ Flickable {
|
||||
}
|
||||
|
||||
function resetPosition(): void {
|
||||
+ resettingPosition = true;
|
||||
+ cancelFlick();
|
||||
oldContentX = startContentX;
|
||||
contentX = startContentX;
|
||||
+ movingRight = false;
|
||||
+ Qt.callLater(() => {
|
||||
+ oldContentX = contentX;
|
||||
+ resettingPosition = false;
|
||||
+ });
|
||||
}
|
||||
}
|
||||
diff --git a/kwin/mobiletaskswitcher/package/contents/ui/TaskSwitcher.qml b/kwin/mobiletaskswitcher/package/contents/ui/TaskSwitcher.qml
|
||||
index e614639..ca3908e 100644
|
||||
--- a/kwin/mobiletaskswitcher/package/contents/ui/TaskSwitcher.qml
|
||||
+++ b/kwin/mobiletaskswitcher/package/contents/ui/TaskSwitcher.qml
|
||||
@@ -85,11 +85,12 @@ FocusScope {
|
||||
|
||||
Keys.onEscapePressed: hide();
|
||||
|
||||
- Component.onCompleted: {
|
||||
- initialSetup();
|
||||
- }
|
||||
-
|
||||
function initialSetup(): void {
|
||||
+ closeAnim.stop();
|
||||
+ container.opacity = 1;
|
||||
+ closeAllButton.closeRequested = false;
|
||||
+ oldTasksCount = tasksCount;
|
||||
+
|
||||
taskSwitcherHelpers.cancelAnimations();
|
||||
state.updateWasInActiveTask(KWinComponents.Workspace.activeWindow);
|
||||
|
||||
@@ -102,12 +103,14 @@ FocusScope {
|
||||
taskSwitcherHelpers.hasVibrated = false;
|
||||
|
||||
taskSwitcherHelpers.closingFactor = 1;
|
||||
+ taskSwitcherHelpers.closingScalingFactor = 1;
|
||||
|
||||
taskSwitcherHelpers.taskSwitchCanLaunch = false;
|
||||
taskSwitchCanLaunchTimer.restart()
|
||||
|
||||
taskList.taskOffsetEasing = Easing.InOutQuart;
|
||||
taskList.homeTouchPositionX = 0;
|
||||
+ flickable.resetPosition();
|
||||
|
||||
backgroundColorOpacityAn.enabled = false;
|
||||
backgroundColorOpacity = state.wasInActiveTask ? 1 : 0;
|
||||
@@ -161,6 +164,11 @@ FocusScope {
|
||||
Connections {
|
||||
target: root.state
|
||||
|
||||
+ function onActivated(): void {
|
||||
+ root.tasksModel.refresh();
|
||||
+ root.initialSetup();
|
||||
+ }
|
||||
+
|
||||
// task scrub mode allows scrubbing through a number of tasks with a mostly horizontal motion
|
||||
function taskScrubMode(): void {
|
||||
taskList.setTaskOffsetValue(0, false, Easing.OutQuart);
|
||||
@@ -827,4 +835,3 @@ FocusScope {
|
||||
}
|
||||
}
|
||||
}
|
||||
-
|
||||
diff --git a/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.cpp b/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.cpp
|
||||
index 5c2f376..e8baaff 100644
|
||||
--- a/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.cpp
|
||||
+++ b/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.cpp
|
||||
@@ -35,8 +35,11 @@ void MobileTaskSwitcherState::init(KWin::QuickSceneEffect *parent)
|
||||
m_border = new EffectTouchBorder{m_effectState};
|
||||
m_taskModel = new TaskModel{parent};
|
||||
m_effect = parent;
|
||||
+ m_effect->setViewCachingEnabled(true);
|
||||
|
||||
// Connect signals
|
||||
+ connect(m_effect, &QuickSceneEffect::activated, this, &MobileTaskSwitcherState::activated);
|
||||
+ connect(m_effect, &QuickSceneEffect::deactivated, this, &MobileTaskSwitcherState::deactivated);
|
||||
connect(this, &MobileTaskSwitcherState::gestureEnabledChanged, this, &MobileTaskSwitcherState::refreshBorders);
|
||||
connect(m_border, &EffectTouchBorder::touchPositionChanged, this, &MobileTaskSwitcherState::processTouchPositionChanged);
|
||||
connect(this, &MobileTaskSwitcherState::gestureInProgressChanged, this, [this]() {
|
||||
@@ -223,13 +226,10 @@ void MobileTaskSwitcherState::restartDoubleClickTimer()
|
||||
|
||||
void MobileTaskSwitcherState::calculateFilteredVelocity(qreal primaryDelta, qreal orthogonalDelta)
|
||||
{
|
||||
- static qreal prevPrimaryDelta = 0;
|
||||
- static qreal prevOrthogonalDelta = 0;
|
||||
-
|
||||
qint64 frameTime = 0;
|
||||
if (!m_frameTimer.isValid()) {
|
||||
- prevPrimaryDelta = 0;
|
||||
- prevOrthogonalDelta = 0;
|
||||
+ m_previousPrimaryDelta = primaryDelta;
|
||||
+ m_previousOrthogonalDelta = orthogonalDelta;
|
||||
m_frameTimer.start();
|
||||
return;
|
||||
}
|
||||
@@ -239,10 +239,10 @@ void MobileTaskSwitcherState::calculateFilteredVelocity(qreal primaryDelta, qrea
|
||||
return;
|
||||
}
|
||||
|
||||
- qreal framePrimaryDelta = primaryDelta - prevPrimaryDelta;
|
||||
- qreal frameOrthogonalDelta = orthogonalDelta - prevOrthogonalDelta;
|
||||
- prevPrimaryDelta = primaryDelta;
|
||||
- prevOrthogonalDelta = orthogonalDelta;
|
||||
+ qreal framePrimaryDelta = primaryDelta - m_previousPrimaryDelta;
|
||||
+ qreal frameOrthogonalDelta = orthogonalDelta - m_previousOrthogonalDelta;
|
||||
+ m_previousPrimaryDelta = primaryDelta;
|
||||
+ m_previousOrthogonalDelta = orthogonalDelta;
|
||||
|
||||
// Implements an exponentially weighted moving average (EWMA) filter (= exponential smoothing)
|
||||
// Smoothing factor is approximated each event to achieve a chosen filter time constant
|
||||
@@ -253,6 +253,24 @@ void MobileTaskSwitcherState::calculateFilteredVelocity(qreal primaryDelta, qrea
|
||||
Q_EMIT velocityChanged();
|
||||
}
|
||||
|
||||
+void MobileTaskSwitcherState::clearVelocityFilter()
|
||||
+{
|
||||
+ m_frameTimer.invalidate();
|
||||
+ m_previousPrimaryDelta = 0;
|
||||
+ m_previousOrthogonalDelta = 0;
|
||||
+ m_xVelocity = 0;
|
||||
+ m_yVelocity = 0;
|
||||
+ m_totalSquaredVelocity = 0;
|
||||
+ Q_EMIT velocityChanged();
|
||||
+}
|
||||
+
|
||||
+void MobileTaskSwitcherState::resetGestureState()
|
||||
+{
|
||||
+ m_touchXPosition = 0;
|
||||
+ m_touchYPosition = 0;
|
||||
+ clearVelocityFilter();
|
||||
+}
|
||||
+
|
||||
void MobileTaskSwitcherState::processTouchPositionChanged(qreal primaryDelta, qreal orthogonalDelta)
|
||||
{
|
||||
calculateFilteredVelocity(primaryDelta, orthogonalDelta);
|
||||
@@ -289,6 +307,7 @@ void MobileTaskSwitcherState::activate()
|
||||
return;
|
||||
}
|
||||
|
||||
+ resetGestureState();
|
||||
m_effectState->setInProgress(false);
|
||||
invokeEffect();
|
||||
}
|
||||
@@ -339,6 +358,8 @@ void MobileTaskSwitcherState::setDBusState(bool active)
|
||||
|
||||
void MobileTaskSwitcherState::invokeEffect()
|
||||
{
|
||||
+ m_shutdownTimer->stop();
|
||||
+ resetGestureState();
|
||||
setInitialTaskIndex(currentTaskIndex()); // TODO! this is only until the crashing bug is fixed and recency sorting is in
|
||||
m_effect->setRunning(true);
|
||||
setDBusState(true);
|
||||
diff --git a/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.h b/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.h
|
||||
index d85f1cc..0aae2a7 100644
|
||||
--- a/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.h
|
||||
+++ b/kwin/mobiletaskswitcher/plugin/mobiletaskswitchereffect.h
|
||||
@@ -144,6 +144,7 @@ private Q_SLOTS:
|
||||
|
||||
private:
|
||||
void invokeEffect();
|
||||
+ void resetGestureState();
|
||||
|
||||
bool m_gestureEnabled{false};
|
||||
EffectTouchBorderState *m_effectState{nullptr};
|
||||
@@ -154,8 +155,8 @@ private:
|
||||
Status m_status = Status::Inactive;
|
||||
bool m_gestureInProgress = false;
|
||||
|
||||
- int m_currentTaskIndex;
|
||||
- int m_initialTaskIndex;
|
||||
+ int m_currentTaskIndex = 0;
|
||||
+ int m_initialTaskIndex = 0;
|
||||
|
||||
void clearVelocityFilter();
|
||||
void calculateFilteredVelocity(qreal primaryPosition, qreal orthogonalPosition);
|
||||
@@ -163,22 +164,24 @@ private:
|
||||
|
||||
// velocities in (logical) pixels/msec
|
||||
QElapsedTimer m_frameTimer;
|
||||
+ qreal m_previousPrimaryDelta = 0;
|
||||
+ qreal m_previousOrthogonalDelta = 0;
|
||||
qreal m_flickVelocityThreshold = 0.5 * 0.5; // squared because total velocity is kept as a square
|
||||
qreal m_filterTimeConstant = 0.03; // time constant of velocity filter
|
||||
|
||||
- qreal m_touchXPosition;
|
||||
- qreal m_touchYPosition;
|
||||
+ qreal m_touchXPosition = 0;
|
||||
+ qreal m_touchYPosition = 0;
|
||||
qreal m_xVelocity = 0;
|
||||
qreal m_yVelocity = 0;
|
||||
// Using the square of velocity for the total (2-axis) because we just need it
|
||||
// for one threshold comparison and we skip having to calculate the square root
|
||||
- qreal m_totalSquaredVelocity;
|
||||
+ qreal m_totalSquaredVelocity = 0;
|
||||
|
||||
// Positions of the task switcher effect itself
|
||||
qreal m_xPosition = 0;
|
||||
qreal m_yPosition = 0;
|
||||
|
||||
- bool m_wasInActiveTask;
|
||||
+ bool m_wasInActiveTask = false;
|
||||
|
||||
QElapsedTimer *m_doubleClickTimer;
|
||||
qint64 getDoubleClickInterval() const
|
||||
diff --git a/kwin/mobiletaskswitcher/plugin/taskfiltermodel.cpp b/kwin/mobiletaskswitcher/plugin/taskfiltermodel.cpp
|
||||
index 59e1f48..6e04c86 100644
|
||||
--- a/kwin/mobiletaskswitcher/plugin/taskfiltermodel.cpp
|
||||
+++ b/kwin/mobiletaskswitcher/plugin/taskfiltermodel.cpp
|
||||
@@ -43,6 +43,12 @@ void TaskFilterModel::setWindowModel(TaskModel *taskModel)
|
||||
sort(0);
|
||||
}
|
||||
|
||||
+void TaskFilterModel::refresh()
|
||||
+{
|
||||
+ invalidateFilter();
|
||||
+ sort(0);
|
||||
+}
|
||||
+
|
||||
QString TaskFilterModel::screenName() const
|
||||
{
|
||||
return m_output ? m_output->name() : QString();
|
||||
diff --git a/kwin/mobiletaskswitcher/plugin/taskfiltermodel.h b/kwin/mobiletaskswitcher/plugin/taskfiltermodel.h
|
||||
index 87244cc..ce3688a 100644
|
||||
--- a/kwin/mobiletaskswitcher/plugin/taskfiltermodel.h
|
||||
+++ b/kwin/mobiletaskswitcher/plugin/taskfiltermodel.h
|
||||
@@ -30,6 +30,8 @@ public:
|
||||
TaskModel *windowModel() const;
|
||||
void setWindowModel(KWin::TaskModel *taskModel);
|
||||
|
||||
+ Q_INVOKABLE void refresh();
|
||||
+
|
||||
QString screenName() const;
|
||||
void setScreenName(const QString &screenName);
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
diff --git a/containments/homescreens/folio/applicationlistmodel.cpp b/containments/homescreens/folio/applicationlistmodel.cpp
|
||||
--- a/containments/homescreens/folio/applicationlistmodel.cpp
|
||||
+++ b/containments/homescreens/folio/applicationlistmodel.cpp
|
||||
@@ -35,9 +35,9 @@ ApplicationListModel::ApplicationListModel(HomeScreen *parent)
|
||||
|
||||
// initialize wayland window checking
|
||||
KWayland::Client::ConnectionThread *connection = KWayland::Client::ConnectionThread::fromApplication(this);
|
||||
- if (!connection) {
|
||||
- return;
|
||||
- }
|
||||
-
|
||||
+ qDebug() << "Folio app model Wayland client connection:" << (connection != nullptr);
|
||||
+ // Listing and launching desktop entries does not need a Wayland client connection. In an
|
||||
+ // embedded compositor session KWayland may not expose its shared connection to this model;
|
||||
+ // still populate the catalog so the drawer is usable.
|
||||
load();
|
||||
}
|
||||
@@ -93,6 +93,7 @@ void ApplicationListModel::load()
|
||||
}
|
||||
|
||||
const KService::List currentApps = queryApplications();
|
||||
+ qDebug() << "Folio application service query returned" << currentApps.size() << "entries";
|
||||
QList<KService::Ptr> toInsert;
|
||||
|
||||
for (const KService::Ptr &service : currentApps) {
|
||||
diff --git a/containments/homescreens/folio/qml/AppDrawer.qml b/containments/homescreens/folio/qml/AppDrawer.qml
|
||||
index a389b20..5b1840a 100644
|
||||
--- a/containments/homescreens/folio/qml/AppDrawer.qml
|
||||
+++ b/containments/homescreens/folio/qml/AppDrawer.qml
|
||||
@@ -87,7 +87,7 @@ Item {
|
||||
anchors.left: parent.left
|
||||
anchors.right: parent.right
|
||||
anchors.bottom: parent.bottom
|
||||
- opacity: 0 // we display with the opacity gradient below
|
||||
+ opacity: 1 // Render app tiles directly with Qt's software Quick backend.
|
||||
headerHeight: root.headerHeight
|
||||
|
||||
// Keyboard navigation
|
||||
@@ -104,10 +104,5 @@ Item {
|
||||
}
|
||||
}
|
||||
|
||||
- // Opacity gradient at grid edges
|
||||
- MobileShell.FlickableOpacityGradient {
|
||||
- anchors.fill: appDrawerGrid
|
||||
- flickable: appDrawerGrid
|
||||
- }
|
||||
}
|
||||
}
|
||||
diff --git a/containments/homescreens/folio/qml/AppDrawerGrid.qml b/containments/homescreens/folio/qml/AppDrawerGrid.qml
|
||||
--- a/containments/homescreens/folio/qml/AppDrawerGrid.qml
|
||||
+++ b/containments/homescreens/folio/qml/AppDrawerGrid.qml
|
||||
@@ -29,6 +29,5 @@ MobileShell.GridView {
|
||||
|
||||
cacheBuffer: cellHeight * 20
|
||||
reuseItems: true
|
||||
- layer.enabled: true
|
||||
|
||||
keyNavigationEnabled: true
|
||||
highlightMoveDuration: 0
|
||||
@@ -0,0 +1,93 @@
|
||||
// SPDX-FileCopyrightText: 2021-2023 Devin Lin <devin@kde.org>
|
||||
// SPDX-FileCopyrightText: 2025 Luis Büchi <luis.buechi@kdemail.net>
|
||||
// SPDX-License-Identifier: LGPL-2.0-or-later
|
||||
|
||||
pragma ComponentBehavior: Bound
|
||||
|
||||
import QtQuick
|
||||
|
||||
Flickable {
|
||||
// TODO flickable is busted, it refuses to actually do any flicks with touch input, only works with mouse
|
||||
// we work around this somewhat by snapping to the nearest task in which direction it was moving when letting go
|
||||
// no matter how far away we are (and no matter how fast we go)
|
||||
id: root
|
||||
|
||||
required property var taskSwitcherState
|
||||
required property var taskSwitcherHelpers
|
||||
required property int tasksCount
|
||||
|
||||
// we use flickable solely for capturing flicks, not positioning elements
|
||||
// the horizontal distance we can swipe in one flick
|
||||
contentWidth: (taskSwitcherHelpers.taskWidth + taskSwitcherHelpers.taskSpacing) * tasksCount
|
||||
contentHeight: height
|
||||
contentX: startContentX
|
||||
|
||||
|
||||
readonly property real startContentX: (taskSwitcherHelpers.taskWidth + taskSwitcherHelpers.taskSpacing) * tasksCount
|
||||
property bool movingRight: false // TODO needed for flickable not flicking workaround
|
||||
property bool resettingPosition: false
|
||||
|
||||
// update position from horizontal flickable movement
|
||||
property real oldContentX
|
||||
onContentXChanged: {
|
||||
if (resettingPosition) {
|
||||
oldContentX = contentX;
|
||||
return;
|
||||
}
|
||||
|
||||
// disable if animations are running to prevent bugs
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
|
||||
if (moving) {
|
||||
// TODO whenever flicking actually works this should probably be swapped with
|
||||
// a minimum velocity after which it should snap to the nearest task
|
||||
taskSwitcherState.xPosition += contentX - oldContentX;
|
||||
}
|
||||
movingRight = contentX < oldContentX;
|
||||
oldContentX = contentX;
|
||||
}
|
||||
|
||||
onMovementStarted: {
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
oldContentX = contentX;
|
||||
movingRight = false;
|
||||
taskSwitcherHelpers.cancelAnimations();
|
||||
}
|
||||
onMovementEnded: {
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
taskSwitcherHelpers.snapToNearestTaskWorkaround(movingRight);
|
||||
resetPosition();
|
||||
}
|
||||
|
||||
onFlickStarted: {
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
root.cancelFlick();
|
||||
}
|
||||
onFlickEnded: {
|
||||
// taskSwitcherHelpers.snapToNearestTaskWorkaround(movingRight);
|
||||
// resetPosition();
|
||||
}
|
||||
|
||||
onDraggingChanged: {
|
||||
if (taskSwitcherHelpers.currentlyBeingClosed) {return}
|
||||
if (dragging) {
|
||||
oldContentX = contentX;
|
||||
movingRight = false;
|
||||
taskSwitcherHelpers.cancelAnimations();
|
||||
} else {
|
||||
resetPosition();
|
||||
}
|
||||
}
|
||||
|
||||
function resetPosition(): void {
|
||||
resettingPosition = true;
|
||||
cancelFlick();
|
||||
oldContentX = startContentX;
|
||||
contentX = startContentX;
|
||||
movingRight = false;
|
||||
Qt.callLater(() => {
|
||||
oldContentX = contentX;
|
||||
resettingPosition = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,837 @@
|
||||
// SPDX-FileCopyrightText: 2015 Marco Martin <notmart@gmail.com>
|
||||
// SPDX-FileCopyrightText: 2021-2024 Devin Lin <devin@kde.org>
|
||||
// SPDX-FileCopyrightText: 2024-2025 Luis Büchi <luis.buechi@kdemail.net>
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
pragma ComponentBehavior: Bound
|
||||
|
||||
import QtQuick
|
||||
import QtQuick.Layouts
|
||||
|
||||
import org.kde.kirigami as Kirigami
|
||||
import org.kde.plasma.core as PlasmaCore
|
||||
import org.kde.plasma.components 3.0 as PlasmaComponents
|
||||
import org.kde.plasma.private.mobileshell as MobileShell
|
||||
import org.kde.plasma.private.mobileshell.state as MobileShellState
|
||||
import org.kde.plasma.private.mobileshell.shellsettingsplugin as ShellSettings
|
||||
import org.kde.plasma.private.mobileshell.taskswitcherplugin as TaskSwitcherPlugin
|
||||
|
||||
import org.kde.kwin 3.0 as KWinComponents
|
||||
import org.kde.kwin.private.effects 1.0
|
||||
import org.kde.kitemmodels
|
||||
|
||||
|
||||
/**
|
||||
* Component that provides a task switcher.
|
||||
*/
|
||||
FocusScope {
|
||||
id: root
|
||||
focus: true
|
||||
|
||||
property TaskSwitcherPlugin.MobileTaskSwitcherState state
|
||||
readonly property QtObject effect: KWinComponents.SceneView.effect
|
||||
readonly property QtObject targetScreen: KWinComponents.SceneView.screen
|
||||
|
||||
readonly property real navBottomMargin: MobileShell.Constants.navigationPanelOnSide(width, height) ? 0 : MobileShell.Constants.navigationPanelThickness
|
||||
readonly property real navRightMargin: MobileShell.Constants.navigationPanelOnSide(width, height) ? MobileShell.Constants.navigationPanelThickness : 0
|
||||
readonly property real topMargin: ShellSettings.Settings.autoHidePanelsEnabled ? 0 : MobileShell.Constants.topPanelHeight
|
||||
readonly property real bottomMargin: ShellSettings.Settings.autoHidePanelsEnabled ? 0 : navBottomMargin
|
||||
readonly property real leftMargin: 0
|
||||
readonly property real rightMargin: ShellSettings.Settings.autoHidePanelsEnabled ? 0 : navRightMargin
|
||||
|
||||
property var taskSwitcherHelpers: TaskSwitcherHelpers {
|
||||
taskSwitcher: root
|
||||
taskList: taskList
|
||||
}
|
||||
|
||||
MobileShell.HapticsEffect {
|
||||
id: haptics
|
||||
}
|
||||
|
||||
property TaskSwitcherPlugin.TaskFilterModel tasksModel: TaskSwitcherPlugin.TaskFilterModel {
|
||||
screenName: root.targetScreen.name
|
||||
windowModel: root.state.taskModel
|
||||
}
|
||||
|
||||
readonly property int tasksCount: taskList.count
|
||||
|
||||
// keep track of task list events
|
||||
property int oldTasksCount: tasksCount
|
||||
onTasksCountChanged: {
|
||||
// we need to subtract 1 from the current index when the closed task index is smaller
|
||||
// this is because this part of the list has been shifted down by 1 when the closed task was removed.
|
||||
if (taskSwitcherHelpers.lastClosedTask < state.currentTaskIndex) {
|
||||
state.currentTaskIndex -= 1;
|
||||
|
||||
// animated at the same speed as the task x position in the TaskList so that the task appears not to move from the perspective of the user.
|
||||
taskSwitcherHelpers.animateGoToTaskIndex(state.currentTaskIndex, Kirigami.Units.longDuration, Easing.InOutQuad);
|
||||
taskSwitcherHelpers.lastClosedTask = -1;
|
||||
}
|
||||
|
||||
if (tasksCount === 0 && oldTasksCount !== 0) {
|
||||
hide();
|
||||
} else if (tasksCount < oldTasksCount) {
|
||||
if (state.currentTaskIndex < 0) {
|
||||
// if the user is on the first task, and it is closed, scroll right
|
||||
taskSwitcherHelpers.animateGoToTaskIndex(0, Kirigami.Units.longDuration);
|
||||
} else if (state.currentTaskIndex >= tasksCount) {
|
||||
// if the user is on the last task, and it is closed, scroll left
|
||||
taskSwitcherHelpers.animateGoToTaskIndex(tasksCount - 1, Kirigami.Units.longDuration);
|
||||
}
|
||||
}
|
||||
|
||||
oldTasksCount = tasksCount;
|
||||
}
|
||||
|
||||
Keys.onEscapePressed: hide();
|
||||
|
||||
function initialSetup(): void {
|
||||
closeAnim.stop();
|
||||
container.opacity = 1;
|
||||
closeAllButton.closeRequested = false;
|
||||
oldTasksCount = tasksCount;
|
||||
|
||||
taskSwitcherHelpers.cancelAnimations();
|
||||
state.updateWasInActiveTask(KWinComponents.Workspace.activeWindow);
|
||||
|
||||
// ensure the task drawer is not opened and reset values to defaults
|
||||
taskSwitcherHelpers.reachedHeightThreshold = false;
|
||||
taskSwitcherHelpers.gestureState = TaskSwitcherHelpers.GestureStates.Undecided;
|
||||
taskSwitcherHelpers.isInTaskScrubMode = false;
|
||||
taskSwitcherHelpers.inLastFrame = false;
|
||||
|
||||
taskSwitcherHelpers.hasVibrated = false;
|
||||
|
||||
taskSwitcherHelpers.closingFactor = 1;
|
||||
taskSwitcherHelpers.closingScalingFactor = 1;
|
||||
|
||||
taskSwitcherHelpers.taskSwitchCanLaunch = false;
|
||||
taskSwitchCanLaunchTimer.restart()
|
||||
|
||||
taskList.taskOffsetEasing = Easing.InOutQuart;
|
||||
taskList.homeTouchPositionX = 0;
|
||||
flickable.resetPosition();
|
||||
|
||||
backgroundColorOpacityAn.enabled = false;
|
||||
backgroundColorOpacity = state.wasInActiveTask ? 1 : 0;
|
||||
backgroundColorOpacityAn.enabled = true;
|
||||
|
||||
// reset the offset to have the task drawer off screen
|
||||
taskList.setTaskOffsetValue(state.wasInActiveTask ? taskSwitcherHelpers.taskOffsetValue : taskSwitcherHelpers.homeOffsetValue, true);
|
||||
|
||||
// task index from the last time using the switcher
|
||||
state.initialTaskIndex = Math.min(state.currentTaskIndex, tasksCount - 1);
|
||||
if (state.wasInActiveTask) {
|
||||
// if we were in an active task instead set initial task index to the position of that task
|
||||
state.initialTaskIndex = taskSwitcherHelpers.getTaskIndexFromWindow(KWinComponents.Workspace.activeWindow);
|
||||
} else {
|
||||
// reset the task index to the start if on home screen
|
||||
state.initialTaskIndex = 0
|
||||
}
|
||||
state.currentTaskIndex = state.initialTaskIndex
|
||||
|
||||
taskSwitcherHelpers.currentDisplayTask = state.currentTaskIndex;
|
||||
|
||||
taskSwitcherHelpers.goToTaskIndex(state.initialTaskIndex);
|
||||
taskList.minimizeAll();
|
||||
|
||||
// fully open the switcher (if this is a button press, not gesture)
|
||||
if (!state.gestureInProgress) {
|
||||
taskSwitcherHelpers.fromButton = true;
|
||||
if (state.wasInActiveTask) {
|
||||
taskList.setTaskOffsetValue(0, true);
|
||||
} else {
|
||||
taskList.setTaskOffsetValue(0);
|
||||
}
|
||||
backgroundColorOpacity = 1;
|
||||
taskSwitcherHelpers.open();
|
||||
}
|
||||
}
|
||||
|
||||
// called by c++ plugin
|
||||
function hideAnimation(): void {
|
||||
closeAnim.restart();
|
||||
}
|
||||
|
||||
function instantHide(): void {
|
||||
state.deactivate(true);
|
||||
}
|
||||
|
||||
function hide(): void {
|
||||
state.deactivate(false);
|
||||
}
|
||||
|
||||
Connections {
|
||||
target: root.state
|
||||
|
||||
function onActivated(): void {
|
||||
root.tasksModel.refresh();
|
||||
root.initialSetup();
|
||||
}
|
||||
|
||||
// task scrub mode allows scrubbing through a number of tasks with a mostly horizontal motion
|
||||
function taskScrubMode(): void {
|
||||
taskList.setTaskOffsetValue(0, false, Easing.OutQuart);
|
||||
if (!root.taskSwitcherHelpers.isInTaskScrubMode) {
|
||||
root.backgroundColorOpacity = 1;
|
||||
root.taskSwitcherHelpers.cancelAnimations();
|
||||
root.taskSwitcherHelpers.open();
|
||||
if (!root.taskSwitcherHelpers.hasVibrated) {
|
||||
// Haptic feedback when the task scrub mode engages
|
||||
haptics.buttonVibrate();
|
||||
root.taskSwitcherHelpers.hasVibrated = true;
|
||||
}
|
||||
}
|
||||
// TODO this makes sense, but makes scrub mode feel a bit weird
|
||||
// improve trigger distance logic for task scrub mode to fix
|
||||
let newTaskIndex = Math.max(0, Math.min(root.tasksCount - 1, Math.floor(root.state.touchXPosition / root.taskSwitcherHelpers.taskScrubDistance) + root.state.initialTaskIndex - (root.state.wasInActiveTask ? 0 : 1)));
|
||||
if (newTaskIndex != root.state.currentTaskIndex || !root.taskSwitcherHelpers.isInTaskScrubMode) {
|
||||
root.taskSwitcherHelpers.animateGoToTaskIndex(newTaskIndex);
|
||||
root.taskSwitcherHelpers.isInTaskScrubMode = true;
|
||||
}
|
||||
}
|
||||
|
||||
function onTouchPositionChanged(): void {
|
||||
let unmodifiedYposition = Math.abs(root.state.touchYPosition)
|
||||
if (root.taskSwitcherHelpers.isInTaskScrubMode || // once in scrub mode, let's not allow to go out, that can result in inconsistent UX
|
||||
(Math.abs(root.state.xVelocity) > Math.abs(root.state.yVelocity) * 3 && // gesture needs to be almost completely horizontal
|
||||
Math.abs(root.state.xVelocity) < 2.5 && // and not with a fast flick TODO! evaluate whether to keep this, it's kinda awkward
|
||||
Math.abs(root.state.touchXPosition) > root.taskSwitcherHelpers.taskScrubDistance * 0.95 && // and have moved far enough sideways
|
||||
unmodifiedYposition < Kirigami.Units.largeSpacing * 2 && // and be close to the screen edge
|
||||
root.tasksCount > 0 && // and there needs to be more than none task open
|
||||
!root.taskSwitcherHelpers.taskDrawerOpened // and the task drawer must not be open
|
||||
)) {
|
||||
taskScrubMode();
|
||||
} else {
|
||||
if (root.taskSwitcherHelpers.currentlyBeingClosed) {
|
||||
// if the task switch is still open but playing the close animation
|
||||
// setup some values and return to the initial setup so that the user can always navigate with no down time
|
||||
root.state.wasInActiveTask = root.taskSwitcherHelpers.openAppAnim.running ? true : false
|
||||
taskList.setTaskOffsetValue(root.state.wasInActiveTask ? root.taskSwitcherHelpers.taskOffsetValue : root.taskSwitcherHelpers.homeOffsetValue, true);
|
||||
root.state.status = !root.state.wasInActiveTask ? (root.taskSwitcherHelpers.openAppAnim.closeAnim && !root.taskSwitcherHelpers.taskDrawerWillOpen ? TaskSwitcherPlugin.MobileTaskSwitcherState.Active : TaskSwitcherPlugin.MobileTaskSwitcherState.Inactive) : TaskSwitcherPlugin.MobileTaskSwitcherState.Inactive
|
||||
root.initialSetup();
|
||||
} else if (root.taskSwitcherHelpers.openAnim.running) {
|
||||
root.taskSwitcherHelpers.cancelAnimations();
|
||||
root.state.status = root.taskSwitcherHelpers.stateClass.Active;
|
||||
}
|
||||
|
||||
root.state.yPosition = unmodifiedYposition + (root.taskSwitcherHelpers.taskDrawerOpened || !root.state.wasInActiveTask ? root.taskSwitcherHelpers.openedYPosition : 0);
|
||||
|
||||
let newXPosition = root.taskSwitcherHelpers.xPositionFromTaskIndex(root.state.initialTaskIndex);
|
||||
if (root.taskSwitcherHelpers.notHomeScreenState && !root.taskSwitcherHelpers.currentlyBeingClosed) {
|
||||
newXPosition = newXPosition - (root.state.touchXPosition / root.taskSwitcherHelpers.currentScale);
|
||||
}
|
||||
root.state.xPosition = newXPosition;
|
||||
|
||||
// allows the user to move the task drawer left and right when on the home screen
|
||||
taskList.homeTouchPositionX = root.taskSwitcherHelpers.notHomeScreenState ? 0 : (root.state.touchXPosition * 0.35);
|
||||
|
||||
// dynamically update the task switcher state based off of the touch position and velocity
|
||||
updateTaskSwitcherState()
|
||||
}
|
||||
}
|
||||
|
||||
function updateTaskSwitcherState(): void {
|
||||
let unmodifiedYposition = Math.abs(root.state.touchYPosition)
|
||||
|
||||
// if the touch is above heightThreshold, set reachedHeightThreshold to true
|
||||
if (unmodifiedYposition > root.taskSwitcherHelpers.heightThreshold) {
|
||||
// set reachedHeightThreshold when above or below two separate points to helps prevent flickering when the task switcher moves in and out of view
|
||||
root.taskSwitcherHelpers.reachedHeightThreshold = true;
|
||||
root.backgroundColorOpacity = root.taskSwitcherHelpers.notHomeScreenState ? 0 : 1;
|
||||
} else if (unmodifiedYposition > root.taskSwitcherHelpers.undoYThreshold) {
|
||||
root.backgroundColorOpacity = 1;
|
||||
} else {
|
||||
root.backgroundColorOpacity = root.taskSwitcherHelpers.notHomeScreenState ? 1 : 0;
|
||||
}
|
||||
|
||||
if (root.state.totalSquaredVelocity > root.state.flickVelocityThreshold) {
|
||||
// flick
|
||||
// ratio between y and x velocity as threshold between vertical and horizontal flick
|
||||
let xyVelocityRatio = 1.7; // with 1.7 swipes up to ~60° from horizontal are counted as horizontal
|
||||
if (root.state.yVelocity > Math.abs(root.state.xVelocity) * xyVelocityRatio) {
|
||||
// downwards flick
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.Undecided);
|
||||
if (unmodifiedYposition < root.taskSwitcherHelpers.undoYThreshold) {
|
||||
taskList.setTaskOffsetValue(root.taskSwitcherHelpers.notHomeScreenState ? 0 : root.taskSwitcherHelpers.homeOffsetValue);
|
||||
}
|
||||
} else if (-root.state.yVelocity > Math.abs(root.state.xVelocity) * xyVelocityRatio || (root.taskSwitcherHelpers.reachedHeightThreshold && root.taskSwitcherHelpers.notHomeScreenState)) {
|
||||
// upwards flick or if the touch is above heightThreshold
|
||||
if (root.taskSwitcherHelpers.notHomeScreenState) {
|
||||
// if in app or task switcher, go home
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.Home);
|
||||
if (root.taskSwitcherHelpers.reachedHeightThreshold) {
|
||||
taskList.setTaskOffsetValue(root.taskSwitcherHelpers.taskOffsetValue);
|
||||
}
|
||||
} else if (unmodifiedYposition > root.taskSwitcherHelpers.undoYThreshold) {
|
||||
// else, keep the task switcher in view
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.TaskSwitcher);
|
||||
taskList.setTaskOffsetValue(root.taskSwitcherHelpers.peekOffsetValue);
|
||||
}
|
||||
} else if (!root.taskSwitcherHelpers.reachedHeightThreshold && !root.taskSwitcherHelpers.isInTaskScrubMode) {
|
||||
// sideways flick
|
||||
if (root.taskSwitcherHelpers.notHomeScreenState) {
|
||||
taskList.setTaskOffsetValue(0, unmodifiedYposition < root.taskSwitcherHelpers.openedYPosition ? true : false);
|
||||
}
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.HorizontalSwipe);
|
||||
}
|
||||
} else {
|
||||
if (unmodifiedYposition > root.taskSwitcherHelpers.undoYThreshold) {
|
||||
// if just moveing out of undoYThreshold, set the state to home
|
||||
if (root.taskSwitcherHelpers.gestureState < TaskSwitcherHelpers.GestureStates.TaskSwitcher) {
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.Home)
|
||||
}
|
||||
// if the touch is above heightThreshold, it will return home
|
||||
if (unmodifiedYposition > root.taskSwitcherHelpers.heightThreshold) {
|
||||
root.taskSwitcherHelpers.hasVibrated = true;
|
||||
if (root.taskSwitcherHelpers.notHomeScreenState) {
|
||||
// move the task switcher out of view
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.Home);
|
||||
taskList.setTaskOffsetValue(root.taskSwitcherHelpers.taskOffsetValue);
|
||||
} else {
|
||||
// keep the task switcher in view when above heightThreshold and from home
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.TaskSwitcher);
|
||||
taskList.setTaskOffsetValue(root.taskSwitcherHelpers.peekOffsetValue);
|
||||
}
|
||||
// minus largeSpacing from the heightThreshold to help prevent flickering when the task switcher moves in and out of view
|
||||
} else if ((unmodifiedYposition < root.taskSwitcherHelpers.heightThreshold - Kirigami.Units.largeSpacing) || root.taskSwitcherHelpers.reachedHeightThreshold == false) {
|
||||
// set reachedHeightThreshold when above or below two separate points to helps prevent flickering when the task switcher moves in and out of view
|
||||
root.taskSwitcherHelpers.reachedHeightThreshold = false;
|
||||
if (root.state.totalSquaredVelocity < root.state.flickVelocityThreshold && root.taskSwitcherHelpers.taskSwitchCanLaunch) {
|
||||
// if velocity is small enough, move the task switcher into view
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.TaskSwitcher);
|
||||
taskList.setTaskOffsetValue(root.taskSwitcherHelpers.notHomeScreenState ? 0 : root.taskSwitcherHelpers.peekOffsetValue);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// if under the undo threshold, it will go back to the task switcher if it is open
|
||||
if (root.taskSwitcherHelpers.taskDrawerOpened) {
|
||||
root.taskSwitcherHelpers.reachedHeightThreshold = false;
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.TaskSwitcher)
|
||||
taskList.setTaskOffsetValue(0);
|
||||
} else {
|
||||
root.taskSwitcherHelpers.reachedHeightThreshold = false;
|
||||
root.setTaskDrawerState(TaskSwitcherHelpers.GestureStates.Undecided)
|
||||
taskList.setTaskOffsetValue(root.taskSwitcherHelpers.notHomeScreenState ? 0 : root.taskSwitcherHelpers.homeOffsetValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// returns to the currently centered app. usually used to "back out" of the switcher
|
||||
// if accidentally invoked, but can also be used to switch to an adjacent app and then open it
|
||||
function returnToApp(): void {
|
||||
let newIndex = root.taskSwitcherHelpers.getNearestTaskIndex();
|
||||
root.taskSwitcherHelpers.openApp(newIndex);
|
||||
}
|
||||
|
||||
// diagonal quick switch gesture logic
|
||||
function quickSwitch(): void {
|
||||
// should "quick switch" to adjacent app in task switcher, but only if we were in an app before
|
||||
let unmodifiedYposition = Math.abs(root.state.touchYPosition)
|
||||
let newIndex = root.state.currentTaskIndex;
|
||||
let shouldSwitch = false;
|
||||
if (root.state.xVelocity > 0) {
|
||||
if (root.taskSwitcherHelpers.notHomeScreenState) {
|
||||
// flick to the right, go to the app on the left
|
||||
newIndex = root.state.currentTaskIndex + 1;
|
||||
}
|
||||
if (newIndex < root.tasksCount) {
|
||||
// switch only if flick doesn't go over end of list
|
||||
shouldSwitch = true;
|
||||
}
|
||||
} else if (root.state.xVelocity < 0) {
|
||||
if (root.taskSwitcherHelpers.notHomeScreenState) {
|
||||
// flick to the left, go to app to the right
|
||||
newIndex = root.state.currentTaskIndex - 1;
|
||||
if (newIndex >= 0) {
|
||||
// switch only if flick doesn't go over end of list
|
||||
shouldSwitch = true;
|
||||
}
|
||||
} else {
|
||||
// flick to the left on the home screen, dismiss the gesture
|
||||
root.taskSwitcherHelpers.close();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (shouldSwitch) {
|
||||
if (!root.taskSwitcherHelpers.taskDrawerOpened && unmodifiedYposition < root.taskSwitcherHelpers.openedYPosition) {
|
||||
// if in a app, switch it to the new task when it is under the openedYPosition
|
||||
taskList.setTaskOffsetValue(0, unmodifiedYposition < root.taskSwitcherHelpers.openedYPosition && root.taskSwitcherHelpers.notHomeScreenState);
|
||||
root.taskSwitcherHelpers.openApp(newIndex, Kirigami.Units.longDuration * 4, Easing.OutExpo);
|
||||
} else {
|
||||
// if already in the task switcher or above the openedYPosition, only change the focus to the new task
|
||||
root.taskSwitcherHelpers.animateGoToTaskIndex(newIndex);
|
||||
root.taskSwitcherHelpers.open();
|
||||
}
|
||||
} else {
|
||||
// if not switching, just open task switcher
|
||||
root.taskSwitcherHelpers.animateGoToTaskIndex(root.state.currentTaskIndex);
|
||||
root.taskSwitcherHelpers.open();
|
||||
}
|
||||
}
|
||||
|
||||
// Logic for deciding how to handle the end of a gesture input
|
||||
function onGestureInProgressChanged(): void {
|
||||
root.taskSwitcherHelpers.fromButton = false;
|
||||
if (root.state.gestureInProgress) {
|
||||
root.taskSwitcherHelpers.currentDisplayTask = root.state.currentTaskIndex;
|
||||
return;
|
||||
}
|
||||
|
||||
if (taskList.count === 0) {
|
||||
// dismiss the gesture if the task list is empty
|
||||
root.taskSwitcherHelpers.close();
|
||||
} if (root.taskSwitcherHelpers.isInTaskScrubMode) {
|
||||
// TODO! do we want to handle upwards flick to dismiss in task scrub mode?
|
||||
let unmodifiedYposition = Math.abs(root.state.touchYPosition)
|
||||
root.backgroundColorOpacity = 1;
|
||||
if (root.taskSwitcherHelpers.taskDrawerOpened || unmodifiedYposition > root.taskSwitcherHelpers.undoYThreshold) {
|
||||
root.taskSwitcherHelpers.animateGoToTaskIndex(root.state.currentTaskIndex);
|
||||
root.taskSwitcherHelpers.open();
|
||||
root.taskSwitcherHelpers.isInTaskScrubMode = false;
|
||||
} else {
|
||||
root.taskSwitcherHelpers.openApp(root.state.currentTaskIndex);
|
||||
}
|
||||
} else if (root.taskSwitcherHelpers.gestureState == TaskSwitcherHelpers.GestureStates.Undecided) {
|
||||
if (root.taskSwitcherHelpers.taskDrawerOpened) {
|
||||
// if in the task switcher, return to it
|
||||
root.taskSwitcherHelpers.animateGoToTaskIndex(root.state.currentTaskIndex);
|
||||
root.taskSwitcherHelpers.open();
|
||||
} else if (root.state.wasInActiveTask) {
|
||||
// if inside a app, return to it
|
||||
returnToApp();
|
||||
} else {
|
||||
// else dismiss the gesture
|
||||
root.taskSwitcherHelpers.close();
|
||||
}
|
||||
} else if (root.taskSwitcherHelpers.gestureState == TaskSwitcherHelpers.GestureStates.HorizontalSwipe) {
|
||||
// sideways flick
|
||||
root.backgroundColorOpacity = 1;
|
||||
quickSwitch();
|
||||
} else if (root.taskSwitcherHelpers.gestureState == TaskSwitcherHelpers.GestureStates.TaskSwitcher) {
|
||||
// open the task drawer
|
||||
root.backgroundColorOpacity = 1;
|
||||
root.taskSwitcherHelpers.animateGoToTaskIndex(root.state.currentTaskIndex);
|
||||
root.taskSwitcherHelpers.open();
|
||||
} else if (root.taskSwitcherHelpers.gestureState == TaskSwitcherHelpers.GestureStates.Home) {
|
||||
root.taskSwitcherHelpers.close();
|
||||
}
|
||||
}
|
||||
|
||||
function onVelocityChanged(): void {
|
||||
|
||||
}
|
||||
|
||||
function onXPositionChanged(): void {
|
||||
root.taskSwitcherHelpers.updateTaskIndex();
|
||||
}
|
||||
}
|
||||
|
||||
// kind of a hack, but this prevents the gesture from immediately activating the task switcher when it is not supposed to
|
||||
Timer {
|
||||
id: taskSwitchCanLaunchTimer
|
||||
interval: 1; running: true; repeat: false
|
||||
onTriggered: root.taskSwitcherHelpers.taskSwitchCanLaunch = true;
|
||||
}
|
||||
|
||||
function setTaskDrawerState(value: int): void {
|
||||
if (taskSwitcherHelpers.gestureState != TaskSwitcherHelpers.GestureStates.TaskSwitcher && value == TaskSwitcherHelpers.GestureStates.TaskSwitcher) {
|
||||
// vibrate only if switching to task drawer
|
||||
if (!taskSwitcherHelpers.hasVibrated) {
|
||||
// Haptic feedback when the task scrub mode engages
|
||||
haptics.buttonVibrate();
|
||||
taskSwitcherHelpers.hasVibrated = true;
|
||||
}
|
||||
|
||||
}
|
||||
taskSwitcherHelpers.gestureState = value;
|
||||
}
|
||||
|
||||
// view of the desktop background
|
||||
KWinComponents.DesktopBackground {
|
||||
id: backgroundItem
|
||||
activity: KWinComponents.Workspace.currentActivity
|
||||
desktop: KWinComponents.Workspace.currentDesktop
|
||||
outputName: root.targetScreen.name
|
||||
}
|
||||
|
||||
// background colour
|
||||
Rectangle {
|
||||
id: backgroundRect
|
||||
anchors.fill: root
|
||||
|
||||
opacity: container.opacity
|
||||
color: {
|
||||
return Qt.rgba(0, 0, 0, 0.6 * root.taskSwitcherHelpers.closingFactor * root.backgroundColorOpacity);
|
||||
}
|
||||
}
|
||||
|
||||
// animate the background opacity based off of the state.
|
||||
property real backgroundColorOpacity: 1
|
||||
Behavior on backgroundColorOpacity {
|
||||
id: backgroundColorOpacityAn
|
||||
NumberAnimation {
|
||||
duration: Kirigami.Units.longDuration
|
||||
}
|
||||
}
|
||||
|
||||
// status bar
|
||||
// TODO: improve load times, it is quite slow
|
||||
// MobileShell.StatusBar {
|
||||
// id: statusBar
|
||||
// z: 1
|
||||
// colorGroup: Kirigami.Theme.ComplementaryColorGroup
|
||||
// backgroundColor: "transparent"
|
||||
//
|
||||
// height: root.topMargin
|
||||
// anchors.top: parent.top
|
||||
// anchors.left: parent.left
|
||||
// anchors.right: parent.right
|
||||
// }
|
||||
|
||||
// Gesture panel
|
||||
Component {
|
||||
id: gesturePanelComponent
|
||||
|
||||
MobileShell.GesturePanel {
|
||||
anchors.left: parent.left
|
||||
anchors.right: parent.right
|
||||
anchors.bottom: parent.bottom
|
||||
|
||||
Kirigami.Theme.inherit: false
|
||||
Kirigami.Theme.colorSet: Kirigami.Theme.Complementary
|
||||
opaqueBar: false
|
||||
|
||||
// Trigger home action on tap
|
||||
onHandleClicked: {
|
||||
if (taskList.count === 0) {
|
||||
root.hide();
|
||||
} else {
|
||||
if (taskList.count > 1 &&
|
||||
root.state.elapsedTimeSinceStart != -1 &&
|
||||
root.state.elapsedTimeSinceStart < root.state.doubleClickInterval) {
|
||||
root.taskSwitcherHelpers.openApp(1);
|
||||
return;
|
||||
}
|
||||
|
||||
const currentIndex = root.state.currentTaskIndex;
|
||||
root.taskSwitcherHelpers.openApp(root.state.currentTaskIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Navigation panel
|
||||
Component {
|
||||
id: navigationPanelComponent
|
||||
|
||||
MobileShell.NavigationPanel {
|
||||
id: navigationPanel
|
||||
backgroundColor: Qt.rgba(0, 0, 0, 0.1)
|
||||
foregroundColorGroup: Kirigami.Theme.Complementary
|
||||
shadow: false
|
||||
|
||||
isVertical: MobileShell.Constants.navigationPanelOnSide(root.width, root.height)
|
||||
|
||||
MobileShellState.PanelSettingsDBusClient {
|
||||
id: panelSettings
|
||||
screenName: Screen.name
|
||||
}
|
||||
|
||||
leftPadding: panelSettings.navigationPanelLeftPadding
|
||||
rightPadding: panelSettings.navigationPanelRightPadding
|
||||
|
||||
leftAction: MobileShell.NavigationPanelAction {
|
||||
enabled: true
|
||||
iconSource: "mobile-task-switcher"
|
||||
shrinkSize: 4
|
||||
|
||||
onTriggered: {
|
||||
if (taskList.count === 0) {
|
||||
root.hide();
|
||||
} else {
|
||||
if (taskList.count > 1 &&
|
||||
root.state.elapsedTimeSinceStart != -1 &&
|
||||
root.state.elapsedTimeSinceStart < root.state.doubleClickInterval) {
|
||||
root.taskSwitcherHelpers.openApp(1);
|
||||
return;
|
||||
}
|
||||
|
||||
const currentIndex = root.state.currentTaskIndex;
|
||||
root.taskSwitcherHelpers.openApp(root.state.currentTaskIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// home button
|
||||
middleAction: MobileShell.NavigationPanelAction {
|
||||
enabled: true
|
||||
iconSource: "start-here-kde"
|
||||
onTriggered: root.hide()
|
||||
}
|
||||
|
||||
// close app/keyboard button
|
||||
rightAction: MobileShell.NavigationPanelAction {
|
||||
enabled: true
|
||||
iconSource: "mobile-close-app"
|
||||
shrinkSize: 4
|
||||
|
||||
onTriggered: {
|
||||
taskList.getTaskAt(root.state.currentTaskIndex).closeApp();
|
||||
}
|
||||
}
|
||||
|
||||
rightCornerAction: MobileShell.NavigationPanelAction {
|
||||
visible: false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loader {
|
||||
id: panelLoader
|
||||
z: !root.taskSwitcherHelpers.currentlyBeingClosed ? 1 : 0
|
||||
sourceComponent: {
|
||||
if (ShellSettings.Settings.navigationPanelEnabled) {
|
||||
return navigationPanelComponent;
|
||||
} else if (ShellSettings.Settings.gesturePanelEnabled) {
|
||||
return gesturePanelComponent;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
states: [
|
||||
State {
|
||||
name: "landscape"
|
||||
when: MobileShell.Constants.navigationPanelOnSide(root.width, root.height)
|
||||
AnchorChanges {
|
||||
target: panelLoader
|
||||
anchors {
|
||||
right: root.right
|
||||
top: root.top
|
||||
bottom: root.bottom
|
||||
left: undefined
|
||||
}
|
||||
}
|
||||
PropertyChanges {
|
||||
target: panelLoader
|
||||
width: navRightMargin
|
||||
anchors.topMargin: root.topMargin
|
||||
}
|
||||
},
|
||||
State {
|
||||
name: "portrait"
|
||||
when: !MobileShell.Constants.navigationPanelOnSide(root.width, root.height)
|
||||
AnchorChanges {
|
||||
target: panelLoader
|
||||
anchors {
|
||||
top: undefined
|
||||
right: root.right
|
||||
left: root.left
|
||||
bottom: root.bottom
|
||||
}
|
||||
}
|
||||
PropertyChanges {
|
||||
target: panelLoader
|
||||
height: navBottomMargin
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
// task list
|
||||
Item {
|
||||
id: container
|
||||
|
||||
// provide shell margins
|
||||
anchors.fill: root
|
||||
anchors.leftMargin: root.leftMargin
|
||||
anchors.rightMargin: root.rightMargin
|
||||
anchors.bottomMargin: root.bottomMargin
|
||||
anchors.topMargin: root.topMargin
|
||||
|
||||
NumberAnimation on opacity {
|
||||
id: closeAnim
|
||||
running: false
|
||||
to: 0
|
||||
duration: Kirigami.Units.longDuration
|
||||
easing.type: Easing.InOutQuad
|
||||
|
||||
onFinished: {
|
||||
closeAllButton.closeRequested = false;
|
||||
}
|
||||
}
|
||||
|
||||
// placeholder message
|
||||
ColumnLayout {
|
||||
id: placeholder
|
||||
spacing: Kirigami.Units.gridUnit
|
||||
|
||||
opacity: {
|
||||
let baseOpacity = ((root.tasksCount === 0 && !root.taskSwitcherHelpers.currentlyBeingClosed) ? 0.9 : 0);
|
||||
return root.taskSwitcherHelpers.gestureState == TaskSwitcherHelpers.GestureStates.TaskSwitcher ? baseOpacity : 0;
|
||||
}
|
||||
Behavior on opacity { NumberAnimation { duration: Kirigami.Units.veryLongDuration } }
|
||||
|
||||
anchors.centerIn: container
|
||||
|
||||
Kirigami.Icon {
|
||||
id: icon
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
implicitWidth: Kirigami.Units.iconSizes.large
|
||||
implicitHeight: Kirigami.Units.iconSizes.large
|
||||
source: "edit-none-symbolic"
|
||||
color: "white"
|
||||
}
|
||||
|
||||
Kirigami.Heading {
|
||||
Layout.fillWidth: true
|
||||
Layout.maximumWidth: root.width * 0.75
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
color: "white"
|
||||
level: 3
|
||||
wrapMode: Text.Wrap
|
||||
horizontalAlignment: Text.AlignHCenter
|
||||
text: i18n("No applications are running.")
|
||||
}
|
||||
}
|
||||
|
||||
RowLayout {
|
||||
id: scrubIconList
|
||||
opacity: root.taskSwitcherHelpers.isInTaskScrubMode ? 1 : 0
|
||||
Behavior on opacity { NumberAnimation { duration: Kirigami.Units.longDuration } }
|
||||
|
||||
anchors.bottom: container.bottom
|
||||
anchors.right: container.horizontalCenter
|
||||
anchors.bottomMargin: root.taskSwitcherHelpers.scrubModeBottomMargin
|
||||
|
||||
anchors.rightMargin: {
|
||||
let size = Kirigami.Units.iconSizes.large + Kirigami.Units.largeSpacing * 2;
|
||||
let offset = (root.state.currentTaskIndex + 0.5) * size;
|
||||
return -offset;
|
||||
}
|
||||
Behavior on anchors.rightMargin {
|
||||
NumberAnimation {
|
||||
duration: root.taskSwitcherHelpers.xAnimDuration;
|
||||
easing.type: root.taskSwitcherHelpers.xAnimEasingType;
|
||||
}
|
||||
}
|
||||
|
||||
spacing: Kirigami.Units.largeSpacing * 2
|
||||
|
||||
layoutDirection: Qt.RightToLeft
|
||||
|
||||
Repeater {
|
||||
model: root.tasksModel
|
||||
|
||||
delegate: Kirigami.Icon {
|
||||
id: iconDelegate
|
||||
|
||||
required property QtObject window
|
||||
required property int index
|
||||
|
||||
readonly property bool isCenteredIcon: iconDelegate.index === root.state.currentTaskIndex;
|
||||
Layout.preferredHeight: isCenteredIcon ? Kirigami.Units.iconSizes.huge : Kirigami.Units.iconSizes.large
|
||||
Layout.preferredWidth: isCenteredIcon ? Kirigami.Units.iconSizes.huge : Kirigami.Units.iconSizes.large
|
||||
Layout.alignment: Qt.AlignVCenter
|
||||
source: iconDelegate.window.icon
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
RowLayout {
|
||||
id: scrubIndicator
|
||||
opacity: root.taskSwitcherHelpers.isInTaskScrubMode ? 1 : 0
|
||||
Behavior on opacity { NumberAnimation { duration: 200 } }
|
||||
|
||||
anchors.bottom: container.bottom
|
||||
anchors.horizontalCenter: container.horizontalCenter
|
||||
anchors.bottomMargin: root.taskSwitcherHelpers.openedYPosition * 1 / 4
|
||||
|
||||
Kirigami.Icon {
|
||||
id: iconScrubBack
|
||||
opacity: root.state.currentTaskIndex == 0 ? 0.3 : 1
|
||||
Behavior on opacity { NumberAnimation { duration: Kirigami.Units.longDuration * 2; easing.type: Easing.OutExpo } }
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
implicitWidth: Kirigami.Units.iconSizes.medium
|
||||
implicitHeight: Kirigami.Units.iconSizes.medium
|
||||
source: "draw-arrow-back"
|
||||
color: "white"
|
||||
}
|
||||
|
||||
Item {
|
||||
width: root.taskSwitcherHelpers.windowWidth / 4
|
||||
}
|
||||
|
||||
Kirigami.Icon {
|
||||
id: iconScrubFront
|
||||
opacity: root.state.currentTaskIndex == root.tasksCount - 1 ? 0.3 : 1
|
||||
Behavior on opacity { NumberAnimation { duration: Kirigami.Units.longDuration * 2; easing.type: Easing.OutExpo } }
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
implicitWidth: Kirigami.Units.iconSizes.medium
|
||||
implicitHeight: Kirigami.Units.iconSizes.medium
|
||||
source: "draw-arrow-forward"
|
||||
color: "white"
|
||||
}
|
||||
}
|
||||
|
||||
// flicking area for task switcher
|
||||
FlickContainer {
|
||||
id: flickable
|
||||
anchors.fill: container
|
||||
|
||||
taskSwitcherState: root.state
|
||||
taskSwitcherHelpers: root.taskSwitcherHelpers
|
||||
tasksCount: root.tasksCount
|
||||
|
||||
// don't allow FlickContainer to steal from swiping on tasks
|
||||
interactive: taskList.taskInteractingCount === 0
|
||||
|
||||
// the item is effectively anchored to the flickable bounds
|
||||
TaskList {
|
||||
id: taskList
|
||||
taskSwitcher: root
|
||||
shellTopMargin: root.topMargin
|
||||
shellBottomMargin: root.bottomMargin
|
||||
|
||||
|
||||
x: flickable.contentX
|
||||
width: flickable.width
|
||||
height: flickable.height
|
||||
}
|
||||
|
||||
PlasmaComponents.ToolButton {
|
||||
id: closeAllButton
|
||||
property bool closeRequested: false
|
||||
visible: root.tasksCount !== 0 && !root.taskSwitcherHelpers.isInTaskScrubMode
|
||||
enabled: !root.taskSwitcherHelpers.currentlyBeingClosed && !root.state.gestureInProgress
|
||||
|
||||
Kirigami.Theme.inherit: false
|
||||
Kirigami.Theme.colorSet: Kirigami.Theme.Complementary
|
||||
|
||||
anchors {
|
||||
bottom: taskList.bottom
|
||||
bottomMargin: (taskList.taskYBase) * 0.75
|
||||
horizontalCenter: taskList.horizontalCenter
|
||||
}
|
||||
|
||||
opacity: (root.taskSwitcherHelpers.currentlyBeingClosed || root.state.gestureInProgress || !root.taskSwitcherHelpers.taskDrawerOpened) ? 0.0 : 1.0
|
||||
Behavior on opacity { NumberAnimation { duration: Kirigami.Units.shortDuration } }
|
||||
|
||||
icon.name: "edit-clear-history"
|
||||
font.bold: true
|
||||
|
||||
text: closeRequested ? i18n("Confirm Close All") : i18n("Close All")
|
||||
|
||||
onClicked: {
|
||||
if (closeRequested) {
|
||||
taskList.closeAll();
|
||||
} else {
|
||||
closeRequested = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
repo_root=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
image_name=${DROIDDECK_PLASMA_BUILD_IMAGE:-droiddeck-plasma-mobile-builder:6.7.5}
|
||||
|
||||
if ! docker image inspect "${image_name}" >/dev/null 2>&1; then
|
||||
docker build --platform linux/arm64 -t "${image_name}" \
|
||||
-f "${repo_root}/tools/plasma-mobile/Dockerfile" "${repo_root}/tools/plasma-mobile"
|
||||
fi
|
||||
|
||||
docker run --rm --platform linux/arm64 \
|
||||
--user "$(id -u):$(id -g)" -e HOME=/tmp \
|
||||
-v "${repo_root}:/src" -w /src "${image_name}" \
|
||||
bash /src/tools/plasma-mobile/build-in-container.sh
|
||||
|
||||
prebuilt="${repo_root}/tools/plasma-mobile/prebuilt"
|
||||
asset_root="${repo_root}/app/src/main/assets/linuxfs"
|
||||
cp "${asset_root}/usr/lib/qt6/plugins/plasma/applets/org.kde.plasma.mobile.homescreen.folio.so" \
|
||||
"${prebuilt}/org.kde.plasma.mobile.homescreen.folio.so"
|
||||
cp "${asset_root}/usr/lib/qt6/qml/org/kde/plasma/private/mobileshell/taskswitcherplugin/libmobiletaskswitcherplugin.so" \
|
||||
"${prebuilt}/libmobiletaskswitcherplugin.so"
|
||||
cp "${asset_root}/usr/share/kwin/effects/mobiletaskswitcher/contents/ui/FlickContainer.qml" \
|
||||
"${prebuilt}/FlickContainer.qml"
|
||||
cp "${asset_root}/usr/share/kwin/effects/mobiletaskswitcher/contents/ui/TaskSwitcher.qml" \
|
||||
"${prebuilt}/TaskSwitcher.qml"
|
||||
echo "Refreshed the Plasma Mobile backports from ${image_name##*:}."
|
||||
@@ -20,6 +20,7 @@ def load(name):
|
||||
|
||||
imports = load('bannerlator-steam-games')
|
||||
shortcuts = load('bannerlator-steam-shortcuts')
|
||||
library = load('bannerlator-steam-library')
|
||||
|
||||
|
||||
class ImportsTest(unittest.TestCase):
|
||||
@@ -73,6 +74,7 @@ class ImportsTest(unittest.TestCase):
|
||||
from unittest.mock import Mock
|
||||
result = Mock(returncode=0, stdout='DROIDDECK_OWNERSHIP=' + json.dumps(dict(account='123', owned={'42': True})))
|
||||
with patch.object(imports, 'identify', side_effect=[None, 42]) as identify, \
|
||||
patch.object(imports, 'request_restart'), \
|
||||
patch.object(imports.time, 'monotonic', side_effect=[0, 301]), \
|
||||
patch.object(imports.time, 'sleep', side_effect=[None, RuntimeError('stop')]), \
|
||||
patch.object(imports.subprocess, 'run', return_value=result), \
|
||||
@@ -83,6 +85,35 @@ class ImportsTest(unittest.TestCase):
|
||||
snapshot = imports.read_json(self.acct / 'config' / imports.STATE, {})
|
||||
self.assertTrue(snapshot['owned']['42'])
|
||||
|
||||
def run_watch(self, beats, routes=None, busy=False):
|
||||
listing = self.root / 'games.json'
|
||||
listing.write_text(json.dumps([self.game]))
|
||||
if routes is not None:
|
||||
imports.save_json(self.acct / 'config/.droiddeck-routes.json', routes)
|
||||
if busy:
|
||||
(self.steam / 'steamapps/downloading/7').mkdir(parents=True)
|
||||
from unittest.mock import Mock
|
||||
result = Mock(returncode=0, stdout='DROIDDECK_OWNERSHIP=' + json.dumps(dict(account='123', owned={'42': True})))
|
||||
with patch.object(imports, 'identify', return_value=42), \
|
||||
patch.object(imports, 'game_running', return_value=False), \
|
||||
patch.object(imports, 'request_restart') as restart, \
|
||||
patch.object(imports.time, 'monotonic', side_effect=list(range(0, 30 * beats, 30))), \
|
||||
patch.object(imports.time, 'sleep', side_effect=[None] * (beats - 1) + [RuntimeError('stop')]), \
|
||||
patch.object(imports.subprocess, 'run', return_value=result), \
|
||||
patch('builtins.print'):
|
||||
with self.assertRaisesRegex(RuntimeError, 'stop'):
|
||||
imports.watch(self.steam, listing)
|
||||
return restart
|
||||
|
||||
def test_newly_owned_game_restarts_the_client_once(self):
|
||||
self.assertEqual(1, self.run_watch(3).call_count)
|
||||
|
||||
def test_imported_game_does_not_restart_the_client(self):
|
||||
self.assertEqual(0, self.run_watch(2, routes={'1': 42}).call_count)
|
||||
|
||||
def test_restart_waits_for_downloads(self):
|
||||
self.assertEqual(0, self.run_watch(2, busy=True).call_count)
|
||||
|
||||
def test_unowned_unknown_and_different_account_stay_shortcuts(self):
|
||||
for owned, account in [(False, '123'), (True, '456')]:
|
||||
self.snapshot(owned, account)
|
||||
@@ -91,6 +122,93 @@ class ImportsTest(unittest.TestCase):
|
||||
self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game]))
|
||||
self.assertFalse((self.steam / 'steamapps').exists())
|
||||
|
||||
def winnative_manifest(self, flags='4', installdir='Example'):
|
||||
path = self.folder.parent / imports.WINNATIVE / 'appmanifest_42.acf'
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text('"AppState"\n{\n\t"appid"\t\t"42"\n\t"StateFlags"\t\t"%s"\n\t"installdir"\t\t"%s"\n'
|
||||
'\t"buildid"\t\t"7"\n\t"InstalledDepots"\n\t{\n\t\t"43"\n\t\t{\n\t\t\t"manifest"\t\t"99"\n'
|
||||
'\t\t\t"size"\t\t"4"\n\t\t}\n\t}\n}\n' % (flags, installdir))
|
||||
return path
|
||||
|
||||
def test_winnative_manifest_carries_installed_build(self):
|
||||
source = self.winnative_manifest()
|
||||
self.snapshot()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
text = (self.steam / 'steamapps/appmanifest_42.acf').read_text()
|
||||
self.assertEqual(source.read_text().replace('"Example"', '"DroidDeck-42"'), text)
|
||||
|
||||
def test_winnative_manifest_identifies_folder(self):
|
||||
self.winnative_manifest()
|
||||
with patch.object(imports.urllib.request, 'urlopen', side_effect=AssertionError):
|
||||
self.assertEqual(42, imports.identify(self.game))
|
||||
|
||||
def test_incomplete_winnative_manifest_is_ignored(self):
|
||||
for flags, installdir in [('1026', 'Example'), ('4', 'Other')]:
|
||||
self.winnative_manifest(flags, installdir)
|
||||
self.assertIsNone(imports.installed_build(self.folder, 42, 'DroidDeck-42'))
|
||||
|
||||
def test_depot_config_records_installed_depots(self):
|
||||
config = self.folder / '.DepotDownloader/depot.config'
|
||||
config.parent.mkdir()
|
||||
config.write_text(json.dumps({'installedManifestIDs': {'43': 99}}))
|
||||
self.assertIsNone(imports.installed_build(self.folder, 42, 'DroidDeck-42'))
|
||||
(self.folder / '.download_complete').touch()
|
||||
self.snapshot()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
text = (self.steam / 'steamapps/appmanifest_42.acf').read_text()
|
||||
self.assertIn('"InstalledDepots"\n {\n "43"\n {\n "manifest" "99"', text)
|
||||
self.assertTrue(text.endswith(' }\n}\n'))
|
||||
config.write_text(json.dumps({'installedManifestIDs': {'43': 0x7FFFFFFFFFFFFFFF}}))
|
||||
self.assertIsNone(imports.installed_build(self.folder, 42, 'DroidDeck-42'))
|
||||
|
||||
def test_bare_import_manifest_gains_installed_build(self):
|
||||
self.snapshot()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
self.winnative_manifest()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
self.assertIn('"buildid"\t\t"7"', (self.steam / 'steamapps/appmanifest_42.acf').read_text())
|
||||
|
||||
def steam_fresh_install(self, downloaded='0'):
|
||||
self.snapshot()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
path = self.steam / 'steamapps/appmanifest_42.acf'
|
||||
path.write_text('"AppState"\n{\n\t"appid"\t\t"42"\n\t"StateFlags"\t\t"6"\n\t"installdir"\t\t"DroidDeck-42"\n'
|
||||
'\t"buildid"\t\t"0"\n\t"BytesDownloaded"\t\t"%s"\n\t"BytesStaged"\t\t"0"\n'
|
||||
'\t"InstalledDepots"\n\t{\n\t}\n}\n' % downloaded)
|
||||
self.winnative_manifest()
|
||||
return path
|
||||
|
||||
def test_queued_fresh_install_takes_installed_build(self):
|
||||
path = self.steam_fresh_install()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
self.assertIn('"buildid"\t\t"7"', path.read_text())
|
||||
|
||||
def test_started_fresh_install_is_left_to_steam(self):
|
||||
for downloaded, staging in [('5', False), ('0', True)]:
|
||||
path = self.steam_fresh_install(downloaded)
|
||||
if staging:
|
||||
(self.steam / 'steamapps/downloading/42').mkdir(parents=True)
|
||||
before = path.read_text()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
self.assertEqual(before, path.read_text())
|
||||
|
||||
def test_links_and_snapshots_from_the_old_mount_carry_over(self):
|
||||
old = self.root / 'old-mount'
|
||||
with patch.object(imports, 'LIBRARY', str(self.root / 'Games')), \
|
||||
patch.object(imports, 'LEGACY_LIBRARY', str(old)):
|
||||
legacy_game = dict(self.game, folder=str(old / 'Example'), exe=str(old / 'Example/Example.exe'))
|
||||
stamp = imports.source_stamp(self.game)
|
||||
imports.save_json(self.acct / 'config' / imports.STATE,
|
||||
dict(account='123', owned={'42': True}, candidates={legacy_game['folder']: 42},
|
||||
sources={legacy_game['folder']: [stamp[0], legacy_game['exe']] + stamp[2:]}))
|
||||
link = self.steam / 'steamapps/common/DroidDeck-42'
|
||||
link.parent.mkdir(parents=True)
|
||||
link.symlink_to(legacy_game['folder'], target_is_directory=True)
|
||||
games, routes = imports.route(self.steam, self.acct, [self.game])
|
||||
self.assertEqual([], games)
|
||||
self.assertEqual({str(self.game['appid']): 42}, routes)
|
||||
self.assertEqual(str(self.folder), imports.os.readlink(link))
|
||||
|
||||
def test_existing_manifest_is_never_overwritten(self):
|
||||
manifest = self.steam / 'steamapps/appmanifest_42.acf'
|
||||
manifest.parent.mkdir(parents=True)
|
||||
@@ -188,6 +306,34 @@ class ImportsTest(unittest.TestCase):
|
||||
self.assertEqual({str(self.game['appid']): 42}, json.loads((path.parent / '.droiddeck-routes.json').read_text()))
|
||||
|
||||
|
||||
class LibraryRenameTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.steam = Path(temp.name)
|
||||
self.vdf = self.steam / 'steamapps/libraryfolders.vdf'
|
||||
self.vdf.parent.mkdir()
|
||||
|
||||
def entry(self, index, path):
|
||||
return '\t"%d"\n\t{\n\t\t"path"\t\t"%s"\n\t\t"contentid"\t\t"%d"\n\t}\n' % (index, path, 7 + index)
|
||||
|
||||
def test_old_mount_keeps_its_entry_under_the_new_path(self):
|
||||
self.vdf.write_text('"libraryfolders"\n{\n' + self.entry(0, '/root') + self.entry(1, '/mnt/bannerlator-sd') + '}\n')
|
||||
with patch('builtins.print'):
|
||||
library.rename(str(self.steam), '/mnt/bannerlator-sd', '/mnt/droiddeck-sd')
|
||||
text = self.vdf.read_text()
|
||||
self.assertIn('"path"\t\t"/mnt/droiddeck-sd"\n\t\t"contentid"\t\t"8"', text)
|
||||
self.assertNotIn('bannerlator-sd', text)
|
||||
|
||||
def test_old_mount_is_dropped_when_new_path_is_registered(self):
|
||||
self.vdf.write_text('"libraryfolders"\n{\n' + self.entry(0, '/mnt/droiddeck-sd') + self.entry(1, '/mnt/bannerlator-sd') + '}\n')
|
||||
with patch('builtins.print'):
|
||||
library.rename(str(self.steam), '/mnt/bannerlator-sd', '/mnt/droiddeck-sd')
|
||||
text = self.vdf.read_text()
|
||||
self.assertEqual(1, text.count('"path"'))
|
||||
self.assertIn('/mnt/droiddeck-sd', text)
|
||||
|
||||
|
||||
class SteamProbeTest(unittest.TestCase):
|
||||
def test_probe_reads_account_and_licenses_and_releases_handles(self):
|
||||
import ctypes as C
|
||||
|
||||
Reference in new issue
Block a user