Merge #570 (PowerVR + Xclipse system Vulkan) into the non-Adreno test branch

# Conflicts:
#	.github/workflows/build.yml
#	app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
#	app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
#	tools/build_local.sh
#	tools/dxvk/build.sh
#	tools/linuxfs/overlay/usr/local/bin/droiddeck-session
#	tools/release/runtime_inputs.py
#	tools/tests/test_runtime_inputs.py
This commit is contained in:
The412Banner committed 2026-10-12 18:34:02 -04:00
commit 56dc433673
104 files changed
+7206 -206

No files matched your search

@@ -14,6 +14,7 @@ add_library(droiddeckwayland SHARED
src/waylandcomp_jni.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
@@ -24,6 +25,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>
@@ -3556,6 +3556,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);
/* gamescope's Wayland backend refuses a seat older than 8. */
wl_global_create(display, &wl_seat_interface, 9, NULL, bind_seat);
wl_global_create(display, &banner_desktop_v1_interface, 1, NULL, bind_desktop);
@@ -77,3 +77,6 @@ extern volatile int g_no_render_node; /* DROIDDECK_WAYLAND_NO_RENDER_NODE */
/* ---- wl_dmabuf.c */
COMPOSITOR_INTERNAL extern dev_t g_main_device; /* the render node clients are told to allocate on */
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);
@@ -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
+154 -35
View File
@@ -3,6 +3,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 "framegen_bridge.h"
@@ -35,6 +36,7 @@ struct vkp_image {
int in_general; /* shm images: moved from PREINITIALIZED to GENERAL */
VkFormat fmt;
int sampled; /* created with SAMPLED usage: the alpha pass can read it */
AHardwareBuffer *android_buffer;
};
static ANativeWindow *g_window; /* the window frames go to; compositor thread only */
@@ -45,6 +47,7 @@ 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;
/* One command buffer + acquire/render-done semaphore pair per PRESENT. A scene frame is one
@@ -486,7 +489,7 @@ static int dev_init(void) {
g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops);
/* Verify the dmabuf-import extensions are present, and log any that are missing. */
const char *dev_exts[7] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME, "VK_KHR_external_memory_fd",
const char *dev_exts[9] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME, "VK_KHR_external_memory_fd",
"VK_EXT_external_memory_dma_buf", "VK_EXT_image_drm_format_modifier",
"VK_KHR_image_format_list", NULL, NULL};
uint32_t n_dev_exts = 5;
@@ -507,6 +510,13 @@ static int dev_init(void) {
* back to waiting for them on the CPU without it. */
const int want_sem_fd = has_ext(exts, ne, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME);
if (want_sem_fd) dev_exts[n_dev_exts++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
const int want_ahb = !g_library_name &&
has_ext(exts, ne, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME) &&
has_ext(exts, ne, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
if (want_ahb) {
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;
}
free(exts);
float prio = 1.0f;
@@ -533,6 +543,9 @@ static int dev_init(void) {
}
vk_loader_load_device(g_dev);
g_vk.GetDeviceQueue(g_dev, g_qfam, 0, &g_queue);
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};
@@ -977,7 +990,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) {
@@ -1135,6 +1239,7 @@ void vkp_image_destroy(struct vkp_image *img) {
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);
}
@@ -1184,11 +1289,14 @@ static int draw_to_scene_blit(const struct vkp_draw *d, int scene_w, int scene_h
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);
}
@@ -1657,13 +1765,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,
@@ -1730,6 +1836,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
drawn++;
}
release_external_client_draws(cmd, draws, n);
int ngen = 0;
VkImage gens[VKP_FG_MAX_GENERATIONS] = {VK_NULL_HANDLE};
VkImage result = scene_img;
@@ -1947,7 +2054,7 @@ int vkp_map_draw(const struct vkp_draw *d, int out[8]) {
* owned by the "foreign" queue family (the game's driver / the display) between our uses, so each
* use acquires them and the destination is released back for the display to read. */
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;
}
@@ -1960,17 +2067,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) { /* shm image: host-written, GENERAL */
if (!src_external) { /* shm image: host-written, GENERAL */
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;
@@ -1984,8 +2095,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,
@@ -2020,7 +2132,7 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
static struct vkp_image *g_rb; /* the readback image, kept for the next shape */
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; }
@@ -2061,11 +2173,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,
@@ -2083,16 +2199,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},
/* the client's buffer goes back to it */
{.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);
@@ -2196,13 +2316,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,
@@ -2243,6 +2361,7 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
if (vkp_effects_active()) vkp_effects_set_formats(VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM);
}
release_external_client_draws(cmd, draws, n);
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,
@@ -2,6 +2,7 @@
#define VK_PRESENT_H
#include <stdint.h>
#include <android/native_window.h>
#include <android/hardware_buffer.h>
/*
* Android-surface render backend for the embedded Wayland compositor.
* Owns a Turnip VkDevice + a swapchain on the SurfaceView's ANativeWindow. Each
@@ -39,6 +40,11 @@ void vkp_output_size(int *w, int *h);
struct vkp_image;
/* android_wlegl clients share complete Android buffer handles, not guessed DMA-BUF layouts.
* The image retains its own AHB reference. Call only from the compositor thread. */
int vkp_android_buffer_supported(void);
struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer);
/* DRM format modifiers this backend knows the memory layout of (both single-plane on Adreno):
* LINEAR, and QCOM_COMPRESSED = UBWC (drm_fourcc.h: fourcc_mod_code(QCOM = 0x05, 1)). */
#define VKP_MOD_LINEAR 0x0000000000000000ULL
@@ -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");
}
@@ -16,6 +16,7 @@ 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
@@ -64,7 +65,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
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),
)
var androidRows by mutableStateOf<List<DriverRow>>(emptyList())
var androidSelected by mutableStateOf("")
@@ -77,7 +79,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(
@@ -110,6 +112,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
/** One line for the settings row that opens this: "Auto · WinNative · Balanced". */
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 label = activity.getString(if (mode == SessionPrefs.GPU_DRIVERS_AUTO) R.string.common_auto else R.string.drivers_manual)
return active?.let { activity.getString(R.string.drivers_summary, label, it) } ?: label
}
@@ -152,6 +155,13 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
fun ensureAuto(force: Boolean) {
mode = SessionPrefs.gpuDriverMode(activity)
if (mode != SessionPrefs.GPU_DRIVERS_AUTO || pairBusy != null || releaseChecking) return
if (gpu.family == GpuInfo.Family.POWERVR) {
// 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
}
if (!force && autoCheckedThisProcess) return
autoCheckedThisProcess = true
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
@@ -1677,7 +1677,7 @@ class MainActivity : ComponentActivity() {
// The runtime draws with Turnip, an Adreno driver: on Mali, Xclipse or PowerVR the
// compositor gets no usable Vulkan device and a session is sound over a black screen.
// Said before the download, not after it; the user may still go ahead.
if (installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()) { showNonAdreno = release; return }
if (installed == null && !com.droiddeck.launcher.core.DeviceSupport.graphicsAvailable()) { showNonAdreno = release; return }
install(release)
}
@@ -1689,7 +1689,7 @@ class MainActivity : ComponentActivity() {
showPhantomGate = true
return false
}
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.graphicsAvailable()
if (warn && available != null) { showNonAdreno = available; return false }
startActivity(intent)
return true
@@ -588,6 +588,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
)
SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions(
steam = SessionState.mode == SessionService.MODE_STEAM,
systemPowerVr = com.droiddeck.launcher.gpu.SystemVulkanDriver.usesDefault(
SessionPrefs.linuxDriver(this@SessionActivity)),
title = if (SessionState.mode == SessionService.MODE_RUN)
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_title_game) else null,
isHomeApp = isHomeApp,
@@ -1288,8 +1290,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// the evdev codes we inject.
FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb"))
// Turnip, not the system Adreno driver: importing the dma-bufs gamescope commits needs
// VK_EXT_image_drm_format_modifier, which the system driver does not implement.
// Adreno imports dma-bufs with Turnip. PowerVR uses its system Vulkan driver
// to import the Android hardware buffers supplied by the runtime bridge.
val turnip = TurnipDriver(this)
val driverId = if (CompositorHost.isStarted) null else turnip.install()
@@ -6,6 +6,8 @@ import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.util.Log
import com.droiddeck.launcher.gpu.DeviceInfo
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
import com.droiddeck.launcher.gpu.TurnipDriver
@@ -103,7 +105,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}" })
@@ -124,16 +130,20 @@ object DeviceReport {
com.droiddeck.launcher.gpu.TurnipReleases.cached(context)))?.let { " (recommended pair: $it)" } ?: ""))
val turnip = TurnipDriver(context)
val androidChoice = SessionPrefs.androidDriver(context)
k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> ${turnip.autoId()}" else androidChoice)
k(" name / version", "${turnip.displayName(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)} ${turnip.driverVersion(if (androidChoice.isEmpty()) turnip.autoId() else androidChoice)}".trim())
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)
@@ -3,21 +3,20 @@ 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
/**
* Whether this device can draw a Linux session at all.
*
* The runtime draws with Turnip, an Adreno driver. On Mali, Xclipse and PowerVR the compositor
* gets no usable Vulkan device and a session comes up as sound over a black screen - a failure
* with nothing in it to read. The app cannot fix that, so it says so before the download rather
* than after it. Adreno is recognised by what only Qualcomm's stack has: the KGSL node, or the
* vendor's own Vulkan driver at its usual path.
*/
/** Whether this device has a graphics backend the runtime can use. Adreno uses Turnip;
* PowerVR uses its vendor Vulkan driver through the bundled runtime bridge. Other GPU families
* still need a supported backend before a session can display frames. */
object DeviceSupport {
fun adreno(): Boolean =
File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists()
fun graphicsAvailable(): Boolean = graphicsAvailable(adreno(), SystemVulkanDriver.isAvailable())
internal fun graphicsAvailable(adreno: Boolean, powerVrReady: Boolean): Boolean = adreno || powerVrReady
/** The chip as the device names it, for the card that explains the refusal. */
fun gpuName(context: Context): String {
val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN } else null
@@ -157,10 +157,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"
}
}
@@ -93,7 +93,7 @@ object DriverPairs {
* the 710/720/722, and upstream Banners-Turnip for the rest. Null when nothing fits (not Adreno).
*/
fun recommendedKey(gpu: GpuInfo, pairs: List<DriverPair>): String? = when (gpu.family) {
Family.NOT_ADRENO -> null
Family.NOT_ADRENO, Family.POWERVR -> null
Family.A8XX -> if (gpu.model == 840) newestDdTurnip(pairs) ?: WN_BALANCED else WN_BALANCED
Family.A7XX_LOW -> BANNER_710
Family.A7XX -> if (gpu.oneUi8Gen2) BANNER_ONEUI else BANNER
@@ -35,6 +35,7 @@ data class GpuInfo(
A6XX("Adreno 6xx"),
/** An Adreno whose model KGSL does not give: treated as the newest family it could be. */
ADRENO_UNKNOWN("Adreno"),
POWERVR("PowerVR"),
NOT_ADRENO("Not an Adreno GPU");
/** [label] in the app's language: the Adreno families are names, the rest is words. */
@@ -56,15 +57,22 @@ data class GpuInfo(
val supportText: String
get() = when (support) {
Support.TESTED -> "Supported"
Support.UNTESTED -> 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 -> "System PowerVR driver: compatibility varies by device"
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"
}
/** [supportText] in the app's language. */
fun supportText(context: Context): String = context.getString(when (support) {
Support.TESTED -> R.string.gpuinfo_supported
Support.UNTESTED -> if (family == Family.A7XX_LOW) R.string.gpuinfo_experimental else R.string.gpuinfo_below_tested
Support.UNTESTED -> when (family) {
Family.POWERVR -> R.string.gpuinfo_powervr
Family.A7XX_LOW -> R.string.gpuinfo_experimental
else -> R.string.gpuinfo_below_tested
}
Support.UNSUPPORTED -> R.string.gpuinfo_unsupported
})
@@ -94,10 +102,17 @@ data class GpuInfo(
fromPlatform > 0 -> "platform"
else -> ""
}
val family = familyOf(adreno, model)
val family = familyOf(adreno, model, SystemVulkanDriver.isPowerVr())
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
}
!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,
@@ -122,7 +137,8 @@ data class GpuInfo(
""
}
internal fun familyOf(adreno: Boolean, model: Int): Family = when {
internal fun familyOf(adreno: Boolean, model: Int, powerVr: Boolean = false): Family = when {
!adreno && powerVr -> Family.POWERVR
!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;
/**
* The Vulkan driver a session draws with inside the runtime: in Steam mode the native client's
@@ -17,7 +21,8 @@ import java.util.List;
* these are glibc processes, that one is bionic.
*
* <p>"" (the default) means the driver the runtime was built with, at
* {@code usr/lib/libvulkan_freedreno.so} inside it - nothing is set and nothing is touched.
* {@code usr/lib/libvulkan_freedreno.so} on Adreno, or the bundled bridge to the system
* PowerVR driver.
* Otherwise the value is an imported driver's id ({@link LinuxVulkanDriverManager}), and the
* session is handed that driver's ICD manifest in {@code BL_VK_DRIVER}: the session script points
* the Vulkan loader at it with {@code VK_DRIVER_FILES} after checking both the manifest and the
@@ -47,30 +52,44 @@ public final class LinuxVulkanDriver {
}
/**
* Label for a stored value. An id that is no longer installed says so - the launch path falls
* back to the runtime's own driver for it.
* Label for a stored value. Missing imports fall back to the runtime on Adreno;
* PowerVR requires another explicit selection or Auto before launching.
*/
public static String optionLabel(Context context, String value) {
if (value == null || value.isEmpty()) return "Runtime default (built into the runtime)";
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);
if (!m.isInstalled(value)) return value + " (imported, missing - uses the runtime default)";
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)";
}
/**
* The ICD manifest path to hand the session, or null to leave the runtime's own driver alone.
* An id whose import is gone resolves to null rather than failing the launch.
* A missing import uses the runtime's own driver on Adreno. PowerVR fails clearly instead:
* its system backend needs environment setup that an explicit import does not receive.
*/
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;
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 + ")");
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;
}
}
@@ -0,0 +1,254 @@
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.FileUtils;
import com.droiddeck.launcher.core.TarZst;
import java.io.File;
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 {
private static final String ASSET = "hybris/runtime.tzst";
/** 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. */
public static String hal() {
for (String path : HALS) if (new File(path).isFile()) 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");
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 {
if (!TarZst.extractAsset(context, ASSET, 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;
try (BufferedReader input = new BufferedReader(new InputStreamReader(
context.getAssets().open("hybris/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());
}
}
@@ -25,9 +25,10 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* The Vulkan driver the in-app compositor runs on. It has to be Turnip: the system Adreno driver
* The Vulkan driver the in-app compositor runs on. Adreno uses Turnip: the system Adreno driver
* does not implement VK_EXT_image_drm_format_modifier, so importing the dma-bufs gamescope hands
* over fails and the session renders nothing. Two builds ship in the apk, one per Adreno
* over fails and the session renders nothing. PowerVR uses the system driver and Android hardware
* buffers instead. Two Turnip builds ship in the apk, one per Adreno
* generation, and the GPU decides which is unpacked - unless the user has imported an AdrenoTools
* zip of their own and chosen it, which then wins.
*
@@ -314,6 +315,7 @@ public final class TurnipDriver {
* and falls through, so a stale preference never blocks a session.
*/
private String choose() {
SessionPrefs.ensurePowerVrAutoDrivers(context);
String chosen = SessionPrefs.androidDriver(context);
if (chosen != null && !chosen.isEmpty()) {
if (BUNDLED.contains(chosen)) {
@@ -339,6 +341,7 @@ public final class TurnipDriver {
if (forced.startsWith("a8")) return DRIVER_A8XX;
if (forced.startsWith("a7")) return DRIVER_A7XX;
}
if (SystemVulkanDriver.isPowerVr()) return null;
String model = gpuModel();
Log.i(TAG, "gpu model: " + (model == null ? "unknown" : model));
if (model != null) {
@@ -6,6 +6,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;
@@ -200,6 +201,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, "/dev/urandom:/dev/random");
bind(cmd, "/proc/self/fd:/dev/fd");
bind(cmd, "/proc/self/fd/0:/dev/stdin");
@@ -277,7 +285,11 @@ public final class LinuxRuntime {
bind(cmd, fake.getPath() + ":" + entry[1]);
}
}
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) {
@@ -288,6 +300,30 @@ public final class LinuxRuntime {
return specs;
}
/**
* Tensor's render node is accessible directly, but Android denies listing its parent
* directory. libdrm enumerates that directory even when given the device number. Expose
* the real node through a listable private directory; retain its real sysfs identity.
*/
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();
// Keep only this node listable even if a previous boot assigned a different minor.
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");
}
/**
* An app process may not open {@code /dev/dri} - the nodes exist but are labelled
* {@code graphics_device}, which stock policy grants surfaceflinger and not us - yet libdrm and
@@ -8,6 +8,7 @@ import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.GameEnvironment
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
@@ -219,9 +220,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) }
@@ -694,6 +699,16 @@ object ComponentsManager {
return PreparedLaunchState(lines.toString(), keep)
}
/** DXVK is supplied at game launch by the selected system PowerVR runtime. */
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) }
}
// ------------------------------------------------------------------ actions
/** Applies a package now, or queues it when a game is running on that Proton. Returns what happened. */
@@ -701,6 +716,7 @@ object ComponentsManager {
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))
@@ -724,6 +740,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) }
@@ -750,7 +767,9 @@ object ComponentsManager {
}
/** Runs the swaps that waited for a game to close. Cheap when nothing is queued. */
fun applyQueued(context: Context): List<String> = synchronized(lock) {
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()
@@ -762,6 +781,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")
@@ -27,6 +27,23 @@ object OrphanReaper {
fun release(pid: Int) { kept.remove(pid) }
/** Signal 0 checks ownership/liveness without sending a signal, even when /proc is unreadable. */
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): Int {
val me = android.os.Process.myPid()
val uid = android.os.Process.myUid()
@@ -53,6 +53,7 @@ object SessionFiles {
"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",
@@ -129,6 +130,10 @@ object SessionFiles {
"usr/local/lib/mangoapp/libtraceevent.so.1",
"usr/local/lib/mangoapp/libtracefs.so.1",
).map { it to it }
// Samsung Xclipse driver workarounds (tools/linuxfs/xclipse-layer), the Vulkan layer
// SystemVulkanDriver enables on that GPU.
val xclipse = listOf("libVkLayer_droiddeck_xclipse.so", "VkLayer_droiddeck_xclipse.json")
.map { "usr/local/lib/droiddeck-xclipse/$it" }
// What the Windows components installer reads .msi packages with (tools/msitools).
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" } +
@@ -140,7 +145,7 @@ object SessionFiles {
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
) + mangoapp + listOf("comet", "GalaxyCommunication.exe", "update-permissions.exe", "LICENSE", "version").map { "usr/local/lib/droiddeck-comet/$it" to "usr/local/lib/droiddeck-comet/$it" } + msitools.map { it to it } + fexPreloads).filter { (asset, _) ->
) + mangoapp + xclipse.map { it to it } + listOf("comet", "GalaxyCommunication.exe", "update-permissions.exe", "LICENSE", "version").map { "usr/local/lib/droiddeck-comet/$it" to "usr/local/lib/droiddeck-comet/$it" } + msitools.map { it to it } + fexPreloads).filter { (asset, _) ->
val dir = asset.substringBeforeLast('/')
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
}
@@ -8,6 +8,8 @@ import com.droiddeck.launcher.core.CpuAllocationDefaults
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.gpu.ScreenEffects
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.gpu.TurnipDriver
import org.json.JSONObject
/** The in-session switches: the HUD and how the on-screen controls decide to appear. */
@@ -216,6 +218,15 @@ object SessionPrefs {
p.edit().putString("gpuDriverMode", if (chosen) GPU_DRIVERS_MANUAL else GPU_DRIVERS_AUTO).apply()
}
/** Also called by direct session launches, which may never open the driver settings. */
@JvmStatic
fun ensurePowerVrAutoDrivers(context: Context) = 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()
}
/** Drivers Auto downloaded: the only ones it removes when a newer pair replaces them. */
fun gpuAutoInstalled(context: Context): Set<String> =
prefs(context).getStringSet("gpuAutoInstalled", emptySet()).orEmpty()
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.session
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
@@ -318,6 +319,7 @@ class SessionService : Service() {
// ── The session ─────────────────────────────────────────────────────────────────────────
private fun runSession(gen: Int) {
SessionPrefs.ensurePowerVrAutoDrivers(this)
SessionTerminal.clear()
try {
LinuxRuntime.writeAccounts(this)
@@ -331,7 +333,17 @@ class SessionService : Service() {
val sessionRoot = LinuxRuntime.sessionRoot(this).apply { mkdirs() }
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
killStragglers()
SessionFiles.stage(this, root)
try {
if (SystemVulkanDriver.usesDefault(SessionPrefs.linuxDriver(this))) {
SystemVulkanDriver.prepare(this)
pruneSystemVulkanRuntime()
}
SessionFiles.stage(this, root)
} catch (error: Exception) {
Log.e(TAG, "Could not prepare the session graphics runtime", error)
stopSession(-1)
return
}
com.droiddeck.launcher.agent.AgentGuest.reset(this)
// The compat tool asks for an Epic game's sign-in code at every launch, the client's Play button included.
com.droiddeck.launcher.stores.gog.GogComet.begin()
@@ -617,6 +629,9 @@ class SessionService : Service() {
// import falls back to. One driver for every session: the driver's shader cache is keyed on
// its build, and with one per mode every emulator compiled its shaders twice.
val linuxDriverId = SessionPrefs.linuxDriver(this)
if (SystemVulkanDriver.usesDefault(linuxDriverId)) {
SystemVulkanDriver.addEnvironment(this, guest)
}
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
// Turnip's own debug switches, for the runtime's driver and everything on it. The file in
@@ -1477,6 +1492,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) {
mainHandler.post {
if (stoppedGen != sessionGen || SessionState.running) {
@@ -1594,9 +1615,11 @@ class SessionService : Service() {
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
killGuestLeftovers()
pruneSystemVulkanRuntime()
finishSessionStop(status, stoppedGen)
}, "session-teardown").start()
} else {
Thread({ pruneSystemVulkanRuntime() }, "system-vulkan-prune").start()
Thread({ com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession); finishSessionStop(status, stoppedGen) }, "gog-session-stop").start()
}
}
@@ -502,9 +502,10 @@ fun ComponentsPage(
val active = gpu.activePair
InUseBar(
queued = gpu.busy != null,
sentence = (active?.let { "${it.name} ${it.version}" } ?: gpu.activeBundle ?: stringResource(R.string.gpu_builtin))
sentence = (active?.let { "${it.name} ${it.version}" } ?: gpu.activeBundle ?: stringResource(if (gpu.systemPowerVr) R.string.gpu_system_powervr else R.string.gpu_builtin))
.let { if (gpu.auto) stringResource(R.string.gpu_bar_auto, it) else it },
note = if (gpu.busy != null) (if (gpu.percent >= 0) "${gpu.percent}%" else "…")
else if (gpu.systemPowerVr) stringResource(R.string.gpu_auto_system_hint)
else gpu.autoStatus.ifEmpty { if (active != null || gpu.activeBundle != null) "" else gpu.pairs.firstOrNull { it.recommended }?.let { stringResource(R.string.gpu_recommended_for, it.name) } ?: stringResource(R.string.gpu_refresh_hint) },
)
}
@@ -515,17 +516,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),
)
}
}
}
}
@@ -552,11 +563,11 @@ fun ComponentsPage(
GPU_TAB -> {
val autoKey = "gpu:auto"
ChoiceLine(
stringResource(R.string.common_auto), stringResource(R.string.gpu_auto_keeps), gpu.auto, removable = false,
stringResource(R.string.common_auto), stringResource(if (gpu.powerVr) R.string.gpu_auto_system_hint else R.string.gpu_auto_keeps), gpu.auto, removable = false,
modifier = Modifier.focusRequester(firstRow).trackRow(autoKey, rowsAt),
onSelect = {
if (gpu.auto) return@ChoiceLine
ask(autoKey, right, ctx.getString(R.string.gpu_use_title, ctx.getString(R.string.common_auto)), ctx.getString(R.string.gpu_auto_hint), ctx.getString(R.string.common_use), false, ctx.getString(R.string.common_auto)) {
ask(autoKey, right, ctx.getString(R.string.gpu_use_title, ctx.getString(R.string.common_auto)), ctx.getString(if (gpu.powerVr) R.string.gpu_auto_system_hint else R.string.gpu_auto_hint), ctx.getString(R.string.common_use), false, ctx.getString(R.string.common_auto)) {
gpuActions.onAuto(true); flyHome(autoKey, GPU_TAB)
}
},
@@ -601,16 +612,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)
@@ -712,14 +724,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)
}
@@ -867,6 +884,7 @@ fun ComponentsPage(
protonChoice = gameProtonChoice,
packages = snapshot?.packages.orEmpty(),
componentChoices = gameComponents,
systemPowerVr = gpu.systemPowerVr,
componentMenu = gameComponentMenu,
protonMenu = gameProtonMenu,
fexMenu = fexMenu,
@@ -1010,11 +1028,11 @@ fun ComponentsPage(
/** The Installed rows of one component layer for the Proton the page shows. */
@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(
@@ -1023,7 +1041,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)
}
}
@@ -1062,11 +1080,12 @@ private fun Stack(
LayerCard(
title = LayerTitle(l),
value = when (l) {
GPU_TAB -> if (gpu.auto) auto else gpu.activePair?.name ?: gpu.activeBundle ?: auto
GPU_TAB -> if (gpu.systemPowerVr) stringResource(R.string.gpu_system_powervr) else if (gpu.auto) auto else gpu.activePair?.name ?: gpu.activeBundle ?: 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()) },
@@ -1137,7 +1156,7 @@ private fun LayerCard(
/** What is in use for the layer: a dot (green, or amber while a change waits), a sentence, and a note or Cancel. */
@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(
@@ -1146,7 +1165,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)
}
@@ -1182,6 +1201,7 @@ private fun GameComponentOverrides(
protonChoice: ProtonDefault.GameChoice?,
packages: List<ComponentsManager.Package>,
componentChoices: Map<String, String>,
systemPowerVr: Boolean,
componentMenu: String?,
protonMenu: Boolean,
fexMenu: Boolean,
@@ -1273,6 +1293,7 @@ private fun GameComponentOverrides(
}
GamePackageRow(
comp = "dxvk",
runtimeManaged = ComponentsManager.runtimeManaged("dxvk", systemPowerVr),
packages = packages,
selectedFile = componentChoices["dxvk"],
open = componentMenu == "dxvk",
@@ -1337,13 +1358,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),
@@ -1351,18 +1375,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)
@@ -1492,13 +1516,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()
@@ -1508,8 +1532,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)) {
@@ -1519,7 +1543,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)
}
@@ -84,6 +84,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(),
/** The pair key being installed, and how far along (-1 = unknown). */
val busy: String? = null,
@@ -263,6 +263,8 @@ class DrawerActions(
val onClose: () -> Unit,
/** Games tab: every Proton with what it uses; null until first read. */
val components: ComponentsManager.Snapshot? = null,
/** DXVK is supplied by the selected system PowerVR runtime. */
val systemPowerVr: Boolean = false,
/** Re-reads the Protons (and runs swaps that waited for a game to close). */
val onComponentsRefresh: () -> Unit = {},
/** Installed games available for profile inspection in the session drawer. */
@@ -1049,7 +1051,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) {
@@ -1151,20 +1157,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) },
)
@@ -1200,7 +1209,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,
)
}
}
}
@@ -1228,17 +1241,22 @@ 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),
// The box already shows the choice: only say more when there is more to say.
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) },
@@ -1259,11 +1277,11 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
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)
@@ -1271,7 +1289,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 ->
+4 -4
View File
@@ -588,7 +588,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; %1$s 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>
@@ -1107,10 +1107,10 @@
<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_title">GPU no compatible</string>
<!-- %1$s is the GPU's name, %2$.0f the download size in MB -->
<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_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>
@@ -1934,7 +1934,7 @@
<string name="gpuinfo_supported">Compatible</string>
<string name="gpuinfo_experimental">Experimental: sus controladores son versiones de prueba</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>
<!-- Driver downloads and imports -->
<string name="turnip_rate_limited">Se alcanzó el límite de solicitudes de GitHub - inténtalo más tarde</string>
+1 -1
View File
@@ -471,7 +471,7 @@
<string name="setup_gpu_unsupported">GPU non pris en charge</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 nécessite un pilote Adreno ; %1$s peut afficher un écran noir.</string>
<string name="setup_gpu_unsupported_detail">Aucun moteur graphique compatible n’est disponible ; %1$s peut afficher un écran noir.</string>
<string name="setup_runtime">Environnement d\'exécution Linux</string>
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
<string name="setup_runtime_missing">Non installé · Environ 3 Go, installé lors du premier lancement d\'un jeu</string>
+4 -4
View File
@@ -584,7 +584,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では画面が真っ暗になる可能性があります。</string>
<string name="setup_runtime">Linux実行環境</string>
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
<string name="setup_runtime_missing">未インストール · 約3GB、初回ゲーム起動時にインストール</string>
@@ -1089,10 +1089,10 @@
<string name="main_wadb_unavailable">ワイヤレスデバッグは利用できません</string>
<string name="main_adb_copied">ADBコマンドをコピーしました</string>
<string name="main_pick_roms">ROMフォルダを選択</string>
<string name="main_non_adreno_title">Adreno GPUではありません</string>
<string name="main_non_adreno_title">サポート対象外のGPU</string>
<!-- %1$s is the GPU's name, %2$.0f the download size in MB -->
<string name="main_non_adreno_text">TurnipはAdreno GPUをサポートしています。%1$sでは、Steamの画面が真っ暗になる可能性があります。ダウンロード:%2$.0f MB。</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>
@@ -1894,7 +1894,7 @@
<string name="gpuinfo_supported">サポート対象</string>
<string name="gpuinfo_experimental">実験的:ドライバーはテストビルドです</string>
<string name="gpuinfo_below_tested">テスト済みハードウェア(Adreno 725以降)未満:動作しない可能性があります</string>
<string name="gpuinfo_unsupported">サポート対象外:DroidDeckにはAdreno(Snapdragon)GPUが必要です</string>
<string name="gpuinfo_unsupported">サポート対象外:このGPUで利用できる互換グラフィックスバックエンドがありません</string>
<!-- Driver downloads and imports -->
<string name="turnip_rate_limited">GitHubのレート制限に達しました。後でもう一度お試しください</string>
+4 -4
View File
@@ -584,7 +584,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에서 화면이 검게 표시될 수 있습니다.</string>
<string name="setup_runtime">Linux 런타임</string>
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
<string name="setup_runtime_missing">설치되지 않음 · 약 3GB, 처음 \"Steam 실행\" 시 설치</string>
@@ -1089,10 +1089,10 @@
<string name="main_wadb_unavailable">무선 디버깅을 사용할 수 없습니다</string>
<string name="main_adb_copied">ADB 명령이 복사되었습니다</string>
<string name="main_pick_roms">ROM 폴더 선택</string>
<string name="main_non_adreno_title">Adreno GPU가 아님</string>
<string name="main_non_adreno_title">지원되지 않는 GPU</string>
<!-- %1$s is the GPU's name, %2$.0f the download size in MB -->
<string name="main_non_adreno_text">Turnip은 Adreno GPU를 지원합니다. %1$s에서는 Steam 화면이 검게 표시될 수 있습니다. 다운로드: %2$.0f MB.</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>
@@ -1894,7 +1894,7 @@
<string name="gpuinfo_supported">지원됨</string>
<string name="gpuinfo_experimental">실험적: 드라이버가 테스트 빌드입니다</string>
<string name="gpuinfo_below_tested">테스트된 하드웨어(Adreno 725 이상)보다 낮음: 실행되지 않을 수 있습니다</string>
<string name="gpuinfo_unsupported">지원되지 않음: DroidDeck에는 Adreno(Snapdragon) GPU가 필요합니다</string>
<string name="gpuinfo_unsupported">지원되지 않음: 이 GPU에서 사용할 수 있는 호환 그래픽 백엔드가 없습니다</string>
<!-- Driver downloads and imports -->
<string name="turnip_rate_limited">GitHub 요청 한도에 도달했습니다. 나중에 다시 시도하세요</string>
+1 -1
View File
@@ -546,7 +546,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 возможен черный экран.</string>
<string name="setup_runtime">Среда выполнения Linux</string>
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
<string name="setup_runtime_missing">Не установлено · около 3 ГБ, устанавливается при первом запуске игры</string>
+4 -4
View File
@@ -584,7 +584,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 可能显示黑屏</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>
@@ -1089,10 +1089,10 @@
<string name="main_wadb_unavailable">无线调试不可用</string>
<string name="main_adb_copied">已复制 ADB 命令</string>
<string name="main_pick_roms">选择 ROM 文件夹</string>
<string name="main_non_adreno_title">不是 Adreno GPU</string>
<string name="main_non_adreno_title">不受支持的 GPU</string>
<!-- %1$s is the GPU's name, %2$.0f the download size in MB -->
<string name="main_non_adreno_text">Turnip 支持 Adreno GPU。在 %1$s 上,Steam 可能显示黑屏。需下载:%2$.0f MB。</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>
@@ -1894,7 +1894,7 @@
<string name="gpuinfo_supported">受支持</string>
<string name="gpuinfo_experimental">实验性:其驱动为测试构建</string>
<string name="gpuinfo_below_tested">低于已测试的硬件(Adreno 725 及更新):可能无法运行</string>
<string name="gpuinfo_unsupported">不受支持:DroidDeck 需要 Adreno(骁龙)GPU</string>
<string name="gpuinfo_unsupported">不受支持:没有适用于此 GPU 的兼容图形后端</string>
<!-- Driver downloads and imports -->
<string name="turnip_rate_limited">已达到 GitHub 的请求频率限制 — 请稍后重试</string>
+4 -4
View File
@@ -584,7 +584,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 可能會出現黑畫面</string>
<string name="setup_runtime">Linux 運行環境</string>
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
<string name="setup_runtime_missing">未安裝 · 約 3 GB,首次開啟 Steam 時安裝</string>
@@ -1089,10 +1089,10 @@
<string name="main_wadb_unavailable">無法使用無線偵錯</string>
<string name="main_adb_copied">已複製 ADB 指令</string>
<string name="main_pick_roms">選擇 ROM 資料夾</string>
<string name="main_non_adreno_title">不是 Adreno GPU</string>
<string name="main_non_adreno_title">不受支援的 GPU</string>
<!-- %1$s is the GPU's name, %2$.0f the download size in MB -->
<string name="main_non_adreno_text">Turnip 支援 Adreno GPU。在 %1$s 上,Steam 可能會出現黑畫面。下載大小:%2$.0f MB。</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>
@@ -1894,7 +1894,7 @@
<string name="gpuinfo_supported">受支援</string>
<string name="gpuinfo_experimental">實驗性:其驅動程式為測試版本</string>
<string name="gpuinfo_below_tested">低於已測試的硬件(Adreno 725 或更新):可能無法執行</string>
<string name="gpuinfo_unsupported">不受支援:DroidDeck 需要 Adreno (Snapdragon) GPU</string>
<string name="gpuinfo_unsupported">不受支援:沒有適用於此 GPU 的兼容圖形後端</string>
<!-- Driver downloads and imports -->
<string name="turnip_rate_limited">已達 GitHub 的速率限制 - 請稍後再試</string>
+4 -4
View File
@@ -584,7 +584,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 可能出現黑畫面。</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>
@@ -1089,10 +1089,10 @@
<string name="main_wadb_unavailable">無法使用無線偵錯</string>
<string name="main_adb_copied">已複製 ADB 指令</string>
<string name="main_pick_roms">選擇 ROM 資料夾</string>
<string name="main_non_adreno_title">不是 Adreno GPU</string>
<string name="main_non_adreno_title">不受支援的 GPU</string>
<!-- %1$s is the GPU's name, %2$.0f the download size in MB -->
<string name="main_non_adreno_text">Turnip 支援 Adreno GPU。在 %1$s 上,Steam 可能會出現黑畫面。下載大小:%2$.0f MB。</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>
@@ -1894,7 +1894,7 @@
<string name="gpuinfo_supported">受支援</string>
<string name="gpuinfo_experimental">實驗性:其驅動程式為測試版本</string>
<string name="gpuinfo_below_tested">低於已測試的硬體(Adreno 725 及更新機型):可能無法執行</string>
<string name="gpuinfo_unsupported">不受支援:DroidDeck 需要 Adreno(Snapdragon)GPU</string>
<string name="gpuinfo_unsupported">不受支援:沒有適用於此 GPU 的相容圖形後端</string>
<!-- Driver downloads and imports -->
<string name="turnip_rate_limited">已達 GitHub 速率限制 - 請稍後再試</string>
+10 -4
View File
@@ -651,7 +651,7 @@
<string name="setup_gpu_unsupported">GPU not supported</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 needs an Adreno driver; %1$s may show a black screen</string>
<string name="setup_gpu_unsupported_detail">No compatible graphics backend is available; %1$s may show a black screen</string>
<string name="setup_runtime">Linux runtime</string>
<string name="setup_runtime_progress">%1$s · %2$d%%</string>
<string name="setup_runtime_missing">Not installed · about 3 GB, installed on first Play</string>
@@ -1183,9 +1183,9 @@
<string name="main_wadb_unavailable">Wireless debugging is unavailable</string>
<string name="main_adb_copied">ADB command copied</string>
<string name="main_pick_roms">Choose the ROMs folder</string>
<string name="main_non_adreno_title">Not an Adreno GPU</string>
<string name="main_non_adreno_title">Unsupported GPU</string>
<!-- %1$s is the GPU's name, %2$.0f the download size in MB -->
<string name="main_non_adreno_text">Turnip supports Adreno GPUs. On %1$s, Steam may show a black screen. Download: %2$.0f MB.</string>
<string name="main_non_adreno_text">No compatible graphics backend is available for %1$s. Steam may show a black screen. Download: %2$.0f MB.</string>
<string name="main_install_anyway">Install anyway</string>
<string name="main_remove_runtime_title">Remove Linux runtime</string>
<string name="main_remove_runtime_text">This deletes the runtime, the Steam client inside it, and every game installed there.</string>
@@ -1902,10 +1902,16 @@
<!-- GPU support line -->
<string name="gpuinfo_not_adreno">Not an Adreno GPU</string>
<string name="gpuinfo_powervr">System PowerVR driver: compatibility varies by device</string>
<string name="gpu_system_powervr">System PowerVR</string>
<string name="gpu_auto_system_hint">Uses the built-in drivers for this GPU</string>
<string name="drivers_powervr_builtin">The system PowerVR driver is selected for the runtime and display.</string>
<string name="cmgr_powervr_dxvk_queued">Queued: %1$s (waiting for a different runtime driver)</string>
<string name="cmgr_powervr_dxvk_managed">DXVK is provided by the system PowerVR runtime. Other DXVK packages can be stored but are not applied with this driver.</string>
<string name="gpuinfo_supported">Supported</string>
<string name="gpuinfo_experimental">Experimental: its drivers are test builds</string>
<string name="gpuinfo_below_tested">Below tested hardware (Adreno 725 and newer): it may not run</string>
<string name="gpuinfo_unsupported">Not supported: DroidDeck needs an Adreno (Snapdragon) GPU</string>
<string name="gpuinfo_unsupported">Not supported: no compatible graphics backend is available for this GPU</string>
<!-- Driver downloads and imports -->
<string name="turnip_rate_limited">GitHub\'s rate limit was hit - try again later</string>
@@ -0,0 +1,14 @@
package com.droiddeck.launcher.core
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class DeviceSupportTest {
@Test fun runtimeDownloadAcceptsOnlyRecognizedGraphicsBackends() {
assertTrue(DeviceSupport.graphicsAvailable(adreno = true, powerVrReady = false))
assertTrue(DeviceSupport.graphicsAvailable(adreno = false, powerVrReady = true))
// A PowerVR HAL without usable DRM access also reaches this unavailable case.
assertFalse(DeviceSupport.graphicsAvailable(adreno = false, powerVrReady = false))
}
}
@@ -0,0 +1,13 @@
package com.droiddeck.launcher.gpu
import org.junit.Assert.assertEquals
import org.junit.Test
class DeviceInfoTest {
@Test fun builtinLabelsDistinguishPowerVrFromTurnipAndGenericSystemVulkan() {
assertEquals("System PowerVR", DeviceInfo.builtinDriverLabel(powerVr = true, runtime = true))
assertEquals("System PowerVR", DeviceInfo.builtinDriverLabel(powerVr = true, runtime = false))
assertEquals("the runtime's own Turnip", DeviceInfo.builtinDriverLabel(powerVr = false, runtime = true))
assertEquals("System Vulkan", DeviceInfo.builtinDriverLabel(powerVr = false, runtime = false))
}
}
@@ -42,6 +42,23 @@ class DriverPairsTest {
assertEquals(GpuInfo.Support.UNSUPPORTED, gpu(0, adreno = false).support)
}
@Test
fun powerVrUsesItsOwnFamilyWithoutClaimingAllModelsAreTested() {
assertEquals(Family.POWERVR, GpuInfo.familyOf(false, 0, powerVr = true))
assertEquals(Family.NOT_ADRENO, GpuInfo.familyOf(false, 0, powerVr = false))
assertEquals(Family.A7XX, GpuInfo.familyOf(true, 740, powerVr = true))
val powerVr = GpuInfo("PowerVR", 0, Family.POWERVR, "", false)
assertEquals(GpuInfo.Support.UNTESTED, powerVr.support)
assertNull("PowerVR never downloads an Adreno driver pair", DriverPairs.recommendedKey(powerVr, emptyList()))
val pairs = DriverPairs.from(TurnipReleases.Check(
listOf(asset("Turnip-r4.zip", "r4", false, DriverPairs.BANNER),
asset("Turnip-r4-Linux.zip", "r4", true, DriverPairs.BANNER)),
emptyList(), emptyList(), 0L,
))
assertFalse(pairs.single().suits(powerVr))
assertNull(DriverPairs.recommendedKey(powerVr, pairs))
}
@Test
fun autoPicksWinNativeBalancedOn8xxAndBannersElsewhere() {
assertEquals(DriverPairs.WN_BALANCED, DriverPairs.recommendedKey(gpu(830), emptyList()))
@@ -0,0 +1,109 @@
package com.droiddeck.launcher.gpu
import java.io.File
import java.nio.file.Files
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class SystemVulkanPruningTest {
@get:Rule val temporary = TemporaryFolder()
@Test fun completedReplacementCollectsOnlyManagedOldDirectories() {
val base = temporary.newFolder("system_vulkan")
val current = completeRuntime(base, "a".repeat(64))
val old = completeRuntime(base, "b".repeat(64))
val stage = abandonedStage(base)
val unrelated = File(base, "notes").apply { mkdir(); File(this, "keep").writeText("keep") }
SystemVulkanDriver.pruneUnused(current, true)
assertEquals("current ICD", File(current, "icd.json").readText())
assertTrue(File(current, "run-proton.py").canExecute())
assertFalse(old.exists())
assertFalse(stage.exists())
assertEquals("keep", File(unrelated, "keep").readText())
}
@Test fun aSurvivingGuestKeepsOldVersionsButNotAbandonedStages() {
val base = temporary.newFolder("system_vulkan")
val current = completeRuntime(base, "a".repeat(64))
val old = completeRuntime(base, "b".repeat(64))
val stage = abandonedStage(base)
SystemVulkanDriver.pruneUnused(current, false)
assertTrue(current.isDirectory)
assertTrue(old.isDirectory)
assertFalse(stage.exists())
SystemVulkanDriver.pruneUnused(current, true)
assertFalse("collect the old version once guests stop", old.exists())
}
@Test fun failedReplacementPreservesThePreviousGoodRuntime() {
val base = temporary.newFolder("system_vulkan")
val current = File(base, "a".repeat(64))
val old = completeRuntime(base, "b".repeat(64))
val stage = abandonedStage(base)
SystemVulkanDriver.pruneUnused(current, true)
assertTrue("missing replacement", old.isDirectory)
assertFalse(stage.exists())
current.mkdir()
File(current, "icd.json").writeText("incomplete")
SystemVulkanDriver.pruneUnused(current, true)
assertEquals("current ICD", File(old, "icd.json").readText())
}
@Test fun deletingOldRuntimeDoesNotFollowItsSymlinks() {
val base = temporary.newFolder("system_vulkan")
val current = completeRuntime(base, "a".repeat(64))
val old = File(base, "b".repeat(64)).apply { mkdir() }
val outside = temporary.newFolder("outside")
val sentinel = File(outside, "keep").apply { writeText("keep") }
Files.createSymbolicLink(File(old, "outside").toPath(), outside.toPath())
SystemVulkanDriver.pruneUnused(current, true)
assertFalse(old.exists())
assertEquals("keep", sentinel.readText())
}
@Test fun linkedBaseOrCurrentRuntimePreventsCleanup() {
val base = temporary.newFolder("system_vulkan")
val old = completeRuntime(base, "b".repeat(64))
val current = File(base, "a".repeat(64))
Files.createSymbolicLink(current.toPath(), old.toPath())
SystemVulkanDriver.pruneUnused(current, true)
assertTrue(old.isDirectory)
Files.delete(current.toPath())
completeRuntime(base, current.name)
val alias = File(temporary.root, "alias")
Files.createSymbolicLink(alias.toPath(), base.toPath())
SystemVulkanDriver.pruneUnused(File(alias, current.name), true)
assertTrue(old.isDirectory)
}
private fun abandonedStage(base: File) =
File(base, ".stage-12345678-1234-1234-1234-123456789abc").apply { mkdir(); File(this, "partial").writeText("partial") }
private fun completeRuntime(base: File, version: String): File {
val directory = File(base, version).apply { mkdir() }
val components = listOf(
"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",
) + listOf("x32", "x64").flatMap { arch ->
listOf("d3d8", "d3d9", "d3d10core", "d3d11", "dxgi").map { "dxvk/$arch/$it.dll" }
}
components.forEach { path -> File(directory, path).apply { parentFile!!.mkdirs(); writeText("component") } }
File(directory, "run-proton.py").setExecutable(true)
File(directory, "icd.json").writeText("current ICD")
return directory
}
}
@@ -0,0 +1,129 @@
package com.droiddeck.launcher.gpu
import java.io.File
import java.nio.file.Files
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assert.assertThrows
import org.junit.Test
class SystemVulkanSelectionTest {
@Test fun defaultPowerVrUsesTheSystemBridge() {
assertTrue(SystemVulkanDriver.usesDefault(true, ""))
assertTrue(SystemVulkanDriver.usesDefault(true, null))
}
@Test fun otherGpusAndExplicitImportsKeepTheirDriver() {
assertFalse(SystemVulkanDriver.usesDefault(false, ""))
assertFalse(SystemVulkanDriver.usesDefault(false, null))
assertFalse(SystemVulkanDriver.usesDefault(true, "custom-driver"))
}
@Test fun renderNodeRequiresARealCharacterDeviceAndBothAccessModes() {
assertTrue(SystemVulkanDriver.renderNodeAvailable(true, true, true))
assertFalse("a regular placeholder is not a DRM device", SystemVulkanDriver.renderNodeAvailable(false, true, true))
assertFalse("read access is required", SystemVulkanDriver.renderNodeAvailable(true, false, true))
assertFalse("write access is required", SystemVulkanDriver.renderNodeAvailable(true, true, false))
assertFalse("a missing node is unavailable", SystemVulkanDriver.renderNodeAvailable(false, false, false))
}
@Test fun renderNodeDriverMustIdentifyPowerVrExactly() {
for (name in listOf("pvrsrvkm", "pvr", "powervr"))
assertTrue(name, SystemVulkanDriver.powerVrDriver(name))
for (name in listOf(null, "", "msm", "panfrost", "not-pvr"))
assertFalse(name, SystemVulkanDriver.powerVrDriver(name))
}
@Test fun samsungXclipseGpuNodeIsSelectedOverItsDisplayNode() {
assertTrue(SystemVulkanDriver.powerVrDriver("sgpu"))
assertFalse("the display controller is not the GPU", SystemVulkanDriver.powerVrDriver("exynos-drm"))
// Galaxy A56 (Exynos 1580): the GPU owns renderD128, the display controller renderD129.
val drivers = mapOf("/dev/dri/renderD128" to "sgpu", "/dev/dri/renderD129" to "exynos-drm")
assertEquals("/dev/dri/renderD128", SystemVulkanDriver.findRenderNode(null) { path ->
SystemVulkanDriver.powerVrDriver(drivers[path])
})
}
@Test fun renderNodeIdentityUsesTheDriverLinkOrUevent() {
val device = Files.createTempDirectory("powervr-device").toFile()
try {
assertFalse("missing identity is unavailable", SystemVulkanDriver.powerVrDevice(device))
val uevent = File(device, "uevent")
uevent.writeText("DRIVER=pvrsrvkm\nOF_NAME=gpu0\n")
assertTrue(SystemVulkanDriver.powerVrDevice(device))
uevent.writeText("DRIVER=msm\nOF_COMPATIBLE_0=not-pvr\n")
assertFalse(SystemVulkanDriver.powerVrDevice(device))
val driver = File(device, "driver").toPath()
Files.createSymbolicLink(driver, File("../../drivers/pvrsrvkm").toPath())
assertTrue(SystemVulkanDriver.powerVrDevice(device))
Files.delete(driver)
Files.createSymbolicLink(driver, File("../../drivers/msm").toPath())
uevent.writeText("DRIVER=pvrsrvkm\n")
assertFalse("an unrelated driver link must not fall back", SystemVulkanDriver.powerVrDevice(device))
} finally {
device.deleteRecursively()
}
}
@Test fun renderNodeDiscoverySkipsOtherDriversAndDeniedNodes() {
val drivers = mapOf(
"/dev/dri/renderD128" to "msm",
"/dev/dri/renderD129" to "pvr",
"/dev/dri/renderD130" to "pvrsrvkm",
)
assertEquals("/dev/dri/renderD129", SystemVulkanDriver.findRenderNode(null) { path ->
SystemVulkanDriver.powerVrDriver(drivers[path])
})
assertEquals("/dev/dri/renderD130", SystemVulkanDriver.findRenderNode(null) { path ->
SystemVulkanDriver.powerVrDriver(drivers[path]) &&
SystemVulkanDriver.renderNodeAvailable(true, path != "/dev/dri/renderD129", true)
})
}
@Test fun renderNodesAreDiscoveredWithoutDirectoryListing() {
for (minor in listOf(128, 129, 191)) {
val expected = "/dev/dri/renderD$minor"
assertEquals(expected, SystemVulkanDriver.findRenderNode(null) { it == expected })
}
assertNull(SystemVulkanDriver.findRenderNode(null) { false })
}
@Test fun listedRenderNodesCoverExtendedMinorNumbers() {
assertEquals("/dev/dri/renderD256", SystemVulkanDriver.findRenderNode(
arrayOf("card0", "renderD256", "renderD128/device", "../renderD129"),
) { path ->
assertTrue(path, path.matches(Regex("/dev/dri/renderD[0-9]+")))
path == "/dev/dri/renderD256"
})
}
@Test fun defaultPowerVrResolvesToTheSystemIcd() {
assertEquals("system/icd.json", LinuxVulkanDriver.resolveIcdPath("", true,
{ "system/icd.json" }, { error("default must not resolve an import") }))
}
@Test fun defaultAdrenoLeavesTheRuntimeIcdUnchanged() {
assertNull(LinuxVulkanDriver.resolveIcdPath("", false,
{ error("Adreno must not prepare the system bridge") }, { error("default must not resolve an import") }))
}
@Test fun missingManualPowerVrImportFailsWithoutSwitchingBackends() {
val failure = assertThrows(IllegalStateException::class.java) {
LinuxVulkanDriver.resolveIcdPath("missing-driver", true,
{ error("manual preference must not silently switch to the system backend") }, { null })
}
assertTrue(failure.message!!.contains("missing-driver"))
assertTrue(failure.message!!.contains("use Auto"))
}
@Test fun missingAdrenoImportKeepsTheExistingRuntimeFallback() {
assertNull(LinuxVulkanDriver.resolveIcdPath("missing-driver", false,
{ error("Adreno must not prepare the system bridge") }, { null }))
}
@Test fun manualPowerVrResolvesTheChosenImport() {
assertEquals("imports/chosen/icd.json", LinuxVulkanDriver.resolveIcdPath("chosen", true,
{ error("manual must not prepare the system bridge") }, { "imports/$it/icd.json" }))
}
}
@@ -130,6 +130,34 @@ class ForcedPackageTest {
assertDefaultDxvkRestoreRow(protonName)
}
@Test fun systemPowerVrRejectsNewGameDxvkSelectionsWithoutChangingSavedProfiles() {
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
val state = File(context.filesDir, "components/state.json")
val saved = state.readText()
assertThrows(IllegalStateException::class.java) {
ComponentsManager.setGameComponent(context, "42", "dxvk", "replacement.wcp") {
ComponentsManager.runtimeManaged(it, true)
}
}
assertEquals(saved, state.readText())
assertEquals("custom-dxvk.wcp", ComponentsManager.gameComponents(context, "42")["dxvk"])
assertFalse(launchState().exists())
}
@Test fun systemPowerVrAllowsClearingASavedGameDxvkSelection() {
proton("proton-exp")
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
ComponentsManager.setGameComponent(context, "42", "dxvk", null) {
ComponentsManager.runtimeManaged(it, true)
}
assertTrue(ComponentsManager.gameComponents(context, "42").isEmpty())
assertDefaultDxvkRestoreRow("proton-exp")
}
@Test fun aNewProtonIsCapturedWhenTheLastOverrideIsReset() {
proton("existing")
writeGameProfile("42", "dxvk", "custom-dxvk.wcp")
@@ -0,0 +1,23 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class OrphanReaperProcessTest {
@Test fun unavailableProcessListDefersCleanup() {
assertTrue(OrphanReaper.hasOtherProcesses(null, 100) { false })
}
@Test fun theAppAndForeignProcessesDoNotKeepOldRuntimes() {
assertFalse(OrphanReaper.hasOtherProcesses(listOf(0, 1, 100, 200), 100) { pid ->
check(pid == 200) { "do not probe self or process groups" }
false
})
}
@Test fun anyRemainingAppProcessDefersCleanup() {
assertTrue(OrphanReaper.hasOtherProcesses(listOf(100, 200, 300), 100) { it == 300 })
assertFalse(OrphanReaper.hasOtherProcesses(emptyList(), 100) { true })
}
}
@@ -0,0 +1,44 @@
package com.droiddeck.launcher.session
import android.content.Context
import org.robolectric.RuntimeEnvironment
import com.droiddeck.launcher.gpu.TurnipDriver
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class PowerVrAutoDriversTest {
private val context: Context = RuntimeEnvironment.getApplication()
@Before fun reset() {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
SessionPrefs.setLinuxDriver(context, "imported-linux")
SessionPrefs.setAndroidDriver(context, "imported-display")
}
@Test fun autoRepairsStaleAdrenoSelectionsOnPowerVr() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true)
assertEquals("", SessionPrefs.linuxDriver(context))
assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context))
}
@Test fun explicitManualChoicesRemainOnPowerVr() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_MANUAL)
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true)
assertEquals("imported-linux", SessionPrefs.linuxDriver(context))
assertEquals("imported-display", SessionPrefs.androidDriver(context))
}
@Test fun adrenoAutoChoicesRemain() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = false)
assertEquals("imported-linux", SessionPrefs.linuxDriver(context))
assertEquals("imported-display", SessionPrefs.androidDriver(context))
}
}
@@ -0,0 +1,14 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class PowerVrComponentsTest {
@Test fun onlyDxvkIsManagedWithTheSystemPowerVrRuntime() {
assertTrue(ComponentsManager.runtimeManaged("dxvk", systemPowerVr = true))
assertFalse(ComponentsManager.runtimeManaged("dxvk", systemPowerVr = false))
assertFalse(ComponentsManager.runtimeManaged("fex", systemPowerVr = true))
assertFalse(ComponentsManager.runtimeManaged("vkd3d", systemPowerVr = true))
}
}
@@ -0,0 +1,41 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class PowerVrQueuedComponentsTest {
@Test fun managedDxvkQueueRemainsVisibleAndCanBeCancelled() {
val context: Context = RuntimeEnvironment.getApplication()
val root = LinuxRuntime.rootDir(context)
root.deleteRecursively()
val data = File(context.filesDir, "components")
data.deleteRecursively()
data.mkdirs()
val proton = File(root, "root/.local/share/Steam/compatibilitytools.d/test-proton")
File(proton, "files/lib/wine").mkdirs()
File(proton, "proton").writeText("# test Proton\n")
File(proton, "version").writeText("1 test-build\n")
File(data, "state.json").writeText(JSONObject().put("queued", JSONObject().put("test-proton",
JSONObject().put("dxvk", JSONObject().put("kind", "package").put("file", "chosen.wcp").put("label", "chosen DXVK"))
)).toString())
assertTrue(ComponentsManager.applyQueued(context) { ComponentsManager.runtimeManaged(it, true) }.isEmpty())
val deferred = ComponentsManager.snapshot(context).protons.single().components.getValue("dxvk")
assertEquals("chosen DXVK", deferred.queued)
ComponentsManager.cancelQueued(context, "test-proton", "dxvk")
assertNull(ComponentsManager.snapshot(context).protons.single().components.getValue("dxvk").queued)
}
}
@@ -1,9 +1,23 @@
package com.droiddeck.launcher.ui
import android.app.Application
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.test.SemanticsMatcher
import androidx.compose.ui.test.assertCountEquals
import androidx.compose.ui.test.assertIsEnabled
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.onAllNodesWithText
import androidx.compose.ui.test.onLast
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollTo
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.ComponentsManager
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@@ -11,8 +25,9 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
// Exercise the component UI without starting App's process-wide servers or crash handler.
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
@Config(sdk = [28], application = Application::class)
class ComponentsPageProfileTest {
@get:Rule val compose = createRobolectricComposeRule()
@@ -56,4 +71,143 @@ class ComponentsPageProfileTest {
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
compose.onNodeWithText(stackHeading).assertExists()
}
@Test @Config(qualifiers = "w1280dp-h1000dp")
fun systemPowerVrKeepsStoredDxvkDisabledAndQueuedDxvkCancellable() {
val context = RuntimeEnvironment.getApplication()
var cancelled = 0
var imported = 0
var swapped = 0
var restored = 0
showDxvk(
systemPowerVr = true,
onCancel = { cancelled++ },
onImport = { imported++ },
onSwap = { swapped++ },
onRestore = { restored++ },
)
compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_managed)).assertExists()
compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_queued, "Next DXVK"), substring = true).assertExists()
compose.onNodeWithText("Stored DXVK").assertIsNotEnabled()
compose.onNodeWithText(context.getString(R.string.comp_original, "1.0")).assertIsNotEnabled()
compose.onNodeWithText(context.getString(R.string.comp_restore_original)).assertIsNotEnabled()
compose.onNodeWithText(context.getString(R.string.common_cancel)).performClick()
compose.onNodeWithText(context.getString(R.string.comp_import_wcp)).performScrollTo().assertIsEnabled().performClick()
compose.runOnIdle {
assertEquals(1, cancelled)
assertEquals(1, imported)
assertEquals(0, swapped)
assertEquals(0, restored)
}
}
@Test @Config(qualifiers = "w1280dp-h1000dp")
fun manualRuntimeKeepsDxvkSelectionAvailable() {
val context = RuntimeEnvironment.getApplication()
showDxvk(systemPowerVr = false)
compose.onNode(hasText("Stored DXVK") and SemanticsMatcher.expectValue(SemanticsProperties.Role, Role.RadioButton)).assertIsEnabled()
compose.onNodeWithText(context.getString(R.string.comp_original, "1.0")).assertIsEnabled()
compose.onNodeWithText(context.getString(R.string.comp_restore_original)).assertIsEnabled()
compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_managed)).assertDoesNotExist()
}
@Test @Config(qualifiers = "w1280dp-h1000dp")
fun systemPowerVrGameProfileKeepsOtherComponentChoicesAndRuntimeOptionsAvailable() {
val context = RuntimeEnvironment.getApplication()
showDxvk(systemPowerVr = true)
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
compose.onNodeWithText("Game A").performClick()
compose.waitUntil(5_000) {
compose.onAllNodesWithText(context.getString(R.string.comp_game_reset)).fetchSemanticsNodes().isNotEmpty()
}
compose.onNodeWithText(context.getString(R.string.gpu_system_powervr)).assertIsNotEnabled()
compose.onNodeWithText(context.getString(R.string.cmgr_powervr_dxvk_managed)).assertExists()
val inheritedChoices = compose.onAllNodesWithText(context.getString(R.string.comp_game_use_general))
inheritedChoices.assertCountEquals(4) // FEX preset, FEX package, Proton and VKD3D remain selectable.
repeat(4) { inheritedChoices[it].assertIsEnabled() }
val runtimeOptions = compose.onAllNodesWithText(context.getString(R.string.comp_game_runtime_options))
runtimeOptions.assertCountEquals(2)
repeat(2) { runtimeOptions[it].assertIsEnabled() }
compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertDoesNotExist()
compose.onNodeWithText("Game A").performClick()
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertExists()
}
@Test @Config(qualifiers = "w1280dp-h1000dp")
fun systemPowerVrGameProfileCanClearAnExistingDxvkOverrideWithoutSelectingAnother() {
val context = RuntimeEnvironment.getApplication()
showDxvk(systemPowerVr = true, gameDxvkOverride = true)
compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick()
compose.onNodeWithText("Game A").performClick()
compose.waitUntil(5_000) {
compose.onAllNodesWithText(context.getString(R.string.comp_game_reset)).fetchSemanticsNodes().isNotEmpty()
}
compose.onNodeWithText(context.getString(R.string.gpu_system_powervr)).performScrollTo().assertIsEnabled().performClick()
compose.onNodeWithText("Stored DXVK").assertDoesNotExist()
compose.onAllNodesWithText(context.getString(R.string.comp_game_use_general)).onLast().performClick()
compose.waitUntil(5_000) { "dxvk" !in ComponentsManager.gameComponents(context, "42") }
compose.onNodeWithText(context.getString(R.string.gpu_system_powervr)).assertIsNotEnabled()
}
private fun showDxvk(
systemPowerVr: Boolean,
gameDxvkOverride: Boolean = false,
onCancel: () -> Unit = {},
onImport: () -> Unit = {},
onSwap: (String) -> Unit = {},
onRestore: (String) -> Unit = {},
) {
val context = RuntimeEnvironment.getApplication()
File(context.filesDir, "components/state.json").apply {
parentFile!!.mkdirs()
writeText(if (gameDxvkOverride) """{"profiles":{"42":{"dxvk":"stored.wcp"}}}""" else "{}")
}
val proton = ComponentsManager.Proton(
"test-proton", "Test Proton", File(context.filesDir, "test-proton"), "/test-proton", "1.0", false,
)
val snapshot = ComponentsManager.Snapshot(
protons = listOf(ComponentsManager.ProtonView(
proton = proton,
components = mapOf("dxvk" to ComponentsManager.Component("1.0", "", "Stored DXVK", "", "stored.wcp", "Next DXVK")),
originals = listOf(ComponentsManager.Original("dxvk", "1.0", "Original DXVK", 1)),
inUseByGame = false,
)),
packages = listOf(ComponentsManager.Package("stored.wcp", "dxvk", "Stored DXVK", "", 1)),
)
compose.setContent {
DroidDeckTheme {
ComponentsPage(
snapshot = snapshot,
catalog = emptyList(),
catalogAt = 0,
protonId = proton.id,
comp = "dxvk",
checking = false,
busy = null,
downloads = emptyMap(),
onProton = {},
onComp = {},
onSwap = onSwap,
onRestore = onRestore,
onCancelQueued = onCancel,
onDeletePackage = {},
onDeleteOriginal = {},
onDownload = {},
onRefresh = {},
onImport = onImport,
onBack = {},
gpu = GpuDriversState(powerVr = true, systemPowerVr = systemPowerVr),
games = listOf(Library.SteamGame(42, "Game A", null, "internal")),
requestInitialFocus = false,
)
}
}
}
}