Merge latest upstream main before Controller UI integration

# Conflicts:
#	app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
#	app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt
#	app/src/main/java/com/droiddeck/launcher/input/PadBridge.java
#	app/src/main/java/com/droiddeck/launcher/ui/DeckControlsPanel.kt
#	app/src/test/java/com/droiddeck/launcher/input/PadBridgeQamTest.kt
This commit is contained in:
Delete228 committed 2026-11-06 14:37:50 +03:00
commit ba5876bf6d
360 files changed
+34610 -1088

No files matched your search

+8 -2
View File
@@ -93,7 +93,7 @@ def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLine
def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines()
.findAll { it.contains('=') && !it.startsWith('#') }
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler'].collectEntries { name ->
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr'].collectEntries { name ->
def pack = file("build/packs/${name}.tar.zst")
if (!pack.isFile()) {
if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
@@ -205,7 +205,7 @@ android {
}
androidResources {
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~:<dir>droiddeck-xbox:<dir>droiddeck-comet:<dir>directaudio'
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~:<dir>droiddeck-xbox:<dir>droiddeck-comet:<dir>directaudio:<dir>hybris'
}
packagingOptions {
@@ -249,6 +249,12 @@ android {
}
}
// No instrumented tests; the unused androidTest variant breaks the VS Code Kotlin import.
androidComponents {
beforeVariants(selector().all()) { it.androidTest.enable = false }
}
// Vendor binaries remain in the user's SDK directory; never vendor them into Git.
if (vitureSdkDir) {
android.sourceSets.main.jniLibs.srcDir(new File(vitureSdkDir, 'android'))
def stageVitureNotices = tasks.register('stageVitureNotices', Copy) {
@@ -11,6 +11,7 @@ add_library(droiddeckwayland SHARED
src/gpu_clock_pin.c
src/droiddeck_ext.c
src/wl_dmabuf.c
src/wl_android_buffer.c
src/wl_clipboard.c
src/wl_text_input.c
src/wl_toplevel_icon.c
@@ -22,6 +23,7 @@ add_library(droiddeckwayland SHARED
generated/color-management-v1-protocol.c
generated/xdg-shell-protocol.c
generated/linux-dmabuf-v1-protocol.c
generated/wayland-android-protocol.c
generated/viewporter-protocol.c
generated/banner-desktop-v1-protocol.c
generated/presentation-time-protocol.c
@@ -0,0 +1,104 @@
/* Generated by wayland-scanner 1.26.0 */
/*
* Copyright © 2012 Collabora, Ltd.
*
* Permission to use, copy, modify, distribute, and sell this
* software and its documentation for any purpose is hereby granted
* without fee, provided that the above copyright notice appear in
* all copies and that both that copyright notice and this permission
* notice appear in supporting documentation, and that the name of
* the copyright holders not be used in advertising or publicity
* pertaining to distribution of the software without specific,
* written prior permission. The copyright holders make no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied
* warranty.
*
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
* THIS SOFTWARE.
*/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include "wayland-util.h"
#ifndef __has_attribute
# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */
#endif
#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4)
#define WL_PRIVATE __attribute__ ((visibility("hidden")))
#else
#define WL_PRIVATE
#endif
extern const struct wl_interface android_wlegl_handle_interface;
extern const struct wl_interface android_wlegl_server_buffer_handle_interface;
extern const struct wl_interface wl_buffer_interface;
static const struct wl_interface *android_types[] = {
NULL,
NULL,
&android_wlegl_handle_interface,
NULL,
NULL,
&wl_buffer_interface,
NULL,
NULL,
NULL,
NULL,
NULL,
&android_wlegl_handle_interface,
&android_wlegl_server_buffer_handle_interface,
NULL,
NULL,
NULL,
NULL,
&wl_buffer_interface,
NULL,
NULL,
};
static const struct wl_message android_wlegl_requests[] = {
{ "create_handle", "nia", android_types + 2 },
{ "create_buffer", "niiiiio", android_types + 5 },
{ "get_server_buffer_handle", "2niiii", android_types + 12 },
};
WL_PRIVATE const struct wl_interface android_wlegl_interface = {
"android_wlegl", 3,
3, android_wlegl_requests,
0, NULL,
};
static const struct wl_message android_wlegl_handle_requests[] = {
{ "add_fd", "h", android_types + 0 },
{ "destroy", "", android_types + 0 },
};
WL_PRIVATE const struct wl_interface android_wlegl_handle_interface = {
"android_wlegl_handle", 1,
2, android_wlegl_handle_requests,
0, NULL,
};
static const struct wl_message android_wlegl_server_buffer_handle_events[] = {
{ "buffer_fd", "h", android_types + 0 },
{ "buffer_ints", "a", android_types + 0 },
{ "buffer", "nii", android_types + 17 },
{ "linear_layout", "3uu", android_types + 0 },
};
WL_PRIVATE const struct wl_interface android_wlegl_server_buffer_handle_interface = {
"android_wlegl_server_buffer_handle", 3,
0, NULL,
4, android_wlegl_server_buffer_handle_events,
};
@@ -0,0 +1,341 @@
/* Generated by wayland-scanner 1.26.0 */
#ifndef ANDROID_SERVER_PROTOCOL_H
#define ANDROID_SERVER_PROTOCOL_H
#include <stdint.h>
#include <stddef.h>
#include "wayland-server.h"
#ifdef __cplusplus
extern "C" {
#endif
struct wl_client;
struct wl_resource;
/**
* @page page_android The android protocol
* @section page_ifaces_android Interfaces
* - @subpage page_iface_android_wlegl - Android EGL graphics buffer support
* - @subpage page_iface_android_wlegl_handle - An Android native_handle_t object
* - @subpage page_iface_android_wlegl_server_buffer_handle - a server allocated buffer
* @section page_copyright_android Copyright
* <pre>
*
* Copyright © 2012 Collabora, Ltd.
*
* Permission to use, copy, modify, distribute, and sell this
* software and its documentation for any purpose is hereby granted
* without fee, provided that the above copyright notice appear in
* all copies and that both that copyright notice and this permission
* notice appear in supporting documentation, and that the name of
* the copyright holders not be used in advertising or publicity
* pertaining to distribution of the software without specific,
* written prior permission. The copyright holders make no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied
* warranty.
*
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
* THIS SOFTWARE.
* </pre>
*/
struct android_wlegl;
struct android_wlegl_handle;
struct android_wlegl_server_buffer_handle;
struct wl_buffer;
#ifndef ANDROID_WLEGL_INTERFACE
#define ANDROID_WLEGL_INTERFACE
/**
* @page page_iface_android_wlegl android_wlegl
* @section page_iface_android_wlegl_desc Description
*
* Interface used in the Android wrapper libEGL to share
* graphics buffers between the server and the client.
* @section page_iface_android_wlegl_api API
* See @ref iface_android_wlegl.
*/
/**
* @defgroup iface_android_wlegl The android_wlegl interface
*
* Interface used in the Android wrapper libEGL to share
* graphics buffers between the server and the client.
*/
extern const struct wl_interface android_wlegl_interface;
#endif
#ifndef ANDROID_WLEGL_HANDLE_INTERFACE
#define ANDROID_WLEGL_HANDLE_INTERFACE
/**
* @page page_iface_android_wlegl_handle android_wlegl_handle
* @section page_iface_android_wlegl_handle_desc Description
*
* The Android native_handle_t is a semi-opaque object, that
* contains an EGL implementation specific number of int32
* values and file descriptors.
*
* We cannot send a variable size array of file descriptors
* over the Wayland protocol, so we send them one by one.
* @section page_iface_android_wlegl_handle_api API
* See @ref iface_android_wlegl_handle.
*/
/**
* @defgroup iface_android_wlegl_handle The android_wlegl_handle interface
*
* The Android native_handle_t is a semi-opaque object, that
* contains an EGL implementation specific number of int32
* values and file descriptors.
*
* We cannot send a variable size array of file descriptors
* over the Wayland protocol, so we send them one by one.
*/
extern const struct wl_interface android_wlegl_handle_interface;
#endif
#ifndef ANDROID_WLEGL_SERVER_BUFFER_HANDLE_INTERFACE
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_INTERFACE
/**
* @page page_iface_android_wlegl_server_buffer_handle android_wlegl_server_buffer_handle
* @section page_iface_android_wlegl_server_buffer_handle_desc Description
*
* On creation a server_side_buffer object will immediately send
* the "buffer_fd" and "buffer_ints" events needed by the client to
* reference the gralloc buffer, followed by the "buffer" event carrying
* the wl_buffer object.
* @section page_iface_android_wlegl_server_buffer_handle_api API
* See @ref iface_android_wlegl_server_buffer_handle.
*/
/**
* @defgroup iface_android_wlegl_server_buffer_handle The android_wlegl_server_buffer_handle interface
*
* On creation a server_side_buffer object will immediately send
* the "buffer_fd" and "buffer_ints" events needed by the client to
* reference the gralloc buffer, followed by the "buffer" event carrying
* the wl_buffer object.
*/
extern const struct wl_interface android_wlegl_server_buffer_handle_interface;
#endif
#ifndef ANDROID_WLEGL_ERROR_ENUM
#define ANDROID_WLEGL_ERROR_ENUM
enum android_wlegl_error {
ANDROID_WLEGL_ERROR_BAD_HANDLE = 0,
ANDROID_WLEGL_ERROR_BAD_VALUE = 1,
};
#endif /* ANDROID_WLEGL_ERROR_ENUM */
#ifndef ANDROID_WLEGL_ERROR_ENUM_IS_VALID
#define ANDROID_WLEGL_ERROR_ENUM_IS_VALID
/**
* @ingroup iface_android_wlegl
* Validate a android_wlegl error value.
*
* @return true on success, false on error.
* @ref android_wlegl_error
*/
static inline bool
android_wlegl_error_is_valid(uint32_t value, uint32_t version) {
switch (value) {
case ANDROID_WLEGL_ERROR_BAD_HANDLE:
return version >= 1;
case ANDROID_WLEGL_ERROR_BAD_VALUE:
return version >= 1;
default:
return false;
}
}
#endif /* ANDROID_WLEGL_ERROR_ENUM_IS_VALID */
/**
* @ingroup iface_android_wlegl
* @struct android_wlegl_interface
*/
struct android_wlegl_interface {
/**
* Create an Android native_handle_t object
*
* This creator method initialises the native_handle_t object
* with everything except the file descriptors, which have to be
* submitted separately.
* @param ints an array of int32_t
*/
void (*create_handle)(struct wl_client *client,
struct wl_resource *resource,
uint32_t id,
int32_t num_fds,
struct wl_array *ints);
/**
* Create a wl_buffer from the native handle
*
* Pass the Android native_handle_t to the server and attach it
* to the new wl_buffer object.
*
* The android_wlegl_handle object must be destroyed immediately
* after this request.
*/
void (*create_buffer)(struct wl_client *client,
struct wl_resource *resource,
uint32_t id,
int32_t width,
int32_t height,
int32_t stride,
int32_t format,
int32_t usage,
struct wl_resource *native_handle);
/**
* @since 2
*/
void (*get_server_buffer_handle)(struct wl_client *client,
struct wl_resource *resource,
uint32_t id,
int32_t width,
int32_t height,
int32_t format,
int32_t usage);
};
/**
* @ingroup iface_android_wlegl
*/
#define ANDROID_WLEGL_CREATE_HANDLE_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl
*/
#define ANDROID_WLEGL_CREATE_BUFFER_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl
*/
#define ANDROID_WLEGL_GET_SERVER_BUFFER_HANDLE_SINCE_VERSION 2
#ifndef ANDROID_WLEGL_HANDLE_ERROR_ENUM
#define ANDROID_WLEGL_HANDLE_ERROR_ENUM
enum android_wlegl_handle_error {
ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS = 0,
};
#endif /* ANDROID_WLEGL_HANDLE_ERROR_ENUM */
#ifndef ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID
#define ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID
/**
* @ingroup iface_android_wlegl_handle
* Validate a android_wlegl_handle error value.
*
* @return true on success, false on error.
* @ref android_wlegl_handle_error
*/
static inline bool
android_wlegl_handle_error_is_valid(uint32_t value, uint32_t version) {
switch (value) {
case ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS:
return version >= 1;
default:
return false;
}
}
#endif /* ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID */
/**
* @ingroup iface_android_wlegl_handle
* @struct android_wlegl_handle_interface
*/
struct android_wlegl_handle_interface {
/**
*/
void (*add_fd)(struct wl_client *client,
struct wl_resource *resource,
int32_t fd);
/**
*/
void (*destroy)(struct wl_client *client,
struct wl_resource *resource);
};
/**
* @ingroup iface_android_wlegl_handle
*/
#define ANDROID_WLEGL_HANDLE_ADD_FD_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_handle
*/
#define ANDROID_WLEGL_HANDLE_DESTROY_SINCE_VERSION 1
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD 0
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS 1
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER 2
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT 3
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT_SINCE_VERSION 3
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an buffer_fd event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_buffer_fd(struct wl_resource *resource_, int32_t fd)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD, fd);
}
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an buffer_ints event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_buffer_ints(struct wl_resource *resource_, struct wl_array *ints)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS, ints);
}
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an buffer event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_buffer(struct wl_resource *resource_, struct wl_resource *buffer, int32_t format, int32_t stride)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER, buffer, format, stride);
}
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an linear_layout event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_linear_layout(struct wl_resource *resource_, uint32_t drm_format, uint32_t stride)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT, drm_format, stride);
}
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,139 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="android">
<copyright>
Copyright © 2012 Collabora, Ltd.
Permission to use, copy, modify, distribute, and sell this
software and its documentation for any purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
the copyright holders not be used in advertising or publicity
pertaining to distribution of the software without specific,
written prior permission. The copyright holders make no
representations about the suitability of this software for any
purpose. It is provided "as is" without express or implied
warranty.
THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
</copyright>
<interface name="android_wlegl" version="3">
<description summary="Android EGL graphics buffer support">
Interface used in the Android wrapper libEGL to share
graphics buffers between the server and the client.
</description>
<enum name="error">
<entry name="bad_handle" value="0" />
<entry name="bad_value" value="1" />
</enum>
<request name="create_handle">
<description summary="Create an Android native_handle_t object">
This creator method initialises the native_handle_t object
with everything except the file descriptors, which have to be
submitted separately.
</description>
<arg name="id" type="new_id" interface="android_wlegl_handle" />
<arg name="num_fds" type="int" />
<arg name="ints" type="array" summary="an array of int32_t" />
</request>
<request name="create_buffer">
<description summary="Create a wl_buffer from the native handle">
Pass the Android native_handle_t to the server and attach it
to the new wl_buffer object.
The android_wlegl_handle object must be destroyed immediately
after this request.
</description>
<arg name="id" type="new_id" interface="wl_buffer" />
<arg name="width" type="int" />
<arg name="height" type="int" />
<arg name="stride" type="int" />
<arg name="format" type="int" />
<arg name="usage" type="int" />
<arg name="native_handle" type="object" interface="android_wlegl_handle" />
</request>
<request name="get_server_buffer_handle" since="2">
<arg name="id" type="new_id" interface="android_wlegl_server_buffer_handle"/>
<arg name="width" type="int"/>
<arg name="height" type="int"/>
<arg name="format" type="int"/>
<arg name="usage" type="int"/>
</request>
</interface>
<interface name="android_wlegl_handle" version="1">
<description summary="An Android native_handle_t object">
The Android native_handle_t is a semi-opaque object, that
contains an EGL implementation specific number of int32
values and file descriptors.
We cannot send a variable size array of file descriptors
over the Wayland protocol, so we send them one by one.
</description>
<enum name="error">
<entry name="too_many_fds" value="0" />
</enum>
<request name="add_fd">
<arg name="fd" type="fd" />
</request>
<request name="destroy" type="destructor" />
</interface>
<interface name="android_wlegl_server_buffer_handle" version="3">
<description summary="a server allocated buffer">
On creation a server_side_buffer object will immediately send
the "buffer_fd" and "buffer_ints" events needed by the client to
reference the gralloc buffer, followed by the "buffer" event carrying
the wl_buffer object.
</description>
<event name="buffer_fd">
<arg name="fd" type="fd"/>
</event>
<event name="buffer_ints">
<arg name="ints" type="array"/>
</event>
<event name="buffer">
<description summary="the wl_buffer">
This event will be sent after the ints and all the fds have been sent
</description>
<arg name="buffer" type="new_id" interface="wl_buffer"/>
<arg name="format" type="int"/>
<arg name="stride" type="int"/>
</event>
<event name="linear_layout" since="3">
<description summary="verified single-plane linear allocation">
Optional metadata sent before the buffer event. The first buffer_fd
contains one uncompressed 32-bit RGB plane at byte offset zero.
drm_format is its DRM FourCC and stride is its row pitch in bytes.
The server has verified the layout and allocation bounds using
Android mapper metadata, not inferred them from opaque handle ints.
Absence of this event means the layout is unspecified.
</description>
<arg name="drm_format" type="uint"/>
<arg name="stride" type="uint"/>
</event>
</interface>
</protocol>
@@ -79,6 +79,9 @@ static struct ahb_buf *find_buf(uint64_t id) {
}
static void buf_free(struct ahb_buf *ab) {
/* A display release does not prove the compositor's Vulkan reads finished.
* Keep the AHB reference and its DMA-BUF record even if the client is gone. */
if (vkp_completion_unknown()) return;
if (ab->resource) { wl_list_remove(&ab->resource_destroy.link); ab->resource = NULL; }
if (ab->fence_src) { wl_event_source_remove(ab->fence_src); ab->fence_src = NULL; }
if (ab->fence_fd >= 0) { close(ab->fence_fd); ab->fence_fd = -1; }
@@ -103,6 +106,7 @@ static void on_buffer_resource_destroyed(struct wl_listener *l, void *data) {
static void send_deferred_release(struct ahb_buf *ab) {
if (vkp_completion_unknown()) return;
if (ab->release_pending && ab->resource)
droiddeck_release_buffer(ab->surface, ab->resource, ab->surface != NULL, ab->deferred_ns);
ab->release_pending = 0;
+102 -16
View File
@@ -154,6 +154,16 @@ static void on_client_destroyed(struct wl_listener *l, void *data) {
free(ci);
}
/* libwayland's own reasons for dropping a client (a failed read or flush, an invalid object, a
* malformed request) go through wl_log, which on Android writes to a closed stderr. */
static void wl_log_to_session(const char *fmt, va_list ap) {
char line[512];
vsnprintf(line, sizeof(line), fmt, ap);
size_t n = strlen(line);
while (n && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = 0;
droiddeck_log("program", "libwayland: %s", line);
}
static void on_client_created(struct wl_listener *l, void *data) {
struct wl_client *client = data;
struct client_info *ci = calloc(1, sizeof(*ci));
@@ -349,6 +359,62 @@ static void perf_note_release(int64_t since_ns) {
}
/* Completion-unknown is terminal for externally owned DMA-BUF contents too.
* Keeping a VkImage alone cannot stop the client from overwriting its backing
* memory after wl_buffer.release. All paths (including cursors and idle roles)
* use this gate; copied SHM buffers retain their normal release behaviour. */
static struct dmabuf_buffer *get_dmabuf(struct wl_resource *buffer);
static int buffer_release_blocked(struct wl_resource *buffer) {
return vkp_completion_unknown() && get_dmabuf(buffer) != NULL;
}
/* Buffer tracing on a GPU that is not an Adreno (no KGSL node): every attach and release of the
* first 400 buffer events, by wl_buffer id and the line that sent it, and any release of a buffer
* already released and not attached again since (gamescope: "Compositor released us but we were
* not acquired"). Off on an Adreno. */
static int g_buf_trace = -1;
static int g_buf_trace_left = 400;
static uint32_t g_released_ids[128];
static int buf_trace_on(void) {
if (g_buf_trace < 0) g_buf_trace = access("/dev/kgsl-3d0", F_OK) != 0;
return g_buf_trace;
}
static void buf_trace_attach(struct wl_resource *buffer) {
if (!buffer || !buf_trace_on()) return;
uint32_t id = wl_resource_get_id(buffer);
for (int i = 0; i < 128; i++) if (g_released_ids[i] == id) g_released_ids[i] = 0;
if (g_buf_trace_left > 0) { g_buf_trace_left--; droiddeck_log("buffer", "attach id %u", id); }
}
static void buf_trace_release(struct wl_resource *buffer, int line) {
if (!buffer || !buf_trace_on()) return;
uint32_t id = wl_resource_get_id(buffer);
int twice = 0, slot = -1;
for (int i = 0; i < 128; i++) {
if (g_released_ids[i] == id) twice = 1;
if (slot < 0 && g_released_ids[i] == 0) slot = i;
}
if (twice) droiddeck_log("buffer", "DOUBLE release id %u (line %d): released again without an attach", id, line);
else if (slot >= 0) g_released_ids[slot] = id;
if (g_buf_trace_left > 0) { g_buf_trace_left--; droiddeck_log("buffer", "release id %u (line %d)", id, line); }
}
#define send_buffer_release(b) send_buffer_release_at((b), __LINE__)
static void send_buffer_release_at(struct wl_resource *buffer, int line) {
if (!buffer_release_blocked(buffer)) { buf_trace_release(buffer, line); wl_buffer_send_release(buffer); }
}
/* Whether a surface other than `except` is showing this buffer right now. gamescope's Wayland
* backend moves one buffer between its planes (the game's frame goes from the window to a
* subsurface above a black backing while a Steam notification is up): releasing it when the first
* surface lets go handed gamescope a buffer still on screen ("Compositor released us but we were
* not acquired"). Only the last surface to let go releases it. */
static int buffer_shown_elsewhere(struct wl_resource *buffer, const struct surface *except) {
struct surface *o;
if (!buffer) return 0;
wl_list_for_each(o, &g_surfaces, link)
if (o != except && o->dmabuf == buffer) return 1;
return 0;
}
static void pending_release_free(struct pending_release *pr) {
if (pr->surface && pr->surface->releases_pending > 0) pr->surface->releases_pending--;
wl_list_remove(&pr->destroy.link);
@@ -372,7 +438,8 @@ static void arm_release_timer(void) {
int64_t earliest = 0;
if (g_release_timer_fd < 0) return;
wl_list_for_each(pr, &g_pending_releases, link)
if (!earliest || pr->at_ns < earliest) earliest = pr->at_ns;
if (!buffer_release_blocked(pr->buffer) && (!earliest || pr->at_ns < earliest))
earliest = pr->at_ns;
struct itimerspec its = {0};
if (earliest) { its.it_value.tv_sec = earliest / 1000000000LL; its.it_value.tv_nsec = earliest % 1000000000LL; }
timerfd_settime(g_release_timer_fd, TFD_TIMER_ABSTIME, &its, NULL);
@@ -384,8 +451,13 @@ static int on_release_timer(int fd, uint32_t mask, void *data) {
int64_t now = now_ns() + 300000;
if (read(fd, &expirations, sizeof(expirations)) < 0 && errno != EAGAIN) return 0;
wl_list_for_each_safe(pr, tmp, &g_pending_releases, link) {
if (pr->at_ns <= now) {
wl_buffer_send_release(pr->buffer);
if (pr->at_ns <= now && !buffer_release_blocked(pr->buffer)) {
/* Attached again since (to its surface or another): that surface releases it later. */
if (buffer_shown_elsewhere(pr->buffer, NULL)) {
pending_release_free(pr);
continue;
}
send_buffer_release(pr->buffer);
perf_note_release(pr->since_ns);
pending_release_free(pr);
}
@@ -396,9 +468,12 @@ static int on_release_timer(int fd, uint32_t mask, void *data) {
}
static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns) {
/* No allocation or immediate-release fallback is allowed for a quarantined
* DMA-BUF. Existing queued releases stay held; their timer is disarmed. */
if (buffer_release_blocked(buffer)) return;
const int limit = g_fps_limit;
const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns;
if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
int64_t now = now_ns();
int64_t at = s->next_release_ns + interval;
int64_t latest = now + interval * (int64_t)(s->releases_pending + 1);
@@ -406,7 +481,7 @@ static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_
if (at > latest) at = latest;
s->next_release_ns = at;
struct pending_release *pr = calloc(1, sizeof(*pr));
if (!pr) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
if (!pr) { send_buffer_release(buffer); perf_note_release(since_ns); return; }
pr->buffer = buffer;
pr->surface = s;
pr->at_ns = at;
@@ -523,7 +598,10 @@ static void constraints_focus_entered(struct wl_resource *target, struct wl_clie
void dmabuf_buffer_unref(struct dmabuf_buffer *b) {
if (!b || --b->refs > 0) return;
/* Surface/client destruction must not close the backing FDs or free the
* imported-buffer record while a GPU read may still be pending. Retain the
* reference without allocating a quarantine node; process exit reclaims it. */
if (!b || vkp_completion_unknown() || --b->refs > 0) return;
vkp_image_destroy(b->img);
for (int i = 0; i < b->n_planes; i++)
if (b->fd[i] >= 0) close(b->fd[i]);
@@ -622,9 +700,10 @@ static void unmap_toplevel(struct surface *s) {
static void drop_dmabuf(struct surface *s, int paced) {
if (s->dmabuf) {
wl_list_remove(&s->dmabuf_destroy.link);
if (!ahb_swapchain_defer_release(s->dmabuf_buf, s->dmabuf, s, paced)) {
if (buffer_shown_elsewhere(s->dmabuf, s)) {
} else if (!ahb_swapchain_defer_release(s->dmabuf_buf, s->dmabuf, s, paced)) {
if (paced) release_buffer(s, s->dmabuf, now_ns());
else wl_buffer_send_release(s->dmabuf);
else send_buffer_release(s->dmabuf);
}
s->dmabuf = NULL;
}
@@ -733,7 +812,7 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
vkp_image_upload_shm(s->shm_img, wl_shm_buffer_get_data(shm), stride);
wl_shm_buffer_end_access(shm);
}
wl_buffer_send_release(buffer);
send_buffer_release(buffer);
s->buf_w = w;
s->buf_h = h;
s->buf_alpha = wl_shm_buffer_get_format(shm) == WL_SHM_FORMAT_ARGB8888;
@@ -777,7 +856,7 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou
}
if (!s->shm_img) s->shm_img = vkp_image_create_shm(1, 1);
if (s->shm_img) vkp_image_upload_shm(s->shm_img, bgra, 4);
wl_buffer_send_release(buffer);
send_buffer_release(buffer);
s->buf_w = 1;
s->buf_h = 1;
s->buf_alpha = bgra[3] != 0xff;
@@ -880,8 +959,9 @@ void **droiddeck_dmabuf_ahb_slot(struct dmabuf_buffer *b) { return &b->ahb_state
void droiddeck_dmabuf_ref(struct dmabuf_buffer *b) { b->refs++; }
void droiddeck_dmabuf_unref(struct dmabuf_buffer *b) { dmabuf_buffer_unref(b); }
void droiddeck_release_buffer(struct surface *s, struct wl_resource *buffer, int paced, int64_t since_ns) {
if (buffer_release_blocked(buffer)) return;
if (paced && s) release_buffer(s, buffer, since_ns);
else { wl_buffer_send_release(buffer); perf_note_release(since_ns); }
else { send_buffer_release(buffer); perf_note_release(since_ns); }
}
void droiddeck_surface_describe(const struct surface *s, char *out, size_t size) { describe(s, out, size); }
const struct droiddeck_color *droiddeck_surface_color(const struct surface *s) {
@@ -1101,7 +1181,7 @@ static void surface_hold_idle(struct surface *s, struct wl_resource *buffer) {
struct wl_shm_buffer *shm = db ? NULL : wl_shm_buffer_get(buffer);
int64_t px = db ? (int64_t)db->width * db->height
: shm ? (int64_t)wl_shm_buffer_get_width(shm) * wl_shm_buffer_get_height(shm) : 0;
if (px <= 0 || px > CURSOR_MAX_PX) { wl_buffer_send_release(buffer); return; }
if (px <= 0 || px > CURSOR_MAX_PX) { send_buffer_release(buffer); return; }
s->idle_buffer = buffer;
s->idle_buffer_destroy.notify = on_idle_buffer_destroyed;
wl_resource_add_destroy_listener(buffer, &s->idle_buffer_destroy);
@@ -1119,7 +1199,7 @@ static struct wl_resource *surface_take_idle(struct surface *s) {
static void surface_drop_idle(struct surface *s) {
surface_forget_idle_px(s);
struct wl_resource *buffer = surface_take_idle(s);
if (buffer) wl_buffer_send_release(buffer);
if (buffer) send_buffer_release(buffer);
}
static void surface_commit(struct wl_client *c, struct wl_resource *r) {
@@ -1172,11 +1252,12 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
cursor_publish_hidden();
} else {
cursor_publish_buffer(s, buffer);
wl_buffer_send_release(buffer);
send_buffer_release(buffer);
}
} else if (s->role == ROLE_NONE) {
if (buffer) surface_hold_idle(s, buffer);
} else if (db) {
buf_trace_attach(buffer);
take_dmabuf(s, db, buffer);
} else if (shm) {
drop_dmabuf(s, 1);
@@ -1187,7 +1268,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
} else {
drop_dmabuf(s, 1);
s->has_content = 0;
if (buffer) wl_buffer_send_release(buffer);
if (buffer) send_buffer_release(buffer);
}
}
@@ -2437,7 +2518,7 @@ static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint3
struct wl_resource *buffer = surface_take_idle(s);
if (buffer) {
cursor_publish_buffer(s, buffer);
wl_buffer_send_release(buffer);
send_buffer_release(buffer);
} else if (g_cursor_shown == s) {
cursor_publish_shown();
} else if (s->idle_px) {
@@ -3836,6 +3917,10 @@ int droiddeck_wayland_run(void) {
return 1;
}
droiddeck_log("display", "Wayland compositor listening on %s/wayland-0", rt ? rt : "?");
wl_log_set_handler_server(wl_log_to_session);
/* A client that falls behind reading (gamescope at a few fps) must not be dropped for a full
* event buffer: libwayland's default is 4 KB per direction. */
wl_display_set_default_max_buffer_size(display, 1u << 20);
wl_display_add_client_created_listener(display, &g_client_created);
wl_global_create(display, &wl_compositor_interface, 6, NULL, bind_compositor);
@@ -3846,6 +3931,7 @@ int droiddeck_wayland_run(void) {
wl_global_create(display, &wl_output_interface, 4, NULL, bind_output);
wl_global_create(display, &xdg_wm_base_interface, 1, NULL, bind_xdg_wm_base);
wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf);
droiddeck_android_wlegl_init(display);
wl_global_create(display, &wl_seat_interface, 9, NULL, bind_seat);
wl_global_create(display, &banner_desktop_v1_interface, 1, NULL, bind_desktop);
wl_global_create(display, &wp_presentation_interface, 2, NULL, bind_presentation);
@@ -61,3 +61,6 @@ extern volatile int g_no_render_node;
COMPOSITOR_INTERNAL extern dev_t g_main_device;
COMPOSITOR_INTERNAL void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t id);
/* ---- wl_android_buffer.c */
COMPOSITOR_INTERNAL void droiddeck_android_wlegl_init(struct wl_display *display);
@@ -1,5 +1,6 @@
#define _POSIX_C_SOURCE 200809L
#include "effects_chain.h"
#include "blend_pass.h"
#include "vk_loader.h"
#include "vk_present.h"
#include <pthread.h>
@@ -146,6 +147,16 @@ int vkp_effects_active(void) {
return spatial_mode(g_cur.scaling) || effect_count(&g_cur) > 0;
}
int vkp_effects_upscaling(void) {
vkp_effects_sync();
return spatial_mode(g_cur.scaling) && g_cur.scaling != 6;
}
int vkp_effects_postprocessing(void) {
vkp_effects_sync();
return effect_count(&g_cur) > 0;
}
VkFilter vkp_effects_blit_filter(void) {
vkp_effects_sync();
return g_cur.scaling == 2 ? VK_FILTER_NEAREST : VK_FILTER_LINEAR;
@@ -233,6 +244,7 @@ static VkImageView make_view(VkImage img, VkFormat fmt) {
}
static void target_destroy(struct fx_target *t) {
if (t->img) blendp_forget_image(t->img);
if (t->ds) g_vk.FreeDescriptorSets(g_dev, g_dpool, 1, &t->ds);
if (t->fb) g_vk.DestroyFramebuffer(g_dev, t->fb, NULL);
if (t->view) g_vk.DestroyImageView(g_dev, t->view, NULL);
@@ -10,6 +10,9 @@ int vkp_effects_sync(void);
int vkp_effects_active(void);
int vkp_effects_upscaling(void);
int vkp_effects_postprocessing(void);
VkFilter vkp_effects_blit_filter(void);
VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h,
@@ -0,0 +1,47 @@
#ifndef VK_EXTERNAL_IMAGE_SYNC_H
#define VK_EXTERNAL_IMAGE_SYNC_H
#include <vulkan/vulkan.h>
struct vkp_external_client_barrier_pair {
VkImageMemoryBarrier acquire;
VkImageMemoryBarrier release;
};
static inline int vkp_is_external_client_image(int dmabuf, int blit_dst) {
return dmabuf && !blit_dst;
}
/* Client-owned dma-bufs, including AHardwareBuffers, live in GENERAL while
* FOREIGN owns them. Layer pool dma-bufs are destinations with a separate
* acquire/release lifecycle and must never take this source-image path. */
static inline int vkp_external_client_barrier_pair(
VkImage image, uint32_t queue_family, int dmabuf, int blit_dst,
struct vkp_external_client_barrier_pair *pair) {
if (!vkp_is_external_client_image(dmabuf, blit_dst) || !pair) return 0;
const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
pair->acquire = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.oldLayout = VK_IMAGE_LAYOUT_GENERAL,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
.dstQueueFamilyIndex = queue_family,
.image = image,
.subresourceRange = range,
.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT,
};
pair->release = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = queue_family,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
.image = image,
.subresourceRange = range,
.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT,
};
return 1;
}
#endif
+1 -1
View File
@@ -12,7 +12,7 @@
X(CreateAndroidSurfaceKHR) X(DestroySurfaceKHR) X(CreateDevice) \
X(GetDeviceProcAddr) X(EnumerateDeviceExtensionProperties) \
X(GetPhysicalDeviceMemoryProperties) X(GetPhysicalDeviceFormatProperties2) \
X(GetPhysicalDeviceImageFormatProperties2)
X(GetPhysicalDeviceImageFormatProperties2) X(GetPhysicalDeviceProperties2)
#define VK_DEVICE_FUNCS(X) \
X(GetDeviceQueue) X(CreateSwapchainKHR) X(DestroySwapchainKHR) X(GetSwapchainImagesKHR) \
+477 -71
View File
@@ -1,6 +1,7 @@
#define _POSIX_C_SOURCE 200809L
#include "vk_present.h"
#include "vk_loader.h"
#include "vk_external_image_sync.h"
#include "sc_layer.h"
#include "effects_chain.h"
#include "cardboard.h"
@@ -19,6 +20,7 @@
#include <poll.h>
#include <time.h>
#include <pthread.h>
#include <stdarg.h>
#include <android/log.h>
#include <android/hardware_buffer.h>
@@ -38,16 +40,59 @@ struct vkp_image {
int in_general;
VkFormat fmt;
int sampled;
AHardwareBuffer *android_buffer;
};
static ANativeWindow *g_window;
static int g_ahb_import;
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
static int g_dev_state;
static void device_lost(const char *where);
static const char *vk_result_name(VkResult r);
/* Why the compositor cannot present ("" while it can). Logged as a DD_PRESENT_FAULT line, read
* back over JNI, and shown on the session-ended screen instead of a silent black one. */
static char g_fault[256];
static char g_swap_reason[160];
static pthread_mutex_t g_fault_lock = PTHREAD_MUTEX_INITIALIZER;
static void set_fault(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
static void set_fault(const char *fmt, ...) {
char msg[sizeof(g_fault)];
va_list ap;
va_start(ap, fmt);
vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
pthread_mutex_lock(&g_fault_lock);
int same = !strcmp(msg, g_fault);
if (!same) snprintf(g_fault, sizeof(g_fault), "%s", msg);
pthread_mutex_unlock(&g_fault_lock);
if (!same) droiddeck_log("present", "DD_PRESENT_FAULT: %s", msg);
}
static void clear_fault(void) {
pthread_mutex_lock(&g_fault_lock);
int had = g_fault[0] != 0;
g_fault[0] = 0;
pthread_mutex_unlock(&g_fault_lock);
if (had) droiddeck_log("present", "presentation recovered: fault cleared");
}
const char *vkp_fault(void) {
static __thread char copy[sizeof(g_fault)];
pthread_mutex_lock(&g_fault_lock);
snprintf(copy, sizeof(copy), "%s", g_fault);
pthread_mutex_unlock(&g_fault_lock);
if (!copy[0] && g_dev_state == -3)
snprintf(copy, sizeof(copy), "the GPU did not confirm the compositor's work finished; presenting stopped");
return copy;
}
/* The driver that answered for the display, as the driver itself reports it. */
static char g_display_driver[320];
const char *vkp_display_driver(void) { return g_display_driver; }
static VkInstance g_inst;
static VkPhysicalDevice g_pd;
static VkDevice g_dev;
static VkQueue g_queue;
static PFN_vkGetAndroidHardwareBufferPropertiesANDROID g_ahb_properties;
static uint32_t g_qfam;
static VkCommandPool g_pool;
#define MAX_PRESENTS (1 + VKP_FG_MAX_GENERATIONS)
@@ -108,10 +153,22 @@ static void perf_add(int64_t *sum, int64_t *max, unsigned *count, int64_t d) {
if (d > *max) *max = d;
(*count)++;
}
static void quarantine_pending_work(VkResult result, const char *where) {
if (g_dev_state != 1) return;
g_dev_state = -3;
g_base_black = 0;
LOGE("GPU completion unconfirmed (%d in %s): presenting stopped; pending resources retained; "
"restart DroidDeck", (int)result, where);
}
static VkResult timed_wait(VkFence fence, uint64_t timeout) {
if (g_dev_state != 1)
return g_dev_state == -2 ? VK_ERROR_DEVICE_LOST : VK_ERROR_UNKNOWN;
int64_t t0 = perf_now();
VkResult r = g_vk.WaitForFences(g_dev, 1, &fence, VK_TRUE, timeout);
perf_add(&g_perf.wait_ns, &g_perf.wait_max_ns, &g_perf.waits, perf_now() - t0);
if (r != VK_SUCCESS && r != VK_ERROR_DEVICE_LOST)
quarantine_pending_work(r, "fence wait");
return r;
}
@@ -206,7 +263,12 @@ static void reset_sync(void) {
static void destroy_swapchain(void) {
g_base_black = 0;
if (g_dev_state != 1) return;
g_vk.DeviceWaitIdle(g_dev);
VkResult idle = g_vk.DeviceWaitIdle(g_dev);
if (idle != VK_SUCCESS) {
if (idle == VK_ERROR_DEVICE_LOST) device_lost("swapchain idle");
else quarantine_pending_work(idle, "swapchain idle");
return;
}
reset_sync();
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
@@ -296,6 +358,7 @@ int vkp_has_window(void) {
}
int vkp_device_lost(void) { return g_dev_state == -2; }
int vkp_completion_unknown(void) { return g_dev_state == -3; }
void vk_present_set_scale_mode(int mode, int alignment) {
if (mode < VKP_MODE_OFF || mode > VKP_MODE_INTEGER) mode = VKP_MODE_FIT;
@@ -406,11 +469,43 @@ static int has_ext(VkExtensionProperties *e, uint32_t n, const char *name) {
return 0;
}
static int is_proprietary(VkDriverId id) {
return id == VK_DRIVER_ID_ARM_PROPRIETARY || id == VK_DRIVER_ID_QUALCOMM_PROPRIETARY ||
id == VK_DRIVER_ID_IMAGINATION_PROPRIETARY || id == VK_DRIVER_ID_SAMSUNG_PROPRIETARY ||
id == VK_DRIVER_ID_BROADCOM_PROPRIETARY;
}
/* What really loaded: adrenotools falls back to the vendor driver when the requested one fails
* to load (hook_impl.cpp), so the name asked for is not proof of the driver in use. */
static void log_display_driver(void) {
PFN_vkGetPhysicalDeviceProperties2 props2 = g_vk.GetPhysicalDeviceProperties2;
VkPhysicalDeviceDriverProperties drv = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES};
VkPhysicalDeviceProperties2 p2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &drv};
if (!props2) {
snprintf(g_display_driver, sizeof(g_display_driver), "%.200s (driver properties not available)", g_gpu_name);
droiddeck_log("gpu", "display driver: %s", g_display_driver);
return;
}
props2(g_pd, &p2);
int fell_back = g_library_name && is_proprietary(drv.driverID);
snprintf(g_display_driver, sizeof(g_display_driver), "%.80s: %.64s %.96s (driver id %d, Vulkan %u.%u.%u)%s", p2.properties.deviceName,
drv.driverName, drv.driverInfo, (int)drv.driverID, VK_API_VERSION_MAJOR(p2.properties.apiVersion),
VK_API_VERSION_MINOR(p2.properties.apiVersion), VK_API_VERSION_PATCH(p2.properties.apiVersion),
fell_back ? " - FELL BACK to the phone's own driver" : "");
droiddeck_log("gpu", "display driver loaded: %s", g_display_driver);
if (fell_back)
droiddeck_log("gpu", "display driver: %s was requested but the phone's own driver answered; the requested "
"driver did not load (a missing library beside it, or a rejected ABI - see the adrenotools lines)",
g_library_name);
}
static int dev_init(void) {
if (g_dev_state != 0) return g_dev_state == 1 ? 0 : -1;
if (vk_loader_open(g_driver_path, g_library_name, g_native_lib_dir) != 0) {
LOGE("present: vk_loader_open failed"); g_dev_state = -1; return -1;
LOGE("present: vk_loader_open failed"); g_dev_state = -1;
set_fault("no Vulkan driver could be loaded for the display (%s)", g_library_name ? g_library_name : "libvulkan.so");
return -1;
}
const char *inst_exts[3] = {VK_KHR_SURFACE_EXTENSION_NAME,
@@ -441,13 +536,19 @@ static int dev_init(void) {
.enabledExtensionCount = n_inst_exts,
.ppEnabledExtensionNames = inst_exts};
if (g_vk.CreateInstance(&ici, NULL, &g_inst) != VK_SUCCESS) {
LOGE("present: vkCreateInstance failed"); g_dev_state = -1; return -1;
LOGE("present: vkCreateInstance failed"); g_dev_state = -1;
set_fault("vkCreateInstance failed on the display driver (%s)", g_library_name ? g_library_name : "the phone's own");
return -1;
}
vk_loader_load_instance(g_inst);
uint32_t npd = 0;
g_vk.EnumeratePhysicalDevices(g_inst, &npd, NULL);
if (!npd) { LOGE("present: no physical devices"); g_dev_state = -1; return -1; }
if (!npd) {
LOGE("present: no physical devices"); g_dev_state = -1;
set_fault("the display driver exposed no GPU to the app");
return -1;
}
VkPhysicalDevice pds[8]; if (npd > 8) npd = 8;
g_vk.EnumeratePhysicalDevices(g_inst, &npd, pds);
g_pd = VK_NULL_HANDLE;
@@ -459,7 +560,11 @@ static int dev_init(void) {
for (uint32_t q = 0; q < nq; q++)
if (qs[q].queueFlags & VK_QUEUE_GRAPHICS_BIT) { g_pd = pds[i]; g_qfam = q; break; }
}
if (g_pd == VK_NULL_HANDLE) { LOGE("present: no graphics queue"); g_dev_state = -1; return -1; }
if (g_pd == VK_NULL_HANDLE) {
LOGE("present: no graphics queue"); g_dev_state = -1;
set_fault("the display GPU offers no graphics queue");
return -1;
}
{
VkPhysicalDeviceProperties props;
g_vk.GetPhysicalDeviceProperties(g_pd, &props);
@@ -479,6 +584,21 @@ static int dev_init(void) {
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL);
VkExtensionProperties *exts = calloc(ne ? ne : 1, sizeof(*exts));
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts);
if (!g_library_name || !strstr(g_library_name, "freedreno")) {
char names[440];
size_t len = 0;
names[0] = 0;
droiddeck_log("gpu", "device extensions: %u", ne);
for (uint32_t i = 0; i < ne; i++) {
if (len + strlen(exts[i].extensionName) + 2 > sizeof(names)) {
droiddeck_log("gpu", " %s", names);
len = 0;
names[0] = 0;
}
len += (size_t)snprintf(names + len, sizeof(names) - len, "%s%s", len ? " " : "", exts[i].extensionName);
}
if (len) droiddeck_log("gpu", " %s", names);
}
for (unsigned i = 0; i < 4; i++) {
if (has_ext(exts, ne, import_exts[i])) dev_exts[n_dev_exts++] = import_exts[i];
else LOGE("present: driver MISSING %s (dmabuf import will fail)", import_exts[i]);
@@ -492,6 +612,8 @@ static int dev_init(void) {
if (want_sem_fd) dev_exts[n_dev_exts++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
g_ahb_import = has_ext(exts, ne, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME) &&
has_ext(exts, ne, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
/* The present path's own AHB import (#561) stays on the phone's own driver. */
const int want_ahb = !g_library_name && g_ahb_import;
if (g_ahb_import) {
dev_exts[n_dev_exts++] = VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME;
dev_exts[n_dev_exts++] = VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME;
@@ -514,11 +636,17 @@ static int dev_init(void) {
dr = g_vk.CreateDevice(g_pd, &dci, NULL, &g_dev);
}
if (dr != VK_SUCCESS) {
LOGE("present: vkCreateDevice failed"); g_dev_state = -1; return -1;
LOGE("present: vkCreateDevice failed"); g_dev_state = -1;
set_fault("vkCreateDevice failed on %s (%s)", g_gpu_name[0] ? g_gpu_name : "the display GPU", vk_result_name(dr));
return -1;
}
vk_loader_load_device(g_dev);
log_display_driver();
g_vk.GetDeviceQueue(g_dev, g_qfam, 0, &g_queue);
vkp_gpu_busy_device(g_pd, g_dev, g_qfam);
if (want_ahb)
g_ahb_properties = (PFN_vkGetAndroidHardwareBufferPropertiesANDROID)
g_vk.GetDeviceProcAddr(g_dev, "vkGetAndroidHardwareBufferPropertiesANDROID");
if (want_sem_fd) {
g_import_sem_fd = (PFN_vkImportSemaphoreFdKHR)g_vk.GetDeviceProcAddr(g_dev, "vkImportSemaphoreFdKHR");
VkSemaphoreCreateInfo wsci = {.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
@@ -555,6 +683,7 @@ static int dev_init(void) {
g_dev_state = 1;
reset_sync();
init_black_image();
if (g_dev_state != 1) return -1;
vkp_framegen_device_ready(g_dev, g_queue, g_qfam, fg_features != NULL);
return 0;
}
@@ -566,13 +695,15 @@ static int swap_init_locked(void);
static int swap_init(void) {
struct timespec ts;
int64_t now;
if (!g_window) return -1;
if (!g_window || g_dev_state != 1) return -1;
clock_gettime(CLOCK_MONOTONIC, &ts);
now = (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
if (now < g_swap_retry_at_ns) return -1;
g_swap_reason[0] = 0;
if (swap_init_locked() == 0) {
g_swap_retry_at_ns = 0;
g_swap_fail_logged = 0;
clear_fault();
return 0;
}
destroy_swapchain();
@@ -580,11 +711,12 @@ static int swap_init(void) {
if (!g_swap_fail_logged) {
g_swap_fail_logged = 1;
LOGE("present: no swapchain on the screen surface; retrying every 0.5 s");
set_fault("no swapchain on the session screen (%s)", g_swap_reason[0] ? g_swap_reason : "unknown reason");
}
return -1;
}
#define SWLOGE(...) do { if (!g_swap_fail_logged) LOGE(__VA_ARGS__); } while (0)
#define SWLOGE(...) do { snprintf(g_swap_reason, sizeof(g_swap_reason), __VA_ARGS__); if (!g_swap_fail_logged) LOGE(__VA_ARGS__); } while (0)
static void vk_format_short(VkFormat f, char *out, size_t n) {
const char *s = NULL;
@@ -824,10 +956,15 @@ static void init_black_image(void) {
g_vk.EndCommandBuffer(cmd);
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd};
g_vk.ResetFences(g_dev, 1, &g_fence);
if (g_vk.QueueSubmit(g_queue, 1, &si, g_fence) == VK_SUCCESS &&
g_vk.WaitForFences(g_dev, 1, &g_fence, VK_TRUE, 1000000000ULL) == VK_SUCCESS)
g_black_state = 1;
else
VkResult qr = g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
if (qr == VK_SUCCESS) {
VkResult fr = timed_wait(g_fence, 1000000000ULL);
if (fr == VK_SUCCESS) g_black_state = 1;
else if (fr == VK_ERROR_DEVICE_LOST) device_lost("black image");
} else if (qr == VK_ERROR_DEVICE_LOST) {
device_lost("black image submit");
}
if (g_black_state != 1)
droiddeck_log("gpu", "letterbox black image unavailable: the whole output is cleared every copy-path frame");
}
@@ -926,7 +1063,98 @@ struct vkp_image *vkp_image_from_dmabuf(int fd, uint32_t drm_format, uint64_t mo
return vkp_image_import_dmabuf(fd, drm_format, modifier, w, h, stride, offset, 0);
}
int vkp_image_is_dmabuf(const struct vkp_image *img) { return img && img->dmabuf && !img->blit_dst; }
/* Return client sources to FOREIGN after their final read. The consuming paths
* wait for our fence before Wayland can release an ordinary dma-buf or an
* android_wlegl AHardwareBuffer. Producer-fence synchronization is separate from
* these image-layout and ownership transfers. */
static void release_external_client_image(VkCommandBuffer cmd, struct vkp_image *img) {
struct vkp_external_client_barrier_pair pair;
if (!img || !vkp_external_client_barrier_pair(
img->image, g_qfam, img->dmabuf, img->blit_dst, &pair))
return;
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &pair.release);
}
static void release_external_client_draws(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) {
for (int i = 0; i < count; i++) {
int seen = 0;
for (int j = 0; j < i; j++) if (draws[j].img == draws[i].img) { seen = 1; break; }
if (!seen) release_external_client_image(cmd, draws[i].img);
}
}
int vkp_image_is_dmabuf(const struct vkp_image *img) {
return img && vkp_is_external_client_image(img->dmabuf, img->blit_dst);
}
int vkp_android_buffer_supported(void) {
return dev_init() == 0 && g_ahb_properties != NULL;
}
struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer) {
if (!buffer || !vkp_android_buffer_supported()) return NULL;
AHardwareBuffer_Desc desc;
AHardwareBuffer_describe(buffer, &desc);
if (!desc.width || !desc.height || desc.layers != 1 ||
(desc.usage & (AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT | AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE)) ||
!(desc.usage & AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE)) return NULL;
VkAndroidHardwareBufferFormatPropertiesANDROID format = {
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
VkAndroidHardwareBufferPropertiesANDROID props = {
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, .pNext = &format};
VkResult result = g_ahb_properties(g_dev, buffer, &props);
if (result != VK_SUCCESS ||
(format.format != VK_FORMAT_R8G8B8A8_UNORM && format.format != VK_FORMAT_R8G8B8A8_SRGB &&
format.format != VK_FORMAT_B8G8R8A8_UNORM && format.format != VK_FORMAT_B8G8R8A8_SRGB) ||
!props.memoryTypeBits ||
!(format.formatFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT)) {
LOGE("android_wlegl: unsupported Android buffer import (%s, format %d)",
vk_result_name(result), format.format);
return NULL;
}
struct vkp_image *img = calloc(1, sizeof(*img));
if (!img) return NULL;
img->w = (int)desc.width; img->h = (int)desc.height;
img->fmt = format.format; img->dmabuf = 1;
const VkFormatFeatureFlags sampled = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
img->sampled = (format.formatFeatures & sampled) == sampled;
VkExternalMemoryImageCreateInfo external = {
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
VkImageCreateInfo create = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &external,
.imageType = VK_IMAGE_TYPE_2D, .format = img->fmt,
.extent = {desc.width, desc.height, 1}, .mipLevels = 1, .arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | (img->sampled ? VK_IMAGE_USAGE_SAMPLED_BIT : 0),
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
result = g_vk.CreateImage(g_dev, &create, NULL, &img->image);
if (result != VK_SUCCESS) goto fail;
/* AHB image requirements are not queryable before binding. The AHB query supplies them. */
uint32_t memory_type = 0;
while (!(props.memoryTypeBits & (1u << memory_type))) memory_type++;
VkImportAndroidHardwareBufferInfoANDROID import = {
.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .buffer = buffer};
VkMemoryDedicatedAllocateInfo dedicated = {
.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
.pNext = &import, .image = img->image};
VkMemoryAllocateInfo allocate = {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &dedicated,
.allocationSize = props.allocationSize, .memoryTypeIndex = memory_type};
result = g_vk.AllocateMemory(g_dev, &allocate, NULL, &img->mem);
if (result != VK_SUCCESS) goto fail;
result = g_vk.BindImageMemory(g_dev, img->image, img->mem, 0);
if (result != VK_SUCCESS) goto fail;
AHardwareBuffer_acquire(buffer);
img->android_buffer = buffer;
return img;
fail:
LOGE("android_wlegl: Vulkan buffer import failed: %s", vk_result_name(result));
vkp_image_destroy(img);
return NULL;
}
struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t modifier, int w, int h,
uint32_t stride, uint32_t offset, int as_blit_dst) {
@@ -940,7 +1168,27 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
const VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
img->sampled = !as_blit_dst && g_vk.GetPhysicalDeviceImageFormatProperties2 &&
modifier_importable(img->fmt, modifier, sampled_usage);
/* Each new format/modifier/size a client hands over, once, for the graphics report: a colour
* or swizzle mismatch on a non-Adreno driver shows up as the pair it arrived as. */
{
static struct { uint32_t fmt; uint64_t mod; int w, h; } seen[32];
static int nseen;
int known = 0;
for (int i = 0; i < nseen; i++)
if (seen[i].fmt == drm_format && seen[i].mod == modifier && seen[i].w == w && seen[i].h == h) known = 1;
if (!known && nseen < 32) {
seen[nseen].fmt = drm_format; seen[nseen].mod = modifier; seen[nseen].w = w; seen[nseen].h = h; nseen++;
droiddeck_log("gpu", "dmabuf import: %c%c%c%c %s %dx%d stride %u offset %u -> vk format %d, %s%s",
drm_format & 0xff, (drm_format >> 8) & 0xff, (drm_format >> 16) & 0xff, (drm_format >> 24) & 0xff,
vkp_modifier_name(modifier), w, h, stride, offset, (int)img->fmt,
img->sampled ? "sampled" : "copied", as_blit_dst ? ", blit target" : "");
}
}
/* Venus reports a row pitch of 0 for gamescope's 1x1 root buffer, and a zero pitch fails
* vkCreateImage, which left the whole window unshown (David Cimo). One packed, 64-byte aligned
* row is what a linear buffer that small holds. */
if (stride == 0 && modifier == 0) stride = ((uint32_t)w * 4 + 63) & ~63u;
VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride};
VkImageDrmFormatModifierExplicitCreateInfoEXT modInfo = {
.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
@@ -1211,7 +1459,7 @@ struct vkp_image *vkp_image_create_shm(int w, int h) {
}
void vkp_image_upload_shm(struct vkp_image *img, const void *data, int stride) {
if (!img || !img->map || !data) return;
if (g_dev_state != 1 || !img || !img->map || !data) return;
size_t rowbytes = (size_t)img->w * 4;
if ((size_t)stride < rowbytes) rowbytes = (size_t)stride;
for (int y = 0; y < img->h; y++)
@@ -1224,12 +1472,14 @@ int vkp_image_height(const struct vkp_image *img) { return img ? img->h : 0; }
void vkp_image_destroy(struct vkp_image *img) {
if (!img) return;
if (g_dev_state == -3) return; /* completion unknown: retain GPU ownership */
if (g_dev) {
blendp_forget_image(img->image);
if (img->map) g_vk.UnmapMemory(g_dev, img->mem);
if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL);
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
}
if (img->android_buffer) AHardwareBuffer_release(img->android_buffer);
free(img);
}
@@ -1271,17 +1521,99 @@ static int draw_to_scene_blit(const struct vkp_draw *d, int scene_w, int scene_h
return map_draw(d, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, (float)scene_w, (float)scene_h, blit);
}
static int effects_source_draw(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
struct vkp_draw *out) {
if (!draws) return 0;
int opaque_above = 0;
for (int i = n - 1; i >= 0; i--) {
const struct vkp_draw *d = &draws[i];
const struct vkp_image *im = d->img;
if (!im || d->blend || d->dx != 0 || d->dy != 0 || d->dw != scene_w || d->dh != scene_h) {
if (im && !d->blend && d->dw * d->dh > opaque_above) opaque_above = d->dw * d->dh;
continue;
}
if (opaque_above > im->w * im->h) return 0;
if (d->sx != 0 || d->sy != 0 || d->sw <= im->w - 1.0f || d->sw >= im->w + 1.0f ||
d->sh <= im->h - 1.0f || d->sh >= im->h + 1.0f ||
im->w <= 0 || im->h <= 0 || im->w > scene_w || im->h > scene_h ||
(im->w == scene_w && im->h == scene_h) ||
(i + 1 < n && vkp_effects_postprocessing())) return 0;
*out = *d;
out->dw = im->w;
out->dh = im->h;
return i + 1;
}
return 0;
}
static void effects_source_note(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
int input_w, int input_h, int output_w, int output_h) {
static uint64_t previous;
uint64_t key = 14695981039346656037ULL;
const int sizes[] = {scene_w, scene_h, n, input_w, input_h, output_w, output_h};
for (unsigned i = 0; i < sizeof(sizes) / sizeof(sizes[0]); i++)
key = (key ^ (uint32_t)sizes[i]) * 1099511628211ULL;
for (int i = 0; i < n; i++) {
const struct vkp_draw *d = &draws[i];
const int values[] = {d->img ? d->img->w : 0, d->img ? d->img->h : 0, d->dw, d->dh, d->blend,
d->sx != 0 || d->sy != 0 || !d->img || d->sw != d->img->w || d->sh != d->img->h};
for (unsigned j = 0; j < sizeof(values) / sizeof(values[0]); j++)
key = (key ^ (uint32_t)values[j]) * 1099511628211ULL;
}
if (key == previous) return;
previous = key;
droiddeck_log("effects", "input %dx%d -> %dx%d, logical scene %dx%d, %d draws",
input_w, input_h, output_w, output_h, scene_w, scene_h, n);
for (int i = 0; i < n && i < 8; i++) {
const struct vkp_draw *d = &draws[i];
droiddeck_log("effects", "draw %d: buffer %dx%d, source %.1f,%.1f %.1fx%.1f -> scene %d,%d %dx%d, blend %d",
i, d->img ? d->img->w : 0, d->img ? d->img->h : 0,
d->sx, d->sy, d->sw, d->sh, d->dx, d->dy, d->dw, d->dh, d->blend);
}
}
static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkImageBlit *blit, VkImage target,
VkFormat target_fmt, int target_w, int target_h, VkFilter filter) {
const struct vkp_image *im = d->img;
const int external_client = vkp_image_is_dmabuf(im);
if (d->blend && im->sampled &&
blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !im->dmabuf, target, target_fmt, target_w, target_h,
blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !external_client,
target, target_fmt, target_w, target_h,
blit) == 0)
return;
g_vk.CmdBlitImage(cmd, im->image, im->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
g_vk.CmdBlitImage(cmd, im->image,
external_client ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
target, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter);
}
static void effects_overlay_draws(VkCommandBuffer cmd, VkImage result, int result_w, int result_h,
int scene_w, int scene_h, const struct vkp_draw *draws, int n) {
if (n <= 0) return;
VkImageMemoryBarrier b = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = result, .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
0, 0, NULL, 0, NULL, 1, &b);
for (int i = 0; i < n; i++) {
VkImageBlit blit;
if (!draws[i].img || !map_draw(&draws[i], (float)result_w / scene_w, (float)result_h / scene_h,
0, 0, 0, 0, (float)result_w, (float)result_h, &blit)) continue;
record_draw(cmd, &draws[i], &blit, result, SCENE_FMT, result_w, result_h, VK_FILTER_LINEAR);
}
b.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
b.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
b.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
b.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 0, NULL, 1, &b);
}
static void destroy_scene_image(void) {
if (g_scene.img) vkp_effects_forget_image(g_scene.img);
if (g_scene.img) hdrc_forget_image(g_scene.img);
@@ -1412,6 +1744,7 @@ static void device_lost(const char *where) {
vkp_gpu_busy_device_lost();
droiddeck_log("error", "GPU device lost (VK_ERROR_DEVICE_LOST in %s): the compositor has stopped presenting; "
"restart the session", where);
set_fault("the display GPU was lost (VK_ERROR_DEVICE_LOST in %s)", where);
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
g_swapchain = VK_NULL_HANDLE;
@@ -1509,6 +1842,7 @@ static void record_screen_blit(VkCommandBuffer cmd, VkImage src, int src_w, int
static int acquire_image(int k, int first, uint32_t *img, VkResult *ar_out) {
for (int attempt = 0; ; attempt++) {
if (g_dev_state != 1) return -1;
if (!g_swapchain && (!first || swap_init() != 0)) return -1;
const int64_t t_acq = perf_now();
VkResult ar = g_vk.AcquireNextImageKHR(g_dev, g_swapchain, 1000000000ULL, g_acqs[k], VK_NULL_HANDLE, img);
@@ -1518,7 +1852,7 @@ static int acquire_image(int k, int first, uint32_t *img, VkResult *ar_out) {
if (ar == VK_ERROR_OUT_OF_DATE_KHR || ar == VK_ERROR_SURFACE_LOST_KHR) {
droiddeck_log("gpu", "screen surface %s on acquire: rebuilding the swapchain", vk_result_name(ar));
destroy_swapchain();
if (first && attempt == 0) continue;
if (first && attempt == 0 && g_dev_state == 1) continue;
return -1;
}
droiddeck_log("error", "present: acquire %d failed (%s %d)", k, vk_result_name(ar), (int)ar);
@@ -1635,6 +1969,7 @@ static void send_hdr_metadata(const struct droiddeck_color *c) {
static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
const struct vkp_hdr_frame *hf, int *how) {
if (how) *how = 0;
if (g_dev_state < 0) return -1;
vkp_apply_window_request();
sc_layer_hide_base();
check_surface_changed();
@@ -1653,6 +1988,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
: "no HDR frames through the screen swapchain any more: rebuilding it as SDR");
destroy_swapchain();
}
if (g_dev_state != 1) return -1;
g_swap_hdr_want = want_hdr;
uint32_t img = 0;
@@ -1673,6 +2009,20 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
cb = 0;
}
vkp_cardboard_begin_frame();
int input_w = scene_w, input_h = scene_h;
int pass_n = n;
int overlay_start = n;
struct vkp_draw source_draw;
const struct vkp_draw *pass_draws = draws;
const int source_end = fx && !hf && vkp_effects_upscaling()
? effects_source_draw(scene_w, scene_h, draws, n, &source_draw) : 0;
if (source_end) {
input_w = source_draw.dw;
input_h = source_draw.dh;
pass_draws = &source_draw;
pass_n = 1;
overlay_start = source_end;
}
const int deep = hf && n > 0 && fg && g_swap_is_hdr && !hf->tonemap && vkp_framegen_format_ok(FG_HDR_FMT) &&
ensure_img(&g_fgscene, scene_w, scene_h, FG_HDR_FMT,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
@@ -1692,7 +2042,11 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
"into the HDR10 swapchain (%s): banding possible in smooth gradients", sw);
}
}
const int pass = deep || ((fx || fg || cb || (hf && n > 0)) && ensure_scene_image(scene_w, scene_h) == 0);
const int pass = deep || ((fx || fg || cb || (hf && n > 0)) && ensure_scene_image(input_w, input_h) == 0);
const int draw_n = pass ? pass_n : n;
if (pass && fx && !hf && vkp_effects_upscaling())
effects_source_note(scene_w, scene_h, draws, n, input_w, input_h,
(int)(scene_w * g_map.kx + 0.5f), (int)(scene_h * g_map.ky + 0.5f));
VkImage scene_img = deep ? g_fgscene.img : g_scene.img;
const VkFormat scene_fmt = deep ? FG_HDR_FMT : SCENE_FMT;
const VkFilter blit_filter = vkp_effects_blit_filter();
@@ -1718,13 +2072,11 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
int seen = 0;
for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; }
if (seen || !im) continue;
if (im->dmabuf) {
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = im->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
} else if (!im->in_general) {
struct vkp_external_client_barrier_pair pair;
if (vkp_external_client_barrier_pair(
im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) {
bars[nb++] = pair.acquire;
} else if (!im->blit_dst && !im->in_general) {
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
@@ -1743,11 +2095,12 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
int covered = 0;
VkImageBlit cover_blit;
if (!(hf && pass)) {
for (int i = n - 1; i >= 0 && !covered; i--) {
const struct vkp_draw *d = &draws[i];
if (!d->img || d->blend || d->dx > 0 || d->dy > 0 || d->dx + d->dw < scene_w ||
d->dy + d->dh < scene_h) continue;
covered = pass ? draw_to_scene_blit(d, scene_w, scene_h, &cover_blit) : draw_to_blit(d, &cover_blit);
for (int i = draw_n - 1; i >= 0 && !covered; i--) {
const struct vkp_draw *d = pass ? &pass_draws[i] : &draws[i];
const int target_w = pass ? input_w : scene_w, target_h = pass ? input_h : scene_h;
if (!d->img || d->blend || d->dx > 0 || d->dy > 0 || d->dx + d->dw < target_w ||
d->dy + d->dh < target_h) continue;
covered = pass ? draw_to_scene_blit(d, input_w, input_h, &cover_blit) : draw_to_blit(d, &cover_blit);
}
}
const int cleared = covered && (pass || record_bars_clear(cmd, target, &cover_blit));
@@ -1771,20 +2124,22 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
hdr_how = g_swap_is_hdr ? 1 : 2;
drawn = n;
}
for (int i = 0; i < n && !hdr_how; i++) {
for (int i = 0; i < draw_n && !hdr_how; i++) {
VkImageBlit blit;
if (!draws[i].img) continue;
if (pass ? !draw_to_scene_blit(&draws[i], scene_w, scene_h, &blit) : !draw_to_blit(&draws[i], &blit)) continue;
record_draw(cmd, &draws[i], &blit, target, pass ? scene_fmt : g_swap_fmt,
pass ? scene_w : (int)g_extent.width, pass ? scene_h : (int)g_extent.height,
const struct vkp_draw *d = pass ? &pass_draws[i] : &draws[i];
if (!d->img) continue;
if (pass ? !draw_to_scene_blit(d, input_w, input_h, &blit) : !draw_to_blit(d, &blit)) continue;
record_draw(cmd, d, &blit, target, pass ? scene_fmt : g_swap_fmt,
pass ? input_w : (int)g_extent.width, pass ? input_h : (int)g_extent.height,
pass ? VK_FILTER_LINEAR : blit_filter);
drawn++;
}
if (!(pass && fx)) release_external_client_draws(cmd, draws, n);
int ngen = 0;
VkImage gens[VKP_FG_MAX_GENERATIONS] = {VK_NULL_HANDLE};
VkImage result = scene_img;
int rw = scene_w, rh = scene_h;
int rw = input_w, rh = input_h;
if (!pass) {
VkImageMemoryBarrier b_present = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
@@ -1799,7 +2154,10 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
if (fg) { mapped_w = scene_w; mapped_h = scene_h; }
vkp_effects_set_formats(scene_fmt, scene_fmt);
result = vkp_effects_run(cmd, scene_img, scene_w, scene_h, mapped_w, mapped_h, &rw, &rh);
result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, &rw, &rh);
effects_overlay_draws(cmd, result, rw, rh, scene_w, scene_h,
draws ? draws + overlay_start : NULL, n - overlay_start);
release_external_client_draws(cmd, draws, n);
result_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
}
VkImageMemoryBarrier b_general = {
@@ -1831,6 +2189,10 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
if (k > 0) {
VkResult ark;
if (acquire_image(k, 0, &img, &ark) != 0) {
/* Teardown may have retained this frame's pending work, or
* acquire may have reported real device loss. Neither permits
* a completion-marker submit or another fence wait. */
if (g_dev_state != 1) return -1;
droiddeck_log("framegen", "present %d/%d: no swapchain image; the frame ends early", k + 1, presents);
pr = VK_ERROR_OUT_OF_DATE_KHR;
break;
@@ -1862,15 +2224,22 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
pr = g_vk.QueuePresentKHR(g_queue, &pi);
perf_add(&g_perf.present_ns, &g_perf.present_max_ns, &g_perf.presents, perf_now() - t_pres);
if (k < ngen) presented_gen++;
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR || pr == VK_ERROR_DEVICE_LOST) break;
if (pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; }
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) break;
}
if (!fence_submitted) {
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO};
g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
VkResult marker = g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
if (marker != VK_SUCCESS) {
if (marker == VK_ERROR_DEVICE_LOST) device_lost("frame completion submit");
else quarantine_pending_work(marker, "frame completion submit");
return -1; /* no fence was submitted; never wait on its unsignalled state */
}
}
VkResult fr = timed_wait(g_fence, UINT64_MAX);
if (fg) vkp_framegen_presented(presented_gen);
if (fr == VK_ERROR_DEVICE_LOST || pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; }
if (fr != VK_SUCCESS) return -1;
if (fg) vkp_framegen_presented(presented_gen);
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) {
droiddeck_log("gpu", "screen surface %s on present: rebuilding the swapchain", vk_result_name(pr));
destroy_swapchain();
@@ -1937,6 +2306,7 @@ void vkp_reset_first_frame(void) {
void vkp_signal_first_frame(void) {
if (g_first_frame_done) return;
g_first_frame_done = 1;
clear_fault();
droiddeck_on_first_frame();
}
@@ -1950,6 +2320,7 @@ int vkp_update_map(int scene_w, int scene_h) {
return g_map.valid ? 0 : -1;
}
check_surface_changed();
if (g_dev_state != 1) return -1;
if (!g_swapchain && swap_init() != 0) return -1;
update_map(scene_w, scene_h);
return g_map.valid ? 0 : -1;
@@ -1972,7 +2343,7 @@ int vkp_map_draw(const struct vkp_draw *d, int out[8]) {
}
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
if (!src || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
if (wait_fd >= 0) close(wait_fd);
return -1;
}
@@ -1985,17 +2356,21 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(g_cmd, &bi);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
VkImageMemoryBarrier acq[2] = {
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}};
if (!src->dmabuf) {
if (!src_external) {
acq[0].oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq[0].newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
@@ -2009,8 +2384,9 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
g_vk.CmdBlitImage(g_cmd, src->image,
src->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
release_external_client_image(g_cmd, src);
VkImageMemoryBarrier rel = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
@@ -2045,7 +2421,7 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
static struct vkp_image *g_rb;
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
if (!src || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
if (!src || src->blit_dst || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
g_dev_state == -2 || dev_init() != 0)
return -1;
if (g_rb && (g_rb->w != src->w || g_rb->h != src->h)) { vkp_image_destroy(g_rb); g_rb = NULL; }
@@ -2086,11 +2462,15 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(cmd, &bi);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
VkImageMemoryBarrier acq[2] = {
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
@@ -2108,15 +2488,20 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_rb->image, .subresourceRange = range,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT}};
uint32_t done_count = 1;
if (!src_external) {
done[done_count++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT}};
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
}
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 0, NULL, 2, done);
0, 0, NULL, 0, NULL, done_count, done);
release_external_client_image(cmd, src);
g_vk.EndCommandBuffer(cmd);
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd};
g_vk.ResetFences(g_dev, 1, &g_fence);
@@ -2158,13 +2543,31 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
const struct vkp_hdr_frame *hf, int *rw, int *rh) {
if (g_pass.active) vkp_pass_abort();
if (vkp_update_map(scene_w, scene_h) != 0) return -1;
int input_w = scene_w, input_h = scene_h;
int pass_n = n, overlay_start = n;
struct vkp_draw source_draw;
const struct vkp_draw *pass_draws = draws;
const int source_end = !hf && vkp_effects_upscaling()
? effects_source_draw(scene_w, scene_h, draws, n, &source_draw) : 0;
if (source_end) {
input_w = source_draw.dw;
input_h = source_draw.dh;
effects_source_note(scene_w, scene_h, draws, n, input_w, input_h,
(int)(scene_w * g_map.kx + 0.5f), (int)(scene_h * g_map.ky + 0.5f));
pass_draws = &source_draw;
pass_n = 1;
overlay_start = source_end;
} else if (!hf && vkp_effects_upscaling()) {
effects_source_note(scene_w, scene_h, draws, n, input_w, input_h,
(int)(scene_w * g_map.kx + 0.5f), (int)(scene_h * g_map.ky + 0.5f));
}
if (hf) {
if (ensure_img(&g_hdrscene, scene_w, scene_h, HDR_FMT,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,
"HDR composition (picture)") != 0)
return -1;
} else if (ensure_scene_image(scene_w, scene_h) != 0) return -1;
} else if (ensure_scene_image(input_w, input_h) != 0) return -1;
VkCommandBuffer cmd = g_cmds[0];
g_vk.ResetCommandBuffer(cmd, 0);
@@ -2188,13 +2591,11 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
int seen = 0;
for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; }
if (seen || !im) continue;
if (im->dmabuf) {
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = im->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
} else if (!im->in_general) {
struct vkp_external_client_barrier_pair pair;
if (vkp_external_client_barrier_pair(
im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) {
bars[nb++] = pair.acquire;
} else if (!im->blit_dst && !im->in_general) {
bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
@@ -2224,19 +2625,22 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 1, &mb, 0, NULL, 0, NULL);
for (int i = 0; i < n; i++) {
for (int i = 0; i < pass_n; i++) {
VkImageBlit blit;
if (!draws[i].img || !draw_to_scene_blit(&draws[i], scene_w, scene_h, &blit)) continue;
record_draw(cmd, &draws[i], &blit, g_scene.img, SCENE_FMT, scene_w, scene_h,
if (!pass_draws[i].img || !draw_to_scene_blit(&pass_draws[i], input_w, input_h, &blit)) continue;
record_draw(cmd, &pass_draws[i], &blit, g_scene.img, SCENE_FMT, input_w, input_h,
VK_FILTER_LINEAR);
}
if (vkp_effects_active()) vkp_effects_set_formats(VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM);
}
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
g_pass.rw = scene_w; g_pass.rh = scene_h;
g_pass.result = vkp_effects_run(cmd, scene_img, scene_w, scene_h, mapped_w, mapped_h,
g_pass.rw = input_w; g_pass.rh = input_h;
g_pass.result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h,
&g_pass.rw, &g_pass.rh);
effects_overlay_draws(cmd, g_pass.result, g_pass.rw, g_pass.rh, scene_w, scene_h,
draws ? draws + overlay_start : NULL, n - overlay_start);
release_external_client_draws(cmd, draws, n);
g_pass.active = 1;
if (rw) *rw = g_pass.rw;
if (rh) *rh = g_pass.rh;
@@ -2246,8 +2650,9 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) {
if (!g_pass.active) { if (wait_fd >= 0) close(wait_fd); return -1; }
g_pass.active = 0;
if (g_dev_state != 1) { if (wait_fd >= 0) close(wait_fd); return -1; }
VkCommandBuffer cmd = g_cmds[0];
if (!dst || !dst->blit_dst || g_dev_state == -2) {
if (!dst || !dst->blit_dst) {
if (wait_fd >= 0) close(wait_fd);
g_vk.EndCommandBuffer(cmd);
return -1;
@@ -2299,5 +2704,6 @@ int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) {
void vkp_pass_abort(void) {
if (!g_pass.active) return;
g_pass.active = 0;
g_vk.EndCommandBuffer(g_cmds[0]);
if (g_dev_state == 1)
g_vk.EndCommandBuffer(g_cmds[0]);
}
@@ -3,6 +3,8 @@
#include <stdint.h>
#include <stddef.h>
#include <android/native_window.h>
#include <android/hardware_buffer.h>
void vk_present_set_driver(const char *driver_path, const char *library_name,
const char *native_lib_dir);
@@ -22,6 +24,9 @@ void vkp_output_size(int *w, int *h);
struct vkp_image;
int vkp_android_buffer_supported(void);
struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer);
#define VKP_MOD_LINEAR 0x0000000000000000ULL
#define VKP_MOD_QCOM_COMPRESSED 0x0500000000000001ULL
#define VKP_MOD_INVALID 0x00ffffffffffffffULL
@@ -61,6 +66,10 @@ int vkp_ready(void);
int vkp_has_window(void);
int vkp_wait_window_request(int timeout_ms);
int vkp_device_lost(void);
/* Compositor thread only. Submitted reads may still be pending: retain imported
* buffer references and withhold DMA-BUF releases until the app process exits.
* This terminal state is distinct from genuine device loss. */
int vkp_completion_unknown(void);
int vkp_render(int scene_w, int scene_h, const struct vkp_draw *draws, int n);
int vkp_render_plain(int scene_w, int scene_h);
@@ -216,6 +216,24 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCompositorTid(JNIEnv
return (jint)g_comp_tid;
}
/* Why presenting failed ("" while it works), for the session-ended screen and the report. */
JNIEXPORT jstring JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCompositorFault(JNIEnv *env, jclass clazz) {
(void)clazz;
extern const char *vkp_fault(void);
const char *f = vkp_fault();
return (*env)->NewStringUTF(env, f ? f : "");
}
/* The display driver as the driver itself reports it ("" before the compositor's device exists). */
JNIEXPORT jstring JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeDisplayDriver(JNIEnv *env, jclass clazz) {
(void)clazz;
extern const char *vkp_display_driver(void);
const char *d = vkp_display_driver();
return (*env)->NewStringUTF(env, d ? d : "");
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStart(JNIEnv *env, jclass clazz,
jstring xdgRuntimeDir) {
@@ -0,0 +1,216 @@
/* android_wlegl buffer import for the existing libhybris Wayland WSI.
* Protocol: Collabora/libhybris, vendored with its license in protocols/wayland-android.xml.
* Native handles are cloned through Android; opaque vendor integers are never interpreted. */
#include "compositor_internal.h"
#include "droiddeck_ext.h"
#include "wayland-android-server-protocol.h"
#include <android/hardware_buffer.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* Stable native_handle_t ABI, unavailable in the public NDK. */
struct android_native_handle {
int version, num_fds, num_ints;
int data[];
};
struct wire_handle {
struct android_native_handle *handle;
int received;
};
enum { MAX_HANDLE_FDS = 64, MAX_HANDLE_INTS = 256, MAX_BUFFER_SIDE = 8192 };
/* VNDK ABI (not exposed by the NDK): frameworks/native/libs/nativewindow/include/
* vndk/hardware_buffer.h, AHARDWAREBUFFER_CREATE_FROM_HANDLE_METHOD_CLONE = 3.
* Method 1 is not accepted by AHardwareBuffer_createFromHandle. */
enum { CREATE_FROM_HANDLE_CLONE = 3 };
static int (*import_handle)(const AHardwareBuffer_Desc *, const struct android_native_handle *,
int32_t, AHardwareBuffer **);
static const struct android_native_handle *(*native_handle)(const AHardwareBuffer *);
static int valid_description(int32_t width, int32_t height, int32_t stride, int32_t format) {
return width > 0 && height > 0 && width <= MAX_BUFFER_SIDE && height <= MAX_BUFFER_SIDE &&
stride >= width && stride <= MAX_BUFFER_SIDE * 4 &&
(format == 1 || format == 2 || format == 5);
}
static void handle_resource_destroy(struct wl_resource *resource) {
struct wire_handle *wire = wl_resource_get_user_data(resource);
if (!wire) return;
for (int i = 0; i < wire->received; i++) close(wire->handle->data[i]);
free(wire->handle);
free(wire);
}
static void handle_add_fd(struct wl_client *client, struct wl_resource *resource, int32_t fd) {
struct wire_handle *wire = wl_resource_get_user_data(resource);
if (wire->received >= wire->handle->num_fds) {
close(fd);
wl_resource_post_error(resource, ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS,
"more native handle descriptors than declared");
return;
}
wire->handle->data[wire->received++] = fd;
}
static void handle_destroy(struct wl_client *client, struct wl_resource *resource) {
wl_resource_destroy(resource);
}
static const struct android_wlegl_handle_interface handle_impl = {
.add_fd = handle_add_fd, .destroy = handle_destroy,
};
static void create_handle(struct wl_client *client, struct wl_resource *resource,
uint32_t id, int32_t fds, struct wl_array *ints) {
if (fds < 0 || fds > MAX_HANDLE_FDS || ints->size % sizeof(int32_t) ||
ints->size > MAX_HANDLE_INTS * sizeof(int32_t)) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid native handle size");
return;
}
struct wire_handle *wire = calloc(1, sizeof(*wire));
if (!wire) { wl_client_post_no_memory(client); return; }
wire->handle = calloc(1, sizeof(*wire->handle) + (size_t)fds * sizeof(int32_t) + ints->size);
if (!wire->handle) { free(wire); wl_client_post_no_memory(client); return; }
wire->handle->version = sizeof(*wire->handle);
wire->handle->num_fds = fds;
wire->handle->num_ints = (int)(ints->size / sizeof(int32_t));
if (ints->size) memcpy(wire->handle->data + fds, ints->data, ints->size);
struct wl_resource *handle = wl_resource_create(client, &android_wlegl_handle_interface, 1, id);
if (!handle) {
free(wire->handle); free(wire); wl_client_post_no_memory(client); return;
}
wl_resource_set_implementation(handle, &handle_impl, wire, handle_resource_destroy);
}
static void buffer_resource_destroy(struct wl_resource *resource) {
dmabuf_buffer_unref(wl_resource_get_user_data(resource));
}
static struct wl_resource *create_android_buffer(struct wl_client *client, uint32_t id,
AHardwareBuffer *hardware) {
AHardwareBuffer_Desc desc;
AHardwareBuffer_describe(hardware, &desc);
struct vkp_image *image = vkp_image_from_android_buffer(hardware);
if (!image) return NULL;
struct dmabuf_buffer *buffer = calloc(1, sizeof(*buffer));
if (!buffer) { vkp_image_destroy(image); wl_client_post_no_memory(client); return NULL; }
buffer->refs = 1;
buffer->width = (int32_t)desc.width; buffer->height = (int32_t)desc.height;
buffer->format = desc.format == 5 ? DRM_ARGB8888 : desc.format == 2 ? DRM_XBGR8888 : DRM_ABGR8888;
buffer->modifier = MOD_INVALID; /* No DMA-BUF layout was inferred from the native handle. */
buffer->img = image;
for (int i = 0; i < MAX_PLANES; i++) buffer->fd[i] = -1;
struct wl_resource *result = wl_resource_create(client, &wl_buffer_interface, 1, id);
if (!result) { dmabuf_buffer_unref(buffer); wl_client_post_no_memory(client); return NULL; }
wl_resource_set_implementation(result, &dbuf_buffer_impl, buffer, buffer_resource_destroy);
struct client_info *info = client_info_of(client);
if (info) info->dmabuf_buffers++;
return result;
}
static void create_buffer(struct wl_client *client, struct wl_resource *resource, uint32_t id,
int32_t width, int32_t height, int32_t stride, int32_t format,
int32_t usage, struct wl_resource *handle_resource) {
/* Some vendor allocators (Samsung Xclipse) record no stride for GPU-only buffers. The import
* must pass that 0 back unchanged: gralloc validates it against the handle's own value. */
if (!valid_description(width, height, stride ? stride : width, format) ||
!wl_resource_instance_of(handle_resource, &android_wlegl_handle_interface, &handle_impl)) {
droiddeck_log("display", "android_wlegl rejected: %dx%d stride=%d format=%d usage=0x%x",
width, height, stride, format, (uint32_t)usage);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid Android buffer description");
return;
}
struct wire_handle *wire = wl_resource_get_user_data(handle_resource);
if (wire->received != wire->handle->num_fds || !wire->received) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "incomplete native handle");
return;
}
AHardwareBuffer_Desc desc = {
.width = (uint32_t)width, .height = (uint32_t)height, .layers = 1,
.format = (uint32_t)format, .usage = (uint32_t)usage, .stride = (uint32_t)stride};
AHardwareBuffer *hardware = NULL;
int status = import_handle(&desc, wire->handle, CREATE_FROM_HANDLE_CLONE, &hardware);
if (status != 0 || !hardware) {
droiddeck_log("display", "android_wlegl import failed: status=%d %dx%d stride=%d format=%d usage=0x%x fds=%d ints=%d",
status, width, height, stride, format, (uint32_t)usage,
wire->handle->num_fds, wire->handle->num_ints);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE,
"Android rejected the native handle (status %d)", status);
return;
}
struct wl_resource *buffer = create_android_buffer(client, id, hardware);
AHardwareBuffer_release(hardware);
if (!buffer) wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "Vulkan cannot import this buffer");
}
static void get_server_buffer(struct wl_client *client, struct wl_resource *resource, uint32_t id,
int32_t width, int32_t height, int32_t format, int32_t usage) {
if (!format) format = 1;
if (!valid_description(width, height, width, format)) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid buffer allocation request");
return;
}
AHardwareBuffer_Desc desc = {
.width = (uint32_t)width, .height = (uint32_t)height, .layers = 1,
.format = (uint32_t)format,
.usage = (uint32_t)usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT};
AHardwareBuffer *hardware = NULL;
if (AHardwareBuffer_allocate(&desc, &hardware) != 0 || !hardware) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "Android buffer allocation failed");
return;
}
AHardwareBuffer_describe(hardware, &desc);
const struct android_native_handle *handle = native_handle(hardware);
if (!handle || handle->num_fds < 1 || handle->num_fds > MAX_HANDLE_FDS ||
handle->num_ints < 0 || handle->num_ints > MAX_HANDLE_INTS) {
AHardwareBuffer_release(hardware);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "invalid allocated native handle");
return;
}
struct wl_resource *buffer = create_android_buffer(client, 0, hardware);
if (!buffer) {
AHardwareBuffer_release(hardware);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "Vulkan cannot import allocated buffer");
return;
}
struct wl_resource *reply = wl_resource_create(client, &android_wlegl_server_buffer_handle_interface,
wl_resource_get_version(resource), id);
if (!reply) {
wl_resource_destroy(buffer); AHardwareBuffer_release(hardware);
wl_client_post_no_memory(client); return;
}
struct wl_array ints = {.size = (size_t)handle->num_ints * sizeof(int32_t),
.alloc = 0, .data = (void *)(handle->data + handle->num_fds)};
android_wlegl_server_buffer_handle_send_buffer_ints(reply, &ints);
for (int i = 0; i < handle->num_fds; i++)
android_wlegl_server_buffer_handle_send_buffer_fd(reply, handle->data[i]);
/* No linear_layout event: Android's opaque allocation need not be linear. */
android_wlegl_server_buffer_handle_send_buffer(reply, buffer, (int32_t)desc.format, (int32_t)desc.stride);
wl_resource_destroy(reply);
AHardwareBuffer_release(hardware);
}
static const struct android_wlegl_interface wlegl_impl = {
.create_handle = create_handle, .create_buffer = create_buffer,
.get_server_buffer_handle = get_server_buffer,
};
static void bind_android_wlegl(struct wl_client *client, void *data, uint32_t version, uint32_t id) {
struct wl_resource *resource = wl_resource_create(client, &android_wlegl_interface,
version < 3 ? version : 3, id);
if (!resource) { wl_client_post_no_memory(client); return; }
wl_resource_set_implementation(resource, &wlegl_impl, NULL, NULL);
}
void droiddeck_android_wlegl_init(struct wl_display *display) {
if (!vkp_android_buffer_supported()) return;
void *library = dlopen("libnativewindow.so", RTLD_NOW | RTLD_LOCAL);
if (!library) return;
import_handle = dlsym(library, "AHardwareBuffer_createFromHandle");
native_handle = dlsym(library, "AHardwareBuffer_getNativeHandle");
if (!import_handle || !native_handle) { dlclose(library); return; }
/* Keep the platform entry points valid for the compositor's lifetime. */
if (wl_global_create(display, &android_wlegl_interface, 3, NULL, bind_android_wlegl))
droiddeck_log("display", "android_wlegl v3: Android buffer import available");
}
@@ -3,6 +3,7 @@ package com.droiddeck.launcher
import android.app.Application
import com.droiddeck.launcher.runtime.BwrapSpawner
import com.droiddeck.launcher.session.CrashHandler
import com.droiddeck.launcher.session.EnhancedSessionLogShare
import com.droiddeck.launcher.session.GpuClockPin
class App : Application() {
@@ -16,6 +17,7 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
com.droiddeck.launcher.ui.Themes.loadGradient(this)
com.droiddeck.launcher.ui.BuildWatermark.install(this)
HomeApp.trackRecents(this)
@@ -14,10 +14,12 @@ import androidx.compose.runtime.mutableIntStateOf
import com.droiddeck.launcher.gpu.AutoDriverTrial
import com.droiddeck.launcher.gpu.AutoPicks
import com.droiddeck.launcher.gpu.DriverBundle
import com.droiddeck.launcher.core.DeviceSupport
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.SystemVulkanDriver
import com.droiddeck.launcher.gpu.TurnipDriver
import com.droiddeck.launcher.gpu.TurnipReleases
import com.droiddeck.launcher.session.SessionService
@@ -42,7 +44,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
var canRestoreBundled by mutableStateOf(false)
private val releaseProgress = HashMap<String, Int>()
var linuxSelected by mutableStateOf("")
val gpu: GpuInfo = GpuInfo.detect()
var gpu: GpuInfo = GpuInfo.detect()
private set
var mode by mutableStateOf(SessionPrefs.GPU_DRIVERS_AUTO)
var pairRows by mutableStateOf<List<PairRow>>(emptyList())
var pairBusy by mutableStateOf<String?>(null)
@@ -65,13 +68,14 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}
fun state() = GpuDriversState(
gpuName = gpu.displayName(activity), gpuFamily = gpu.family.label(activity), soc = gpu.soc, supportText = gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)),
gpuName = gpu.displayName(activity), gpuFamily = if (gpu.name.contains("Xclipse", ignoreCase = true)) gpu.family.label(gpu.name) else gpu.family.label(activity), soc = gpu.soc, supportText = gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)),
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.ifEmpty { activity.getString(R.string.drivers_not_checked) }, checking = releaseChecking,
linuxRows = linuxRows, linuxSelected = linuxSelected, androidRows = androidRows, androidSelected = androidSelected,
linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, canRestoreBundled = canRestoreBundled,
activeBundle = activeBundle,
activeBundle = activeBundle, powerVr = gpu.family == GpuInfo.Family.POWERVR,
systemPowerVr = SystemVulkanDriver.usesDefault(linuxSelected),
mode = uiMode, display = displaySlot(), runtime = runtimeSlot(),
canRestart = !sessionRunning,
checkedAt = TurnipReleases.cached(activity)?.checkedAt ?: 0L,
@@ -142,7 +146,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
DriverRow(id, it.label, activity.getString(if (linux) R.string.drivers_bundle_sets_display else R.string.drivers_bundle_sets_runtime), true, DriverRow.BUNDLE)
}
linuxRows = LinuxVulkanDriver.optionValues(activity).map { id ->
if (id.isEmpty()) DriverRow("", activity.getString(R.string.gpu_runtime_default), activity.getString(R.string.drivers_runtime_builtin), false)
if (id.isEmpty()) DriverRow("", activity.getString(if (gpu.family == GpuInfo.Family.POWERVR) R.string.gpu_system_powervr else R.string.gpu_runtime_default), activity.getString(R.string.drivers_runtime_builtin), false)
else bundleRow(id, linux = true) ?: DriverRow(
id, lm.getDriverName(id),
listOfNotNull(
@@ -177,6 +181,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
fun summary(): String {
val active = pairRows.firstOrNull { it.active }?.name ?: activeBundle
?: if (SystemVulkanDriver.usesDefault(linuxSelected) && androidSelected == TurnipDriver.AUTO) activity.getString(R.string.gpu_system_powervr) else null
val display = displaySlot().name
val base = when {
uiMode == GPU_MODE_AUTO -> activity.getString(R.string.drivers_summary, activity.getString(R.string.common_auto), active ?: display)
@@ -193,17 +198,28 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val pairs = DriverPairs.from(TurnipReleases.cached(activity))
val recommended = if (QuestExperimental.isSupported()) null else recommendedKey(pairs)
pairRows = pairs.map { p ->
val bundle = p.bundle?.let { installedBundle(it) }
val nad = DriverPairs.isNonAdreno(p.key)
val bundle = p.bundle?.let { if (nad) installedBundleAnyBuild(it) else 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
val update = nad && bundle != null && p.bundle?.let { TurnipReleases.updateAvailable(activity, it) } == true
val builtOn = if (nad) p.bundle?.builtOn.orEmpty() else ""
val version = when {
!nad -> p.version
bundle != null -> bundle.version.ifEmpty { p.version }
builtOn.isNotEmpty() -> activity.getString(R.string.drivers_built_on, builtOn)
else -> p.version
}
PairRow(
key = p.key, name = p.name, version = p.version,
key = p.key, name = p.name, version = version, update = if (update) builtOn.takeIf { it.isNotEmpty() }?.let { activity.getString(R.string.drivers_built_on, it) } ?: p.version else null,
detail = if (!p.complete) activity.getString(R.string.drivers_half_published) else activity.getString(R.string.drivers_pair_size, 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,
active = displayId != null && linuxId != null && SessionPrefs.linuxDriver(activity) == linuxId &&
(SessionPrefs.androidDriver(activity) == displayId ||
// A Mali pair under Auto: the display is the phone's own driver.
(gpu.family.mali && DriverPairs.isNonAdreno(p.key) && SessionPrefs.androidDriver(activity) == TurnipDriver.AUTO)),
)
}.sortedByDescending { it.recommended }
}
@@ -237,7 +253,9 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
private fun releasesStale(): Boolean {
val cached = TurnipReleases.cached(activity)
return cached == null || System.currentTimeMillis() - cached.checkedAt > RELEASE_CHECK_INTERVAL_MS ||
cached.assets.none { it.pair.isNotEmpty() }
cached.assets.none { it.pair.isNotEmpty() } ||
// A list checked before this device's open non-Adreno drivers were offered has none of them.
(!DeviceSupport.adreno() && cached.assets.none { DriverPairs.isNonAdreno(it.pair) })
}
fun ensureAuto(force: Boolean) {
@@ -247,9 +265,33 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
if (force) autoStatus = activity.getString(R.string.drivers_auto_waits_for_session)
return
}
if (gpu.family == GpuInfo.Family.POWERVR && !SystemVulkanDriver.isXclipse()) {
// Auto owns both choices. Manual imports remain available when Manual is selected.
SessionPrefs.ensurePowerVrAutoDrivers(activity)
autoStatus = activity.getString(R.string.drivers_powervr_builtin)
refreshDrivers()
return
}
// A Mali pair set by an earlier build put its PanVK Android half on the display, which fails
// on Mali gralloc. Under Auto the display is the phone's own driver (Android's loader).
if (gpu.family.mali) {
// Builds before 0.5.0-nad1 turned the bridge on under Auto without recording it, and
// left it on for good (it wins over the pair). Under Auto that switch is taken as Auto's.
if (!SessionPrefs.maliFallbackKnown(activity))
SessionPrefs.setMaliFallbackByAuto(activity, if (SessionPrefs.vkBridge(activity)) "bridge" else "")
// A lone imported PanVK Android driver set by hand stalls the display the same way
// ("black screen with the start-up logo"), so under Auto any imported display goes.
val display = SessionPrefs.androidDriver(activity)
if (display != TurnipDriver.AUTO) {
SessionPrefs.setAndroidDriver(activity, TurnipDriver.AUTO)
Log.i(TAG, "auto: Mali display back on the phone's own driver (was $display)")
}
}
AutoDriverTrial.rollbackDue(activity)?.let { trial ->
AutoDriverTrial.rollBack(activity, trial)
autoStatus = activity.getString(R.string.drivers_rolled_back, trial.name)
// The drivers before the trial on a Mali are the runtime's Turnip, which finds no GPU there.
if (gpu.family.mali && maliHasNoRoute()) useMaliFallback(trial.name)
refreshDrivers()
return
}
@@ -263,6 +305,29 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
refreshDrivers()
return
}
if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null &&
com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull() == null) {
releaseChecking = true
autoStatus = activity.getString(R.string.drivers_checking_latest)
Thread({
com.droiddeck.launcher.gpu.VulkanInfo.query()
ui.post {
releaseChecking = false
gpu = GpuInfo.detect()
Log.i(TAG, "auto: Mali named by its driver: ${gpu.name} -> ${gpu.family}")
lastAutoCheck = 0L
ensureAuto(force)
}
}, "gpu-name").start()
return
}
Log.i(TAG, "auto: ${gpu.name} (${gpu.family}) -> " + (DriverPairs.recommendedKey(gpu, emptyList()) ?: "no pair"))
if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null) {
// No PanVK build covers this Mali (e.g. the G1 series, arch v14): the phone's own driver.
autoStatus = useMaliFallback(null)
refreshDrivers()
return
}
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)).lowercase())
return
@@ -275,6 +340,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
runCatching { com.droiddeck.launcher.gpu.VulkanInfo.query() }
ui.post {
releaseChecking = false
if (gpu.family == GpuInfo.Family.POWERVR) gpu = GpuInfo.detect()
refreshReleaseRows()
refreshPairs()
val pairs = DriverPairs.from(TurnipReleases.cached(activity))
@@ -284,10 +350,37 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
when {
row?.active == true -> autoStatus = problem?.let { activity.getString(R.string.drivers_up_to_date_check_failed, it) }
?: activity.getString(R.string.upd_current_status)
gpu.family == GpuInfo.Family.POWERVR && (pair == null || !pair.complete) -> {
// RADV is not published right now: the Xclipse falls back to the system route.
SessionPrefs.ensurePowerVrAutoDrivers(activity)
autoStatus = activity.getString(R.string.drivers_powervr_builtin)
refreshDrivers()
}
gpu.family.mali && (pair == null || !pair.complete) &&
(problem != null || TurnipReleases.cached(activity)?.failed?.contains(TurnipReleases.NON_ADRENO_LABEL) == true) -> {
// The list could not be read: nothing is known to be missing, so a working route stays.
// With no open driver, Venus or bridge the session would run the runtime's Turnip,
// which finds no GPU on a Mali, so the stand-in goes on anyway.
autoStatus = activity.getString(R.string.upd_couldnt_check, problem ?: TurnipReleases.NON_ADRENO_LABEL)
if (maliHasNoRoute()) {
useMaliFallback(null)
refreshDrivers()
}
}
gpu.family.mali && (pair == null || !pair.complete) -> {
// No open driver for this Mali published yet: the phone's own driver until it is.
autoStatus = useMaliFallback(key?.let { DriverPairs.nonAdrenoName(it) } ?: gpu.name)
refreshDrivers()
}
pair == null || !pair.complete ->
autoStatus = problem?.let { activity.getString(R.string.upd_couldnt_check, it) } ?: activity.getString(R.string.drivers_recommended_unpublished)
AutoDriverTrial.release(pair) in AutoDriverTrial.bad(activity) ->
AutoDriverTrial.release(pair) in AutoDriverTrial.bad(activity) -> {
autoStatus = activity.getString(R.string.drivers_skipping_bad, pair.name, pair.version)
if (gpu.family.mali && maliHasNoRoute()) {
useMaliFallback(pair.name)
refreshDrivers()
}
}
SessionState.running -> autoStatus = activity.getString(R.string.drivers_auto_waits_for_session)
holdBack && row?.installed != true -> autoStatus = activity.getString(R.string.drivers_auto_waits_for_network, pair.name, pair.version)
else -> installPair(pair, auto = true)
@@ -296,6 +389,53 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}, "gpu-driver-auto").start()
}
/**
* A Mali with no open driver pair to install ([missing] names the unpublished pair, or null when
* no PanVK build covers this GPU) runs through the phone's own driver: Mali (Venus) where this
* apk carries it (Steam runs on it from the G57 to the G1 series), the Mali bridge otherwise.
* Venus needs Vulkan 1.2 from the phone's driver; the bridge raises a Vulkan 1.1 driver
* (r32p1 on the G77, G78 and G610) for gamescope itself, so there the bridge stands in.
* The Linux driver choice is left alone (it is the bridge's fallback), and Auto
* switches only its own choice off again once a pair is installed ([endMaliFallback]).
*/
private fun useMaliFallback(missing: String?): String {
val oldVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(activity)
val venus = oldVulkan == null && com.droiddeck.launcher.session.VenusComponent.available(activity)
if (oldVulkan != null) Log.i(TAG, "auto: Mali driver reports Vulkan $oldVulkan; Venus needs 1.2, the bridge stands in")
if (venus && !SessionPrefs.venus(activity)) {
SessionPrefs.setVenus(activity, true)
SessionPrefs.setMaliFallbackByAuto(activity, "venus")
} else if (!venus && !SessionPrefs.vkBridge(activity)) {
SessionPrefs.setVkBridge(activity, true)
SessionPrefs.setMaliFallbackByAuto(activity, "bridge")
}
val route = activity.getString(if (venus) R.string.drivers_route_venus else R.string.drivers_route_bridge)
Log.i(TAG, "auto: Mali stand-in route $route (missing pair: ${missing ?: "none covers ${gpu.name}"})")
if (oldVulkan != null) return activity.getString(R.string.drivers_mali_old_vulkan_bridge, missing ?: gpu.name, oldVulkan)
return if (missing == null) activity.getString(R.string.drivers_mali_no_pair_auto, route)
else activity.getString(R.string.drivers_mali_unpublished_auto, missing, route)
}
/** Neither an installed open Linux driver nor Venus or the bridge: the runtime's Turnip would run. */
private fun maliHasNoRoute(): Boolean {
if (SessionPrefs.vkBridge(activity)) return false
// Venus on a Vulkan 1.1 driver does not start (VenusComponent.wanted), so it is no route.
if (SessionPrefs.venus(activity) && com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(activity) == null) return false
val linux = SessionPrefs.linuxDriver(activity)
return linux.isEmpty() || !LinuxVulkanDriverManager(activity).isInstalled(linux)
}
/** A pair is installed for this Mali: the route Auto switched on in its place goes off again. */
private fun endMaliFallback() {
when (SessionPrefs.maliFallbackByAuto(activity)) {
"venus" -> SessionPrefs.setVenus(activity, false)
"bridge" -> SessionPrefs.setVkBridge(activity, false)
else -> return
}
Log.i(TAG, "auto: pair installed; ${SessionPrefs.maliFallbackByAuto(activity)} (Auto's stand-in) off")
SessionPrefs.setMaliFallbackByAuto(activity, "")
}
fun selectPair(key: String) {
if (pairBusy != null) return
val pair = DriverPairs.from(TurnipReleases.cached(activity)).firstOrNull { it.key == key && it.complete } ?: return
@@ -304,7 +444,15 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
installPair(pair, auto = false)
}
private fun installPair(pair: DriverPairs.DriverPair, auto: Boolean) {
/** A newer build of an installed open non-Adreno pair: replaced in place, still selected if it was. */
fun updatePair(key: String) {
if (pairBusy != null) return
val pair = DriverPairs.from(TurnipReleases.cached(activity)).firstOrNull { it.key == key && it.complete } ?: return
val wasActive = pairRows.firstOrNull { it.key == key }?.active == true
installPair(pair, auto = wasActive && mode == SessionPrefs.GPU_DRIVERS_AUTO, force = true, select = wasActive)
}
private fun installPair(pair: DriverPairs.DriverPair, auto: Boolean, force: Boolean = false, select: Boolean = true) {
if (!pair.complete) return
pairBusy = pair.key
pairPercent = 0
@@ -314,7 +462,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val result = runCatching {
val zips = pair.assets
val ids = zips.mapIndexed { i, asset ->
installedIdOf(asset)
(if (force) null else 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
@@ -322,23 +470,39 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
ui.post {
pairBusy = null
pairPercent = -1
result.onSuccess { (displayId, linuxId) ->
result.onSuccess { (pairDisplayId, linuxId) ->
if (!select) {
android.widget.Toast.makeText(activity, activity.getString(R.string.drivers_pair_updated, pair.name), android.widget.Toast.LENGTH_LONG).show()
return@onSuccess
}
if (auto && SessionState.running) {
lastAutoCheck = 0L
autoStatus = activity.getString(R.string.drivers_auto_waits_for_session)
return@onSuccess
}
// A Mali pair under Auto: the compositor draws on the phone's own Mali driver
// (dma-buf, modifiers and AHB all work there) and the guest runs the pair's
// PanVK. Its Android half stays installed for a manual pick.
// The same when the pair is picked by hand: a PanVK Android half on the display
// stalls Mali gralloc ("Waiting for Steam's first frame"); it stays a manual pick
// under "Runtime and display drivers separately".
val displayId = if (gpu.family.mali && DriverPairs.isNonAdreno(pair.key)) TurnipDriver.AUTO else pairDisplayId
val previousDisplay = SessionPrefs.androidDriver(activity)
val previousLinux = SessionPrefs.linuxDriver(activity)
val displayChanged = previousDisplay != displayId
SessionPrefs.setAndroidDriver(activity, displayId)
SessionPrefs.setLinuxDriver(activity, linuxId)
// A route Auto switched on in place of a missing pair goes off now that one is
// here. A Mali bridge or Venus switch the user set stays: it wins for the session
// (DeviceSupport.vkBridge, VenusComponent.wanted) and the pair waits.
if (gpu.family.mali && DriverPairs.isNonAdreno(pair.key)) endMaliFallback()
val restart = displayChanged && CompositorHost.isStarted
if (auto) {
val trial = AutoDriverTrial.current(activity)
val lastGood = trial?.let { setOf(it.previousDisplay, it.previousLinux) } ?: setOf(previousDisplay, previousLinux)
val changed = previousDisplay != displayId || previousLinux != linuxId
SessionPrefs.setGpuAutoInstalled(activity, SessionPrefs.gpuAutoInstalled(activity) + setOf(displayId, linuxId))
// A Mali pair's display is the phone's own driver (AUTO): not a download to own or prune.
SessionPrefs.setGpuAutoInstalled(activity, SessionPrefs.gpuAutoInstalled(activity) + setOf(displayId, linuxId).filter { it.isNotEmpty() && it != TurnipDriver.AUTO })
if (changed) AutoDriverTrial.begin(
activity, AutoDriverTrial.release(pair), "${pair.name} ${pair.version}", displayId, linuxId,
trial?.previousDisplay ?: previousDisplay, trial?.previousLinux ?: previousLinux,
@@ -366,6 +530,9 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
private fun installedBundle(asset: TurnipReleases.Asset): DriverBundle.Bundle? =
TurnipReleases.installedId(activity, asset) { DriverBundle.get(activity, it) != null }?.let { DriverBundle.get(activity, it) }
private fun installedBundleAnyBuild(asset: TurnipReleases.Asset): DriverBundle.Bundle? =
TurnipReleases.installedIdAnyBuild(activity, asset) { DriverBundle.get(activity, it) != null }?.let { DriverBundle.get(activity, it) }
private fun installedIdOf(asset: TurnipReleases.Asset): String? = when {
asset.bundle -> installedBundle(asset)?.id
asset.linux -> TurnipReleases.installedId(activity, asset, LinuxVulkanDriverManager(activity)::isInstalled)
@@ -163,6 +163,8 @@ class FrontEndActivity : ComponentActivity() {
private var tuSysmem by mutableStateOf(false)
private var zinkLazy by mutableStateOf(false)
private var vkBridge by mutableStateOf(false)
private var venus by mutableStateOf(false)
private var venusHostVulkan by mutableStateOf<String?>(null)
private var vkBridgeSafe by mutableStateOf(true)
private var bridgeProtonDxvk by mutableStateOf(false)
private val adrenoGpu by lazy { com.droiddeck.launcher.core.DeviceSupport.adreno() }
@@ -197,6 +199,7 @@ class FrontEndActivity : ComponentActivity() {
private var gameStoresEnabled by mutableStateOf(true)
private var gameStoresSpeedTier by mutableStateOf("fast")
private var navRequest by mutableStateOf<String?>(null)
private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong()
private var storesShowMature by mutableStateOf(false)
private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first())
private var storesView by mutableStateOf(SessionPrefs.DEFAULT_STORES_VIEW)
@@ -208,6 +211,7 @@ class FrontEndActivity : ComponentActivity() {
private var wifiDiscoveryBlocked by mutableStateOf(false)
private var integrationState by mutableStateOf(SteamIntegration.State())
private var integrationFocus by mutableStateOf<SteamIntegration.Feature?>(null)
private var pendingSessionLogExport: File? = null
private val wifiLocationReceiver = object : android.content.BroadcastReceiver() {
override fun onReceive(context: android.content.Context?, intent: Intent?) {
refreshWifiDiscovery()
@@ -266,6 +270,26 @@ class FrontEndActivity : ComponentActivity() {
val then = onSavePicked.also { onSavePicked = null } ?: return@registerForActivityResult
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then)
}
private val pickSessionLogExport = registerForActivityResult(ActivityResultContracts.CreateDocument("application/zip")) { uri ->
val folder = pendingSessionLogExport.also { pendingSessionLogExport = null } ?: return@registerForActivityResult
if (uri != null) {
SessionLogShare.prepare(this, { folder }) { zip ->
if (zip == null) {
android.widget.Toast.makeText(this, R.string.setup_log_export_failed, android.widget.Toast.LENGTH_LONG).show()
} else Thread({
val saved = runCatching {
contentResolver.openOutputStream(uri)?.use { output -> zip.inputStream().buffered().use { it.copyTo(output) } }
?: error("Could not open destination")
}.isSuccess
ui.post {
android.widget.Toast.makeText(this,
if (saved) R.string.setup_log_export_saved else R.string.setup_log_export_failed,
android.widget.Toast.LENGTH_LONG).show()
}
}, "save-session-logs").start()
}
}
}
private fun refreshWifiDiscovery() {
wifiDiscoveryPermission = WifiDiscovery.permissionGranted(this)
@@ -410,6 +434,27 @@ class FrontEndActivity : ComponentActivity() {
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), getString(R.string.main_saves_pick_zip, name), GameSaves.savesDir().parentFile?.parentFile?.path))
}
private fun importAddons(name: String, target: com.droiddeck.launcher.runtime.WowAddons.Target) {
if (SessionState.running) {
android.widget.Toast.makeText(this, R.string.main_addons_close_session, android.widget.Toast.LENGTH_LONG).show()
return
}
onSavePicked = { zip ->
saveAction(getString(R.string.main_addons_importing, name)) {
if (SessionState.running) return@saveAction getString(R.string.main_addons_close_session)
val imported = try {
com.droiddeck.launcher.runtime.WowAddons.import(zip, target)
} catch (_: com.droiddeck.launcher.runtime.WowAddons.TooLarge) {
return@saveAction getString(R.string.main_addons_too_large, zip.name)
}
if (imported.isEmpty()) getString(R.string.main_addons_none, zip.name)
else resources.getQuantityString(R.plurals.main_addons_imported, imported.size, imported.size, target.flavor)
}
}
val downloads = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).path
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), getString(R.string.main_addons_pick_zip, name), downloads))
}
private fun exportSaves(name: String, layout: GameSaves.Layout, game: () -> GameSaves.Game) {
onSavePicked = { dir ->
saveAction(getString(R.string.main_saves_exporting, name)) {
@@ -533,10 +578,15 @@ class FrontEndActivity : ComponentActivity() {
private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList())
private var runningLabel by mutableStateOf<String?>(null)
private var logsEnabled by mutableStateOf(true)
private var enhancedDiagnosticsArmed by mutableStateOf(false)
private var gameDebugLogsEnabled by mutableStateOf(false)
private var gameDebugLogsNeedsRestart by mutableStateOf(false)
private var vacDiagnostics by mutableStateOf(false)
private var agentCommands by mutableStateOf(false)
private var graphicsLogs by mutableStateOf(false)
private var steamGpuDrawing by mutableStateOf(false)
private var bridgeFellBack by mutableStateOf(false)
private var bridgeFellBackMemory by mutableStateOf(false)
private var clearCachedApps by mutableStateOf(false)
private var adbPaired by mutableStateOf(false)
private var memoryHud by mutableStateOf(SessionPrefs.MEMORY_HUD_OFF)
@@ -1026,6 +1076,7 @@ class FrontEndActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
pendingSessionLogExport = savedInstanceState?.getString(KEY_PENDING_SESSION_LOG_EXPORT)?.let(::File)
homeChoiceOpen = savedInstanceState?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
gameSpaceOffered = savedInstanceState?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
if (savedInstanceState == null) readIntegrationIntent(intent)
@@ -1083,7 +1134,7 @@ class FrontEndActivity : ComponentActivity() {
FrontEndScreen(
FrontEndState(
installed = installed, ready = ready, available = available?.version, removalPending = removalPending, runtimeActionsBlocked = runtimeChangesBlocked(),
vkBridge = vkBridge, vkBridgeSafe = vkBridgeSafe, bridgeProtonDxvk = bridgeProtonDxvk, adreno = adrenoGpu,
vkBridge = vkBridge, venus = venus, venusHostVulkan = venusHostVulkan, vkBridgeSafe = vkBridgeSafe, bridgeProtonDxvk = bridgeProtonDxvk, adreno = adrenoGpu,
shortcutPicker = shortcutPicker,
shortcutLibraryScanning = shortcutLibraryScanning,
gameSyncFolder = gameSyncFolder,
@@ -1091,8 +1142,10 @@ class FrontEndActivity : ComponentActivity() {
desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
offlineAccount = offlineAccount, offline = offline,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
enhancedDiagnosticsArmed = enhancedDiagnosticsArmed,
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
graphicsLogs = graphicsLogs, steamGpuDrawing = steamGpuDrawing, bridgeFellBack = bridgeFellBack, bridgeFellBackMemory = bridgeFellBackMemory,
clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit,
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
frameGen = FrameGen.mode(this),
@@ -1162,8 +1215,13 @@ class FrontEndActivity : ComponentActivity() {
onSteamGame = { g ->
if (shortcutPicker) chooseGameShortcut(g)
else {
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g)
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { launchGame(g) }
val request = gameLaunchRequest.incrementAndGet()
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g) {
if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) return@beforeLaunch
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) {
if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g)
}
}
}
},
onEpicLauncher = { openEpicLauncher() },
@@ -1233,9 +1291,18 @@ class FrontEndActivity : ComponentActivity() {
onRemovePackage = { id -> removePackage(id) },
onRuntime = { onRuntimeButton() },
onVkBridge = { on ->
SessionPrefs.setVkBridge(this, on); vkBridge = on
SessionPrefs.setVkBridge(this, on); SessionPrefs.setMaliFallbackByAuto(this, ""); vkBridge = on
if (!on) com.droiddeck.launcher.session.ComponentsManager.settleAutoDxvk(this)
},
onVenus = { on ->
SessionPrefs.setVenus(this, on)
SessionPrefs.setMaliFallbackByAuto(this, "")
venus = on
if (on && !com.droiddeck.launcher.core.DeviceSupport.adreno()) Thread({
com.droiddeck.launcher.gpu.VulkanInfo.query()["api"]?.let { SessionPrefs.setHostVulkanApi(this, it) }
runOnUiThread { venusHostVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(this) }
}, "venus-host-vulkan").start()
},
onVkBridgeSafe = { on -> SessionPrefs.setVkBridgeSafe(this, on); vkBridgeSafe = on },
onBridgeProtonDxvk = { on ->
SessionPrefs.setBridgeProtonDxvk(this, on); bridgeProtonDxvk = on
@@ -1253,6 +1320,13 @@ class FrontEndActivity : ComponentActivity() {
onGameComponents = { game -> openComponents(gameKey = game.profileKey) },
onComponentsTab = { tab -> openComponents(focusContent = true, tab = tab) },
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } },
onAddonImport = { sg, target -> importAddons(sg.name, target) },
onAddonDelete = { target, name ->
saveAction(getString(R.string.main_addons_deleting, name)) {
com.droiddeck.launcher.runtime.WowAddons.delete(target, name)
getString(R.string.main_addons_deleted, name)
}
},
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } },
onPerformance = { refreshCores(); showComponents = false; showMapping = false; showPerformance = true },
onRoms = { showRoms = true },
@@ -1270,6 +1344,15 @@ class FrontEndActivity : ComponentActivity() {
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
},
onEnhancedDiagnostics = {
val requested = !com.droiddeck.launcher.session.EnhancedDiagnostics.isArmed(this)
if (!com.droiddeck.launcher.session.EnhancedDiagnostics.setArmed(this, requested)) {
android.widget.Toast.makeText(
this, R.string.setup_logging_update_failed, android.widget.Toast.LENGTH_LONG,
).show()
}
enhancedDiagnosticsArmed = com.droiddeck.launcher.session.EnhancedDiagnostics.isArmed(this)
},
onGameDebugLogs = {
val changed = SessionPrefs.setGameDebugLogsEnabled(this, !SessionPrefs.gameDebugLogsEnabled(this))
if (!changed) android.widget.Toast.makeText(
@@ -1278,6 +1361,14 @@ class FrontEndActivity : ComponentActivity() {
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
},
onSteamGpuDrawing = {
SessionPrefs.setSteamGpuCompositing(this, !SessionPrefs.steamGpuCompositing(this))
steamGpuDrawing = SessionPrefs.steamGpuCompositing(this)
},
onGraphicsLogs = {
SessionPrefs.setDetailedGraphicsLogs(this, !SessionPrefs.detailedGraphicsLogs(this))
graphicsLogs = SessionPrefs.detailedGraphicsLogs(this)
},
onVacDiagnostics = {
SessionPrefs.setVacDiagnostics(this, !SessionPrefs.vacDiagnostics(this))
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
@@ -1293,11 +1384,40 @@ class FrontEndActivity : ComponentActivity() {
if (limit == com.droiddeck.launcher.core.BackgroundAppLimit.OFF) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this)
},
onShareLogs = {
SessionLogShare.prepare(this, { SessionLogShare.latest(this) }) { zip ->
val folder = SessionLogShare.latest(this)
if (folder == null) {
android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
} else if (com.droiddeck.launcher.session.EnhancedDiagnostics.isActive(this, folder)) {
SessionLogShare.prepareEnhanced(this, { folder }) { zips ->
if (zips.isEmpty()) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
else shareEnhancedArchives(zips)
}
} else {
SessionLogShare.prepare(this, { folder }) { zip ->
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
else startActivity(SessionLogShare.shareIntent(this, zip))
}
}
},
onShareSessionLog = { folder ->
SessionLogShare.prepare(this, { folder }) { zip ->
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
else startActivity(SessionLogShare.shareIntent(this, zip))
}
},
onSaveSessionLog = { folder ->
pendingSessionLogExport = folder
pickSessionLogExport.launch("DroidDeck-${folder.name}.zip")
},
onDeleteSessionLog = { folder, done ->
Thread({
val deleted = runCatching { SessionLogShare.deleteSession(this, folder) }.getOrDefault(false)
ui.post {
if (!deleted) android.widget.Toast.makeText(this, R.string.setup_log_delete_failed, android.widget.Toast.LENGTH_SHORT).show()
done()
}
}, "delete-session-logs").start()
},
onClearLogs = {
Thread({
val cleared = runCatching { SessionArtifacts.clearAll(this) }.getOrDefault(0)
@@ -1468,6 +1588,7 @@ class FrontEndActivity : ComponentActivity() {
onStickClick = { on -> ControllerPrefs.setStickClick(this, on); refreshController() },
onAdaptiveSticks = { on -> ControllerPrefs.setAdaptiveSticks(this, on); refreshController() },
onRumble = { on -> ControllerPrefs.setRumble(this, on); refreshController() },
onDeadZone = { v -> ControllerPrefs.setDeadZone(this, v); refreshController() },
onSteamButton = { on -> ControllerPrefs.setSteamButton(this, on); refreshController() },
onQamButton = { on -> ControllerPrefs.setQamButton(this, on); refreshController() },
onKeyboardButton = { on -> ControllerPrefs.setKeyboardButton(this, on); refreshController() },
@@ -1585,6 +1706,9 @@ class FrontEndActivity : ComponentActivity() {
com.droiddeck.launcher.frontend.GamesFolderMigration.run(this)
SessionLogShare.clear(this)
SessionArtifacts.finishAbandoned(this)
if (SessionPrefs.takeMemoryKillNotice(this)) runOnUiThread {
android.widget.Toast.makeText(this, R.string.session_killed_for_memory, android.widget.Toast.LENGTH_LONG).show()
}
SessionArtifacts.scrubOlder(this)
SessionArtifacts.prune(this)
}, "finish-abandoned").start()
@@ -1802,6 +1926,7 @@ class FrontEndActivity : ComponentActivity() {
super.onSaveInstanceState(outState)
outState.putBoolean(STATE_HOME_CHOICE_OPEN, homeChoiceOpen)
outState.putBoolean(STATE_GAME_SPACE_OFFERED, gameSpaceOffered)
pendingSessionLogExport?.let { outState.putString(KEY_PENDING_SESSION_LOG_EXPORT, it.absolutePath) }
if (slowUsbNever) SessionPrefs.setSlowUsbWarningOff(this)
saveCompatLaunch(outState)
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
@@ -1816,6 +1941,7 @@ class FrontEndActivity : ComponentActivity() {
else @Suppress("DEPRECATION") state.getParcelable(key)
override fun onDestroy() {
gameLaunchRequest.incrementAndGet()
cancelCompatLaunch()
updates.unregister()
super.onDestroy()
@@ -2030,6 +2156,7 @@ class FrontEndActivity : ComponentActivity() {
gpuActions = com.droiddeck.launcher.ui.GpuDriversActions(
onAuto = { on -> drivers.setMode(on) },
onPair = { key -> drivers.selectPair(key) },
onPairUpdate = { key -> drivers.updatePair(key) },
onRefresh = { if (drivers.mode == SessionPrefs.GPU_DRIVERS_AUTO) drivers.ensureAuto(force = true) else drivers.checkLatestTurnip() },
onSelectLinux = { id -> drivers.selectDriver(id, linux = true) },
onSelectAndroid = { id -> drivers.selectDriver(id, linux = false) },
@@ -2580,6 +2707,8 @@ class FrontEndActivity : ComponentActivity() {
tuSysmem = SessionPrefs.tuSysmem(this)
zinkLazy = SessionPrefs.zinkLazy(this)
vkBridge = SessionPrefs.vkBridge(this)
venus = SessionPrefs.venus(this)
venusHostVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(this)
vkBridgeSafe = SessionPrefs.vkBridgeSafe(this)
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
noXalia = SessionPrefs.noXalia(this)
@@ -2602,6 +2731,32 @@ class FrontEndActivity : ComponentActivity() {
SessionPrefs.logsEnabled(this) && SessionPrefs.gameDebugLogsEnabled(this) &&
!SessionPaths.currentSessionLogsRetained(this)
private fun shareEnhancedArchives(zips: List<java.io.File>) {
if (isFinishing || isDestroyed) return
val choices = zips.map { zip ->
val label = when {
zip.name.endsWith("-session.zip") -> getString(R.string.diagnostics_share_session)
zip.name.endsWith("-graphics.zip") -> getString(R.string.diagnostics_share_graphics)
else -> getString(R.string.diagnostics_share_games)
}
label to listOf(zip)
} + (getString(R.string.diagnostics_share_all) to zips)
android.app.AlertDialog.Builder(this)
.setTitle(R.string.diagnostics_share_title)
.setItems(choices.map { it.first }.toTypedArray()) { _, which ->
val selected = choices[which].second
runCatching {
startActivity(if (selected.size == 1) SessionLogShare.shareIntent(this, selected.single())
else SessionLogShare.shareEnhancedIntent(this, selected))
}.onFailure {
android.util.Log.w("SessionLogShare", "could not share latest session logs", it)
android.widget.Toast.makeText(this, R.string.session_logs_share_failed, android.widget.Toast.LENGTH_LONG).show()
}
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
private fun refresh() {
val listX64 = SessionPrefs.activeSteamClientArch(this) == "x86_64"
if (listX64 != steamGamesX64) {
@@ -2626,10 +2781,15 @@ class FrontEndActivity : ComponentActivity() {
frameGenLabel = FrameGen.label(this)
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this)
enhancedDiagnosticsArmed = com.droiddeck.launcher.session.EnhancedDiagnostics.isArmed(this)
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
graphicsLogs = SessionPrefs.detailedGraphicsLogs(this)
steamGpuDrawing = SessionPrefs.steamGpuCompositing(this)
bridgeFellBack = SessionPrefs.bridgeFellBack(this)
bridgeFellBackMemory = SessionPrefs.bridgeFellBackForMemory(this)
clearCachedApps = SessionPrefs.clearCachedApps(this)
adbPaired = WirelessAdbFix.hasSavedPairing(this)
memoryHud = SessionPrefs.memoryHud(this)
@@ -2867,6 +3027,7 @@ class FrontEndActivity : ComponentActivity() {
companion object {
private const val STATE_HOME_CHOICE_OPEN = "home_choice_open"
private const val KEY_PENDING_SESSION_LOG_EXPORT = "pending_session_log_export"
private const val STATE_GAME_SPACE_OFFERED = "game_space_offered"
private const val TAG = "MainActivity"
private const val MEDIA_SETTLE_MS = 1500L
@@ -96,6 +96,7 @@ import com.droiddeck.launcher.input.SteamControllerBle
import com.droiddeck.launcher.input.DirectTouchHold
import com.droiddeck.launcher.input.GestureTouchStreamGate
import com.droiddeck.launcher.input.PointerGestures
import com.droiddeck.launcher.input.PointerSpace
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenDisplays
import com.droiddeck.launcher.input.SecondScreenMode
@@ -207,6 +208,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
private val guestKeysDown = mutableSetOf<Int>()
private val guestButtonsDown = mutableMapOf<Int, Boolean>()
private lateinit var surfaceView: SurfaceView
private lateinit var sessionOverlay: ComposeView
private lateinit var loading: LoadingState
@@ -374,6 +376,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onCancel = { padBridge?.cancelBackQam() },
holds = { backHold },
)
private val mouseBackInput = com.droiddeck.launcher.input.MouseBackInput(
sendRight = { down -> heldButtons.set(32, PointerGestures.BTN_RIGHT, down) },
mouseAttached = ::mouseAttached,
)
private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
private var drawerDirectionDownTime = 0L
private var drawerDirectionDeviceId = -1
@@ -628,6 +634,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Log.i(TAG, "input device $deviceId disconnected")
dropMouseCursor()
backQamInput.onDeviceRemoved(deviceId)
mouseBackInput.onDeviceRemoved(deviceId)
joyConVr?.refresh()
physicalInputBindings?.disconnected(deviceId)
padBridge?.onDeviceRemoved(deviceId)
@@ -708,7 +715,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun dispatchPointerCaptureChanged(hasCapture: Boolean) {
super.dispatchPointerCaptureChanged(hasCapture)
Log.i(TAG, "pointer capture " + if (hasCapture) "on" else "off")
if (!hasCapture) uiHandler.postDelayed(::updatePointerCapture, 250)
if (!hasCapture) {
releaseHeldGuestInput()
uiHandler.postDelayed(::updatePointerCapture, 250)
}
}
}
sessionRoot = root
@@ -720,6 +730,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
bridge.setStickDeadZone(ControllerPrefs.deadZone(this))
bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this))
padBridge = bridge
inputRouter = InputRouter(inputOutput).also { bridge.setInputRouter(it); DeckControls.setRouter(it); physicalInputBindings = com.droiddeck.launcher.input.PhysicalInputBindings(it) }
@@ -775,6 +786,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
.also { root.addView(it) }
touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener)
directTouchHold = DirectTouchHold(PointerGestures.slop(this), pointerListener, directTouchSink)
touchSlop = PointerGestures.slop(this)
threeFingerTap = com.droiddeck.launcher.input.ThreeFingerTap(PointerGestures.slop(this) * 2)
twoFingerGestures = com.droiddeck.launcher.input.TwoFingerGestures(PointerGestures.slop(this) * 2,
object : com.droiddeck.launcher.input.TwoFingerGestures.Listener {
@@ -1248,6 +1260,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionDrawer(drawerOpen || (docked && drawerPinned), drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, docked = docked,
backRequest = drawerBackRequests, onLayerChange = { drawerLayerOpen = it }, a = DrawerActions(
steam = SessionState.mode == SessionService.MODE_STEAM,
systemPowerVr = com.droiddeck.launcher.gpu.SystemVulkanDriver.usesDefault(
SessionPrefs.linuxDriver(this@SessionActivity)),
direct = noSteamSession(),
title = if (SessionState.mode == SessionService.MODE_RUN)
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_title_game) else null,
@@ -1918,7 +1932,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Toast.makeText(this, R.string.session_no_logs, Toast.LENGTH_LONG).show()
return
}
SessionLogShare.prepare(this, { folder }) { zip ->
if (com.droiddeck.launcher.session.EnhancedDiagnostics.isActive(this, folder)) {
SessionLogShare.prepareEnhanced(this, { folder }) { zips ->
if (zips.isEmpty()) {
Toast.makeText(this, R.string.session_logs_archive_failed, Toast.LENGTH_LONG).show()
} else runCatching { shareEnhancedArchives(zips) }
.onFailure {
Log.w(TAG, "could not share current session logs", it)
Toast.makeText(this, R.string.session_logs_share_failed, Toast.LENGTH_LONG).show()
}
}
} else SessionLogShare.prepare(this, { folder }) { zip ->
if (zip == null) {
Toast.makeText(this, R.string.session_logs_archive_failed, Toast.LENGTH_LONG).show()
} else {
@@ -1931,6 +1955,31 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
private fun shareEnhancedArchives(zips: List<File>) {
val choices = zips.map { zip ->
val label = when {
zip.name.endsWith("-session.zip") -> getString(R.string.diagnostics_share_session)
zip.name.endsWith("-graphics.zip") -> getString(R.string.diagnostics_share_graphics)
else -> getString(R.string.diagnostics_share_games)
}
label to listOf(zip)
} + (getString(R.string.diagnostics_share_all) to zips)
android.app.AlertDialog.Builder(this)
.setTitle(R.string.diagnostics_share_title)
.setItems(choices.map { it.first }.toTypedArray()) { _, which ->
val selected = choices[which].second
runCatching {
startActivity(if (selected.size == 1) SessionLogShare.shareIntent(this, selected.single())
else SessionLogShare.shareEnhancedIntent(this, selected))
}.onFailure {
Log.w(TAG, "could not share current session logs", it)
Toast.makeText(this, R.string.session_logs_share_failed, Toast.LENGTH_LONG).show()
}
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
private fun readPrefs() {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
unfoldedControls = SessionPrefs.unfoldedControls(this)
@@ -2260,7 +2309,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun windowOutputSize(width: Int, height: Int): Pair<Int, Int>? {
if (isInPictureInPictureMode || width <= 0 || height <= 0) return null
if (width <= 0 || height <= 0) return null
if (isInPictureInPictureMode) return com.droiddeck.launcher.session.PipPolicy.outputSize(
width, height, SessionState.outputSize.first, SessionState.outputSize.second)
if (bottomGame != null) return when {
SessionState.followScreen ->
com.droiddeck.launcher.session.SessionDisplay.followSize(width, height, false, SessionState.followScale)
@@ -2466,10 +2517,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
closeSecondScreen(reset = true)
updateGlassesScreen()
updateHeadTracker()
if (status == 0) {
Thread({
val hint = sessionExitHint(status)
runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
SessionState.relaunch?.let { next ->
if (status == 0) SessionState.relaunch?.let { next ->
SessionState.relaunch = null
next.putExtra(EXTRA_RETURN_HOME, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
next.putExtra(EXTRA_LINK_TASK, intent.getIntExtra(EXTRA_LINK_TASK, -1))
@@ -2477,14 +2529,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
recreate()
return@runOnUiThread
}
finish()
}
return
}
Thread({
val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: prootFailureHint()
runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
showEnded(status, hint)
}
}, "session-end-hint").start()
@@ -2549,13 +2593,44 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return EndHint(resources.getQuantityString(R.plurals.session_end_runtime_damaged, broken.size, broken.size, broken.first()), repair = true)
}
private fun presentationFault(): String? {
runCatching { com.droiddeck.launcher.wayland.WaylandCompositor.compositorFault() }.getOrNull()
?.takeIf { it.isNotEmpty() }?.let { return it }
val waylandLog = SessionState.logDirectory?.let { File(it, "wayland.log") }?.takeIf { it.isFile } ?: return null
return try {
java.io.RandomAccessFile(waylandLog, "r").use { f ->
val start = maxOf(0L, waylandLog.length() - 256L * 1024)
f.seek(start)
val bytes = ByteArray((waylandLog.length() - start).toInt())
f.readFully(bytes)
var fault: String? = null
String(bytes, Charsets.ISO_8859_1).lineSequence().forEach { line ->
val i = line.indexOf("DD_PRESENT_FAULT: ")
if (i >= 0) fault = line.substring(i + 18).trim().ifEmpty { null }
else if (line.contains("presentation recovered: fault cleared")) fault = null
}
fault
}
} catch (_: Exception) {
null
}
}
private fun prootFailureHint(): EndHint? {
if (SessionState.failureCode != "PROOT_MISSING") return null
val message = SessionState.failureMessage ?: return null
return EndHint(message)
}
private fun presentationFaultHint(): EndHint? = presentationFault()?.let {
EndHint(getString(R.string.session_end_present_fault, it), evenOnSuccess = true)
}
private fun sessionExitHint(status: Int): EndHint? = if (status == 0) presentationFaultHint()
else runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: prootFailureHint()
private fun sessionEndHint(log: File?): EndHint? {
presentationFaultHint()?.let { return it }
if (log == null || !log.isFile) return null
return try {
var enosys = 0
@@ -2582,8 +2657,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val fallback = if (SessionState.steamClientArch == "arm64") getString(R.string.session_end_steam_try_x64) else null
EndHint(listOfNotNull(message, fallback).joinToString("\n"))
} else if (launchFailure == com.droiddeck.launcher.session.SessionLaunchFailure.VULKAN_DEVICE_MISSING) {
val adreno = com.droiddeck.launcher.gpu.GpuInfo.detect().family != com.droiddeck.launcher.gpu.GpuInfo.Family.NOT_ADRENO
EndHint(getString(if (adreno) R.string.session_end_vulkan_device else R.string.session_end_gpu_unsupported))
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
val family = gpu.family
val adreno = family != com.droiddeck.launcher.gpu.GpuInfo.Family.NOT_ADRENO &&
family != com.droiddeck.launcher.gpu.GpuInfo.Family.POWERVR && !family.mali
val message = getString(R.string.session_end_vulkan_device)
EndHint(if (adreno) message else "${gpu.name} (${family.label(gpu.name)})\n$message")
} else if (fexMissing) {
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true)
@@ -2638,6 +2717,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}) return true
}
if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
Log.i(TAG, String.format(java.util.Locale.ROOT, "back key device=%d (%s) source=0x%x flags=0x%x",
event.deviceId, event.device?.name, event.source, event.flags))
}
val mouseToGuest = !pipUi && !screenKeyTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen &&
!SessionState.suspended && !(::loading.isInitialized && (loading.visible || loading.ended))
if (mouseBackInput.onKeyEvent(event, mouseToGuest)) return true
val backToQam = !pipUi && !screenKeyTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
!inputSettingsOpen && !gestureSettingsOpen &&
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
@@ -2985,7 +3071,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val gestureOutput = object : TouchscreenGestures.Output {
override fun moveTo(x: Float, y: Float) {
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
if (pointerLocked) {
if (gesturePointerReady) moveBy(x - gesturePointerX, y - gesturePointerY, true)
} else movePointer(x, y)
@@ -2995,7 +3081,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
cursorVisible = false
}
override fun moveBy(dx: Float, dy: Float, relative: Boolean) {
val rect = drawnRect() ?: return
val rect = (if (pointerLocked) drawnRect() else pointerSurfaceRect()) ?: return
if (relative || pointerLocked) {
val scale = sceneScale(rect)
sendSceneDelta(dx * scale, dy * scale)
@@ -3006,7 +3092,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun prepareRelativePan() {
if (pointerLocked) return
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
moveTo(rect.centerX(), rect.centerY())
}
override fun key(code: Int, down: Boolean) {
@@ -3050,7 +3136,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val scrollListener = object : ScrollTouchGestures.Listener {
override fun onMove(x: Float, y: Float) {
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
val cx = x.coerceIn(rect.left, rect.right)
val cy = y.coerceIn(rect.top, rect.bottom)
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, outputView().width), InputSpace.y(cy, outputView().height))
@@ -3060,7 +3146,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
heldButtons.set(1, button, pressed)
}
override fun onScroll(dx: Float, dy: Float) {
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
val out = SessionState.outputSize
scrollRestX += dx * out.first / rect.width()
scrollRestY += dy * out.second / rect.height()
@@ -3079,7 +3165,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onScrollStart() {
scrollRestX = 0f
scrollRestY = 0f
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
val x = rect.left + rect.width() * PAD_SCROLL_POINTER_X
WaylandCompositor.nativeSendPointer(1, InputSpace.x(x, outputView().width), InputSpace.y(rect.centerY(), outputView().height))
cursorVisible = false
@@ -3092,7 +3178,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onNavigate() {
cursorVisible = false
}
override fun scrollSpeed(): Float = (drawnRect()?.height() ?: 0f) * PAD_SCROLL_HEIGHTS_PER_S
override fun scrollSpeed(): Float = (pointerSurfaceRect()?.height() ?: 0f) * PAD_SCROLL_HEIGHTS_PER_S
}
private fun padMouseMode(): Boolean {
@@ -3115,7 +3201,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
(routedTouchMode == SessionPrefs.TOUCH_AUTO || routedTouchMode == SessionPrefs.TOUCH_DIRECT) && padMouseMode()
private fun fingerScroll(dx: Float, dy: Float) {
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
val out = SessionState.outputSize
scrollRestX += dx * out.first / rect.width() * AXIS_UNITS_PER_PIXEL
scrollRestY += dy * out.second / rect.height() * AXIS_UNITS_PER_PIXEL
@@ -3138,7 +3224,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (!WaylandCompositor.nativeCursorInputPos(cursorPosBuf)) return
val x = cursorPosBuf[0] / InputSpace.WIDTH.toFloat() * outputView().width
val y = cursorPosBuf[1] / InputSpace.HEIGHT.toFloat() * outputView().height
if (rect.contains(x, y)) touchpad.place(x, y)
touchpad.place(x.coerceIn(rect.left, rect.right), y.coerceIn(rect.top, rect.bottom))
}
private fun moveLockedPointer(x: Float, y: Float) {
@@ -3150,7 +3236,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun movePointer(x: Float, y: Float, fromMouse: Boolean = false) {
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
val cx = x.coerceIn(rect.left, rect.right)
val cy = y.coerceIn(rect.top, rect.bottom)
WaylandCompositor.nativeSendPointer(1, InputSpace.x(cx, outputView().width), InputSpace.y(cy, outputView().height))
@@ -3555,7 +3641,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (width <= 0f || height <= 0f) return
val nx = (x / width).coerceIn(0f, 1f)
val ny = (y / height).coerceIn(0f, 1f)
val rect = drawnRect() ?: return
val rect = pointerSurfaceRect() ?: return
val px = rect.left + nx * rect.width()
val py = rect.top + ny * rect.height()
WaylandCompositor.nativeSendPointer(1, InputSpace.x(px, outputView().width), InputSpace.y(py, outputView().height))
@@ -3703,7 +3789,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun sendSceneButton(code: Int, down: Boolean) {
val writer = if (evdevMouseActive) mouseWriter else null
val raw = if (down) evdevMouseActive.also { guestButtonsDown[code] = it }
else guestButtonsDown.remove(code) ?: evdevMouseActive
val writer = if (raw) mouseWriter else null
if (writer != null) writer.writeMouseButton(code.toShort(), down)
else WaylandCompositor.nativeSendSceneInput(3, code, if (down) 1 else 0)
}
@@ -3741,10 +3829,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return android.graphics.RectF(left, top, left + drawnW, top + drawnH)
}
/**
* Where the pointer can travel on this view. With the glasses owning the output the view is
* not showing the picture, so the whole view is the touchpad; using the letterboxed picture
* rect there would leave the pointer unable to reach the scene edges.
*/
private fun pointerSurfaceRect(): android.graphics.RectF? {
val view = outputView()
return PointerSpace.area(view.width, view.height, glassesOutputActive, drawnRect())
}
private var ignoreGameTouch = false
private var lockedTouchTurns = false
private var touchEditorOpen by mutableStateOf(false)
private var lockedSwipeUsed = false
private var touchSlop = 0f
private var lockedSwipeX = 0f
private var lockedSwipeY = 0f
private var dismissTouch = false
@@ -3789,15 +3887,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
com.droiddeck.launcher.input.TouchRouter.Route.SCROLL -> scrollTouch.onTouch(event)
else -> {
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
val inPicture = drawnRect()?.let { !topPictureMapped || it.contains(event.x, event.y) } ?: false
lockedTouchTurns = programLocksPointer() && inPicture && route != com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD
}
if (com.droiddeck.launcher.input.TouchRouter.steamKeyboardZone(snapshot)) {
val wasActive = threeFingerTap.active
if (threeFingerTap.onTouch(event)) padBridge?.triggerSteamKeyboard()
if (threeFingerTap.active && !wasActive) {
if (route == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD || lockedTouchTurns) touchpad.cancel()
if (route == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD) touchpad.cancel()
else {
directTouchHold.cancel()
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
@@ -3805,8 +3899,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
if (threeFingerTap.active || wasActive) return true
}
if (route == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD || lockedTouchTurns) {
val rect = drawnRect() ?: return false
if (route == com.droiddeck.launcher.input.TouchRouter.Route.TOUCHPAD) {
val rect = (if (pointerLocked) drawnRect() else pointerSurfaceRect()) ?: return false
if (touchpad.bounds != rect) {
val fresh = touchpad.bounds.width() <= 1f
touchpad.bounds = rect
@@ -3859,8 +3953,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun forwardTouch(event: MotionEvent, rect: android.graphics.RectF): Boolean {
val swipeX = lockedSwipeX
val swipeY = lockedSwipeY
lockedSwipeX = event.x
lockedSwipeY = event.y
if (programLocksPointer() && event.actionMasked == MotionEvent.ACTION_MOVE && !lockedSwipeUsed &&
abs(event.x - swipeX) <= touchSlop && abs(event.y - swipeY) <= touchSlop) return true
val anchor = if (event.actionMasked == MotionEvent.ACTION_POINTER_UP && event.actionIndex == 0 && event.pointerCount > 1) 1 else 0
lockedSwipeX = event.getX(anchor)
lockedSwipeY = event.getY(anchor)
if ((event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) && lockedSwipeUsed) {
lockedSwipeUsed = false
directTouchHold.cancel()
@@ -3892,14 +3989,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (evdevMouseActive) sendMouseDelta(event.x, event.y) else movePointer(event.x, event.y, fromMouse = true)
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {
if (evdevMouseActive) sendMouseDelta(event.x, event.y) else movePointer(event.x, event.y, fromMouse = true)
val button = when (event.actionButton) {
MotionEvent.BUTTON_SECONDARY -> PointerGestures.BTN_RIGHT
MotionEvent.BUTTON_TERTIARY -> PointerGestures.BTN_MIDDLE
MotionEvent.BUTTON_BACK -> BTN_SIDE
MotionEvent.BUTTON_FORWARD -> BTN_EXTRA
else -> PointerGestures.BTN_LEFT
}
heldButtons.set(8, button, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS)
guestMouseButton(event.actionButton)?.let { heldButtons.set(8, it, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) }
}
MotionEvent.ACTION_SCROLL -> {
val v = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
@@ -3914,7 +4004,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun isHardwareMouse(d: InputDevice?): Boolean =
d != null && !d.isVirtual && (d.supportsSource(InputDevice.SOURCE_MOUSE) || d.supportsSource(InputDevice.SOURCE_MOUSE_RELATIVE))
private fun mouseAttached(): Boolean = InputDevice.getDeviceIds().any { isHardwareMouse(InputDevice.getDevice(it)) }
/** Android also sends the Back and Forward buttons as key events, so they are handled as keys. */
private fun guestMouseButton(actionButton: Int): Int? = when (actionButton) {
MotionEvent.BUTTON_SECONDARY -> PointerGestures.BTN_RIGHT
MotionEvent.BUTTON_TERTIARY -> PointerGestures.BTN_MIDDLE
MotionEvent.BUTTON_BACK, MotionEvent.BUTTON_FORWARD -> null
else -> PointerGestures.BTN_LEFT
}
private fun mouseAttached(): Boolean = InputDevice.getDeviceIds().any { id ->
val d = InputDevice.getDevice(id)
isHardwareMouse(d) && d?.supportsSource(InputDevice.SOURCE_TOUCHPAD) != true
}
private fun relativeMouseAttached(): Boolean = !isInMultiWindowMode && !glassesOutputActive && InputDevice.getDeviceIds().any { id ->
val d = InputDevice.getDevice(id)
@@ -4012,14 +4113,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
moveCapturedMouse(dx, dy)
}
}
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {
val button = when (event.actionButton) {
MotionEvent.BUTTON_SECONDARY -> PointerGestures.BTN_RIGHT
MotionEvent.BUTTON_TERTIARY -> PointerGestures.BTN_MIDDLE
else -> PointerGestures.BTN_LEFT
}
heldButtons.set(8, button, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS)
}
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE ->
guestMouseButton(event.actionButton)?.let { heldButtons.set(8, it, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) }
MotionEvent.ACTION_SCROLL -> {
val v = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
if (v != 0f) sendSceneWheel(-Math.round(v))
@@ -4205,6 +4300,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun keyboardCoversPad() =
SessionState.mode == SessionService.MODE_STEAM && AgentGuest.steamKeyboard
private fun releaseHeldGuestInput() {
mouseBackInput.cancel()
heldButtons.release(1 or 2 or 8 or 16)
guestKeysDown.toList().forEach { sendGuestKey(it, false) }
heldKeys.release(8)
}
private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1) {
if (down && pipUi) return
val code = if (key == KEY_RIGHTCTRL && SessionState.mode == SessionService.MODE_DESKTOP) KEY_LEFTCTRL else key
@@ -4426,6 +4528,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
(getSystemService(INPUT_SERVICE) as? InputManager)
?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper()))
padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this))
refreshSecondScreenDisplays()
if (SessionState.guestPid > 1) padBridge?.syncConnectedControllers()
joyConVr?.refresh()
@@ -4460,6 +4563,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (runtimeRemovalBlocked) { super.onPause(); return }
physicalShortcuts.clear()
backQamInput.cancel()
mouseBackInput.cancel()
capturePausedFrame()
padBridge?.setInputEnabled(false)
sessionClipboard.stop()
@@ -5033,11 +5137,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
super.onWindowFocusChanged(hasFocus)
if (!hasFocus) com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this)
if (!hasFocus) backQamInput.cancel()
if (!hasFocus) mouseBackInput.cancel()
if (!hasFocus && ::padMouse.isInitialized) padMouse.reset()
if (runtimeRemovalBlocked) return
if (!hasFocus) {
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
if (::touchpad.isInitialized) touchpad.cancel()
if (::scrollTouch.isInitialized) scrollTouch.cancel()
releaseHeldGuestInput()
}
if (hasFocus && !pipUi) {
goFullscreen()
@@ -18,12 +18,15 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.session.SessionArtifacts
import com.droiddeck.launcher.session.SessionEvents
import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.nio.file.Files
import java.util.UUID
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@@ -93,6 +96,7 @@ class AgentBridgeProvider : ContentProvider() {
}
"prefs" -> prefs(context, request)
"glasses" -> glasses(context, request)
"logs" -> logs(context)
"access" -> JSONObject().put("ok", true).put("commands", AgentAccess.commandsAllowed(context))
.put("debugBuild", BuildConfig.DEBUG).put("inbox", AgentEnv.inbox(context).absolutePath)
else -> error("UNKNOWN_COMMAND", "Unknown agent command '$method'")
@@ -197,9 +201,46 @@ class AgentBridgeProvider : ContentProvider() {
private fun hex(text: String, max: Int): Int? =
text.removePrefix("0x").removePrefix("0X").takeIf { it.isNotEmpty() }?.toIntOrNull(16)?.takeIf { it in 0..max }
private fun logDir(context: Context): File? =
SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: SessionPaths.sessionFolders(context).lastOrNull()
private fun cleanupExpiredLogExports(exports: File) {
val now = System.currentTimeMillis()
val canonicalRoot = exports.canonicalFile
exports.listFiles()?.forEach { candidate ->
val isUuid = runCatching { UUID.fromString(candidate.name).toString() == candidate.name }.getOrDefault(false)
if (!isUuid || !candidate.isDirectory || Files.isSymbolicLink(candidate.toPath())) return@forEach
if (candidate.canonicalFile.parentFile != canonicalRoot) return@forEach
if (now - candidate.lastModified() >= LOG_EXPORT_RETENTION_MS) candidate.deleteRecursively()
}
}
// The session folder is app-private, so adb pulls this copy from external files instead.
private fun logs(context: Context): JSONObject {
val dir = logDir(context)?.takeIf { it.isDirectory }
?: return error("NO_SESSION_LOGS", "No session artifact directory is available")
val externalFiles = context.getExternalFilesDir(null)
?: return error("NO_SESSION_LOGS", "External app storage is unavailable")
val exports = File(externalFiles, "agent-logs")
if ((!exports.exists() && !exports.mkdirs()) || !exports.isDirectory) {
return error("NO_SESSION_LOGS", "Could not create the session export directory")
}
cleanupExpiredLogExports(exports)
val output = File(exports, UUID.randomUUID().toString())
val zip = try {
SessionLogShare.zipFolder(context, dir, output)
} catch (error: Exception) {
output.deleteRecursively()
throw error
}
?: return error("NO_SESSION_LOGS", "The session artifact directory is empty")
return JSONObject().put("ok", true).put("command", "logs").put("sessionId", dir.name)
.put("zip", zip.absolutePath).put("cleanupDir", output.absolutePath)
}
private fun state(context: Context): JSONObject {
val runtimeVersion = LinuxRuntimeInstaller.installedVersion(context)
val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: SessionPaths.sessionFolders(context).lastOrNull()
val dir = logDir(context)
val session = JSONObject()
.put("id", SessionState.sessionId ?: dir?.name ?: JSONObject.NULL)
.put("phase", SessionState.phase.name)
@@ -351,6 +392,7 @@ class AgentBridgeProvider : ContentProvider() {
const val RESULT_JSON = "json"
const val EXTRA_REQUEST = "request"
const val SCHEMA = 2
private const val LOG_EXPORT_RETENTION_MS = 24 * 60 * 60 * 1000L
private val recoveryComplete = CountDownLatch(1)
fun awaitRecovery() {
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.agent
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadState
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.wayland.WaylandCompositor
@@ -143,9 +144,10 @@ object AgentInput {
val right = request.optString("stick", "left") == "right"
val x = request.optDouble("x", 0.0).toFloat().coerceIn(-1f, 1f)
val y = request.optDouble("y", 0.0).toFloat().coerceIn(-1f, 1f)
bridge.applyTouch { if (right) { it.rightX = x; it.rightY = y } else { it.leftX = x; it.leftY = y } }
val stickWrite = if (right) PadBridge.RIGHT_STICK else PadBridge.LEFT_STICK
bridge.applyTouch(stickWrite) { if (right) { it.rightX = x; it.rightY = y } else { it.leftX = x; it.leftY = y } }
hold(request, 300)
bridge.applyTouch { if (right) { it.rightX = 0f; it.rightY = 0f } else { it.leftX = 0f; it.leftY = 0f } }
bridge.applyTouch(stickWrite) { if (right) { it.rightX = 0f; it.rightY = 0f } else { it.leftX = 0f; it.leftY = 0f } }
return JSONObject().put("stick", if (right) "right" else "left")
}
@@ -130,22 +130,46 @@ public class PulseAudioComponent extends SessionPart {
private void ensureClientSink(java.io.PrintWriter out) {
try {
long deadline = System.currentTimeMillis() + 15000L;
// Nothing that may block (a sink whose AAudio open hangs: a Galaxy S24 FE (US) hung the
// daemon's start-up loading one from default.pa) is loaded by the daemon itself; the
// fallbacks are loaded here, after it is up, each pactl call bounded by its timeout.
long started = System.currentTimeMillis();
long deadline = started + 30000L;
String sinks = null;
boolean socketSeen = false;
while (System.currentTimeMillis() < deadline && pid > 1) {
if (socket().exists() && (sinks = pactl("list", "short", "sinks")) != null) break;
socketSeen |= socket().exists();
if (socketSeen && (sinks = pactl("list", "short", "sinks")) != null) break;
try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
}
note(out, "client sink: daemon " + (sinks != null ? "answered" : "did not answer") + " after "
+ (System.currentTimeMillis() - started) + " ms (socket " + (socketSeen ? "present" : "never appeared") + ", pactl "
+ (new File(workingDir, "pactl").isFile() ? "present" : "MISSING") + ", daemon pid " + pid + ")");
String line;
if (sinks == null) {
line = "== client sink: the daemon did not answer in 15 s; no fallback attempted";
line = "== client sink: the daemon did not answer in 30 s; no fallback attempted";
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
} else {
boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
&& pactl("set-default-sink", "AAudioSink") != null;
line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
// AAudio can refuse the first open with AAUDIO_ERROR_DISCONNECTED while Android is
// still switching the output route as the session starts (seen on a Galaxy S24 FE):
// try DirectAudio again, then the plain sink, a few times over ten seconds.
String loadedAs = null;
for (int attempt = 1; attempt <= 5 && loadedAs == null && pid > 1; attempt++) {
try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
if (pactl("load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1",
"adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls) != null
&& pactl("set-default-sink", "DirectAudio") != null) {
loadedAs = "DirectAudio on attempt " + attempt;
} else if (pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink",
"performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null
&& pactl("set-default-sink", "AAudioSink") != null) {
loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt;
}
}
line = loadedAs != null ? "== client sink: DirectAudio did not come up at start; retried and got " + loadedAs
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too after 5 retries - no client sound."
+ " If audio.log shows AAUDIO_ERROR_DISCONNECTED, Android refused the audio output: rebooting the phone usually fixes this";
Log.w(TAG, line);
}
Log.i(TAG, line);
@@ -155,6 +179,14 @@ public class PulseAudioComponent extends SessionPart {
}
}
/** A timestamped line in the session's audio log. */
private void note(java.io.PrintWriter out, String what) {
String line = "== " + new java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.US).format(new java.util.Date()) + " " + what;
Log.i(TAG, line);
if (out != null) synchronized (out) { out.println(line); out.flush(); }
}
/** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
private String pactl(String... args) {
File pactl = new File(workingDir, "pactl");
if (!pactl.isFile() || pid <= 1) return null;
@@ -149,5 +149,8 @@ internal class AddonPack(
listOf("version", "comet"))
val BUTLER = AddonPack("butler", BuildConfig.PACK_BUTLER_SHA256, BuildConfig.PACK_BUTLER_SIZE,
listOf("version", "butler", "7z.so", "libc7zip.so"))
@JvmField
val POWERVR = AddonPack("powervr", BuildConfig.PACK_POWERVR_SHA256, BuildConfig.PACK_POWERVR_SIZE,
listOf("runtime.tzst", "version.txt"))
}
}
@@ -10,6 +10,8 @@ import android.os.PowerManager
import android.os.StatFs
import android.provider.Settings
import android.util.Log
import com.droiddeck.launcher.gpu.DeviceInfo
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import android.view.Display
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
@@ -110,6 +112,7 @@ object DeviceReport {
runCatching {
val info = context.packageManager.getPackageInfo(context.packageName, 0)
k("Version", "${info.versionName} (${info.longVersionCode})")
k("App build", "${com.droiddeck.launcher.BuildConfig.BUILD_LABEL} (source ${com.droiddeck.launcher.BuildConfig.SOURCE_COMMIT})")
}
k("Package", context.packageName)
k("targetSdk", context.applicationInfo.targetSdkVersion)
@@ -186,7 +189,11 @@ object DeviceReport {
h("GPU")
k("KGSL gpu_model", readSys("/sys/class/kgsl/kgsl-3d0/gpu_model"))
k("KGSL chip id", readSys("/sys/class/kgsl/kgsl-3d0/gpu_chipid"))
k("System Vulkan ICD", if (File("/vendor/lib64/hw/vulkan.adreno.so").exists()) "/vendor/lib64/hw/vulkan.adreno.so" else "not at the usual path")
k("System Vulkan ICD", when {
SystemVulkanDriver.isPowerVr() -> SystemVulkanDriver.hal()
File("/vendor/lib64/hw/vulkan.adreno.so").exists() -> "/vendor/lib64/hw/vulkan.adreno.so"
else -> "not at the usual path"
})
h("Display")
k("Session output", SessionState.outputSize?.let { "${it.first}x${it.second}" })
@@ -208,7 +215,7 @@ object DeviceReport {
h("Drivers")
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText(SessionPrefs.vkBridge(context))}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
k("GPU", "${gpu.name} · ${gpu.family.label(gpu.name)} · ${gpu.supportText(SessionPrefs.vkBridge(context))}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
if (gpu.model == 740) {
val hint = com.droiddeck.launcher.gpu.TpUbwcHint
k("TP UBWC hint", hint.forThisDevice(context) ?: "driver default")
@@ -221,19 +228,25 @@ object DeviceReport {
com.droiddeck.launcher.gpu.AutoDriverTrial.bad(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())
val displayId = androidChoice.ifEmpty { turnip.autoId() }
val displayLabel = if (displayId == "system") DeviceInfo.builtinDriverLabel(SystemVulkanDriver.isPowerVr(), runtime = false)
else "${turnip.displayName(displayId)} ${turnip.driverVersion(displayId)}".trim()
k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> $displayLabel" else androidChoice)
k(" name / version", displayLabel)
k(" imported available", turnip.enumerateImported().ifEmpty { listOf("none") }.joinToString(", "))
val lm = LinuxVulkanDriverManager(context)
run {
val id = SessionPrefs.linuxDriver(context)
val label = if (id.isEmpty()) "runtime default (the Turnip built into the runtime)"
val label = if (id.isEmpty()) DeviceInfo.builtinDriverLabel(SystemVulkanDriver.isPowerVr(), runtime = true)
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]"
if (lm.isInstalled(id)) "" else if (SystemVulkanDriver.isPowerVr()) " [MISSING - select an installed driver or Auto]"
else " [MISSING - falls back to the runtime's own]"
k("Linux driver", label)
}
k("Runtime's own ICD", LinuxRuntime.vulkanIcd(context)?.path)
k("Mali (Venus)", if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) "in use"
else if (com.droiddeck.launcher.session.VenusComponent.available(context)) "available, off" else "not in this build")
h("Runtime")
k("Installed version", LinuxRuntimeInstaller.installedVersion(context))
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.core
import android.content.Context
import android.os.Build
import com.droiddeck.launcher.R
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import java.io.File
object DeviceSupport {
@@ -10,16 +11,35 @@ object DeviceSupport {
File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
}
private val maliGpu by lazy { !adrenoGpu && File("/dev/mali0").exists() }
fun adreno(): Boolean = adrenoGpu
fun mali(): Boolean = maliGpu
fun graphicsAvailable(): Boolean = graphicsAvailable(adreno(), SystemVulkanDriver.isAvailable())
internal fun graphicsAvailable(adreno: Boolean, powerVrReady: Boolean): Boolean = adreno || powerVrReady
fun vkBridge(context: Context): Boolean =
!adreno() && com.droiddeck.launcher.session.SessionPrefs.vkBridge(context)
bridgeUsable() && !com.droiddeck.launcher.session.VenusComponent.wanted(context) &&
com.droiddeck.launcher.session.SessionPrefs.vkBridge(context)
fun canDraw(context: Context): Boolean = adreno() || vkBridge(context)
fun mali(): Boolean = isMali
private val isMali by lazy {
!adreno() && (File("/dev/mali0").exists() ||
com.droiddeck.launcher.gpu.GpuInfo.detect().family.name.startsWith("MALI"))
}
fun bridgeUsable(): Boolean = !adreno() && !SystemVulkanDriver.isAvailable() && File("/dev/mali0").exists()
fun openDriverActive(context: Context): Boolean {
if (adreno()) return false
if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) return false
if (bridgeUsable() && com.droiddeck.launcher.session.SessionPrefs.vkBridge(context)) return false
val linux = com.droiddeck.launcher.session.SessionPrefs.linuxDriver(context).ifEmpty { return false }
return com.droiddeck.launcher.gpu.DriverPairs.isNonAdreno(com.droiddeck.launcher.gpu.DriverBundle.containing(context, linux, true)?.id)
}
fun canDraw(context: Context): Boolean = graphicsAvailable() || openDriverActive(context) || vkBridge(context) ||
com.droiddeck.launcher.session.VenusComponent.wanted(context)
fun gpuName(context: Context): String {
val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN } else null
@@ -30,8 +30,6 @@ object GameEnvironment {
fun defaults(preset: String, forceSsbs: Boolean = false): Map<String, String?> = linkedMapOf<String, String?>(
"MESA_SHADER_CACHE_DISABLE" to "false",
"DROIDDECK_ANTICHEAT_OFFLINE" to "1",
"VKD3D_FEATURE_LEVEL" to "12_2",
"VKD3D_SHADER_MODEL" to "6_9",
"DOTNET_GCRegionRange" to "800000000",
"DOTNET_EnableWriteXorExecute" to "0",
).apply {
@@ -131,42 +131,81 @@ object LogRedactor {
@Volatile
private var accounts: List<Learned> = emptyList()
fun learnAccounts(vararg loginUsers: java.io.File) {
internal const val MAX_LEARN_INPUT_BYTES = 2 * 1024 * 1024
private const val MAX_LEARNED_ACCOUNTS = 2048
private const val MAX_LEARNED_ADDRESSES = 1024
private const val MAX_ACCOUNT_LENGTH = 256
private fun boundedText(file: java.io.File): String? = try {
file.inputStream().buffered().use { input ->
val out = java.io.ByteArrayOutputStream()
val buffer = ByteArray(16 * 1024)
var remaining = MAX_LEARN_INPUT_BYTES
while (remaining > 0) {
val read = input.read(buffer, 0, minOf(buffer.size, remaining))
if (read < 0) return out.toString(Charsets.UTF_8.name())
if (read == 0) continue
out.write(buffer, 0, read)
remaining -= read
}
if (input.read() != -1) null else out.toString(Charsets.UTF_8.name())
}
} catch (_: Exception) {
null
}
fun learnAccounts(vararg loginUsers: java.io.File): Boolean {
val names = LinkedHashSet<String>()
val kv = Regex("\"(AccountName|PersonaName)\"\\s+\"([^\"]*)\"")
var unread = false
for (file in loginUsers) {
if (!file.isFile) continue
val text = try { file.readText() } catch (e: Exception) { unread = true; continue }
kv.findAll(text).map { it.groupValues[2].trim() }.filter { it.length >= 3 }.forEach { names += it }
val text = boundedText(file)
if (text == null) {
unread = true
continue
}
for (match in kv.findAll(text)) {
val name = match.groupValues[2].trim()
if (name.length < 3) continue
if (name.length > MAX_ACCOUNT_LENGTH || names.size >= MAX_LEARNED_ACCOUNTS) {
unread = true
break
}
names += name
}
}
val learned = names.map { name ->
val needs = name.lowercase().takeIf { name.all { it.code < 0x80 } }
Learned(Regex("(?i)(?<![A-Za-z0-9_])" + Regex.escape(name) + "(?![A-Za-z0-9_])"), needs)
}
accounts = if (unread) (accounts + learned).distinctBy { it.regex.pattern } else learned
accounts = if (unread) (learned + accounts).distinctBy { it.regex.pattern }.take(MAX_LEARNED_ACCOUNTS) else learned
return !unread
}
fun learnFromRuntime(root: java.io.File) {
learnOwnAddresses(java.io.File(root, "etc/droiddeck-net"))
learnAccounts(
fun learnFromRuntime(root: java.io.File): Boolean {
val addressesComplete = learnOwnAddresses(java.io.File(root, "etc/droiddeck-net"))
val accountsComplete = learnAccounts(
java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf"),
java.io.File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf"),
)
matchers.remove()
return addressesComplete && accountsComplete
}
@Volatile
private var own: List<Learned> = emptyList()
fun learnOwnAddresses(linkFile: java.io.File) {
fun learnOwnAddresses(linkFile: java.io.File): Boolean {
val found = ArrayList<Learned>()
try {
if (linkFile.isFile) linkFile.forEachLine { line ->
val addr = line.trim().takeIf { it.startsWith("addr ") }?.split(Regex("\\s+"))?.getOrNull(1) ?: return@forEachLine
val text = if (linkFile.isFile) boundedText(linkFile) ?: return false else ""
text.lineSequence().forEach { line ->
val addr = line.trim().takeIf { it.startsWith("addr ") }?.split(Regex("\\s+"))?.getOrNull(1) ?: return@forEach
if (found.size >= MAX_LEARNED_ADDRESSES) return false
when (kind(addr)) {
"public IPv6" -> {
val groups = expand6(addr)?.take(4) ?: return@forEachLine
val groups = expand6(addr)?.take(4) ?: return@forEach
val prefix = groups.joinToString(":") { g -> "0{0,3}" + Regex.escape(g.trimStart('0').ifEmpty { "0" }) }
found += Learned(
Regex("(?i)(?<![0-9A-Fa-f:])$prefix(?::[0-9A-Fa-f]{0,4}){1,4}(?:%[A-Za-z0-9_.]+)?"),
@@ -177,9 +216,10 @@ object LogRedactor {
}
}
} catch (e: Exception) {
return
return false
}
own = found
return true
}
fun kind(address: String): String? {
@@ -99,10 +99,11 @@ object AddedGames {
fun candidates(folder: File): List<File> = rank(folder).exes
fun rank(folder: File): GameExePicker.Ranking {
fun rank(folder: File, reuse: Boolean = false): GameExePicker.Ranking {
val key = "${folder.path}|${folder.lastModified()}"
val now = System.currentTimeMillis()
ranked[key]?.takeIf { now - it.first < RANK_FRESH_MS }?.let { return it.second }
if (reuse) kept?.rank(folder)?.let { return it }
val guessed = GameExePicker.rank(folder) { !skipExe(it.name) }
val declared = declaredExes(folder)
val preferred = declared.map { it.path }.toSet()
@@ -114,23 +115,27 @@ object AddedGames {
)
if (ranked.size > 256) ranked.clear()
ranked[key] = now to result
kept?.keepRank(folder, result)
return result
}
private val ranked = java.util.concurrent.ConcurrentHashMap<String, Pair<Long, GameExePicker.Ranking>>()
private const val RANK_FRESH_MS = 60_000L
@Volatile private var kept: AddedGamesCache? = null
private val identified = java.util.concurrent.ConcurrentHashMap<String, String>()
internal fun identifiedName(folder: File, exe: File): String? {
val key = "${exe.path}|${exe.length()}|${exe.lastModified()}|${folder.lastModified()}"
identified[key]?.let { return it.ifEmpty { null } }
kept?.name(key)?.let { identified[key] = it; return it.ifEmpty { null } }
val id = runCatching { GameIdentifier.identify(exe) }.getOrNull()
val found = id?.name?.takeIf {
id.nameSource in setOf(GameIdentifier.Source.STEAM_MANIFEST_ACF, GameIdentifier.Source.GOG_INFO, GameIdentifier.Source.PE_VERSION)
}
val name = found?.let { if (id?.nameSource == GameIdentifier.Source.PE_VERSION) betterSpelling(underscoresToSpaces(it), folder.name) else it }
identified[key] = name.orEmpty()
kept?.keepName(key, name.orEmpty())
return name
}
@@ -172,17 +177,17 @@ object AddedGames {
"launcher", "game", "engine", "system", "data", "app",
)
internal fun groupGames(folder: File): List<File>? {
internal fun groupGames(folder: File, reuse: Boolean = false): List<File>? {
val files = folder.listFiles() ?: return null
if (files.any { it.isFile && it.name.endsWith(".exe", ignoreCase = true) && !skipExe(it.name) }) return null
if (declaredExes(folder).isNotEmpty()) return null
val dirs = files.filter { it.isDirectory && !it.name.startsWith(".") && !isSteamLibraryFolder(it.name) }.sortedBy { it.name.lowercase() }
if (dirs.any { it.name.lowercase() in GAME_PARTS || GameExePicker.auxiliaryDir(it) }) return null
return dirs.filter { rank(it).exes.isNotEmpty() }.takeIf { it.size >= 2 }
return dirs.filter { rank(it, reuse).exes.isNotEmpty() }.takeIf { it.size >= 2 }
}
private fun expand(folder: File, entries: Set<String>): List<File> =
if (folder.path in entries) listOf(folder) else groupGames(folder) ?: listOf(folder)
private fun expand(folder: File, entries: Set<String>, reuse: Boolean = false): List<File> =
if (folder.path in entries) listOf(folder) else groupGames(folder, reuse) ?: listOf(folder)
private fun entryFolders(context: Context): Set<String> = AddedExes.list(context).map { it.folder }.toSet()
@@ -192,7 +197,19 @@ object AddedGames {
internal fun isSteamLibraryFolder(name: String): Boolean =
name.equals("steamapps", ignoreCase = true) || name == com.droiddeck.launcher.session.GameStorage.X64_CARD_DIR
fun scan(context: Context): List<Game> {
private val scanning = Any()
fun scan(context: Context): List<Game> = synchronized(scanning) {
val file = File(context.filesDir, AddedGamesCache.FILE)
val cache = kept?.takeIf { it.file == file } ?: AddedGamesCache(file).also { kept = it }
try {
scanAll(context)
} finally {
cache.save()
}
}
private fun scanAll(context: Context): List<Game> {
val out = ArrayList<Game>()
GamesFolderMigration.run(context)
val folders = listOfNotNull(
@@ -208,16 +225,16 @@ object AddedGames {
if (folder.name.lowercase() in steamInstalls || isSteamLibraryFolder(folder.name)) continue
if (folder.path in removed) continue
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
for (game in expand(folder, entries)) if (game.path !in removed) scanGame(context, game, out)
for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true)
}
}
for (entry in AddedExes.list(context)) {
val folder = File(entry.folder)
if (folder.path in removed || !folder.isDirectory) continue
scanGame(context, folder, out, single = entry)
scanGame(context, folder, out, single = entry, reuse = true)
}
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out)
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out)
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out, reuse = true)
for (game in com.droiddeck.launcher.runtime.BattleNet.games(context)) {
if (game.folder.path !in removed) com.droiddeck.launcher.runtime.BattleNet.shortcut(context, game)?.let(out::add)
}
@@ -398,11 +415,11 @@ object AddedGames {
private val INSTALL_DIR = Regex("\"installdir\"\\s*\"([^\"]*)\"", RegexOption.IGNORE_CASE)
private fun scanGame(context: Context, folder: File, out: MutableList<Game>, single: AddedExes.Entry? = null) {
private fun scanGame(context: Context, folder: File, out: MutableList<Game>, single: AddedExes.Entry? = null, reuse: Boolean = false) {
run {
val sidecar = StoreGameSidecar.read(folder)
sidecar?.takeIf { it.id.isNotEmpty() }?.let { SessionPrefs.followStoreGame(context, "${it.store.id}:${it.id}", folder.path) { old -> !File(old).exists() } }
val ranking = rank(folder)
val ranking = rank(folder, reuse)
val candidates = ranking.exes
val picked = SessionPrefs.addedGameExe(context, folder.path)
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
@@ -0,0 +1,87 @@
package com.droiddeck.launcher.frontend
import android.util.AtomicFile
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.concurrent.ConcurrentHashMap
internal class AddedGamesCache(val file: File) {
private class Rank(val modified: Long, val at: Long, val ranking: GameExePicker.Ranking)
private class Name(val name: String, val at: Long)
private val ranks = ConcurrentHashMap<String, Rank>()
private val names = ConcurrentHashMap<String, Name>()
@Volatile private var changed = false
init {
val json = runCatching { JSONObject(AtomicFile(file).readFully().toString(Charsets.UTF_8)) }.getOrNull()
json?.optJSONObject("ranks")?.let { all ->
for (path in all.keys()) runCatching {
val o = all.getJSONObject(path)
val exes = o.getJSONArray("exes")
val scores = o.getJSONArray("scores")
require(exes.length() > 0 && exes.length() == scores.length())
ranks[path] = Rank(o.getLong("modified"), o.getLong("at"), GameExePicker.Ranking(
List(exes.length()) { File(exes.getString(it)) }, List(scores.length()) { scores.getInt(it) }, o.optBoolean("uncertain"),
))
}
}
json?.optJSONObject("names")?.let { all ->
for (key in all.keys()) runCatching { all.getJSONObject(key).let { names[key] = Name(it.getString("name"), it.getLong("at")) } }
}
}
fun rank(folder: File): GameExePicker.Ranking? {
val kept = ranks[folder.path] ?: return null
val age = System.currentTimeMillis() - kept.at
val top = kept.ranking.exes.first()
return kept.ranking.takeIf { kept.modified == folder.lastModified() && age in 0 until KEEP_MS && top.isFile }
}
fun keepRank(folder: File, ranking: GameExePicker.Ranking) {
if (ranking.exes.isEmpty()) {
if (ranks.remove(folder.path) != null) changed = true
return
}
ranks[folder.path] = Rank(folder.lastModified(), System.currentTimeMillis(), ranking)
changed = true
}
fun name(key: String): String? = names[key]?.takeIf { System.currentTimeMillis() - it.at in 0 until KEEP_MS }?.name
fun keepName(key: String, name: String) {
names[key] = Name(name, System.currentTimeMillis())
changed = true
}
@Synchronized
fun save() {
if (!changed) return
changed = false
val oldest = System.currentTimeMillis() - KEEP_MS
val keptRanks = JSONObject()
ranks.forEach { (path, r) ->
if (r.at >= oldest) keptRanks.put(path, JSONObject().put("modified", r.modified).put("at", r.at)
.put("exes", JSONArray(r.ranking.exes.map { it.path })).put("scores", JSONArray(r.ranking.scores))
.put("uncertain", r.ranking.uncertain))
}
val keptNames = JSONObject()
names.forEach { (key, n) -> if (n.at >= oldest) keptNames.put(key, JSONObject().put("name", n.name).put("at", n.at)) }
val atomic = AtomicFile(file)
var out: java.io.FileOutputStream? = null
try {
out = atomic.startWrite()
out.write(JSONObject().put("ranks", keptRanks).put("names", keptNames).toString().toByteArray())
atomic.finishWrite(out)
} catch (e: Exception) {
out?.let(atomic::failWrite)
changed = true
}
}
companion object {
const val FILE = "added-games-scan.json"
const val KEEP_MS = 7L * 24 * 3600 * 1000
}
}
@@ -3,6 +3,8 @@ package com.droiddeck.launcher.frontend
import android.content.Context
import android.net.ConnectivityManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.util.AtomicFile
import android.util.Log
@@ -20,7 +22,11 @@ object AutoComponents {
private const val TAG = "AutoComponents"
fun appKey(game: Library.SteamGame): String? =
if (game.library == Library.ADDED) Integer.toUnsignedString(game.appId) else game.appId.takeIf { it > 0 }?.toString()
when {
game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id -> game.profileKey
game.library == Library.ADDED -> Integer.toUnsignedString(game.appId)
else -> game.appId.takeIf { it > 0 }?.toString()
}
fun autoPicks(findings: List<WinCompSources.Finding>, catalog: Map<String, WinComponents.Component>): Map<String, WinComponents.AutoReason> {
val out = LinkedHashMap<String, WinComponents.AutoReason>()
@@ -48,6 +54,8 @@ object AutoComponents {
val downloading = MutableStateFlow<Map<String, WinComponents.Progress>>(emptyMap())
val repairFailures = MutableStateFlow<Map<String, String>>(emptyMap())
val pendingGames = MutableStateFlow<Set<String>>(emptySet())
val pendingComponents = MutableStateFlow<Set<String>>(emptySet())
@@ -56,12 +64,12 @@ object AutoComponents {
if (job.pics != null) return
val flow = if (job.component != null) pendingComponents else pendingGames
val id = job.component ?: job.game?.let { appKey(it) } ?: return
flow.value = if (on) flow.value + id else flow.value - id
flow.value = if (on || job.component != null && job.key in queuedKeys) flow.value + id else flow.value - id
}
internal class Job(
val game: Library.SteamGame?, val component: String?, val asked: Boolean, val seq: Long, val pics: List<Int>? = null,
val inSession: Boolean = false,
val inSession: Boolean = false, val revision: Int? = null,
) {
val key get() = when {
pics != null -> "pics"
@@ -79,29 +87,45 @@ object AutoComponents {
@Volatile private var worker: Thread? = null
private const val PAUSE_MS = 15_000L
private fun waitFor(game: Library.SteamGame, id: String) {
val key = appKey(game) ?: return
synchronized(waiting) { waiting.getOrPut(id) { ArrayList() }.let { if (it.none { g -> appKey(g) == key }) it.add(game) } }
}
fun queueGame(context: Context, game: Library.SteamGame, asked: Boolean) {
if (appKey(game) == null) return
enqueue(context, Job(game, null, asked, seq.incrementAndGet()))
}
private fun queueDownload(context: Context, id: String, asked: Boolean, inSession: Boolean = false) =
enqueue(context, Job(null, id, asked, seq.incrementAndGet(), inSession = inSession))
fun queueRepair(context: Context, id: String, gameKey: String?, revision: Int) {
if (!WinComponents.validId(id)) return
gameKey?.let { Pending.add(context, it, listOf(id), mapOf(id to revision)) }
queueDownload(context, id, asked = true, inSession = gameKey != null,
revision = maxOf(revision, Pending.revision(context, id) ?: 0))
}
private fun queueDownload(context: Context, id: String, asked: Boolean, inSession: Boolean = false, revision: Int? = null) =
enqueue(context, Job(null, id, asked, seq.incrementAndGet(), inSession = inSession, revision = revision))
private fun enqueue(context: Context, job: Job) {
if (!queuedKeys.add(job.key)) {
synchronized(jobs) {
val added = synchronized(jobs) {
if (!queuedKeys.add(job.key)) {
val old = jobs.firstOrNull { it.key == job.key }
if (old != null && ((job.asked && !old.asked) || (job.inSession && !old.inSession)) && jobs.remove(old)) {
val revision = listOfNotNull(old?.revision, job.revision).maxOrNull()
val pics = listOfNotNull(old?.pics, job.pics).flatten().distinct().takeIf { old?.pics != null || job.pics != null }
if (old != null && ((job.asked && !old.asked) || (job.inSession && !old.inSession) || revision != old.revision || pics != old.pics) && jobs.remove(old)) {
jobs.add(Job(old.game ?: job.game, old.component, old.asked || job.asked,
if (job.asked && !old.asked) job.seq else old.seq, old.pics ?: job.pics, old.inSession || job.inSession))
if (job.asked && !old.asked) job.seq else old.seq, pics,
old.inSession || job.inSession, revision))
}
}
if (runNow && !draining) drain(context)
return
false
} else {
jobs.add(job)
mark(job, true)
true
}.also { (jobs as java.lang.Object).notifyAll() }
}
if (job.component != null) Log.i(TAG, "wincomp: queued ${job.component}")
mark(job, true)
jobs.add(job)
if (added && job.component != null) Log.i(TAG, "wincomp: queued ${job.component}")
if (runNow) { if (!draining) drain(context) } else ensureWorker(context.applicationContext)
}
@@ -113,8 +137,15 @@ object AutoComponents {
private fun gameProcessRunning(): Boolean = com.droiddeck.launcher.session.SteamGameProcess.running()
private fun queuePending(context: Context, key: String) {
Pending.ids(context, key).forEach { id ->
queueDownload(context, id, asked = true, inSession = true, revision = Pending.revision(context, id))
}
}
fun queueInSession(context: Context, game: Library.SteamGame) {
if (appKey(game) == null) return
val key = appKey(game) ?: return
queuePending(context, key)
enqueue(context, Job(game, null, true, seq.incrementAndGet(), inSession = true))
}
@@ -124,7 +155,6 @@ object AutoComponents {
try {
while (true) {
val job = next(context) ?: return
queuedKeys.remove(job.key)
run(context, job)
}
} finally {
@@ -135,6 +165,7 @@ object AutoComponents {
private fun next(context: Context): Job? = synchronized(jobs) {
val job = jobs.sortedWith(order).firstOrNull { !mustWait(context, it) } ?: return null
jobs.remove(job)
queuedKeys.remove(job.key)
job
}
@@ -148,13 +179,17 @@ object AutoComponents {
worker = Thread({
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
while (true) {
try { jobs.put(jobs.take()) } catch (e: InterruptedException) { return@Thread }
val job = next(app)
if (job == null) {
try { Thread.sleep(PAUSE_MS) } catch (e: InterruptedException) { return@Thread }
continue
val job = try {
synchronized(jobs) {
next(app) ?: run {
(jobs as java.lang.Object).wait(PAUSE_MS)
next(app)
}
}
} catch (e: InterruptedException) {
return@Thread
}
queuedKeys.remove(job.key)
if (job == null) continue
WinComponents.background { run(app, job) }
}
}, "auto-components").apply { isDaemon = true; start() }
@@ -164,18 +199,23 @@ object AutoComponents {
try {
when {
job.pics != null -> SteamAppInfo.lookup(context, job.pics)
job.component != null -> download(context, job.component, job.asked, job.inSession)
job.component != null -> download(context, job.component, job.asked, job.inSession, job.revision)
else -> job.game?.let { apply(context, it, job.asked, job.inSession) }
}
} catch (e: Exception) {
Log.w(TAG, "wincomp: ${job.key}: ${e.javaClass.simpleName}: ${e.message}")
job.component?.let {
repairFailures.value = repairFailures.value + (it to (e.message ?: "Install failed"))
Pending.drop(context, it, job.revision)
}
} finally {
mark(job, false)
changes.value = changes.value + 1
}
}
private fun apply(context: Context, game: Library.SteamGame, asked: Boolean, inSession: Boolean = false) {
private fun apply(context: Context, game: Library.SteamGame, asked: Boolean, inSession: Boolean = false,
knownCatalog: Map<String, WinComponents.Component>? = null) {
val key = appKey(game) ?: return
val folder = game.gameFiles
if (game.library == Library.ADDED && game.source == Library.ADDED && folder != null && SteamMatch.get(context, folder.path) == null) {
@@ -183,9 +223,10 @@ object AutoComponents {
}
val store = com.droiddeck.launcher.stores.Store.byId(game.source)
if (folder != null && (store == com.droiddeck.launcher.stores.Store.GOG || store == com.droiddeck.launcher.stores.Store.EPIC)) StoreListBackfill.fill(context, folder)
if (asked && online(context)) steamAppOf(context, game)?.let { SteamAppInfo.lookup(context, listOf(it)) }
if (knownCatalog == null && asked && online(context)) steamAppOf(context, game)?.let { SteamAppInfo.lookup(context, listOf(it)) }
val findings = findings(context, game)
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return
val refreshed = if (knownCatalog == null && asked && online(context)) catalogOf(context, true) else null
val catalog = knownCatalog ?: (refreshed ?: catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return
val wanted = autoPicks(findings, catalog)
val user = WinComponents.selection(context, key).user
val before = WinComponents.selection(context, key).auto
@@ -196,22 +237,37 @@ object AutoComponents {
if (user[id] == false) { kept[id] = reason; continue }
if (id in installed) { kept[id] = reason; continue }
if (id in before) kept[id] = reason
synchronized(waiting) { waiting.getOrPut(id) { ArrayList() }.let { if (it.none { g -> appKey(g) == key }) it.add(game) } }
queueDownload(context, id, asked, inSession)
waitFor(game, id)
missing.add(id)
}
if (inSession) Pending.set(context, key, (Pending.ids(context, key).filter { it !in installed && it !in wanted } + missing).distinct())
if (before.keys != kept.keys) {
WinComponents.setAuto(context, key, kept)
Log.i(TAG, "${game.name}: on by itself ${kept.keys.joinToString().ifEmpty { "(none)" }}")
}
Pending.update(context, key, catalog.mapValues { it.value.revision }) { ids ->
ids.filter { id -> user[id] != false && (id !in installed && id !in wanted || (Pending.revision(context, id) ?: 0) > (catalog[id]?.revision ?: 0)) } + missing
}
missing.forEach { id -> queueDownload(context, id, asked, inSession, catalog[id]?.revision) }
changes.value = changes.value + 1
}
private fun download(context: Context, id: String, asked: Boolean, inSession: Boolean = false) {
val catalog = catalogOf(context, true)?.associateBy { it.name } ?: run { Pending.drop(context, id); return }
private fun download(context: Context, id: String, asked: Boolean, inSession: Boolean = false, requestedRevision: Int? = null) {
val catalog = catalogOf(context, true)?.associateBy { it.name } ?: run {
repairFailures.value = repairFailures.value + (id to "Could not load the component catalog")
return
}
val catalogComponent = catalog[id]
val requiredRevision = maxOf(requestedRevision ?: 0, Pending.revision(context, id) ?: 0)
if (catalogComponent != null && catalogComponent.revision < requiredRevision) {
repairFailures.value = repairFailures.value + (id to "The component catalog is older than the requested revision")
return
}
if (id !in installedOf(context)) {
val c = catalog[id] ?: run { Pending.drop(context, id); return }
val c = catalogComponent ?: run {
repairFailures.value = repairFailures.value + (id to "Component is no longer available")
Pending.drop(context, id, requestedRevision)
return
}
val started = System.currentTimeMillis()
downloading.value = downloading.value + (id to WinComponents.Progress(id, "", WinComponents.Phase.DOWNLOAD, -1))
val problem = try {
@@ -219,12 +275,28 @@ object AutoComponents {
} finally {
downloading.value = downloading.value - id
}
if (problem != null) { Log.w(TAG, "wincomp: $id did not install: $problem"); Pending.drop(context, id); return }
if (problem != null) {
repairFailures.value = repairFailures.value + (id to problem)
Log.w(TAG, "wincomp: $id did not install: $problem")
Pending.drop(context, id, maxOf(requestedRevision ?: 0, c.revision))
return
}
Log.i(TAG, "wincomp: $id installed in ${System.currentTimeMillis() - started}ms")
}
val games = synchronized(waiting) { waiting.remove(id).orEmpty() }
games.forEach { apply(context, it, asked, inSession) }
Pending.drop(context, id)
var applied = true
games.forEach { game ->
try {
apply(context, game, asked, inSession, knownCatalog = catalog)
} catch (e: Exception) {
applied = false
appKey(game)?.let { key -> Pending.add(context, key, listOf(id), mapOf(id to (catalog[id]?.revision ?: requestedRevision ?: 0))) }
waitFor(game, id)
Log.w(TAG, "wincomp: $id installed, but ${game.name} was not updated: ${e.javaClass.simpleName}: ${e.message}")
}
}
if (applied) Pending.drop(context, id, maxOf(requestedRevision ?: 0, catalog[id]?.revision ?: 0))
repairFailures.value = repairFailures.value - id
}
internal object Pending {
@@ -233,24 +305,37 @@ object AutoComponents {
@Synchronized fun read(context: Context): JSONObject =
runCatching { JSONObject(file(context).readText()) }.getOrDefault(JSONObject()).let { it.optJSONObject("games") ?: JSONObject() }
@Synchronized fun set(context: Context, key: String, ids: List<String>) {
@Synchronized fun set(context: Context, key: String, ids: List<String>, revisions: Map<String, Int> = emptyMap()) {
val games = read(context)
if (ids.isEmpty()) games.remove(key) else games.put(key, JSONArray(ids))
write(context, games)
write(context, games, revisions)
}
@Synchronized fun ids(context: Context, key: String): List<String> =
read(context).optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
@Synchronized fun add(context: Context, key: String, ids: List<String>) {
@Synchronized fun update(context: Context, key: String, revisions: Map<String, Int>, transform: (List<String>) -> List<String>): Boolean {
val games = read(context)
val current = games.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
val ids = transform(current).distinct()
if (ids.isEmpty()) games.remove(key) else games.put(key, JSONArray(ids))
return write(context, games, revisions)
}
@Synchronized fun revision(context: Context, id: String): Int? =
runCatching { JSONObject(file(context).readText()).optJSONObject("revisions")?.optInt(id) }.getOrNull()
@Synchronized fun add(context: Context, key: String, ids: List<String>, revisions: Map<String, Int> = emptyMap()) {
val games = read(context)
val have = games.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
games.put(key, JSONArray((have + ids).distinct()))
write(context, games)
write(context, games, revisions)
}
@Synchronized fun drop(context: Context, id: String) {
@Synchronized fun drop(context: Context, id: String, throughRevision: Int? = null) {
val games = read(context)
val required = runCatching { JSONObject(file(context).readText()).optJSONObject("revisions")?.optInt(id, 0) ?: 0 }.getOrDefault(0)
if (throughRevision != null && required > throughRevision) return
for (k in games.keys().asSequence().toList()) {
val left = games.optJSONArray(k)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty() - id
if (left.isEmpty()) games.remove(k) else games.put(k, JSONArray(left))
@@ -258,13 +343,29 @@ object AutoComponents {
write(context, games)
}
private fun write(context: Context, games: JSONObject) {
private fun write(context: Context, games: JSONObject, required: Map<String, Int> = emptyMap()): Boolean {
val f = file(context)
runCatching {
return runCatching {
f.parentFile?.mkdirs()
val tmp = File(f.path + ".tmp")
tmp.writeText(JSONObject().put("games", games).toString())
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
val before = runCatching { JSONObject(f.readText()).optJSONObject("revisions") }.getOrNull()
val revisions = JSONObject()
for (key in games.keys()) {
val ids = games.getJSONArray(key)
for (i in 0 until ids.length()) {
val id = ids.getString(i)
revisions.put(id, maxOf(before?.optInt(id, 0) ?: 0, required[id] ?: 0))
}
}
tmp.writeText(JSONObject().put("games", games).put("revisions", revisions).toString())
if (!tmp.renameTo(f)) {
f.delete()
if (!tmp.renameTo(f)) throw java.io.IOException("Could not replace pending repair file")
}
true
}.getOrElse {
Log.w(TAG, "wincomp: could not save pending repairs: ${it.javaClass.simpleName}: ${it.message}")
false
}
}
}
@@ -329,21 +430,76 @@ object AutoComponents {
}
fun beforeLaunch(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = false)
internal fun prepareLaunch(context: Context, game: Library.SteamGame): Boolean {
val key = appKey(game) ?: return false
val findings = findings(context, game)
val cached = catalogOf(context, false)
val current = if (online(context)) catalogOf(context, true) else null
val catalog = (current ?: cached)?.associateBy { it.name } ?: run {
val missing = WinComponents.selection(context, key).effective
.filter { WinComponents.validId(it) && it !in installedOf(context) }
val pendingSaved = missing.isEmpty() || Pending.update(context, key, emptyMap()) { ids -> (ids + missing).distinct() }
val pending = Pending.ids(context, key)
pending.forEach { waitFor(game, it) }
queuePending(context, key)
if (!pendingSaved) {
missing.forEach { id ->
waitFor(game, id)
queueDownload(context, id, asked = true, inSession = true, revision = Pending.revision(context, id))
repairFailures.value = repairFailures.value + (id to "Could not save pending repairs")
}
}
return pendingSaved && pending.isEmpty()
}
val wanted = autoPicks(findings, catalog)
val selection = WinComponents.selection(context, key)
val user = selection.user
val installed = installedOf(context)
val roots = selection.effective + wanted.keys.filter { user[it] != false }
val required = withParts(roots.filter { WinComponents.validId(it) }, catalog)
val missing = required.filter { user[it] != false && it !in installed }
val pendingSaved = Pending.update(context, key, catalog.mapValues { it.value.revision }) { ids ->
ids.filter { id -> user[id] != false && (id !in installed && id !in wanted || (Pending.revision(context, id) ?: 0) > (catalog[id]?.revision ?: 0)) } + missing
}
missing.forEach { id ->
waitFor(game, id)
queueDownload(context, id, asked = true, inSession = true,
revision = maxOf(catalog[id]?.revision ?: 0, Pending.revision(context, id) ?: 0))
}
Pending.ids(context, key).forEach { waitFor(game, it) }
queuePending(context, key)
if (!pendingSaved && missing.isNotEmpty()) {
missing.forEach { id -> repairFailures.value = repairFailures.value + (id to "Could not save pending repairs") }
return false
}
return true
}
fun beforeLaunch(context: Context, game: Library.SteamGame, onReady: () -> Unit) {
val app = context.applicationContext
Thread({
val ready = runCatching { prepareLaunch(app, game) }.getOrElse {
Log.w(TAG, "${game.name}: launch repair discovery failed: ${it.javaClass.simpleName}: ${it.message}")
false
}
queueGame(app, game, asked = false)
if (ready) Handler(Looper.getMainLooper()).post(onReady)
}, "auto-components-launch").apply { isDaemon = true; start() }
}
fun restoreMissing(context: Context): List<String> {
val selections = WinComponents.selections(context)
if (selections.isEmpty()) return emptyList()
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return emptyList()
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name }
val installed = installedOf(context)
val lostFor = selections.mapValues { (_, selection) ->
val lostFor = if (catalog == null) emptyMap() else selections.mapValues { (_, selection) ->
withParts(selection.effective.filter { WinComponents.validId(it) }, catalog).filter { it !in installed && it in catalog }
}.filterValues { it.isNotEmpty() }
if (lostFor.isEmpty()) return emptyList()
val lost = lostFor.values.flatten().distinct()
Log.i(TAG, "wincomp: reinstalling ${lost.joinToString()}, picked for games but missing from the runtime")
lostFor.forEach { (key, ids) -> Pending.add(context, key, ids) }
lost.forEach { queueDownload(context, it, asked = true, inSession = true) }
if (lost.isNotEmpty()) {
Log.i(TAG, "wincomp: reinstalling ${lost.joinToString()}, picked for games but missing from the runtime")
lostFor.forEach { (key, ids) -> Pending.add(context, key, ids, catalog!!.mapValues { it.value.revision }) }
}
Pending.read(context).keys().asSequence().toList().forEach { queuePending(context, it) }
return lost
}
@@ -360,6 +516,7 @@ object AutoComponents {
fun refreshLater(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = true)
fun sweep(context: Context, games: List<Library.SteamGame>) {
if (online(context) && !unfavourable(context)) catalogOf(context, true)
val apps = games.mapNotNull { steamAppOf(context, it) }.distinct()
if (apps.isNotEmpty() && SteamAppInfo.needLookup(context, apps).isNotEmpty()) enqueue(context, Job(null, null, false, seq.incrementAndGet(), pics = apps))
games.forEach { queueGame(context, it, asked = false) }
@@ -14,6 +14,8 @@ object SteamRedists {
"228988" to ("vcredist2019_dll" to "VC++ 2019"),
"228989" to ("vcredist2022_dll" to "VC++ 2022"),
"228990" to ("d3dx9" to "DirectX (June 2010)"),
// OpenAL 2.0.7.0 (Hotline Miami lists it; without it HotlineGL.exe fails to load, c0000135).
"229020" to ("oalinst_dll" to "OpenAL"),
)
val SCRIPTED = mapOf(
72850 to listOf("xact" to "DirectX XACT audio"),
@@ -1,6 +1,9 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build
import android.os.PowerManager
import android.util.Log
@@ -13,14 +16,17 @@ import java.util.Locale
class ClockLogComponent(private val logFile: File) : SessionPart() {
@Volatile private var running = false
private var stopped = false
private var thread: Thread? = null
override fun start() {
@Synchronized override fun start() {
if (stopped || running) return
running = true
thread = Thread({ run() }, "clock-log").apply { isDaemon = true; start() }
}
override fun stop() {
@Synchronized override fun stop() {
stopped = true
running = false
thread?.interrupt()
thread = null
@@ -65,6 +71,7 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
if (!h.isNaN()) line.append(String.format(Locale.US, " headroom %.2f", h))
}
}
batteryTenths()?.let { line.append(String.format(Locale.US, " | battery %.1f C", it / 10.0)) }
w.write(line.append('\n').toString())
w.flush()
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
@@ -75,6 +82,10 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
}
}
private fun batteryTenths(): Int? =
app().registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
?.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, Int.MIN_VALUE)?.takeIf { it != Int.MIN_VALUE }
companion object {
private const val TAG = "SessionService"
private const val PERIOD_MS = 2000L
@@ -85,8 +96,13 @@ class ClockLogComponent(private val logFile: File) : SessionPart() {
"/sys/kernel/ged/hal/current_freqency", "/sys/kernel/ged/hal/current_frequency",
"/proc/gpufreqv2/gpufreq_status", "/proc/gpufreq/gpufreq_var_dump",
"/sys/kernel/gpu/gpu_clock", "/sys/class/misc/mali0/device/cur_freq",
"/sys/class/misc/mali0/device/clock",
"/sys/class/misc/mali0/device/clock", "/sys/class/kgsl/kgsl-3d0/clock_mhz",
"/sys/class/kgsl/kgsl-3d0/gpu_clock", "/sys/class/kgsl/kgsl-3d0/gpuclk",
"/sys/class/kgsl/kgsl-3d0/devfreq/cur_freq", "/sys/kernel/gpu/gpu_clock",
"/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq",
)
listOf("kgsl-3d0", "3d00000.qcom,kgsl-3d0", "2c00000.qcom,kgsl-3d0", "5000000.qcom,kgsl-3d0", "5900000.qcom,kgsl-3d0")
.forEach { list.add("/sys/class/devfreq/$it/cur_freq") }
File("/sys/class/devfreq").list()?.sorted()?.forEach { node ->
if (node.contains("mali", true) || node.contains("gpu", true)) list.add("/sys/class/devfreq/$node/cur_freq")
}
@@ -53,7 +53,7 @@ object DeviceInfo {
private fun gpu(context: Context, gpu: GpuInfo) = Section("GPU", buildList<Pair<String, String>> {
add("GPU", gpu.name)
add("Family", gpu.family.label)
add("Family", gpu.family.label(gpu.name))
add("Model found from", when (gpu.modelSource) {
"kernel" -> "the kernel's GPU name"
"vulkan" -> "the Vulkan driver (the kernel's name has no model)"
@@ -146,10 +146,20 @@ object DeviceInfo {
add("Driver mode", SessionPrefs.gpuDriverMode(context))
val turnip = TurnipDriver(context)
val choice = SessionPrefs.androidDriver(context).ifEmpty { turnip.autoId() }
add("Display driver", "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
val powerVr = gpu.family == GpuInfo.Family.POWERVR
add("Display driver", if (choice == "system") builtinDriverLabel(powerVr, runtime = false)
else "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
val linux = LinuxVulkanDriverManager(context)
val id = SessionPrefs.linuxDriver(context)
add("Game driver", if (id.isEmpty()) "the runtime's own Turnip" else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
add("Game driver", if (id.isEmpty()) builtinDriverLabel(powerVr, runtime = true) else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
if (gpu.oneUi8Gen2) add("Note", "One UI on an 8 Gen 2: needs the OneUI Turnip build")
})
/** Shared by the device card and the session report, which are written in English. */
internal fun builtinDriverLabel(powerVr: Boolean, runtime: Boolean): String = when {
powerVr -> "System PowerVR"
runtime -> "the runtime's own Turnip"
else -> "System Vulkan"
}
}
@@ -75,8 +75,8 @@ object DriverBundle {
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 library = linuxDir.listFiles()?.firstOrNull { it.isFile && LinuxVulkanDriverManager.isDriverLibrary(it.name) }
library?.copyTo(File(linuxStage, LinuxVulkanDriverManager.storedName(library.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)
@@ -86,6 +86,10 @@ object DriverBundle {
}
val base = LinuxVulkanDriverManager.sanitizeId(manifest.tag.ifEmpty { "${manifest.name}-${manifest.version}" })
get(context, base)?.takeIf { DriverPairs.isNonAdreno(it.id) }?.let { old ->
Log.i(TAG, "replacing bundle ${old.id} (display ${old.androidId}, runtime ${old.linuxId})")
remove(context, old)
}
val saved = registry(context)
var id = base
var n = 2
@@ -12,6 +12,48 @@ object DriverPairs {
const val DD_TURNIP = "dd-turnip"
fun ddTurnip(tag: String) = "$DD_TURNIP:$tag"
/** The open non-Adreno drivers (The412Banner/droiddeck-nonadreno-drivers), one pair per driver. */
const val NON_ADRENO = "nad"
const val NAD_RADV_XCLIPSE = "nad:radv-xclipse"
/** RADV-Xclipse rebased on JimVulkan's upstream: a manual choice, never Auto. */
const val NAD_RADV_XCLIPSE_UPSTREAM = "nad:radv-xclipse-upstream"
private val XCLIPSE_MODEL = Regex("""(?i)xclipse\s*(\d{3})\b""")
const val NAD_MALI_JM = "nad:panvk-mali-jm"
const val NAD_MALI_G710 = "nad:panvk-mali-g710"
const val NAD_MALI_G615 = "nad:panvk-mali-g615"
const val NAD_MALI_G720 = "nad:panvk-mali-g720"
/** One PanVK kbase binary for Mali v9-v13; its display half needs Android 15. */
const val NAD_MALI_KBASE = "nad:panvk-mali-kbase"
const val MALI_KBASE_MIN_SDK = 35
/** faux123's PanVK builds for three handhelds: manual choices, never Auto. */
const val NAD_FAUX_RP4PRO = "nad:panvk-faux123-rp4pro"
const val NAD_FAUX_ACE = "nad:panvk-faux123-ace"
const val NAD_FAUX_RG556 = "nad:panvk-faux123-rg556"
/** The one Mali a device-specific build is for, by the number in the GPU's name. */
private val DEVICE_BUILDS = mapOf(NAD_FAUX_RP4PRO to 77, NAD_FAUX_ACE to 610, NAD_FAUX_RG556 to 57)
/** "PanVK-Mali-G720" (the release asset's id) to its pair key, "nad:panvk-mali-g720". */
fun nonAdreno(id: String) = "$NON_ADRENO:" + id.lowercase()
/** True for a non-Adreno pair's key, or a bundle installed from one ("PanVK-Mali-G720"). */
fun isNonAdreno(keyOrBundleId: String?): Boolean = keyOrBundleId != null &&
(keyOrBundleId.startsWith("$NON_ADRENO:") || Regex("""^(?i)(RADV-Xclipse|PanVK-[A-Za-z0-9]+)(-[A-Za-z0-9]+)*$""").matches(keyOrBundleId))
fun nonAdrenoName(key: String): String = describeNonAdreno(key).first
private fun describeNonAdreno(key: String): Pair<String, Set<Family>> = when (key) {
NAD_RADV_XCLIPSE -> "RADV · Samsung Xclipse" to setOf(Family.POWERVR)
NAD_RADV_XCLIPSE_UPSTREAM -> "RADV upstream · Samsung Xclipse" to setOf(Family.POWERVR)
NAD_MALI_JM -> "PanVK · Mali G52-G78" to setOf(Family.MALI_JM)
NAD_MALI_G710 -> "PanVK · Mali-G610/G710" to setOf(Family.MALI_G610_G710)
NAD_MALI_G615 -> "PanVK · Mali-G615" to setOf(Family.MALI_G615)
NAD_MALI_G720 -> "PanVK · Mali-G720" to setOf(Family.MALI_G720)
NAD_FAUX_RP4PRO -> "PanVK faux123 · Retroid Pocket 4 Pro (Mali-G77)" to setOf(Family.MALI_JM)
NAD_FAUX_ACE -> "PanVK faux123 · GameForce Ace (Mali-G610)" to setOf(Family.MALI_G610_G710)
NAD_FAUX_RG556 -> "PanVK faux123 · Anbernic RG556 (Mali-G57)" to setOf(Family.MALI_JM)
NAD_MALI_KBASE -> "PanVK kbase · Mali G57-G925" to
setOf(Family.MALI_JM, Family.MALI_G610_G710, Family.MALI_G615, Family.MALI_G720, Family.MALI_LATEST)
else -> key.removePrefix("$NON_ADRENO:") to emptySet<Family>()
}
class DriverPair(
val key: String,
val name: String,
@@ -24,14 +66,23 @@ object DriverPairs {
val assets: List<TurnipReleases.Asset> get() = listOfNotNull(bundle ?: display, if (bundle == null) linux else null)
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))
fun suits(gpu: GpuInfo) = when {
// The system-driver family covers PowerVR and Xclipse; RADV is only for the Xclipse.
key == NAD_RADV_XCLIPSE || key == NAD_RADV_XCLIPSE_UPSTREAM ->
gpu.family == Family.POWERVR && gpu.name.contains("Xclipse", ignoreCase = true)
// One binary for Mali v9-v13, not the older G52/G76 in the Job Manager family.
key == NAD_MALI_KBASE -> gpu.family.mali && GpuInfo.maliKbaseCovered(gpu.name)
key in DEVICE_BUILDS -> gpu.family.mali && GpuInfo.maliNumber(gpu.name) == DEVICE_BUILDS[key]
else -> 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
key.startsWith("$NON_ADRENO:") -> describeNonAdreno(key)
else -> describeFixed(key)
}
@@ -47,7 +98,7 @@ object DriverPairs {
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)
val order = listOf(DD_TURNIP, BANNER, BANNER_A8XX, BANNER_ONEUI, BANNER_710, WN_BALANCED, WN_PERFORMANCE, NON_ADRENO)
return assets.map { it.pair }.distinct()
.sortedBy { key -> order.indexOf(key.substringBefore(':')).let { i -> if (i < 0) order.size else i } }
.map { key ->
@@ -61,12 +112,26 @@ object DriverPairs {
}
}
/** 950 and 960 panic on the older build; a name without a model number is treated the same way. */
private fun xclipseNeedsUpstream(name: String): Boolean =
XCLIPSE_MODEL.find(name)?.groupValues?.get(1).let { it == null || it == "950" || it == "960" }
fun recommendedKey(
gpu: GpuInfo, pairs: List<DriverPair>,
rules: List<AutoPicks.Rule> = AutoPicks.BUILT_IN, bad: Set<String> = emptySet(),
sdk: Int = android.os.Build.VERSION.SDK_INT, blob: Int? = null,
): String? {
if (gpu.family == Family.NOT_ADRENO) return null
when (gpu.family) {
Family.POWERVR -> return when {
!gpu.name.contains("Xclipse", ignoreCase = true) -> null
xclipseNeedsUpstream(gpu.name) && pairs.any { it.key == NAD_RADV_XCLIPSE_UPSTREAM } -> NAD_RADV_XCLIPSE_UPSTREAM
else -> NAD_RADV_XCLIPSE
}
Family.MALI_OTHER, Family.NOT_ADRENO -> return null
Family.MALI_JM, Family.MALI_G610_G710, Family.MALI_G615, Family.MALI_G720, Family.MALI_LATEST ->
return maliKey(gpu, pairs, sdk)
else -> Unit
}
val keys = AutoPicks.preferences(gpu, rules, sdk, blob)
.ifEmpty { AutoPicks.preferences(gpu, AutoPicks.BUILT_IN, sdk, blob) }
.mapNotNull { if (it == AutoPicks.NEWEST_DD_TURNIP) newestDdTurnip(pairs) else it }
@@ -74,6 +139,20 @@ object DriverPairs {
?: keys.firstOrNull()
}
private fun maliKey(gpu: GpuInfo, pairs: List<DriverPair>, sdk: Int): String? {
val family = when (gpu.family) {
Family.MALI_JM -> NAD_MALI_JM
Family.MALI_G610_G710 -> NAD_MALI_G710
Family.MALI_G615 -> NAD_MALI_G615
Family.MALI_G720 -> NAD_MALI_G720
else -> null
}
val kbase = NAD_MALI_KBASE.takeIf { sdk >= MALI_KBASE_MIN_SDK && GpuInfo.maliKbaseCovered(gpu.name) }
if (pairs.isEmpty()) return kbase ?: family
fun listed(key: String?) = key?.takeIf { k -> pairs.any { it.key == k && it.complete } }
return listed(kbase) ?: listed(family) ?: kbase ?: family
}
fun newestDdTurnip(pairs: List<DriverPair>): String? = pairs
.filter { it.key.startsWith("$DD_TURNIP:") && it.complete }
.maxByOrNull { p ->
@@ -24,8 +24,22 @@ data class GpuInfo(
A7XX("Adreno 7xx"),
A6XX("Adreno 6xx"),
ADRENO_UNKNOWN("Adreno"),
POWERVR("PowerVR"),
/** Mali on Arm's kbase driver, by the open PanVK build each generation needs. */
MALI_JM("Mali (G52-G78)"),
MALI_G610_G710("Mali-G610/G710"),
MALI_G615("Mali-G615"),
MALI_G720("Mali-G720"),
/** Mali-G715/G725/G925: only the one-binary PanVK kbase build covers them (Android 15+). */
MALI_LATEST("Mali-G715/G725/G925"),
/** A Mali no open driver build covers: the Vulkan bridge is its only path. */
MALI_OTHER("Mali"),
NOT_ADRENO("Not an Adreno GPU");
val mali: Boolean get() = name.startsWith("MALI_")
fun label(gpuName: String): String = if (this == POWERVR && gpuName.contains("Xclipse", ignoreCase = true)) "Samsung Xclipse" else label
fun label(context: Context): String = if (this == NOT_ADRENO) context.getString(R.string.gpuinfo_not_adreno) else label
}
@@ -47,10 +61,16 @@ data class GpuInfo(
val supportText: String
get() = when (support) {
Support.TESTED -> "Supported"
Support.UNTESTED -> if (isA850) "Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device"
else if (family == Family.A7XX_LOW) "Experimental: its drivers are test builds"
else "Outside tested hardware (Adreno 650, 725 and newer): it may not run"
Support.UNSUPPORTED -> "Not supported: DroidDeck needs an Adreno (Snapdragon) GPU"
Support.UNTESTED -> when {
family == Family.POWERVR -> if (name.contains("Xclipse", ignoreCase = true)) "Experimental: RADV or the system Xclipse driver"
else "System PowerVR driver: compatibility varies by device"
family == Family.MALI_OTHER -> "Experimental: Mali through the phone's own driver (Venus)"
family.mali -> "Experimental: open Mali driver (test builds)"
isA850 -> "Experimental Adreno 850 support: requires compatible experimental display and game drivers; not verified on this device"
family == Family.A7XX_LOW -> "Experimental: its drivers are test builds"
else -> "Outside tested hardware (Adreno 650, 725 and newer): it may not run"
}
Support.UNSUPPORTED -> "Not supported: no compatible graphics backend is available for this GPU"
}
fun supportText(bridge: Boolean): String = when {
@@ -68,8 +88,9 @@ data class GpuInfo(
fun supportText(context: Context): String = context.getString(when (support) {
Support.TESTED -> R.string.gpuinfo_supported
Support.UNTESTED -> when {
family == Family.POWERVR -> if (name.contains("Xclipse", ignoreCase = true)) R.string.gpuinfo_xclipse else R.string.gpuinfo_powervr
isA850 -> R.string.gpuinfo_a850_experimental
family == Family.A7XX_LOW -> R.string.gpuinfo_experimental
family == Family.A7XX_LOW || family.mali -> R.string.gpuinfo_experimental
else -> R.string.gpuinfo_below_tested
}
Support.UNSUPPORTED -> R.string.gpuinfo_unsupported
@@ -91,10 +112,20 @@ data class GpuInfo(
{ VulkanInfo.cachedOrNull()?.get("device") },
{ platformGpuModel },
) else 0 to ""
val family = familyOf(adreno, model)
// Mali, named by the vendor's Vulkan driver ("Mali-G720-Immortalis MC12") or by kbase.
val mali = if (adreno || !File("/dev/mali0").exists()) null else maliName()
val family = familyOf(adreno, model, SystemVulkanDriver.isPowerVr(), mali)
val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true)
return GpuInfo(
name = if (!adreno) Build.HARDWARE.ifBlank { UNNAMED } else if (model > 0) "Adreno $model" else "Adreno",
name = when {
family == Family.POWERVR -> SystemVulkanDriver.gpuName().let { gpu ->
VulkanInfo.cachedOrNull()?.get("device")?.takeIf { it.contains(gpu, ignoreCase = true) } ?: gpu
}
mali != null && mali.isNotEmpty() -> mali
!adreno -> Build.HARDWARE.ifBlank { UNNAMED }
model > 0 -> "Adreno $model"
else -> "Adreno"
},
model = model, family = family, soc = soc,
oneUi8Gen2 = samsung && model == 740,
kgslName = raw.orEmpty(), modelSource = source, kgslChipId = chipId,
@@ -136,7 +167,68 @@ data class GpuInfo(
""
}
internal fun familyOf(adreno: Boolean, model: Int): Family = when {
/**
* The Mali's name, "" when nothing names it: the vendor Vulkan driver's own name when this
* process has asked it, kbase's gpuinfo where SELinux lets the app read it (most phones do
* not), else the GPU the chip is known to carry ([MALI_SOCS]).
*/
private fun maliName(): String =
VulkanInfo.cachedOrNull()?.get("device")?.takeIf { it.contains("Mali", ignoreCase = true) }
?: FileUtils.readString(File("/sys/class/misc/mali0/device/gpuinfo"))?.trim()?.takeIf { it.contains("Mali", ignoreCase = true) }
?.substringBefore(" ")
?: maliOfSoc(socIds())
?: ""
/** The chip's names as the platform gives them: "mt6989", "MT6989", "gs201". */
private fun socIds(): List<String> = listOfNotNull(
if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL else null,
systemProperty("ro.board.platform"), systemProperty("ro.soc.model"), Build.HARDWARE, Build.BOARD,
).filter { it.isNotBlank() }
/** Chips whose Mali is known for certain (MediaTek Dimensity / Helio / Kompanio, Google Tensor). */
private val MALI_SOCS = mapOf(
"mt6993" to "Mali-G1-Ultra", "mt6991" to "Mali-G925", "mt6989" to "Mali-G720", "mt6899" to "Mali-G720", "mt6985" to "Mali-G715",
"mt6983" to "Mali-G710", "mt6897" to "Mali-G615", "mt6878" to "Mali-G615", "mt6895" to "Mali-G610",
"mt6896" to "Mali-G610", "mt6886" to "Mali-G610", "mt6893" to "Mali-G77", "mt6891" to "Mali-G77",
"mt6889" to "Mali-G77", "mt6885" to "Mali-G77", "mt6877" to "Mali-G68", "mt6853" to "Mali-G57",
"mt6833" to "Mali-G57", "mt6835" to "Mali-G57", "mt6789" to "Mali-G57", "mt6785" to "Mali-G76",
"mt6781" to "Mali-G52", "mt6769" to "Mali-G52", "mt8192" to "Mali-G57", "mt8195" to "Mali-G57",
"gs101" to "Mali-G78", "gs201" to "Mali-G710", "zuma" to "Mali-G715", "zumapro" to "Mali-G715",
"s5e8835" to "Mali-G68", "s5e8825" to "Mali-G68",
)
/** The Mali [ids] name a chip of, "Mali-G720 (by chip mt6989)", or null for an unknown chip. */
internal fun maliOfSoc(ids: List<String>): String? = ids.firstNotNullOfOrNull { id ->
MALI_SOCS[id.trim().lowercase()]?.let { "$it (by chip ${id.trim().lowercase()})" }
}
/** The number in a Mali's name: 720 for "Mali-G720-Immortalis MC12". */
fun maliNumber(name: String): Int? =
Regex("""G(\d{2,3})""", RegexOption.IGNORE_CASE).find(name)?.groupValues?.get(1)?.toIntOrNull()
/**
* The Malis the one-binary PanVK kbase build covers (arch v9-v13): G57/G68/G77/G78,
* G610/G710, G615/G715, G720/G725 and G925. Not the older Bifrost G52/G76.
*/
fun maliKbaseCovered(name: String): Boolean =
maliNumber(name) in setOf(57, 68, 77, 78, 610, 710, 615, 715, 720, 725, 925)
/** The PanVK generation a Mali name belongs to; MALI_OTHER when none of the builds covers it. */
internal fun maliFamily(name: String): Family {
val number = maliNumber(name) ?: return Family.MALI_OTHER
return when (number) {
31, 51, 52, 57, 68, 71, 72, 76, 77, 78 -> Family.MALI_JM
610, 710 -> Family.MALI_G610_G710
615 -> Family.MALI_G615
720 -> Family.MALI_G720
715, 725, 925 -> Family.MALI_LATEST
else -> Family.MALI_OTHER
}
}
internal fun familyOf(adreno: Boolean, model: Int, powerVr: Boolean = false, mali: String? = null): Family = when {
!adreno && powerVr -> Family.POWERVR
!adreno && mali != null -> maliFamily(mali)
!adreno -> Family.NOT_ADRENO
model == 0 -> Family.ADRENO_UNKNOWN
model >= 800 -> Family.A8XX
@@ -3,8 +3,12 @@ package com.droiddeck.launcher.gpu;
import android.content.Context;
import android.util.Log;
import com.droiddeck.launcher.R;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
public final class LinuxVulkanDriver {
private static final String TAG = "LinuxVulkanDriver";
@@ -25,15 +29,36 @@ public final class LinuxVulkanDriver {
return values;
}
public static String resolveIcdPath(Context context, String value) {
if (value == null || value.isEmpty()) return null;
public static String optionLabel(Context context, String value) {
if (value == null || value.isEmpty()) return SystemVulkanDriver.isPowerVr()
? context.getString(R.string.gpu_system_powervr) : "Runtime default (built into the runtime)";
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
String icd = m.getIcdPath(value);
if (icd == null) {
Log.w(TAG, "imported Linux driver \"" + value + "\" is gone; using the runtime's own driver");
return null;
}
Log.i(TAG, "Linux session draws with imported driver " + value + " (" + icd + ")");
if (!m.isInstalled(value)) return value + (SystemVulkanDriver.isPowerVr()
? " (imported, missing)" : " (imported, missing - uses the runtime default)");
String ver = m.getDriverVersion(value);
return m.getDriverName(value) + (ver.isEmpty() ? "" : " " + ver) + " (imported)";
}
public static String resolveIcdPath(Context context, String value) {
boolean powerVr = SystemVulkanDriver.isPowerVr();
return resolveIcdPath(value, powerVr,
() -> SystemVulkanDriver.icdPath(context), id -> {
String icd = new LinuxVulkanDriverManager(context).getIcdPath(id);
if (icd == null) Log.w(TAG, "imported Linux driver \"" + id + "\" is gone"
+ (powerVr ? "" : "; using the runtime's own driver"));
else Log.i(TAG, "Linux session draws with imported driver " + id + " (" + icd + ")");
return icd;
});
}
/** Resolve the selected backend before looking up an imported driver. */
static String resolveIcdPath(String value, boolean powerVr, Supplier<String> systemIcd,
Function<String, String> importedIcd) {
if (SystemVulkanDriver.usesDefault(powerVr, value)) return systemIcd.get();
if (value == null || value.isEmpty()) return null;
String icd = importedIcd.apply(value);
if (powerVr && icd == null) throw new IllegalStateException(
"Selected Linux Vulkan driver \"" + value + "\" is unavailable. Select an installed driver or use Auto.");
return icd;
}
}
@@ -45,7 +45,9 @@ public class LinuxVulkanDriverManager {
public boolean isInstalled(String id) {
if (id == null || id.isEmpty() || id.contains("/") || id.contains("..")) return false;
File dir = getDriverDir(id);
return new File(dir, LIB_NAME).isFile() && new File(dir, ICD_NAME).isFile();
if (!new File(dir, ICD_NAME).isFile()) return false;
for (String name : STORED_NAMES) if (new File(dir, name).isFile()) return true;
return false;
}
public String getIcdPath(String id) {
@@ -107,10 +109,10 @@ public class LinuxVulkanDriverManager {
if (entry.isDirectory()) continue;
String base = new File(entry.getName()).getName();
if (base.isEmpty()) continue;
if (base.startsWith("libvulkan_freedreno") && base.endsWith(".so")) {
if (soName != null) Log.w(TAG, "zip has several libvulkan_freedreno*.so; using the first (" + soName + ")");
if (isDriverLibrary(base)) {
if (soName != null) Log.w(TAG, "zip has several driver libraries; using the first (" + soName + ")");
else {
Files.copy(zis, new File(tmpDir, LIB_NAME).toPath(), StandardCopyOption.REPLACE_EXISTING);
Files.copy(zis, new File(tmpDir, storedName(base)).toPath(), StandardCopyOption.REPLACE_EXISTING);
soName = base;
}
} else if (base.equals(META_NAME)) {
@@ -142,7 +144,8 @@ public class LinuxVulkanDriverManager {
if (soName == null) {
throw new IllegalArgumentException(context.getString(R.string.lvd_no_library));
}
File so = new File(tmpDir, LIB_NAME);
String stored = storedName(soName);
File so = new File(tmpDir, stored);
if (!isAarch64Elf(so)) {
throw new IllegalArgumentException(context.getString(R.string.lvd_not_aarch64, soName));
}
@@ -167,7 +170,7 @@ public class LinuxVulkanDriverManager {
JSONObject icd = new JSONObject();
icd.put("file_format_version", "1.0.0");
JSONObject icdBody = new JSONObject();
icdBody.put("library_path", new File(dir, LIB_NAME).getAbsolutePath());
icdBody.put("library_path", new File(dir, stored).getAbsolutePath());
icdBody.put("api_version", "1.1.274");
icd.put("ICD", icdBody);
if (!FileUtils.writeString(new File(tmpDir, ICD_NAME), icd.toString(2))) throw new IOException("cannot write icd.json");
@@ -180,6 +183,7 @@ public class LinuxVulkanDriverManager {
meta.put("libc", "glibc");
meta.put("minGlibc", minGlibc);
meta.put("sourceLibraryName", soName);
meta.put("libraryName", stored);
meta.put("importedAt", System.currentTimeMillis());
if (!FileUtils.writeString(new File(tmpDir, META_NAME), meta.toString(2))) throw new IOException("cannot write meta.json");
@@ -198,6 +202,24 @@ public class LinuxVulkanDriverManager {
return id;
}
/** The names an installed driver's library is kept under; Turnip keeps {@link #LIB_NAME}. */
private static final String[] STORED_NAMES = {LIB_NAME, "libvulkan_panfrost.so", "libvulkan_radeon.so"};
/**
* The name a driver library is installed under: its own driver's (PanVK, RADV), so the session
* log and the graphics report say which driver it is; a Turnip build keeps {@link #LIB_NAME}.
*/
public static String storedName(String soName) {
if (soName != null && soName.startsWith("libvulkan_panfrost")) return "libvulkan_panfrost.so";
if (soName != null && soName.startsWith("libvulkan_radeon")) return "libvulkan_radeon.so";
return LIB_NAME;
}
public static boolean isDriverLibrary(String base) {
return base.endsWith(".so") && (base.startsWith("libvulkan_freedreno")
|| base.startsWith("libvulkan_panfrost") || base.startsWith("libvulkan_radeon"));
}
static String sanitizeId(String name) {
String s = name.trim().replaceAll("[^A-Za-z0-9._-]+", "_").replaceAll("^[._]+", "");
if (s.length() > 64) s = s.substring(0, 64);
@@ -0,0 +1,267 @@
package com.droiddeck.launcher.gpu;
import android.content.Context;
import android.os.Build;
import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
import com.droiddeck.launcher.core.AddonPack;
import com.droiddeck.launcher.core.FileUtils;
import com.droiddeck.launcher.core.TarZst;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.TreeSet;
import java.util.UUID;
import java.util.function.Predicate;
import org.json.JSONObject;
/** Isolated glibc-to-Android Vulkan bridge. It does not replace the rootfs's Mesa libraries. */
public final class SystemVulkanDriver {
/** Vendor HALs the bridge loads. Samsung Xclipse (Exynos, sgpu) is experimental. */
private static final String[] HALS = {
"/vendor/lib64/hw/vulkan.powervr.so",
"/vendor/lib64/hw/vulkan.samsung.so"
};
private static final String[] REQUIRED = {
"lib/libhybris-vulkan-icd.so.0", "lib/libhybris-common.so.1",
"lib/libhybris/linker/q.so", "lib/libVkLayer_hybris_compat.so",
"run-proton.py", "wsi/libVkLayer_window_system_integration.so",
"wsi/VkLayer_window_system_integration.json",
"dxvk/x32/d3d8.dll", "dxvk/x32/d3d9.dll", "dxvk/x32/d3d10core.dll",
"dxvk/x32/d3d11.dll", "dxvk/x32/dxgi.dll",
"dxvk/x64/d3d8.dll", "dxvk/x64/d3d9.dll", "dxvk/x64/d3d10core.dll",
"dxvk/x64/d3d11.dll", "dxvk/x64/dxgi.dll"
};
/** Rootfs directory of the Xclipse layer the apk stages (SessionFiles). */
private static final String XCLIPSE_LAYER_DIR = "/usr/local/lib/droiddeck-xclipse";
private SystemVulkanDriver() {}
/**
* The first vendor HAL present, or null. An Exynos with a Mali (Exynos 1280/1380: /dev/mali0)
* may name its HAL vulkan.samsung.so too; that is a Mali, not an Xclipse, and is not taken.
*/
public static String hal() {
for (String path : HALS) {
if (!new File(path).isFile()) continue;
if (path.endsWith("/vulkan.samsung.so") && new File("/dev/mali0").exists()) continue;
return path;
}
return null;
}
/** Samsung's Xclipse (Exynos, sgpu) rather than PowerVR. */
public static boolean isXclipse() {
String hal = hal();
return hal != null && hal.endsWith("/vulkan.samsung.so");
}
/** The system-driver GPU family, for labels. */
public static String gpuName() { return isXclipse() ? "Xclipse" : "PowerVR"; }
/** Whether a system-driver GPU (PowerVR or Xclipse) is present; the name predates Xclipse. */
public static boolean isPowerVr() { return hal() != null; }
/** HAL detection names the GPU; launching also needs the real DRM render node. */
public static boolean isAvailable() { return isPowerVr() && renderNodeAvailable(); }
public static boolean renderNodeAvailable() {
return renderNodePath() != null;
}
/** Select the actual PowerVR node, including devices where another GPU owns renderD128. */
public static String renderNodePath() {
String[] nodes = new File("/dev/dri").list();
if (nodes == null) nodes = new File("/sys/class/drm").list();
return findRenderNode(nodes, SystemVulkanDriver::renderNodeAvailable);
}
static String findRenderNode(String[] nodes, Predicate<String> available) {
TreeSet<String> candidates = new TreeSet<>();
// Android can deny directory listing while allowing direct access. Probe the kernel's
// reserved render range too; directory entries also cover dynamically allocated minors.
for (int minor = 128; minor < 192; minor++) candidates.add("renderD" + minor);
if (nodes != null) for (String node : nodes)
if (node.matches("renderD[0-9]+")) candidates.add(node);
for (String node : candidates) {
String path = "/dev/dri/" + node;
if (available.test(path)) return path;
}
return null;
}
private static boolean renderNodeAvailable(String node) {
try {
if (!renderNodeAvailable(OsConstants.S_ISCHR(Os.stat(node).st_mode),
Os.access(node, OsConstants.R_OK), Os.access(node, OsConstants.W_OK))) return false;
return powerVrDevice(new File("/sys/class/drm/" + new File(node).getName() + "/device"));
} catch (ErrnoException error) {
return false;
}
}
static boolean powerVrDriver(String driver) {
return "pvrsrvkm".equals(driver) || "pvr".equals(driver) || "powervr".equals(driver)
|| "sgpu".equals(driver);
}
static boolean powerVrDevice(File device) {
try {
return powerVrDriver(Files.readSymbolicLink(new File(device, "driver").toPath())
.getFileName().toString());
} catch (IOException error) {
// Some Android policies expose uevent but deny reading the driver symlink.
try (BufferedReader input = Files.newBufferedReader(
new File(device, "uevent").toPath(), StandardCharsets.US_ASCII)) {
String line;
while ((line = input.readLine()) != null)
if (line.startsWith("DRIVER=")) return powerVrDriver(line.substring(7));
} catch (IOException ignored) { }
return false;
}
}
static boolean renderNodeAvailable(boolean characterDevice, boolean readable, boolean writable) {
return characterDevice && readable && writable;
}
public static boolean usesDefault(String choice) {
return usesDefault(isPowerVr(), choice);
}
static boolean usesDefault(boolean powerVr, String choice) {
return powerVr && (choice == null || choice.isEmpty());
}
/** APK-versioned directories stay intact while an older session still has libraries mapped. */
public static synchronized File prepare(Context context) throws IOException {
if (!isPowerVr()) throw new IOException("System PowerVR Vulkan driver is unavailable");
if (!renderNodeAvailable()) throw new IOException(
"System PowerVR requires an identifiable, readable and writable DRM render node");
if (!AddonPack.POWERVR.await(context)) throw new IOException(
"Couldn't download the PowerVR graphics runtime. Check your connection and try again.");
File target = runtimeDirectory(context);
File base = target.getParentFile();
if (complete(target)) return target;
if (!base.isDirectory() && !base.mkdirs()) throw new IOException("Cannot create system Vulkan directory");
File staged = new File(base, ".stage-" + UUID.randomUUID());
try {
try (FileInputStream archive = new FileInputStream(AddonPack.POWERVR.file(context, "runtime.tzst"))) {
if (!TarZst.extract(archive, staged)) throw new IOException("Cannot unpack system Vulkan runtime");
}
for (String name : REQUIRED)
if (!present(staged, name)) throw new IOException("Missing system Vulkan component: " + name);
if (!new File(staged, "run-proton.py").canExecute())
throw new IOException("System Vulkan Proton wrapper is not executable");
JSONObject library = new JSONObject();
library.put("library_path", new File(target, REQUIRED[0]).getPath());
library.put("api_version", "1.3.0");
JSONObject manifest = new JSONObject();
manifest.put("file_format_version", "1.0.0");
manifest.put("ICD", library);
Files.write(new File(staged, "icd.json").toPath(), manifest.toString().getBytes(StandardCharsets.UTF_8));
if (target.exists()) throw new IOException("Incomplete system Vulkan runtime directory: " + target.getName());
if (!staged.renameTo(target)) throw new IOException("Cannot publish system Vulkan runtime");
return target;
} catch (org.json.JSONException error) {
throw new IOException("Cannot write system Vulkan manifest", error);
} finally {
if (staged.exists()) FileUtils.delete(staged);
}
}
/** The current APK's versioned runtime path, without extracting or modifying it. */
public static File runtimeDirectory(Context context) throws IOException {
String version;
if (!AddonPack.POWERVR.installed(context)) throw new IOException("PowerVR graphics runtime is not installed");
try (BufferedReader input = new BufferedReader(new InputStreamReader(
new FileInputStream(AddonPack.POWERVR.file(context, "version.txt")), StandardCharsets.US_ASCII))) {
version = input.readLine();
}
if (version == null || !version.matches("[0-9a-f]{64}")) throw new IOException("Invalid system Vulkan runtime version");
return new File(new File(context.getFilesDir(), "system_vulkan"), version);
}
/** Collect abandoned stages, and obsolete versions once older guests can no longer load them. */
public static synchronized void pruneUnused(Context context, boolean guestsStopped) throws IOException {
pruneUnused(runtimeDirectory(context), guestsStopped);
}
static synchronized void pruneUnused(File current, boolean guestsStopped) {
File base = current.getParentFile();
if (base == null || Files.isSymbolicLink(base.toPath()) || Files.isSymbolicLink(current.toPath())) return;
File[] entries = base.listFiles();
if (entries == null) return;
// Retain the previous good version if publishing the replacement failed.
boolean pruneVersions = guestsStopped && complete(current);
for (File entry : entries) {
if (entry.equals(current)) continue;
String name = entry.getName();
boolean oldVersion = pruneVersions && name.matches("[0-9a-f]{64}");
boolean abandonedStage = name.matches("\\.stage-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
// The prepare monitor excludes any extraction still writing a .stage directory.
if (oldVersion || abandonedStage) FileUtils.delete(entry);
}
}
private static boolean complete(File directory) {
if (!new File(directory, "icd.json").isFile()) return false;
for (String name : REQUIRED) if (!present(directory, name)) return false;
return new File(directory, "run-proton.py").canExecute();
}
private static boolean present(File directory, String name) {
File file = new File(directory, name);
return file.isFile() && file.length() > 0;
}
public static String icdPath(Context context) {
try {
return new File(prepare(context), "icd.json").getPath();
} catch (IOException error) {
throw new IllegalStateException("System Vulkan runtime is unavailable", error);
}
}
public static void addEnvironment(Context context, List<String> environment) {
File directory;
try { directory = prepare(context); }
catch (IOException error) { throw new IllegalStateException("System Vulkan runtime is unavailable", error); }
String node = renderNodePath();
if (node == null) throw new IllegalStateException("System PowerVR render node is unavailable");
environment.add("HYBRIS_ANDROID_SDK_VERSION=" + Build.VERSION.SDK_INT);
environment.add("HYBRIS_VULKAN_HAL=" + hal());
environment.add("HYBRIS_LINKER_DIR=" + new File(directory, "lib/libhybris/linker").getPath());
// Prefer framework dependencies for the system Vulkan loader, including libbase.so.
environment.add("HYBRIS_LD_LIBRARY_PATH=/system/lib64:/system_ext/lib64:/vendor/lib64/egl:/vendor/lib64/hw:/vendor/lib64");
boolean xclipse = isXclipse();
// Xclipse gets its own layer (tools/linuxfs/xclipse-layer) in front of everything: it sets
// bionic's environ for the driver's shader compiler, among other driver workarounds. The
// session's own clients need nothing else; games keep the compat layer's BC emulation.
String layers = xclipse ? "VK_LAYER_DROIDDECK_xclipse" : "VK_LAYER_HYBRIS_compat";
environment.add("VK_LAYER_PATH=" + new File(directory, "lib").getPath() + (xclipse ? ":" + XCLIPSE_LAYER_DIR : ""));
environment.add("VK_INSTANCE_LAYERS=" + layers);
// Proton game launches add their WSI layer in front of these (droiddeck-game-env).
environment.add("DROIDDECK_HYBRIS_LAYERS=" + (xclipse ? layers + ":VK_LAYER_HYBRIS_compat" : layers));
if (xclipse) environment.add("DROIDDECK_HYBRIS_LAYER_PATH=" + XCLIPSE_LAYER_DIR);
// DXVK 3 needs 256 bytes of push constants; this driver has 128.
if (xclipse) environment.add("DROIDDECK_HYBRIS_DXVK=dxvk-2.6.2");
// The Android driver has a render node, but no KMS primary node. SDL presents
// through the wrapper's Wayland Vulkan swapchain instead of a KMS-style path.
environment.add("BL_GAMESCOPE_BACKEND=sdl");
// The Android pvr kernel accepts Vulkan DMA-BUF imports but rejects PRIME GEM handles.
environment.add("BL_POWERVR_DRM_HANDLES=1");
environment.add("BL_POWERVR_RENDER_NODE=" + node);
// Inner Gamescope/Xwayland lacks the bridge's Android-buffer WSI protocols.
environment.add("BL_STEAM_GL_PRESENT=1");
// Only actual Proton game launches use the bundled DXVK and X11 WSI layer.
environment.add("DROIDDECK_POWERVR_RUNTIME=" + directory.getPath());
}
}
@@ -263,7 +263,24 @@ public final class TurnipDriver {
}
private String choose() {
SessionPrefs.ensurePowerVrAutoDrivers(context);
String chosen = SessionPrefs.androidDriver(context);
// Mali (Venus): the phone's own driver draws the screen, as Venus replays on it.
if (com.droiddeck.launcher.session.VenusComponent.wanted(context)) {
Log.i(TAG, "Mali (Venus): display on the system Vulkan loader");
return null;
}
// A Mali under Auto draws its display on Android's own Vulkan loader, whatever an earlier
// build set: a PanVK Android half fails on Mali gralloc. A manual pick is respected.
if (chosen != null && !chosen.isEmpty() && new File("/dev/mali0").exists()
&& !com.droiddeck.launcher.core.DeviceSupport.INSTANCE.adreno()
&& SessionPrefs.GPU_DRIVERS_AUTO.equals(SessionPrefs.INSTANCE.gpuDriverMode(context))) {
DriverBundle.Bundle bundle = DriverBundle.INSTANCE.containing(context, chosen, false);
if (bundle != null && DriverPairs.INSTANCE.isNonAdreno(bundle.getId())) {
Log.i(TAG, "Mali under Auto: display on the system Vulkan loader, not " + chosen);
return null;
}
}
if (chosen != null && !chosen.isEmpty()) {
if (BUNDLED.contains(chosen)) {
Log.i(TAG, "driver pinned by the user: " + chosen);
@@ -289,6 +306,7 @@ public final class TurnipDriver {
if (forced.startsWith("a7")) return DRIVER_A7XX;
if (forced.startsWith("a6")) return DRIVER_A6XX;
}
if (SystemVulkanDriver.isPowerVr()) return null;
String quest = QuestExperimental.INSTANCE.defaultAndroidDriver();
if (quest != null) return quest;
if (com.droiddeck.launcher.core.DeviceSupport.INSTANCE.vkBridge(context)) {
@@ -296,7 +314,7 @@ public final class TurnipDriver {
return null;
}
GpuInfo gpu = gpuDetector.get();
if (gpu.getFamily() == GpuInfo.Family.NOT_ADRENO) {
if (gpu.getFamily() == GpuInfo.Family.NOT_ADRENO || gpu.getFamily().getMali()) {
Log.i(TAG, "not an Adreno GPU; leaving the display driver to the system");
return null;
}
@@ -22,12 +22,17 @@ object TurnipReleases {
private const val KEY_PICKS = "autoPicks"
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 pair: String = "", val bundle: Boolean = false)
val sha256: String = "", val pair: String = "", val bundle: Boolean = false,
val assetId: Long = 0, val updatedAt: String = "") {
/** "2026-10-15" from GitHub's updated_at; empty when the check did not record it. */
val builtOn: String get() = updatedAt.take(10)
}
class Check(val assets: List<Asset>, val latest: List<Pair<String, String>>, val failed: List<String>, val checkedAt: Long)
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?)
/** [prerelease]: a source whose bundles are all test builds offers them from pre-releases too. */
private class Source(val label: String, val repo: String, val prerelease: Boolean = false, val classify: (name: String, tag: String) -> Kind?)
private val SOURCES = listOf(
Source("Banners-Turnip", "The412Banner/Banners-Turnip") { name, tag ->
@@ -56,8 +61,22 @@ object TurnipReleases {
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)
},
// <Id>-Pair.zip: open drivers for GPUs that are not Adreno (PanVK for Mali, RADV for
// Xclipse), both halves in one zip. One release per driver, replaced in place on each
// rebuild; every one is a test build, published as a pre-release.
Source(NON_ADRENO_LABEL, NON_ADRENO_REPO, prerelease = true) { name, _ ->
val m = Regex("""^(RADV-Xclipse(?:-[A-Za-z0-9]+)*?|PanVK-[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*?)-Pair\.zip$""").find(name) ?: return@Source null
val key = DriverPairs.nonAdreno(m.groupValues[1])
Kind(false, "Android + Linux · " + DriverPairs.nonAdrenoName(key), key, bundle = true)
},
)
private const val NON_ADRENO_REPO = "The412Banner/droiddeck-nonadreno-drivers"
const val NON_ADRENO_LABEL = "Non-Adreno"
private fun sources(): List<Source> =
if (com.droiddeck.launcher.core.DeviceSupport.adreno()) SOURCES.filter { it.repo != NON_ADRENO_REPO } else SOURCES
fun autoPicks(context: Context): List<AutoPicks.Rule> =
AutoPicks.parse(prefs(context).getString(KEY_PICKS, null)) ?: AutoPicks.BUILT_IN
@@ -71,9 +90,13 @@ object TurnipReleases {
val latest = JSONArray()
val failed = ArrayList<String>()
var lastError: Exception? = null
for (src in SOURCES) {
val sources = sources()
for (src in sources) {
try {
val releases = JSONArray(get(context, "https://api.github.com/repos/${src.repo}/releases?per_page=15"))
// The non-Adreno repo keeps one release per driver plus many component builds (gamescope,
// Venus): its driver pairs fall past the first 15, so it is read in one full page.
val perPage = if (src.repo == NON_ADRENO_REPO) 100 else 15
val releases = JSONArray(get(context, "https://api.github.com/repos/${src.repo}/releases?per_page=$perPage"))
val seen = HashSet<String>()
var newest: String? = null
for (i in 0 until releases.length()) {
@@ -86,7 +109,7 @@ object TurnipReleases {
val a = list.getJSONObject(j)
val name = a.getString("name")
val kind = src.classify(name, tag) ?: continue
if (kind.bundle && r.optBoolean("prerelease")) continue
if (kind.bundle && r.optBoolean("prerelease") && !src.prerelease) continue
val linux = kind.linux
val label = kind.label
val sha = Hashes.githubSha256(a.optString("digest")) ?: continue
@@ -94,7 +117,7 @@ object TurnipReleases {
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("pair", kind.pair)
.put("bundle", kind.bundle))
.put("bundle", kind.bundle).put("id", a.optLong("id")).put("updated_at", a.optString("updated_at")))
}
}
if (newest != null) latest.put(JSONObject().put("source", src.label).put("tag", newest))
@@ -103,7 +126,7 @@ object TurnipReleases {
lastError = e
}
}
if (failed.size == SOURCES.size) throw lastError ?: IOException("no source answered")
if (failed.size == sources.size) throw lastError ?: IOException("no source answered")
runCatching { get(context, AutoPicks.URL, AutoPicks.URL) }
.onFailure { Log.i(TAG, "auto picks: ${it.message}") }
.getOrNull()?.takeIf { AutoPicks.parse(it) != null }
@@ -154,7 +177,7 @@ object TurnipReleases {
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.optString("pair", ""),
a.optBoolean("bundle", false)))
a.optBoolean("bundle", false), a.optLong("id"), a.optString("updated_at", "")))
}
val latest = ArrayList<Pair<String, String>>()
val l = json.optJSONArray("latest") ?: JSONArray()
@@ -165,16 +188,53 @@ object TurnipReleases {
return Check(out, latest, failed, json.optLong("checkedAt"))
}
fun installedId(context: Context, asset: Asset, isInstalled: (String) -> Boolean): String? =
fun installedId(context: Context, asset: Asset, isInstalled: (String) -> Boolean): String? {
val d = downloads(context)
if (DriverPairs.isNonAdreno(asset.pair) && asset.sha256.isNotEmpty() &&
!asset.sha256.equals(d.optString(SHA_PREFIX + asset.name, asset.sha256), ignoreCase = true)) return null
return d.optString(asset.name, "").takeIf { it.isNotEmpty() && isInstalled(it) }
}
private const val SHA_PREFIX = "sha256:"
private const val ASSET_ID_PREFIX = "asset:"
private const val UPDATED_PREFIX = "updated:"
/** The id an open non-Adreno pair's asset was installed as, whichever build of it that was. */
fun installedIdAnyBuild(context: Context, asset: Asset, isInstalled: (String) -> Boolean): String? =
downloads(context).optString(asset.name, "").takeIf { it.isNotEmpty() && isInstalled(it) }
/**
* An open non-Adreno pair is rebuilt in place under the same tag: a different digest, asset id
* or upload time than the one installed means a newer build.
*/
fun updateAvailable(context: Context, asset: Asset): Boolean {
if (!DriverPairs.isNonAdreno(asset.pair)) return false
val d = downloads(context)
if (d.optString(asset.name, "").isEmpty()) return false
val sha = d.optString(SHA_PREFIX + asset.name, "")
val id = d.optLong(ASSET_ID_PREFIX + asset.name, 0)
val updated = d.optString(UPDATED_PREFIX + asset.name, "")
return (sha.isNotEmpty() && asset.sha256.isNotEmpty() && !sha.equals(asset.sha256, ignoreCase = true)) ||
(id != 0L && asset.assetId != 0L && id != asset.assetId) ||
(updated.isNotEmpty() && asset.updatedAt.isNotEmpty() && updated != asset.updatedAt)
}
/** When the installed build of [asset] was uploaded, as recorded at download ("" if unknown). */
fun installedBuiltOn(context: Context, asset: Asset): String = downloads(context).optString(UPDATED_PREFIX + asset.name, "").take(10)
fun isDownloaded(context: Context, id: String): Boolean {
val d = downloads(context)
return d.keys().asSequence().any { d.optString(it) == id }
}
fun recordDownload(context: Context, asset: Asset, id: String) {
prefs(context).edit().putString(KEY_DOWNLOADS, downloads(context).put(asset.name, id).toString()).apply()
val d = downloads(context).put(asset.name, id)
if (DriverPairs.isNonAdreno(asset.pair)) {
if (asset.sha256.isNotEmpty()) d.put(SHA_PREFIX + asset.name, asset.sha256)
if (asset.assetId != 0L) d.put(ASSET_ID_PREFIX + asset.name, asset.assetId)
if (asset.updatedAt.isNotEmpty()) d.put(UPDATED_PREFIX + asset.name, asset.updatedAt)
}
prefs(context).edit().putString(KEY_DOWNLOADS, d.toString()).apply()
}
fun forget(context: Context, id: String) {
@@ -9,7 +9,7 @@ internal object DroidDeckHudConfig {
"hudOutline" to "40", "hudOutlineAccent" to "1",
"showFPS" to "1", "showFPSGraph" to "1", "showCPUUsage" to "1", "showCPULoad" to "1", "showGPULoad" to "1",
"showVram" to "1", "showRAM" to "1", "showPower" to "1", "showTemp" to "1", "showBatteryTemp" to "1",
"showGpuTemp" to "0", "showBattery" to "0", "showLow001" to "1", "fpsDecimal" to "1", "showPerCore" to "1",
"showGpuTemp" to "0", "showBattery" to "0", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1", "fpsDecimal" to "1", "showPerCore" to "1",
"showSwap" to "1", "showNet" to "1", "showResolution" to "1", "showProton" to "1", "showSession" to "1",
"showClock" to "1", "showEngine" to "1", "showRenderer" to "1", "showGpuModel" to "1",
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
@@ -37,11 +37,11 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
fun from(token: String?): DroidDeckHudSize =
values().firstOrNull { it.token.equals(token, ignoreCase = true) } ?: FULL
val MINIMAL_CHIPS = setOf("FPS", "FPS graph", "0.01% low", "FPS .1", "Engine", "Clock")
val MINIMAL_CHIPS = setOf("FPS", "FPS graph", "1% low", "0.1% low", "0.01% low", "FPS .1", "Engine", "Clock")
val PILL_CHIPS = setOf("FPS", "FPS graph", "GPU", "CPU", "VRAM", "RAM", "Battery", "GPU model", "FPS .1", "Engine", "Clock")
val STANDARD_CHIPS = setOf(
"FPS", "FPS graph", "GPU", "GPU temp", "CPU", "VRAM", "RAM", "Power", "Temp",
"Battery", "GPU model", "Engine", "0.01% low", "FPS .1", "Clock",
"Battery", "GPU model", "Engine", "1% low", "0.1% low", "0.01% low", "FPS .1", "Clock",
)
val MEGA_ONLY = setOf(
"Per-core", "Swap", "Network", "Resolution", "Proton", "Wrapper", "DX ver", "Session",
@@ -90,6 +90,8 @@ class DroidDeckHudView(context: Context) : View(context) {
private var showPower = true
private var showBatteryTemp = false
private var showGraph = false
private var showLow1 = true
private var showLow01 = true
private var showLow001 = true
private var fpsDecimal = true
private var showClockTime = true
@@ -299,6 +301,8 @@ class DroidDeckHudView(context: Context) : View(context) {
showPower = cfg.get("showPower", "1") == "1"
showBatteryTemp = cfg.get("showBatteryTemp", "0") == "1"
showGraph = cfg.get("showFPSGraph", "0") == "1"
showLow1 = cfg.get("showLow1", "1") == "1"
showLow01 = cfg.get("showLow01", "1") == "1"
showLow001 = cfg.get("showLow001", "1") == "1"
fpsDecimal = cfg.get("fpsDecimal", "1") == "1"
showClockTime = cfg.get("showClock", "1") == "1"
@@ -750,8 +754,10 @@ class DroidDeckHudView(context: Context) : View(context) {
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
rows.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
rows.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
rows.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
rows.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
if (showLow1)
rows.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
if (showLow01)
rows.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
if (showLow001)
rows.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx)))
}
@@ -799,7 +805,7 @@ class DroidDeckHudView(context: Context) : View(context) {
val tiles = ArrayList<Tile>()
if (showFPS) tiles.add(Tile("FPS", colFps, listOf(Span(fpsText(fpsNow), colValue, valPx, glow = true)),
"${fmt1(fpsAvg)} avg · ${lowText(lows.low1Fps) ?: "—"} 1%", false))
"${fmt1(fpsAvg)} avg" + (if (showLow1) " · ${lowText(lows.low1Fps) ?: "—"} 1%" else ""), false))
if (showFPS) tiles.add(Tile("FRAME", colDim, numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", valPx, unitPx),
"${fmt1(graphMinMs)} – ${fmt1(graphMaxMs)}", false))
if (showGPU && hasGpuStats(s)) tiles.add(Tile("GPU", colGpu, numUnit(s.gpuPercent?.toString(), "%", valPx, unitPx),
@@ -963,11 +969,14 @@ class DroidDeckHudView(context: Context) : View(context) {
Span(fpsText(fpsNow), colValue, if (minGenerating) bigPx * 0.55f else bigPx),
Span("fps", colDim, if (minGenerating) bigUnitPx * 0.8f else bigUnitPx))
val sub = ArrayList<Span>()
sub += Span("1% ", colDim, subPx); sub += Span(lowText(lows.low1Fps) ?: "—", colFps, subPx)
sub += Span(" · 0.1% ", colDim, subPx); sub += Span(lowText(lows.low01Fps) ?: "—", colFps, subPx)
if (showLow001) {
sub += Span(" · 0.01% ", colDim, subPx); sub += Span(lowText(lows.low001Fps) ?: "—", colFps, subPx)
fun low(label: String, value: Float) {
if (sub.isNotEmpty()) sub += Span(" · ", colDim, subPx)
sub += Span("$label ", colDim, subPx)
sub += Span(lowText(value) ?: "—", colFps, subPx)
}
if (showLow1) low("1%", lows.low1Fps)
if (showLow01) low("0.1%", lows.low01Fps)
if (showLow001) low("0.01%", lows.low001Fps)
val footerLabel = listOf(if (showEngine) engineLabel else "", displayServer)
.filter { it.isNotBlank() }.joinToString(" · ")
val hdr = if (hdrState != DroidDeckHudHdr.NONE) hdrLine(footPx) else emptyList()
@@ -979,11 +988,13 @@ class DroidDeckHudView(context: Context) : View(context) {
max(measure(footerLabel, footPx), runWidth(hdr)), if (showGraph) sp(120f) else 0f)
val bigBase = headerBottom + sp(8f) + capHeight(big[0].sizePx)
placeRun(left - inkLeft(big[0].text, big[0].sizePx), bigBase, big, glow = true)
val subBase = bigBase + sp(10f) + capHeight(subPx)
placeRun(left - inkLeft(sub[0].text, subPx), subBase, sub)
var last = subBase
var last = bigBase
if (sub.isNotEmpty()) {
last += sp(10f) + capHeight(subPx)
placeRun(left - inkLeft(sub[0].text, subPx), last, sub)
}
if (showGraph) {
val top = subBase + sp(9f)
val top = last + sp(9f)
graphRect = RectF(left, top, left + colW, top + sp(24f))
last = top + sp(24f)
}
@@ -1042,10 +1053,15 @@ class DroidDeckHudView(context: Context) : View(context) {
val groups = ArrayList<List<Span>>()
run {
val l = ArrayList<Span>()
l += Span("1% ", colDim, rowPx); l += Span(lowText(lows.low1Fps) ?: "—", colFps, rowPx)
l += Span(" 0.1% ", colDim, rowPx); l += Span(lowText(lows.low01Fps) ?: "—", colFps, rowPx)
if (showLow001) { l += Span(" 0.01% ", colDim, rowPx); l += Span(lowText(lows.low001Fps) ?: "—", colFps, rowPx) }
groups += l
fun low(label: String, value: Float) {
if (l.isNotEmpty()) l += Span(" ", colDim, rowPx)
l += Span("$label ", colDim, rowPx)
l += Span(lowText(value) ?: "—", colFps, rowPx)
}
if (showLow1) low("1%", lows.low1Fps)
if (showLow01) low("0.1%", lows.low01Fps)
if (showLow001) low("0.01%", lows.low001Fps)
if (l.isNotEmpty()) groups += l
}
if (showGPU || showGpuTemp) {
val l = arrayListOf(Span("GPU", colGpu, rowPx))
@@ -1208,8 +1224,10 @@ class DroidDeckHudView(context: Context) : View(context) {
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
right.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
right.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
right.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
right.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
if (showLow1)
right.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
if (showLow01)
right.add(HudRow(Span("0.1%", colLo, rowPx), numUnit(lowText(lows.low01Fps), "FPS", rowPx, unitPx)))
if (showLow001)
right.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx)))
}
@@ -22,6 +22,9 @@ object ControllerPrefs {
val sizes = listOf(80, 90, 100, 110, 125)
val deadZones = listOf(0, 5, 8, 12, 15, 20, 25)
const val DEFAULT_DEAD_ZONE_PERCENT = 12
val mappable = listOf(
"a" to R.string.ctrl_button_a, "b" to R.string.ctrl_button_b, "x" to R.string.ctrl_button_x, "y" to R.string.ctrl_button_y,
"lb" to R.string.ctrl_button_lb, "rb" to R.string.ctrl_button_rb, "lt" to R.string.ctrl_button_lt, "rt" to R.string.ctrl_button_rt,
@@ -51,6 +54,7 @@ object ControllerPrefs {
val snap: Boolean,
val customLayout: Boolean,
val mapping: Map<String, String>,
val deadZone: Int,
)
internal fun prefs(context: Context) = context.getSharedPreferences("controller", Context.MODE_PRIVATE)
@@ -72,6 +76,7 @@ object ControllerPrefs {
snap = p.getBoolean("snap", true),
customLayout = p.all.keys.any { it.startsWith("layout.") },
mapping = mappable.associate { (id, _) -> id to target(context, id) },
deadZone = deadZone(context),
)
}
@@ -109,6 +114,13 @@ object ControllerPrefs {
fun rumbleEnabled(context: Context): Boolean = prefs(context).getBoolean("rumble", true)
fun deadZone(context: Context): Int =
prefs(context).getInt("deadZone", DEFAULT_DEAD_ZONE_PERCENT).takeIf { it in deadZones } ?: DEFAULT_DEAD_ZONE_PERCENT
fun setDeadZone(context: Context, percent: Int) {
prefs(context).edit().putInt("deadZone", percent).apply()
}
fun setRumble(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("rumble", on).apply()
}
@@ -0,0 +1,54 @@
package com.droiddeck.launcher.input
import android.view.InputDevice
import android.view.KeyCharacterMap
import android.view.KeyEvent
/**
* Some firmware turns a mouse's right button into Back. Most report it from the mouse itself; REDMAGIC's
* cast mode injects it from no device and without the virtual-hard-key flag that the navigation bar and
* back gesture set, so that form only counts while a mouse is connected.
*/
class MouseBackInput(private val sendRight: (Boolean) -> Unit, private val mouseAttached: () -> Boolean) {
private val held = mutableSetOf<Int>()
fun onKeyEvent(event: KeyEvent, toGuest: Boolean): Boolean {
if (event.keyCode != KeyEvent.KEYCODE_BACK) return false
val device = event.deviceId
val fromMouse = isFromMouse(event)
val injected = isInjectedBack(event)
if (device in held && (fromMouse || injected)) {
if (event.action == KeyEvent.ACTION_UP) {
held.remove(device)
if (held.isEmpty()) sendRight(false)
}
return true
}
if (event.action != KeyEvent.ACTION_DOWN || event.repeatCount > 0 || !toGuest) return false
if (!fromMouse && !(injected && mouseAttached())) return false
if (held.isEmpty()) sendRight(true)
held.add(device)
return true
}
fun cancel() {
if (held.isEmpty()) return
held.clear()
sendRight(false)
}
fun onDeviceRemoved(deviceId: Int) {
if (held.isEmpty()) return
held.remove(deviceId)
if (!mouseAttached()) held.remove(KeyCharacterMap.VIRTUAL_KEYBOARD)
if (held.isEmpty()) sendRight(false)
}
companion object {
fun isFromMouse(event: KeyEvent): Boolean =
event.isFromSource(InputDevice.SOURCE_MOUSE) || event.isFromSource(InputDevice.SOURCE_MOUSE_RELATIVE)
fun isInjectedBack(event: KeyEvent): Boolean =
event.deviceId == KeyCharacterMap.VIRTUAL_KEYBOARD && (event.flags and KeyEvent.FLAG_VIRTUAL_HARD_KEY) == 0
}
}
@@ -550,6 +550,7 @@ class OnScreenControls(
control.ax = if (adaptive) event.getX(index) else control.cx
control.ay = if (adaptive) event.getY(index) else control.cy
control.drag(event.getX(index), event.getY(index))
control.dirty = true
}
if (SessionPrefs.lowLatency(context)) requestUnbufferedDispatch(event)
apply()
@@ -694,15 +695,18 @@ class OnScreenControls(
private fun adaptiveStickAt(x: Float, y: Float): Control? {
if (!settings.adaptiveSticks || editing || buttonsOnly || quickHidden) return null
if (x < safe.left || x >= width - safe.right || y < safe.top || y >= height - safe.bottom) return null
if (controls.any { it.stick < 0 && isVisible(it) && it.contains(x, y, it.radius, 5f) }) return null
return controls.filter {
val dx = x - it.cx
val dy = y - it.cy
val reach = it.radius * 1.4f * sqrt(1.5f)
it.stick >= 0 && isVisible(it) && it.pressedBy == -1 && dx * dx + dy * dy <= reach * reach
}.minByOrNull {
val dx = x - it.cx
val dy = y - it.cy
if (controls.any { control ->
control.stick < 0 && isVisible(control) && control.contains(x, y, control.radius, 5f)
}) return null
return controls.filter { control ->
val dx = if (control.stick == 0) max(0f, x - control.cx) else x - control.cx
val dy = y - control.cy
val reach = control.radius * 1.4f * sqrt(1.5f)
control.stick >= 0 && isVisible(control) && control.pressedBy == -1 &&
dx * dx + dy * dy <= reach * reach
}.minByOrNull { control ->
val dx = x - control.cx
val dy = y - control.cy
dx * dx + dy * dy
}
}
@@ -737,7 +741,10 @@ class OnScreenControls(
bridge.setSystemButtons(controls.any { it.id == "guide" && it.pressedBy != -1 }, qamHeld)
} else {
bridge.setSystemButtons(false, qamHeld)
bridge.applyTouch(this, InputRole.PRIMARY) { state ->
val stickWrites = controls.filter { it.stick >= 0 && it.dirty }.fold(0) { mask, control ->
mask or if (control.stick == 0) PadBridge.LEFT_STICK else PadBridge.RIGHT_STICK
}
bridge.applyTouch(this, InputRole.PRIMARY, stickWrites) { state ->
val used = HashSet<String>()
val held = HashSet<String>()
for (control in controls) {
@@ -17,7 +17,10 @@ import java.util.concurrent.atomic.AtomicIntegerArray;
public final class PadBridge {
private static final String TAG = "PadBridge";
public static final int SLOTS = 4;
public static final int LEFT_STICK = 1;
public static final int RIGHT_STICK = 2;
private static final float DEAD_ZONE = 0.12f;
private float stickDeadZone = DEAD_ZONE;
private static final int[] JOYSTICK_AXES = {
MotionEvent.AXIS_X, MotionEvent.AXIS_Y, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ,
MotionEvent.AXIS_RX, MotionEvent.AXIS_RY,
@@ -52,6 +55,8 @@ public final class PadBridge {
private volatile java.util.function.IntPredicate excluded = id -> false;
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
private final PadState[] playerStates = new PadState[SLOTS];
private final float[][] rawSticks = new float[SLOTS][4];
private final int[] retainedSticks = new int[SLOTS];
private final PadState effectiveState = new PadState();
private final PadState homeGuideReport = new PadState();
private final PadState combinedState = new PadState();
@@ -203,7 +208,7 @@ public final class PadBridge {
chordButtonPressed = false;
qamChordGeneration++;
chordHandler.removeCallbacksAndMessages(null);
state.clear();
clearPlayerState(0);
publish();
}
@@ -240,7 +245,7 @@ public final class PadBridge {
playerWriters[slot].destroy();
playerWriters[slot] = null;
}
if (playerStates[slot] != null) playerStates[slot].clear();
clearPlayerState(slot);
}
systemGuidePressed = false;
systemQamPressed = false;
@@ -250,7 +255,7 @@ public final class PadBridge {
qamTapPressed = false;
qamChordGeneration++;
if (open) {
state.clear();
clearPlayerState(0);
writer.writePad(state);
writer.close();
open = false;
@@ -415,6 +420,65 @@ public final class PadBridge {
return true;
}
public synchronized void setStickDeadZone(int percent) {
float value = Math.max(0, Math.min(25, percent)) / 100f;
if (stickDeadZone == value) return;
stickDeadZone = value;
for (int slot = 0; slot < SLOTS; slot++) {
if (retainedSticks[slot] == 0) continue;
int owner = owners[slot], partner = partners[slot];
if (owner != NO_CONTROLLER && (InputDevice.getDevice(owner) == null || excluded.test(owner))) leave(slot, owner);
if (partner != NO_CONTROLLER && (InputDevice.getDevice(partner) == null || excluded.test(partner))) leave(slot, partner);
if (retainedSticks[slot] == 0) continue;
projectSticks(slot);
publish(slot);
}
}
private void retainStick(int slot, int side, float x, float y) {
rawSticks[slot][side * 2] = x;
rawSticks[slot][side * 2 + 1] = y;
retainedSticks[slot] |= 1 << side;
}
private void projectSticks(int slot) {
PadState pad = stateFor(slot);
for (int side = 0; side < 2; side++) {
if ((retainedSticks[slot] & (1 << side)) == 0) continue;
float x = rawSticks[slot][side * 2];
float y = rawSticks[slot][side * 2 + 1];
boolean centred = inStickDeadZone(x, y, stickDeadZone);
if (side == JoyCon.LEFT) {
pad.leftX = centred ? 0f : x;
pad.leftY = centred ? 0f : y;
} else {
pad.rightX = centred ? 0f : x;
pad.rightY = centred ? 0f : y;
}
}
}
private void clearPlayerState(int slot) {
stateFor(slot).clear();
retainedSticks[slot] = 0;
Arrays.fill(rawSticks[slot], 0f);
}
private void mutateState(java.util.function.Consumer<PadState> mutation) {
float lx = state.leftX, ly = state.leftY, rx = state.rightX, ry = state.rightY;
mutation.accept(state);
if (state.leftX != lx || state.leftY != ly) retainedSticks[0] &= ~1;
if (state.rightX != rx || state.rightY != ry) retainedSticks[0] &= ~2;
}
static boolean inStickDeadZone(float x, float y, float deadZone) {
return x * x + y * y < deadZone * deadZone;
}
private static boolean hasChordStickInput(float x, float y) {
return Math.max(Math.abs(x), Math.abs(y)) >= DEAD_ZONE;
}
public synchronized boolean onMotionEvent(MotionEvent event) {
if (!isControllerMotionEvent(event) || excluded.test(event.getDeviceId())) return false;
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
@@ -429,26 +493,25 @@ public final class PadBridge {
int side = JoyCon.side(device);
if (side >= 0) {
int[] stick = JoyCon.stickAxes(side, device, event.getSource());
float x = axis(event, stick[0]);
float y = axis(event, stick[1]);
if (side == JoyCon.LEFT) {
pad.leftX = x;
pad.leftY = y;
} else {
pad.rightX = x;
pad.rightY = y;
}
if (x != 0f || y != 0f) noteChordInput(slot);
float x = event.getAxisValue(stick[0]);
float y = event.getAxisValue(stick[1]);
boolean chordStickInput = hasChordStickInput(x, y);
retainStick(slot, side, x, y);
projectSticks(slot);
if (chordStickInput) noteChordInput(slot);
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) notePlayerInput();
publish(slot);
InputTiming.end(timing);
return true;
}
pad.leftX = axis(event, MotionEvent.AXIS_X);
pad.leftY = axis(event, MotionEvent.AXIS_Y);
float lx = event.getAxisValue(MotionEvent.AXIS_X);
float ly = event.getAxisValue(MotionEvent.AXIS_Y);
boolean wired = wiredXboxLayout(event);
pad.rightX = rightX(event, wired);
pad.rightY = rightY(event, wired);
float rx = event.getAxisValue(wired ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z);
float ry = event.getAxisValue(wired ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ);
retainStick(slot, JoyCon.LEFT, lx, ly);
retainStick(slot, JoyCon.RIGHT, rx, ry);
projectSticks(slot);
int source = event.getSource();
float lt = 0f;
float rt = 0f;
@@ -470,7 +533,7 @@ public final class PadBridge {
pad.up = hatY < -0.5f;
pad.down = hatY > 0.5f;
}
if (pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f
if (hasChordStickInput(lx, ly) || hasChordStickInput(rx, ry)
|| lt > 0f || rt > 0f || pad.up || pad.right || pad.down || pad.left) noteChordInput(slot);
if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f
|| lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) {
@@ -500,10 +563,18 @@ public final class PadBridge {
}
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
applyTouch(defaultTouchSource, InputRole.PRIMARY, mutation);
applyTouch(defaultTouchSource, InputRole.PRIMARY, 0, mutation);
}
public synchronized void applyTouch(int stickWrites, java.util.function.Consumer<PadState> mutation) {
applyTouch(defaultTouchSource, InputRole.PRIMARY, stickWrites, mutation);
}
public synchronized void applyTouch(Object owner, InputRole role, java.util.function.Consumer<PadState> mutation) {
applyTouch(owner, role, 0, mutation);
}
public synchronized void applyTouch(Object owner, InputRole role, int stickWrites, java.util.function.Consumer<PadState> mutation) {
if (!builtinPad) return;
long timing = InputTiming.begin();
TouchSource source = touchSources.get(owner);
@@ -512,7 +583,18 @@ public final class PadBridge {
if (inputRouter != null) source.route = inputRouter.pad(role);
touchSources.put(owner, source);
}
float lx = source.raw.leftX, ly = source.raw.leftY, rx = source.raw.rightX, ry = source.raw.rightY;
mutation.accept(source.raw);
if (inputRouter == null && (touchRoute == null || !touchRoute.active())) {
if ((stickWrites & LEFT_STICK) != 0 || source.raw.leftX != lx || source.raw.leftY != ly) {
retainedSticks[0] &= ~LEFT_STICK;
state.leftX = state.leftY = 0f;
}
if ((stickWrites & RIGHT_STICK) != 0 || source.raw.rightX != rx || source.raw.rightY != ry) {
retainedSticks[0] &= ~RIGHT_STICK;
state.rightX = state.rightY = 0f;
}
}
activeControllerId = NO_CONTROLLER;
slotControllers.set(0, NO_CONTROLLER);
notePlayerInput();
@@ -530,7 +612,7 @@ public final class PadBridge {
}
public synchronized void applyExternal(java.util.function.Consumer<PadState> mutation, boolean changed) {
mutation.accept(state);
mutateState(mutation);
if (changed) {
activeControllerId = NO_CONTROLLER;
notePlayerInput();
@@ -566,7 +648,7 @@ public final class PadBridge {
if (inputRouter == null) for (TouchSource source : touchSources.values()) source.raw.clear();
routedTouch.clear();
DeckControls.INSTANCE.suspend();
if (inputRouter == null) state.clear();
if (inputRouter == null) clearPlayerState(0);
homeGuidePressed = false;
homeGuideSlot = -1;
clearBackQamWrites();
@@ -574,8 +656,8 @@ public final class PadBridge {
if (inputRouter == null) releaseBackPaddles();
publish();
for (int slot = 1; slot < SLOTS; slot++) {
if (inputRouter == null) clearPlayerState(slot);
if (playerWriters[slot] == null) continue;
if (inputRouter == null) playerStates[slot].clear();
publish(slot);
}
}
@@ -615,7 +697,7 @@ public final class PadBridge {
if (!homeGuidePressed) return;
clearBackQamWrites();
homeGuidePressed = false;
if (inputRouter == null) state.clear();
if (inputRouter == null) clearPlayerState(0);
else {
inputRouter.releaseAll();
DeckControls.INSTANCE.suspend();
@@ -642,7 +724,7 @@ public final class PadBridge {
writeBackQamReport(modifier, modifierAt);
}
if (!pressed && !backQamPressed && !homeGuidePressed) {
backQamAxesBlocked = hasAxes(liveReport);
backQamAxesBlocked = hasQamAxes();
if (!backQamWrites.isEmpty()) {
PadState neutral = new PadState();
neutral.copyFrom(lastWrittenReport);
@@ -658,7 +740,7 @@ public final class PadBridge {
if (!backQamPressed && backQamWrites.isEmpty()) return;
clearBackQamWrites();
backQamPressed = false;
if (inputRouter == null) state.clear();
if (inputRouter == null) clearPlayerState(0);
else {
inputRouter.releaseAll();
DeckControls.INSTANCE.suspend();
@@ -699,15 +781,18 @@ public final class PadBridge {
private void writePad(PadState report) {
liveReport.copyFrom(report);
if (backQamAxesBlocked && !hasAxes(liveReport)) backQamAxesBlocked = false;
if (backQamAxesBlocked && !hasQamAxes()) backQamAxesBlocked = false;
long at = android.os.SystemClock.uptimeMillis();
if (backQamPressed || homeGuidePressed || !backQamWrites.isEmpty()) at += backQamDelayMs;
writeBackQamReport(report, at);
}
private static boolean hasAxes(PadState pad) {
return pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f
|| pad.leftTrigger != 0f || pad.rightTrigger != 0f;
private boolean hasQamAxes() {
boolean left = (retainedSticks[0] & 1) != 0 && liveReport.leftX == state.leftX && liveReport.leftY == state.leftY
? hasChordStickInput(rawSticks[0][0], rawSticks[0][1]) : liveReport.leftX != 0f || liveReport.leftY != 0f;
boolean right = (retainedSticks[0] & 2) != 0 && liveReport.rightX == state.rightX && liveReport.rightY == state.rightY
? hasChordStickInput(rawSticks[0][2], rawSticks[0][3]) : liveReport.rightX != 0f || liveReport.rightY != 0f;
return left || right || liveReport.leftTrigger != 0f || liveReport.rightTrigger != 0f;
}
private static void clearAxes(PadState pad) {
@@ -845,7 +930,7 @@ public final class PadBridge {
slotJoyCons.set(slot * 2 + 1 - side, owner.getId());
if (slot == firstPlayerSlot()) releaseBackPaddles();
if (slot == 0) clearBackQamWrites();
stateFor(slot).clear();
clearPlayerState(slot);
if (slot == 0) publish();
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") joins \"" + owner.getName() + "\" as player " + (slot + 1));
return slot;
@@ -893,7 +978,7 @@ public final class PadBridge {
if (slotControllers.get(slot) == id) slotControllers.set(slot, owners[slot]);
if (activeControllerId == id) activeControllerId = owners[slot];
if (slot == firstPlayerSlot()) releaseBackPaddles();
stateFor(slot).clear();
clearPlayerState(slot);
publish(slot);
}
@@ -912,11 +997,11 @@ public final class PadBridge {
if (slot == homeGuideSlot) homeGuideSlot = -1;
if (slot == firstPlayerSlot()) releaseBackPaddles();
if (slot == 0) {
state.clear();
clearPlayerState(0);
publish();
return;
}
playerStates[slot].clear();
clearPlayerState(slot);
if (playerWriters[slot] != null) {
playerWriters[slot].destroy();
playerWriters[slot] = null;
@@ -1035,14 +1120,6 @@ public final class PadBridge {
&& device.getMotionRange(MotionEvent.AXIS_RZ, event.getSource()) != null;
}
public static float rightX(MotionEvent event, boolean wired) {
return axis(event, wired ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z);
}
public static float rightY(MotionEvent event, boolean wired) {
return axis(event, wired ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ);
}
public static float leftTrigger(MotionEvent event, boolean wired) {
if (wired) return Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_Z) + 1f) / 2f));
float value = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
@@ -1055,8 +1132,4 @@ public final class PadBridge {
return value != 0f ? value : event.getAxisValue(MotionEvent.AXIS_GAS);
}
private static float axis(MotionEvent event, int axis) {
float value = event.getAxisValue(axis);
return Math.abs(value) < DEAD_ZONE ? 0f : value;
}
}
@@ -90,8 +90,8 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
val wired = wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(event) }
sticks.leftX = event.getAxisValue(MotionEvent.AXIS_X)
sticks.leftY = event.getAxisValue(MotionEvent.AXIS_Y)
sticks.rightX = PadBridge.rightX(event, wired)
sticks.rightY = PadBridge.rightY(event, wired)
sticks.rightX = scrollAxis(event, if (wired) MotionEvent.AXIS_RX else MotionEvent.AXIS_Z)
sticks.rightY = scrollAxis(event, if (wired) MotionEvent.AXIS_RY else MotionEvent.AXIS_RZ)
if (hasTriggerAxes(event)) {
sticks.leftTrigger = PadBridge.leftTrigger(event, wired)
sticks.rightTrigger = PadBridge.rightTrigger(event, wired)
@@ -295,6 +295,7 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
}
companion object {
private const val SCROLL_AXIS_DEAD_ZONE = 0.12f
private const val DEAD_ZONE = 0.15f
private const val STICK_NAVIGATE = 0.5f
private const val REPEAT_FIRST_MS = 300L
@@ -348,6 +349,9 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S
return scaled * scaled / length
}
private fun scrollAxis(event: MotionEvent, axis: Int): Float =
event.getAxisValue(axis).let { if (abs(it) < SCROLL_AXIS_DEAD_ZONE) 0f else it }
private fun source(deviceId: Int, kind: Int): Int = deviceId * 2 + kind
@@ -0,0 +1,20 @@
package com.droiddeck.launcher.input
import android.graphics.RectF
/**
* The area of the session view that drives the guest pointer.
*
* The view is also the compositor output only while it shows the picture: the phone, or the
* bottom screen. With the glasses owning the output the view is a touchpad for a scene drawn
* elsewhere, so the whole view has to drive the pointer. Using the picture rect there would
* confine it to the letterboxed band the scene would occupy on the phone, and the pointer could
* not reach the scene edges.
*/
object PointerSpace {
fun area(viewWidth: Int, viewHeight: Int, glassesOwnOutput: Boolean, picture: RectF?): RectF? {
if (viewWidth <= 0 || viewHeight <= 0) return null
if (glassesOwnOutput) return RectF(0f, 0f, viewWidth.toFloat(), viewHeight.toFloat())
return picture
}
}
@@ -61,6 +61,9 @@ object BattleNet {
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" && it.code != "WoWF" }
// Blizzard's China client installs some products under a CN uid; they are the same games and keep their store identity.
private val CN_UIDS = mapOf("s2_cn" to "s2", "osic" to "osi", "anbs_cn" to "anbs")
fun notInstalled(title: Title, installedIds: Collection<String?>) =
installedIds.mapNotNull { id -> id?.let(::title)?.code }.none { it == title.code }
@@ -164,8 +167,10 @@ object BattleNet {
internal fun title(uid: String): Title? {
val id = uid.lowercase()
TITLES.firstOrNull { it.uid == id }?.let { return it }
CN_UIDS[id]?.let { alias -> TITLES.firstOrNull { it.uid == alias }?.let { return it } }
val base = id.substringBeforeLast('_', "")
return if (base.isNotEmpty() && id.substringAfterLast('_') in LOCALES) TITLES.firstOrNull { it.uid == base } else null
if (base.isEmpty() || id.substringAfterLast('_') !in LOCALES) return null
return TITLES.firstOrNull { it.uid == base } ?: CN_UIDS[base]?.let { alias -> TITLES.firstOrNull { it.uid == alias } }
}
internal fun titleForProduct(product: String): Title? {
@@ -9,6 +9,7 @@ import android.net.ConnectivityManager
import android.net.LinkProperties
import android.net.Network
import android.net.NetworkCapabilities
import android.net.RouteInfo
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Build
@@ -23,6 +24,7 @@ import java.io.File
import java.io.IOException
import java.net.Inet4Address
import java.net.Inet6Address
import java.net.InetAddress
import org.json.JSONArray
import org.json.JSONObject
@@ -156,7 +158,7 @@ class LinuxNetworkLinkComponent(
try {
file.parentFile?.mkdirs()
val staged = File(file.path + ".staged")
staged.writeText(describe(properties))
staged.writeText(describe(properties, capabilities))
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
} catch (e: IOException) {
Log.w(TAG, "Could not publish the network link", e)
@@ -210,11 +212,7 @@ class LinuxNetworkLinkComponent(
}
})
put("gateways", JSONArray().apply {
properties?.routes.orEmpty().filter { it.isDefaultRoute }.forEach {
it.gateway?.takeUnless { address -> address.isAnyLocalAddress }?.let { address ->
put(address.hostAddress?.substringBefore('%'))
}
}
gateways(properties, capabilities).forEach { put(it.hostAddress?.substringBefore('%')) }
})
put("dns", JSONArray().apply {
properties?.dnsServers.orEmpty().filter { !it.isLinkLocalAddress }.forEach {
@@ -301,7 +299,7 @@ class LinuxNetworkLinkComponent(
}
}
private fun describe(properties: LinkProperties?): String {
internal fun describe(properties: LinkProperties?, capabilities: NetworkCapabilities?): String {
val addresses = properties?.linkAddresses.orEmpty()
.filter { it.address is Inet4Address || it.address is Inet6Address }
val name = properties?.interfaceName?.takeIf { addresses.isNotEmpty() } ?: OFFLINE_NAME
@@ -316,10 +314,7 @@ class LinuxNetworkLinkComponent(
for (address in addresses) {
append("addr ${address.address.hostAddress?.substringBefore('%')} ${address.prefixLength}\n")
}
for (family in listOf(Inet4Address::class.java, Inet6Address::class.java)) {
val gateway = properties?.routes.orEmpty()
.firstOrNull { it.isDefaultRoute && family.isInstance(it.gateway) && !it.gateway!!.isAnyLocalAddress }
?.gateway ?: continue
for (gateway in gateways(properties, capabilities)) {
append("gw ${gateway.hostAddress?.substringBefore('%')}\n")
}
}
@@ -329,6 +324,27 @@ class LinuxNetworkLinkComponent(
seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) }
companion object {
internal fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?): List<InetAddress> =
listOf(Inet4Address::class.java, Inet6Address::class.java).mapNotNull { family ->
properties?.routes.orEmpty()
.firstOrNull { it.isDefaultRoute && family.isInstance(it.gateway) && !it.gateway!!.isAnyLocalAddress }
?.gateway
?: if (family == Inet4Address::class.java &&
capabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true &&
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
properties?.interfaceName != null &&
properties.routes.any {
it.destination.address is Inet4Address &&
(Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || it.type == RouteInfo.RTN_UNICAST)
}
) {
properties.linkAddresses.firstOrNull {
it.address is Inet4Address && !it.address.isAnyLocalAddress &&
!it.address.isLoopbackAddress && !it.address.isLinkLocalAddress
}?.address
} else null
}
internal fun seededMac(readId: () -> String?): String {
val id = runCatching(readId).getOrNull() ?: "bannerlator"
val bytes = java.security.MessageDigest.getInstance("SHA-1").digest(id.toByteArray())
@@ -7,6 +7,7 @@ import android.system.ErrnoException;
import android.system.Os;
import android.system.StructStat;
import android.system.StructUtsname;
import com.droiddeck.launcher.gpu.SystemVulkanDriver;
import com.droiddeck.launcher.session.SessionPrefs;
@@ -191,6 +192,13 @@ public final class LinuxRuntime {
bind(cmd, "/dev");
bind(cmd, "/proc");
bind(cmd, "/sys");
if (com.droiddeck.launcher.gpu.SystemVulkanDriver.isPowerVr()) {
// The glibc bridge loads the device's existing Android HAL and its dependencies.
// These read-only Android partitions remain subject to the app's normal permissions.
for (String path : new String[]{"/system", "/vendor", "/apex", "/system_ext", "/product", "/odm"})
if (new File(path).isDirectory()) bind(cmd, path);
if (new File("/linkerconfig/ld.config.txt").isFile()) bind(cmd, "/linkerconfig/ld.config.txt");
}
bind(cmd, DeviceControlsComponent.prepareBacklight(context, root).getPath() + ":/sys/class/backlight");
bind(cmd, "/dev/urandom:/dev/random");
bind(cmd, "/proc/self/fd:/dev/fd");
@@ -198,6 +206,10 @@ public final class LinuxRuntime {
bind(cmd, "/proc/self/fd/1:/dev/stdout");
bind(cmd, "/proc/self/fd/2:/dev/stderr");
bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/fs/selinux");
// A kernel that refuses to list /sys/class/thermal (Pixel 10, Android 17) made mangoapp abort
// at start ("filesystem_error ... Permission denied: '/sys/class/thermal/'") until its
// wrapper gave up: it lists the directory for CPU temperatures. Empty there instead.
if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/class/thermal");
bind(cmd, context.getFilesDir().getPath());
bind(cmd, context.getCacheDir().getPath());
bind(cmd, liveDir(context).getPath());
@@ -259,7 +271,11 @@ public final class LinuxRuntime {
if (unreadablePciDevice()) {
bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/bus/pci/devices");
}
bindGpuNode(context, cmd);
if (com.droiddeck.launcher.gpu.SystemVulkanDriver.isPowerVr()) {
bindPowerVrGpuNode(context, cmd);
} else {
bindGpuNode(context, cmd);
}
bindAdrenoStats(cmd, extraBinds);
bindCpuTemps(cmd, root);
if (extraBinds != null) {
@@ -270,6 +286,24 @@ public final class LinuxRuntime {
return specs;
}
private static void bindPowerVrGpuNode(Context context, List<String> cmd) {
if (new File("/dev/dri").list() != null) return;
String node = SystemVulkanDriver.renderNodePath();
if (node == null) return;
String name = new File(node).getName();
File dri = new File(context.getCacheDir(), "powervr-drm/" + name + "/dri");
try {
if (!dri.isDirectory() && !dri.mkdirs()) return;
new File(dri, name).createNewFile();
} catch (IOException e) {
android.util.Log.w("LinuxRuntime", "Cannot expose the PowerVR render node", e);
return;
}
bind(cmd, dri.getPath() + ":/dev/dri");
bind(cmd, node + ":" + node);
android.util.Log.i("LinuxRuntime", "PowerVR: exposing real " + name + " through a listable directory");
}
private static boolean unreadablePciDevice() {
File[] devices = new File("/sys/bus/pci/devices").listFiles();
if (devices == null) return false;
@@ -279,7 +313,7 @@ public final class LinuxRuntime {
return false;
}
static final String MALI_DEVICE = "/dev/mali0";
public static final String MALI_DEVICE = "/dev/mali0";
static final String[] DRM_RENDER_NODES = {
"/dev/dri/renderD128", "/dev/dri/renderD129", "/dev/dri/renderD130", "/dev/dri/renderD131",
@@ -287,6 +321,7 @@ public final class LinuxRuntime {
public static String gpuStandIn(Context context) {
if (new File(KGSL_DEVICE).exists()) return KGSL_DEVICE;
if (com.droiddeck.launcher.core.DeviceSupport.INSTANCE.openDriverActive(context) && new File(MALI_DEVICE).exists()) return MALI_DEVICE;
if (!com.droiddeck.launcher.core.DeviceSupport.INSTANCE.vkBridge(context)) return null;
return bridgeStandIn(path -> new File(path).exists());
}
@@ -0,0 +1,164 @@
package com.droiddeck.launcher.runtime
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreInstalls
import org.apache.commons.compress.archivers.zip.ZipFile
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.LinkOption
object WowAddons {
var imports by mutableIntStateOf(0)
private set
class TooLarge : IOException()
class Target(val flavor: String, val addOns: File)
class Addon(val name: String, val root: String)
internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024
private val SUFFIX = Regex("[-_](standard|mainline|classic|vanilla|tbc|bcc|wrath|wotlkc|cata|mists|forever)$", RegexOption.IGNORE_CASE)
fun targets(game: Library.SteamGame): List<Target> {
if (game.source != Store.BATTLENET.id) return emptyList()
val title = game.storeId?.let(BattleNet::title) ?: return emptyList()
if (title.flavor == null) return emptyList()
val folder = game.gameFiles ?: return emptyList()
return targets(title, folder)
}
internal fun targets(title: BattleNet.Title, folder: File): List<Target> {
val flavors = BattleNet.TITLES.filter { it.code == title.code }.mapNotNull { it.flavor }
.flatMap { listOf(it, it.dropLast(1) + "_beta_") }.distinct()
val root = if (folder.name in flavors) folder.parentFile ?: return emptyList() else folder
return flavors.map { File(root, it) }.filter { it.isDirectory }.map { Target(it.name, addOnsFolder(it)) }
}
fun installed(target: Target): List<String> =
target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
.map { it.name }.sortedBy { it.lowercase() }
fun delete(target: Target, name: String) {
val folder = target.addOns.listFiles()?.firstOrNull { it.name == name && !it.name.startsWith(".") }
?: throw IOException("Cannot find $name")
StoreInstalls.deleteTree(folder)
if (Files.exists(folder.toPath(), LinkOption.NOFOLLOW_LINKS)) throw IOException("Cannot delete $name")
imports++
}
fun import(zipFile: File, target: Target): List<String> {
ZipFile.builder().setFile(zipFile).get().use { zip ->
val all = zip.entries.toList()
if (all.any { it.isUnixSymlink }) return emptyList()
val entries = all.filter { clean(it.name) != null }
val addons = addons(entries.filter { !it.isDirectory }.mapNotNull { clean(it.name) })
if (addons.isEmpty()) return emptyList()
val addOns = target.addOns
if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}")
val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}")
try {
val fresh = File(stage, "new")
val buffer = ByteArray(64 * 1024)
var written = 0L
for (entry in entries) {
if (entry.isDirectory) continue
val path = clean(entry.name) ?: continue
val addon = addons.firstOrNull { path.startsWith(it.root) } ?: continue
val out = inside(fresh, addon.name + "/" + path.removePrefix(addon.root)) ?: continue
out.parentFile?.mkdirs()
zip.getInputStream(entry).use { input ->
out.outputStream().use { output ->
while (true) {
val read = input.read(buffer)
if (read < 0) break
written += read
if (written > MAX_EXPANDED_BYTES) throw TooLarge()
output.write(buffer, 0, read)
}
}
}
}
swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() })
} finally {
StoreInstalls.deleteTree(stage)
}
imports++
return addons.map { it.name }
}
}
internal fun addons(files: List<String>): List<Addon> {
val tocs = files.filter { it.endsWith(".toc", ignoreCase = true) }
val folders = tocs.map { it.substringBeforeLast('/', "") }.distinct().sortedBy { it.length }
val roots = ArrayList<String>()
for (folder in folders) {
if (roots.none { it.isEmpty() || folder.startsWith("$it/") }) roots.add(folder)
}
return roots.mapNotNull { root ->
val inFolder = tocs.filter { it.substringBeforeLast('/', "") == root }
.map { it.substringAfterLast('/').dropLast(4) }
val name = addonName(root.substringAfterLast('/'), inFolder)
name.takeIf { it.isNotEmpty() && !it.startsWith(".") }?.let { Addon(it, if (root.isEmpty()) "" else "$root/") }
}.distinctBy { it.name.lowercase() }
}
private fun addonName(folder: String, tocs: List<String>): String {
val match = tocs.firstOrNull { it.equals(folder, ignoreCase = true) }
?: tocs.firstOrNull { it.replace(SUFFIX, "").equals(folder, ignoreCase = true) }
if (match != null) return folder
return tocs.map { it.replace(SUFFIX, "") }.minByOrNull { it.length }.orEmpty()
}
private fun clean(name: String): String? {
val parts = name.replace('\\', '/').trim('/').split('/')
if (name.startsWith("/") || name.startsWith("\\") || parts.any { it.isEmpty() || it == "." || it == ".." || it.endsWith(":") }) return null
if (parts.first() == "__MACOSX" || parts.last().startsWith("._")) return null
return parts.joinToString("/")
}
private fun inside(root: File, path: String): File? {
val out = File(root, path)
return out.takeIf { it.canonicalPath.startsWith(root.canonicalPath + File.separator) }
}
private fun addOnsFolder(flavor: File): File = child(child(flavor, "Interface"), "AddOns")
private fun child(parent: File, name: String): File =
parent.listFiles()?.firstOrNull { it.name.equals(name, ignoreCase = true) } ?: File(parent, name)
internal fun swap(fresh: List<Pair<File, String>>, addOns: File, old: File) {
val done = ArrayList<Replaced>()
try {
for ((folder, name) in fresh) done.add(replace(folder, addOns, name, old))
} catch (e: IOException) {
done.asReversed().forEach { undo(it) }
throw e
}
}
private class Replaced(val installed: File, val previous: File?, val kept: File?)
private fun undo(replaced: Replaced) {
StoreInstalls.deleteTree(replaced.installed)
if (replaced.previous != null) replaced.kept?.renameTo(replaced.previous)
}
private fun replace(fresh: File, addOns: File, name: String, old: File): Replaced {
val current = addOns.listFiles()?.firstOrNull { it.name.equals(name, ignoreCase = true) }
val kept = current?.let { File(old, it.name) }
if (current != null && !current.renameTo(kept!!)) throw IOException("Cannot replace ${current.path}")
val installed = File(addOns, name)
if (!fresh.renameTo(installed)) {
kept?.renameTo(current)
throw IOException("Cannot install $name")
}
return Replaced(installed, current, kept)
}
}
@@ -9,6 +9,7 @@ import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.gpu.AppVulkan
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.github.luben.zstd.ZstdInputStream
import com.github.luben.zstd.ZstdOutputStream
@@ -199,9 +200,13 @@ object ComponentsManager {
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
}
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) = synchronized(lock) {
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) =
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
require(comp in COMPONENTS)
if (file != null) requireSelectable(context, comp, managed)
val state = loadState(context)
val profiles = state.sub("profiles")
val profile = profiles.optJSONObject(scope) ?: JSONObject().also { profiles.put(scope, it) }
@@ -638,11 +643,21 @@ object ComponentsManager {
return PreparedLaunchState(lines.toString(), keep)
}
internal fun runtimeManaged(comp: String, systemPowerVr: Boolean): Boolean = comp == "dxvk" && systemPowerVr
private fun runtimeManaged(context: Context, comp: String): Boolean =
runtimeManaged(comp, SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(context)))
private fun requireSelectable(context: Context, comp: String, managed: (String) -> Boolean = { runtimeManaged(context, it) }) {
check(!managed(comp)) { context.getString(R.string.cmgr_powervr_dxvk_managed) }
}
fun swap(context: Context, protonId: String, file: String, auto: Boolean = false): String = synchronized(lock) {
val p = proton(context, protonId)
val wcp = File(packagesDir(context), safeName(file))
val info = packageInfo(context, wcp)
requireSelectable(context, info.comp)
val state = loadState(context)
if (inUse(context, p)) {
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
@@ -668,6 +683,7 @@ object ComponentsManager {
}
fun restore(context: Context, protonId: String, comp: String, protonVersion: String): String = synchronized(lock) {
requireSelectable(context, comp)
val p = proton(context, protonId)
val wcp = File(originalsDir(context), "$protonId/${safeName(protonVersion)}/$comp.wcp")
check(wcp.isFile) { context.getString(R.string.cmgr_original_missing) }
@@ -693,7 +709,10 @@ object ComponentsManager {
.put("protonVersion", p.version).put("files", JSONObject(fingerprint(p.dir, comp) as Map<*, *>)).put("at", System.currentTimeMillis() / 1000))
}
fun applyQueued(context: Context): List<String> = synchronized(lock) {
/** Runs the swaps that waited for a game to close. Cheap when nothing is queued. */
fun applyQueued(context: Context): List<String> = applyQueued(context) { runtimeManaged(context, it) }
internal fun applyQueued(context: Context, managed: (String) -> Boolean): List<String> = synchronized(lock) {
val state = loadState(context)
val queued = state.sub("queued")
if (queued.length() == 0) return emptyList()
@@ -705,6 +724,7 @@ object ComponentsManager {
val comps = queued.optJSONObject(pid) ?: continue
for (comp in comps.keys().asSequence().toList()) {
val q = comps.optJSONObject(comp) ?: continue
if (managed(comp)) continue
runCatching {
if (q.optString("kind") == "original") {
val v = q.optString("protonVersion")
@@ -0,0 +1,118 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.AtomicFile
import android.util.Log
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
object EnhancedDiagnostics {
const val MANIFEST_FILE = "enhanced-diagnostics.json"
private const val TAG = "EnhancedDiagnostics"
private const val PREFS = "session"
private const val ARMED = "enhancedDiagnosticsNext"
private const val ACTIVE_RECORDS = "enhancedDiagnosticsActiveSessions"
private const val SCHEMA = 1
fun isArmed(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(ARMED, false)
fun setArmed(context: Context, armed: Boolean): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(ARMED, armed).commit()
fun isActive(context: Context, folder: File?): Boolean = activeAt(context, folder) != null
internal fun isCurrentSessionActive(context: Context): Boolean = isActive(context, SessionPaths.current())
fun manifest(context: Context, folder: File?): JSONObject? {
val activeAt = activeAt(context, folder) ?: return null
return buildManifest(folder!!, activeAt)
}
@Synchronized
internal fun consumeInto(context: Context, folder: File): Boolean {
if (!isArmed(context)) return isActive(context, folder)
if (!folder.isDirectory) return false
val activatedAt = System.currentTimeMillis()
if (!activateAndConsume(context, folder, activatedAt)) return false
val marker = AtomicFile(File(folder, MANIFEST_FILE))
val manifest = buildManifest(folder, activatedAt)
val output = try {
marker.startWrite()
} catch (error: Exception) {
Log.w(TAG, "could not start the informational enhanced diagnostics manifest", error)
return true
}
try {
output.write((manifest.toString() + "\n").toByteArray(Charsets.UTF_8))
marker.finishWrite(output)
} catch (error: Exception) {
marker.failWrite(output)
Log.w(TAG, "could not write the informational enhanced diagnostics manifest", error)
}
return true
}
@Synchronized
internal fun clearRecordFor(context: Context, folder: File) {
removeRecord(context, folder)
}
private fun buildManifest(folder: File, activatedAt: Long) = JSONObject()
.put("schema", SCHEMA)
.put("profile", "enhanced")
.put("sessionId", folder.name)
.put("activatedAtEpochMs", activatedAt)
.put("exportBundlesBounded", true)
.put("rawCaptureByteBounded", false)
.put("rawCaptureLimitation", "Game and component diagnostics may grow until the session ends")
.put("collectorsRequested", JSONArray(listOf(
"session", "graphics", "games", "processes", "audio", "network", "components",
)))
private fun activeAt(context: Context, folder: File?): Long? {
val path = trustedPath(context, folder) ?: return null
return records(context).optLong(path, Long.MIN_VALUE).takeIf { it != Long.MIN_VALUE }
}
private fun activateAndConsume(context: Context, folder: File, activatedAt: Long): Boolean {
val path = trustedPath(context, folder) ?: return false
val records = records(context)
records.keys().asSequence().toList().forEach { known ->
if (!File(known).isDirectory) records.remove(known)
}
records.put(path, activatedAt)
return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(ACTIVE_RECORDS, records.toString())
.putBoolean(ARMED, false)
.commit()
}
private fun removeRecord(context: Context, folder: File) {
val path = runCatching { folder.canonicalPath }.getOrNull() ?: return
val records = records(context)
if (records.has(path)) {
records.remove(path)
saveRecords(context, records)
}
}
private fun trustedPath(context: Context, folder: File?): String? {
if (folder == null || !SessionPaths.isSessionFolder(folder)) return null
return runCatching {
val canonical = folder.canonicalFile
if (canonical.parentFile != SessionFiles.logDirectory(context).canonicalFile) null else canonical.path
}.getOrNull()
}
private fun records(context: Context): JSONObject {
val text = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(ACTIVE_RECORDS, null)
return runCatching { JSONObject(text ?: "{}") }.getOrDefault(JSONObject())
}
private fun saveRecords(context: Context, records: JSONObject): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString(ACTIVE_RECORDS, records.toString()).commit()
}
@@ -0,0 +1,975 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.ParcelFileDescriptor
import android.system.Os
import android.system.OsConstants
import com.droiddeck.launcher.core.LogRedactor
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedInputStream
import java.io.ByteArrayOutputStream
import java.io.Closeable
import java.io.File
import java.io.FileOutputStream
import java.io.FileInputStream
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.channels.Channels
import java.nio.channels.FileChannel
import java.nio.channels.FileLock
import java.nio.channels.OverlappingFileLockException
import java.nio.channels.SeekableByteChannel
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.StandardOpenOption
import java.nio.file.attribute.BasicFileAttributes
import java.security.MessageDigest
import java.util.Locale
import java.util.UUID
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
internal data class EnhancedShareLimits(
val maxFilesPerArchive: Int = 256,
val maxDiscoveredFiles: Int = 768,
val maxBytesPerFile: Long = 8L * 1024 * 1024,
val maxBytesTotal: Long = 64L * 1024 * 1024,
)
internal interface SecureSourceOpener {
fun <T> withChannel(root: Path, relative: Path, block: (SeekableByteChannel) -> T): T?
}
internal object EnhancedSessionLogShare {
private enum class Category(val suffix: String) { SESSION("session"), GRAPHICS("graphics"), GAMES("games") }
internal class DiagnosticStageLease internal constructor(
val directory: File,
private val canonicalPath: String,
private val channel: FileChannel,
private val lock: FileLock,
) : Closeable {
override fun close() {
synchronized(stageLifecycleMonitor) {
activeStagePaths.remove(canonicalPath)
try {
lock.release()
} finally {
try {
channel.close()
} finally {
directory.deleteRecursively()
}
}
}
}
}
private data class Candidate(
val file: File,
val anchor: File,
val entry: String,
val origin: String,
val category: Category,
val linePrefix: String? = null,
)
private data class Record(
val entry: String,
val origin: String,
val status: String,
val sourceBytes: Long = 0,
val capturedBytes: Long = 0,
val reason: String? = null,
)
private data class Snapshot(val file: File, val sourceBytes: Long, val truncated: Boolean)
private class StageUnavailableException(cause: Throwable) : IOException("Diagnostic staging directory is unavailable", cause)
private class SourceReadException(cause: Throwable) : IOException("Could not read diagnostic source", cause)
private data class CollectionResult(
val candidates: List<Candidate>,
val truncated: Boolean,
val partial: Boolean,
)
private data class ScanResult(
val files: List<File>,
val truncated: Boolean,
val partial: Boolean = false,
)
private data class LegacySource(val file: File, val root: File, val entry: String)
private data class LegacyDiscovery(
val sources: List<LegacySource>,
val truncated: Boolean,
val partial: Boolean,
)
private class Budget(val limit: Long, var remaining: Long = limit)
private val sourceOpenerOverride = object : ThreadLocal<SecureSourceOpener?>() {
override fun initialValue(): SecureSourceOpener? = null
}
private val stageLifecycleMonitor = Any()
private val activeStagePaths = mutableSetOf<String>()
internal fun acquireDiagnosticStage(context: Context, outputName: String): DiagnosticStageLease {
val cache = context.cacheDir
require(outputName.isNotBlank() && File(outputName).name == outputName)
return withStageLifecycleLock(cache) {
val stage = File(cache, "$outputName-${UUID.randomUUID()}.diagnostic-stage")
if (!stage.mkdir()) throw IOException("Could not create the diagnostic staging directory")
val channel = try {
FileChannel.open(File(stage, ".active").toPath(), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)
} catch (error: Exception) {
stage.deleteRecursively()
throw IOException("Could not create the diagnostic staging lock", error)
}
try {
val lock = channel.tryLock()
?: throw IOException("Could not lock the diagnostic staging directory")
val canonicalPath = stage.canonicalPath
activeStagePaths += canonicalPath
DiagnosticStageLease(stage, canonicalPath, channel, lock)
} catch (error: Exception) {
channel.close()
stage.deleteRecursively()
throw IOException("Could not lock the diagnostic staging directory", error)
}
}
}
internal fun cleanupAbandonedStages(context: Context) {
val cache = context.cacheDir
val canonicalCache = cache.canonicalFile
withStageLifecycleLock(cache) {
cache.listFiles()?.forEach { stage ->
if (!stage.isDirectory || Files.isSymbolicLink(stage.toPath()) ||
stage.canonicalFile.parentFile != canonicalCache || !isDiagnosticStage(stage.name)) return@forEach
if (stage.canonicalPath in activeStagePaths) return@forEach
val active = File(stage, ".active")
if (Files.isSymbolicLink(active.toPath())) return@forEach
val channel = runCatching {
FileChannel.open(active.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE)
}.getOrNull() ?: return@forEach
val abandoned = try {
channel.tryLock()?.let { lock -> lock.release(); true } ?: false
} catch (_: OverlappingFileLockException) {
false
} finally {
channel.close()
}
if (abandoned) stage.deleteRecursively()
}
}
}
private fun isDiagnosticStage(name: String): Boolean {
val suffix = ".diagnostic-stage"
if (!name.endsWith(suffix)) return false
val base = name.removeSuffix(suffix)
val uuidStart = base.length - 36
if (uuidStart < 2 || base[uuidStart - 1] != '-') return false
return runCatching { UUID.fromString(base.substring(uuidStart)).toString() == base.substring(uuidStart) }
.getOrDefault(false)
}
private fun <T> withStageLifecycleLock(cache: File, block: () -> T): T = synchronized(stageLifecycleMonitor) {
FileChannel.open(File(cache, ".diagnostic-stages.lock").toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE)
.use { channel -> channel.lock().use { block() } }
}
internal fun setSourceOpenerForTest(opener: SecureSourceOpener?) {
if (opener == null) sourceOpenerOverride.remove() else sourceOpenerOverride.set(opener)
}
internal fun hasSourceOpenerForTest(): Boolean = sourceOpenerOverride.get() != null
fun create(
context: Context,
folder: File,
onProgress: ((Float) -> Unit)? = null,
limits: EnhancedShareLimits = EnhancedShareLimits(),
): List<File> {
if (!folder.isDirectory || Files.isSymbolicLink(folder.toPath()) ||
limits.maxFilesPerArchive < 1 || limits.maxBytesPerFile < 1 || limits.maxBytesTotal < 1) {
return emptyList()
}
val out = SessionLogShare.shareDir(context).apply { deleteRecursively(); mkdirs() }
val stageLease = acquireDiagnosticStage(context, out.name)
val stage = stageLease.directory
return try {
val redactionLearningComplete = LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
val discovery = collect(context, folder, limits.maxDiscoveredFiles, legacy = false)
val candidates = discovery.candidates
val totalCandidates = candidates.size.coerceAtLeast(1)
val share = limits.maxBytesTotal / Category.values().size
val budgets = Category.values().associateWith { category ->
Budget(if (category == Category.GAMES) limits.maxBytesTotal - share * 2 else share)
}
var completed = 0
Category.values().map { category ->
val budget = budgets.getValue(category)
val records = ArrayList<Record>()
val selected = candidates.filter { it.category == category }
val zip = File(out, "DroidDeck-${folder.name}-${category.suffix}.zip")
ZipOutputStream(zip.outputStream().buffered()).use { archive ->
val names = HashSet<String>()
selected.forEachIndexed { index, candidate ->
val safeEntry = safeEntry(candidate.entry)
val record = when {
index >= limits.maxFilesPerArchive -> Record(
safeEntry ?: "<invalid>", candidate.origin, "omitted", reason = "file-count-limit",
)
safeEntry == null -> Record("<invalid>", candidate.origin, "omitted", reason = "unsafe-entry-name")
!names.add(safeEntry) -> Record(safeEntry, candidate.origin, "omitted", reason = "duplicate-entry")
else -> addCandidate(archive, candidate.copy(entry = safeEntry), stage, budget, limits)
}
records += record
completed++
onProgress?.invoke((completed.toFloat() / totalCandidates).coerceIn(0f, 1f))
}
if (category == Category.SESSION) addTrustedActivation(context, folder, archive)?.let(records::add)
if (selected.isEmpty()) records += Record("", category.suffix, "unavailable", reason = "no-matching-artifacts")
if (discovery.truncated) records += Record("", "discovery", "truncated", reason = "candidate-limit")
if (discovery.partial) records += Record("", "discovery", "truncated", reason = "filesystem-error")
addManifest(
archive, folder.name, category.suffix, records, limits, budget.limit, redactionLearningComplete,
)
}
zip
}
} finally {
stageLease.close()
}
}
fun createLegacy(
context: Context,
folder: File,
onProgress: ((Float) -> Unit)? = null,
outputDirectory: File = SessionLogShare.shareDir(context),
limits: EnhancedShareLimits = EnhancedShareLimits(maxFilesPerArchive = 512),
): File? {
if (!folder.isDirectory || Files.isSymbolicLink(folder.toPath()) ||
limits.maxFilesPerArchive < 1 || limits.maxBytesPerFile < 1 || limits.maxBytesTotal < 1) {
return null
}
val out = outputDirectory.apply { deleteRecursively(); mkdirs() }
val redactionLearningComplete = LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
val discovery = collect(context, folder, limits.maxDiscoveredFiles, legacy = true)
val candidates = discovery.candidates.filter { it.linePrefix == null }
if (candidates.isEmpty()) {
out.deleteRecursively()
return null
}
val stageLease = acquireDiagnosticStage(context, out.name)
val stage = stageLease.directory
val records = ArrayList<Record>()
val budget = Budget(limits.maxBytesTotal)
val zip = File(out, "DroidDeck-${folder.name}.zip")
return try {
ZipOutputStream(zip.outputStream().buffered()).use { archive ->
val names = HashSet<String>()
candidates.forEachIndexed { index, candidate ->
val safeEntry = safeEntry(candidate.entry)
records += when {
index >= limits.maxFilesPerArchive -> Record(
safeEntry ?: "<invalid>", candidate.origin, "omitted", reason = "file-count-limit",
)
safeEntry == null -> Record("<invalid>", candidate.origin, "omitted", reason = "unsafe-entry-name")
!names.add(safeEntry) -> Record(safeEntry, candidate.origin, "omitted", reason = "duplicate-entry")
else -> addCandidate(archive, candidate.copy(entry = safeEntry), stage, budget, limits)
}
onProgress?.invoke((index + 1f) / candidates.size)
}
addTrustedActivation(context, folder, archive)?.let(records::add)
if (discovery.truncated) records += Record("", "discovery", "truncated", reason = "candidate-limit")
if (discovery.partial) records += Record("", "discovery", "truncated", reason = "filesystem-error")
addManifest(archive, folder.name, "all", records, limits, budget.limit, redactionLearningComplete)
}
zip
} finally {
stageLease.close()
}
}
private fun addTrustedActivation(
context: Context,
folder: File,
archive: ZipOutputStream,
): Record? {
val manifest = EnhancedDiagnostics.manifest(context, folder) ?: return null
val bytes = (manifest.toString(2) + "\n").toByteArray()
val entry = "${folder.name}/${EnhancedDiagnostics.MANIFEST_FILE}"
archive.putNextEntry(ZipEntry(entry))
archive.write(bytes)
archive.closeEntry()
return Record(entry, "app-private-activation-state", "captured", bytes.size.toLong(), bytes.size.toLong())
}
private fun addCandidate(
archive: ZipOutputStream,
candidate: Candidate,
stage: File,
budget: Budget,
limits: EnhancedShareLimits,
): Record {
if (budget.remaining <= 0) {
return Record(candidate.entry, candidate.origin, "omitted", reason = "bundle-byte-limit")
}
if (!stage.isDirectory || !stage.canWrite()) throw StageUnavailableException(IOException("staging path is not writable"))
val snapshot = try {
snapshot(candidate, stage, minOf(limits.maxBytesPerFile, budget.remaining))
} catch (error: StageUnavailableException) {
throw error
} catch (error: Exception) {
if (!stage.isDirectory || !stage.canWrite()) throw StageUnavailableException(error)
val reportedError = (error as? SourceReadException)?.cause ?: error
return Record(candidate.entry, candidate.origin, "error", reason = reportedError.javaClass.simpleName)
} ?: return Record(candidate.entry, candidate.origin, "omitted", reason = "unsafe-or-unavailable-source")
if (snapshot.file.length() == 0L && candidate.linePrefix != null) {
snapshot.file.delete()
return Record(
candidate.entry,
candidate.origin,
if (snapshot.truncated) "truncated" else "unavailable",
snapshot.sourceBytes,
reason = if (snapshot.truncated) "no-matching-lines-in-bounded-scan" else "no-matching-lines",
)
}
return try {
budget.remaining -= snapshot.file.length()
archive.putNextEntry(ZipEntry(candidate.entry))
val writer = archive.bufferedWriter()
LogRedactor.scrubForShare(snapshot.file, writer)
writer.flush()
archive.closeEntry()
Record(
candidate.entry,
candidate.origin,
if (snapshot.truncated) "truncated" else "captured",
snapshot.sourceBytes,
snapshot.file.length(),
if (snapshot.truncated) "per-file-or-bundle-byte-limit" else null,
)
} finally {
snapshot.file.delete()
}
}
private fun snapshot(candidate: Candidate, stage: File, limit: Long): Snapshot? {
val rootPath = candidate.anchor.toPath().toAbsolutePath().normalize()
val sourcePath = candidate.file.toPath().toAbsolutePath().normalize()
if (!sourcePath.startsWith(rootPath) || sourcePath == rootPath || limit < 1) return null
val target = try {
File.createTempFile("diagnostic-", ".log", stage)
} catch (error: Exception) {
throw StageUnavailableException(error)
}
try {
val relative = rootPath.relativize(sourcePath)
return withSecureChannel(rootPath, relative) { input ->
val size = readSource { input.size() }
candidate.linePrefix?.let { prefix ->
val truncated = filterChannel(input, target, prefix, size, TRACE_SCAN_BYTES, limit)
return@withSecureChannel Snapshot(target, size, truncated)
}
writeStage {
FileOutputStream(target).channel.use { output ->
if (size <= limit) {
copy(input, output, 0, size)
} else {
val marker = "\n<diagnostic file truncated: beginning and tail retained>\n".toByteArray()
val content = (limit - marker.size).coerceAtLeast(0)
copyCompleteHead(input, output, content / 2)
val markerBytes = minOf(marker.size.toLong(), limit - output.position()).toInt()
output.write(ByteBuffer.wrap(marker, 0, markerBytes))
copyCompleteTail(input, output, size, (limit - output.position()).coerceAtLeast(0))
}
output.force(false)
}
}
Snapshot(target, size, size > limit)
} ?: target.delete().let { null }
} catch (e: Exception) {
if (e is StageUnavailableException) {
target.delete()
throw e
}
val targetWasPresent = target.exists()
target.delete()
if (!stage.isDirectory || !stage.canWrite() || !targetWasPresent) throw StageUnavailableException(e)
throw e
}
}
private fun filterChannel(
channel: SeekableByteChannel,
target: File,
prefix: String,
sourceSize: Long,
scanLimit: Long,
outputLimit: Long,
): Boolean {
val wanted = prefix.toByteArray()
var written = 0L
var truncated = sourceSize > scanLimit
writeStage {
target.outputStream().buffered().use { output ->
fun scan(start: Long, count: Long, discardPartialFirstLine: Boolean) {
readSource { channel.position(start) }
val input = BufferedInputStream(Channels.newInputStream(channel), COPY_BUFFER_BYTES)
val line = ByteArrayOutputStream(1024)
var oversized = false
var scanned = 0L
var discard = discardPartialFirstLine
fun emit() {
val bytes = line.toByteArray()
if (!discard && !oversized && bytes.size >= wanted.size && wanted.indices.all { bytes[it] == wanted[it] }) {
if (written + bytes.size + 1 <= outputLimit) {
output.write(bytes)
output.write('\n'.code)
written += bytes.size + 1
} else truncated = true
}
line.reset()
oversized = false
discard = false
}
while (scanned < count) {
val value = readSource { input.read() }
if (value < 0) break
scanned++
if (value == '\n'.code) emit()
else if (!oversized && !discard) {
if (line.size() >= LogRedactor.MAX_LINE_LENGTH) {
oversized = true
line.reset()
} else line.write(value)
}
}
if (start + scanned >= sourceSize && (line.size() > 0 || oversized)) emit()
}
if (sourceSize <= scanLimit) {
scan(0, sourceSize, false)
} else {
val head = scanLimit / 2
val tail = scanLimit - head
scan(0, head, false)
scan((sourceSize - tail).coerceAtLeast(0), tail, true)
}
}
}
return truncated
}
private fun <T> withSecureChannel(root: Path, relative: Path, block: (SeekableByteChannel) -> T): T? {
sourceOpenerOverride.get()?.let { return it.withChannel(root, relative, block) }
return withAndroidSecureChannel(root, relative, block)
}
private fun <T> withAndroidSecureChannel(root: Path, relative: Path, block: (SeekableByteChannel) -> T): T? {
val opened = ArrayList<ParcelFileDescriptor>()
var invokingBlock = false
return try {
val parts = relative.map { it.toString() }
if (parts.isEmpty()) return null
opened += openDirectoryDescriptor(root.toString()) ?: return null
for (part in parts.dropLast(1)) {
opened += openDirectoryDescriptor(procChild(opened.last(), part)) ?: return null
}
val leafFd = openDescriptor(procChild(opened.last(), parts.last())) ?: return null
try {
val stat = Os.fstat(leafFd)
if (!OsConstants.S_ISREG(stat.st_mode) || stat.st_nlink != 1L) return null
// Android's FileInputStream(FileDescriptor) is deliberately not the descriptor owner.
FileInputStream(leafFd).use { stream ->
invokingBlock = true
block(stream.channel)
}
} finally {
runCatching { Os.close(leafFd) }
}
} catch (error: Exception) {
if (invokingBlock) throw error
null
} finally {
opened.asReversed().forEach { runCatching { it.close() } }
}
}
private fun openDescriptor(path: String): java.io.FileDescriptor? = runCatching {
Os.open(
path,
OsConstants.O_RDONLY or OsConstants.O_CLOEXEC or OsConstants.O_NOFOLLOW or OsConstants.O_NONBLOCK,
0,
)
}.getOrNull()
private fun openDirectoryDescriptor(path: String): ParcelFileDescriptor? {
val fd = openDescriptor(path) ?: return null
return try {
if (!OsConstants.S_ISDIR(Os.fstat(fd).st_mode)) return null
ParcelFileDescriptor.dup(fd)
} finally {
runCatching { Os.close(fd) }
}
}
private fun procChild(directory: ParcelFileDescriptor, name: String): String =
"/proc/self/fd/${directory.fd}/$name"
private fun copy(input: SeekableByteChannel, output: FileChannel, start: Long, count: Long) {
readSource { input.position(start) }
var left = count
val buffer = ByteBuffer.allocate(64 * 1024)
while (left > 0) {
buffer.clear()
buffer.limit(minOf(buffer.capacity().toLong(), left).toInt())
val read = readSource { input.read(buffer) }
if (read < 0) break
buffer.flip()
while (buffer.hasRemaining()) writeStage { output.write(buffer) }
left -= read
}
}
private fun copyCompleteHead(input: SeekableByteChannel, output: FileChannel, limit: Long) {
if (limit <= 0) return
copy(input, output, 0, limit)
val copied = output.position()
readSource { input.position(0) }
val buffer = ByteBuffer.allocate(64 * 1024)
var scanned = 0L
var lastComplete = 0L
while (scanned < copied) {
buffer.clear()
buffer.limit(minOf(buffer.capacity().toLong(), copied - scanned).toInt())
val read = readSource { input.read(buffer) }
if (read < 0) break
buffer.flip()
repeat(read) { index ->
if (buffer.get(index) == '\n'.code.toByte()) lastComplete = scanned + index + 1
}
scanned += read
}
writeStage { output.truncate(lastComplete) }
writeStage { output.position(lastComplete) }
}
private fun copyCompleteTail(
input: SeekableByteChannel,
output: FileChannel,
sourceSize: Long,
limit: Long,
) {
if (limit <= 0 || sourceSize <= 0) return
var start = (sourceSize - limit).coerceAtLeast(0)
if (start > 0) {
readSource { input.position(start) }
val buffered = BufferedInputStream(Channels.newInputStream(input), COPY_BUFFER_BYTES)
while (start < sourceSize) {
val value = readSource { buffered.read() }
if (value < 0) return
start++
if (value == '\n'.code) break
}
}
copy(input, output, start, (sourceSize - start).coerceAtMost(limit))
}
private inline fun <T> readSource(block: () -> T): T = try {
block()
} catch (error: Exception) {
throw SourceReadException(error)
}
private inline fun <T> writeStage(block: () -> T): T = try {
block()
} catch (error: SourceReadException) {
throw error
} catch (error: StageUnavailableException) {
throw error
} catch (error: Exception) {
throw StageUnavailableException(error)
}
private fun addManifest(
archive: ZipOutputStream,
sessionId: String,
category: String,
records: List<Record>,
limits: EnhancedShareLimits,
categoryBudget: Long,
redactionLearningComplete: Boolean,
) {
val entries = JSONArray()
records.take(MAX_MANIFEST_RECORDS).forEach { record ->
entries.put(JSONObject().apply {
put("entry", record.entry)
put("origin", record.origin)
put("status", record.status)
put("sourceBytes", record.sourceBytes)
put("capturedBytes", record.capturedBytes)
record.reason?.let { put("reason", it) }
})
}
if (records.size > MAX_MANIFEST_RECORDS) {
entries.put(JSONObject().apply {
put("entry", "")
put("origin", "manifest")
put("status", "omitted")
put("reason", "${records.size - MAX_MANIFEST_RECORDS} additional records")
})
}
val manifest = JSONObject().apply {
put("schema", 1)
put("sessionId", sessionId)
put("category", category)
put("generatedAtMillis", System.currentTimeMillis())
put("redactionLearning", if (redactionLearningComplete) "complete" else "incomplete")
put("limits", JSONObject().apply {
put("maxFilesPerArchive", limits.maxFilesPerArchive)
put("maxDiscoveredFiles", limits.maxDiscoveredFiles)
put("maxBytesPerFile", limits.maxBytesPerFile)
put("budgetBasis", "raw-input-snapshot-bytes")
put("maxRawInputBytesTotal", limits.maxBytesTotal)
put("categoryRawInputBudgetBytes", categoryBudget)
})
put("entries", entries)
}.toString(2) + "\n"
archive.putNextEntry(ZipEntry("diagnostics-manifest.json"))
archive.write(manifest.toByteArray())
archive.closeEntry()
}
private fun collect(context: Context, folder: File, maxFiles: Int, legacy: Boolean): CollectionResult {
val out = LinkedHashMap<String, Candidate>()
val categoryCounts = HashMap<Category, Int>()
val perCategory = (maxFiles / Category.values().size).coerceAtLeast(1)
var truncated = false
var partial = false
fun add(
file: File,
root: File,
entry: String,
origin: String,
forcedCategory: Category? = null,
linePrefix: String? = null,
) {
val safe = safeEntry(entry) ?: return
val category = forcedCategory ?: category(entry.removePrefix("${folder.name}/"))
if (out.size >= maxFiles || (categoryCounts[category] ?: 0) >= perCategory) {
truncated = true
return
}
val anchor = anchorFor(context, root)
if (out.putIfAbsent(safe, Candidate(file, anchor, safe, origin, category, linePrefix)) == null) {
categoryCounts[category] = (categoryCounts[category] ?: 0) + 1
}
}
CRITICAL_SESSION_FILES.forEach { name ->
File(folder, name).takeIf { it.exists() }?.let { add(it, folder, "${folder.name}/$name", "session-critical") }
}
File(folder, "session.log").takeIf { it.exists() }?.let { file ->
add(
file, folder, "${folder.name}/graphics/frame-trace.log", "guest-frame-trace",
Category.GRAPHICS, "DROIDDECK_FRAME_TRACE ",
)
add(
file, folder, "${folder.name}/graphics/process-trace.log", "guest-process-trace",
Category.GRAPHICS, "DROIDDECK_PROCESS_TRACE ",
)
add(
file, folder, "${folder.name}/games/game-lifecycle.log", "guest-game-lifecycle",
Category.GAMES, "DROIDDECK_DIAGNOSTICS event=game_",
)
}
if (SessionPaths.current()?.canonicalFile == folder.canonicalFile && !File(folder, "steam").exists()) {
val steam = File(SessionPrefs.activeSteamRoot(context), "logs")
val scan = directFiles(steam, remaining(maxFiles, out.size))
truncated = truncated || scan.truncated
partial = partial || scan.partial
scan.files.forEach {
add(it, steam, "${folder.name}/steam/${it.name}", "live-steam")
}
}
val logs = LinuxRuntime.logDir(context)
for ((name, root) in listOf(SessionLogShare.STORES_DIR to File(logs, SessionLogShare.STORES_DIR), SessionPaths.TOOLS_DIR to File(logs, SessionPaths.TOOLS_DIR))) {
val scan = directFiles(root, remaining(maxFiles, out.size))
truncated = truncated || scan.truncated
partial = partial || scan.partial
scan.files.asSequence().filter { recent(it) }
.forEach { add(it, root, "$name/${it.name}", name) }
}
if (legacy) {
val scan = legacyBattleNet(context)
truncated = truncated || scan.truncated
partial = partial || scan.partial
scan.sources.forEach { source ->
add(source.file, source.root, source.entry, "battlenet")
}
} else {
battleNetRoots(context).forEach { (prefix, root) ->
val scan = walk(root, remaining(maxFiles, out.size))
truncated = truncated || scan.truncated
partial = partial || scan.partial
scan.files.asSequence().filter { recent(it) && it.name.endsWith(".log", true) }
.forEach { file ->
val relative = root.toPath().toAbsolutePath().normalize().relativize(file.toPath().toAbsolutePath().normalize()).joinToString("/")
add(file, root, "battlenet/$prefix/$relative", "battlenet")
}
}
}
val sessionScan = walk(folder, remaining(maxFiles, out.size))
truncated = truncated || sessionScan.truncated
partial = partial || sessionScan.partial
sessionScan.files.forEach { file ->
val relative = file.toPath().toAbsolutePath().normalize()
.let { folder.toPath().toAbsolutePath().normalize().relativize(it).joinToString("/") }
if (relative == EnhancedDiagnostics.MANIFEST_FILE) return@forEach
add(file, folder, "${folder.name}/$relative", "session")
}
return CollectionResult(out.values.toList(), truncated, partial)
}
private fun remaining(maxFiles: Int, found: Int): Int = (maxFiles - found + 1).coerceAtLeast(0)
private fun walk(root: File, limit: Int): ScanResult {
if (limit <= 0 || !root.isDirectory || Files.isSymbolicLink(root.toPath())) return ScanResult(emptyList(), false)
val files = ArrayList<File>(limit)
var truncated = false
var partial = false
var visited = 0
val rootPath = root.toPath()
val visitLimit = (limit * 4).coerceAtLeast(limit).coerceAtMost(MAX_DISCOVERY_VISITS)
try {
Files.walkFileTree(rootPath, object : SimpleFileVisitor<Path>() {
private fun countVisit(): FileVisitResult {
visited++
return if (visited > visitLimit) {
truncated = true
FileVisitResult.TERMINATE
} else FileVisitResult.CONTINUE
}
override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult =
if (dir == rootPath) FileVisitResult.CONTINUE else countVisit()
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
if (countVisit() == FileVisitResult.TERMINATE) return FileVisitResult.TERMINATE
if (files.size >= limit) {
truncated = true
return FileVisitResult.TERMINATE
}
if (attrs.isRegularFile || Files.isSymbolicLink(file)) files += file.toFile()
return FileVisitResult.CONTINUE
}
override fun visitFileFailed(file: Path, exc: IOException): FileVisitResult {
partial = true
return countVisit()
}
override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
if (exc != null) partial = true
return FileVisitResult.CONTINUE
}
})
} catch (_: Exception) {
partial = true
}
return ScanResult(files, truncated, partial)
}
private fun directFiles(root: File, limit: Int): ScanResult {
if (limit <= 0 || !root.isDirectory || Files.isSymbolicLink(root.toPath())) return ScanResult(emptyList(), false)
val files = ArrayList<File>(limit)
var truncated = false
var partial = false
try {
Files.newDirectoryStream(root.toPath()).use { entries ->
val iterator = entries.iterator()
while (iterator.hasNext() && files.size < limit) {
val path = iterator.next()
if (Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Files.isSymbolicLink(path)) {
files += path.toFile()
}
}
truncated = iterator.hasNext()
}
} catch (_: Exception) {
partial = true
}
return ScanResult(files, truncated, partial)
}
private fun battleNetRoots(context: Context): List<Pair<String, File>> {
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
val data = File(drive, "ProgramData/Battle.net")
return listOf(
"droiddeck" to File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet"),
"client" to File(drive, "users/steamuser/AppData/Local/Battle.net/Logs"),
"agent" to File(data, "Agent"),
"setup" to File(data, "Setup"),
)
}
private fun legacyBattleNet(context: Context): LegacyDiscovery {
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
val data = File(drive, "ProgramData/Battle.net")
val agent = File(data, "Agent")
val setup = File(data, "Setup")
val agentChildren = childDirectories(agent, "Agent.")
val setupChildren = childDirectories(setup, "")
val scans = listOf(
legacyNewest(
"droiddeck",
listOf(File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet")),
2,
setOf("battlenet.log", "spawned.log"),
),
legacyNewest("client", listOf(File(drive, "users/steamuser/AppData/Local/Battle.net/Logs")), 6),
legacyNewest(
"agent", listOf(File(agent, "Logs")) + agentChildren.files.map { File(it, "Logs") }, 10,
byDir = true,
),
legacyNewest("setup", setupChildren.files.map { File(it, "Logs") }, 3, byDir = true),
)
return LegacyDiscovery(
scans.flatMap { it.sources },
scans.any { it.truncated } || agentChildren.truncated || setupChildren.truncated,
scans.any { it.partial } || agentChildren.partial || setupChildren.partial,
)
}
private fun legacyNewest(
folder: String,
roots: List<File>,
count: Int,
names: Set<String>? = null,
byDir: Boolean = false,
): LegacyDiscovery {
val found = ArrayList<Pair<File, File>>()
var truncated = false
var partial = false
roots.forEach { root ->
val scan = directFiles(root, MAX_BATTLENET_SCAN)
truncated = truncated || scan.truncated
partial = partial || scan.partial
found += scan.files.asSequence()
.filter { recent(it) && it.name.endsWith(".log") && it.length() <= LEGACY_LOG_MAX_BYTES }
.filter { names == null || it.name in names }
.map { it to root }
.toList()
}
val ordered = found.sortedByDescending { it.first.lastModified() }
return LegacyDiscovery(
ordered.take(count).map { (file, root) ->
val relative = if (byDir) "$folder/${file.parentFile?.parentFile?.name}/${file.name}" else "$folder/${file.name}"
LegacySource(file, root, "battlenet/$relative")
},
truncated || ordered.size > count,
partial,
)
}
private fun childDirectories(root: File, prefix: String): ScanResult {
if (!root.isDirectory || Files.isSymbolicLink(root.toPath())) return ScanResult(emptyList(), false)
val found = ArrayList<File>()
var truncated = false
var partial = false
try {
Files.newDirectoryStream(root.toPath()).use { entries ->
val iterator = entries.iterator()
while (iterator.hasNext() && found.size < MAX_BATTLENET_DIRECTORIES) {
val path = iterator.next()
if (path.fileName.toString().startsWith(prefix) &&
Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS) && !Files.isSymbolicLink(path)) found += path.toFile()
}
truncated = iterator.hasNext()
}
} catch (_: Exception) {
partial = true
}
return ScanResult(found, truncated, partial)
}
private fun recent(file: File): Boolean = file.lastModified() >= System.currentTimeMillis() - RECENT_MILLIS
private fun anchorFor(context: Context, root: File): File {
val path = root.toPath().toAbsolutePath().normalize()
for (anchor in listOf(context.filesDir, context.cacheDir)) {
if (path.startsWith(anchor.toPath().toAbsolutePath().normalize())) return anchor
}
return root.parentFile ?: root
}
private fun safeEntry(name: String): String? {
if (name.any { it.code < 0x20 || it.code == 0x7f }) return null
val normalized = name.replace('\\', '/').trimStart('/')
val parts = normalized.split('/')
if (normalized.isEmpty() || parts.any { it.isEmpty() || it == "." || it == ".." }) return null
return parts.joinToString("/") { safeComponent(it) }
}
private fun safeComponent(value: String): String {
if (value in KNOWN_COMPONENTS || KNOWN_COMPONENT_PATTERNS.any { it.matches(value) }) return value
val suffix = SAFE_SUFFIX.find(value)?.value.orEmpty().lowercase(Locale.US)
val digest = MessageDigest.getInstance("SHA-256").digest(value.toByteArray())
.take(8).joinToString("") { "%02x".format(Locale.US, it.toInt() and 0xff) }
return "entry-$digest$suffix"
}
private fun category(entry: String): Category {
val value = entry.lowercase(Locale.US)
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") ||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").any(value::contains)) return Category.GAMES
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
return Category.SESSION
}
private val GAME_LOG = Regex("steam-[0-9]+\\.(log|txt)")
private val KNOWN_COMPONENTS = setOf(
"steam", "graphics", "games", "battlenet", "client", "agent", "setup", "stores", "tools",
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt",
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
)
private val KNOWN_COMPONENT_PATTERNS = listOf(
Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
Regex("steam-[0-9]+\\.(?:log|txt)"),
Regex("(?:battle\\.net-[0-9]+|battle\\.net-setup-[0-9]+|Agent-[0-9]+)\\.log"),
Regex("(?:Agent\\.[0-9]+|bna_[0-9]+)"),
Regex("stores-[0-9]{4}-[0-9]{2}-[0-9]{2}\\.log"),
Regex("entry-[0-9a-f]{16}(?:\\.[a-z0-9]{1,8})?"),
)
private val SAFE_SUFFIX = Regex("\\.[A-Za-z0-9]{1,8}$")
private val CRITICAL_SESSION_FILES = listOf(
"session.log", "app.log", "wayland.log", "audio.log", "device.txt", "network.txt",
"events.jsonl", "memory.csv", "capture.json", "crash.log",
)
private const val RECENT_MILLIS = 7L * 24 * 60 * 60 * 1000
private const val COPY_BUFFER_BYTES = 64 * 1024
private const val TRACE_SCAN_BYTES = 16L * 1024 * 1024
private const val LEGACY_LOG_MAX_BYTES = 8L * 1024 * 1024
private const val MAX_BATTLENET_SCAN = 64
private const val MAX_BATTLENET_DIRECTORIES = 64
private const val MAX_MANIFEST_RECORDS = 512
private const val MAX_DISCOVERY_VISITS = 4096
}
@@ -117,8 +117,7 @@ object GameEnvironmentStore {
if (gameDxvk.length() > 0) json.put(DXVK_CONFIG_GAMES, gameDxvk)
json.put(
GAME_DEBUG_LOGS,
gameDebugLogsOverride ?: (SessionPrefs.logsEnabled(context) &&
SessionPrefs.gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context)),
gameDebugLogsOverride ?: SessionPrefs.gameDebugLogsEffective(context),
)
write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString())
}
@@ -48,7 +48,33 @@ object GameStorage {
return when {
pref == SessionPrefs.GAME_STORAGE_OFF -> null
pref.isEmpty() -> options(context).firstOrNull()?.let { Option(it.name, it.path) }
else -> Option(SessionPrefs.gameStorageLabel(context), pref)
else -> Option(SessionPrefs.gameStorageLabel(context), pref).takeIf { attached(File(pref)) }
}
}
fun disconnected(context: Context): Boolean {
val pref = SessionPrefs.gameStorage(context)
return pref.isNotEmpty() && pref != SessionPrefs.GAME_STORAGE_OFF && !attached(File(pref))
}
internal fun attached(path: File): Boolean =
attached(path, runCatching { Environment.getExternalStorageState(path) }.getOrNull())
internal fun attached(
path: File,
state: String?,
externalStoragePath: Boolean = isExternalStoragePath(path),
): Boolean = when {
state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY -> true
externalStoragePath -> false
state == Environment.MEDIA_UNKNOWN || state == null -> path.isDirectory || path.parentFile?.isDirectory == true
else -> false
}
private fun isExternalStoragePath(path: File): Boolean {
val absolute = path.absoluteFile.toPath().normalize()
return listOf(File("/storage"), File("/mnt/media_rw")).any {
absolute.startsWith(it.absoluteFile.toPath().normalize())
}
}
@@ -0,0 +1,250 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.Build
import android.system.Os
import com.droiddeck.launcher.core.DeviceSupport
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.gpu.DriverBundle
import com.droiddeck.launcher.gpu.DriverPairs
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.gpu.TurnipReleases
import com.droiddeck.launcher.gpu.VulkanInfo
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* graphics-report.txt in each session's folder: which graphics path the session drew with and why,
* the GPU and its device nodes, the environment the guest got, and at the end what the compositor
* said about its driver. Written for a non-Adreno test report, where a black screen otherwise comes
* with nothing to read; the Share logs zip takes the whole folder, so it travels with the logs.
* Read-only: nothing here opens a GPU node or changes a setting.
*/
object GraphicsReport {
const val FILE = "graphics-report.txt"
const val GAMES_DIR = "games"
/** One file in games/ past this is cut to its first part at the session's end. */
private const val GAME_FILE_MAX = 20L * 1024 * 1024
/** All of games/ past this loses its oldest launches. */
private const val GAMES_TOTAL_MAX = 120L * 1024 * 1024
/** The guest keys the report repeats: everything that decides which Vulkan driver loads. */
private val ENV_PREFIXES = listOf(
"VK_", "BL_VK", "BL_DRM", "BL_VKBRIDGE", "VKBRIDGE", "MESA_", "GALLIUM_", "ZINK", "TU_", "PANVK",
"DROIDDECK_POWERVR", "DROIDDECK_HYBRIS", "BL_GAME_LOGS", "LIBGL_", "GAMESCOPE_DISABLE", "XWAYLAND",
)
/** Per-game graphics logs and the guest's Vulkan summary: on for a non-Adreno GPU, or by Setup's switch. */
fun detailed(context: Context): Boolean = !DeviceSupport.adreno() || SessionPrefs.detailedGraphicsLogs(context)
/** For finish(), which runs from the session's end without a context of its own. */
@Volatile private var appContext: Context? = null
/** Writes the start of the report; never throws. */
fun begin(context: Context, dir: File, guest: List<String>) {
appContext = context.applicationContext
runCatching { File(dir, FILE).writeText(start(context, guest)) }
.onFailure { android.util.Log.w("GraphicsReport", "could not write $FILE", it) }
}
private fun start(context: Context, guest: List<String>): String = buildString {
val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
appendLine("== graphics report, session start $time")
appendLine("build: ${com.droiddeck.launcher.BuildConfig.BUILD_LABEL} (source ${com.droiddeck.launcher.BuildConfig.SOURCE_COMMIT})")
appendLine()
val gpu = runCatching { GpuInfo.detect() }.getOrNull()
appendLine("-- path")
appendLine("path: " + path(context))
appendLine("driver mode: " + SessionPrefs.gpuDriverMode(context))
appendLine("display driver (compositor): " + SessionPrefs.androidDriver(context).ifEmpty {
if (DeviceSupport.adreno()) "(auto: bundled Turnip)" else "(auto: the phone's own Vulkan driver, ${SystemVulkanDriver.hal() ?: "vendor HAL"})"
})
val display = SessionPrefs.androidDriver(context)
appendLine("display driver chosen by: " + when {
display.isEmpty() -> "auto (or a pair on a non-Adreno GPU: the phone's own driver)"
DriverBundle.containing(context, display, false) != null -> "pair (its display half)"
else -> "user (picked on its own)"
})
val linux = SessionPrefs.linuxDriver(context)
appendLine("runtime driver: " + linux.ifEmpty { "(runtime default)" })
if (linux.isNotEmpty()) {
val dir = com.droiddeck.launcher.gpu.LinuxVulkanDriverManager(context).getDriverDir(linux)
appendLine("runtime driver dir: ${dir.path} (" + (dir.listFiles()?.filter { it.name.endsWith(".so") }?.joinToString { it.name } ?: "missing") + ")")
}
val prefs = context.getSharedPreferences("graphics_report", Context.MODE_PRIVATE)
val previous = prefs.getString("lastDrivers", null)
val now = "display ${SessionPrefs.androidDriver(context).ifEmpty { "(auto)" }}, runtime ${linux.ifEmpty { "(default)" }}, bridge ${DeviceSupport.vkBridge(context)}, venus ${VenusComponent.wanted(context)}"
appendLine("previous session's drivers: " + (previous ?: "(none recorded)") + if (previous != null && previous != now) " << CHANGED" else "")
prefs.edit().putString("lastDrivers", now).apply()
DriverBundle.active(context)?.let { b ->
appendLine("pair: ${b.name} ${b.version} (bundle ${b.id})")
release(context, b.id)?.let { appendLine("pair release: $it") }
}
if (gpu != null) {
val pairs = DriverPairs.from(TurnipReleases.cached(context))
appendLine("auto would pick: " + (DriverPairs.recommendedKey(gpu, pairs) ?: "(no pair: system driver or bridge)"))
}
appendLine("frame generation: " + runCatching { com.droiddeck.launcher.gpu.FrameGen.mode(context).toString() }.getOrDefault("?") +
" (engine=off means it is switched off in Play settings; a driver that fails LSFG's gates logs \"device gates\" below)")
appendLine("mali bridge setting: " + SessionPrefs.vkBridge(context) + ", in use: " + DeviceSupport.vkBridge(context))
val standIn = runCatching { com.droiddeck.launcher.runtime.LinuxRuntime.gpuStandIn(context) }.getOrNull()
appendLine("render node for the guest: " + (standIn?.let { node ->
com.droiddeck.launcher.runtime.LinuxRuntime.deviceNumbers(node)?.let { n -> "/dev/dri/renderD${n.substringAfter(':')} -> $node ($n)" } ?: node
} ?: if (SystemVulkanDriver.isPowerVr()) "the system GPU's own /dev/dri node (#570)" else "none"))
appendLine()
appendLine("-- gpu")
if (gpu != null) {
appendLine("family: ${gpu.family} (${gpu.supportText})")
appendLine("name: ${gpu.name}" + if (gpu.model > 0) ", model ${gpu.model} (${gpu.modelSource})" else "")
}
appendLine("vulkan device (app): " + (VulkanInfo.cachedOrNull()?.get("device") ?: "(not probed)"))
appendLine("system vulkan hal: " + (SystemVulkanDriver.hal() ?: "none"))
read("/sys/class/misc/mali0/device/gpuinfo")?.let { appendLine("mali gpuinfo: $it") }
appendLine("android: ${Build.VERSION.RELEASE} (sdk ${Build.VERSION.SDK_INT}), ${Build.MANUFACTURER} ${Build.MODEL}")
val soc = if (Build.VERSION.SDK_INT >= 31) "${Build.SOC_MANUFACTURER} ${Build.SOC_MODEL}" else Build.HARDWARE
appendLine("soc: $soc, board ${Build.BOARD}, hardware ${Build.HARDWARE}")
appendLine("kernel: " + (System.getProperty("os.version") ?: "?"))
appendLine()
appendLine("-- gpu nodes (from the app; not opened)")
val dri = File("/dev/dri").list()?.sorted()?.map { "/dev/dri/$it" }.orEmpty()
for (path in listOf("/dev/kgsl-3d0", "/dev/mali0") + dri) appendLine(node(path))
if (dri.isEmpty()) appendLine("/dev/dri: " + if (File("/dev/dri").exists()) "not listable" else "absent")
appendLine()
appendLine("-- guest environment (graphics)")
guest.filter { e -> ENV_PREFIXES.any { e.startsWith(it) } }.sorted().forEach { appendLine(it) }
appendLine()
}
/** Which backend this session's Vulkan goes through, as the session decides it. */
private fun path(context: Context): String = when {
DeviceSupport.adreno() -> "Turnip (Adreno, KGSL)"
VenusComponent.wanted(context) -> "Mali (Venus): Mesa Venus over vtest to the phone's own Vulkan driver, with the Mali compatibility layer"
DeviceSupport.vkBridge(context) -> "Mali bridge (#517): the phone's own Vulkan driver through the bridge"
DeviceSupport.openDriverActive(context) -> "open driver pair (PanVK / RADV)"
SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(context)) && SystemVulkanDriver.isAvailable() ->
"system Vulkan (#570): ${SystemVulkanDriver.gpuName()} driver through libhybris"
SessionPrefs.linuxDriver(context).isNotEmpty() -> "imported runtime driver ${SessionPrefs.linuxDriver(context)}"
else -> "none for this GPU (no Adreno, no system HAL, no pair, bridge off)"
}
/** The release tag and download a pair bundle came from, when the last release check knows it. */
private fun release(context: Context, bundleId: String): String? {
val bundles = TurnipReleases.cached(context)?.assets?.filter { it.bundle }.orEmpty()
val asset = bundles.firstOrNull { it.name.removeSuffix("-Pair.zip") == bundleId }
?: bundles.firstOrNull { bundleId.startsWith(it.name.removeSuffix("-Pair.zip") + "-") }
?: return null
val installed = TurnipReleases.installedBuiltOn(context, asset)
return "${asset.tag} ${asset.url}" +
(if (installed.isNotEmpty()) ", installed build uploaded $installed" else "") +
(if (asset.builtOn.isNotEmpty()) ", listed build uploaded ${asset.builtOn}" else "") +
(if (TurnipReleases.updateAvailable(context, asset)) " << NEWER BUILD AVAILABLE" else "")
}
private fun node(path: String): String {
val f = File(path)
if (!f.exists()) return "$path: absent"
val access = (if (f.canRead()) "r" else "-") + (if (f.canWrite()) "w" else "-")
val rdev = runCatching { Os.stat(path).st_rdev }.getOrNull()
val numbers = rdev?.let { " ${major(it)}:${minor(it)}" }.orEmpty()
val label = runCatching { String(Os.getxattr(path, "security.selinux")).trimEnd('\u0000') }.getOrNull()
return "$path: $access$numbers" + (label?.let { " $it" } ?: "")
}
/** Linux's dev_t split (glibc's gnu_dev_major / gnu_dev_minor). */
internal fun major(dev: Long): Long = ((dev ushr 8) and 0xfff) or ((dev ushr 32) and 0xfffff000L)
internal fun minor(dev: Long): Long = (dev and 0xff) or ((dev ushr 12) and 0xffffff00L)
private fun read(path: String): String? = FileUtils.readString(File(path))?.trim()?.takeIf { it.isNotEmpty() }
/** The compositor's driver lines from the app's own log. */
private val COMPOSITOR = Regex(
"""vk_present|waylandcomp|vk_loader|compositor|vkCreateDevice|extension|adrenotools|TurnipDriver|""" +
"""graphics driver|display driver|DD_PRESENT_FAULT|SystemVulkan|vkbridge|VkBridge|mali_gralloc|panvk|PanVK|radv|MESA|native buffer|first frame|present|""" +
"""lsfg|FrameGen|device gates|AAudio|directaudio|pulse|gralloc|dma.?buf|modifier|import""",
RegexOption.IGNORE_CASE,
)
/** The session script's driver lines: what it exported, the bridge's self-test, vulkaninfo, gamescope's Vulkan errors. */
private val GUEST = Regex("""== vulkan driver|== vkbridge|== vulkaninfo|vulkan:|panvk|PanVK|radv|primary node|No compatible|DRM format|kbase|AAUDIO|client sink|Xwayland|\(EE\)|glamor|XWAYLAND_NO_GLAMOR""", RegexOption.IGNORE_CASE)
/**
* The end of the report, from the finished folder: the compositor's driver lines out of
* app.log, and games/ held to its size limits. Never throws.
*/
fun finish(dir: File) {
runCatching {
val report = File(dir, FILE)
if (!report.isFile) return
val lines = File(dir, "app.log").takeIf { it.isFile }?.useLines { seq -> seq.filter { COMPOSITOR.containsMatchIn(it) }.take(400).toList() }.orEmpty()
val games = File(dir, GAMES_DIR).listFiles()?.filter { it.isDirectory }?.sortedBy { it.name }.orEmpty()
val guestLines = File(dir, "session.log").takeIf { it.isFile }?.useLines { seq ->
seq.filter { GUEST.containsMatchIn(it) }.take(200).toList()
}.orEmpty()
val fallbackLines = File(dir, "vkbridge-fallback").takeIf { it.isFile }?.readLines()?.map { it.trim() }?.filter { it.isNotEmpty() }
val fellBack = fallbackLines?.firstOrNull()
val fallbackReason = fallbackLines?.getOrNull(1).orEmpty()
runCatching { SessionPrefs.setBridgeFellBack(appContext ?: return@runCatching, fellBack != null, fallbackReason) }
val limits = File(dir, "limits.txt").takeIf { it.isFile }?.readText()?.trim()
val audio = File(dir, "audio.log").takeIf { it.isFile }?.readText().orEmpty()
report.appendText(buildString {
limits?.let { appendLine("open files limit: $it") }
fellBack?.let {
if (fallbackReason == "memory") appendLine("!! MALI BRIDGE FELL BACK: memory sharing = none (no method passed the server's self-test); the session ran on $it")
else appendLine("!! MALI BRIDGE FELL BACK: the self-test failed images or draws; the session ran on $it")
}
com.droiddeck.launcher.wayland.WaylandCompositor.compositorFault().takeIf { it.isNotEmpty() }?.let {
appendLine("!! DISPLAY FAILED: $it")
}
com.droiddeck.launcher.wayland.WaylandCompositor.displayDriver().takeIf { it.isNotEmpty() }?.let {
appendLine("display driver (as loaded): $it")
}
appContext?.let { ctx ->
if (SessionPrefs.venus(ctx)) VenusComponent.hostVulkanTooOld(ctx)?.let {
appendLine("!! VENUS OFF: the phone's driver reports Vulkan $it; gamescope needs 1.2 or newer, so the session did not use Venus")
}
}
if (audio.contains("AAUDIO_ERROR_DISCONNECTED")) {
appendLine("!! SOUND: Android refused the audio output (AAUDIO_ERROR_DISCONNECTED) - rebooting the phone usually fixes this")
}
if (guestLines.any { it.contains("vkbridge", ignoreCase = true) && it.contains("FAIL") }) {
appendLine("!! MALI BRIDGE SELF-TEST FAILED: this GPU's driver did not pass the bridge's checks (see below)")
}
if (guestLines.any { it.contains("MEM_EXEC_INIT") }) {
appendLine("note: kbase refused KBASE_IOCTL_MEM_EXEC_INIT with EPERM. That answer comes from the kbase driver")
appendLine(" itself (proot does not filter ioctls; Android's seccomp would kill or return ENOSYS; SELinux")
appendLine(" would return EACCES), so it is the kernel's policy for this context, not the session's.")
}
appendLine("-- driver lines from the session log (${guestLines.size})")
guestLines.forEach { appendLine(it) }
appendLine()
appendLine("-- compositor and driver lines from app.log (${lines.size})")
lines.forEach { appendLine(it) }
appendLine()
appendLine("-- game launches with detailed logs: ${games.size}")
games.forEach { appendLine(it.name) }
appendLine("== session end " + SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date()))
})
capGames(File(dir, GAMES_DIR))
}.onFailure { android.util.Log.w("GraphicsReport", "could not finish $FILE", it) }
}
/** Cuts each file in [games] to [GAME_FILE_MAX] and drops the oldest launches past [GAMES_TOTAL_MAX]. */
internal fun capGames(games: File, fileMax: Long = GAME_FILE_MAX, totalMax: Long = GAMES_TOTAL_MAX) {
if (!games.isDirectory) return
games.walkTopDown().filter { it.isFile && it.length() > fileMax }.forEach { f ->
runCatching { java.io.RandomAccessFile(f, "rw").use { it.setLength(fileMax) } }
}
val launches = games.listFiles()?.filter { it.isDirectory }?.sortedBy { it.name }.orEmpty().toMutableList()
fun size(d: File) = d.walkTopDown().filter { it.isFile }.sumOf { it.length() }
var total = launches.sumOf { size(it) }
while (total > totalMax && launches.size > 1) {
val oldest = launches.removeAt(0)
total -= size(oldest)
FileUtils.delete(oldest)
}
}
}
@@ -77,6 +77,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
var stepText: String? = null
var downloadAt = -1
var downloadPercent = -1
var applyingAt = -1
var clientDownloadAt = -1
var clientDownload: String? = null
var clientPercent = -1
@@ -99,10 +100,16 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
val done = m.groupValues[1].toLong()
val total = maxOf(1L, m.groupValues[2].toLong())
downloadPercent = (done * 100 / total).toInt()
} else if (steam && UPDATE_APPLYING.matches(line)) {
applyingAt = at
}
}
}
return when {
applyingAt > stepAt && applyingAt > downloadAt -> Line(
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update_applying), -1,
Topic.STEAM, readable = true,
)
downloadAt > stepAt && downloadPercent >= 0 -> Line(
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update, downloadPercent), downloadPercent,
Topic.STEAM, readable = true,
@@ -151,6 +158,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
private const val TAIL_BYTES = 48L * 1024
private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""")
private val UPDATE_APPLYING = Regex("""^\s*(?:\[[^\]]+\]\s*)*(?:Extracting package|Installing update)\.\.\.\s*$""")
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
private val INSTALL_MEGABYTES = Regex("""^, (\d+) of (\d+) MB""")
}
@@ -11,6 +11,22 @@ object OrphanReaper {
fun release(pid: Int) { kept.remove(pid) }
fun hasOtherProcesses(): Boolean = hasOtherProcesses(
File("/proc").list()?.mapNotNull { it.toIntOrNull() }, android.os.Process.myPid(),
) { pid ->
try {
android.system.Os.kill(pid, 0)
true
} catch (error: android.system.ErrnoException) {
error.errno != android.system.OsConstants.ESRCH && error.errno != android.system.OsConstants.EPERM
} catch (error: SecurityException) {
true
}
}
internal fun hasOtherProcesses(pids: List<Int>?, ownPid: Int, signalable: (Int) -> Boolean): Boolean =
pids == null || pids.any { it > 1 && it != ownPid && signalable(it) }
fun reap(reason: String, matching: (String) -> Boolean = { true }): Int {
val me = android.os.Process.myPid()
val uid = android.os.Process.myUid()
@@ -11,4 +11,12 @@ object PipPolicy {
height.toDouble() / width > 2.39 -> 100 to 239
else -> width to height
}
fun outputSize(width: Int, height: Int, outputWidth: Int, outputHeight: Int): Pair<Int, Int>? {
if (width <= 0 || height <= 0 || outputWidth <= 0 || outputHeight <= 0) return null
val scale = minOf(width.toFloat() / outputWidth, height.toFloat() / outputHeight)
val fittedWidth = ((outputWidth * scale).toInt() and 1.inv()).coerceAtLeast(2)
val fittedHeight = ((outputHeight * scale).toInt() and 1.inv()).coerceAtLeast(2)
return fittedWidth to fittedHeight
}
}
@@ -502,14 +502,20 @@ object SessionArtifacts {
return true
}
/**
* Finishes the folders of sessions whose process died without its teardown. Returns true when
* the newest of them ended because Android killed the app for memory, so the app can say so
* (a game "crashing" on a phone with little free RAM is usually this, not a driver fault).
*/
@Synchronized
fun finishAbandoned(context: Context, beforeGuestStart: Boolean = false) {
fun finishAbandoned(context: Context, beforeGuestStart: Boolean = false): Boolean {
val stopWhenSessionStarts = !beforeGuestStart
val parent = LinuxRuntime.logDir(context)
val abandoned = parent.listFiles { f ->
SessionPaths.isSessionFolder(f) && !File(f, COMPLETE_MARKER).exists() && !inFlight(f)
}?.sortedWith(SessionPaths.chronological) ?: return
if (abandoned.isEmpty()) return
}?.sortedWith(SessionPaths.chronological) ?: return false
if (abandoned.isEmpty()) return false
var killedForMemory = false
val current = SessionPaths.current()
val latestPreviousSession = SessionPaths.sessionFolders(context).lastOrNull { it != current }
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
@@ -534,8 +540,10 @@ object SessionArtifacts {
"audio.log, device.txt) were on disk already and are as they were left.\n" +
(if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") +
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
"session died of a crash, the entry is in there unless the device rebooted.\n"
"session died of a crash, the entry is in there unless the device rebooted.\n" +
(if (newest) exitReasons(context) else "")
)
if (newest && lastExitForMemory(context)) killedForMemory = true
}
if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() &&
(runtimeExpired.exists() || !beforeGuestStart) &&
@@ -593,7 +601,7 @@ object SessionArtifacts {
break
}
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
if (beforeGuestStart) return
if (beforeGuestStart) break
val scrubbed = scrubTree(record) { stopWhenSessionStarts && SessionState.running }
val marked = markScrubbed(scrubbed)
if (scrubbed.deferred) break
@@ -604,6 +612,54 @@ object SessionArtifacts {
Log.w(TAG, "could not finish $dir", e)
}
}
// Whoever finishes the folder first (the agent provider starts before the activity) leaves
// the notice for the launcher to show.
if (killedForMemory) SessionPrefs.setMemoryKillNotice(context, true)
return killedForMemory
}
/** Android's newest record for this app's main process says it was killed for memory. */
private fun lastExitForMemory(context: Context): Boolean {
if (android.os.Build.VERSION.SDK_INT < 30) return false
return runCatching {
val am = context.getSystemService(android.app.ActivityManager::class.java) ?: return false
am.getHistoricalProcessExitReasons(context.packageName, 0, 3)
.firstOrNull { it.processName == context.packageName }
?.reason == android.app.ApplicationExitInfo.REASON_LOW_MEMORY
}.getOrDefault(false)
}
private fun exitReasons(context: Context): String {
if (android.os.Build.VERSION.SDK_INT < 30) return ""
return runCatching {
val am = context.getSystemService(android.app.ActivityManager::class.java) ?: return ""
val reasons = am.getHistoricalProcessExitReasons(context.packageName, 0, 3)
if (reasons.isEmpty()) return ""
val fmt = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.US)
buildString {
append("\nAndroid's record of how this app's recent processes ended (newest first):\n")
reasons.forEach { r ->
append(" ${fmt.format(java.util.Date(r.timestamp))} ${r.processName} pid ${r.pid}: reason ${reasonName(r.reason)}, " +
"status ${r.status}, importance ${r.importance}, pss ${r.pss / 1024} MB, rss ${r.rss / 1024} MB" +
(r.description?.let { " - $it" } ?: "") + "\n")
}
}
}.getOrDefault("")
}
private fun reasonName(reason: Int): String = when (reason) {
android.app.ApplicationExitInfo.REASON_LOW_MEMORY -> "LOW_MEMORY (killed for memory)"
android.app.ApplicationExitInfo.REASON_SIGNALED -> "SIGNALED"
android.app.ApplicationExitInfo.REASON_CRASH -> "CRASH"
android.app.ApplicationExitInfo.REASON_CRASH_NATIVE -> "CRASH_NATIVE"
android.app.ApplicationExitInfo.REASON_ANR -> "ANR"
android.app.ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE -> "EXCESSIVE_RESOURCE_USAGE"
android.app.ApplicationExitInfo.REASON_USER_REQUESTED -> "USER_REQUESTED"
android.app.ApplicationExitInfo.REASON_USER_STOPPED -> "USER_STOPPED"
android.app.ApplicationExitInfo.REASON_EXIT_SELF -> "EXIT_SELF"
android.app.ApplicationExitInfo.REASON_DEPENDENCY_DIED -> "DEPENDENCY_DIED"
android.app.ApplicationExitInfo.REASON_OTHER -> "OTHER"
else -> reason.toString()
}
@Synchronized
@@ -40,10 +40,12 @@ object SessionFiles {
WinComponents.publish(context)
val files = arrayOf(
"usr/local/bin/droiddeck-game-env" to "usr/local/bin/droiddeck-game-env",
"usr/local/bin/droiddeck-diagnostic-inventory" to "usr/local/bin/droiddeck-diagnostic-inventory",
"usr/local/bin/droiddeck-wincomponents" to "usr/local/bin/droiddeck-wincomponents",
"usr/local/bin/droiddeck-msi-install" to "usr/local/bin/droiddeck-msi-install",
"usr/local/bin/droiddeck-esync" to "usr/local/bin/droiddeck-esync",
"usr/local/bin/droiddeck-steam-compat" to "usr/local/bin/droiddeck-steam-compat",
"usr/local/bin/droiddeck-steam-taskset" to "usr/local/libexec/droiddeck-steam/taskset",
"usr/local/bin/droiddeck-fex" to "usr/local/bin/droiddeck-fex",
"libblsession.so" to "usr/local/lib/libblsession.so",
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
@@ -71,6 +73,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1",
"usr/local/bin/droiddeck-steam-launch" to "usr/local/bin/droiddeck-steam-launch",
"usr/local/bin/droiddeck-desktop-games" to "usr/local/bin/droiddeck-desktop-games",
"usr/local/bin/droiddeck-desktop-programs" to "usr/local/bin/droiddeck-desktop-programs",
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
"usr/local/bin/droiddeck-downloads" to "usr/local/bin/droiddeck-downloads",
"usr/local/bin/droiddeck-root" to "usr/local/bin/droiddeck-root",
@@ -141,6 +144,8 @@ object SessionFiles {
"usr/local/lib/mangoapp/libtraceevent.so.1",
"usr/local/lib/mangoapp/libtracefs.so.1",
).map { it to it }
val xclipse = listOf("libVkLayer_droiddeck_xclipse.so", "VkLayer_droiddeck_xclipse.json")
.map { "usr/local/lib/droiddeck-xclipse/$it" }
val msitools = listOf("msiinfo", "cabextract", "7z", "7z.so", "libmsi-1.0.so.0", "libgsf-1.so.114", "libgcab-1.0.so.0")
.map { "usr/local/lib/droiddeck-msitools/$it" } +
listOf("NOTICE", "GPL-2", "GPL-3", "LGPL-2.1", "7zip-License", "7zip-unRarLicense").map { "usr/local/share/licenses/droiddeck-msitools/$it" }
@@ -164,12 +169,22 @@ object SessionFiles {
val gpuLoad = listOf(
"usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so" to "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so",
"usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_gpu_load.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_gpu_load.json",
"usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so" to "usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_vramcap.so",
"usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_vram_cap.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json",
)
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
listOf("libblsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
} + listOf("libvulkan-thunk.so", "libwebkitinput.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
// The Mali compatibility layer (tools/venus/layer, David Cimo): an implicit Vulkan layer that
// fills in the features DXVK requires and Mali lacks. Idle outside Wine and on GPUs that have them.
// Never staged on an Adreno: an implicit layer is loaded into every Vulkan program there.
val maliCompat = if (com.droiddeck.launcher.core.DeviceSupport.adreno()) emptyList() else listOf(
"usr/local/lib/droiddeck-mali/libVkLayer_droiddeck_mali_compat.so",
"usr/local/share/vulkan/implicit_layer.d/VkLayer_droiddeck_mali_compat.json",
).map { it to it }
val optional = (arrayOf(
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
"usr/local/bin/droiddeck-glprobe" to "usr/local/bin/droiddeck-glprobe",
"usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so" to "usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so",
"usr/local/lib/vkbridge/libvulkan_droidbridge.so" to "usr/local/lib/vkbridge/libvulkan_droidbridge.so",
"usr/local/share/vkbridge/droidbridge_icd.json" to "usr/local/share/vkbridge/droidbridge_icd.json",
@@ -178,7 +193,7 @@ object SessionFiles {
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
"usr/local/lib/droiddeck-dirt/ws2_32.dll" to "usr/local/lib/droiddeck-dirt/ws2_32.dll",
) + mangoapp + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
val dir = asset.substringBeforeLast('/')
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
}
@@ -11,14 +11,12 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.content.FileProvider
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.LogRedactor
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import java.util.ArrayList
object SessionLogShare {
data class Details(val sizeBytes: Long, val modifiedAt: Long)
private val main = Handler(Looper.getMainLooper())
var progress by mutableStateOf<Float?>(null)
@@ -35,86 +33,55 @@ object SessionLogShare {
}, "share-logs").start()
}
fun latest(context: Context): File? = SessionPaths.sessionFolders(context).lastOrNull()
fun latest(context: Context): File? = sessions(context).lastOrNull()
fun sessions(context: Context): List<File> {
val current = SessionPaths.current()?.takeIf { it.isDirectory && SessionPaths.isSessionFolder(it) }
return (SessionPaths.sessionFolders(context) + listOfNotNull(current))
.distinctBy { it.absoluteFile.toPath().normalize().toString() }
.sortedWith(SessionPaths.chronological)
}
fun zipFolder(context: Context, folder: File, onProgress: ((Float) -> Unit)? = null): File? {
if (!folder.isDirectory) return null
val files = folder.walkTopDown().filter { it.isFile }
.filterNot { it.parentFile?.name == "steam" && it.length() > STEAM_LOG_MAX_BYTES }.toList()
if (files.isEmpty()) return null
val out = shareDir(context).apply { deleteRecursively(); mkdirs() }
val zip = File(out, "DroidDeck-${folder.name}.zip")
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
val live = liveSteamLogs(context, folder)
val logs = LinuxRuntime.logDir(context)
val stores = recent(File(logs, STORES_DIR))
val tools = recent(File(logs, SessionPaths.TOOLS_DIR))
val battleNet = battleNetLogs(context)
val total = (files + live + stores + tools + battleNet.map { it.second }).sumOf { it.length() }.coerceAtLeast(1L)
var done = 0L
var shown = -1
fun advance(f: File) {
done += f.length()
val percent = (done * 100 / total).toInt()
if (percent != shown) { shown = percent; onProgress?.invoke(percent / 100f) }
fun details(folder: File): Details {
var size = 0L
var modified = folder.lastModified()
folder.walkTopDown().filter { it.isFile }.forEach { file ->
size += file.length()
modified = maxOf(modified, file.lastModified())
}
ZipOutputStream(zip.outputStream().buffered()).use { z ->
files.forEach { f -> addEntry(z, folder.name + "/" + f.relativeTo(folder).invariantSeparatorsPath, f); advance(f) }
live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f); advance(f) }
stores.forEach { f -> addEntry(z, "$STORES_DIR/" + f.name, f); advance(f) }
tools.forEach { f -> addEntry(z, SessionPaths.TOOLS_DIR + "/" + f.name, f); advance(f) }
battleNet.forEach { (name, f) -> addEntry(z, "$BATTLENET_DIR/$name", f); advance(f) }
}
return zip
return Details(size, modified)
}
private fun addEntry(z: ZipOutputStream, name: String, f: File) {
z.putNextEntry(ZipEntry(name))
val w = z.bufferedWriter()
LogRedactor.scrubForShare(f, w)
w.flush()
z.closeEntry()
fun deleteSession(context: Context, folder: File): Boolean {
if (runCatching { SessionPaths.current()?.canonicalFile == folder.canonicalFile }.getOrDefault(false)) return false
val knownSession = runCatching { folder.canonicalFile }.getOrNull() in sessions(context).mapNotNull { runCatching { it.canonicalFile }.getOrNull() }
return knownSession && folder.isDirectory && folder.deleteRecursively()
}
private fun liveSteamLogs(context: Context, folder: File): List<File> {
if (folder != SessionPaths.current() || File(folder, "steam").exists()) return emptyList()
val logs = File(SessionPrefs.activeSteamRoot(context), "logs")
return logs.listFiles()?.filter { it.isFile && it.length() <= STEAM_LOG_MAX_BYTES }.orEmpty()
fun prepareEnhanced(context: Context, folder: () -> File?, done: (List<File>) -> Unit) {
if (progress != null) return
progress = 0f
Thread({
val zips = runCatching {
folder()?.let { dir ->
EnhancedSessionLogShare.create(context, dir, onProgress = { p ->
main.post { if (progress != null) progress = p }
})
}.orEmpty()
}.onFailure { Log.w("SessionLogShare", "could not package enhanced diagnostics", it) }
.getOrDefault(emptyList())
main.post { progress = null; done(zips) }
}, "share-diagnostics").start()
}
private const val STEAM_LOG_MAX_BYTES = 8L * 1024 * 1024
fun zipFolder(context: Context, folder: File, out: File = shareDir(context), onProgress: ((Float) -> Unit)? = null): File? {
return EnhancedSessionLogShare.createLegacy(context, folder, onProgress, out)
}
const val STORES_DIR = "stores"
private const val RECENT_DAYS = 7
private fun shareDir(context: Context): File = File(context.cacheDir, "share")
private const val BATTLENET_DIR = "battlenet"
private fun battleNetLogs(context: Context): List<Pair<String, File>> {
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
val data = File(drive, "ProgramData/Battle.net")
fun logsUnder(dir: File, prefix: String) = dir.listFiles { f -> f.isDirectory && f.name.startsWith(prefix) }.orEmpty().map { File(it, "Logs") }
return newest("droiddeck", listOf(File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet")), 2, setOf("battlenet.log", "spawned.log")) +
newest("client", listOf(File(drive, "users/steamuser/AppData/Local/Battle.net/Logs")), 6) +
newest("agent", listOf(File(data, "Agent/Logs")) + logsUnder(File(data, "Agent"), "Agent."), 10, byDir = true) +
newest("setup", logsUnder(File(data, "Setup"), ""), 3, byDir = true)
}
private fun newest(folder: String, dirs: List<File>, count: Int, names: Set<String>? = null, byDir: Boolean = false): List<Pair<String, File>> {
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
return dirs.flatMap { dir ->
dir.listFiles { f -> f.isFile && f.name.endsWith(".log") && (names == null || f.name in names) && f.lastModified() >= since && f.length() <= STEAM_LOG_MAX_BYTES }.orEmpty().toList()
}.sortedByDescending { it.lastModified() }.take(count).map { f ->
(if (byDir) "$folder/${f.parentFile?.parentFile?.name}/${f.name}" else "$folder/${f.name}") to f
}
}
private fun recent(dir: File): List<File> {
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
return dir.listFiles { f -> f.isFile && f.lastModified() >= since }?.sortedBy { it.name }.orEmpty()
}
internal fun shareDir(context: Context): File = File(context.cacheDir, "share")
fun clear(context: Context) {
shareDir(context).deleteRecursively()
@@ -131,4 +98,19 @@ object SessionLogShare {
send.clipData = ClipData.newRawUri(zip.name, uri)
return Intent.createChooser(send, context.getString(R.string.logshare_chooser)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
fun shareEnhancedIntent(context: Context, zips: List<File>): Intent {
require(zips.isNotEmpty())
val uris = ArrayList(zips.map { FileProvider.getUriForFile(context, context.packageName + ".logs", it) })
val send = Intent(Intent.ACTION_SEND_MULTIPLE)
.setType("application/zip")
.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)
.putExtra(Intent.EXTRA_SUBJECT, zips.first().name.substringBeforeLast('-'))
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
send.clipData = ClipData.newUri(context.contentResolver, zips.first().name, uris.first()).also { clip ->
for (i in 1 until uris.size) clip.addItem(ClipData.Item(uris[i]))
}
return Intent.createChooser(send, context.getString(R.string.logshare_chooser))
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
}
@@ -26,7 +26,8 @@ object SessionPaths {
@Synchronized
fun beginOrCurrent(context: Context, label: String? = null): File {
dir?.let { if (it.isDirectory) return it }
val parent = if (SessionPrefs.logsEnabled(context)) SessionFiles.logDirectory(context)
val enhanced = EnhancedDiagnostics.isArmed(context)
val parent = if (SessionPrefs.logsEnabled(context) || enhanced) SessionFiles.logDirectory(context)
else File(context.cacheDir, "session-logs")
val day = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date())
val last = parent.listFiles()?.mapNotNull { f ->
@@ -36,9 +37,13 @@ object SessionPaths {
var number = last + 1
var made = File(parent, "$day-${"%02d".format(Locale.US, number)}-$what")
while (made.exists()) made = File(parent, "$day-${"%02d".format(Locale.US, ++number)}-$what")
EnhancedDiagnostics.clearRecordFor(context, made)
if (!made.isDirectory && !made.mkdirs()) Log.e(TAG, "could not create $made")
dir = made
Log.i(TAG, "session logs: $made" + if (SessionPrefs.logsEnabled(context)) "" else " (logs off: discarded at the end)")
if (enhanced && !EnhancedDiagnostics.consumeInto(context, made)) {
Log.e(TAG, "could not activate enhanced diagnostics for $made")
}
Log.i(TAG, "session logs: $made" + if (parent == SessionFiles.logDirectory(context)) "" else " (logs off: discarded at the end)")
return made
}
@@ -8,6 +8,8 @@ import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.gpu.Cardboard
import com.droiddeck.launcher.gpu.ScreenEffects
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.gpu.TurnipDriver
import org.json.JSONObject
import java.io.File
@@ -504,6 +506,17 @@ object SessionPrefs {
p.edit().putString("gpuDriverMode", if (chosen) GPU_DRIVERS_MANUAL else GPU_DRIVERS_AUTO).apply()
}
@JvmStatic
fun ensurePowerVrAutoDrivers(context: Context) {
if (com.droiddeck.launcher.core.DeviceSupport.openDriverActive(context)) return
ensurePowerVrAutoDrivers(context, SystemVulkanDriver.isPowerVr())
}
internal fun ensurePowerVrAutoDrivers(context: Context, powerVr: Boolean) {
if (!powerVr || gpuDriverMode(context) != GPU_DRIVERS_AUTO) return
prefs(context).edit().putString("linuxDriver", "").putString("androidDriver", TurnipDriver.AUTO).apply()
}
fun gpuAutoInstalled(context: Context): Set<String> =
prefs(context).getStringSet("gpuAutoInstalled", emptySet()).orEmpty()
@@ -775,8 +788,62 @@ object SessionPrefs {
@JvmStatic
fun vkBridge(context: Context): Boolean = prefs(context).getBoolean("vkBridge", com.droiddeck.launcher.core.DeviceSupport.mali())
fun venus(context: Context): Boolean = prefs(context).getBoolean("venus", false)
fun hostVulkanApi(context: Context): String = prefs(context).getString("hostVulkanApi", "").orEmpty()
fun setHostVulkanApi(context: Context, api: String) {
if (api != hostVulkanApi(context)) prefs(context).edit().putString("hostVulkanApi", api).apply()
}
fun bridgeFellBack(context: Context): Boolean = prefs(context).getBoolean("bridgeFellBack", false)
fun bridgeFellBackForMemory(context: Context): Boolean = prefs(context).getString("bridgeFallbackReason", "") == "memory"
fun setBridgeFellBack(context: Context, on: Boolean, reason: String = "") {
prefs(context).edit().putBoolean("bridgeFellBack", on).putString("bridgeFallbackReason", if (on) reason else "").apply()
}
fun steamGpuCompositing(context: Context): Boolean {
if (!steamGpuCompositingAllowed()) {
if (prefs(context).getBoolean("steamGpuCompositing", false))
prefs(context).edit().putBoolean("steamGpuCompositing", false).apply()
return false
}
return prefs(context).getBoolean("steamGpuCompositing", false)
}
fun steamGpuCompositingAllowed(): Boolean =
!com.droiddeck.launcher.core.DeviceSupport.adreno() && !com.droiddeck.launcher.core.DeviceSupport.mali()
fun setSteamGpuCompositing(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("steamGpuCompositing", on && steamGpuCompositingAllowed()).apply()
}
fun takeMemoryKillNotice(context: Context): Boolean {
val on = prefs(context).getBoolean("memoryKillNotice", false)
if (on) prefs(context).edit().putBoolean("memoryKillNotice", false).apply()
return on
}
fun setMemoryKillNotice(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("memoryKillNotice", on).apply()
}
fun maliFallbackByAuto(context: Context): String = prefs(context).getString("maliFallbackByAuto", "").orEmpty()
fun maliFallbackKnown(context: Context): Boolean = prefs(context).contains("maliFallbackByAuto")
fun setMaliFallbackByAuto(context: Context, route: String) {
prefs(context).edit().putString("maliFallbackByAuto", route).apply()
}
fun setVenus(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("venus", on).apply()
}
fun setVkBridge(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("vkBridge", on).apply()
prefs(context).edit().putBoolean("vkBridge", on).putBoolean("bridgeFellBack", false).apply()
}
@JvmStatic
@@ -786,6 +853,7 @@ object SessionPrefs {
prefs(context).edit().putBoolean("bridgeProtonDxvk", on).apply()
}
@JvmStatic
fun vkBridgeSafe(context: Context): Boolean = prefs(context).getBoolean("vkBridgeSafe", true)
fun setVkBridgeSafe(context: Context, on: Boolean) {
@@ -824,7 +892,7 @@ object SessionPrefs {
key = "logs",
oldValue = logsEnabled(context),
newValue = on,
newEffective = on && gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context),
newEffective = gameDebugLogsEffective(context, on, gameDebugLogsEnabled(context)),
)
}
@@ -837,7 +905,7 @@ object SessionPrefs {
key = "gameDebugLogsEnabled",
oldValue = gameDebugLogsEnabled(context),
newValue = on,
newEffective = logsEnabled(context) && on && SessionPaths.currentSessionLogsRetained(context),
newEffective = gameDebugLogsEffective(context, logsEnabled(context), on),
)
}
@@ -850,8 +918,7 @@ object SessionPrefs {
): Boolean {
if (oldValue == newValue) return true
val saved = prefs(context)
val oldEffective = logsEnabled(context) && gameDebugLogsEnabled(context) &&
SessionPaths.currentSessionLogsRetained(context)
val oldEffective = gameDebugLogsEffective(context)
fun publish(value: Boolean) = GameEnvironmentStore.publish(context, gameDebugLogsOverride = value)
if (oldEffective == newEffective) {
if (saved.edit().putBoolean(key, newValue).commit()) return true
@@ -887,6 +954,20 @@ object SessionPrefs {
}
}
fun detailedGraphicsLogs(context: Context): Boolean =
prefs(context).getBoolean("detailedGraphicsLogs", false)
fun setDetailedGraphicsLogs(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("detailedGraphicsLogs", on).apply()
}
internal fun gameDebugLogsEffective(
context: Context,
logs: Boolean = logsEnabled(context),
gameLogs: Boolean = gameDebugLogsEnabled(context),
): Boolean = EnhancedDiagnostics.isCurrentSessionActive(context) ||
(logs && gameLogs && SessionPaths.currentSessionLogsRetained(context))
fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false)
fun setBattleNetNoSteamSet(context: Context) { prefs(context).edit().putBoolean("battleNetNoSteamSet", true).apply() }
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import android.app.Notification
import android.app.NotificationChannel
@@ -405,6 +406,7 @@ class SessionService : Service() {
private fun collectSessionArtifacts(dir: File, steamArch: String?) {
SessionLogCapture.stopFor(dir)
try {
GraphicsReport.finish(dir)
SessionArtifacts.collect(this, dir, "session stopped", steamArch)
} finally {
SessionPaths.release(this, dir)
@@ -424,6 +426,21 @@ class SessionService : Service() {
return lines
}
/** Whether a kernel release ("6.1.157-android14-11") is older than [major].[minor]; false if unreadable. */
internal fun kernelBefore(release: String, major: Int, minor: Int): Boolean {
val m = Regex("""^(\d+)\.(\d+)""").find(release) ?: return false
val (a, b) = m.destructured
return a.toInt() < major || (a.toInt() == major && b.toInt() < minor)
}
/** Whether the newest finished session's log shows Xwayland itself crashing. */
private fun lastXwaylandCrashed(): Boolean = runCatching {
val last = SessionPaths.sessionFolders(this).filter { it != SessionPaths.current() }.lastOrNull() ?: return false
val log = File(last, "session.log").takeIf { it.isFile } ?: return false
log.useLines { lines -> lines.any { it.contains("(EE) Segmentation fault") } } &&
log.useLines { lines -> lines.any { it.contains("X11 I/O error") || it.contains("Xwayland", ignoreCase = true) } }
}.getOrDefault(false)
private fun tuDebugOverride(): String? = File(Environment.getExternalStorageDirectory(), TU_DEBUG_SWITCH)
.takeIf { it.isFile }?.let { FileUtils.readString(it)?.trim() }?.takeIf { it.isNotEmpty() }
@@ -435,6 +452,13 @@ class SessionService : Service() {
private fun runSession(gen: Int) {
SessionPrefs.ensurePowerVrAutoDrivers(this)
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) {
com.droiddeck.launcher.gpu.VulkanInfo.query()["api"]?.let { SessionPrefs.setHostVulkanApi(this, it) }
if (SessionPrefs.venus(this)) VenusComponent.hostVulkanTooOld(this)?.let {
Log.w(TAG, "venus: off for this session - the phone's driver reports Vulkan $it and gamescope needs 1.2 or newer; the session uses the PanVK pair or the bridge")
}
}
SessionTerminal.clear()
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)
try {
@@ -452,10 +476,19 @@ class SessionService : Service() {
val stillStarting = { gen == sessionGen && SessionState.running }
val prootPack = LinuxRuntime.patchedProot(this) || AddonPack.PROOT.await(this, stillStarting)
val directAudioPack = AddonPack.DIRECTAUDIO.await(this, stillStarting)
val systemVulkan = SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(this))
val powerVrPack = !systemVulkan || (stillStarting() && AddonPack.POWERVR.await(this, stillStarting))
if (!stillStarting()) {
Log.i(TAG, "session stopped while add-on packs were downloading")
return
}
if (!powerVrPack) {
val message = getString(R.string.session_powervr_missing)
Log.e(TAG, "powervr pack unavailable; the system graphics runtime cannot be prepared")
failSession(gen, "POWERVR_MISSING", message, -1)
stopSession(-1, gen)
return
}
if (!directAudioPack) {
Log.w(TAG, "directaudio pack unavailable; game audio drivers will not be staged")
mainHandler.post {
@@ -476,7 +509,21 @@ class SessionService : Service() {
val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
.onFailure { Log.w(TAG, "agent environment skipped", it) }
.getOrDefault(emptyList())
SessionFiles.stage(this, root, startsSession = true)
try {
if (systemVulkan) {
SystemVulkanDriver.prepare(this)
if (!stillStarting()) {
Log.i(TAG, "session stopped while the system graphics runtime was unpacking")
return
}
pruneSystemVulkanRuntime()
}
SessionFiles.stage(this, root, startsSession = true)
} catch (error: Exception) {
Log.e(TAG, "Could not prepare the session graphics runtime", error)
stopSession(-1, gen)
return
}
SessionArtifacts.awaitCollections()
SessionArtifacts.finishAbandoned(this, beforeGuestStart = true)
VacDiagnostics.arm(this)
@@ -512,18 +559,32 @@ class SessionService : Service() {
.onSuccess { if (it != null) Log.i(TAG, it) }
.onFailure { Log.w(TAG, "forced components", it) }
}
addClientEnvironment(guest, steamHere, agentEnvironment)
try {
addClientEnvironment(guest, steamHere, agentEnvironment)
} catch (e: IllegalStateException) {
Log.e(TAG, "Could not resolve the selected Linux Vulkan driver", e)
failSession(gen, "VULKAN_DRIVER_UNAVAILABLE", e.message ?: "Selected Linux Vulkan driver is unavailable", -1)
stopSession(-1, gen)
return
}
if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)
val fastPathAt = guest.size
val pulse = startAudio(guest, sessionDir, directAudioPack)
startVkBridge(guest, sessionDir)
if (VenusComponent.wanted(this)) {
components.add(VenusComponent(File(sessionDir, "venus.log")).also { it.attach(this) })
}
if (steamHere) {
val encoder = VideoEncodeBridge(File(filesDir, "venc/venc.sock"))
encoder.attach(this)
components.add(encoder)
guest.add("BL_VENC_SOCKET=" + encoder.socket.absolutePath)
}
startVkBridge(guest, sessionDir)
com.droiddeck.launcher.gpu.ClockLogComponent(File(sessionDir, "clocks.log")).let {
it.attach(this)
components.add(it)
}
guest.add("BL_WIDTH=" + size.first)
guest.add("BL_HEIGHT=" + size.second)
@@ -540,6 +601,7 @@ class SessionService : Service() {
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
guest.add("BL_LOG=" + sessionLog.path)
guest.add("BL_DEBUG_DIR=" + sessionDir.path)
if (EnhancedDiagnostics.isActive(this, sessionDir)) guest.add("DROIDDECK_ENHANCED_DIAGNOSTICS=1")
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
@@ -569,6 +631,10 @@ class SessionService : Service() {
guest.add("BL_LAUNCH_DIR=" + sessionRoot.path)
GameStorage.effective(this)?.let { guest.add("BL_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("BL_STEAM_UI=desktop")
// Detailed graphics logs: per-game logs and the guest's Vulkan summary (a GPU that is not
// an Adreno, or Setup's switch), and graphics-report.txt for every session.
if (GraphicsReport.detailed(this)) guest.add("BL_GAME_LOGS=1")
GraphicsReport.begin(this, sessionDir, guest)
val shellGuest = ArrayList(guest).apply {
add("SHELL=/bin/bash")
add("TERM=xterm-256color")
@@ -668,7 +734,14 @@ class SessionService : Service() {
if (gen == sessionGen) components.clear()
return
}
components.forEach { it.start() }
try {
components.forEach { it.start() }
} catch (e: Exception) {
Log.e(TAG, "Could not start the session components", e)
failSession(gen, "COMPONENT_START_FAILED", e.message ?: "Session component could not be started", -1)
stopSession(-1, gen)
return
}
val line = command.joinToString(" ") {
it.replace("\\", "\\\\").replace(" ", "\\ ")
@@ -768,6 +841,7 @@ class SessionService : Service() {
SessionState.sessionId = sessionDir.name
SessionState.eventsFile = File(sessionDir, "events.jsonl")
SessionEvents.record("session.logs_ready", mapOf("logDir" to sessionDir.path))
if (EnhancedDiagnostics.isActive(this, sessionDir)) SessionEvents.record("diagnostics.enhanced", mapOf("schema" to 1))
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
NetworkReport.write(this, File(sessionDir, "network.txt"))
SessionLogCapture.start(File(sessionDir, "app.log"))
@@ -810,7 +884,12 @@ 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) }
val venus = VenusComponent.wanted(this)
if (venus) {
VenusComponent.guestEnv(this).forEach { guest.add(it) }
} else {
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
}
val linuxDriverId = SessionPrefs.linuxDriver(this)
SessionState.runtimeDriver = linuxDriverId
com.droiddeck.launcher.gpu.AutoDriverTrial.sessionStarting(
@@ -819,11 +898,39 @@ class SessionService : Service() {
?: SessionPrefs.androidDriver(this),
linuxDriverId,
)
if (!com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)) LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
val bridge = com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)
if (!bridge && !venus && SystemVulkanDriver.usesDefault(linuxDriverId)) {
SystemVulkanDriver.addEnvironment(this, guest)
}
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) {
guest.add("XWAYLAND_NO_GLAMOR=1")
Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)")
}
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) guest.add("BL_RAISE_NOFILE=1")
if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) {
val kernel = System.getProperty("os.version").orEmpty()
val old = kernelBefore(kernel, 6, 6)
val maliNode = LinuxRuntime.gpuStandIn(this) == LinuxRuntime.MALI_DEVICE
if (old || maliNode) {
guest.add("GAMESCOPE_DISABLE_EXPLICIT_SYNC=1")
Log.i(TAG, "gamescope: explicit sync off (" + (if (old) "kernel $kernel has no SYNCOBJ_EVENTFD" else "Mali stand-in node has no syncobjs") + ")")
}
}
if (!bridge && com.droiddeck.launcher.core.DeviceSupport.openDriverActive(this)) {
if (SessionPrefs.steamGpuCompositing(this)) {
Log.i(TAG, "steam: GPU web compositing (Setup's \"Steam interface: GPU drawing\")")
} else {
guest.add("BL_STEAM_SOFT_COMPOSITING=1")
Log.i(TAG, "steam: software web compositing for the open driver pair (GPU raster kept)")
}
guest.add("BL_OPEN_DRIVER=1")
LinuxRuntime.gpuStandIn(this)?.takeIf { it == LinuxRuntime.MALI_DEVICE }?.let { guest.add("BL_DRM_STANDIN=$it") }
}
val tuOverride = tuDebugOverride()
val tuDriver = sysmemDriver(linuxDriverId)
(tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") }
if (!venus && com.droiddeck.launcher.core.DeviceSupport.adreno()) (tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") }
if (SessionPrefs.zinkLazy(this)) {
guest.add("ZINK_DESCRIPTORS=lazy")
guest.add("ZINK_DEBUG=compact")
@@ -872,20 +979,17 @@ class SessionService : Service() {
.takeIf { it.isNotEmpty() }?.let { guest.add("BL_GAME_CPUS=$it") }
}
private fun noSteamGame(): Boolean =
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
private fun startVkBridge(guest: MutableList<String>, sessionDir: File) {
if (!com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)) return
val socket = File(filesDir, "vkbridge/server.sock")
val bridge = com.droiddeck.launcher.gpu.VkBridgeComponent(socket, File(sessionDir, "vkbridge-server.log"))
bridge.attach(this)
components.add(bridge)
com.droiddeck.launcher.gpu.ClockLogComponent(File(sessionDir, "vkbridge-clocks.log")).let {
it.attach(this)
components.add(it)
}
guest.add("BL_VKBRIDGE=1")
if (SessionPrefs.steamGpuCompositing(this)) guest.add("BL_STEAM_GPU_COMPOSITING=1")
SessionPrefs.linuxDriver(this).takeIf { it.isNotEmpty() }
?.let { runCatching { LinuxVulkanDriver.resolveIcdPath(this, it) }.getOrNull() }
?.let { guest.add("BL_VKBRIDGE_FALLBACK_ICD=$it") }
guest.add("VKBRIDGE_SOCKET=" + socket.path)
guest.add("VKBRIDGE_CLIENT_LOG=" + File(sessionDir, "vkbridge-client.log").path)
guest.add("VKBRIDGE_MODE=" + SessionPrefs.vkBridgeMode(this))
@@ -895,6 +999,8 @@ class SessionService : Service() {
}
Log.i(TAG, "vkbridge: on (${com.droiddeck.launcher.core.DeviceSupport.gpuName(this)}, ${SessionPrefs.vkBridgeMode(this)} mode), socket $socket")
}
private fun noSteamGame(): Boolean =
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
private fun startAudio(guest: MutableList<String>, sessionDir: File, directAudioPack: Boolean): PulseAudioComponent {
val wantsDirectAudio = directAudioPack &&
@@ -1832,6 +1938,12 @@ class SessionService : Service() {
}.onFailure { Log.w(TAG, "could not request Steam wake", it) }
}
/** Background-only: preserve old runtimes until all earlier guest processes are gone. */
private fun pruneSystemVulkanRuntime() {
runCatching { SystemVulkanDriver.pruneUnused(this, !OrphanReaper.hasOtherProcesses()) }
.onFailure { Log.w(TAG, "could not prune unused system Vulkan runtimes", it) }
}
private fun finishSessionStop(status: Int, stoppedGen: Int, afterStopped: () -> Unit = {}) {
mainHandler.post {
try {
@@ -1971,10 +2083,12 @@ class SessionService : Service() {
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
killGuestLeftovers()
pruneSystemVulkanRuntime()
finishSessionStop(status, stoppedGen, collectEnded)
if (launcherEnded) importLauncherGames()
}, "session-teardown").start()
} else {
Thread({ pruneSystemVulkanRuntime() }, "system-vulkan-prune").start()
Thread({
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
finishSessionStop(status, stoppedGen, collectEnded)
@@ -23,7 +23,7 @@ object SettingsReset {
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "storageDiagnostics",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics",
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
"bootMovieApplyNext", "bootMovieSteamSeen",
@@ -0,0 +1,131 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.Process
import android.util.Log
import com.droiddeck.launcher.core.DeviceSupport
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.core.SessionPart
import java.io.File
import java.io.PrintWriter
/**
* Vulkan for the session on a Mali, through Venus (the "Mali (Venus)" route; by David Cimo,
* DavidCimo/droiddeck-mali, ported to this branch).
*
* The guest's processes are glibc and cannot load the vendor's bionic driver. Instead they load
* Mesa's Venus ICD (libvulkan_virtio.so), which serializes every Vulkan call over a unix socket to
* virglrenderer's vtest server. The server runs here, on the Android side, and replays the calls
* on the device's own Vulkan driver. Both ends of the socket are under the app's files directory,
* which the session binds at its own path, so the same path works inside and out.
*/
class VenusComponent(private val logFile: File?) : SessionPart() {
@Volatile private var pid = -1
override fun start() {
val context = app()
stageIcd(context)
val libDir = context.applicationInfo.nativeLibraryDir
val socket = socket(context)
socket.delete()
val env = arrayOf(
"LD_LIBRARY_PATH=$libDir",
// vtest forks a render server per client; this is where its executable is.
"RENDER_SERVER_EXEC_PATH=$libDir/libvirgl_render_server.so",
"TMPDIR=" + context.cacheDir.path,
)
val command = "$libDir/libvirgl_test_server.so --venus --no-virgl --socket-path " + socket.path
val out = logFile?.let { runCatching { PrintWriter(java.io.FileWriter(it, true)) }.getOrNull() }
pid = HostProcess.start(command, env, context.filesDir, { status ->
Log.w(TAG, "vtest server exited: $status")
out?.let { synchronized(it) { it.println("vtest server exited: $status"); it.flush() } }
}, { line ->
Log.i(TAG, line)
out?.let { synchronized(it) { it.println(line); it.flush() } }
})
Log.i(TAG, "vtest server pid $pid on $socket")
}
override fun stop() {
if (pid > 1) Process.killProcess(pid)
pid = -1
}
companion object {
private const val TAG = "Venus"
private const val ASSET = "venus/libvulkan_virtio.so"
private const val DIR = "venus"
private const val LIB = "libvulkan_virtio.so"
private const val ICD = "virtio_icd.json"
/**
* The selection rule: Venus when Setup's "Mali (Venus)" is on, on a GPU that is neither an
* Adreno nor one the system-driver route covers (PowerVR, Xclipse), and the apk carries it.
* It then replaces the Mali bridge and any open driver pair for the session.
*/
@JvmStatic
fun wanted(context: Context): Boolean =
!DeviceSupport.adreno() && !com.droiddeck.launcher.gpu.SystemVulkanDriver.isAvailable() &&
SessionPrefs.venus(context) && available(context) && hostVulkanTooOld(context) == null
/** The phone driver's Vulkan version when it is below 1.2: gamescope skips such a device, so Venus cannot run. */
@JvmStatic
fun hostVulkanTooOld(context: Context): String? {
val api = com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull()?.get("api") ?: SessionPrefs.hostVulkanApi(context)
val parts = api.split('.').mapNotNull { it.trim().toIntOrNull() }
if (parts.size < 2) return null
return api.takeIf { parts[0] < 1 || (parts[0] == 1 && parts[1] < 2) }
}
/** Whether this apk carries the Venus component (tools/venus, venus.tzst). */
@JvmStatic
fun available(context: Context): Boolean = runCatching {
context.assets.list(DIR)?.contains(LIB) == true &&
File(context.applicationInfo.nativeLibraryDir, "libvirgl_test_server.so").isFile
}.getOrDefault(false)
@JvmStatic
fun socket(context: Context): File = File(File(context.filesDir, DIR), "vtest.sock")
/** What the guest needs to find the ICD and the server. */
@JvmStatic
fun guestEnv(context: Context): List<String> {
val dir = File(context.filesDir, DIR)
return listOf(
"VK_ICD_FILENAMES=" + File(dir, ICD).path,
"VN_DEBUG=vtest",
"VTEST_SOCKET_NAME=" + socket(context).path,
// Xwayland has no DRI3 without a DRM node, so swapchains present through shared memory.
"MESA_VK_WSI_DEBUG=sw",
// The Mali compatibility layer in every process but gamescope, not only Wine: Zink
// (Steam's GL, Xwayland's glamor) requires robustness2's nullDescriptor, which the
// layer stands in for. The session script checks it and falls back to llvmpipe.
"DROIDDECK_MALI_COMPAT=1",
"BL_VENUS=1",
// gamescope's composite layout without immutable YCbCr samplers from the start
// (patch 0930): a Mali-G615 refused every composite pipeline with them, and testing
// that through Venus took the render server down.
"GAMESCOPE_NO_YCBCR_SAMPLERS=1",
)
}
/** Copies the ICD out of the APK when it changed, and writes its manifest with an absolute path. */
private fun stageIcd(context: Context) {
val dir = File(context.filesDir, DIR).apply { mkdirs() }
val lib = File(dir, LIB)
// Copied again after every app update: the asset is compressed, so its size is unknown up front.
val installed = context.packageManager.getPackageInfo(context.packageName, 0).lastUpdateTime
if (!lib.isFile || lib.lastModified() < installed) {
val tmp = File(dir, "$LIB.tmp")
context.assets.open(ASSET).use { input -> tmp.outputStream().use { input.copyTo(it) } }
if (!tmp.renameTo(lib)) throw java.io.IOException("could not move the Venus ICD into place")
Log.i(TAG, "staged $lib (${lib.length()} bytes)")
}
if (!FileUtils.writeString(
File(dir, ICD),
"""{"file_format_version":"1.0.1","ICD":{"library_path":"${lib.path}","api_version":"1.4.354"}}""",
)) throw java.io.IOException("could not write the Venus ICD manifest")
}
}
}
@@ -38,6 +38,7 @@ object WinComponents {
private const val MSI_CACHE = "$STORE/.packages"
private val PROTON_PROVIDES = setOf("gecko", "mono", "cjkfonts", "powershell", "VulkanRT")
private val NESTED_KEYS = setOf("url", "file_name", "file_checksum", "file_size")
private val installLock = Any()
fun validId(id: String): Boolean = ID.matches(id) && ".." !in id
@@ -61,7 +62,7 @@ object WinComponents {
class Component(
val name: String, val description: String, val provider: String, val status: String,
val dependencies: List<String>, val steps: List<Step>,
val snapshot: String = "",
val snapshot: String = "", val revision: Int = 0,
)
enum class Support { READY, NEEDS_INSTALLER, UNSUPPORTED }
@@ -127,7 +128,7 @@ object WinComponents {
name, o.optString("description"), o.optString("provider"), o.optString("status"),
(0 until deps.length()).map { deps.getString(it) }.filter { validId(it) },
(0 until steps.length()).map { steps.getJSONObject(it).let { s -> Step(s.optString("action"), s) } },
o.optString("snapshot"),
o.optString("snapshot"), o.optInt("revision", 0).coerceAtLeast(0),
)
}
if (listed.any { it.name == VCREDIST_ARM64 }) listed else listed + builtInArm64Runtime()
@@ -170,15 +171,31 @@ object WinComponents {
else -> true
}
fun installed(context: Context, id: String): String? = runCatching {
JSONObject(File(LinuxRuntime.rootDir(context), "$STORE/$id/component.json").readText()).optString("version", "?")
internal fun installedVersion(directory: File, revision: Int): String? = runCatching {
val meta = JSONObject(File(directory, "component.json").readText())
if (meta.optInt("revision", 0) < revision) null else meta.optString("version", "?")
}.getOrNull()
fun installedIds(context: Context): List<String> =
File(LinuxRuntime.rootDir(context), STORE).listFiles { f -> f.isDirectory && validId(f.name) }
.orEmpty().map { it.name }.filter { installed(context, it) != null }.sorted()
fun installed(context: Context, id: String): String? = installedVersion(
File(LinuxRuntime.rootDir(context), "$STORE/$id"), cached(context)?.firstOrNull { it.name == id }?.revision ?: 0,
)
fun install(context: Context, c: Component, all: Map<String, Component>, onProgress: (Progress) -> Unit): String? {
internal fun downloadedIds(store: File): List<String> =
store.listFiles { f -> f.isDirectory && validId(f.name) }.orEmpty()
.filter { installedVersion(it, 0) != null }.map { it.name }.sorted()
fun downloadedIds(context: Context): List<String> = downloadedIds(File(LinuxRuntime.rootDir(context), STORE))
fun installedIds(context: Context): List<String> {
val revisions = cached(context).orEmpty().associate { it.name to it.revision }
return File(LinuxRuntime.rootDir(context), STORE).listFiles { f -> f.isDirectory && validId(f.name) }
.orEmpty().filter { installedVersion(it, revisions[it.name] ?: 0) != null }.map { it.name }.sorted()
}
fun install(context: Context, c: Component, all: Map<String, Component>, onProgress: (Progress) -> Unit): String? =
synchronized(installLock) { installLocked(context, c, all, onProgress) }
private fun installLocked(context: Context, c: Component, all: Map<String, Component>, onProgress: (Progress) -> Unit): String? {
if (support(c, all) != Support.READY) return "${c.name} cannot be installed here yet"
val order = ArrayList<Component>()
fun visit(x: Component, depth: Int) {
@@ -353,7 +370,7 @@ object WinComponents {
val version = msi?.optString("version")?.takeIf { it.isNotEmpty() }
?: Regex("""\b(\d+\.\d+(\.\d+)*)\b""").find(c.description)?.value ?: "catalog"
val meta = JSONObject()
.put("id", c.name).put("version", version)
.put("id", c.name).put("version", version).put("revision", c.revision)
.put("overrides", JSONArray(overrides.distinct()))
.put("requires", JSONArray(c.dependencies))
msi?.let { meta.put("kind", it.optString("kind", "msi")).put("product", it.optString("product")).put("notes", it.optJSONArray("notes") ?: JSONArray()) }
@@ -556,8 +573,7 @@ object WinComponents {
matches.forEach { f -> f.copyTo(File(dest, f.name.lowercase()), overwrite = true) }
}
@Synchronized
fun uninstall(context: Context, id: String) {
fun uninstall(context: Context, id: String) = synchronized(installLock) {
require(validId(id))
FileUtils.delete(File(LinuxRuntime.rootDir(context), "$STORE/$id"))
save(context, selections(context).mapValues { (_, sel) -> Selection(sel.auto - id, sel.user - id) })
@@ -52,6 +52,19 @@ object CloudPlan {
return Plan(transfer, conflicts, same)
}
/**
* Files to send. GOG objects uploaded by older builds are raw while their cloud hash is still the
* local raw MD5, so they appear in [Plan.same]; resending them stores the gzip form Galaxy reads.
* A forced GOG upload is the manual repair path and sends every local file, including unchanged
* ones the service gives no hash for; once rewritten the cloud hash is the compressed MD5.
*/
fun upSend(plan: Plan, force: Boolean, repairRawGog: Boolean, allLocal: Collection<String> = emptyList()): List<String> {
if (force) {
return (plan.transfer + plan.conflicts + if (repairRawGog) allLocal else emptyList()).distinct()
}
return (plan.transfer + if (repairRawGog) plan.same else emptyList()).distinct()
}
fun toJson(baseline: Map<String, Entry>): String = JSONObject().apply {
for ((k, e) in baseline) put(k, JSONObject().put("l", e.localMd5).put("c", e.cloudMd5 ?: "").put("t", e.cloudModified))
}.toString()
@@ -374,18 +374,31 @@ object CloudSaves {
val remote = remote(cloud) { it in files }
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
val plan = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
val send = if (force) plan.transfer + plan.conflicts else plan.transfer
val send = CloudPlan.upSend(plan, force, cloud is GogCloud, files.keys)
val next = HashMap(base)
for (name in plan.same) remote[name]?.let { r -> next[name] = CloudPlan.Entry(local.getValue(name).md5, r.md5, r.modifiedMs) }
if (send.isNotEmpty()) {
backupCloud(context, store, id, cloud, send.mapNotNull { remote[it] })
val data = send.associateWith { files.getValue(it).readBytes() }
val stamped = cloud.put(data)
for ((name, t) in stamped) if (t > 0) files[name]?.setLastModified(t)
val after = remote(cloud) { it in data }
for (name in data.keys) {
val stamped = HashMap<String, Long>()
val sentMd5 = HashMap<String, String>()
if (cloud is GogCloud) {
// Stream one save at a time: gzip needs a full-size buffer and uploads can be large.
val filesToSend = send.associateWith { files.getValue(it) }
val results = cloud.putFiles(filesToSend, send.associateWith { files.getValue(it).lastModified() })
for ((name, result) in results) {
if (result.modifiedMs > 0) stamped[name] = result.modifiedMs
result.md5?.let { sentMd5[name] = it }
}
} else {
val data = send.associateWith { files.getValue(it).readBytes() }
for ((name, bytes) in data) sentMd5[name] = md5(bytes)
stamped += cloud.put(data, send.associateWith { files.getValue(it).lastModified() })
for ((name, t) in stamped) if (t > 0) files[name]?.setLastModified(t)
}
val after = remote(cloud) { it in send }
for (name in send) {
val r = after[name]
next[name] = CloudPlan.Entry(md5(data.getValue(name)), r?.md5, r?.modifiedMs ?: stamped[name] ?: -1L)
next[name] = CloudPlan.Entry(sentMd5.getValue(name), r?.md5, r?.modifiedMs ?: stamped[name] ?: -1L)
}
}
saveBaseline(context, store, id, next)
@@ -1,24 +1,43 @@
package com.droiddeck.launcher.stores
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import java.security.DigestOutputStream
import java.text.SimpleDateFormat
import java.time.Instant
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.util.Locale
import java.util.TimeZone
import java.util.zip.CRC32
import java.util.zip.Deflater
import java.util.zip.DeflaterOutputStream
import org.json.JSONArray
import org.json.JSONObject
class CloudFile(val name: String, var modifiedMs: Long, var md5: String? = null, val readLink: String? = null)
class CloudPut(val modifiedMs: Long, val md5: String?)
interface CloudTransport {
fun list(): List<CloudFile>
fun details(file: CloudFile) {}
fun get(file: CloudFile): Pair<ByteArray, Long>
fun put(files: Map<String, ByteArray>): Map<String, Long>
fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long> = emptyMap()): Map<String, Long>
/** Uploads from files so a transport can stream instead of holding every save in memory. */
fun putFiles(files: Map<String, File>, modifiedMs: Map<String, Long> = emptyMap()): Map<String, CloudPut> {
val data = files.mapValues { it.value.readBytes() }
val digests = data.mapValues { md5Hex(it.value) }
return put(data, modifiedMs).mapValues { (name, modified) -> CloudPut(modified, digests.getValue(name)) }
}
}
private const val TIMEOUT = 30_000
@@ -47,6 +66,9 @@ internal fun gunzip(data: ByteArray): ByteArray? = try {
java.util.zip.GZIPInputStream(data.inputStream()).use { it.readBytes() }
} catch (e: Exception) { null }
/** Same gzip GOG uses on PUT: deflate level 6, mtime 0, OS Unix. */
private val GOG_GZIP_HEADER = byteArrayOf(0x1f, 0x8b.toByte(), 8, 0, 0, 0, 0, 0, 0, 3)
internal fun gzipGogPut(data: ByteArray): ByteArray {
val deflater = Deflater(6, true)
val raw = ByteArrayOutputStream()
@@ -63,14 +85,14 @@ internal fun gzipGogPut(data: ByteArray): ByteArray {
}
val crc = CRC32().also { it.update(data) }
return ByteArrayOutputStream(18 + raw.size()).apply {
write(byteArrayOf(0x1f, 0x8b.toByte(), 8, 0, 0, 0, 0, 0, 0, 3))
write(GOG_GZIP_HEADER)
write(raw.toByteArray())
writeIntLe(crc.value.toInt())
writeIntLe(data.size)
}.toByteArray()
}
private fun ByteArrayOutputStream.writeIntLe(v: Int) {
private fun OutputStream.writeIntLe(v: Int) {
write(v and 0xff)
write(v ushr 8 and 0xff)
write(v ushr 16 and 0xff)
@@ -117,13 +139,64 @@ internal fun gogRelativeNames(files: List<CloudFile>, location: String?): Pair<S
}
}
private fun md5Hex(data: ByteArray): String =
java.security.MessageDigest.getInstance("MD5").digest(data).joinToString("") { "%02x".format(it) }
private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) }
private class GzipFile(val length: Long, val rawMd5: String, val etag: String)
/** Streams the same gzip framing as [gzipGogPut] into [dst] without reading the save into memory. */
private fun gzipFile(src: File, dst: File): GzipFile {
val raw = java.security.MessageDigest.getInstance("MD5")
val compressed = java.security.MessageDigest.getInstance("MD5")
val crc = CRC32()
var size = 0L
val file = FileOutputStream(dst)
val out = DigestOutputStream(file, compressed)
try {
out.write(GOG_GZIP_HEADER)
val deflater = Deflater(6, true)
try {
val deflate = DeflaterOutputStream(out, deflater, 64 * 1024)
src.inputStream().use { input ->
val buf = ByteArray(64 * 1024)
while (true) {
val n = input.read(buf)
if (n < 0) break
raw.update(buf, 0, n)
crc.update(buf, 0, n)
size += n
deflate.write(buf, 0, n)
}
}
deflate.finish()
} finally {
deflater.end()
}
out.writeIntLe(crc.value.toInt())
out.writeIntLe(size.toInt())
out.flush()
return GzipFile(dst.length(), raw.digest().toHex(), compressed.digest().toHex())
} finally {
out.close()
}
}
/** GOG Galaxy parses `X-Object-Meta-LocalLastModified`; objects without it fail as "invalid data". */
private val GOG_STAMP = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx", Locale.US)
private fun gogStamp(ms: Long): String =
Instant.ofEpochMilli(ms).atOffset(ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS).format(GOG_STAMP)
class GogCloud(
private val userId: String,
private val clientId: String,
private val token: String,
private val location: String? = null,
baseUrl: String? = null,
) : CloudTransport {
private val base = "https://cloudstorage.gog.com/v1/$userId/$clientId"
private val base = baseUrl ?: "https://cloudstorage.gog.com/v1/$userId/$clientId"
private val ua = "GOG Galaxy"
private var prefix: String? = location?.let { "$it/" }
@@ -190,16 +263,38 @@ class GogCloud(
return gogDecodeCloudBody(data, encoding) to modified
}
override fun put(files: Map<String, ByteArray>): Map<String, Long> = files.mapValues { (name, data) ->
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> = files.mapValues { (name, data) ->
val body = gzipGogPut(data)
putBody(name, body.inputStream(), body.size.toLong(), md5Hex(body), modifiedMs[name] ?: System.currentTimeMillis())
}
override fun putFiles(files: Map<String, File>, modifiedMs: Map<String, Long>): Map<String, CloudPut> = files.mapValues { (name, file) ->
val compressed = File.createTempFile("gog-cloud-", ".gz")
try {
val gz = gzipFile(file, compressed)
val modified = putBody(name, compressed.inputStream(), gz.length, gz.etag, modifiedMs[name] ?: file.lastModified())
CloudPut(modified, gz.rawMd5)
} finally {
compressed.delete()
}
}
private fun putBody(name: String, source: InputStream, length: Long, etag: String, modified: Long): Long {
val c = open("$base/${cloudKey(name)}", "PUT", token, ua)
c.doOutput = true
c.setRequestProperty("Content-Type", "application/octet-stream")
c.setFixedLengthStreamingMode(data.size)
c.outputStream.use { it.write(data) }
val code = c.responseCode
c.disconnect()
if (code !in 200..299) throw java.io.IOException("GOG cloud put HTTP $code")
CloudFile(name, -1L).also { details(it) }.modifiedMs
try {
c.doOutput = true
c.setRequestProperty("Content-Type", "application/octet-stream")
c.setRequestProperty("Content-Encoding", "gzip")
c.setRequestProperty("Etag", etag)
c.setRequestProperty("X-Object-Meta-LocalLastModified", gogStamp(modified))
c.setFixedLengthStreamingMode(length)
c.outputStream.use { out -> source.use { it.copyTo(out, 64 * 1024) } }
val code = c.responseCode
if (code !in 200..299) throw java.io.IOException("GOG cloud put HTTP $code")
return CloudFile(name, -1L).also { details(it) }.modifiedMs
} finally {
c.disconnect()
}
}
}
@@ -208,6 +303,6 @@ class EpicCloud(private val accountId: String, private val appName: String, priv
override fun get(file: CloudFile): Pair<ByteArray, Long> = com.droiddeck.launcher.stores.epic.EpicSaveSync.read(file)
override fun put(files: Map<String, ByteArray>): Map<String, Long> =
override fun put(files: Map<String, ByteArray>, modifiedMs: Map<String, Long>): Map<String, Long> =
com.droiddeck.launcher.stores.epic.EpicSaveSync.write(token, accountId, appName, files)
}
@@ -97,20 +97,25 @@ object StoreInstallRoot {
fun installRoot(context: Context): File = internalRoot(context)
fun externalTarget(context: Context): Target? =
if (SessionPrefs.defaultStorageFolder(context).isNotBlank()) customTarget(context)
else detectedExternalTarget(context)
fun externalTarget(context: Context): Target? = when {
SessionPrefs.defaultStorageFolder(context).isNotBlank() -> customTarget(context)
GameStorage.disconnected(context) -> null
else -> detectedExternalTarget(context)
}
internal fun externalTarget(targets: List<Target>, internalRoot: File): Target? =
targets.firstOrNull { it.folder && it.root.absolutePath != internalRoot.absolutePath }
?: targets.firstOrNull { it.removable && it.root.absolutePath != internalRoot.absolutePath }
fun defaultTarget(context: Context): Target? = when (SessionPrefs.defaultStorage(context)) {
SessionPrefs.DEFAULT_STORAGE_INTERNAL -> Target(internalRoot(context), context.getString(com.droiddeck.launcher.R.string.games_internal), removable = false)
SessionPrefs.DEFAULT_STORAGE_EXTERNAL -> externalTarget(context)
SessionPrefs.DEFAULT_STORAGE_INTERNAL -> internalTarget(context)
SessionPrefs.DEFAULT_STORAGE_EXTERNAL -> externalTarget(context) ?: internalTarget(context)
else -> null
}
private fun internalTarget(context: Context) =
Target(internalRoot(context), context.getString(com.droiddeck.launcher.R.string.games_internal), removable = false)
fun libraryRoot(context: Context): File? = GameStorage.effective(context)?.let { File(it.path, ON_VOLUME) }
fun roots(context: Context): List<File> {
@@ -74,29 +74,36 @@ object StoresState {
fun register(backend: StoreBackend) { backends[backend.store] = backend }
private val refreshRequests = java.util.concurrent.atomic.AtomicInteger()
fun refresh(context: Context) {
val app = context.applicationContext
com.droiddeck.launcher.stores.download.SavedQueue.restore(app)
background("stores-refresh") {
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(app) }
val found = Store.entries.mapNotNull { store -> StoreAccounts.displayName(app, store)?.let { store to it } }
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled || it.state == StoreGameSidecar.STATE_UPDATING }?.let { InstalledStoreGame(it, folder) }
} + runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetBackend.installedGames(app) }.getOrDefault(emptyList())
val partial = StoreInstallRoot.unfinished(app)
val version = if (StoresNative.available) StoresNative.version ?: "" else ""
main.post {
androidx.compose.runtime.snapshots.Snapshot.withMutableSnapshot {
val restored = found.toMap()
accounts.keys.toList().filter { it !in restored }.forEach { accounts.remove(it); libraryAsked.remove(it) }
accounts.putAll(restored)
installed = onDisk
unfinished = partial
engine = version
accountsLoaded = true
if (refreshRequests.getAndIncrement() > 0) return
var seen = 0
background("stores-refresh", onFailure = { if (refreshRequests.getAndSet(0) > seen) main.post { refresh(app) } }) {
do {
seen = refreshRequests.get()
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(app) }
val found = Store.entries.mapNotNull { store -> StoreAccounts.displayName(app, store)?.let { store to it } }
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled || it.state == StoreGameSidecar.STATE_UPDATING }?.let { InstalledStoreGame(it, folder) }
} + runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetBackend.installedGames(app) }.getOrDefault(emptyList())
val partial = StoreInstallRoot.unfinished(app)
val version = if (StoresNative.available) StoresNative.version ?: "" else ""
main.post {
androidx.compose.runtime.snapshots.Snapshot.withMutableSnapshot {
val restored = found.toMap()
accounts.keys.toList().filter { it !in restored }.forEach { accounts.remove(it); libraryAsked.remove(it) }
accounts.putAll(restored)
installed = onDisk
unfinished = partial
engine = version
accountsLoaded = true
}
com.droiddeck.launcher.stores.gog.GogMaintenance.checkInstalled(app, onDisk)
}
com.droiddeck.launcher.stores.gog.GogMaintenance.checkInstalled(app, onDisk)
}
} while (!refreshRequests.compareAndSet(seen, 0))
}
}
@@ -206,6 +213,7 @@ object StoresState {
main.post {
if (store == Store.XBOX && StoreAccounts.signedInAs(app, store) != null) return@post
accounts.remove(store); library.remove(store); status.remove(store); problems.remove(store); libraryAsked.remove(store)
if (store == Store.GOG) com.droiddeck.launcher.stores.gog.GogMaintenance.reset()
logLine("${store.label}: signed out")
}
}
@@ -34,11 +34,16 @@ object BattleNetInstall {
internal const val STATE = "BNET_STATE "
internal const val DONE = "BNET_DONE "
internal const val ERROR = "BNET_ERROR "
private const val VERSIONS = "https://%s.version.battle.net/v2/products/%s/versions"
private const val CN = "cn"
private const val BUILD_INFO = ".build.info"
private const val CHECK_AGAIN_MS = 30 * 60_000L
private const val START_WAIT_MS = 60_000L
/** Blizzard serves China from battlenet.com.cn; its global version hostnames do not answer for that region. */
internal fun versionsUrl(region: String, product: String): String =
"https://" + (if (region == CN) "cn.version.battlenet.com.cn" else "$region.version.battle.net") +
"/v2/products/$product/versions"
internal val LOCALES = listOf(
"enUS", "enGB", "esMX", "esES", "ptBR", "ptPT", "frFR", "deDE", "itIT", "ruRU", "jaJP", "koKR", "plPL", "trTR",
"zhTW", "zhCN", "thTH", "arSA",
@@ -187,7 +192,7 @@ object BattleNetInstall {
checks.execute {
val local = runCatching { buildKey(File(folder, BUILD_INFO).readText()) }.getOrNull()
?: return@execute retryLater()
val latest = runCatching { latestBuild(fetch(VERSIONS.format(Locale.ROOT, local.first, product)), local.first) }
val latest = runCatching { latestBuild(fetch(versionsUrl(local.first, product)), local.first) }
.onFailure { Log.w(TAG, "versions of $product: ${it.javaClass.simpleName}") }.getOrNull()
?: return@execute retryLater()
val behind = latest != local.second
@@ -41,7 +41,7 @@ internal object GogMaintenance {
}
fun checkInstalled(context: Context, games: List<InstalledStoreGame>) {
val user = StoreAccounts.displayName(context, Store.GOG).orEmpty()
val user = StoresState.accounts[Store.GOG].orEmpty()
if (user != account) { reset(); account = user }
if (user.isBlank()) return
games.filter { it.sidecar.store == Store.GOG && it.sidecar.isInstalled }.forEach { check(context, it) }
@@ -112,16 +112,19 @@ internal fun BarActions(
qamModifier: Modifier = Modifier,
qamInteraction: MutableInteractionSource? = null,
onQamConfirm: (() -> Unit)? = null,
showShortcuts: Boolean = false,
) {
onMenu?.let {
BarButton(stringResource(R.string.touch_droiddeck_menu), menuModifier.testTag("bottom-bar-menu"), icon = R.drawable.ic_stat_session,
active = menuActive, onClick = it)
}
onSteam?.let {
BarButton(stringResource(R.string.drawer_steam_menu), steamModifier.testTag("bottom-bar-steam"), label = "STEAM", onClick = it)
BarButton(stringResource(R.string.drawer_steam_menu), steamModifier.testTag("bottom-bar-steam"), label = "STEAM",
shortcut = if (showShortcuts) "⧉" else null, onClick = it)
}
onQam?.let {
BarButton(stringResource(R.string.drawer_open_qam), qamModifier.testTag("bottom-bar-qam"), vector = Icons.Outlined.MoreHoriz,
shortcut = if (showShortcuts) "☰" else null,
interactionSource = qamInteraction ?: remember { MutableInteractionSource() }, onConfirm = onQamConfirm, onClick = it)
}
}
@@ -483,17 +483,27 @@ fun ComponentsPage(
)
else -> {
val st = compState(l)
val managedDxvk = ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)
val label = ComponentsManager.LABEL[l] ?: l
if (st == null) InUseBar(false, stringResource(R.string.comp_no_proton), "")
else {
val reappliedAt = view?.reappliedAt?.takeIf { it > 0 }?.let { DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(it * 1000)) }
InUseBar(
queued = st.queued != null,
sentence = (if (st.queued != null) stringResource(R.string.comp_next_queued, st.queued) else stringResource(R.string.comp_in_use, label, st.inUse))
.let { if (reappliedAt != null) stringResource(R.string.comp_reapplied, it, reappliedAt) else it },
note = if (view?.inUseByGame == true) stringResource(R.string.comp_waits) else stringResource(R.string.comp_applies_next_game),
onCancel = if (st.queued != null) onCancelQueued else null,
)
Column {
InUseBar(
queued = st.queued != null,
sentence = (if (managedDxvk) stringResource(R.string.comp_in_use, label, stringResource(R.string.gpu_system_powervr)) +
(st.queued?.let { "\n" + stringResource(R.string.cmgr_powervr_dxvk_queued, it) } ?: "")
else if (st.queued != null) stringResource(R.string.comp_next_queued, st.queued) else stringResource(R.string.comp_in_use, label, st.inUse))
.let { if (reappliedAt != null && !managedDxvk) stringResource(R.string.comp_reapplied, it, reappliedAt) else it },
note = if (managedDxvk) "" else if (view?.inUseByGame == true) stringResource(R.string.comp_waits) else stringResource(R.string.comp_applies_next_game),
onCancel = if (st.queued != null) onCancelQueued else null,
maxLines = if (managedDxvk && st.queued != null) 3 else 2,
)
if (managedDxvk) Text(
stringResource(R.string.cmgr_powervr_dxvk_managed),
fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp),
)
}
}
}
}
@@ -537,16 +547,17 @@ fun ComponentsPage(
}
else -> {
val label = ComponentsManager.LABEL[l] ?: l
val rows = installedFor(l, view, snapshot)
val managedDxvk = ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)
val rows = installedFor(l, view, snapshot, managedDxvk)
if (rows.isEmpty()) EmptyLine(stringResource(R.string.comp_nothing_stored, label))
val p = view?.proton
rows.forEachIndexed { i, item ->
val key = "row:$l:${item.file ?: item.protonVersion}"
ChoiceLine(
item.name, item.detail, item.selected, item.removable, tag = item.tag,
modifier = (if (i == 0) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
item.name, item.detail, item.selected, item.removable, tag = item.tag, enabled = !managedDxvk,
modifier = (if (i == 0 && !managedDxvk) Modifier.focusRequester(firstRow) else Modifier).trackRow(key, rowsAt),
onSelect = {
if (item.selected || p == null) return@ChoiceLine
if (managedDxvk || item.selected || p == null) return@ChoiceLine
val waits = if (view.inUseByGame) ctx.getString(R.string.comp_waits_long) else ctx.getString(R.string.comp_applies_long)
if (item.file != null) ask(key, right, ctx.getString(R.string.comp_swap_title, label), ctx.getString(R.string.comp_swap_body, item.name, p.name, waits), ctx.getString(R.string.comp_swap), false, item.name) {
onSwap(item.file); flyHome(key, l)
@@ -617,14 +628,19 @@ fun ComponentsPage(
}
}
else -> {
SmallButton(stringResource(R.string.comp_import_wcp), onClick = onImport)
val managedDxvk = ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)
SmallButton(
stringResource(R.string.comp_import_wcp), onClick = onImport,
modifier = if (managedDxvk) Modifier.focusRequester(firstRow) else Modifier,
)
val st = compState(l)
val p = view?.proton
val build = p?.let { ComponentsManager.safeName(it.version) }
if (st != null && p != null && st.activeFile != null && view.originals.any { it.comp == l && it.protonVersion == build }) {
val label = ComponentsManager.LABEL[l] ?: l
Box(Modifier.trackRow("restore:$l", rowsAt)) {
FocusText(stringResource(R.string.comp_restore_original), pal.signal) {
if (managedDxvk) SmallButton(stringResource(R.string.comp_restore_original), enabled = false) {}
else FocusText(stringResource(R.string.comp_restore_original), pal.signal) {
ask("restore:$l", false, ctx.getString(R.string.comp_restore_title, label), ctx.getString(R.string.comp_restore_original_body, p.name, label), ctx.getString(R.string.common_restore), false, ctx.getString(R.string.comp_restore_original)) {
onRestore(build!!); flyHome("restore:$l", l)
}
@@ -770,6 +786,7 @@ fun ComponentsPage(
protonChoice = gameProtonChoice,
packages = snapshot?.packages.orEmpty(),
componentChoices = gameComponents,
systemPowerVr = gpu.systemPowerVr,
componentMenu = gameComponentMenu,
protonMenu = gameProtonMenu,
fexMenu = fexMenu,
@@ -900,6 +917,7 @@ fun ComponentsPage(
winOpen,
compat = selectedGame.protonPrefix,
steamAppId = selectedGame.appId.takeIf { selectedGame.library != Library.ADDED },
game = selectedGame,
) {
winComponentsOpen = null
winComponentsRevision++
@@ -908,11 +926,11 @@ fun ComponentsPage(
}
@Composable
private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapshot: Snapshot?): List<InstalledItem> {
private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapshot: Snapshot?, runtimeManaged: Boolean = false): List<InstalledItem> {
view ?: return emptyList()
val st = view.components[l] ?: return emptyList()
val build = ComponentsManager.safeName(view.proton.version)
val activeIsOriginal = st.activeFile == null
val activeIsOriginal = !runtimeManaged && st.activeFile == null
return view.originals.filter { it.comp == l }.map { o ->
val isCurrent = o.protonVersion == build
InstalledItem(
@@ -921,7 +939,7 @@ private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapsho
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
)
} + (snapshot?.packages ?: emptyList()).filter { it.comp == l }.map { s ->
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", s.file == st.activeFile, true, s.file, null)
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", !runtimeManaged && s.file == st.activeFile, true, s.file, null)
}
}
@@ -960,11 +978,12 @@ private fun Stack(
LayerCard(
title = LayerTitle(l),
value = when (l) {
GPU_TAB -> gpuCardValue(gpu, auto)
GPU_TAB -> if (gpu.systemPowerVr) stringResource(R.string.gpu_system_powervr) else gpuCardValue(gpu, auto)
PROTON_TAB -> (view?.proton?.name ?: "") + " ▾"
else -> st?.let { if (it.activeFile == null) original else it.inUse } ?: ""
else -> if (ComponentsManager.runtimeManaged(l, gpu.systemPowerVr)) stringResource(R.string.gpu_system_powervr)
else st?.let { if (it.activeFile == null) original else it.inUse } ?: ""
},
swapped = l in ComponentsManager.COMPONENTS && st?.activeFile != null,
swapped = l in ComponentsManager.COMPONENTS && st?.activeFile != null && !ComponentsManager.runtimeManaged(l, gpu.systemPowerVr),
selected = l == layer,
landed = landed[l] ?: 0, ring = rings[l] ?: 0,
modifier = Modifier.focusRequester(focus.getValue(l)).onGloballyPositioned { onPlaced(l, it.boundsInRoot()) },
@@ -1031,7 +1050,7 @@ private fun LayerCard(
}
@Composable
private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel: (() -> Unit)? = null) {
private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel: (() -> Unit)? = null, maxLines: Int = 2) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
@@ -1040,7 +1059,7 @@ private fun InUseBar(queued: Boolean, sentence: String, note: String, onCancel:
.border(1.dp, pal.line, RoundedCornerShape(12.dp)).padding(horizontal = 14.dp, vertical = 8.dp),
) {
Box(Modifier.size(8.dp).background(if (queued) QUEUED else pal.good, CircleShape))
Text(sentence, fontSize = 14.sp, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Text(sentence, fontSize = 14.sp, color = colors.onBackground, maxLines = maxLines, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
if (onCancel != null) FocusText(stringResource(R.string.common_cancel), pal.signal, onClick = onCancel)
else if (note.isNotEmpty() && !LocalNarrowPane.current) Text(note, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
@@ -1075,6 +1094,7 @@ private fun GameComponentOverrides(
protonChoice: ProtonDefault.GameChoice?,
packages: List<ComponentsManager.Package>,
componentChoices: Map<String, String>,
systemPowerVr: Boolean,
componentMenu: String?,
protonMenu: Boolean,
fexMenu: Boolean,
@@ -1166,6 +1186,7 @@ private fun GameComponentOverrides(
}
GamePackageRow(
comp = "dxvk",
runtimeManaged = ComponentsManager.runtimeManaged("dxvk", systemPowerVr),
packages = packages,
selectedFile = componentChoices["dxvk"],
open = componentMenu == "dxvk",
@@ -1230,13 +1251,16 @@ private fun GamePackageRow(
onMenu: (String?) -> Unit,
onPick: (String, String?) -> Unit,
onRuntimeOptions: (() -> Unit)? = null,
runtimeManaged: Boolean = false,
) {
val choices = packages.filter { it.comp == comp }
val selected = choices.firstOrNull { it.file == selectedFile }
val title = ComponentsManager.LABEL[comp] ?: comp
val enabled = !busy && (!runtimeManaged || selectedFile != null)
SettingsRow(
title,
if (selected == null) {
if (runtimeManaged) stringResource(R.string.cmgr_powervr_dxvk_managed)
else if (selected == null) {
if (proton == null) stringResource(R.string.comp_game_component_general)
else stringResource(R.string.comp_game_component_runtime, proton.name)
} else stringResource(R.string.comp_game_component_override, selected.version),
@@ -1244,18 +1268,18 @@ private fun GamePackageRow(
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
Box {
ValueChip(
selected?.version ?: stringResource(R.string.comp_game_use_general),
open,
enabled = !busy,
if (runtimeManaged) stringResource(R.string.gpu_system_powervr) else selected?.version ?: stringResource(R.string.comp_game_use_general),
open && enabled,
enabled = enabled,
modifier = Modifier.widthIn(max = 240.dp),
) { onMenu(if (open) null else comp) }
AnchoredMenu(open, onDismiss = { onMenu(null) }, title = title) { first ->
AnchoredMenu(open && enabled, onDismiss = { onMenu(null) }, title = title) { first ->
MenuItem(
stringResource(R.string.comp_game_use_general),
checked = selected == null,
focusRequester = first,
) { onPick(comp, null); onMenu(null) }
choices.forEach { option ->
if (!runtimeManaged) choices.forEach { option ->
MenuItem(option.version, checked = option.file == selectedFile, detail = option.description) {
onPick(comp, option.file)
onMenu(null)
@@ -1377,13 +1401,13 @@ private fun Tag(text: String) {
@Composable
private fun ChoiceLine(
name: String, detail: String, selected: Boolean, removable: Boolean,
modifier: Modifier = Modifier, tag: String? = null, badge: String? = null, progress: Int? = null,
modifier: Modifier = Modifier, tag: String? = null, badge: String? = null, progress: Int? = null, enabled: Boolean = true,
onSelect: () -> Unit, onDelete: () -> Unit = {},
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val hot = rememberHot(src) && enabled
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth()
@@ -1393,8 +1417,8 @@ private fun ChoiceLine(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.weight(1f).heightIn(min = 56.dp).then(modifier)
.glideBorder(hot, ROW_SHAPE, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onSelect)
.controllerConfirm(onClick = onSelect)
.hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, role = Role.RadioButton, onClick = onSelect)
.controllerConfirm(enabled = enabled, onClick = onSelect)
.padding(start = 14.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(20.dp).border(2.dp, if (selected) pal.signal else colors.onSurfaceVariant, CircleShape)) {
@@ -1404,7 +1428,7 @@ private fun ChoiceLine(
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis,
color = if (selected) pal.signal else colors.onBackground, modifier = Modifier.weight(1f, fill = false),
color = if (!enabled) colors.onSurfaceVariant else if (selected) pal.signal else colors.onBackground, modifier = Modifier.weight(1f, fill = false),
)
if (tag != null) Tag(tag)
}
@@ -25,6 +25,7 @@ class ControllerActions(
val onStickClick: (Boolean) -> Unit,
val onAdaptiveSticks: (Boolean) -> Unit,
val onRumble: (Boolean) -> Unit,
val onDeadZone: (Int) -> Unit,
val onSteamButton: (Boolean) -> Unit,
val onQamButton: (Boolean) -> Unit,
val onKeyboardButton: (Boolean) -> Unit,
@@ -68,6 +69,7 @@ fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPre
ToggleRow(host, "controller-stick-click", stringResource(R.string.ctrl_stick_click), stringResource(R.string.ctrl_stick_click_hint), c.stickClick, onChange = a.onStickClick)
ToggleRow(host, "controller-adaptive", stringResource(R.string.ctrl_adaptive), stringResource(R.string.ctrl_adaptive_hint), c.adaptiveSticks, onChange = a.onAdaptiveSticks)
ToggleRow(host, "controller-rumble", stringResource(R.string.ctrl_rumble), null, c.rumble, onChange = a.onRumble)
ChoiceRow(host, "controller-dead-zone", stringResource(R.string.ctrl_dead_zone), null, ControllerPrefs.deadZones.map { it to stringResource(R.string.ctrl_percent, it) }, c.deadZone, onPick = a.onDeadZone)
ToggleRow(host, "controller-steam", stringResource(R.string.ctrl_steam_button), null, c.steamButton, onChange = a.onSteamButton)
ToggleRow(host, "controller-qam", stringResource(R.string.ctrl_qam_button), null, c.qamButton, onChange = a.onQamButton)
ToggleRow(host, "controller-keyboard", stringResource(R.string.ctrl_keyboard_button), null, c.keyboardButton, onChange = a.onKeyboardButton)
@@ -540,7 +540,7 @@ class DeckControlsPanel(
private fun move(dx: Float, dy: Float, r: Float) {
knobX = dx
knobY = dy
pad.applyTouch(this@DeckControlsPanel, inputRole) { s ->
pad.applyTouch(this@DeckControlsPanel, inputRole, if (right) PadBridge.RIGHT_STICK else PadBridge.LEFT_STICK) { s ->
if (right) { s.rightX = dx / r; s.rightY = dy / r } else { s.leftX = dx / r; s.leftY = dy / r }
}
invalidate()
@@ -153,6 +153,8 @@ private val METRICS = listOf(
HudMetric("FPS", "showFPS", R.string.drawer_hud_fps),
HudMetric("FPS graph", "showFPSGraph", R.string.hud_metric_graph),
HudMetric("FPS .1", "fpsDecimal", R.string.hud_metric_decimal),
HudMetric("1% low", "showLow1", R.string.hud_metric_low1),
HudMetric("0.1% low", "showLow01", R.string.hud_metric_low01),
HudMetric("0.01% low", "showLow001", R.string.hud_metric_low001),
HudMetric("Engine", "showEngine", R.string.hud_metric_engine),
HudMetric("GPU model", "showGpuModel", R.string.hud_metric_gpu_model),
@@ -176,6 +178,6 @@ private val METRICS = listOf(
private val HIDDEN = mapOf(
DroidDeckHudSize.PILL to setOf("FPS", "FPS graph"),
DroidDeckHudSize.MINIMAL to setOf("FPS"),
DroidDeckHudSize.TILES to setOf("FPS graph", "0.01% low"),
DroidDeckHudSize.TILES to setOf("FPS graph", "0.1% low", "0.01% low"),
DroidDeckHudSize.STRIP to setOf("FPS"),
)
@@ -102,10 +102,15 @@ class FrontEndState(
val frameGenLabel: String,
val romsDir: String?,
val logsEnabled: Boolean,
val enhancedDiagnosticsArmed: Boolean = false,
val gameDebugLogsEnabled: Boolean = false,
val gameDebugLogsNeedsRestart: Boolean = false,
val vacDiagnostics: Boolean = false,
val agentCommands: Boolean = false,
val graphicsLogs: Boolean = false,
val steamGpuDrawing: Boolean = false,
val bridgeFellBack: Boolean = false,
val bridgeFellBackMemory: Boolean = false,
val clearCachedApps: Boolean = false,
val adbPaired: Boolean = false,
val backgroundAppLimit: Int = -1,
@@ -151,6 +156,8 @@ class FrontEndState(
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
val adreno: Boolean = true,
val vkBridge: Boolean = false,
val venus: Boolean = false,
val venusHostVulkan: String? = null,
val vkBridgeSafe: Boolean = true,
val bridgeProtonDxvk: Boolean = false,
val showPhantomGate: Boolean = false,
@@ -210,6 +217,7 @@ class FrontEndActions(
val onRemovePackage: (String) -> Unit,
val onRuntime: () -> Unit,
val onVkBridge: (Boolean) -> Unit = {},
val onVenus: (Boolean) -> Unit = {},
val onVkBridgeSafe: (Boolean) -> Unit = {},
val onBridgeProtonDxvk: (Boolean) -> Unit = {},
val onFrameGenPick: (FrameGen.Mode) -> Unit,
@@ -219,19 +227,27 @@ class FrontEndActions(
val onGameComponents: (Library.SteamGame) -> Unit = { onComponents(true) },
val onComponentsTab: (String) -> Unit = {},
val onSaveImport: (Library.SteamGame) -> Unit = {},
val onAddonImport: (Library.SteamGame, com.droiddeck.launcher.runtime.WowAddons.Target) -> Unit = { _, _ -> },
val onAddonDelete: (com.droiddeck.launcher.runtime.WowAddons.Target, String) -> Unit = { _, _ -> },
val onSaveExport: (Library.SteamGame, com.droiddeck.launcher.session.GameSaves.Layout) -> Unit = { _, _ -> },
val onPerformance: () -> Unit,
val onRoms: () -> Unit,
val onFiles: () -> Unit,
val onBrowseFiles: (File) -> Unit = {},
val onLogs: () -> Unit,
val onEnhancedDiagnostics: () -> Unit = {},
val onGameDebugLogs: () -> Unit = {},
val onVacDiagnostics: () -> Unit = {},
val onAgentCommands: () -> Unit = {},
val onGraphicsLogs: () -> Unit = {},
val onSteamGpuDrawing: () -> Unit = {},
val onClearCachedApps: (Boolean) -> Unit = {},
val onMemoryHud: (String) -> Unit = {},
val onBackgroundAppLimit: (Int) -> Unit = {},
val onShareLogs: () -> Unit = {},
val onShareSessionLog: (File) -> Unit = {},
val onSaveSessionLog: (File) -> Unit = {},
val onDeleteSessionLog: (File, () -> Unit) -> Unit = { _, done -> done() },
val onClearLogs: () -> Unit = {},
val onResetSettings: () -> Unit = {},
val onOffline: () -> Unit,
@@ -193,11 +193,13 @@ internal fun SetupPanel(
)
val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_launcher), stringResource(R.string.setup_tab_storage), stringResource(R.string.setup_tab_sync), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses))
var tab by rememberSaveable { mutableStateOf(if (SetupTabs.openLauncher) LAUNCHER_TAB else 0) }
var logsRefresh by remember { mutableStateOf(0) }
var deleteSessionLogs by remember { mutableStateOf<java.io.File?>(null) }
SetupTabs.openLauncher = false
if (SetupTabs.openOverview) { tab = 0; SetupTabs.openOverview = false }
val chipFocus = remember { List(tabs.size) { FocusRequester() } }
var tabTurned by remember { mutableStateOf(false) }
val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true }
val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true; if (i == 5) logsRefresh++ }
val inputModeManager = LocalInputModeManager.current
LaunchedEffect(com.droiddeck.launcher.storage.StorageState.openRequests) {
if (com.droiddeck.launcher.storage.StorageState.openPending) {
@@ -246,6 +248,8 @@ internal fun SetupPanel(
Column(modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
when (tab) {
0 -> {
// Setup's "Safe mode" row, under the GPU row while the bridge is on and can be used here.
val bridgeModeRow = !s.adreno && s.vkBridge && com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()
val gpuCheck: @Composable (Boolean) -> Unit = { divider ->
CheckRow(
if (gpuOk) CheckState.OK else CheckState.WARN,
@@ -257,19 +261,32 @@ internal fun SetupPanel(
},
when (gpu.support) {
com.droiddeck.launcher.gpu.GpuInfo.Support.TESTED -> stringResource(R.string.setup_gpu_detail, gpu.displayName(ctx), gpuName)
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED -> stringResource(R.string.setup_gpu_untested_detail, gpu.displayName(ctx), gpu.supportText(ctx).replaceFirstChar { it.lowercase() })
else -> if (s.vkBridge) stringResource(R.string.setup_gpu_bridge_detail, gpuName)
com.droiddeck.launcher.gpu.GpuInfo.Support.UNTESTED ->
if (!s.adreno && s.venus && s.venusHostVulkan != null) stringResource(R.string.setup_gpu_venus_host_too_old, gpu.displayName(ctx), s.venusHostVulkan)
else if (!s.adreno && s.vkBridge && !com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()) stringResource(R.string.setup_gpu_bridge_unusable, gpu.displayName(ctx))
else if (!s.adreno && s.vkBridge && s.bridgeFellBack) stringResource(if (s.bridgeFellBackMemory) R.string.setup_gpu_bridge_no_memory_sharing else R.string.setup_gpu_bridge_fell_back, gpu.displayName(ctx))
else stringResource(R.string.setup_gpu_untested_detail, gpu.displayName(ctx), gpu.supportText(ctx).replaceFirstChar { it.lowercase() })
else -> if (s.venus && s.venusHostVulkan != null) stringResource(R.string.setup_gpu_venus_host_too_old, gpuName, s.venusHostVulkan)
else if (s.vkBridge && !com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()) stringResource(R.string.setup_gpu_bridge_unusable, gpuName)
else if (s.vkBridge && s.bridgeFellBack) stringResource(if (s.bridgeFellBackMemory) R.string.setup_gpu_bridge_no_memory_sharing else R.string.setup_gpu_bridge_fell_back, gpuName)
else if (s.vkBridge) stringResource(R.string.setup_gpu_bridge_detail, gpuName)
else stringResource(R.string.setup_gpu_unsupported_detail, gpuName)
},
divider = divider || (!s.adreno && s.vkBridge),
divider = divider || bridgeModeRow,
action = if (s.adreno) null else { {
SecondaryButton(
stringResource(if (s.vkBridge) R.string.setup_gpu_bridge_on else R.string.setup_gpu_bridge_off),
enabled = !s.sessionRunning, compact = true, onClick = { a.onVkBridge(!s.vkBridge) },
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SecondaryButton(
stringResource(if (s.venus) R.string.setup_gpu_venus_on else R.string.setup_gpu_venus_off),
enabled = !s.sessionRunning, compact = true, onClick = { a.onVenus(!s.venus) },
)
SecondaryButton(
stringResource(if (s.vkBridge) R.string.setup_gpu_bridge_on else R.string.setup_gpu_bridge_off),
enabled = !s.sessionRunning, compact = true, onClick = { a.onVkBridge(!s.vkBridge) },
)
}
} },
)
if (!s.adreno && s.vkBridge) CheckRow(
if (bridgeModeRow) CheckRow(
CheckState.OK,
stringResource(R.string.setup_bridge_safe),
stringResource(if (s.vkBridgeSafe) R.string.setup_bridge_safe_on_detail else R.string.setup_bridge_safe_off_detail),
@@ -382,11 +399,12 @@ internal fun SetupPanel(
val shownChecks = all.filterIndexed { i, _ -> checks[i] }
shownChecks.forEachIndexed { i, check -> check(i < shownChecks.lastIndex) }
}
if (passing < checks.size) {
val needsAttention = all.filterIndexed { i, _ -> !checks[i] && i != 1 }
if (needsAttention.isNotEmpty()) {
SectionTitle(stringResource(R.string.setup_needs_you), null)
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
all.forEachIndexed { i, check ->
if (!checks[i]) Column(Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, AttentionAmber.copy(alpha = 0.5f), Shape14)) { check(false) }
needsAttention.forEach { check ->
Column(Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, AttentionAmber.copy(alpha = 0.5f), Shape14)) { check(false) }
}
}
}
@@ -543,6 +561,10 @@ internal fun SetupPanel(
5 -> {
SettingsGroup(stringResource(R.string.setup_tab_diagnostics)) {
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
ToggleRow(
host, "enhanced-diagnostics", stringResource(R.string.setup_enhanced_diagnostics),
stringResource(R.string.setup_enhanced_diagnostics_hint), s.enhancedDiagnosticsArmed,
) { a.onEnhancedDiagnostics() }
ToggleRow(
host, "game-debug-logs", stringResource(R.string.setup_game_debug_logs),
stringResource(if (s.gameDebugLogsNeedsRestart) R.string.setup_game_debug_logs_restart else R.string.setup_game_debug_logs_hint),
@@ -551,8 +573,48 @@ internal fun SetupPanel(
) { a.onGameDebugLogs() }
ToggleRow(host, "vacdiag", stringResource(R.string.setup_vac_diag), stringResource(R.string.setup_vac_diag_hint), s.vacDiagnostics) { a.onVacDiagnostics() }
ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), null, s.agentCommands) { a.onAgentCommands() }
ToggleRow(host, "graphics-logs", stringResource(R.string.setup_graphics_logs), stringResource(R.string.setup_graphics_logs_hint), s.graphicsLogs) { a.onGraphicsLogs() }
if (!s.adreno && com.droiddeck.launcher.session.SessionPrefs.steamGpuCompositingAllowed()) ToggleRow(host, "steam-gpu-drawing", stringResource(R.string.setup_steam_gpu_drawing), stringResource(R.string.setup_steam_gpu_drawing_hint), s.steamGpuDrawing) { a.onSteamGpuDrawing() }
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs,
progress = com.droiddeck.launcher.session.SessionLogShare.progress)
androidx.compose.material3.HorizontalDivider()
Text(stringResource(R.string.setup_log_sessions), fontSize = 13.sp, fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
Text(stringResource(R.string.setup_log_export_hint), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = 14.dp, end = 14.dp, bottom = 8.dp))
val sessionLogs = remember(ctx, logsRefresh) { com.droiddeck.launcher.session.SessionLogShare.sessions(ctx).asReversed() }
if (sessionLogs.isEmpty()) {
Text(stringResource(R.string.setup_log_empty), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
}
sessionLogs.forEach { folder ->
val active = folder == com.droiddeck.launcher.session.SessionPaths.current()
var details by remember(folder) { mutableStateOf<com.droiddeck.launcher.session.SessionLogShare.Details?>(null) }
LaunchedEffect(folder, logsRefresh) {
details = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
com.droiddeck.launcher.session.SessionLogShare.details(folder)
}
}
Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp)) {
Text(folder.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis)
details?.let { detail ->
Text(
stringResource(R.string.setup_log_size_date,
android.text.format.Formatter.formatShortFileSize(ctx, detail.sizeBytes),
"${android.text.format.DateFormat.getDateFormat(ctx).format(java.util.Date(detail.modifiedAt))} ${android.text.format.DateFormat.getTimeFormat(ctx).format(java.util.Date(detail.modifiedAt))}"),
fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (active) Text(stringResource(R.string.setup_log_current), fontSize = 12.sp, color = MaterialTheme.colorScheme.primary)
Row(Modifier.fillMaxWidth().padding(top = 6.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SecondaryButton(stringResource(R.string.setup_log_share), enabled = com.droiddeck.launcher.session.SessionLogShare.progress == null, compact = true, modifier = Modifier.weight(1f)) { a.onShareSessionLog(folder) }
SecondaryButton(stringResource(R.string.setup_log_save), enabled = com.droiddeck.launcher.session.SessionLogShare.progress == null, compact = true, modifier = Modifier.weight(1f)) { a.onSaveSessionLog(folder) }
SecondaryButton(stringResource(R.string.setup_log_delete), compact = true, enabled = !active, modifier = Modifier.weight(1f)) { deleteSessionLogs = folder }
}
}
androidx.compose.material3.HorizontalDivider()
}
ActionRow(stringResource(R.string.setup_saved_logs), stringResource(R.string.setup_saved_logs_hint, com.droiddeck.launcher.session.SessionPaths.KEEP_SESSIONS), stringResource(R.string.setup_clear_logs), a.onClearLogs)
ActionRow(stringResource(R.string.setup_reset_settings), stringResource(R.string.setup_reset_settings_hint),
stringResource(R.string.setup_reset_settings_button), a.onResetSettings)
@@ -595,6 +657,20 @@ internal fun SetupPanel(
}
}
}
deleteSessionLogs?.let { folder ->
androidx.compose.material3.AlertDialog(
onDismissRequest = { deleteSessionLogs = null },
title = { Text(stringResource(R.string.setup_log_delete_title)) },
text = { Text(stringResource(R.string.setup_log_delete_message, folder.name)) },
confirmButton = {
androidx.compose.material3.TextButton(onClick = {
deleteSessionLogs = null
a.onDeleteSessionLog(folder) { logsRefresh++ }
}) { Text(stringResource(R.string.setup_log_delete)) }
},
dismissButton = { androidx.compose.material3.TextButton(onClick = { deleteSessionLogs = null }) { Text(stringResource(R.string.common_cancel)) } },
)
}
}
@Composable
@@ -73,6 +73,7 @@ import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
@@ -86,7 +87,9 @@ import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.GameRemoval
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.runtime.WowAddons
import com.droiddeck.launcher.session.GameSaves
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.CloudSaves
import com.droiddeck.launcher.stores.InstalledStoreGame
@@ -136,7 +139,7 @@ internal class GameRef(val appId: Int?, val store: Store?, val storeId: String?)
}
}
internal enum class GameTab { ABOUT, ACHIEVEMENTS, LAUNCH, SAVES, INSTALL }
internal enum class GameTab { ABOUT, ACHIEVEMENTS, LAUNCH, SAVES, ADDONS, INSTALL }
@Composable
internal fun GameDetail(
@@ -180,12 +183,14 @@ internal fun GameDetail(
.takeUnless { it.trim().equals(title.trim(), ignoreCase = true) }.orEmpty()
val scored = scores != null && (scores.metacritic != Lookup.None || scores.hltb != Lookup.None)
val prefix = game?.protonPrefix?.takeIf { it.isDirectory }
val addonTargets = remember(game?.gameId, game?.gameFiles) { game?.let(WowAddons::targets).orEmpty() }
val tabs = buildList {
if (description.isNotBlank() || developer.isNotBlank() || publisher.isNotBlank() || releaseDate.isNotBlank() || scored || (!s.shortcutPicker && title.isNotBlank() && title != id)) add(GameTab.ABOUT)
if (achievementState != null) add(GameTab.ACHIEVEMENTS)
val cloud = game?.library == Library.XBOX_CLOUD
if (game != null && !cloud) add(GameTab.LAUNCH)
if (game != null && game.library == Library.ADDED && prefix != null) add(GameTab.SAVES)
if (addonTargets.isNotEmpty()) add(GameTab.ADDONS)
if ((game != null && !cloud) || installed != null) add(GameTab.INSTALL)
}
var picked by remember(key) { mutableStateOf<GameTab?>(null) }
@@ -248,6 +253,7 @@ internal fun GameDetail(
} ?: stringResource(R.string.achievements_title)
GameTab.LAUNCH -> stringResource(R.string.game_tab_launch)
GameTab.SAVES -> stringResource(if (Store.byId(source).let { it == Store.GOG || it == Store.EPIC }) R.string.game_tab_saves_cloud else R.string.games_saves)
GameTab.ADDONS -> stringResource(R.string.game_tab_addons)
GameTab.INSTALL -> stringResource(R.string.game_tab_install)
}
}
@@ -263,6 +269,7 @@ internal fun GameDetail(
GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) }
GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail)
GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a)
GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, a)
GameTab.INSTALL -> InstallTab(game, installed, item, store)
}
}
@@ -857,6 +864,44 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
}
}
@Composable
private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a: FrontEndActions) {
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
targets.forEach { target ->
val names by produceState(emptyList<String>(), target.addOns, WowAddons.imports) {
value = withContext(Dispatchers.IO) { WowAddons.installed(target) }
}
if (targets.size > 1) SectionLabel(target.flavor)
MenuItem(
stringResource(R.string.games_import_addons), checked = false,
detail = pluralStringResource(R.plurals.games_addons_count, names.size, names.size),
) { a.onAddonImport(g, target) }
MenuItem(stringResource(R.string.games_open_addons_folder), checked = false) {
target.addOns.mkdirs()
a.onBrowseFiles(target.addOns)
}
names.forEach { name -> AddonRow(name, target, a) }
}
}
}
@Composable
private fun AddonRow(name: String, target: WowAddons.Target, a: FrontEndActions) {
var asking by remember(target.addOns, name) { mutableStateOf(false) }
val delete = stringResource(R.string.common_delete)
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 2.dp, bottom = 2.dp)) {
Text(name, fontSize = 14.sp, color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
if (!SessionState.running) IconAction(Icons.Outlined.Delete, delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true }
}
if (asking) ConfirmDialog(
title = stringResource(R.string.games_delete_addon_title, name),
text = stringResource(R.string.games_delete_addon_body),
confirm = delete,
onConfirm = { a.onAddonDelete(target, name) },
onDismiss = { asking = false },
)
}
@Composable
private fun CloudRows(g: Library.SteamGame) {
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON } ?: return
@@ -89,6 +89,8 @@ class PairRow(
val complete: Boolean,
val installed: Boolean,
val active: Boolean,
/** A newer build of this installed pair (its build date), or null. */
val update: String? = null,
)
const val GPU_MODE_AUTO = "auto"
@@ -110,6 +112,9 @@ class GpuDriversState(
val supported: Boolean = true,
val unsupported: Boolean = false,
val auto: Boolean = true,
val powerVr: Boolean = false,
/** The selected runtime supplies DXVK for PowerVR game launches. */
val systemPowerVr: Boolean = false,
val pairs: List<PairRow> = emptyList(),
val busy: String? = null,
val percent: Int = -1,
@@ -138,6 +143,7 @@ class GpuDriversState(
class GpuDriversActions(
val onAuto: (Boolean) -> Unit = {},
val onPair: (String) -> Unit = {},
val onPairUpdate: (String) -> Unit = {},
val onRefresh: () -> Unit = {},
val onSelectLinux: (String) -> Unit = {},
val onSelectAndroid: (String) -> Unit = {},
@@ -258,7 +264,7 @@ internal fun GpuDriversBody(
modes.indices.forEach { choice(it, Modifier.weight(1f).fillMaxHeight()) }
}
when (gpu.mode) {
GPU_MODE_AUTO -> AutoBody(gpu)
GPU_MODE_AUTO -> AutoBody(gpu, actions)
GPU_MODE_PAIR -> PairBody(gpu, actions)
else -> MixBody(single, actions, slotFocus, onOpenSlot)
}
@@ -351,14 +357,26 @@ private fun RestartBanner(target: String, canRestart: Boolean, afterLater: Focus
}
@Composable
private fun AutoBody(gpu: GpuDriversState) {
private fun AutoBody(gpu: GpuDriversState, actions: GpuDriversActions) {
val colors = MaterialTheme.colorScheme
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
PanelTitle(
stringResource(if (gpu.activePair != null) R.string.gpu_auto_title else R.string.gpu_auto_builtin_title, gpu.gpuName),
stringResource(R.string.gpu_auto_reason, gpu.gpuFamily),
)
gpu.activePair?.let { p -> PanelRow(p.name, "${p.version} · ${p.detail}", selected = true, onClick = null) }
gpu.activePair?.let { p ->
// An open non-Adreno pair is rebuilt in place while it is tested: offer the newer build.
PanelRow(
p.name, "${p.version} · " + (p.update?.let { stringResource(R.string.proton_update_available, it) } ?: p.detail), selected = true,
trailing = when {
gpu.busy == p.key -> "${gpu.percent.coerceAtLeast(0)}%"
p.update != null -> stringResource(R.string.common_update)
else -> null
},
enabled = gpu.busy == null,
onClick = p.update?.let { { actions.onPairUpdate(p.key) } },
)
}
if (gpu.autoStatus.isNotEmpty()) Text(gpu.autoStatus, fontSize = 13.sp, color = colors.onSurfaceVariant)
}
}
@@ -376,15 +394,17 @@ private fun PairBody(gpu: GpuDriversState, actions: GpuDriversActions) {
fontSize = 13.sp, color = colors.onSurfaceVariant,
)
for (p in rows) PanelRow(
p.name, "${p.version} · ${p.detail}", selected = p.active,
p.name, "${p.version} · " + (p.update?.let { stringResource(R.string.proton_update_available, it) } ?: p.detail), selected = p.active,
badge = if (p.recommended) stringResource(R.string.gpu_autos_pick) else null,
trailing = when {
gpu.busy == p.key -> "${gpu.percent.coerceAtLeast(0)}%"
p.update != null -> stringResource(R.string.common_update)
p.installed -> stringResource(R.string.gpu_installed)
else -> stringResource(R.string.common_download)
},
enabled = gpu.busy == null,
onClick = { if (!p.active) actions.onPair(p.key) },
// A rebuilt open non-Adreno pair (same release, newer build) is updated in place.
onClick = { if (p.update != null) actions.onPairUpdate(p.key) else if (!p.active) actions.onPair(p.key) },
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (gpu.pairs.any { !it.suits }) FocusText(stringResource(if (showAll) R.string.gpu_hide_other else R.string.gpu_show_other), pal.signal) { showAll = !showAll }
@@ -325,6 +325,7 @@ class DrawerActions(
val onClose: () -> Unit,
val onDismissScreen: (() -> Unit)? = null,
val components: ComponentsManager.Snapshot? = null,
val systemPowerVr: Boolean = false,
val onComponentsRefresh: () -> Unit = {},
val componentCatalog: List<ComponentsManager.CatalogItem> = emptyList(),
val componentCatalogAt: Long = 0,
@@ -494,7 +495,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
if (a.pipSupported) SteamActionPill(
stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, focus.track(page, "pip"),
) { host.open = null; a.onPip() }
StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true }
if (docked) StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true }
val steamActions = a.steam && a.onSteamMenu != null && a.onQam != null
val qamInteraction = remember { MutableInteractionSource() }
var qamStartedOnPress by remember { mutableStateOf(false) }
@@ -510,7 +511,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
}
BarActions(
onMenu = { host.open = null; a.onClose() }, menuActive = true,
onMenu = if (docked) ({ host.open = null; a.onClose() }) else null, menuActive = true,
onSteam = if (steamActions) ({ host.open = null; a.onSteamMenu?.invoke() }) else null,
onQam = if (steamActions) ({
host.open = null
@@ -522,7 +523,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
qamModifier = focus.track(page, "qam"),
qamInteraction = qamInteraction,
onQamConfirm = { host.open = null; a.onQam?.invoke() },
showShortcuts = !docked,
)
if (!docked) StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true }
}
a.onAchievements?.let { show ->
DrawerAchievementsRow(a.achievementsProgress, Modifier.padding(top = if (short) 6.dp else 10.dp).then(focus.track(page, "achievements"))) {
@@ -1342,7 +1345,11 @@ private fun SelectedGameProfileGroup(host: MenuHost, a: DrawerActions, track: (S
for (component in ComponentsManager.COMPONENTS) {
val value = profile.components.getValue(component)
if (!value.inherited) {
ProfileSummaryRow(ComponentsManager.LABEL.getValue(component), profileValueLabel(value))
ProfileSummaryRow(
ComponentsManager.LABEL.getValue(component),
if (ComponentsManager.runtimeManaged(component, a.systemPowerVr)) stringResource(R.string.gpu_system_powervr)
else profileValueLabel(value),
)
}
}
if (profile.startWithoutSteam) {
@@ -1451,20 +1458,23 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
)
for (comp in ComponentsManager.COMPONENTS) {
val value = gameProfile.components.getValue(comp)
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val options: List<Pair<String?, String>> =
listOf(null to stringResource(R.string.comp_game_use_general)) +
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
if (managedDxvk) emptyList() else snap.packages.filter { it.comp == comp }.map { it.file to it.version }
DrawerStackedChoice(
host = host,
key = "game-cmp-$comp",
label = ComponentsManager.LABEL.getValue(comp),
hint = if (value.inherited) {
hint = if (managedDxvk) stringResource(R.string.cmgr_powervr_dxvk_managed) else if (value.inherited) {
stringResource(R.string.drawer_component_inherited, value.value)
} else {
null
},
options = options,
selected = gameProfile.componentFiles[comp],
enabled = !managedDxvk || gameProfile.componentFiles[comp] != null,
valueLabel = if (managedDxvk) stringResource(R.string.gpu_system_powervr) else null,
chipModifier = track("cmp-$comp"),
onPick = { file -> a.onGameComponent(gameProfile.appId, comp, file) },
)
@@ -1499,7 +1509,11 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
for (comp in ComponentsManager.COMPONENTS) {
Row(modifier = Modifier.fillMaxWidth().padding(top = 3.dp)) {
Text(ComponentsManager.LABEL.getValue(comp), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.width(96.dp))
Text(r.components.getValue(comp).inUse, fontSize = 12.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
if (ComponentsManager.runtimeManaged(comp, a.systemPowerVr)) stringResource(R.string.gpu_system_powervr)
else r.components.getValue(comp).inUse,
fontSize = 12.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
}
}
@@ -1527,16 +1541,21 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
val build = ComponentsManager.safeName(p.version)
for (comp in ComponentsManager.COMPONENTS) {
val st = view.components.getValue(comp)
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val originals = view.originals.filter { it.comp == comp }
val options = originals.map { "orig:${it.protonVersion}" to (if (it.protonVersion == build) originalLabel else stringResource(R.string.comp_original, it.protonVersion)) } +
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
if (options.isEmpty()) continue
if (options.isEmpty() && !managedDxvk) continue
val current = st.activeFile ?: "orig:$build"
val shown = options.firstOrNull { it.first == current }?.second
DrawerStackedChoice(
host, "cmp-$comp", ComponentsManager.LABEL.getValue(comp),
st.queued?.let { stringResource(R.string.comp_next_queued, it) } ?: st.inUse.takeIf { it != shown },
if (managedDxvk) stringResource(R.string.cmgr_powervr_dxvk_managed) +
(st.queued?.let { "\n" + stringResource(R.string.cmgr_powervr_dxvk_queued, it) } ?: "")
else st.queued?.let { stringResource(R.string.comp_next_queued, it) } ?: st.inUse.takeIf { it != shown },
options, current,
enabled = !managedDxvk,
valueLabel = if (managedDxvk) stringResource(R.string.gpu_system_powervr) else null,
note = if (view.inUseByGame) stringResource(R.string.comp_waits_long) else stringResource(R.string.comp_applies_long),
chipModifier = track("cmp-$comp"),
onPick = { v -> if (v != current || st.queued != null) a.onComponentSwap(p.id, comp, v) },
@@ -1649,11 +1668,11 @@ internal fun ComponentDownloadsDrawerGroup(
private fun <T> DrawerStackedChoice(
host: MenuHost, key: String, label: String, hint: String?,
options: List<Pair<T, String>>, selected: T, note: String? = null,
chipModifier: Modifier = Modifier, onPick: (T) -> Unit,
chipModifier: Modifier = Modifier, enabled: Boolean = true, valueLabel: String? = null, onPick: (T) -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val open = host.open == key
val open = host.open == key && enabled
Column(
modifier = Modifier.fillMaxWidth()
.background(if (open) pal.signal.copy(alpha = 0.10f) else Color.Transparent)
@@ -1661,7 +1680,7 @@ private fun <T> DrawerStackedChoice(
) {
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Box(modifier = Modifier.fillMaxWidth().padding(top = 6.dp)) {
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, modifier = chipModifier.fillMaxWidth()) {
ValueChip(valueLabel ?: options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled = enabled, modifier = chipModifier.fillMaxWidth()) {
host.open = if (open) null else key
}
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
@@ -104,6 +104,7 @@ internal fun WinComponentsDialog(
var slowCatalog by remember { mutableStateOf(false) }
LaunchedEffect(Unit) { kotlinx.coroutines.delay(300); slowCatalog = true }
var installed by remember { mutableStateOf(emptySet<String>()) }
var freshInstalled by remember { mutableStateOf(emptySet<String>()) }
var present by remember { mutableStateOf(emptySet<String>()) }
var selection by remember { mutableStateOf(WinComponents.selection(context, appKey)) }
val picks = selection.effective
@@ -141,9 +142,11 @@ internal fun WinComponentsDialog(
findings = found
selection = withContext(Dispatchers.IO) { WinComponents.selection(context, appKey) }
present = withContext(Dispatchers.IO) { PrefixInstalledDetector.detect(compat) }
installed = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
installed = withContext(Dispatchers.IO) { WinComponents.downloadedIds(context).toSet() }
freshInstalled = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
}
val autoDownloading by com.droiddeck.launcher.frontend.AutoComponents.downloading.collectAsState()
val repairFailures by com.droiddeck.launcher.frontend.AutoComponents.repairFailures.collectAsState()
val online = rememberOnline()
val autoChanges by com.droiddeck.launcher.frontend.AutoComponents.changes.collectAsState()
val pendingGames by com.droiddeck.launcher.frontend.AutoComponents.pendingGames.collectAsState()
@@ -152,7 +155,8 @@ internal fun WinComponentsDialog(
if (game != null) withContext(Dispatchers.IO) { com.droiddeck.launcher.frontend.AutoComponents.cachedFindings(context, appKey) }
?.let { findings = it; if (appKey !in pendingGames) findingsKnown = true }
selection = withContext(Dispatchers.IO) { WinComponents.selection(context, appKey) }
installed = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
installed = withContext(Dispatchers.IO) { WinComponents.downloadedIds(context).toSet() }
freshInstalled = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
}
fun setUser(id: String, on: Boolean) {
selection = WinComponents.Selection(selection.auto, selection.user + (id to on))
@@ -173,15 +177,25 @@ internal fun WinComponentsDialog(
}
val all = catalog.orEmpty()
val c = all[id]
if (id in installed || c == null) { setUser(id, true); return }
if (id in installed) {
setUser(id, true)
if (c != null && id !in freshInstalled) {
com.droiddeck.launcher.frontend.AutoComponents.queueRepair(context, id,
game?.let { com.droiddeck.launcher.frontend.AutoComponents.appKey(it) }, c.revision)
}
return
}
if (c == null) { setUser(id, true); return }
busyId = id; reverting = false
progress = WinComponents.Progress(id, "", WinComponents.Phase.DOWNLOAD, -1)
progress = null
coroutine.launch {
val problem = withContext(Dispatchers.IO) {
WinComponents.install(context, c, all) { p -> progress = p }
if (WinComponents.installed(context, id) != null) null
else WinComponents.install(context, c, all) { p -> progress = p }
}
progress = null
installed = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
installed = withContext(Dispatchers.IO) { WinComponents.downloadedIds(context).toSet() }
freshInstalled = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
if (problem != null) { error = problem; failed = id } else setUser(id, true)
busyId = null
}
@@ -244,6 +258,9 @@ internal fun WinComponentsDialog(
val status = when {
!online && id !in installed && support == Support.READY -> stringResource(R.string.wincomp_when_online)
id == failed && error != null -> stringResource(R.string.wincomp_failed, error.orEmpty())
id in repairFailures -> stringResource(R.string.wincomp_failed, repairFailures.getValue(id))
id in pendingComponents && id in installed && id !in freshInstalled -> stringResource(R.string.wincomp_repair_queued)
id in installed && id !in freshInstalled -> stringResource(R.string.wincomp_repair_required)
id in here && id !in picks -> stringResource(R.string.wincomp_already_here)
id in installed -> stringResource(R.string.wincomp_downloaded)
support == Support.NEEDS_INSTALLER -> stringResource(R.string.wincomp_needs_installer)
@@ -275,6 +292,12 @@ internal fun WinComponentsDialog(
modifier = (if (usable && focus != null) Modifier.focusRequester(focus) else Modifier)
.onFocusChanged { if (it.isFocused) switchFocused = true },
) { on -> toggle(id, on) }
if (id in repairFailures && c != null) {
SecondaryButton(stringResource(R.string.wincomp_retry), compact = true) {
com.droiddeck.launcher.frontend.AutoComponents.queueRepair(context, id,
game?.let { com.droiddeck.launcher.frontend.AutoComponents.appKey(it) }, c.revision)
}
}
}
fun firstUsable(ids: List<String>, focus: FocusRequester): (String) -> FocusRequester? {
val first = ids.firstOrNull { supportOf(it) == Support.READY }
@@ -74,6 +74,12 @@ object AppUpdates {
val updatable: Boolean,
val committedAt: Long = 0L,
val ciBuild: Boolean = BuildConfig.CI_BUILD,
/**
* A build of the non-Adreno test branch (Mali / Xclipse / PowerVR routes). The official
* channels carry the Adreno-only app: installing one over it drops those routes, so none is
* offered. Its updates are published on The412Banner/droiddeck-nonadreno-drivers.
*/
val nonAdrenoTest: Boolean = false,
)
enum class PreviewHistoryKind { CURRENT, BEHIND, RECENT }
@@ -125,6 +131,7 @@ object AppUpdates {
BuildConfig.VERSION_CODE,
releaseSigned,
BuildConfig.COMMIT_TIME,
nonAdrenoTest = BuildConfig.BUILD_LABEL.contains("non-adreno"),
)
fun release(catalog: Catalog, follow: Follow): Release? = when (follow.channel) {
@@ -191,6 +198,7 @@ object AppUpdates {
}
fun installBlock(r: Release, me: Installed = installed()): InstallBlock? = when {
me.nonAdrenoTest -> InstallBlock(R.string.upd_block_non_adreno_test)
r.apk == null -> InstallBlock(R.string.upd_block_no_apk)
r.apk.versionCode < me.versionCode -> InstallBlock(R.string.upd_block_version_code, r.apk.versionCode, me.versionCode)
else -> null
@@ -180,6 +180,28 @@ public final class WaylandCompositor {
public static native int nativeCompositorTid();
private static native String nativeCompositorFault();
private static native String nativeDisplayDriver();
/** Why the compositor cannot present, or "" while it can (or before the library is loaded). */
public static String compositorFault() {
try {
return nativeCompositorFault();
} catch (Throwable t) {
return "";
}
}
/** The driver that answered for the display, as it reports itself; "" when not known yet. */
public static String displayDriver() {
try {
return nativeDisplayDriver();
} catch (Throwable t) {
return "";
}
}
public static native void nativeSetHideShell(boolean hide);
public static native void nativeSetOutputRefreshRate(float hz);
+37 -5
View File
@@ -180,6 +180,7 @@
<string name="app_fex_x86">%1$s عبر FEX</string>
<string name="app_fex_not_ready">هذا البرنامج مبني لأجهزة كمبيوتر %1$s ويعمل عبر FEX، الذي لم يتم إعداده بعد. افتح Steam مرة واحدة أثناء تسجيل الدخول: سيجعله DroidDeck يُنزّل FEX وSteam Linux Runtime اللازمة، ثم يُفتح هذا البرنامج.</string>
<string name="session_proot_missing">تعذّر تنزيل proot الخاص بـ DroidDeck. تحقّق من الاتصال وحاول مرة أخرى. لم تبدأ الجلسة لأن proot الاحتياطي أبطأ من أن يصلح للعب.</string>
<string name="session_powervr_missing">تعذّر تنزيل بيئة رسومات PowerVR. تحقق من الاتصال وحاول مرة أخرى.</string>
<string name="session_directaudio_missing">تعذّر تنزيل DirectAudio، لذا يستخدم صوت الألعاب المسار الأبطأ في هذه الجلسة.</string>
<string name="session_end_program">هذا البرنامج</string>
<string name="session_end_steam_download">تعذّر تنزيل عميل Steam. قد تكون شبكتك أو VPN تحظر خوادم Steam؛ تحقّق من الاتصال وحاول مرة أخرى.</string>
@@ -593,7 +594,7 @@
<string name="perf_ram_cap_hint">يُطبَّق أثناء تشغيل عميل Steam، في جلسة Steam أو من سطح المكتب. عندما تستخدم الجلسة أكثر من هذا الحد، يُضغط Steam ثم عمليات الجلسة المدعومة الأخرى في zRAM. حد مرن: لا يُغلَق شيء، لكن قد تتقطّع الألعاب أثناء استعادة الصفحات.</string>
<string name="perf_ram_cap_unavailable">يتطلب مساحة تبديل zRAM، وهي غير متوفرة على هذا الجهاز.</string>
<string name="perf_vram_cap">حد VRAM</string>
<string name="perf_vram_cap_hint">ذاكرة الفيديو التي يُبلغ بها DXVK ألعاب Direct3D، فتخصّص للأنسجة مساحة أقل. تظل إعدادات DXVK الخاصة باللعبة هي الأولى. يسري في الجلسة التالية.</string>
<string name="perf_vram_cap_hint">يُبلّغ ألعاب Direct3D من 9 إلى 12 بميزانية ذاكرة الفيديو هذه لتشجيع تقليل استخدامها. قد تتجاوزها الألعاب؛ لا يضيف هذا ترحيل ذاكرة GPU ولا يضمن منع الانهيار بسبب نفاد الذاكرة. يسري في الجلسة التالية.</string>
<string name="perf_gpuclock">تثبيت GPU على أعلى تردد له</string>
<string name="perf_gpuclock_hint">لـ Adreno فقط. تقطّع أقل، مع استهلاك أكبر للبطارية والحرارة.</string>
<string name="perf_fixes">إصلاحات الجلسة</string>
@@ -678,6 +679,8 @@
<string name="hud_group_metrics">القراءات</string>
<string name="hud_metric_graph">مخطط زمن الإطار</string>
<string name="hud_metric_decimal">معدل الإطارات بخانة عشرية</string>
<string name="hud_metric_low1">أدنى 1%</string>
<string name="hud_metric_low01">أدنى 0.1%</string>
<string name="hud_metric_low001">أدنى 0.01%</string>
<string name="hud_metric_engine">محرك الرسومات</string>
<string name="hud_metric_gpu_model">اسم GPU</string>
@@ -823,7 +826,7 @@
<string name="setup_gpu_unsupported">GPU غير مدعوم</string>
<string name="setup_gpu_detail">%1$s · %2$s</string>
<string name="setup_gpu_untested_detail">%1$s: %2$s</string>
<string name="setup_gpu_unsupported_detail">يحتاج Steam إلى برنامج تشغيل Adreno؛ قد يعرض %1$s شاشة سوداء</string>
<string name="setup_gpu_unsupported_detail">لا تتوفر واجهة رسومات متوافقة مع %1$s. قد يعرض Steam شاشة سوداء.</string>
<string name="setup_runtime">بيئة تشغيل Linux</string>
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
<string name="setup_runtime_missing">غير مثبّت · نحو 3 GB، يُثبَّت عند أول تشغيل</string>
@@ -1130,6 +1133,7 @@
<string name="ctrl_stick_click_hint">انقر مرتين مع الاستمرار على عصا للحصول على L3 أو R3</string>
<string name="ctrl_adaptive">عصي تكيّفية</string>
<string name="ctrl_rumble">اهتزاز اللعبة</string>
<string name="ctrl_dead_zone">المنطقة الميتة لعصا التحكم</string>
<string name="ctrl_steam_button">زر Steam</string>
<string name="ctrl_qam_button">زر QAM</string>
<string name="ctrl_keyboard_button">زر لوحة المفاتيح</string>
@@ -1207,6 +1211,18 @@
<string name="games_export_gamehub">تصدير بصيغة GameHub المضغوطة…</string>
<string name="games_export_winlator">تصدير بصيغة Winlator المضغوطة…</string>
<string name="games_open_save_folder">فتح مجلد الحفظ</string>
<string name="games_import_addons">استيراد الإضافات من zip…</string>
<string name="games_open_addons_folder">فتح مجلد الإضافات</string>
<string name="games_delete_addon_title">حذف %1$s؟</string>
<string name="games_delete_addon_body">يؤدي هذا إلى حذف مجلد الإضافة. تبقى إعداداتها.</string>
<plurals name="games_addons_count">
<item quantity="zero">%1$d إضافة</item>
<item quantity="one">%1$d إضافة</item>
<item quantity="two">%1$d إضافتان</item>
<item quantity="few">%1$d إضافات</item>
<item quantity="many">%1$d إضافة</item>
<item quantity="other">%1$d إضافة</item>
</plurals>
<string name="games_never_played">لم يتم تشغيلها أبدًا</string>
<string name="games_runtime_busy_percent">بيئة التشغيل مشغولة · %1$d%%</string>
<string name="games_runtime_busy">بيئة التشغيل مشغولة</string>
@@ -1393,6 +1409,21 @@
<item quantity="many">تم استيراد %1$d ملفًا من %2$s إلى %3$s. تم نسخ ملفات الحفظ القديمة احتياطيًا إلى Download/DroidDeck/Saves/backups</item>
<item quantity="other">تم استيراد %1$d ملف من %2$s إلى %3$s. تم نسخ ملفات الحفظ القديمة احتياطيًا إلى Download/DroidDeck/Saves/backups</item>
</plurals>
<string name="main_addons_close_session">أغلِق الجلسة أولاً حتى لا تستخدم اللعبة إضافاتها أثناء الاستيراد</string>
<string name="main_addons_importing">استيراد الإضافات إلى %1$s</string>
<string name="main_addons_pick_zip">اختر ملف zip للإضافات الخاصة بـ %1$s</string>
<string name="main_addons_too_large">%1$s كبير جدًا بحيث لا يمكن استيراده</string>
<string name="main_addons_deleting">جارٍ حذف %1$s</string>
<string name="main_addons_deleted">تم حذف %1$s</string>
<string name="main_addons_none">لم يتم العثور على إضافات في %1$s</string>
<plurals name="main_addons_imported">
<item quantity="zero">تم استيراد %1$d إضافة إلى %2$s</item>
<item quantity="one">تم استيراد %1$d إضافة إلى %2$s</item>
<item quantity="two">تم استيراد %1$d إضافتين إلى %2$s</item>
<item quantity="few">تم استيراد %1$d إضافات إلى %2$s</item>
<item quantity="many">تم استيراد %1$d إضافة إلى %2$s</item>
<item quantity="other">تم استيراد %1$d إضافة إلى %2$s</item>
</plurals>
<string name="main_saves_pick_zip">اختر ملف zip لملفات حفظ %1$s</string>
<string name="main_saves_exporting">تصدير %1$s</string>
<plurals name="main_saves_exported">
@@ -1420,8 +1451,8 @@
<string name="main_wadb_unavailable">تصحيح الأخطاء اللاسلكي غير متاح</string>
<string name="main_adb_copied">تم نسخ أمر ADB</string>
<string name="main_pick_roms">اختر مجلد ROMs</string>
<string name="main_non_adreno_title">وحدة GPU ليست من نوع Adreno</string>
<string name="main_non_adreno_text">يدعم Turnip وحدات GPU من نوع Adreno. على %1$s، قد يعرض Steam شاشة سوداء. حجم التنزيل: %2$.0f MB.</string>
<string name="main_non_adreno_title">وحدة معالجة رسومات غير مدعومة</string>
<string name="main_non_adreno_text">لا تتوفر واجهة رسومات متوافقة مع %1$s. قد يعرض Steam شاشة سوداء. التنزيل: %2$.0f ميغابايت.</string>
<string name="main_install_anyway">التثبيت على أي حال</string>
<string name="main_remove_runtime_title">إزالة بيئة تشغيل Linux</string>
<string name="main_remove_runtime_text">سيؤدي هذا إلى حذف بيئة التشغيل وعميل Steam بداخلها وكل لعبة مثبَّتة فيها.</string>
@@ -2187,7 +2218,7 @@
<string name="gpuinfo_experimental">تجريبي: برامج تشغيله إصدارات اختبارية</string>
<string name="gpuinfo_a850_experimental">دعم تجريبي لـ Adreno 850: يتطلب برامج تشغيل تجريبية متوافقة للعرض والألعاب، ولم يُتحقَّق منه على هذا الجهاز</string>
<string name="gpuinfo_below_tested">أقل من العتاد المُختبَر (Adreno 725 وأحدث): قد لا يعمل</string>
<string name="gpuinfo_unsupported">غير مدعوم: يحتاج DroidDeck إلى وحدة GPU من نوع Adreno (Snapdragon)</string>
<string name="gpuinfo_unsupported">غير مدعوم: لا تتوفر واجهة رسومات متوافقة مع وحدة معالجة الرسومات هذه</string>
<string name="turnip_rate_limited">تم الوصول إلى حدّ الطلبات في GitHub - حاوِل مرة أخرى لاحقًا</string>
<string name="turnip_github_http">استجاب GitHub بـ HTTP %1$d</string>
@@ -3616,6 +3647,7 @@
<string name="game_resource_steam_cloud">Steam Cloud</string>
<string name="game_resource_steam_cloud_detail">للألعاب التي تُحفظ بياناتها في حساب Steam الخاص بك</string>
<string name="game_resource_search">البحث في الويب</string>
<string name="game_tab_addons">الإضافات</string>
<string name="game_tab_install">تثبيت</string>
<string name="game_install_location">الموقع</string>
<string name="game_install_folder">مجلد</string>
+31 -5
View File
@@ -180,6 +180,7 @@
<string name="app_fex_x86">%1$s con FEX</string>
<string name="app_fex_not_ready">Este programa está hecho para PC %1$s y se ejecuta con FEX, que aún no está listo. Abre Steam una vez con tu sesión iniciada: DroidDeck hará que descargue FEX y el Steam Linux Runtime que necesita, y después se abrirá.</string>
<string name="session_proot_missing">No se pudo descargar el proot de DroidDeck. Revisa la conexión e inténtalo de nuevo. La sesión no se inició porque el proot alternativo es demasiado lento para jugar.</string>
<string name="session_powervr_missing">No se pudo descargar el entorno gráfico de PowerVR. Revisa la conexión e inténtalo de nuevo.</string>
<string name="session_directaudio_missing">No se pudo descargar DirectAudio, así que el audio de los juegos usa la ruta más lenta en esta sesión.</string>
<string name="session_end_program">Este programa</string>
<string name="session_end_steam_download">No se pudo descargar el cliente de Steam. Es posible que tu red o VPN esté bloqueando los servidores de Steam; revisa la conexión e inténtalo de nuevo.</string>
@@ -587,7 +588,7 @@
<string name="perf_ram_cap_hint">Se aplica mientras se ejecuta el cliente de Steam, en modo Steam o desde el escritorio. Cuando la sesión usa más de esto, Steam y luego los demás procesos compatibles de la sesión se comprimen en zRAM. Es un límite flexible: no se cierra nada, pero los juegos pueden tener microcortes mientras se recuperan las páginas.</string>
<string name="perf_ram_cap_unavailable">Requiere swap de zRAM, y este dispositivo no lo tiene.</string>
<string name="perf_vram_cap">Límite de VRAM</string>
<string name="perf_vram_cap_hint">La memoria de video que DXVK informa a los juegos Direct3D, para que calculen sus texturas con menos. Los ajustes de DXVK propios de un juego siguen teniendo prioridad. Se aplica en la próxima sesión.</string>
<string name="perf_vram_cap_hint">Informa a los juegos Direct3D 9 a 12 de este presupuesto de memoria de video para reducir su uso. Los juegos pueden superarlo; no agrega paginación de GPU ni garantiza evitar fallos por falta de memoria. Se aplica en la próxima sesión.</string>
<string name="perf_gpuclock">Mantener la GPU a su reloj máximo</string>
<string name="perf_gpuclock_hint">Solo Adreno. Menos microcortes, más consumo de batería y calor.</string>
<string name="perf_fixes">Correcciones de sesión</string>
@@ -672,6 +673,8 @@
<string name="hud_group_metrics">Lecturas</string>
<string name="hud_metric_graph">Gráfico de tiempos de fotograma</string>
<string name="hud_metric_decimal">Tasa de fotogramas con decimal</string>
<string name="hud_metric_low1">1% más bajo</string>
<string name="hud_metric_low01">0.1% más bajo</string>
<string name="hud_metric_low001">0.01% más bajo</string>
<string name="hud_metric_engine">Motor gráfico</string>
<string name="hud_metric_gpu_model">Nombre de la GPU</string>
@@ -841,7 +844,7 @@
<string name="setup_gpu_unsupported">GPU no compatible</string>
<string name="setup_gpu_detail">%1$s · %2$s</string>
<string name="setup_gpu_untested_detail">%1$s: %2$s</string>
<string name="setup_gpu_unsupported_detail">Steam necesita un controlador Adreno; %1$s puede mostrar una pantalla negra</string>
<string name="setup_gpu_unsupported_detail">No hay un motor gráfico compatible disponible para %1$s. Steam puede mostrar una pantalla negra.</string>
<string name="setup_runtime">Runtime de Linux</string>
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
<string name="setup_runtime_missing">No instalado · unos 3 GB, se instala al jugar por primera vez</string>
@@ -1139,6 +1142,7 @@
<string name="ctrl_stick_click_hint">Toca dos veces y mantén un stick para L3 o R3</string>
<string name="ctrl_adaptive">Sticks adaptables</string>
<string name="ctrl_rumble">Vibración en juegos</string>
<string name="ctrl_dead_zone">Zona muerta de la palanca</string>
<string name="ctrl_steam_button">Botón Steam</string>
<string name="ctrl_qam_button">Botón QAM</string>
<string name="ctrl_keyboard_button">Botón de teclado</string>
@@ -1259,6 +1263,15 @@
<string name="games_export_gamehub">Exportar como zip de GameHub…</string>
<string name="games_export_winlator">Exportar como zip de Winlator…</string>
<string name="games_open_save_folder">Abrir carpeta de guardado</string>
<string name="games_import_addons">Importar addons desde zip…</string>
<string name="games_open_addons_folder">Abrir carpeta de addons</string>
<string name="games_delete_addon_title">¿Eliminar %1$s?</string>
<string name="games_delete_addon_body">Esto elimina la carpeta del addon. Sus ajustes se conservan.</string>
<plurals name="games_addons_count">
<item quantity="one">%1$d addon</item>
<item quantity="other">%1$d addons</item>
<item quantity="many">%1$d de addons</item>
</plurals>
<string name="games_never_played">Nunca jugado</string>
<string name="games_runtime_busy_percent">Runtime ocupado · %1$d%%</string>
<string name="games_runtime_busy">Runtime ocupado</string>
@@ -1438,6 +1451,18 @@
<item quantity="other">Se importaron %1$d archivos del %2$s en %3$s. Copia de las partidas anteriores en Download/DroidDeck/Saves/backups</item>
<item quantity="many">Se importaron %1$d archivos del %2$s en %3$s. Copia de las partidas anteriores en Download/DroidDeck/Saves/backups</item>
</plurals>
<string name="main_addons_close_session">Cierra primero la sesión para que el juego no use sus addons durante la importación</string>
<string name="main_addons_importing">Importando addons en %1$s</string>
<string name="main_addons_pick_zip">Elige un zip de addons para %1$s</string>
<string name="main_addons_too_large">%1$s es demasiado grande para importarlo</string>
<string name="main_addons_deleting">Eliminando %1$s</string>
<string name="main_addons_deleted">Se eliminó %1$s</string>
<string name="main_addons_none">No se encontraron addons en %1$s</string>
<plurals name="main_addons_imported">
<item quantity="one">Se importó %1$d addon en %2$s</item>
<item quantity="other">Se importaron %1$d addons en %2$s</item>
<item quantity="many">Se importaron %1$d de addons en %2$s</item>
</plurals>
<string name="main_saves_pick_zip">Elige un zip de partidas guardadas para %1$s</string>
<string name="main_saves_exporting">Exportando %1$s</string>
<plurals name="main_saves_exported">
@@ -1459,8 +1484,8 @@
<string name="main_wadb_unavailable">La Depuración inalámbrica no está disponible</string>
<string name="main_adb_copied">Comando ADB copiado</string>
<string name="main_pick_roms">Elige la carpeta de ROMs</string>
<string name="main_non_adreno_title">La GPU no es Adreno</string>
<string name="main_non_adreno_text">Turnip es compatible con GPU Adreno. En %1$s, Steam puede mostrar una pantalla negra. Descarga: %2$.0f MB.</string>
<string name="main_non_adreno_title">GPU no compatible</string>
<string name="main_non_adreno_text">No hay un motor gráfico compatible disponible para %1$s. Steam puede mostrar una pantalla negra. Descarga: %2$.0f MB.</string>
<string name="main_install_anyway">Instalar de todos modos</string>
<string name="main_remove_runtime_title">Eliminar el runtime de Linux</string>
<string name="main_remove_runtime_text">Esto elimina el runtime, el cliente de Steam que contiene y todos los juegos instalados en él.</string>
@@ -2168,7 +2193,7 @@
<string name="gpuinfo_experimental">Experimental: sus controladores son versiones de prueba</string>
<string name="gpuinfo_a850_experimental">Compatibilidad experimental con Adreno 850: requiere controladores experimentales de pantalla y de juegos compatibles; no verificada en este dispositivo</string>
<string name="gpuinfo_below_tested">Por debajo del hardware probado (Adreno 725 y posteriores): puede que no funcione</string>
<string name="gpuinfo_unsupported">No compatible: DroidDeck necesita una GPU Adreno (Snapdragon)</string>
<string name="gpuinfo_unsupported">No compatible: no hay un motor gráfico compatible disponible para esta GPU</string>
<string name="turnip_rate_limited">Se alcanzó el límite de solicitudes de GitHub - inténtalo más tarde</string>
<string name="turnip_github_http">GitHub respondió HTTP %1$d</string>
<string name="turnip_download_failed">Error en la descarga</string>
@@ -3481,6 +3506,7 @@
<string name="game_resource_steam_cloud">Steam Cloud</string>
<string name="game_resource_steam_cloud_detail">Para juegos con partidas guardadas en tu cuenta de Steam</string>
<string name="game_resource_search">Búsqueda web</string>
<string name="game_tab_addons">Addons</string>
<string name="game_tab_install">Instalar</string>
<string name="game_install_location">Ubicación</string>
<string name="game_install_folder">Carpeta</string>
+29 -5
View File
@@ -180,6 +180,7 @@
<string name="app_fex_x86">%1$s през FEX</string>
<string name="app_fex_not_ready">Тази програма е компилирана за %1$s компютри и се стартира през FEX, който още не е настроен. Отворете Steam веднъж, докато сте влезли: DroidDeck ще изтегли FEX и необходимата Steam Linux Runtime, след което тя ще се отвори.</string>
<string name="session_proot_missing">proot на DroidDeck не можа да бъде изтеглен. Проверете връзката и опитайте пак. Сесията не беше стартирана, защото резервният proot е твърде бавен за игра.</string>
<string name="session_powervr_missing">Графичната среда за PowerVR не можа да бъде изтеглена. Проверете връзката и опитайте отново.</string>
<string name="session_directaudio_missing">DirectAudio не можа да бъде изтеглен, затова звукът на игрите използва по-бавния път в тази сесия.</string>
<string name="session_end_program">Тази програма</string>
<string name="session_end_steam_download">Клиентът на Steam не можа да бъде изтеглен. Мрежата или VPN връзката ви може да блокира сървърите на Steam; проверете връзката и опитайте отново.</string>
@@ -585,7 +586,7 @@
<string name="perf_ram_cap_hint">Прилага се, докато клиентът на Steam работи, в режим Steam или от работния плот. Когато сесията използва повече от това, Steam и след това другите поддържани процеси на сесията се компресират в zRAM. Меко ограничение: нищо не се затваря, но игрите може да засичат, докато страниците се връщат.</string>
<string name="perf_ram_cap_unavailable">Изисква zRAM swap, който това устройство няма.</string>
<string name="perf_vram_cap">Ограничение на VRAM</string>
<string name="perf_vram_cap_hint">Видеопаметта, която DXVK отчита на игрите с Direct3D, за да планират текстури за по-малко. Собствените настройки на DXVK на играта имат предимство. Прилага се от следващата сесия.</string>
<string name="perf_vram_cap_hint">Съобщава този бюджет за видео памет на игри с Direct3D 9 до 12, за да намали използването на памет. Игрите може да го надвишат; това не добавя странициране на GPU и не гарантира защита от сривове при недостиг на памет. Прилага се от следващата сесия.</string>
<string name="perf_gpuclock">Задръжте GPU на максималната му честота</string>
<string name="perf_gpuclock_hint">Само за Adreno. По-малко засечки, по-голямо използване на батерията и повече топлина.</string>
<string name="perf_fixes">Корекции на сесията</string>
@@ -670,6 +671,8 @@
<string name="hud_group_metrics">Показания</string>
<string name="hud_metric_graph">Графика на времето на кадрите</string>
<string name="hud_metric_decimal">Честота на кадрите с десетичен знак</string>
<string name="hud_metric_low1">1% най-ниски</string>
<string name="hud_metric_low01">0.1% най-ниски</string>
<string name="hud_metric_low001">0.01% най-ниски</string>
<string name="hud_metric_engine">Графичен двигател</string>
<string name="hud_metric_gpu_model">Име на GPU</string>
@@ -811,7 +814,7 @@
<string name="setup_gpu_unsupported">GPU не се поддържа</string>
<string name="setup_gpu_detail">%1$s · %2$s</string>
<string name="setup_gpu_untested_detail">%1$s: %2$s</string>
<string name="setup_gpu_unsupported_detail">Steam изисква драйвер за Adreno; %1$s може да покаже черен екран</string>
<string name="setup_gpu_unsupported_detail">Няма съвместим графичен бекенд за %1$s. Steam може да показва черен екран.</string>
<string name="setup_runtime">Linux среда за изпълнение</string>
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
<string name="setup_runtime_missing">Не е инсталирано · около 3 GB, инсталира се при първото Play</string>
@@ -1106,6 +1109,7 @@
<string name="ctrl_stick_click_hint">Докоснете двукратно и задръжте стик за L3 или R3</string>
<string name="ctrl_adaptive">Адаптивни стикове</string>
<string name="ctrl_rumble">Вибрация от играта</string>
<string name="ctrl_dead_zone">Мъртва зона на стика</string>
<string name="ctrl_steam_button">Бутон Steam</string>
<string name="ctrl_qam_button">Бутон QAM</string>
<string name="ctrl_keyboard_button">Бутон за клавиатура</string>
@@ -1183,6 +1187,14 @@
<string name="games_export_gamehub">Експортиране като GameHub zip…</string>
<string name="games_export_winlator">Експортиране като Winlator zip…</string>
<string name="games_open_save_folder">Отваряне на папката за записи</string>
<string name="games_import_addons">Импортиране на добавки от ZIP…</string>
<string name="games_open_addons_folder">Отваряне на папката с добавки</string>
<string name="games_delete_addon_title">Да се изтрие ли %1$s?</string>
<string name="games_delete_addon_body">Това изтрива папката на добавката. Настройките ѝ се запазват.</string>
<plurals name="games_addons_count">
<item quantity="one">%1$d добавка</item>
<item quantity="other">%1$d добавки</item>
</plurals>
<string name="games_never_played">Никога не е играна</string>
<string name="games_runtime_busy_percent">Средата за изпълнение е заета · %1$d%%</string>
<string name="games_runtime_busy">Средата за изпълнение е заета</string>
@@ -1361,6 +1373,17 @@
<item quantity="one">Импортиран %1$d файл от %2$s в %3$s. Старите запазвания са архивирани в Download/DroidDeck/Saves/backups</item>
<item quantity="other">Импортирани %1$d файла от %2$s в %3$s. Старите запазвания са архивирани в Download/DroidDeck/Saves/backups</item>
</plurals>
<string name="main_addons_close_session">Затвори сесията първо, за да не използва играта добавките си по време на импортирането</string>
<string name="main_addons_importing">Импортиране на добавки в %1$s</string>
<string name="main_addons_pick_zip">Избор на ZIP файл с добавки за %1$s</string>
<string name="main_addons_too_large">%1$s е твърде голям за импортиране</string>
<string name="main_addons_deleting">Изтриване на %1$s</string>
<string name="main_addons_deleted">Изтрито: %1$s</string>
<string name="main_addons_none">Не са намерени добавки в %1$s</string>
<plurals name="main_addons_imported">
<item quantity="one">Импортирана %1$d добавка в %2$s</item>
<item quantity="other">Импортирани %1$d добавки в %2$s</item>
</plurals>
<string name="main_saves_pick_zip">Избор на ZIP файл със запазвания за %1$s</string>
<string name="main_saves_exporting">Експортиране на %1$s</string>
<plurals name="main_saves_exported">
@@ -1380,8 +1403,8 @@
<string name="main_wadb_unavailable">Безжичното отстраняване на грешки не е достъпно</string>
<string name="main_adb_copied">Командата за ADB е копирана</string>
<string name="main_pick_roms">Избор на папката ROMs</string>
<string name="main_non_adreno_title">Не е Adreno GPU</string>
<string name="main_non_adreno_text">Turnip поддържа Adreno GPU-та. На %1$s Steam може да покаже черен екран. Изтегляне: %2$.0f MB.</string>
<string name="main_non_adreno_title">Неподдържан GPU</string>
<string name="main_non_adreno_text">Няма съвместим графичен бекенд за %1$s. Steam може да показва черен екран. Изтегляне: %2$.0f MB.</string>
<string name="main_install_anyway">Инсталиране въпреки това</string>
<string name="main_remove_runtime_title">Премахване на средата на Linux</string>
<string name="main_remove_runtime_text">Това изтрива средата, клиента на Steam в нея и всяка инсталирана в нея игра.</string>
@@ -2095,7 +2118,7 @@
<string name="gpuinfo_experimental">Експериментален: драйверите му са тестови версии</string>
<string name="gpuinfo_a850_experimental">Експериментална поддръжка на Adreno 850: изисква съвместими експериментални драйвери за дисплея и игрите; не е проверена на това устройство</string>
<string name="gpuinfo_below_tested">Под тестваните устройства (Adreno 725 и по-нови): може да не работи</string>
<string name="gpuinfo_unsupported">Не се поддържа: DroidDeck изисква GPU Adreno (Snapdragon)</string>
<string name="gpuinfo_unsupported">Не се поддържа: няма съвместим графичен бекенд за този GPU</string>
<string name="turnip_rate_limited">Достигнато е ограничението на GitHub за заявки - опитай отново по-късно</string>
<string name="turnip_github_http">GitHub отговори с HTTP %1$d</string>
@@ -3472,6 +3495,7 @@
<string name="game_resource_steam_cloud">Steam Cloud</string>
<string name="game_resource_steam_cloud_detail">За игри със записи в акаунта ви в Steam</string>
<string name="game_resource_search">Търсене в мрежата</string>
<string name="game_tab_addons">Добавки</string>
<string name="game_tab_install">Инсталиране</string>
<string name="game_install_location">Местоположение</string>
<string name="game_install_folder">Папка</string>
+33 -5
View File
@@ -180,6 +180,7 @@
<string name="app_fex_x86">%1$s přes FEX</string>
<string name="app_fex_not_ready">Tento program je sestaven pro PC %1$s a běží přes FEX, který ještě není nastaven. Jednou spusťte přihlášený Steam: DroidDeck tím stáhne FEX a Steam Linux Runtime, který potřebuje, a pak se tento program otevře.</string>
<string name="session_proot_missing">Proot od DroidDeck se nepodařilo stáhnout. Zkontrolujte připojení a zkuste to znovu. Relace nebyla spuštěna, protože záložní proot je na hraní příliš pomalý.</string>
<string name="session_powervr_missing">Grafické prostředí PowerVR se nepodařilo stáhnout. Zkontrolujte připojení a zkuste to znovu.</string>
<string name="session_directaudio_missing">DirectAudio se nepodařilo stáhnout, takže zvuk her v této relaci používá pomalejší cestu.</string>
<string name="session_end_program">Tento program</string>
<string name="session_end_steam_download">Klienta Steam se nepodařilo stáhnout. Vaše síť nebo VPN možná blokuje servery Steamu; zkontrolujte připojení a zkuste to znovu.</string>
@@ -589,7 +590,7 @@
<string name="perf_ram_cap_hint">Platí, když běží klient Steam, v režimu Steam nebo z Plochy. Když relace použije víc, zkomprimuje se do zRAM Steam a poté další podporované procesy relace. Měkký limit: nic se nezavře, ale hry mohou trhat, než se stránky načtou zpět.</string>
<string name="perf_ram_cap_unavailable">Vyžaduje swap zRAM, který toto zařízení nemá.</string>
<string name="perf_vram_cap">Limit VRAM</string>
<string name="perf_vram_cap_hint">Video paměť, kterou DXVK hlásí hrám Direct3D, aby počítaly s menším rozpočtem na textury. Vlastní nastavení DXVK hry mají přednost. Použije se od příští relace.</string>
<string name="perf_vram_cap_hint">Hlásí hrám s Direct3D 9 až 12 tento rozpočet videopaměti, aby snížily její využití. Hry jej mohou překročit; nepřidává stránkování GPU ani nezaručuje ochranu před pády kvůli nedostatku paměti. Platí od příští relace.</string>
<string name="perf_gpuclock">Udržet GPU na nejvyšších taktech</string>
<string name="perf_gpuclock_hint">Jen Adreno. Méně zadrhávání, více spotřeby baterie a tepla.</string>
<string name="perf_fixes">Opravy relace</string>
@@ -674,6 +675,8 @@
<string name="hud_group_metrics">Údaje</string>
<string name="hud_metric_graph">Graf časů snímků</string>
<string name="hud_metric_decimal">Snímková frekvence s desetinným místem</string>
<string name="hud_metric_low1">1% nejnižší</string>
<string name="hud_metric_low01">0.1% nejnižší</string>
<string name="hud_metric_low001">0.01% nejnižší</string>
<string name="hud_metric_engine">Grafický engine</string>
<string name="hud_metric_gpu_model">Název GPU</string>
@@ -817,7 +820,7 @@
<string name="setup_gpu_unsupported">GPU nepodporováno</string>
<string name="setup_gpu_detail">%1$s · %2$s</string>
<string name="setup_gpu_untested_detail">%1$s: %2$s</string>
<string name="setup_gpu_unsupported_detail">Steam vyžaduje ovladač Adreno; %1$s může zobrazit černou obrazovku</string>
<string name="setup_gpu_unsupported_detail">Pro %1$s není k dispozici kompatibilní grafický backend. Steam může zobrazit černou obrazovku.</string>
<string name="setup_runtime">Běhové prostředí Linuxu</string>
<string name="setup_runtime_progress">%1$s · %2$d %%</string>
<string name="setup_runtime_missing">Nenainstalováno · přibližně 3 GB, instaluje se při prvním Play</string>
@@ -1118,6 +1121,7 @@
<string name="ctrl_stick_click_hint">Dvojitým dotykem a podržením páčky aktivujete L3 nebo R3</string>
<string name="ctrl_adaptive">Adaptivní páčky</string>
<string name="ctrl_rumble">Vibrace ve hře</string>
<string name="ctrl_dead_zone">Mrtvá zóna páčky</string>
<string name="ctrl_steam_button">Tlačítko Steam</string>
<string name="ctrl_qam_button">Tlačítko QAM</string>
<string name="ctrl_keyboard_button">Tlačítko klávesnice</string>
@@ -1195,6 +1199,16 @@
<string name="games_export_gamehub">Exportovat jako GameHub zip…</string>
<string name="games_export_winlator">Exportovat jako Winlator zip…</string>
<string name="games_open_save_folder">Otevřít složku s uloženými pozicemi</string>
<string name="games_import_addons">Importovat doplňky ze ZIP…</string>
<string name="games_open_addons_folder">Otevřít složku s doplňky</string>
<string name="games_delete_addon_title">Smazat %1$s?</string>
<string name="games_delete_addon_body">Tím se smaže složka doplňku. Jeho nastavení zůstane zachováno.</string>
<plurals name="games_addons_count">
<item quantity="one">%1$d doplněk</item>
<item quantity="few">%1$d doplňky</item>
<item quantity="many">%1$d doplňku</item>
<item quantity="other">%1$d doplňků</item>
</plurals>
<string name="games_never_played">Nikdy nehráno</string>
<string name="games_runtime_busy_percent">Runtime zaneprázdněn · %1$d%%</string>
<string name="games_runtime_busy">Runtime zaneprázdněn</string>
@@ -1377,6 +1391,19 @@
<item quantity="many">Importováno %1$d souborů z %2$s do %3$s. Staré uložené pozice byly zálohovány do Download/DroidDeck/Saves/backups</item>
<item quantity="other">Importováno %1$d souborů z %2$s do %3$s. Staré uložené pozice byly zálohovány do Download/DroidDeck/Saves/backups</item>
</plurals>
<string name="main_addons_close_session">Nejprve zavřete relaci, aby hra během importu nepoužívala své doplňky.</string>
<string name="main_addons_importing">Importování doplňků do %1$s</string>
<string name="main_addons_pick_zip">Vyberte ZIP s doplňky pro %1$s</string>
<string name="main_addons_too_large">%1$s je pro import příliš velký</string>
<string name="main_addons_deleting">Mazání: %1$s</string>
<string name="main_addons_deleted">Smazáno: %1$s</string>
<string name="main_addons_none">V %1$s nebyly nalezeny žádné doplňky</string>
<plurals name="main_addons_imported">
<item quantity="one">Importován %1$d doplněk do %2$s</item>
<item quantity="few">Importovány %1$d doplňky do %2$s</item>
<item quantity="many">Importováno %1$d doplňku do %2$s</item>
<item quantity="other">Importováno %1$d doplňků do %2$s</item>
</plurals>
<string name="main_saves_pick_zip">Vyberte ZIP s uloženou pozicí pro %1$s</string>
<string name="main_saves_exporting">Exportování %1$s</string>
<plurals name="main_saves_exported">
@@ -1400,8 +1427,8 @@
<string name="main_wadb_unavailable">Bezdrátové ladění není k dispozici</string>
<string name="main_adb_copied">Příkaz ADB zkopírován</string>
<string name="main_pick_roms">Vybrat složku ROMs</string>
<string name="main_non_adreno_title">Není GPU Adreno</string>
<string name="main_non_adreno_text">Turnip podporuje GPU Adreno. Na %1$s může Steam zobrazit černou obrazovku. Stažení: %2$.0f MB.</string>
<string name="main_non_adreno_title">Nepodporovaný GPU</string>
<string name="main_non_adreno_text">Pro %1$s není k dispozici kompatibilní grafický backend. Steam může zobrazit černou obrazovku. Ke stažení: %2$.0f MB.</string>
<string name="main_install_anyway">Přesto instalovat</string>
<string name="main_remove_runtime_title">Odstranit runtime Linuxu</string>
<string name="main_remove_runtime_text">Tím se odstraní runtime, klient Steam v něm a všechny hry v něm nainstalované.</string>
@@ -2141,7 +2168,7 @@
<string name="gpuinfo_experimental">Experimentální: jeho ovladače jsou testovací sestavení</string>
<string name="gpuinfo_a850_experimental">Experimentální podpora Adreno 850: vyžaduje kompatibilní experimentální ovladače displeje a her; na tomto zařízení neověřeno</string>
<string name="gpuinfo_below_tested">Pod testovaným hardwarem (Adreno 725 a novější): nemusí fungovat</string>
<string name="gpuinfo_unsupported">Není podporováno: DroidDeck potřebuje GPU Adreno (Snapdragon)</string>
<string name="gpuinfo_unsupported">Nepodporováno: pro tento GPU není k dispozici kompatibilní grafický backend</string>
<string name="turnip_rate_limited">Byl dosažen limit požadavků GitHubu - zkuste to později</string>
<string name="turnip_github_http">GitHub odpověděl HTTP %1$d</string>
@@ -3544,6 +3571,7 @@
<string name="game_resource_steam_cloud">Steam Cloud</string>
<string name="game_resource_steam_cloud_detail">Pro hry s uloženými pozicemi ve vašem účtu Steam</string>
<string name="game_resource_search">Hledat na webu</string>
<string name="game_tab_addons">Doplňky</string>
<string name="game_tab_install">Instalovat</string>
<string name="game_install_location">Umístění</string>
<string name="game_install_folder">Složka</string>
+29 -5
View File
@@ -180,6 +180,7 @@
<string name="app_fex_x86">%1$s via FEX</string>
<string name="app_fex_not_ready">Dette program er bygget til %1$s-pc’er og køres via FEX, som ikke er sat op endnu. Åbn Steam én gang, mens du er logget ind: DroidDeck downloader så FEX og den Steam Linux Runtime, det kræver, hvorefter dette åbner.</string>
<string name="session_proot_missing">DroidDecks proot kunne ikke downloades. Tjek forbindelsen, og prøv igen. Sessionen blev ikke startet, fordi reserve-proot er for langsom at spille på.</string>
<string name="session_powervr_missing">PowerVR-grafikmiljøet kunne ikke hentes. Tjek forbindelsen, og prøv igen.</string>
<string name="session_directaudio_missing">DirectAudio kunne ikke downloades, så spillyd bruger den langsommere vej i denne session.</string>
<string name="session_end_program">Dette program</string>
<string name="session_end_steam_download">Steam-klienten kunne ikke downloades. Dit netværk eller din VPN blokerer muligvis Steams servere; tjek forbindelsen, og prøv igen.</string>
@@ -585,7 +586,7 @@
<string name="perf_ram_cap_hint">Gælder, mens Steam-klienten kører, i Steam-tilstand eller fra skrivebordet. Når sessionen bruger mere end dette, komprimeres Steam og derefter sessionens andre understøttede processer i zRAM. En blød grænse: intet lukkes, men spil kan hakke, mens sider hentes tilbage.</string>
<string name="perf_ram_cap_unavailable">Kræver zRAM-swap, som denne enhed ikke har.</string>
<string name="perf_vram_cap">VRAM-grænse</string>
<string name="perf_vram_cap_hint">Den videohukommelse, DXVK rapporterer til Direct3D-spil, så de budgetterer teksturer til mindre. Et spils egne DXVK-indstillinger har forrang. Træder i kraft ved næste session.</string>
<string name="perf_vram_cap_hint">Rapporterer dette videohukommelsesbudget til Direct3D 9 til 12-spil for at mindske hukommelsesforbruget. Spil kan overskride det; dette tilføjer ikke GPU-paging og garanterer ikke beskyttelse mod nedbrud ved hukommelsesmangel. Gælder fra næste session.</string>
<string name="perf_gpuclock">Hold GPU’en på dens højeste clock</string>
<string name="perf_gpuclock_hint">Kun Adreno. Færre hak, mere batteribrug og varme.</string>
<string name="perf_fixes">Sessionsrettelser</string>
@@ -670,6 +671,8 @@
<string name="hud_group_metrics">Målinger</string>
<string name="hud_metric_graph">Billedtidsgraf</string>
<string name="hud_metric_decimal">Billedhastighed med decimal</string>
<string name="hud_metric_low1">1% laveste</string>
<string name="hud_metric_low01">0.1% laveste</string>
<string name="hud_metric_low001">0.01% laveste</string>
<string name="hud_metric_engine">Grafikmotor</string>
<string name="hud_metric_gpu_model">GPU-navn</string>
@@ -811,7 +814,7 @@
<string name="setup_gpu_unsupported">GPU ikke understøttet</string>
<string name="setup_gpu_detail">%1$s · %2$s</string>
<string name="setup_gpu_untested_detail">%1$s: %2$s</string>
<string name="setup_gpu_unsupported_detail">Steam kræver en Adreno-driver; %1$s kan vise en sort skærm</string>
<string name="setup_gpu_unsupported_detail">Ingen kompatibel grafikbackend er tilgængelig for %1$s. Steam kan vise en sort skærm.</string>
<string name="setup_runtime">Linux-runtime</string>
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
<string name="setup_runtime_missing">Ikke installeret · omkring 3 GB, installeres ved første Spil</string>
@@ -1106,6 +1109,7 @@
<string name="ctrl_stick_click_hint">Dobbelttryk og hold en stick nede for L3 eller R3</string>
<string name="ctrl_adaptive">Adaptive styrepinde</string>
<string name="ctrl_rumble">Spilvibration</string>
<string name="ctrl_dead_zone">Dødzone for styrepind</string>
<string name="ctrl_steam_button">Steam-knap</string>
<string name="ctrl_qam_button">QAM-knap</string>
<string name="ctrl_keyboard_button">Tastaturknap</string>
@@ -1183,6 +1187,14 @@
<string name="games_export_gamehub">Eksporter som GameHub-zip…</string>
<string name="games_export_winlator">Eksporter som Winlator-zip…</string>
<string name="games_open_save_folder">Åbn savemappe</string>
<string name="games_import_addons">Importer addons fra zip…</string>
<string name="games_open_addons_folder">Åbn addon-mappe</string>
<string name="games_delete_addon_title">Slet %1$s?</string>
<string name="games_delete_addon_body">Dette fjerner addonens mappe. Dens indstillinger bevares.</string>
<plurals name="games_addons_count">
<item quantity="one">%1$d addon</item>
<item quantity="other">%1$d addons</item>
</plurals>
<string name="games_never_played">Aldrig spillet</string>
<string name="games_runtime_busy_percent">Runtime optaget · %1$d%%</string>
<string name="games_runtime_busy">Runtime optaget</string>
@@ -1361,6 +1373,17 @@
<item quantity="one">Importerede %1$d fil fra %2$s til %3$s. Gamle gemte spil sikkerhedskopieret til Download/DroidDeck/Saves/backups</item>
<item quantity="other">Importerede %1$d filer fra %2$s til %3$s. Gamle gemte spil sikkerhedskopieret til Download/DroidDeck/Saves/backups</item>
</plurals>
<string name="main_addons_close_session">Luk sessionen først, så spillet ikke bruger sine addons under importen</string>
<string name="main_addons_importing">Importerer addons til %1$s</string>
<string name="main_addons_pick_zip">Vælg en zip med addons til %1$s</string>
<string name="main_addons_too_large">%1$s er for stor til at blive importeret</string>
<string name="main_addons_deleting">Sletter %1$s</string>
<string name="main_addons_deleted">%1$s slettet</string>
<string name="main_addons_none">Ingen addons fundet i %1$s</string>
<plurals name="main_addons_imported">
<item quantity="one">Importerede %1$d addon til %2$s</item>
<item quantity="other">Importerede %1$d addons til %2$s</item>
</plurals>
<string name="main_saves_pick_zip">Vælg en zip med gemte spil til %1$s</string>
<string name="main_saves_exporting">Eksporterer %1$s</string>
<plurals name="main_saves_exported">
@@ -1380,8 +1403,8 @@
<string name="main_wadb_unavailable">Trådløs fejlretning er ikke tilgængelig</string>
<string name="main_adb_copied">ADB-kommando kopieret</string>
<string name="main_pick_roms">Vælg ROMs-mappen</string>
<string name="main_non_adreno_title">Ikke en Adreno-GPU</string>
<string name="main_non_adreno_text">Turnip understøtter Adreno-GPU\'er. På %1$s kan Steam vise en sort skærm. Download: %2$.0f MB.</string>
<string name="main_non_adreno_title">GPU understøttes ikke</string>
<string name="main_non_adreno_text">Ingen kompatibel grafikbackend er tilgængelig for %1$s. Steam kan vise en sort skærm. Download: %2$.0f MB.</string>
<string name="main_install_anyway">Installer alligevel</string>
<string name="main_remove_runtime_title">Fjern Linux-runtime</string>
<string name="main_remove_runtime_text">Dette sletter runtime\'en, Steam-klienten i den og alle spil installeret der.</string>
@@ -2095,7 +2118,7 @@
<string name="gpuinfo_experimental">Eksperimentel: dens drivere er testversioner</string>
<string name="gpuinfo_a850_experimental">Eksperimentel Adreno 850-understøttelse: kræver kompatible eksperimentelle skærm- og spildrivere; ikke bekræftet på denne enhed</string>
<string name="gpuinfo_below_tested">Under testet hardware (Adreno 725 og nyere): kører muligvis ikke</string>
<string name="gpuinfo_unsupported">Ikke understøttet: DroidDeck kræver en Adreno (Snapdragon) GPU</string>
<string name="gpuinfo_unsupported">Understøttes ikke: ingen kompatibel grafikbackend er tilgængelig for denne GPU</string>
<string name="turnip_rate_limited">GitHubs hastighedsgrænse blev nået - forsøg igen senere</string>
<string name="turnip_github_http">GitHub svarede HTTP %1$d</string>
@@ -3472,6 +3495,7 @@
<string name="game_resource_steam_cloud">Steam Cloud</string>
<string name="game_resource_steam_cloud_detail">Til spil med gemte data på din Steam-konto</string>
<string name="game_resource_search">Websøgning</string>
<string name="game_tab_addons">Addons</string>
<string name="game_tab_install">Installer</string>
<string name="game_install_location">Placering</string>
<string name="game_install_folder">Mappe</string>
+29 -5
View File
@@ -180,6 +180,7 @@
<string name="app_fex_x86">%1$s über FEX</string>
<string name="app_fex_not_ready">Dieses Programm ist für %1$s-PCs gebaut und läuft über FEX, das noch nicht eingerichtet ist. Öffne Steam einmal, während du angemeldet bist: DroidDeck lässt es FEX und die nötige Steam Linux Runtime herunterladen, danach lässt sich das Programm öffnen.</string>
<string name="session_proot_missing">DroidDecks proot konnte nicht heruntergeladen werden. Prüfe die Verbindung und versuch es erneut. Die Sitzung wurde nicht gestartet, da das Ersatz-proot zum Spielen zu langsam ist.</string>
<string name="session_powervr_missing">Die PowerVR-Grafikumgebung konnte nicht heruntergeladen werden. Prüfe die Verbindung und versuch es erneut.</string>
<string name="session_directaudio_missing">DirectAudio konnte nicht heruntergeladen werden, daher nutzt der Spielton in dieser Sitzung den langsameren Weg.</string>
<string name="session_end_program">Dieses Programm</string>
<string name="session_end_steam_download">Der Steam-Client konnte nicht heruntergeladen werden. Dein Netzwerk oder VPN blockiert möglicherweise die Server von Steam; prüfe die Verbindung und versuche es erneut.</string>
@@ -585,7 +586,7 @@
<string name="perf_ram_cap_hint">Gilt, solange der Steam-Client läuft, im Steam-Modus oder vom Desktop aus. Verbraucht die Sitzung mehr als diesen Wert, werden Steam und danach die übrigen unterstützten Prozesse der Sitzung in zRAM komprimiert. Ein weiches Limit: Nichts wird geschlossen, aber Spiele können ruckeln, während Seiten zurückgeladen werden.</string>
<string name="perf_ram_cap_unavailable">Benötigt zRAM-Swap, den dieses Gerät nicht hat.</string>
<string name="perf_vram_cap">VRAM-Limit</string>
<string name="perf_vram_cap_hint">Der Grafikspeicher, den DXVK an Direct3D-Spiele meldet, damit sie weniger für Texturen einplanen. Eigene DXVK-Einstellungen eines Spiels haben Vorrang. Gilt ab der nächsten Sitzung.</string>
<string name="perf_vram_cap_hint">Meldet Direct3D-9-bis-12-Spielen dieses Videospeicherbudget, um den Speicherverbrauch zu senken. Spiele können es überschreiten; dies fügt kein GPU-Paging hinzu und garantiert keinen Schutz vor Abstürzen durch Speichermangel. Gilt ab der nächsten Sitzung.</string>
<string name="perf_gpuclock">GPU auf höchstem Takt halten</string>
<string name="perf_gpuclock_hint">Nur Adreno. Weniger Ruckler, mehr Akkuverbrauch und Wärme.</string>
<string name="perf_fixes">Sitzungskorrekturen</string>
@@ -670,6 +671,8 @@
<string name="hud_group_metrics">Messwerte</string>
<string name="hud_metric_graph">Frametime-Diagramm</string>
<string name="hud_metric_decimal">Bildrate mit Nachkommastelle</string>
<string name="hud_metric_low1">1%-Tiefstwert</string>
<string name="hud_metric_low01">0.1%-Tiefstwert</string>
<string name="hud_metric_low001">0.01%-Tiefstwert</string>
<string name="hud_metric_engine">Grafik-Engine</string>
<string name="hud_metric_gpu_model">GPU-Name</string>
@@ -811,7 +814,7 @@
<string name="setup_gpu_unsupported">GPU nicht unterstützt</string>
<string name="setup_gpu_detail">%1$s · %2$s</string>
<string name="setup_gpu_untested_detail">%1$s: %2$s</string>
<string name="setup_gpu_unsupported_detail">Steam benötigt einen Adreno-Treiber; %1$s zeigt möglicherweise einen schwarzen Bildschirm</string>
<string name="setup_gpu_unsupported_detail">Für %1$s ist kein kompatibles Grafik-Backend verfügbar. Steam zeigt möglicherweise einen schwarzen Bildschirm.</string>
<string name="setup_runtime">Linux-Laufzeit</string>
<string name="setup_runtime_progress">%1$s · %2$d %%</string>
<string name="setup_runtime_missing">Nicht installiert · ca. 3 GB, wird beim ersten „Spielen“ installiert</string>
@@ -1098,6 +1101,7 @@
<string name="ctrl_stick_click_hint">Doppeltippen und Stick halten für L3 oder R3</string>
<string name="ctrl_adaptive">Adaptive Sticks</string>
<string name="ctrl_rumble">Spielvibration</string>
<string name="ctrl_dead_zone">Stick-Totzone</string>
<string name="ctrl_steam_button">Steam-Taste</string>
<string name="ctrl_qam_button">QAM-Taste</string>
<string name="ctrl_keyboard_button">Tastatur-Taste</string>
@@ -1175,6 +1179,14 @@
<string name="games_export_gamehub">Als GameHub-ZIP exportieren…</string>
<string name="games_export_winlator">Als Winlator-ZIP exportieren…</string>
<string name="games_open_save_folder">Spielstandordner öffnen</string>
<string name="games_import_addons">Addons aus ZIP importieren…</string>
<string name="games_open_addons_folder">Addon-Ordner öffnen</string>
<string name="games_delete_addon_title">%1$s löschen?</string>
<string name="games_delete_addon_body">Dadurch wird der Ordner des Addons entfernt. Die Einstellungen bleiben erhalten.</string>
<plurals name="games_addons_count">
<item quantity="one">%1$d Addon</item>
<item quantity="other">%1$d Addons</item>
</plurals>
<string name="games_never_played">Nie gespielt</string>
<string name="games_runtime_busy_percent">Laufzeit beschäftigt · %1$d %%</string>
<string name="games_runtime_busy">Laufzeit beschäftigt</string>
@@ -1353,6 +1365,17 @@
<item quantity="one">%1$d Datei aus %2$s in %3$s importiert. Alte Spielstände gesichert unter Download/DroidDeck/Saves/backups</item>
<item quantity="other">%1$d Dateien aus %2$s in %3$s importiert. Alte Spielstände gesichert unter Download/DroidDeck/Saves/backups</item>
</plurals>
<string name="main_addons_close_session">Schließe zuerst die Sitzung, damit das Spiel seine Addons während des Imports nicht verwendet</string>
<string name="main_addons_importing">Addons werden in %1$s importiert</string>
<string name="main_addons_pick_zip">Addon-ZIP für %1$s auswählen</string>
<string name="main_addons_too_large">%1$s ist zu groß zum Importieren</string>
<string name="main_addons_deleting">%1$s wird gelöscht</string>
<string name="main_addons_deleted">%1$s gelöscht</string>
<string name="main_addons_none">Keine Addons in %1$s gefunden</string>
<plurals name="main_addons_imported">
<item quantity="one">%1$d Addon in %2$s importiert</item>
<item quantity="other">%1$d Addons in %2$s importiert</item>
</plurals>
<string name="main_saves_pick_zip">Spielstand-ZIP für %1$s auswählen</string>
<string name="main_saves_exporting">Export von %1$s</string>
<plurals name="main_saves_exported">
@@ -1372,8 +1395,8 @@
<string name="main_wadb_unavailable">Debugging über WLAN ist nicht verfügbar</string>
<string name="main_adb_copied">ADB-Befehl kopiert</string>
<string name="main_pick_roms">ROMs-Ordner auswählen</string>
<string name="main_non_adreno_title">Keine Adreno-GPU</string>
<string name="main_non_adreno_text">Turnip unterstützt Adreno-GPUs. Auf %1$s zeigt Steam eventuell einen schwarzen Bildschirm. Download: %2$.0f MB.</string>
<string name="main_non_adreno_title">Nicht unterstützte GPU</string>
<string name="main_non_adreno_text">Für %1$s ist kein kompatibles Grafik-Backend verfügbar. Steam zeigt möglicherweise einen schwarzen Bildschirm. Download: %2$.0f MB.</string>
<string name="main_install_anyway">Trotzdem installieren</string>
<string name="main_remove_runtime_title">Linux-Laufzeit entfernen</string>
<string name="main_remove_runtime_text">Dadurch werden die Laufzeit, der Steam-Client darin und alle dort installierten Spiele gelöscht.</string>
@@ -2087,7 +2110,7 @@
<string name="gpuinfo_experimental">Experimentell: Die Treiber sind Test-Builds</string>
<string name="gpuinfo_a850_experimental">Experimentelle Adreno-850-Unterstützung: erfordert kompatible experimentelle Anzeige- und Spieltreiber; auf diesem Gerät nicht geprüft</string>
<string name="gpuinfo_below_tested">Unter der getesteten Hardware (Adreno 725 und neuer): läuft eventuell nicht</string>
<string name="gpuinfo_unsupported">Nicht unterstützt: DroidDeck braucht eine Adreno-GPU (Snapdragon)</string>
<string name="gpuinfo_unsupported">Nicht unterstützt: Für diese GPU ist kein kompatibles Grafik-Backend verfügbar</string>
<string name="turnip_rate_limited">Das Rate-Limit von GitHub wurde erreicht - versuche es später erneut</string>
<string name="turnip_github_http">GitHub antwortete mit HTTP %1$d</string>
@@ -3472,6 +3495,7 @@
<string name="game_resource_steam_cloud">Steam Cloud</string>
<string name="game_resource_steam_cloud_detail">Für Spiele mit Speicherständen in deinem Steam-Konto</string>
<string name="game_resource_search">Websuche</string>
<string name="game_tab_addons">Addons</string>
<string name="game_tab_install">Installieren</string>
<string name="game_install_location">Speicherort</string>
<string name="game_install_folder">Ordner</string>
+29 -5
View File
@@ -180,6 +180,7 @@
<string name="app_fex_x86">%1$s μέσω FEX</string>
<string name="app_fex_not_ready">Αυτό το πρόγραμμα είναι χτισμένο για υπολογιστές %1$s και εκτελείται μέσω FEX, το οποίο δεν έχει ρυθμιστεί ακόμα. Ανοίξτε το Steam μία φορά ενώ είστε συνδεδεμένοι: το DroidDeck κάνει λήψη του FEX και του Steam Linux Runtime που χρειάζεται, και μετά αυτό ανοίγει.</string>
<string name="session_proot_missing">Δεν ήταν δυνατή η λήψη του proot του DroidDeck. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά. Η συνεδρία δεν ξεκίνησε, επειδή το εναλλακτικό proot είναι πολύ αργό για παιχνίδι.</string>
<string name="session_powervr_missing">Δεν ήταν δυνατή η λήψη του γραφικού περιβάλλοντος PowerVR. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά.</string>
<string name="session_directaudio_missing">Δεν ήταν δυνατή η λήψη του DirectAudio, οπότε ο ήχος των παιχνιδιών χρησιμοποιεί την πιο αργή διαδρομή σε αυτή τη συνεδρία.</string>
<string name="session_end_program">Αυτό το πρόγραμμα</string>
<string name="session_end_steam_download">Δεν ήταν δυνατή η λήψη του πελάτη Steam. Το δίκτυο ή το VPN σας ίσως αποκλείει τους διακομιστές του Steam· ελέγξτε τη σύνδεση και δοκιμάστε ξανά.</string>
@@ -585,7 +586,7 @@
<string name="perf_ram_cap_hint">Ισχύει όσο τρέχει ο πελάτης Steam, σε λειτουργία Steam ή από την επιφάνεια εργασίας. Όταν η συνεδρία χρησιμοποιεί περισσότερη, το Steam και έπειτα οι άλλες υποστηριζόμενες διεργασίες της συνεδρίας συμπιέζονται στη zRAM. Ήπιο όριο: τίποτα δεν κλείνει, αλλά τα παιχνίδια μπορεί να κολλάνε όσο επιστρέφουν οι σελίδες.</string>
<string name="perf_ram_cap_unavailable">Απαιτεί zRAM swap, που δεν υπάρχει σε αυτή τη συσκευή.</string>
<string name="perf_vram_cap">Όριο VRAM</string>
<string name="perf_vram_cap_hint">Η μνήμη βίντεο που αναφέρει το DXVK στα παιχνίδια Direct3D, ώστε να προγραμματίζουν υφές για λιγότερη. Οι δικές ρυθμίσεις DXVK του παιχνιδιού υπερισχύουν. Εφαρμόζεται στην επόμενη συνεδρία.</string>
<string name="perf_vram_cap_hint">Αναφέρει αυτόν τον προϋπολογισμό μνήμης βίντεο σε παιχνίδια Direct3D 9 έως 12 για να μειωθεί η χρήση μνήμης. Τα παιχνίδια μπορεί να τον υπερβούν· δεν προσθέτει σελιδοποίηση GPU ούτε εγγυάται προστασία από σφάλματα έλλειψης μνήμης. Ισχύει από την επόμενη συνεδρία.</string>
<string name="perf_gpuclock">Διατήρηση της GPU στη μέγιστη συχνότητά της</string>
<string name="perf_gpuclock_hint">Μόνο Adreno. Λιγότερα κολλήματα, μεγαλύτερη χρήση μπαταρίας και θερμότητα.</string>
<string name="perf_fixes">Διορθώσεις συνεδρίας</string>
@@ -670,6 +671,8 @@
<string name="hud_group_metrics">Μετρήσεις</string>
<string name="hud_metric_graph">Γράφημα χρόνου καρέ</string>
<string name="hud_metric_decimal">Ρυθμός καρέ με δεκαδικό</string>
<string name="hud_metric_low1">1% χαμηλότερα</string>
<string name="hud_metric_low01">0.1% χαμηλότερα</string>
<string name="hud_metric_low001">0.01% χαμηλότερα</string>
<string name="hud_metric_engine">Μηχανή γραφικών</string>
<string name="hud_metric_gpu_model">Όνομα GPU</string>
@@ -811,7 +814,7 @@
<string name="setup_gpu_unsupported">Η GPU δεν υποστηρίζεται</string>
<string name="setup_gpu_detail">%1$s · %2$s</string>
<string name="setup_gpu_untested_detail">%1$s: %2$s</string>
<string name="setup_gpu_unsupported_detail">Το Steam απαιτεί πρόγραμμα οδήγησης Adreno· το %1$s μπορεί να εμφανίσει μαύρη οθόνη</string>
<string name="setup_gpu_unsupported_detail">Δεν υπάρχει συμβατό υποσύστημα γραφικών για %1$s. Το Steam μπορεί να εμφανίσει μαύρη οθόνη.</string>
<string name="setup_runtime">Runtime Linux</string>
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
<string name="setup_runtime_missing">Δεν έχει εγκατασταθεί · περίπου 3 GB, εγκαθίσταται στο πρώτο Play</string>
@@ -1106,6 +1109,7 @@
<string name="ctrl_stick_click_hint">Πατήστε δύο φορές και κρατήστε έναν μοχλό για L3 ή R3</string>
<string name="ctrl_adaptive">Προσαρμοστικοί μοχλοί</string>
<string name="ctrl_rumble">Κραδασμός παιχνιδιού</string>
<string name="ctrl_dead_zone">Νεκρή ζώνη μοχλού</string>
<string name="ctrl_steam_button">Κουμπί Steam</string>
<string name="ctrl_qam_button">Κουμπί QAM</string>
<string name="ctrl_keyboard_button">Κουμπί πληκτρολογίου</string>
@@ -1183,6 +1187,14 @@
<string name="games_export_gamehub">Εξαγωγή ως zip GameHub…</string>
<string name="games_export_winlator">Εξαγωγή ως zip Winlator…</string>
<string name="games_open_save_folder">Άνοιγμα φακέλου αποθήκευσης</string>
<string name="games_import_addons">Εισαγωγή προσθέτων από zip…</string>
<string name="games_open_addons_folder">Άνοιγμα φακέλου προσθέτων</string>
<string name="games_delete_addon_title">Διαγραφή του %1$s;</string>
<string name="games_delete_addon_body">Ο φάκελος του πρόσθετου θα διαγραφεί. Οι ρυθμίσεις του παραμένουν.</string>
<plurals name="games_addons_count">
<item quantity="one">%1$d πρόσθετο</item>
<item quantity="other">%1$d πρόσθετα</item>
</plurals>
<string name="games_never_played">Δεν έχει παιχτεί ποτέ</string>
<string name="games_runtime_busy_percent">Το runtime είναι απασχολημένο · %1$d%%</string>
<string name="games_runtime_busy">Το runtime είναι απασχολημένο</string>
@@ -1361,6 +1373,17 @@
<item quantity="one">Έγινε εισαγωγή %1$d αρχείου από το %2$s στο %3$s. Τα παλιά αρχεία αποθήκευσης κρατήθηκαν ως αντίγραφο ασφαλείας στο Download/DroidDeck/Saves/backups</item>
<item quantity="other">Έγινε εισαγωγή %1$d αρχείων από το %2$s στο %3$s. Τα παλιά αρχεία αποθήκευσης κρατήθηκαν ως αντίγραφο ασφαλείας στο Download/DroidDeck/Saves/backups</item>
</plurals>
<string name="main_addons_close_session">Κλείστε πρώτα τη συνεδρία, ώστε το παιχνίδι να μη χρησιμοποιεί τα πρόσθετά του κατά την εισαγωγή</string>
<string name="main_addons_importing">Εισαγωγή προσθέτων στο %1$s</string>
<string name="main_addons_pick_zip">Επιλέξτε ένα zip προσθέτων για το %1$s</string>
<string name="main_addons_too_large">Το %1$s είναι πολύ μεγάλο για εισαγωγή</string>
<string name="main_addons_deleting">Γίνεται διαγραφή του %1$s</string>
<string name="main_addons_deleted">Το %1$s διαγράφηκε</string>
<string name="main_addons_none">Δεν βρέθηκαν πρόσθετα στο %1$s</string>
<plurals name="main_addons_imported">
<item quantity="one">Έγινε εισαγωγή %1$d προσθέτου στο %2$s</item>
<item quantity="other">Έγινε εισαγωγή %1$d προσθέτων στο %2$s</item>
</plurals>
<string name="main_saves_pick_zip">Επιλέξτε ένα zip αποθηκευμένων αρχείων για το %1$s</string>
<string name="main_saves_exporting">Εξαγωγή %1$s</string>
<plurals name="main_saves_exported">
@@ -1380,8 +1403,8 @@
<string name="main_wadb_unavailable">Ο ασύρματος εντοπισμός σφαλμάτων δεν είναι διαθέσιμος</string>
<string name="main_adb_copied">Η εντολή ADB αντιγράφηκε</string>
<string name="main_pick_roms">Επιλέξτε τον φάκελο ROMs</string>
<string name="main_non_adreno_title">Δεν είναι GPU Adreno</string>
<string name="main_non_adreno_text">Το Turnip υποστηρίζει GPU Adreno. Σε %1$s, το Steam ίσως εμφανίσει μαύρη οθόνη. Λήψη: %2$.0f MB.</string>
<string name="main_non_adreno_title">Μη υποστηριζόμενη GPU</string>
<string name="main_non_adreno_text">Δεν υπάρχει συμβατό υποσύστημα γραφικών για %1$s. Το Steam μπορεί να εμφανίσει μαύρη οθόνη. Λήψη: %2$.0f MB.</string>
<string name="main_install_anyway">Εγκατάσταση παρόλα αυτά</string>
<string name="main_remove_runtime_title">Κατάργηση του Linux runtime</string>
<string name="main_remove_runtime_text">Αυτό διαγράφει το runtime, τον πελάτη Steam μέσα σε αυτό και κάθε παιχνίδι που είναι εγκατεστημένο εκεί.</string>
@@ -2095,7 +2118,7 @@
<string name="gpuinfo_experimental">Πειραματικό: τα προγράμματα οδήγησής του είναι δοκιμαστικές εκδόσεις</string>
<string name="gpuinfo_a850_experimental">Πειραματική υποστήριξη Adreno 850: απαιτεί συμβατά πειραματικά προγράμματα οδήγησης οθόνης και παιχνιδιών· δεν έχει επαληθευτεί σε αυτή τη συσκευή</string>
<string name="gpuinfo_below_tested">Κάτω από το δοκιμασμένο υλικό (Adreno 725 και νεότερα): ίσως να μην εκτελεστεί</string>
<string name="gpuinfo_unsupported">Δεν υποστηρίζεται: το DroidDeck χρειάζεται GPU Adreno (Snapdragon)</string>
<string name="gpuinfo_unsupported">Δεν υποστηρίζεται: δεν υπάρχει συμβατό υποσύστημα γραφικών για αυτήν την GPU</string>
<string name="turnip_rate_limited">Το όριο ρυθμού του GitHub ξεπεράστηκε - δοκιμάστε ξανά αργότερα</string>
<string name="turnip_github_http">Το GitHub απάντησε με HTTP %1$d</string>
@@ -3472,6 +3495,7 @@
<string name="game_resource_steam_cloud">Steam Cloud</string>
<string name="game_resource_steam_cloud_detail">Για παιχνίδια με αποθηκεύσεις στον λογαριασμό σας Steam</string>
<string name="game_resource_search">Αναζήτηση στον ιστό</string>
<string name="game_tab_addons">Πρόσθετα</string>
<string name="game_tab_install">Εγκατάσταση</string>
<string name="game_install_location">Τοποθεσία</string>
<string name="game_install_folder">Φάκελος</string>
Loaded 100 of 360 files, more files were not shown because too many files have changed in this diff. Show more