Merge upstream main into unified input profiles

Integrate screen keys, portrait controls, and Home/Back shortcuts with routed input. Preserve remapped axes, neutral gating, and explicit Back bindings; discard stale queued chord reports when routing changes.

Validation: 2,632 debug JVM tests across 385 suites pass with Java 17 and skipRust. Device testing and latency measurements were not repeated for this merge.
This commit is contained in:
Delete228 committed 2026-10-27 13:14:29 +03:00
commit 92b4361100
525 files changed
+40912 -3336

No files matched your search

+359
View File
@@ -0,0 +1,359 @@
#include "framegen.hpp"
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace {
constexpr int levels = 7;
constexpr VkImageUsageFlags flow_usage =
VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
enum Pipeline { LUMA, DOWNSAMPLE, FLOW3, FLOW4, EXPAND3, EXPAND4, GLOBAL_MOTION, PREWARP, FLOW_REG, SYNTH };
struct Image { VkExtent3D extent; VkFormat format; VkImageUsageFlags usage; };
struct Allocation { VkDeviceSize size; std::unique_ptr<uint8_t[]> data; };
struct Binding { VkDescriptorType type; VkImageView view; VkBuffer buffer; VkDeviceSize range; };
struct Dispatch { unsigned pipeline; uint32_t x, y, z; };
std::map<VkImage, Image> images;
std::map<VkImageView, VkImage> views;
std::map<VkBuffer, VkBufferCreateInfo> buffers;
std::map<VkDeviceMemory, Allocation> allocations;
std::map<VkBuffer, VkDeviceMemory> buffer_memory;
std::map<VkDescriptorSet, std::map<uint32_t, Binding>> descriptors;
std::map<VkPipeline, unsigned> pipelines;
std::map<VkImage, unsigned> image_ids;
std::map<VkBuffer, unsigned> buffer_ids;
std::vector<Dispatch> dispatches;
uintptr_t serial = 100;
unsigned buffer_creates, set_creates;
VkPipeline bound_pipeline;
VkDescriptorSet bound_set;
uint64_t command_hash = 14695981039346656037ull;
template<class T> T handle() { return reinterpret_cast<T>(++serial); }
void hash(uint64_t value) {
for (unsigned i = 0; i < 8; i++) {
command_hash = (command_hash ^ (value & 255)) * 1099511628211ull;
value >>= 8;
}
}
void hash_image(VkImage image) {
assert(images.count(image));
if (!image_ids.count(image)) image_ids[image] = static_cast<unsigned>(image_ids.size() + 1);
const auto &info = images.at(image);
hash(image_ids.at(image));
hash(info.extent.width); hash(info.extent.height); hash(info.format); hash(info.usage);
}
template<class Info, class Out>
VkResult VKAPI_CALL create(VkDevice, const Info *, const VkAllocationCallbacks *, Out *out) {
*out = handle<Out>();
return VK_SUCCESS;
}
template<class T> void VKAPI_CALL destroy(VkDevice, T, const VkAllocationCallbacks *) {}
VkResult VKAPI_CALL create_image(VkDevice, const VkImageCreateInfo *info,
const VkAllocationCallbacks *, VkImage *out) {
*out = handle<VkImage>();
images[*out] = {info->extent, info->format, info->usage};
return VK_SUCCESS;
}
VkResult VKAPI_CALL create_view(VkDevice, const VkImageViewCreateInfo *info,
const VkAllocationCallbacks *, VkImageView *out) {
assert(images.count(info->image));
*out = handle<VkImageView>();
views[*out] = info->image;
return VK_SUCCESS;
}
void VKAPI_CALL destroy_image(VkDevice, VkImage image, const VkAllocationCallbacks *) {
assert(images.erase(image) == 1);
}
void VKAPI_CALL destroy_view(VkDevice, VkImageView view, const VkAllocationCallbacks *) {
assert(views.erase(view) == 1);
}
VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo *info,
const VkAllocationCallbacks *, VkBuffer *out) {
*out = handle<VkBuffer>();
buffers[*out] = *info;
buffer_creates++;
return VK_SUCCESS;
}
void VKAPI_CALL destroy_buffer(VkDevice, VkBuffer buffer, const VkAllocationCallbacks *) {
assert(buffers.erase(buffer) == 1);
buffer_memory.erase(buffer);
}
void VKAPI_CALL image_requirements(VkDevice, VkImage image, VkMemoryRequirements *out) {
const auto &info = images.at(image);
const uint64_t bytes = info.format == VK_FORMAT_R32_SFLOAT ? 4 : 8;
*out = {uint64_t(info.extent.width) * info.extent.height * bytes, 1, 1};
}
void VKAPI_CALL buffer_requirements(VkDevice, VkBuffer buffer, VkMemoryRequirements *out) {
*out = {buffers.at(buffer).size, 1, 1};
}
VkResult VKAPI_CALL allocate(VkDevice, const VkMemoryAllocateInfo *info,
const VkAllocationCallbacks *, VkDeviceMemory *out) {
*out = handle<VkDeviceMemory>();
allocations[*out].size = info->allocationSize;
return VK_SUCCESS;
}
void VKAPI_CALL free_memory(VkDevice, VkDeviceMemory memory, const VkAllocationCallbacks *) {
assert(allocations.erase(memory) == 1);
}
VkResult VKAPI_CALL bind_image(VkDevice, VkImage image, VkDeviceMemory memory, VkDeviceSize) {
assert(images.count(image) && allocations.count(memory));
return VK_SUCCESS;
}
VkResult VKAPI_CALL bind_buffer(VkDevice, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize) {
assert(buffers.count(buffer) && allocations.count(memory));
buffer_memory[buffer] = memory;
return VK_SUCCESS;
}
VkResult VKAPI_CALL map_memory(VkDevice, VkDeviceMemory memory, VkDeviceSize offset,
VkDeviceSize size, VkMemoryMapFlags, void **out) {
auto &allocation = allocations.at(memory);
assert(offset == 0 && size <= allocation.size);
allocation.data = std::make_unique<uint8_t[]>(allocation.size);
*out = allocation.data.get();
return VK_SUCCESS;
}
void VKAPI_CALL unmap(VkDevice, VkDeviceMemory memory) { assert(allocations.count(memory)); }
VkResult VKAPI_CALL idle(VkDevice) { return VK_SUCCESS; }
void VKAPI_CALL memory_properties(VkPhysicalDevice, VkPhysicalDeviceMemoryProperties *out) {
*out = {};
out->memoryTypeCount = 1;
out->memoryTypes[0].propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
}
VkResult VKAPI_CALL allocate_sets(VkDevice, const VkDescriptorSetAllocateInfo *info, VkDescriptorSet *out) {
for (uint32_t i = 0; i < info->descriptorSetCount; i++) {
out[i] = handle<VkDescriptorSet>();
descriptors[out[i]] = {};
set_creates++;
}
return VK_SUCCESS;
}
VkResult VKAPI_CALL reset_pool(VkDevice, VkDescriptorPool, VkDescriptorPoolResetFlags) {
descriptors.clear();
return VK_SUCCESS;
}
void VKAPI_CALL update_sets(VkDevice, uint32_t count, const VkWriteDescriptorSet *writes,
uint32_t, const VkCopyDescriptorSet *) {
for (uint32_t i = 0; i < count; i++) {
const auto &write = writes[i];
assert(descriptors.count(write.dstSet) && write.descriptorCount == 1);
Binding binding{write.descriptorType, VK_NULL_HANDLE, VK_NULL_HANDLE, 0};
if (write.pImageInfo) {
binding.view = write.pImageInfo->imageView;
assert(views.count(binding.view));
} else {
binding.buffer = write.pBufferInfo->buffer;
binding.range = write.pBufferInfo->range;
assert(buffers.count(binding.buffer));
}
descriptors.at(write.dstSet)[write.dstBinding] = binding;
}
}
VkResult VKAPI_CALL create_pipelines(VkDevice, VkPipelineCache, uint32_t count,
const VkComputePipelineCreateInfo *, const VkAllocationCallbacks *,
VkPipeline *out) {
for (uint32_t i = 0; i < count; i++) {
const auto index = static_cast<unsigned>(pipelines.size());
out[i] = handle<VkPipeline>();
pipelines[out[i]] = index;
}
return VK_SUCCESS;
}
void VKAPI_CALL bind_pipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline pipeline) {
assert(pipelines.count(pipeline));
bound_pipeline = pipeline;
}
void VKAPI_CALL bind_sets(VkCommandBuffer, VkPipelineBindPoint, VkPipelineLayout,
uint32_t, uint32_t count, const VkDescriptorSet *sets,
uint32_t, const uint32_t *) {
assert(count == 1 && descriptors.count(sets[0]));
bound_set = sets[0];
}
void VKAPI_CALL dispatch(VkCommandBuffer, uint32_t x, uint32_t y, uint32_t z) {
const unsigned pipeline = pipelines.at(bound_pipeline);
dispatches.push_back({pipeline, x, y, z});
hash(1); hash(pipeline); hash(x); hash(y); hash(z);
for (const auto &[slot, binding] : descriptors.at(bound_set)) {
hash(slot); hash(binding.type);
if (binding.view) {
hash_image(views.at(binding.view));
} else {
if (!buffer_ids.count(binding.buffer))
buffer_ids[binding.buffer] = static_cast<unsigned>(buffer_ids.size() + 1);
const auto &allocation = allocations.at(buffer_memory.at(binding.buffer));
const auto size = binding.range == VK_WHOLE_SIZE ? allocation.size : binding.range;
assert(allocation.data && size <= allocation.size);
hash(buffer_ids.at(binding.buffer)); hash(size);
for (VkDeviceSize i = 0; i < size; i++) hash(allocation.data[i]);
}
}
}
void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags src, VkPipelineStageFlags dst,
VkDependencyFlags flags, uint32_t nm, const VkMemoryBarrier *memory,
uint32_t nb, const VkBufferMemoryBarrier *, uint32_t ni,
const VkImageMemoryBarrier *image) {
assert(nb == 0);
hash(2); hash(src); hash(dst); hash(flags); hash(nm); hash(ni);
for (uint32_t i = 0; i < nm; i++) {
hash(memory[i].srcAccessMask); hash(memory[i].dstAccessMask);
}
for (uint32_t i = 0; i < ni; i++) {
hash_image(image[i].image);
hash(image[i].oldLayout); hash(image[i].newLayout);
hash(image[i].srcAccessMask); hash(image[i].dstAccessMask);
hash(image[i].srcQueueFamilyIndex); hash(image[i].dstQueueFamilyIndex);
}
}
void VKAPI_CALL clear_image(VkCommandBuffer, VkImage image, VkImageLayout layout,
const VkClearColorValue *color, uint32_t count, const VkImageSubresourceRange *) {
assert(count == 1);
hash(3); hash_image(image); hash(layout);
for (unsigned i = 0; i < 4; i++) hash(color->uint32[i]);
}
void VKAPI_CALL copy_image(VkCommandBuffer, VkImage src, VkImageLayout sl, VkImage dst,
VkImageLayout dl, uint32_t count, const VkImageCopy *region) {
assert(count == 1);
hash(4); hash_image(src); hash(sl); hash_image(dst); hash(dl);
hash(region->extent.width); hash(region->extent.height); hash(region->extent.depth);
}
uint32_t dimension(uint32_t full, int level) { return std::max(full >> level, 1u); }
void check_images(uint32_t width, uint32_t height, int finest) {
assert(images.size() == static_cast<size_t>(32 - 2 * finest));
for (int level = finest; level < levels; level++) {
const auto w = dimension(width, level), h = dimension(height, level);
assert(std::any_of(images.begin(), images.end(), [=](const auto &entry) {
const auto &image = entry.second;
return image.format == VK_FORMAT_R16G16B16A16_SFLOAT && image.usage == flow_usage &&
image.extent.width == w && image.extent.height == h;
}));
}
}
VkImageView external_image(uint32_t width, uint32_t height) {
VkImage image = handle<VkImage>();
VkImageView view = handle<VkImageView>();
images[image] = {{width, height, 1}, VK_FORMAT_R8G8B8A8_UNORM,
VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT};
views[view] = image;
return view;
}
void record(ddfg::FrameGen &fg, int model, uint32_t width, uint32_t height, unsigned generations) {
const auto previous = external_image(width, height), current = external_image(width, height);
const auto first = dispatches.size();
for (unsigned i = 0; i < generations; i++)
fg.record(reinterpret_cast<VkCommandBuffer>(1), previous, current, external_image(width, height),
float(i + 1) / float(generations + 1), 0, i, i != 0);
std::vector<Dispatch> expected;
auto add = [&](unsigned pipeline, int level) {
expected.push_back({pipeline, (dimension(width, level) + 15) / 16,
(dimension(height, level) + 15) / 16, 1});
};
add(LUMA, 0); add(LUMA, 0);
for (int level = 1; level < levels; level++) { add(DOWNSAMPLE, level); add(DOWNSAMPLE, level); }
expected.push_back({GLOBAL_MOTION, 8, 1, 1});
for (int level = fg.flowFinest(); level < levels; level++) add(PREWARP, level);
for (int level = levels - 1; level >= fg.flowFinest(); level--) add(model == 4 ? FLOW4 : FLOW3, level);
for (int i = 0; i < 4; i++) add(FLOW_REG, fg.flowFinest());
add(model == 4 ? EXPAND4 : EXPAND3, 0);
for (unsigned i = 0; i < generations; i++) add(SYNTH, 0);
assert(dispatches.size() - first == expected.size());
for (size_t i = 0; i < expected.size(); i++) {
const auto &actual = dispatches[first + i], &want = expected[i];
assert(actual.pipeline == want.pipeline && actual.x == want.x && actual.y == want.y && actual.z == want.z);
}
for (auto it = views.begin(); it != views.end();) {
if (images.at(it->second).format == VK_FORMAT_R8G8B8A8_UNORM) {
images.erase(it->second);
it = views.erase(it);
} else ++it;
}
}
}
int main(int argc, char **argv) {
assert(argc == 8);
const std::string mode = argv[1];
const int model = std::atoi(argv[2]), preset = std::atoi(argv[3]);
uint32_t width = static_cast<uint32_t>(std::atoi(argv[4]));
uint32_t height = static_cast<uint32_t>(std::atoi(argv[5]));
const unsigned generations = static_cast<unsigned>(std::atoi(argv[6]));
const unsigned repeats = static_cast<unsigned>(std::atoi(argv[7]));
assert((model == 3 || model == 4) && preset >= 0 && preset <= 2);
assert(width && height && generations >= 1 && generations <= 3 && repeats > 0);
ddfg::DeviceDispatch dd;
ddfg::InstanceDispatch id;
id.GetPhysicalDeviceMemoryProperties = memory_properties;
dd.CreateImage = create_image; dd.DestroyImage = destroy_image;
dd.CreateImageView = create_view; dd.DestroyImageView = destroy_view;
dd.CreateBuffer = create_buffer; dd.DestroyBuffer = destroy_buffer;
dd.GetImageMemoryRequirements = image_requirements; dd.GetBufferMemoryRequirements = buffer_requirements;
dd.AllocateMemory = allocate; dd.FreeMemory = free_memory;
dd.BindImageMemory = bind_image; dd.BindBufferMemory = bind_buffer;
dd.MapMemory = map_memory; dd.UnmapMemory = unmap; dd.DeviceWaitIdle = idle;
dd.CreateSampler = create<VkSamplerCreateInfo, VkSampler>; dd.DestroySampler = destroy<VkSampler>;
dd.CreateShaderModule = create<VkShaderModuleCreateInfo, VkShaderModule>;
dd.DestroyShaderModule = destroy<VkShaderModule>;
dd.CreateDescriptorSetLayout = create<VkDescriptorSetLayoutCreateInfo, VkDescriptorSetLayout>;
dd.DestroyDescriptorSetLayout = destroy<VkDescriptorSetLayout>;
dd.CreatePipelineLayout = create<VkPipelineLayoutCreateInfo, VkPipelineLayout>;
dd.DestroyPipelineLayout = destroy<VkPipelineLayout>;
dd.CreateDescriptorPool = create<VkDescriptorPoolCreateInfo, VkDescriptorPool>;
dd.DestroyDescriptorPool = destroy<VkDescriptorPool>; dd.ResetDescriptorPool = reset_pool;
dd.AllocateDescriptorSets = allocate_sets; dd.UpdateDescriptorSets = update_sets;
dd.CreateComputePipelines = create_pipelines; dd.DestroyPipeline = destroy<VkPipeline>;
dd.CmdBindPipeline = bind_pipeline; dd.CmdBindDescriptorSets = bind_sets; dd.CmdDispatch = dispatch;
dd.CmdPipelineBarrier = barrier; dd.CmdClearColorImage = clear_image; dd.CmdCopyImage = copy_image;
ddfg::FrameGen fg;
assert(fg.init(&dd, &id, reinterpret_cast<VkPhysicalDevice>(1), reinterpret_cast<VkDevice>(2),
0, reinterpret_cast<VkQueue>(3)));
ddfg::Config cfg;
cfg.enabled = true; cfg.model = model; cfg.perfPreset = preset; cfg.flowScale = 0.6f;
fg.configure(cfg);
assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM));
assert(mode == "resources" || mode == "record" || mode == "resize" || mode == "preset");
for (unsigned repeat = 0; repeat < repeats; repeat++) {
const auto old_buffers = buffer_creates, old_sets = set_creates;
if (mode != "record") check_images(width, height, fg.flowFinest());
record(fg, model, width, height, generations);
if (mode != "record") {
assert(buffer_creates - old_buffers == static_cast<unsigned>(15 - fg.flowFinest()));
assert(set_creates - old_sets == static_cast<unsigned>(54 - 4 * fg.flowFinest()));
}
if (repeat + 1 == repeats) break;
if (mode == "resize") {
width += 17; height += 9;
assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM));
} else if (mode == "preset") {
cfg.perfPreset = (cfg.perfPreset + 1) % 3;
fg.configure(cfg);
} else {
assert(mode == "record");
}
}
uint64_t bytes = 0;
for (const auto &[image, info] : images) {
(void)image;
bytes += uint64_t(info.extent.width) * info.extent.height *
(info.format == VK_FORMAT_R32_SFLOAT ? 4 : 8);
}
std::printf("PASS images=%zu bytes=%llu buffers=%u sets=%u dispatches=%zu trace=%016llx\n",
images.size(), static_cast<unsigned long long>(bytes), buffer_creates, set_creates,
dispatches.size(), static_cast<unsigned long long>(command_hash));
fg.destroy();
assert(images.empty() && views.empty());
}
+101
View File
@@ -0,0 +1,101 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
@unittest.skipUnless(shutil.which("cc"), "C compiler required")
class AndroidVolumeTest(unittest.TestCase):
def test_missing_or_invalid_initial_state_recovers_without_restarting_the_sink(self):
header = Path(__file__).resolve().parents[1] / "aaudio-sink/android-volume.h"
harness = r'''
#define _GNU_SOURCE
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#define PA_VOLUME_NORM 65536U
#define PA_USEC_PER_MSEC 1000
#define PA_SINK_INIT 0
#define PA_SUBSCRIPTION_EVENT_SINK 1
#define PA_SUBSCRIPTION_EVENT_CHANGE 2
#define PA_MIN(a,b) ((a)<(b)?(a):(b))
#define pa_xnew0(type,n) ((type*)calloc(n,sizeof(type)))
#define pa_xstrdup strdup
#define pa_xfree free
#define pa_log_warn(...) ((void)0)
typedef struct { unsigned value; } pa_cvolume;
typedef struct pa_time_event { int value; } pa_time_event;
typedef struct pa_mainloop_api { void (*time_free)(pa_time_event*); } pa_mainloop_api;
typedef struct { pa_mainloop_api *mainloop; } pa_core;
typedef struct pa_sink {
void *userdata; int state; bool muted; unsigned n_volume_steps, index;
struct { unsigned channels; } sample_spec;
pa_cvolume real_volume, reference_volume, soft_volume;
pa_core *core;
void (*set_volume)(struct pa_sink*), (*set_mute)(struct pa_sink*);
} pa_sink;
struct android_volume;
struct userdata { struct android_volume *android_volume; };
static int restarts, frees;
static char *pa_sprintf_malloc(const char *format, ...) {
va_list ap; va_start(ap,format); char *result; assert(vasprintf(&result,format,ap)>=0); va_end(ap); return result;
}
static void pa_cvolume_set(pa_cvolume *volume, unsigned channels, unsigned value) { volume->value=value; }
static unsigned pa_cvolume_max(const pa_cvolume *volume) { return volume->value; }
static void pa_cvolume_reset(pa_cvolume *volume, unsigned channels) { volume->value=PA_VOLUME_NORM; }
static bool pa_cvolume_equal(const pa_cvolume *a, const pa_cvolume *b) { return a->value==b->value; }
static void pa_sink_volume_changed(pa_sink *sink, const pa_cvolume *volume) { sink->real_volume=*volume; }
static void pa_sink_mute_changed(pa_sink *sink, bool muted) { sink->muted=muted; }
static void pa_sink_set_set_volume_callback(pa_sink *sink, void (*callback)(pa_sink*)) { sink->set_volume=callback; }
static void pa_sink_set_set_mute_callback(pa_sink *sink, void (*callback)(pa_sink*)) { sink->set_mute=callback; }
static void pa_subscription_post(pa_core *core, int event, unsigned index) {}
static uint64_t pa_rtclock_now(void) { return 0; }
static void pa_core_rttime_restart(pa_core *core, pa_time_event *event, uint64_t time) { restarts++; }
static pa_time_event *pa_core_rttime_new(pa_core *core, uint64_t time,
void (*callback)(pa_mainloop_api*,pa_time_event*,const struct timeval*,void*), void *userdata) {
return calloc(1,sizeof(pa_time_event));
}
static void free_timer(pa_time_event *event) { frees++; free(event); }
#include "android-volume.h"
static void state(const char *directory, const char *text) {
char *path=pa_sprintf_malloc("%s/volume.state",directory);
FILE *f=fopen(path,"w"); assert(f); fputs(text,f); fclose(f); free(path);
}
int main(int argc, char **argv) {
pa_mainloop_api api={.time_free=free_timer}; pa_core core={.mainloop=&api};
struct userdata userdata={0};
pa_sink sink={.userdata=&userdata,.core=&core,.state=1,.sample_spec={.channels=2},.real_volume={PA_VOLUME_NORM}};
userdata.android_volume=android_volume_new(&sink,argv[1]);
assert(userdata.android_volume && userdata.android_volume->timer && sink.set_volume && sink.set_mute);
state(argv[1],"invalid\n");
android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume);
assert(sink.real_volume.value==PA_VOLUME_NORM && restarts==1);
state(argv[1],"3 15 1\n");
android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume);
assert(sink.real_volume.value==3*PA_VOLUME_NORM/15 && sink.muted && sink.n_volume_steps==16);
assert(sink.soft_volume.value==PA_VOLUME_NORM && restarts==2);
sink.real_volume.value=2*PA_VOLUME_NORM/3; sink.set_volume(&sink);
char *request=pa_sprintf_malloc("%s/volume.request",argv[1]);
FILE *f=fopen(request,"r"); unsigned level; assert(f && fscanf(f,"%u",&level)==1 && level==10); fclose(f); free(request);
android_volume_free(userdata.android_volume); assert(frees==1);
return 0;
}
'''
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "pulsecore").mkdir()
for name in ("core-rtclock.h", "core-subscribe.h"):
(root / "pulsecore" / name).touch()
source = root / "test.c"
source.write_text(harness)
binary = root / "test"
subprocess.run(["cc", "-std=c11", "-I", str(root), "-I", str(header.parent),
str(source), "-o", str(binary)], check=True, capture_output=True)
subprocess.run([str(binary), str(root)], check=True, capture_output=True)
File diff suppressed because it is too large. Load diff
+169
View File
@@ -0,0 +1,169 @@
from pathlib import Path
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
def function_source(name):
source = SCRIPT.read_text()
start = source.index('%s() {' % name)
end = source.index('\n }', start)
return source[start:end + len('\n }')]
def run_bash(script, env=None):
return subprocess.run(['bash', '-c', script], capture_output=True, text=True, timeout=10, env=env)
class ClientZramFocusTest(unittest.TestCase):
def test_refocus_restarts_the_delay_and_game_exit_restores_a_packed_client(self):
source = SCRIPT.read_text()
start = source.index(' if [ "$_bl_game" = 1 ] && bl_game_focused; then')
stop = source.index(' nap 5', start)
body = source[start:stop]
harness = '''
_bl_since=-1 _bl_since_apps= _bl_packed=-1 _bl_apps=" 413150"
_bl_pids=(123)
bl_game_focused() { [ "$focused" = 1 ]; }
bl_over_cap() { return 1; }
bl_zram_send() { echo "send:$1"; }
tick() {
SECONDS=$1 _bl_game=$2 focused=$3
''' + body + '''
}
tick 0 1 1
tick 5 1 0
tick 30 1 1
echo "refocus:$_bl_packed"
tick 49 1 1
tick 50 1 1
tick 55 1 0
tick 60 0 0
'''
result = run_bash(harness)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['refocus:-1', 'send:1', 'send:0'], result.stdout.splitlines())
def monitor_harness(self):
source = SCRIPT.read_text()
start = source.index(' bl_zram_scan\n if bl_cap_due; then')
stop = source.index(' nap 5', start)
return '''
_bl_since=-1 _bl_since_apps= _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30
_bl_apps=" 413150"
_bl_pids=(123)
step() { :; }
bl_zram_scan() { :; }
bl_game_focused() { [ "$focused" = 1 ]; }
bl_cap_due() { [ "$cap_due" = 1 ]; }
bl_over_cap() { [ "$over_cap" = 1 ]; }
bl_zram_send() { echo "send:$1:$3"; }
tick() {
SECONDS=$1 _bl_game=$2 focused=$3 over_cap=$4 cap_due=$5
''' + source[start:stop] + '\n}\n'
def test_client_toggle_still_disables_automatic_compression(self):
result = run_bash(self.monitor_harness() + '''
BL_ZRAM_CLIENT=0
tick 0 1 1 0 0
tick 25 1 1 0 0
tick 30 0 0 0 0
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual('', result.stdout)
def test_a_new_game_restarts_the_compression_delay(self):
result = run_bash(self.monitor_harness() + '''
tick 0 1 1 0 0
_bl_apps=" 413150 1245620"
tick 15 1 1 0 0
tick 20 1 1 0 0
echo "starting:$_bl_packed"
tick 34 1 1 0 0
tick 35 1 1 0 0
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['starting:-1', 'send:1:client'], result.stdout.splitlines())
def test_ram_cap_can_still_compress_an_unfocused_client(self):
result = run_bash(self.monitor_harness() + '''
BL_ZRAM_CLIENT=0 BL_RAM_CAP_MB=1024
bl_zram_usage() { _bl_rss=$((768 * 1024)); }
tick 0 1 0 1 1
echo "cap:$_bl_packed:$_bl_since:$_bl_backoff"
tick 5 0 0 0 0
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['send:1:client', 'send:1:session', 'cap:0:-1:60', 'send:0:client'], result.stdout.splitlines())
def test_game_exit_defers_restore_until_the_session_is_under_the_ram_cap(self):
result = run_bash(self.monitor_harness() + '''
tick 0 1 1 0 0
tick 20 1 1 0 0
tick 25 1 0 0 0
tick 30 0 0 1 0
echo "deferred:$_bl_unpack:$_bl_packed"
tick 35 0 0 0 1
echo "restored:$_bl_unpack"
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['send:1:client', 'deferred:1:-1', 'send:0:client', 'restored:0'], result.stdout.splitlines())
def test_scan_keeps_the_running_game_and_ignores_steams_own_reaper(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
root = Path(temp.name)
self.write_cmd(root, 10, ['/usr/lib/steam/reaper', 'SteamLaunch', 'AppId=769', '--'])
self.write_cmd(root, 20, ['/usr/bin/FEX', '/usr/lib/steam/reaper', 'SteamLaunch', 'AppId=1245620', '--'])
self.write_cmd(root, 30, ['/home/deck/.local/share/Steam/steamrtarm64/steam'])
self.write_cmd(root, 40, ['/usr/bin/wine', 'game.exe'])
self.write_cmd(root, 50, ['/usr/bin/FEXInterpreter', '/usr/bin/steamwebhelper'])
scan = function_source('bl_zram_scan').replace('for _d in /proc/[0-9]*', 'for _d in "$FAKE"/[0-9]*')
result = run_bash('FAKE=%s\n%s\nbl_zram_scan\necho "game=$_bl_game"\necho "apps=${_bl_apps# }"\necho "pids=${_bl_pids[*]}"\necho "others=${_bl_others[*]}"' % (root, scan))
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual(['game=1', 'apps=1245620', 'pids=30 50', 'others=40'], result.stdout.splitlines())
def test_focus_must_be_the_running_game(self):
focus = function_source('bl_game_focused')
script = '''
%s
check() {
BL_DESKTOP=$1 BL_LAUNCH_DIR=$2 _bl_apps=$3
if bl_game_focused; then echo yes; else echo no; fi
}
check "" "$dir" " 413150"
check "" "$dir" " 1245620"
printf '%%s\\n' '{"focusedApp": 999}' > "$dir/agent/focus.json"
check "" "$dir" " 413150"
printf '%%s\\n' '{"focusedApp": 769}' > "$dir/agent/focus.json"
check "" "$dir" " 413150"
rm -f "$dir/agent/focus.json"
check 1 "$dir" " 413150"
check "" "" " 413150"
''' % focus
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
launch = Path(temp.name)
(launch / 'agent').mkdir()
(launch / 'agent' / 'focus.json').write_text('{"t": 1, "focusedApp": 413150}\n')
result = run_bash('dir=%s\n%s' % (launch, script))
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual(['yes', 'no', 'no', 'no', 'yes', 'yes'], result.stdout.splitlines())
@staticmethod
def write_cmd(root, pid, args):
proc = root / str(pid)
proc.mkdir()
(proc / 'cmdline').write_bytes(b'\0'.join(arg.encode() for arg in args) + b'\0')
if __name__ == '__main__':
unittest.main()
+102
View File
@@ -0,0 +1,102 @@
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
CHAIN = ROOT / "app/src/main/cpp/framegen/ddfg"
class DdfgFlowLevelsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = shutil.which(os.environ.get("CXX", "c++"))
if compiler is None:
raise unittest.SkipTest("A host C++ compiler is required")
candidates = [Path("/usr/include/vulkan"), Path("/opt/homebrew/include/vulkan")]
for key in ("ANDROID_NDK_HOME", "ANDROID_NDK_ROOT", "NDK_HOME"):
if os.environ.get(key):
candidates.extend(Path(os.environ[key]).glob("toolchains/llvm/prebuilt/*/sysroot/usr/include/vulkan"))
for sdk in {Path(os.environ.get("ANDROID_HOME", "/nonexistent")),
Path(os.environ.get("ANDROID_SDK_ROOT", "/nonexistent")),
Path.home() / "Library/Android/sdk", Path.home() / "Android/Sdk"}:
candidates.extend(sdk.glob("ndk/*/toolchains/llvm/prebuilt/*/sysroot/usr/include/vulkan"))
headers = next((p for p in candidates if (p / "vulkan.h").is_file()), None)
if headers is None:
raise unittest.SkipTest("Vulkan headers from the Android NDK or system SDK are required")
cls.temp = tempfile.TemporaryDirectory(prefix="droiddeck-ddfg-levels-")
cls.addClassCleanup(cls.temp.cleanup)
work = Path(cls.temp.name)
shutil.copytree(headers, work / "include/vulkan", ignore=shutil.ignore_patterns("*.hpp"))
if (headers.parent / "vk_video").is_dir():
shutil.copytree(headers.parent / "vk_video", work / "include/vk_video")
cls.binary = work / "ddfg-flow-levels"
build = subprocess.run([
compiler, "-std=c++17", "-O2", "-Wall", "-Wextra",
"-Wno-missing-field-initializers", "-Wno-misleading-indentation",
"-I" + str(work / "include"), "-I" + str(CHAIN),
str(ROOT / "tools/tests/ddfg_flow_levels_harness.cpp"), str(CHAIN / "framegen.cpp"),
"-o", str(cls.binary),
], capture_output=True, text=True, timeout=120)
if build.returncode:
raise RuntimeError(build.stdout + build.stderr)
def run_case(self, mode="resources", model=4, preset=2, width=1280, height=720, generations=1, repeats=1):
result = subprocess.run([
str(self.binary), mode, str(model), str(preset), str(width), str(height),
str(generations), str(repeats),
], capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertTrue(result.stdout.startswith("PASS "), result.stdout)
return dict(re.findall(r"(\w+)=(\w+)", result.stdout))
def test_each_model_and_preset_allocates_only_solved_flow_levels(self):
for model in (3, 4):
for preset, finest in enumerate((1, 2, 3)):
with self.subTest(model=model, preset=preset):
values = self.run_case(model=model, preset=preset)
self.assertEqual(int(values["images"]), 32 - 2 * finest)
self.assertEqual(int(values["buffers"]), 18 - finest)
self.assertEqual(int(values["sets"]), 54 - 4 * finest)
def test_default_preset_saves_the_exact_high_resolution_flow_payload(self):
for width, height in ((1280, 720), (1920, 1080), (2560, 1440)):
with self.subTest(width=width, height=height):
values = self.run_case(width=width, height=height)
pixels = lambda level: max(width >> level, 1) * max(height >> level, 1)
luma_bytes = 4 * (2 * sum(pixels(l) for l in range(7)) +
sum(pixels(l) for l in range(3, 7)))
flow_bytes = 8 * (sum(pixels(l) for l in range(3, 7)) +
2 * width * height + 2 * pixels(3))
self.assertEqual(int(values["bytes"]), luma_bytes + flow_bytes)
def test_small_and_odd_extents_keep_valid_bindings_and_dispatch_sizes(self):
for width, height in ((1, 1), (17, 9), (135, 73)):
for preset in range(3):
with self.subTest(width=width, height=height, preset=preset):
self.run_case(width=width, height=height, preset=preset)
def test_two_three_and_four_times_generation_keep_the_same_dispatch_schedule(self):
for model in (3, 4):
for preset in range(3):
for generations in (1, 2, 3):
with self.subTest(model=model, preset=preset, generations=generations):
self.run_case("record", model=model, preset=preset, generations=generations, repeats=3)
def test_resize_rebuilds_every_solved_level(self):
for preset in range(3):
with self.subTest(preset=preset):
self.run_case("resize", preset=preset, generations=3, repeats=3)
def test_live_preset_changes_rebuild_the_level_range(self):
for model in (3, 4):
with self.subTest(model=model):
self.run_case("preset", model=model, generations=3, repeats=4)
if __name__ == "__main__":
unittest.main()
+74
View File
@@ -0,0 +1,74 @@
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
TOOLS = Path(__file__).resolve().parents[1]
GPU = TOOLS / "linuxfs/desktop/droiddeck-gpu"
WINDOW = TOOLS / "linuxfs/overlay/usr/local/bin/droiddeck-gpu-window"
KEYS = ("MESA_VK_WSI_DEBUG", "SDL_VIDEODRIVER", "WAYLAND_DISPLAY", "BL_GPU_CHILD_WSI", "BL_DESKTOP_GPU_CHILD")
class DesktopGpuWindowTest(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.tmp, True)
self.out = self.tmp / "gamescope.json"
fake = self.tmp / "gamescope"
fake.write_text("#!%s\nimport json, os, sys\njson.dump({'args': sys.argv[1:], 'env': {k: os.environ.get(k) for k in %r}}, open(%r, 'w'))\n"
% (sys.executable, KEYS, str(self.out)))
fake.chmod(0o755)
def run_gpu(self, **env):
base = {k: v for k, v in os.environ.items() if k not in KEYS + ("BL_DEBUG_DIR", "BL_DESKTOP_GPU_WINDOW")}
base.update(PATH="%s:%s" % (self.tmp, os.environ["PATH"]), BL_WIDTH="1280", BL_HEIGHT="720", **env)
subprocess.run(["bash", str(GPU), "game.exe"], env=base, check=True, capture_output=True)
return json.loads(self.out.read_text())
def test_on_the_desktop_the_game_gets_a_window_of_its_own(self):
run = self.run_gpu(WAYLAND_DISPLAY="wayland-1", MESA_VK_WSI_DEBUG="sw,linear")
self.assertEqual(run["args"][:2], ["--backend", "sdl"])
self.assertNotIn("-f", run["args"])
self.assertEqual(run["args"][-2:], ["/usr/local/bin/droiddeck-gpu-window", "game.exe"])
self.assertEqual(run["env"]["WAYLAND_DISPLAY"], "wayland-1")
self.assertEqual(run["env"]["SDL_VIDEODRIVER"], "wayland")
self.assertEqual(run["env"]["MESA_VK_WSI_DEBUG"], "sw")
self.assertEqual(run["env"]["BL_GPU_CHILD_WSI"], "linear")
self.assertEqual(run["env"]["BL_DESKTOP_GPU_CHILD"], "1")
def test_full_screen_stays_available(self):
for env in ({"WAYLAND_DISPLAY": "wayland-1", "BL_DESKTOP_GPU_WINDOW": "0"}, {"WAYLAND_DISPLAY": "wayland-0"}, {}):
run = self.run_gpu(**env)
self.assertEqual(run["args"][:2], ["--backend", "wayland"])
self.assertIn("-f", run["args"])
self.assertEqual(run["env"]["WAYLAND_DISPLAY"], "wayland-0")
self.assertIsNone(run["env"]["MESA_VK_WSI_DEBUG"])
self.assertIsNone(run["env"]["BL_GPU_CHILD_WSI"])
def test_the_game_inside_the_window_gets_its_own_settings_back(self):
script = "import json, os; print(json.dumps({k: os.environ.get(k) for k in %r}))" % (KEYS,)
for saved, expected in (("linear", "linear"), ("", None)):
env = {k: v for k, v in os.environ.items() if k not in KEYS + ("DISPLAY",)}
env.update(BL_GPU_CHILD_WSI=saved, MESA_VK_WSI_DEBUG="sw", SDL_VIDEODRIVER="wayland")
out = subprocess.run([sys.executable, str(WINDOW), sys.executable, "-c", script], env=env,
check=True, capture_output=True, text=True).stdout
child = json.loads(out)
self.assertEqual(child["MESA_VK_WSI_DEBUG"], expected)
self.assertEqual(child["SDL_VIDEODRIVER"], "x11")
self.assertIsNone(child["BL_GPU_CHILD_WSI"])
def test_outside_a_window_the_game_keeps_its_settings(self):
script = "import os; print(os.environ.get('MESA_VK_WSI_DEBUG'), os.environ.get('SDL_VIDEODRIVER'))"
env = {k: v for k, v in os.environ.items() if k not in KEYS + ("DISPLAY",)}
env.update(MESA_VK_WSI_DEBUG="linear", SDL_VIDEODRIVER="x11")
out = subprocess.run([sys.executable, str(WINDOW), sys.executable, "-c", script], env=env,
check=True, capture_output=True, text=True).stdout.split()
self.assertEqual(out, ["linear", "x11"])
if __name__ == "__main__":
unittest.main()
+97
View File
@@ -456,6 +456,15 @@ class ProtonRunTest(Temp):
("0", "0", str(appid << 32 | 0x02000000), "1"))
self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], str(self.root / ("steamapps/compatdata/%d" % appid)))
def test_a_window_draws_with_the_desktops_software_gl(self):
target = RUN["Target"]("2596113170", "/c", "/i", str(self.root), "fixed")
session = {"MESA_LOADER_DRIVER_OVERRIDE": "zink", "GALLIUM_DRIVER": "zink", "LIBGL_KOPPER_DRI2": "true"}
env = RUN["environment"](session, target, "/tool", str(self.root), window=True)
self.assertEqual((env["LIBGL_ALWAYS_SOFTWARE"], env["GALLIUM_DRIVER"]), ("1", "llvmpipe"))
self.assertNotIn("MESA_LOADER_DRIVER_OVERRIDE", env)
self.assertNotIn("LIBGL_KOPPER_DRI2", env)
self.assertEqual(RUN["environment"](session, target, "/tool", str(self.root))["GALLIUM_DRIVER"], "zink")
def test_a_steam_game_keeps_its_own_id(self):
target = RUN["Target"]("413150", "/c", "/i", str(self.root), "steam")
env = RUN["environment"]({"PROTON_USE_WINED3D": "0"}, target, "/tool", str(self.root), window=True)
@@ -465,6 +474,13 @@ class ProtonRunTest(Temp):
self.assertEqual(RUN["arguments"]("/root/x/setup.msi", ["/qn"]), ["msiexec", "/i", "Z:\\root\\x\\setup.msi", "/qn"])
self.assertEqual(RUN["arguments"]("/root/x/a.exe", ["-w"]), ["/root/x/a.exe", "-w"])
def test_a_virtual_desktop_runs_the_program_by_its_windows_path(self):
pfx = "/root/Steam/steamapps/compatdata/2596113170"
self.assertEqual(RUN["arguments"](pfx + "/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe", [], "1280x720", pfx),
["explorer.exe", "/desktop=droiddeck,1280x720", "C:\\Program Files (x86)\\Battle.net\\Battle.net Launcher.exe"])
self.assertEqual(RUN["arguments"]("/root/.cache/setup.exe", ["--lang=enUS"], "1920x1080", pfx),
["explorer.exe", "/desktop=droiddeck,1920x1080", "Z:\\root\\.cache\\setup.exe", "--lang=enUS"])
def test_a_games_own_program_is_left_to_steam(self):
self.write("Steam/appcache/appinfo.vdf", appinfo({413150: STARDEW}))
self.assertEqual(RUN["compat"]()["launch_programs"](STARDEW["config"]),
@@ -554,6 +570,50 @@ class ProtonRunTest(Temp):
self.game("70", "Linux Game", "run.sh")
self.assertEqual(self.run_main(["--app", "70"])[0], 2)
def test_without_steam_a_shortcut_reuses_a_signed_prefix_folder(self):
bat = self.write("Games/Epic/Game/.droiddeck-launch.bat", b"@echo off")
start = self.tmp / "Games/Epic/Game/Binaries"
start.mkdir()
signed = self.root / "steamapps/compatdata/-1561598272"
signed.mkdir(parents=True)
code, calls, dirs = self.run_main(["--app", "2733369024", "--dir", str(start), "--", str(bat)])
self.assertIsNone(code)
env = calls[0][2]
self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], str(signed))
self.assertFalse((self.root / "steamapps/compatdata/2733369024").exists())
def test_prefix_folder_prefers_initialized_unsigned_over_empty_signed(self):
signed = self.root / "steamapps/compatdata/-1561598272"
signed.mkdir(parents=True)
initialized = self.root / "steamapps/compatdata/2733369024/pfx"
initialized.mkdir(parents=True)
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), str(initialized.parent))
def test_prefix_folder_prefers_initialized_signed_over_empty_unsigned(self):
unsigned = self.root / "steamapps/compatdata/2733369024"
unsigned.mkdir(parents=True)
initialized = self.root / "steamapps/compatdata/-1561598272/pfx"
initialized.mkdir(parents=True)
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), str(initialized.parent))
def test_prefix_folder_prefers_unsigned_when_initialization_ties(self):
unsigned = self.root / "steamapps/compatdata/2733369024/pfx"
unsigned.mkdir(parents=True)
signed = self.root / "steamapps/compatdata/-1561598272/pfx"
signed.mkdir(parents=True)
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), str(unsigned.parent))
def test_prefix_folder_skips_numeric_names_too_long_to_convert(self):
from unittest.mock import patch
folder = self.root / "steamapps/compatdata"
folder.mkdir(parents=True)
with patch.object(RUN["os"], "listdir", return_value=["9" * 5000]):
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024),
str(folder / "2733369024"))
def test_without_steam_a_shortcut_keeps_its_prefix_folder_and_launch_options(self):
bat = self.write("Games/Epic/Game/.droiddeck-launch.bat", b"@echo off")
start = self.tmp / "Games/Epic/Game/Binaries"
@@ -568,6 +628,43 @@ class ProtonRunTest(Temp):
self.assertTrue((self.root / "steamapps/compatdata/2733369024").is_dir())
self.assertEqual(dirs, [str(start)])
def write_account(self):
self.write("Steam/config/loginusers.vdf",
'"users"\n{\n\t"76561198352563669"\n\t{\n\t\t"MostRecent"\t\t"1"\n\t}\n}\n')
return "Steam/userdata/392297941/config/"
def test_without_steam_and_options_a_game_takes_its_steam_launch_options(self):
config = self.write_account()
self.write(config + "localconfig.vdf", '"UserLocalConfigStore"\n{\n\t"Software"\n\t{\n\t\t"Valve"\n\t\t{\n'
'\t\t\t"Steam"\n\t\t\t{\n\t\t\t\t"apps"\n\t\t\t\t{\n\t\t\t\t\t"413150"\n\t\t\t\t\t{\n'
'\t\t\t\t\t\t"cloud"\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t"LaunchOptions"\t\t"-wrong"\n\t\t\t\t\t\t}\n'
'\t\t\t\t\t\t"LaunchOptions"\t\t"DXVK_HUD=1 %command% -d3d9 \\"-name=Two Words\\""\n'
'\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n')
shortcuts = runpy.run_path(str(BIN / "droiddeck-steam-shortcuts"))
self.write(config + "shortcuts.vdf", shortcuts["write"]({"shortcuts": {
"0": {"appid": -1561598272, "AppName": "Batman", "LaunchOptions": "-d3d9"},
"1": {"appid": -1, "AppName": "Other", "LaunchOptions": "-x"},
}}))
root = str(self.root)
self.assertEqual(RUN["steam_options"]("413150", root), 'DXVK_HUD=1 %command% -d3d9 "-name=Two Words"')
self.assertEqual(RUN["steam_options"]("2733369024", root), "-d3d9")
self.assertEqual(RUN["steam_options"]("70", root), "")
self.assertEqual(RUN["steam_options"]("2733369025", root), "")
info = {"common": {"type": "Game"}, "config": {"launch": {
"0": {"executable": "Game.exe", "type": "default", "config": {"oslist": "windows"}}}}}
self.write("Steam/appcache/appinfo.vdf", appinfo({413150: info}))
program = self.game("413150", "Some Game", "Game.exe")
code, calls, _ = self.run_main(["--app", "413150"])
self.assertIsNone(code)
_, argv, env = calls[0]
self.assertEqual(argv[1:], ["waitforexitandrun", str(program), "-d3d9", "-name=Two Words"])
self.assertEqual(env["DXVK_HUD"], "1")
bat = self.write("Games/GOG/Batman/Batman.exe", b"MZ")
code, calls, _ = self.run_main(["--app", "2733369024", "--", str(bat)])
self.assertEqual(calls[0][1][1:], ["waitforexitandrun", str(bat), "-d3d9"])
code, calls, _ = self.run_main(["--app", "2733369024", "--options", "", "--", str(bat)])
self.assertEqual(calls[0][1][1:], ["waitforexitandrun", str(bat)])
def test_launch_options_split_like_steam_does(self):
split = RUN["split_options"]
self.assertEqual(split(""), ({}, []))
+172
View File
@@ -0,0 +1,172 @@
import json
from pathlib import Path
import runpy
import subprocess
import tempfile
import unittest
from unittest import mock
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat"))
class DeviceControlsTest(unittest.TestCase):
def test_sync_controls_queued_notifications_are_processed_without_another_frame(self):
with tempfile.TemporaryDirectory() as directory:
Path(directory, "state.json").write_text(json.dumps({"brightness": 0.5, "revision": 1}))
helper = LIVE["Helper"]("/steam", 0)
helper.controls_installed = True
page = mock.Mock(events=[])
page.ws.pending.return_value = False
helper.page = page
payload = json.dumps({"id": 1, "options": {"strTitle": "Pick a file"}})
def evaluate(expression):
for name, value in [(LIVE["BRIGHTNESS_BINDING"], "0.4"), (LIVE["FILE_BINDING"], payload)]:
page.events.append({"method": "Runtime.bindingCalled", "params": {"name": name, "payload": value}})
return True
def drain():
events, page.events = page.events, []
return events
page.evaluate.side_effect = evaluate
page.drain.side_effect = drain
helper.reconcile = mock.Mock()
helper.sync_frame_limit = mock.Mock()
helper.ensure_tools = mock.Mock(side_effect=[None, StopIteration])
helper.open_chooser = mock.Mock()
watcher = mock.Mock()
watcher.fileno.return_value = -1
watcher.changed.return_value = False
globals_ = LIVE["Helper"].serve.__globals__
with mock.patch.dict(globals_, {"CONTROLS_DIR": directory,
"brightness_request": lambda value: LIVE["brightness_request"](value, directory)}), \
mock.patch.dict(globals_["COMPAT"], {"state_path": lambda name: str(Path(directory, name))}), \
mock.patch.object(globals_["select"], "select", return_value=([], [], [])) as select_:
with self.assertRaises(StopIteration):
helper.serve(watcher)
self.assertEqual(float(Path(directory, "brightness.request").read_text()), 0.4)
helper.open_chooser.assert_called_once_with(payload)
self.assertEqual(page.events, [])
select_.assert_not_called()
def test_native_brightness_notifications_do_not_echo_android_readback(self):
harness = r"""
const assert = require('assert');
globalThis.window = globalThis;
const requests = [], callbacks = [];
const timers = [];
globalThis.setTimeout = callback => timers.push(callback);
let current = 1;
window.droiddeckBrightnessChanged = value => requests.push(Number(value));
globalThis.SteamClient = { System: { Display: {
RegisterForBrightnessChanges(cb) { callbacks.push(cb); cb({ flBrightness: 1 }); return {}; },
SetBrightness(value) {
if (current === value) return;
current = value;
callbacks.forEach(cb => cb({ flBrightness: value }));
}
} } };
const script = require('fs').readFileSync(process.argv[2], 'utf8');
assert.strictEqual(eval(script), 'installed');
assert.strictEqual(eval(script), 'present');
const bridge = window.__droiddeckBrightness;
bridge.set(0.5);
bridge.set(0.5);
assert.deepStrictEqual(requests, []);
callbacks.forEach(cb => cb({ flBrightness: 0.8 }));
assert.deepStrictEqual(requests, [0.8]);
bridge.set(0.7992126);
assert.deepStrictEqual(requests, [0.8]);
for (const value of [NaN, Infinity, -1, 2, '0.5']) callbacks.forEach(cb => cb({ flBrightness: value }));
assert.deepStrictEqual(requests, [0.8]);
assert.strictEqual(callbacks.length, 1);
SteamClient.System.Display.SetBrightness = value => callbacks.forEach(cb => cb({ flBrightness: value + 0.1 }));
bridge.set(0.3);
assert.deepStrictEqual(requests, [0.8]);
callbacks.forEach(cb => cb({ flBrightness: 0.6 }));
assert.deepStrictEqual(requests, [0.8, 0.6]);
SteamClient.System.Display.SetBrightness = () => {};
bridge.set(0.65);
timers.forEach(callback => callback());
callbacks.forEach(cb => cb({ flBrightness: 0.7 }));
assert.deepStrictEqual(requests, [0.8, 0.6, 0.7]);
"""
with tempfile.TemporaryDirectory() as directory:
script = Path(directory) / "bridge.js"
script.write_text(LIVE["BRIGHTNESS_JS"])
test = Path(directory) / "test.js"
test.write_text(harness)
result = subprocess.run(["node", str(test), str(script)], capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
def test_requests_reject_nonfinite_and_out_of_range_values(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "brightness.request"
for value in ["NaN", "Infinity", "-0.1", "1.1", "invalid", None]:
LIVE["brightness_request"](value, directory)
self.assertFalse(path.exists())
LIVE["brightness_request"]("0.4", directory)
self.assertEqual(float(path.read_text()), 0.4)
def test_failed_request_revision_republishes_the_actual_brightness(self):
with tempfile.TemporaryDirectory() as directory:
globals_ = LIVE["Helper"].sync_controls.__globals__
previous = globals_["CONTROLS_DIR"]
try:
globals_["CONTROLS_DIR"] = directory
helper = LIVE["Helper"]("/steam", 0)
calls = []
helper.controls_installed = True
helper.page = type("Page", (), {"evaluate": lambda self, expression: calls.append(expression) or True})()
path = Path(directory) / "state.json"
path.write_text(json.dumps({"brightness": 0.5, "revision": 1}))
helper.sync_controls()
helper.sync_controls()
self.assertEqual(len(calls), 1)
path.write_text(json.dumps({"brightness": 0.5, "revision": 2}))
helper.sync_controls()
self.assertEqual(len(calls), 2)
finally:
globals_["CONTROLS_DIR"] = previous
def test_display_bridge_retries_binding_and_install_before_caching_state(self):
with tempfile.TemporaryDirectory() as directory:
globals_ = LIVE["Helper"].sync_controls.__globals__
previous = globals_["CONTROLS_DIR"]
try:
globals_["CONTROLS_DIR"] = directory
Path(directory, "state.json").write_text(json.dumps({"brightness": 0.5, "revision": 1}))
calls, installs, writes = [], ["unavailable", "installed", "present"], []
class Page:
present = True
def call(self, method, params):
calls.append((method, params))
def evaluate(self, expression):
if expression == LIVE["BRIGHTNESS_JS"]:
return installs.pop(0)
writes.append(expression)
return self.present
helper = LIVE["Helper"]("/steam", 0)
helper.page = Page()
helper.sync_controls()
self.assertIsNone(helper.controls_state)
self.assertFalse(writes)
helper.sync_controls()
helper.sync_controls()
self.assertEqual(len(calls), 2)
self.assertEqual(len(writes), 1)
self.assertEqual(calls[1], ("Runtime.addBinding", {"name": LIVE["BRIGHTNESS_BINDING"]}))
helper.page.present = False
Path(directory, "state.json").write_text(json.dumps({"brightness": 0.7, "revision": 2}))
helper.sync_controls()
self.assertIsNone(helper.controls_state)
self.assertFalse(helper.controls_installed)
helper.page.present = True
helper.sync_controls()
self.assertEqual(len(calls), 3)
self.assertEqual(helper.controls_state["brightness"], 0.7)
finally:
globals_["CONTROLS_DIR"] = previous
if __name__ == "__main__":
unittest.main()
+12
View File
@@ -47,6 +47,8 @@ elif a[:1] == ["shell"]:
s.setdefault("log_commands", []).append(a)
p.write_text(json.dumps(s))
if "ls" in a: print(s["session"])
elif a[-1].endswith("/device.txt"): print(s.get("report", ""))
elif a[-1].endswith("/app.log"): print(s.get("app_log", ""))
else: print("package not debuggable")
'''
@@ -112,6 +114,16 @@ class DeviceSmokeTest(unittest.TestCase):
self.assertEqual(1, result.returncode, result.stdout)
self.assertIn("could not launch", result.stdout)
def test_fast_path_requires_a_session_activation_log(self):
for active in (False, True):
with self.subTest(active=active):
result, _ = self.run_smoke(
session="session", report="proot fast path (eligible) true",
app_log="proot: fast path on (66 binds)" if active else "proot: fast path off - too many binds",
)
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
self.assertEqual(active, "PASS proot fast path was on" in result.stdout)
def test_session_name_remains_one_remote_argument(self):
session = "x';id;#"
result, state = self.run_smoke(session=session)
+57
View File
@@ -196,6 +196,63 @@ class AgentTest(unittest.TestCase):
answer = self.ask({"kind": "vr", "action": "status"})
self.assertEqual("UNAVAILABLE", answer["error"]["code"])
def fake_proc(self, pid, parent, comm, env):
root = self.dir / "proc" / str(pid)
root.mkdir(parents=True)
(root / "comm").write_text(comm + "\n")
(root / "stat").write_text("%d (%s) S %d 0 0" % (pid, comm, parent))
(root / "environ").write_bytes(b"\0".join(b"%s=%s" % (k.encode(), v.encode()) for k, v in env.items()) + b"\0")
def tag(self, wins, arch="arm64"):
snap = {"displays": {":0": [], ":1": wins}}
with patch.dict(os.environ, {"DISPLAY": ":0", "BL_STEAM_CLIENT_ARCH": arch}), \
patch.object(agent.subprocess, "run") as run, patch.object(agent, "log"):
run.return_value.returncode = 0
tagged = agent.tag_game_windows(snap, proc=self.dir / "proc")
return tagged, [call.args[0][-1] for call in run.call_args_list]
def test_a_sandboxed_flatpak_window_is_tagged_with_its_shortcut(self):
self.fake_proc(40, 1, "gjs", {"FLATPAK_ID": "com.github.tchx84.Flatseal", "SteamAppId": "2166984148"})
win = {"window": 7, "map": "viewable", "class": "com.github.tchx84.Flatseal", "pid": None}
self.assertEqual(self.tag([win]), (True, ["2166984148"]))
def test_a_flatpak_window_named_after_the_app_is_matched(self):
self.fake_proc(40, 1, "vacuumtube", {"FLATPAK_ID": "rocks.shy.VacuumTube", "SteamAppId": "3000000001"})
win = {"window": 7, "map": "viewable", "class": "VacuumTube", "pid": None}
self.assertEqual(self.tag([win]), (True, ["3000000001"]))
def test_a_window_whose_process_has_no_app_id_falls_back_to_its_flatpak(self):
self.fake_proc(40, 1, "bwrap", {"FLATPAK_ID": "com.github.tchx84.Flatseal", "SteamAppId": "2166984148"})
self.fake_proc(41, 1, "gjs", {})
win = {"window": 7, "map": "viewable", "class": "com.github.tchx84.Flatseal", "pid": 41}
self.assertEqual(self.tag([win]), (True, ["2166984148"]))
def test_a_flatpak_shared_by_two_shortcuts_is_not_guessed(self):
self.fake_proc(40, 1, "gjs", {"FLATPAK_ID": "com.github.tchx84.Flatseal", "SteamAppId": "2166984148"})
self.fake_proc(42, 1, "gjs", {"FLATPAK_ID": "com.github.tchx84.Flatseal", "SteamAppId": "3000000003"})
win = {"window": 7, "map": "viewable", "class": "com.github.tchx84.Flatseal", "pid": None}
self.assertEqual(self.tag([win]), (False, []))
def test_a_window_outside_the_reaper_takes_its_process_app_id(self):
self.fake_proc(30, 1, "proot", {})
self.fake_proc(31, 30, "electron", {"SteamAppId": "3000000002"})
win = {"window": 8, "map": "viewable", "class": "electron", "pid": 31}
self.assertEqual(self.tag([win]), (True, ["3000000002"]))
def test_windows_gamescope_already_resolves_are_left_alone(self):
self.fake_proc(20, 1, "reaper", {})
self.fake_proc(21, 20, "game", {"SteamAppId": "413150"})
wins = [{"window": 9, "map": "viewable", "class": "game", "pid": 21},
{"window": 10, "map": "viewable", "class": "tagged", "pid": None, "appId": 5},
{"window": 11, "map": "viewable", "class": "other", "pid": None},
{"window": 12, "map": "unmapped", "class": "game", "pid": 21},
{"window": 13, "map": "viewable", "class": "steam_app_550", "pid": None}]
self.assertEqual(self.tag(wins), (False, []))
def test_the_x86_client_still_tags_its_game_classes(self):
win = {"window": 13, "map": "viewable", "class": "steam_app_550", "pid": None}
self.assertEqual(self.tag([win], arch="x86_64"), (True, ["550"]))
def test_exec_output_and_status(self):
answer = self.ask({"kind": "exec", "argv": ["sh", "-c", "echo out; echo err >&2; exit 3"], "env": {"X": "1"}})
self.assertTrue(answer["ok"])
+71
View File
@@ -48,6 +48,8 @@ class FexTestCase(unittest.TestCase):
"HOST_PRELOAD": str(self.tmp / "ld.so.preload"),
"DEVICE_FONTS": str(self.tmp / "android-fonts"),
"FONT_RULES": str(self.tmp / "66-droiddeck-device-fonts.conf"),
"OWN_FEX": str(self.tmp / "own"),
"OWN_FEX_TAG": str(self.tmp / "own/share/fex-emu/.droiddeck-tag"),
}
patcher = mock.patch.dict(G, patches)
patcher.start()
@@ -202,6 +204,75 @@ class LocateTest(FexTestCase):
self.assertEqual((fex["bin"], fex["server"], fex["portable"]), (str(tool / "usr/bin/FEX"), str(tool / "usr/bin/FEXServer"), True))
self.assertTrue(fex["host_thunks"].endswith("HostThunks") and fex["guest_thunks"].endswith("GuestThunks") and fex["thunks_db"])
def own_fex(self, tag, loads=True):
own = self.tmp / "own"
self.write(own / "bin/FEX", mode=0o755)
self.write(own / "bin/FEXServer", mode=0o755)
self.write(own / "share/fex-emu/.droiddeck-tag", tag + "\n")
listing = b"libc.so.6 => /usr/lib/libc.so.6\n" if loads else b"libxxhash.so.0 => not found\n"
patcher = mock.patch.object(G["subprocess"], "run", lambda args, **kw: subprocess.CompletedProcess(args, 0, listing))
patcher.start()
self.addCleanup(patcher.stop)
return own
def test_an_own_build_that_no_longer_loads_is_installed_again_and_skipped(self):
tool = self.fex_tool(self.steam)
self.own_fex("fex-2610-r7", loads=False)
calls = []
with mock.patch.dict(os.environ, {"BL_FEX_TAG": "fex-2610-r7"}), \
mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(args) or 1):
FEX["update_own_fex"]()
self.assertEqual([[str(BIN / "droiddeck-fex-update")]], calls)
self.assertEqual(FEX["fex_install"]()["bin"], str(tool / "usr/bin/FEX"))
def test_droiddeck_s_own_build_comes_before_the_steam_tool(self):
self.fex_tool(self.steam)
own = self.own_fex("fex-2610-r7")
fex = FEX["fex_install"]()
self.assertEqual((fex["bin"], fex["server"], fex["portable"]), (str(own / "bin/FEX"), str(own / "bin/FEXServer"), False))
def test_the_build_the_session_names_is_installed_once(self):
self.own_fex("fex-2610-r6")
calls = []
with mock.patch.dict(os.environ, {"BL_FEX_TAG": "fex-2610-r7"}), \
mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(args) or 0):
FEX["update_own_fex"]()
self.write(self.tmp / "own/share/fex-emu/.droiddeck-tag", "fex-2610-r7\n")
FEX["update_own_fex"]()
self.assertEqual([[str(BIN / "droiddeck-fex-update")]], calls)
def test_a_failed_build_waits_an_hour_unless_the_session_names_another(self):
self.own_fex("fex-2610-r6")
Path(G["STATE"]).mkdir(parents=True, exist_ok=True)
calls = []
tag = {"BL_FEX_TAG": "fex-2610-r7"}
with mock.patch.dict(os.environ, tag), \
mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(os.environ["BL_FEX_TAG"]) or 1):
FEX["update_own_fex"]()
FEX["update_own_fex"]()
failed = Path(G["STATE"]) / "update-failed"
os.utime(failed, (failed.stat().st_atime, failed.stat().st_mtime - 3601))
FEX["update_own_fex"]()
os.environ["BL_FEX_TAG"] = "fex-2610-r8"
FEX["update_own_fex"]()
self.assertEqual(["fex-2610-r7", "fex-2610-r7", "fex-2610-r8"], calls)
def test_a_missing_updater_falls_back_to_the_fex_already_here(self):
self.fex_tool(self.steam)
Path(G["STATE"]).mkdir(parents=True, exist_ok=True)
with mock.patch.dict(os.environ, {"BL_FEX_TAG": "fex-2610-r7"}), \
mock.patch.object(G["subprocess"], "call", mock.Mock(side_effect=FileNotFoundError)):
FEX["update_own_fex"]()
self.assertEqual(FEX["fex_install"]()["bin"], str(self.steam / "steamapps/common/FEX-Emu/usr/bin/FEX"))
def test_no_build_is_installed_without_one_from_the_session(self):
calls = []
with mock.patch.dict(os.environ, {}, clear=False), \
mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(args) or 0):
os.environ.pop("BL_FEX_TAG", None)
FEX["update_own_fex"]()
self.assertEqual([], calls)
def test_library_folders_are_read(self):
other = self.tmp / "other"
(other / "steamapps/common").mkdir(parents=True)
@@ -0,0 +1,95 @@
import json
import runpy
import tempfile
import unittest
from pathlib import Path
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
TOOL = COMPAT["TOOL"]
OLD = {"name": "DroidDeck-Proton-11-11.2", "display": "DroidDeck-Proton 11-11.2", "dir": "DroidDeck-Proton 11-11.2", "valve": False}
NEW = {"name": "DroidDeck-Proton-11-11.4", "display": "DroidDeck-Proton 11-11.4", "dir": "DroidDeck-Proton 11-11.4", "valve": False}
VALVE = {"name": TOOL, "display": "Proton Experimental ARM64", "dir": "Proton - Experimental (ARM64)", "valve": True}
GE = {"name": "GE-Proton11-7", "display": "GE-Proton11-7", "dir": "GE-Proton11-7", "valve": False}
def config_text(entries):
mapping = "".join('"%s" { "name" "%s" "config" "" "priority" "%s" }' % (app, name, "75" if app == "0" else "250") for app, name in entries)
return '"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { %s } } } } }' % mapping
class DroidDeckProtonDefaultTest(unittest.TestCase):
def run_default(self, state, mapping, catalog, apps=(), request=None, settle=True):
with tempfile.TemporaryDirectory() as tmp:
directory = Path(tmp)
(directory / "state.json").write_text(json.dumps(state))
if request is not None:
(directory / "request.json").write_text(json.dumps(request))
config = directory / "config.vdf"
config.write_text(config_text(mapping))
default = COMPAT["register_default"](str(config), list(apps), catalog=catalog, directory=str(directory), settle=settle)
return default, COMPAT["read_config_mapping"](str(config)), json.loads((directory / "state.json").read_text())
def test_a_replacement_seen_while_steam_runs_still_moves_the_default_later(self):
_, mapping, state = self.run_default(
{"default": OLD["name"], "own_proton": True, "tools": [VALVE, OLD]}, [("0", OLD["name"])], [VALVE, NEW], settle=False)
self.assertEqual(state["tools"], [VALVE, NEW])
self.assertIn(OLD["name"], state["own_builds"])
default, mapping, state = self.run_default(state, [("0", OLD["name"])], [VALVE, NEW])
self.assertEqual(default, NEW["name"])
self.assertEqual(mapping, {"0": NEW["name"]})
def test_a_valve_default_picked_in_steam_after_a_replacement_is_kept(self):
default, mapping, _ = self.run_default(
{"default": OLD["name"], "own_proton": True, "tools": [VALVE, OLD]}, [("0", TOOL)], [VALVE, NEW])
self.assertEqual(default, TOOL)
self.assertEqual(mapping, {"0": TOOL})
def test_the_first_start_with_droiddeck_proton_makes_it_the_default_for_following_titles(self):
default, mapping, state = self.run_default(
{"default": TOOL, "auto": {"42": TOOL}}, [("0", TOOL), ("42", TOOL), ("43", TOOL)], [VALVE, NEW], ["42", "43"])
self.assertEqual(default, NEW["name"])
self.assertEqual(mapping, {"0": NEW["name"], "42": NEW["name"], "43": TOOL})
self.assertEqual(state["default"], NEW["name"])
self.assertTrue(state["own_proton"])
def test_a_default_picked_after_the_switch_is_kept(self):
default, mapping, state = self.run_default(
{"default": NEW["name"], "own_proton": True, "applied": 1, "tools": [VALVE, NEW]},
[("0", NEW["name"])], [VALVE, NEW], request={"seq": 2, "valve": True, "dir": VALVE["dir"]})
self.assertEqual(default, TOOL)
self.assertEqual(mapping, {"0": TOOL})
default, mapping, state = self.run_default(
{"default": TOOL, "own_proton": True, "tools": [VALVE, NEW]}, [("0", TOOL)], [VALVE, NEW])
self.assertEqual(default, TOOL)
self.assertEqual(mapping, {"0": TOOL})
def test_a_replaced_build_moves_its_default_and_titles_to_the_newest(self):
default, mapping, state = self.run_default(
{"default": OLD["name"], "own_proton": True, "auto": {"42": OLD["name"]}, "tools": [VALVE, OLD, GE]},
[("0", OLD["name"]), ("42", OLD["name"]), ("43", OLD["name"]), ("44", GE["name"]), ("45", TOOL)],
[VALVE, NEW, GE], ["42", "43", "44", "45"])
self.assertEqual(default, NEW["name"])
self.assertEqual(mapping, {"0": NEW["name"], "42": NEW["name"], "43": NEW["name"], "44": GE["name"], "45": TOOL})
self.assertEqual(state["auto"], {"42": NEW["name"]})
def test_a_replaced_build_does_not_override_a_valve_default(self):
default, mapping, _ = self.run_default(
{"default": TOOL, "own_proton": True, "tools": [VALVE, OLD]}, [("0", TOOL), ("43", OLD["name"])], [VALVE, NEW], ["43"])
self.assertEqual(default, TOOL)
self.assertEqual(mapping, {"0": TOOL, "43": NEW["name"]})
def test_nothing_changes_without_droiddeck_proton(self):
default, mapping, state = self.run_default({"default": TOOL}, [("0", TOOL)], [VALVE, GE])
self.assertEqual(default, TOOL)
self.assertEqual(mapping, {"0": TOOL})
self.assertNotIn("own_proton", state)
def test_the_newest_build_is_found_by_version(self):
newest, gone = COMPAT["own_proton_moves"]({"tools": [OLD]}, [dict(NEW, name="a", dir="DroidDeck-Proton 11-9.10"), dict(NEW, name="b", dir="DroidDeck-Proton 11-11.1")])
self.assertEqual(newest, "b")
self.assertEqual(gone, {OLD["name"]})
if __name__ == "__main__":
unittest.main()
+15
View File
@@ -413,6 +413,21 @@ class DroiddeckctlTest(FakeAdbTest):
self.assertEqual("Awake", out["wakefulness"])
self.assertIn(["shell", "input", "keyevent", "KEYCODE_WAKEUP"], [c["args"] for c in self.calls()])
def test_proot_profile_queues_only_the_next_session(self):
self.configure({"env": {"ok": True}})
code, out = self.run_ctl("proot-profile", "enable", "--slow-us", "250")
self.assertEqual(0, code, out)
self.assertEqual({"op": "set", "lines": ["PROOT_PROFILE=1", "PROOT_PROFILE_SLOW_US=250"], "persistent": False},
self.calls("env")[0]["request"])
def test_proot_profile_report_needs_no_adb_or_device(self):
path = self.dir / "session.log"
path.write_text('ordinary log')
with unittest.mock.patch.object(ctl, "adb_path", side_effect=AssertionError("must stay offline")):
code, out = self.run_ctl("proot-profile", "report", str(path))
self.assertEqual(0, code, out)
self.assertFalse(out["hasCounters"])
def test_override_pushes_to_the_inbox_first(self):
self.configure({
"access": {"ok": True, "commands": True, "inbox": "/sdcard/Android/data/x/files/agent-inbox"},
+1 -1
View File
@@ -6,7 +6,7 @@ import tempfile
import textwrap
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-steam-x64"
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-fex-update"
SOURCE = SCRIPT.read_text()
START = SOURCE.index("fex_install() {")
END = SOURCE.index("\n}\n", START) + 3
+3 -3
View File
@@ -5,9 +5,9 @@ import tempfile
import textwrap
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-steam-x64"
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-fex-update"
SOURCE = SCRIPT.read_text()
START = SOURCE.index("x64_fex() {")
START = SOURCE.index("fex_ready() {")
END = SOURCE.index("\n}\n", START) + 3
X64_FEX = SOURCE[START:END]
@@ -35,7 +35,7 @@ class FexSelectTest(unittest.TestCase):
fex.chmod(0o755)
body = (X64_FEX.replace("/usr/local/share/fex-emu/.droiddeck-tag", "$ROOT/tag")
.replace("/usr/local/bin/FEX", "$ROOT/FEX"))
script = HARNESS + body + 'if x64_fex; then echo "NOW $FEX_NOW|$FEX_FROM"; else echo FAILED; fi\n'
script = HARNESS + body + 'if fex_ready; then echo "NOW $FEX_NOW|$FEX_FROM"; else echo FAILED; fi\n'
env = dict(os.environ, ROOT=root, LOADS="1" if loads else "0", INSTALLABLE=" ".join(installable))
env.pop("BL_FEX_TAG", None)
if catalog:
+67
View File
@@ -0,0 +1,67 @@
import contextlib
import fcntl
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-flatpak-setup"
class FlatpakSetupTest(unittest.TestCase):
def run_setup(self, uid, pacman, locked=False, busy=False):
with tempfile.TemporaryDirectory() as directory, contextlib.ExitStack() as held:
root = Path(directory)
if locked:
(root / "work/db").mkdir(parents=True)
(root / "work/db/db.lck").write_text("")
if busy:
holder = held.enter_context(open(root / "work/setup.lock", "w"))
fcntl.flock(holder, fcntl.LOCK_EX | fcntl.LOCK_NB)
bin_dir = root / "bin"
bin_dir.mkdir()
stubs = {"id": "echo %d" % uid, "curl": "exit 7", "pacman": pacman, "pacman-key": "exit 0"}
for name, body in stubs.items():
(bin_dir / name).write_text("#!/bin/sh\n%s\n" % body)
(bin_dir / name).chmod(0o755)
script = root / "setup"
script.write_text(SCRIPT.read_text().replace("WORK=/var/cache/droiddeck-flatpak", "WORK=%s/work" % root)
.replace("/etc/pacman.d/gnupg/pubring.gpg", str(root / "pubring.gpg"))
.replace(" /etc/pacman.conf >", " %s >" % (root / "pacman.conf")))
(root / "pacman.conf").write_text("[options]\n[core]\nInclude = /etc/pacman.d/mirrorlist\n")
(root / "pubring.gpg").write_text("")
env = dict(os.environ, PATH="%s:%s" % (bin_dir, os.environ["PATH"]))
result = subprocess.run(["bash", str(script)], env=env, capture_output=True, text=True, timeout=30)
return result.returncode, result.stdout
def test_a_manual_run_without_root_says_so(self):
code, out = self.run_setup(1000, "exit 0")
self.assertEqual(code, 1)
self.assertIn("== FAIL needs root", out)
self.assertNotIn("Reading the package lists", out)
def test_an_unreachable_mirror_reports_pacmans_error(self):
code, out = self.run_setup(0, "echo \"error: failed retrieving file 'core.db' : Could not resolve host\" >&2; exit 1")
self.assertEqual(code, 1)
self.assertIn("== FAIL could not reach the Arch Linux ARM mirrors (error: failed retrieving file 'core.db' : "
"Could not resolve host)", out)
SYNC = ("db=; while [ $# -gt 0 ]; do [ \"$1\" = --dbpath ] && db=$2; shift; done\n"
"[ -e \"$db/db.lck\" ] && { echo 'error: failed to synchronize all databases (unable to lock database)' >&2; exit 1; }\n"
"mkdir -p \"$db/sync\" && touch \"$db/sync/extra.db\"")
def test_a_lock_left_by_an_interrupted_run_is_cleared(self):
code, out = self.run_setup(0, self.SYNC, locked=True)
self.assertNotIn("unable to lock database", out)
self.assertIn("== STEP Downloading Flatpak", out)
def test_a_setup_that_is_still_running_keeps_its_lock(self):
code, out = self.run_setup(0, self.SYNC, locked=True, busy=True)
self.assertEqual(code, 1)
self.assertIn("== FAIL another Flatpak setup is still running", out)
self.assertNotIn("Reading the package lists", out)
if __name__ == "__main__":
unittest.main()
+139
View File
@@ -0,0 +1,139 @@
"""The Quick Access Frame Limit follows the panel when its refresh rate changes."""
from pathlib import Path
import runpy
import subprocess
import tempfile
import unittest
from unittest import mock
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat"))
HARNESS = r"""
const assert = require('assert');
globalThis.window = globalThis;
globalThis.btoa = text => Buffer.from(text, 'binary').toString('base64');
let timers = new Map(), nextTimer = 0;
globalThis.setTimeout = (callback, ms) => { timers.set(++nextTimer, callback); return nextTimer; };
globalThis.clearTimeout = id => timers.delete(id);
globalThis.setInterval = () => 0;
const fire = async () => {
const pending = [...timers.values()]; timers = new Map();
for (const callback of pending) await callback();
};
let rates = [36, 48, 72, 144];
const notify = [];
const service = {
GetState: async () => ({ BSuccess: () => true,
Body: () => ({ toObject: () => ({ state: { active_display_info: { supported_frame_rates: rates } } }) }) }),
RegisterForNotifyStateChanged(callback) { notify.push(callback); return {}; },
SetBlurParams() {},
};
const writes = [];
globalThis.settingsStore = { clientSettings: {
gamescope_enable_app_target_framerate: true, gamescope_app_target_framerate: 120, gamescope_disable_framelimit: false } };
const varints = bytes => { const out = []; let value = 0, shift = 0;
for (const b of bytes) { value += (b & 127) * 2 ** shift; shift += 7; if (b < 128) { out.push(value); value = 0; shift = 0; } }
return out; };
globalThis.SteamClient = { Settings: { SetSetting(encoded) {
const [key, value] = varints([...Buffer.from(encoded, 'base64')]);
assert.strictEqual(key, 21002 * 8);
writes.push(value);
settingsStore.clientSettings.gamescope_app_target_framerate = value;
} } };
const modules = {
1: { source: () => 'RegisterForNotifyStateChanged only', exports: { other: { GetState() {} } } },
2: { source: () => 'n.MX.SetBlurParams(); n.MX.RegisterForNotifyStateChanged()', exports: { hooks: () => {} } },
3: { source: () => 'SetBlurParams RegisterForNotifyStateChanged GetState', exports: { MX: service } },
};
const webpack = modules => { const require = id => modules[id].exports;
require.m = Object.fromEntries(Object.entries(modules).map(([id, m]) => [id, { toString: m.source }]));
return require; };
globalThis.webpackChunksteamui = { push([, , callback]) { callback(webpack(modules)); } };
const script = require('fs').readFileSync(process.argv[2], 'utf8');
const change = async next => { rates = next; notify.forEach(callback => callback()); };
(async () => {
assert.strictEqual(eval(script), 'installed');
assert.strictEqual(eval(script), 'present');
await fire();
assert.deepStrictEqual(writes, [144], 'a remembered limit the panel does not offer moves to the highest value');
await fire();
assert.deepStrictEqual(writes, [144], 'unchanged choices are not written again');
settingsStore.clientSettings.gamescope_app_target_framerate = 72;
await change([24, 30, 40, 60, 120]);
await fire();
assert.deepStrictEqual(writes, [144, 120], '72 is not offered at 120 Hz');
settingsStore.clientSettings.gamescope_app_target_framerate = 60;
await change([12, 15, 20, 30, 60]);
await fire();
assert.deepStrictEqual(writes, [144, 120], '60 is still offered at 60 Hz and is kept');
await change([18, 24, 36, 72]);
await change([24, 30, 40, 60, 120]);
await fire();
assert.deepStrictEqual(writes, [144, 120], 'a passing rate during a mode switch is not acted on');
settingsStore.clientSettings.gamescope_enable_app_target_framerate = false;
settingsStore.clientSettings.gamescope_app_target_framerate = 72;
await change([36, 48, 144]);
await fire();
assert.deepStrictEqual(writes, [144, 120], 'nothing changes while Steam has the frame limit turned off');
settingsStore.clientSettings.gamescope_enable_app_target_framerate = true;
window.__droiddeckFrameLimit.schedule();
await fire();
assert.deepStrictEqual(writes, [144, 120, 144], 'turning the limit on after a rate change moves an unoffered value');
settingsStore.clientSettings.gamescope_app_target_framerate = 72;
const setSetting = SteamClient.Settings.SetSetting;
SteamClient.Settings.SetSetting = () => { throw new Error('busy'); };
window.__droiddeckFrameLimit.schedule();
await fire();
SteamClient.Settings.SetSetting = setSetting;
window.__droiddeckFrameLimit.schedule();
await fire();
assert.deepStrictEqual(writes, [144, 120, 144, 144], 'a failed write is tried again on the next check');
settingsStore.clientSettings.gamescope_app_target_framerate = 72;
SteamClient.Settings.SetSetting = () => Promise.reject(new Error('busy'));
window.__droiddeckFrameLimit.schedule();
await fire();
SteamClient.Settings.SetSetting = setSetting;
window.__droiddeckFrameLimit.schedule();
await fire();
assert.deepStrictEqual(writes, [144, 120, 144, 144, 144], 'a rejected write is caught and tried again');
delete window.__droiddeckFrameLimit;
webpackChunksteamui.push = ([, , callback]) => callback(webpack({ 1: modules[1], 2: modules[2] }));
assert.strictEqual(eval(script), 'unavailable');
})().catch(error => { console.error(error); process.exit(1); });
"""
class FrameLimitSyncTest(unittest.TestCase):
def test_limit_is_kept_when_offered_and_moved_to_the_highest_value_otherwise(self):
with tempfile.TemporaryDirectory() as directory:
script = Path(directory) / "frame_limit.js"
script.write_text(LIVE["FRAME_LIMIT_JS"])
test = Path(directory) / "test.js"
test.write_text(HARNESS)
result = subprocess.run(["node", str(test), str(script)], capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
def test_install_is_retried_until_steam_is_ready_and_reported_once_per_state(self):
helper = LIVE["Helper"]("/steam", 0)
page = mock.Mock()
page.evaluate.side_effect = ["unavailable", "unavailable", "installed"]
helper.page = page
said = []
clock = [100.0]
globals_ = LIVE["Helper"].sync_frame_limit.__globals__
with mock.patch.dict(globals_, {"say": said.append}), mock.patch.object(globals_["time"], "monotonic", lambda: clock[0]):
helper.sync_frame_limit()
helper.sync_frame_limit()
clock[0] += 10
helper.sync_frame_limit()
clock[0] += 10
helper.sync_frame_limit()
clock[0] += 10
helper.sync_frame_limit()
self.assertEqual(page.evaluate.call_count, 3)
self.assertEqual(said, ["frame limit sync: unavailable", "frame limit sync: installed"])
if __name__ == "__main__":
unittest.main()
+216
View File
@@ -8,6 +8,7 @@ import shlex
import subprocess
import sys
import tempfile
from unittest import mock
import unittest
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
@@ -76,6 +77,35 @@ class GameEnvironmentTest(unittest.TestCase):
env=env, text=True, capture_output=True, check=True)
self.assertEqual(result.stdout.strip(), expected)
def test_desktop_games_restart_on_the_gpu_with_steams_preloads_handed_back(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
gpu = home / "gpu"
gpu.write_text("#!/bin/bash\necho \"gpu LD_PRELOAD=${LD_PRELOAD-unset}\"\nexport BL_DESKTOP_GPU_CHILD=1\nexec \"$@\"\n")
gpu.chmod(0o755)
launcher = home / "launcher"
setup = COMPAT["BL_DESKTOP_GPU_SETUP"].replace("/usr/local/bin/droiddeck-gpu", str(gpu))
launcher.write_text("#!/bin/bash\nverb=$1; shift\n" + setup + "echo \"game $verb $* LD_PRELOAD=${LD_PRELOAD-unset} saved=${BL_GPU_SAVED_LD_PRELOAD-unset}\"\n")
launcher.chmod(0o755)
base = {key: value for key, value in os.environ.items() if not key.startswith("BL_")}
base["LD_PRELOAD"] = "overlay.so"
for extra, args, expected in (
({"BL_DESKTOP": "1"}, ["waitforexitandrun", "game.exe"],
["gpu LD_PRELOAD=unset", "game waitforexitandrun game.exe LD_PRELOAD=overlay.so saved=unset"]),
({"BL_DESKTOP": "1", "BL_DESKTOP_GPU": "Off"}, ["waitforexitandrun", "game.exe"],
["game waitforexitandrun game.exe LD_PRELOAD=overlay.so saved=unset"]),
({"BL_DESKTOP": "1"}, ["run", "setup.exe"],
["game run setup.exe LD_PRELOAD=overlay.so saved=unset"]),
({"BL_DESKTOP": "1"}, ["waitforexitandrun", "iscriptevaluator.exe"],
["game waitforexitandrun iscriptevaluator.exe LD_PRELOAD=overlay.so saved=unset"]),
({}, ["waitforexitandrun", "game.exe"],
["game waitforexitandrun game.exe LD_PRELOAD=overlay.so saved=unset"]),
):
with self.subTest(extra=extra, args=args):
result = subprocess.run([str(launcher)] + args, env=dict(base, **extra),
text=True, capture_output=True, check=True)
self.assertEqual(result.stdout.splitlines(), expected)
def test_the_install_script_evaluator_gets_its_scripts_marked_first(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
@@ -180,6 +210,14 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(MODULE["apply_config"](env, config, "42")["TU_DEBUG"], "sysmem")
self.assertNotIn("TU_DEBUG", MODULE["apply_config"](env, config, "43"))
def test_the_vram_cap_comes_before_the_games_own_dxvk_settings(self):
cap = MODULE["vram_cap"]
self.assertEqual(cap({"BL_VRAM_MB": "4096"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4096")
self.assertEqual(cap({"BL_VRAM_MB": "2048", "DXVK_CONFIG": "dxvk.maxFrameRate = 60;"})["DXVK_CONFIG"],
"dxgi.maxDeviceMemory = 2048; dxvk.maxFrameRate = 60")
for off in ({}, {"BL_VRAM_MB": "0"}, {"BL_VRAM_MB": "lots"}, {"BL_VRAM_MB": "²"}, {"BL_VRAM_MB": "-1"}):
self.assertNotIn("DXVK_CONFIG", cap(off))
def test_a_games_wine_sync_choice_also_reaches_its_setup_runs(self):
env = {"BL_SYNC": "1", "BL_SYNC_FALLBACK": "1", "BL_FSYNC_FIRST": "0", "OTHER": "kept"}
config = {"version": 1, "games": {"42": {"BL_SYNC": "0", "BL_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "FEX_TSOENABLED": "1"}}}
@@ -264,6 +302,13 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(env["WINEDLLOVERRIDES"], "libsentry.windows.release.x86_64=d")
self.assertEqual(extra, ["--rendering-driver", "vulkan"])
self.assertEqual(MODULE["engine_fixes"](str(game / "Game.exe"), ["--rendering-driver", "opengl3"])[1], [])
script = Path(tmp) / "GDScript Game"
script.mkdir()
for name in ("Game.exe", "Game.pck", "libsentry.windows.release.x86_64.dll"):
(script / name).touch()
env, extra, notes = MODULE["engine_fixes"](str(script / "Game.exe"), [])
self.assertNotIn("WINEDLLOVERRIDES", env)
self.assertEqual(extra, ["--rendering-driver", "vulkan"])
other = Path(tmp) / "Other"
other.mkdir()
(other / "Other.exe").touch()
@@ -357,6 +402,131 @@ class GameEnvironmentTest(unittest.TestCase):
(asylum / name).touch()
self.assertEqual(MODULE["engine_fixes"](str(asylum / "BmLauncher.exe"), []), ({}, [], []))
def test_d3dgear_capture_hook_beside_the_game_is_turned_off(self):
with tempfile.TemporaryDirectory() as tmp:
game = Path(tmp) / "The Crew 2"
game.mkdir()
for name in ("TheCrew2.exe", "TheCrew2_BE.exe", "d3dgear64.dll"):
(game / name).touch()
env, extra, notes = MODULE["engine_fixes"](str(game / "TheCrew2.exe"), [])
self.assertEqual((env, extra), ({"WINEDLLOVERRIDES": "d3dgear64=d"}, []))
self.assertTrue(notes)
(game / "d3dgear64.dll").rename(game / "D3DGear64.DLL")
self.assertEqual(MODULE["engine_fixes"](str(game / "TheCrew2.exe"), [])[0], {"WINEDLLOVERRIDES": "d3dgear64=d"})
(game / "D3DGear64.DLL").unlink()
self.assertEqual(MODULE["engine_fixes"](str(game / "TheCrew2.exe"), []), ({}, [], []))
def test_dll_overrides_from_several_fixes_are_all_kept(self):
with tempfile.TemporaryDirectory() as tmp:
for name in ("Game.exe", "Game.pck", "GodotSharp.dll", "libsentry.windows.release.x86_64.dll", "d3dgear64.dll"):
(Path(tmp) / name).touch()
env = MODULE["engine_fixes"](str(Path(tmp) / "Game.exe"), [])[0]
self.assertEqual(env["WINEDLLOVERRIDES"], "libsentry.windows.release.x86_64=d;d3dgear64=d")
def test_black_ops_iii_and_dark_souls_remastered_skip_protonfixes(self):
for exe in ("/game/Call of Duty Black Ops III/BlackOps3.exe", "/game/DARK SOULS REMASTERED/DarkSoulsRemastered.exe"):
env, extra, notes = MODULE["engine_fixes"](exe, [])
self.assertEqual((env, extra), ({"PROTONFIXES_DISABLE": "1"}, []))
self.assertTrue(notes)
self.assertEqual(MODULE["engine_fixes"]("/game/Game/DarkSoulsII.exe", []), ({}, [], []))
def test_game_cores_are_parsed_from_lists_and_ranges(self):
parse = MODULE["parse_cores"]
self.assertEqual(parse("0-3,6"), {0, 1, 2, 3, 6})
self.assertEqual(parse(" 4, 5 "), {4, 5})
for bad in ("", "a", "3-1", "1,,2", "-1", "1-"):
self.assertIsNone(parse(bad), bad)
def test_a_profiles_game_cores_pin_the_game_within_the_online_cores(self):
calls = []
os_mod = MODULE["os"]
with mock.patch.dict(MODULE["game_cores"].__globals__, {"online_cores": lambda: {0, 1, 2, 3, 4, 5, 6, 7}}), \
mock.patch.object(os_mod, "sched_setaffinity", side_effect=lambda pid, cores: calls.append(set(cores)), create=True):
MODULE["game_cores"]({"DROIDDECK_GAME_CORES": "0-2,9"})
MODULE["game_cores"]({"DROIDDECK_GAME_CORES": "junk"})
MODULE["game_cores"]({"DROIDDECK_GAME_CORES": "12-13"})
MODULE["game_cores"]({})
self.assertEqual(calls, [{0, 1, 2}])
self.assertEqual(MODULE["parse_cores"]("0,2-7"), {0, 2, 3, 4, 5, 6, 7})
def test_windows_games_see_only_the_cores_they_are_pinned_to(self):
os_mod = MODULE["os"]
online = {"online_cores": lambda: {0, 1, 2, 3, 4, 5, 6, 7}}
cases = [
({"BL_GAME_CPUS": "6,7"}, {6, 7}, "2:6,7", "2:6,7"),
({"DROIDDECK_GAME_CORES": "0-2"}, {0, 1, 2}, "3:0,1,2", "3:0,1,2"),
({"BL_GAME_CPUS": "0-7"}, set(range(8)), None, None),
({}, {6, 7}, None, None),
({"BL_GAME_CPUS": "6,7", "WINE_CPU_TOPOLOGY": "4:0,1,2,3"}, {6, 7}, "4:0,1,2,3", "4:0,1,2,3"),
({"WINE_CPU_TOPOLOGY": "2:0,1"}, set(range(8)), "2:0,1", "2:0,1"),
({"BL_GAME_CPUS": "6,7", "WINE_CPU_TOPOLOGY": ""}, {6, 7}, "", None),
({"BL_GAME_CPUS": "6,7", "PROTON_CPU_TOPOLOGY": "1:7"}, {6, 7}, None, "1:7"),
({"BL_GAME_CPUS": "9"}, {9}, None, None),
]
for env, affinity, expected, proton in cases:
with mock.patch.dict(MODULE["cpu_topology"].__globals__, online), \
mock.patch.object(os_mod, "sched_getaffinity", return_value=affinity, create=True):
MODULE["cpu_topology"](env)
self.assertEqual(env.get("WINE_CPU_TOPOLOGY"), expected, env)
self.assertEqual(env.get("PROTON_CPU_TOPOLOGY"), proton, env)
def test_reskate_runs_at_feature_level_12_1(self):
with tempfile.TemporaryDirectory() as tmp:
reskate = Path(tmp) / "ReSkate"
reskate.mkdir()
for name in ("Skate.exe", "ReSkate.dll", "ReSkateLauncher.exe", "EAAntiCheat.GameServiceLauncher.exe"):
(reskate / name).touch()
for exe in ("ReSkateLauncher.exe", "Skate.exe"):
env, extra, notes = MODULE["engine_fixes"](str(reskate / exe), [])
self.assertEqual((env, extra), ({"VKD3D_FEATURE_LEVEL": "12_1"}, []), exe)
self.assertTrue(notes)
config = {"version": 1, "shared": {"VKD3D_FEATURE_LEVEL": "12_2"}}
self.assertEqual(MODULE["apply_config"]({}, config, "3354750", env)["VKD3D_FEATURE_LEVEL"], "12_1")
config["games"] = {"3354750": {"VKD3D_FEATURE_LEVEL": "12_2"}}
self.assertEqual(MODULE["apply_config"]({}, config, "3354750", env)["VKD3D_FEATURE_LEVEL"], "12_2")
skate = Path(tmp) / "Skate"
skate.mkdir()
for name in ("Skate.exe", "EAAntiCheat.GameServiceLauncher.exe"):
(skate / name).touch()
self.assertEqual(MODULE["engine_fixes"](str(skate / "EAAntiCheat.GameServiceLauncher.exe"), [])[:2], ({}, []))
def test_caravan_sandwitch_robocop_and_cyberpunk_run_at_feature_level_12_1(self):
with tempfile.TemporaryDirectory() as tmp:
caravan = Path(tmp) / "Caravan SandWitch"
shipping = caravan / "CaravanSandWitch/Binaries/Win64"
shipping.mkdir(parents=True)
for name in ("CaravanSandWitch.exe", ".droiddeck-launch.bat"):
(caravan / name).touch()
(shipping / "CaravanSandWitch-Win64-Shipping.exe").touch()
cyberpunk = Path(tmp) / "Cyberpunk 2077"
(cyberpunk / "bin/x64").mkdir(parents=True)
for name in ("REDprelauncher.exe", "bin/x64/Cyberpunk2077.exe"):
(cyberpunk / name).touch()
robocop = Path(tmp) / "RoboCop Rogue City"
(robocop / "RoboCop/Binaries/Win64").mkdir(parents=True)
for name in ("RoboCop.exe", "RoboCop/Binaries/Win64/RoboCop-Win64-Shipping.exe"):
(robocop / name).touch()
games = [caravan / "CaravanSandWitch.exe", caravan / ".droiddeck-launch.bat",
shipping / "CaravanSandWitch-Win64-Shipping.exe",
robocop / "RoboCop.exe", robocop / "RoboCop/Binaries/Win64/RoboCop-Win64-Shipping.exe",
cyberpunk / "REDprelauncher.exe", cyberpunk / "bin/x64/Cyberpunk2077.exe"]
for exe in games:
env, extra, notes = MODULE["engine_fixes"](str(exe), [])
self.assertEqual((env, extra), ({"VKD3D_FEATURE_LEVEL": "12_1"}, []), exe)
self.assertTrue(notes)
config = {"version": 1, "shared": {"VKD3D_FEATURE_LEVEL": "12_2"}}
self.assertEqual(MODULE["apply_config"]({}, config, "1582650", env)["VKD3D_FEATURE_LEVEL"], "12_1")
config["games"] = {"1582650": {"VKD3D_FEATURE_LEVEL": "12_2"}}
self.assertEqual(MODULE["apply_config"]({}, config, "1582650", env)["VKD3D_FEATURE_LEVEL"], "12_2")
other = Path(tmp) / "Other/Binaries/Win64"
other.mkdir(parents=True)
(other / "Other-Win64-Shipping.exe").touch()
self.assertEqual(MODULE["engine_fixes"](str(other / "Other-Win64-Shipping.exe"), []), ({}, [], []))
witcher = Path(tmp) / "The Witcher 3"
witcher.mkdir()
(witcher / "REDprelauncher.exe").touch()
self.assertNotIn("VKD3D_FEATURE_LEVEL", MODULE["engine_fixes"](str(witcher / "REDprelauncher.exe"), [])[0])
def test_unity_players_keep_tso_over_the_preset(self):
with tempfile.TemporaryDirectory() as tmp:
def game(*names):
@@ -1184,6 +1354,52 @@ class DirectAudioPrefixTest(unittest.TestCase):
self.assertIsNone(self.link("system32"))
class UbisoftOverlayTest(unittest.TestCase):
SETTINGS = (
"language:\n code: en-US\n"
"overlay:\n enabled: true\n forceunhookgame: false\n fps_enabled: false\n warning_enabled: true\n"
"patchTrigger:\n source: USER_RESTART\n"
)
def test_the_overlay_and_its_prompt_are_turned_off_and_the_rest_is_kept(self):
got = MODULE["overlay_off"](self.SETTINGS)
self.assertEqual(got, self.SETTINGS.replace("enabled: true", "enabled: false"))
self.assertEqual(MODULE["overlay_off"](got), got)
def test_missing_keys_or_section_are_added(self):
self.assertEqual(MODULE["overlay_off"]("overlay:\n fps_enabled: true\nmisc:\n a: 1\n"),
"overlay:\n fps_enabled: true\n enabled: false\n warning_enabled: false\nmisc:\n a: 1\n")
self.assertEqual(MODULE["overlay_off"](""), "overlay:\n enabled: false\n warning_enabled: false\n")
def test_blank_lines_inside_the_overlay_section_do_not_end_it(self):
text = "overlay:\n enabled: true\n\n warning_enabled: true\n\nmisc:\n a: 1\n"
self.assertEqual(MODULE["overlay_off"](text), text.replace("true", "false"))
self.assertEqual(MODULE["overlay_off"]("overlay:\n fps_enabled: true\n\nmisc:\n a: 1\n"),
"overlay:\n fps_enabled: true\n enabled: false\n warning_enabled: false\n\nmisc:\n a: 1\n")
def test_an_annotated_overlay_header_is_the_same_section(self):
self.assertEqual(MODULE["overlay_off"]("overlay: # in-game\n enabled: true\n"),
"overlay: # in-game\n enabled: false\n warning_enabled: false\n")
def test_only_prefixes_with_ubisoft_connect_are_touched(self):
with tempfile.TemporaryDirectory() as tmp:
prefix = Path(tmp) / "447040/pfx"
env = {"STEAM_COMPAT_DATA_PATH": str(prefix.parent)}
settings = prefix / MODULE["UBISOFT_SETTINGS"]
prefix.mkdir(parents=True)
MODULE["ubisoft_overlay_off"](env)
self.assertFalse(settings.exists())
(prefix / MODULE["UBISOFT_LAUNCHER"]).mkdir(parents=True)
MODULE["ubisoft_overlay_off"](env)
self.assertEqual(settings.read_text(), "overlay:\n enabled: false\n warning_enabled: false\n")
settings.write_text(self.SETTINGS)
settings.chmod(0o644)
MODULE["ubisoft_overlay_off"](env)
self.assertEqual(settings.read_text(), self.SETTINGS.replace("enabled: true", "enabled: false"))
self.assertEqual(settings.stat().st_mode & 0o777, 0o644)
self.assertEqual(sorted(p.name for p in settings.parent.iterdir()), ["settings.yaml"])
if __name__ == "__main__":
unittest.main()
+2
View File
@@ -66,6 +66,8 @@ static void send_toplevel_configure(struct surface *s) { (void)s; resizes++; }
#define pointer_button(...) ((void)0)
#define scroll_event(...) ((void)0)
#define axis_event(...) ((void)0)
#define stream_take(...) ((void)0)
#define stream_forget_all(...) ((void)0)
#define pointer_delta(...) ((void)0)
#define deliver_touch(m) ((void)0)
#define deliver_pointer(m) (pointers++)
+91
View File
@@ -0,0 +1,91 @@
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
TOOLS = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(TOOLS))
from proot_profile import report
PROGRAM = r'''
#define _POSIX_C_SOURCE 200809L
#define PR_NB_SYSNUM 2
#define PR_void 0
static const char *stringify_sysnum(unsigned nr) { return nr ? "openat" : "void"; }
#include "profile.h"
int main(void) {
errno = EBUSY;
if (!dd_profile_enabled()) return errno != EBUSY;
if (errno != EBUSY) return 1;
for (int i = 0; i < 40; i++) {
uint64_t wall = dd_profile_clock(CLOCK_MONOTONIC);
uint64_t cpu = dd_profile_clock(CLOCK_THREAD_CPUTIME_ID);
struct timespec wait = {0, 2000000};
nanosleep(&wait, 0);
errno = ENOENT;
dd_profile_record(1, 1, 123, wall, cpu);
if (errno != ENOENT) return 2;
if (i == 9) dd_profile_flush();
}
dd_profile_next = 0;
uint64_t wall = dd_profile_clock(CLOCK_MONOTONIC);
uint64_t cpu = dd_profile_clock(CLOCK_THREAD_CPUTIME_ID);
struct timespec wait = {0, 2000000};
nanosleep(&wait, 0);
dd_profile_record(1, 0, 123, wall, cpu);
return 0;
}
'''
class ProotProfileTest(unittest.TestCase):
def test_snapshots_replace_instead_of_adding_and_tracers_remain_separate(self):
with tempfile.TemporaryDirectory() as work:
path = Path(work) / 'session.log'
records = [dict(type='total', tracer=1, id=2, syscall='statx', stage='enter',
calls=n, wall_ns=n * 100, cpu_ns=n * 10, max_ns=100) for n in (3, 8)]
records.append(dict(records[-1], tracer=2, calls=2))
records += [dict(type='total', tracer=1, id=3, syscall='openat', stage='enter',
calls=1, wall_ns=1000, cpu_ns=1000, max_ns=1000)]
path.write_text('unrelated log\n' + ''.join('prefix proot-profile ' + json.dumps(r) + '\n' for r in records)
+ 'proot-profile {truncated\n' + 'proot-profile []\n')
result = report(path)
self.assertEqual(11, result['handlerCalls'])
self.assertEqual(3, result['tracers'])
self.assertEqual(2, result['malformedRecords'])
self.assertEqual('statx', result['totals'][0]['syscall'])
self.assertEqual('openat', report(path, 'cpu')['totals'][0]['syscall'])
def test_empty_logs_do_not_claim_profiling_ran(self):
with tempfile.TemporaryDirectory() as work:
path = Path(work) / 'session.log'
path.write_text('ordinary log\n')
self.assertFalse(report(path)['hasCounters'])
@unittest.skipUnless(shutil.which('cc'), 'C compiler required')
def test_real_clocks_bounded_samples_errno_and_periodic_counters(self):
with tempfile.TemporaryDirectory() as work:
source = Path(work) / 'profile.c'
binary = Path(work) / 'profile'
source.write_text(PROGRAM)
subprocess.run(['cc', '-Wall', '-Wextra', '-Werror', '-std=c99', '-I', str(TOOLS / 'proot'),
str(source), '-o', str(binary)], check=True)
for setting in ('0', ''):
result = subprocess.run([binary], env=dict(os.environ, PROOT_PROFILE=setting), capture_output=True, check=True)
self.assertEqual(b'', result.stderr)
result = subprocess.run([binary], env=dict(os.environ, PROOT_PROFILE='1', PROOT_PROFILE_SLOW_US='1'),
capture_output=True, check=True)
rows = [json.loads(line.split(b'proot-profile ', 1)[1]) for line in result.stderr.splitlines()]
self.assertEqual(33, sum(row['type'] == 'slow' for row in rows))
self.assertEqual(32, sum(row['type'] == 'slow' and row['stage'] == 'enter' for row in rows))
self.assertGreater(sum(row['type'] == 'total' for row in rows), 2)
log = Path(work) / 'session.log'
log.write_bytes(result.stderr)
counters = report(log)
self.assertEqual(41, counters['handlerCalls'])
self.assertGreater(counters['handlerWallNs'], counters['handlerCpuNs'])
self.assertEqual(40, counters['totals'][0]['calls'])
+48
View File
@@ -45,6 +45,26 @@ VULKAN_SCRIPT = r'''"InstallScript"
'''
UBISOFT_SCRIPT = r'''"installscript"
{
"Run Process"
{
"Ubisoft Connect PC Client"
{
"process 1" "%INSTALLDIR%\\UbisoftConnectInstaller.exe"
"command 1" "/S"
}
"easyanticheat"
{
"HasRunKey" "HKEY_CURRENT_USER\\SOFTWARE\\Ubisoft\\WatchDogs2EAC"
"process 1" "%INSTALLDIR%\\EasyAntiCheat\\InstallWD2EAC.cmd"
"command 1" ""
}
}
}
'''
class SeedRedistsTest(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp())
@@ -353,5 +373,33 @@ class SeedRedistsTest(unittest.TestCase):
self.assertEqual(self.reg.read_text().count('"Vulkan111080"'), 2)
def ubisoft(self):
script = self.tmp / "legacycompat/evaluatorscript_447040.vdf"
script.parent.mkdir(parents=True)
script.write_text('"evaluatorscript"\n{\n\t"appid"\t\t"447040"\n\t"1"\n'
+ "\n".join("\t" + line for line in UBISOFT_SCRIPT.splitlines()) + "\n}\n")
env = dict(os.environ, DROIDDECK_LIBRARIES="", DROIDDECK_SEED_SCRIPTS=str(script))
return subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
def test_the_ubisoft_connect_installer_is_left_to_run(self):
self.ubisoft()
self.assertIn('"easyanticheat"=dword:00000001', self.user.read_text())
self.assertNotIn("Ubisoft Connect PC Client", self.reg.read_text())
self.assertNotIn("Ubisoft Connect PC Client", (self.reg.parent / ".droiddeck-redists").read_text())
def test_a_ubisoft_connect_marker_an_earlier_seeding_wrote_comes_out(self):
marker = "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\447040\tUbisoft Connect PC Client"
self.reg.write_text(
"WINE REGISTRY Version 2\n"
"\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\447040] 1791729070\n"
'"Ubisoft Connect PC Client"=dword:00000001\n'
"\n[Software\\\\Wow6432Node\\\\Valve\\\\Steam\\\\Apps\\\\447040] 1791729070\n"
'"Ubisoft Connect PC Client"=dword:00000001\n')
(self.reg.parent / ".droiddeck-redists").write_text(marker + "\n")
result = self.ubisoft()
self.assertNotIn("Ubisoft Connect PC Client", self.reg.read_text())
self.assertNotIn("Ubisoft Connect PC Client", (self.reg.parent / ".droiddeck-redists").read_text())
self.assertIn("Ubisoft Connect markers out", result.stdout)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -22,7 +22,7 @@ PACKAGES = [line.split()[1] for line in VARIANTS.read_text().splitlines()
def guest_prefix(package):
source = SERVICE.read_text()
before_environment = source.split("val guest = ArrayList<String>()", 1)[1].split(
"addClientEnvironment(guest, steamHere)", 1)[0]
"addClientEnvironment(guest,", 1)[0]
environment = source.split("private fun addClientEnvironment(", 1)[1].split(
'guest.add("HOME=/root")', 1)[0]
prefix = []
+64
View File
@@ -0,0 +1,64 @@
"""Steam owns game caps; the nested compositor follows the output refresh rate."""
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
class SessionPacingTest(unittest.TestCase):
def launch(self, refresh, **overrides):
source = SESSION.read_text()
start = source.index(' width=${BL_WIDTH:-1280}')
end = source.index('\nfi\n\nbl_displays()', start)
block = source[start:end].replace('/usr/local/bin/droiddeck-pipewire', 'pipewire_stub')
with tempfile.TemporaryDirectory() as directory:
env = dict(os.environ, XDG_RUNTIME_DIR=directory, BL_REFRESH=str(refresh),
BL_MANGOAPP='0', BL_FPS='0', DROIDDECK_GAME_FRAME_LIMIT='0')
env.pop('GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST', None)
env.update(overrides)
script = '''
set -u
mode=steam
pipewire_stub() { return 1; }
run_gamescope() { printf 'ARG:%s\\n' "$@"; printf 'FOLLOW:%s\\n' "${GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST:-}"; }
''' + block
result = subprocess.run(['bash', '-c', script], env=env, capture_output=True,
text=True, timeout=5)
self.assertEqual(0, result.returncode, result.stderr)
self.follow = [line.removeprefix('FOLLOW:') for line in result.stdout.splitlines()
if line.startswith('FOLLOW:')]
return [line.removeprefix('ARG:') for line in result.stdout.splitlines()
if line.startswith('ARG:')]
def test_display_refresh_sets_the_nested_compositor_rate(self):
for refresh in (60, 90, 120):
with self.subTest(refresh=refresh):
args = self.launch(refresh)
self.assertEqual(str(refresh), args[args.index('-r') + 1])
self.assertIn('-e', args)
def test_gamescope_follows_the_panel_after_the_starting_rate(self):
self.launch(144)
self.assertEqual(['1'], self.follow)
self.launch(0)
self.assertEqual([''], self.follow)
def test_retired_cap_variables_do_not_override_the_display_rate(self):
for performance in ('0', '1'):
with self.subTest(performance=performance):
args = self.launch(120, BL_FPS='30', DROIDDECK_GAME_FRAME_LIMIT=performance)
self.assertEqual('120', args[args.index('-r') + 1])
self.assertNotIn('--framerate-limit', args)
def test_retired_cap_cannot_set_the_rate_when_the_display_rate_is_unknown(self):
args = self.launch(0, BL_FPS='30', DROIDDECK_GAME_FRAME_LIMIT='1')
self.assertNotIn('-r', args)
self.assertNotIn('--framerate-limit', args)
if __name__ == '__main__':
unittest.main()
@@ -45,6 +45,68 @@ class SteamCompatEnvironmentTest(unittest.TestCase):
client_path += ':' + inherited['LD_LIBRARY_PATH']
self.assertEqual(result.stdout.splitlines(), ['1', client_path])
def test_session_exit_stops_the_library_helper(self):
source = (BIN / 'droiddeck-session').read_text()
launch = next(line for line in source.splitlines()
if 'droiddeck-steam-compat "$steam_root"' in line)
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
pid = root / 'pid'
helper = root / 'droiddeck-steam-compat'
helper.write_text('#!/bin/sh\necho $$ > "$PID_FILE"\nexec sleep 30\n')
helper.chmod(0o755)
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
PID_FILE=str(pid), steam_root='/steam', steam_x64='0')
subprocess.run(['bash', '-c', '_bl_compat_env=(env)\n' + launch + '\n'
'until [ -s "$PID_FILE" ]; do sleep 0.05; done\n'
'kill $(jobs -p)\nwait'],
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10)
helper_pid = int(pid.read_text())
try:
os.kill(helper_pid, 0)
except ProcessLookupError:
return
os.kill(helper_pid, 9)
self.fail('droiddeck-steam-compat outlived the session')
def test_the_x86_64_client_gets_only_the_file_dialog_bridge(self):
source = (BIN / 'droiddeck-session').read_text()
start = source.index(' if [ "$steam_x64" = 1 ]; then\n { droiddeck-steam-compat --files-only')
block = source[start:source.index(' fi\n', start) + len(' fi\n')]
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
helper = root / 'droiddeck-steam-compat'
helper.write_text('#!/bin/sh\necho "$@" >> "$ARGS_FILE"\n')
helper.chmod(0o755)
for x64, expected in (('1', '--files-only /steam'), ('0', '/steam')):
with self.subTest(x64=x64):
args = root / ('args-' + x64)
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
ARGS_FILE=str(args), steam_root='/steam', steam_x64=x64)
subprocess.run(['bash', '-c', '_bl_compat_env=(env)\n' + block + 'wait\n'], env=env, timeout=10, check=True)
self.assertEqual(args.read_text().split('\n')[0], expected)
def test_files_only_mode_installs_only_the_file_dialog_hook(self):
import runpy
compat = runpy.run_path(str(BIN / 'droiddeck-steam-compat'))
calls = []
class Page:
def __init__(self, port, path):
self.ws = None
def evaluate(self, expression):
calls.append(('evaluate', expression[:40]))
return True
def call(self, method, params):
calls.append((method, params['name']))
helper = compat['Helper']('/steam', 1234, files_only=True)
helper.attach.__globals__.update(shared_context=lambda port: '/devtools/page/1', Page=Page)
self.assertTrue(helper.attach())
bindings = [name for method, name in calls if method == 'Runtime.addBinding']
self.assertEqual(bindings, [compat['FILE_BINDING']])
self.assertIn(('evaluate', compat['FILE_JS'][:40]), calls)
if __name__ == '__main__':
unittest.main()
+9
View File
@@ -42,6 +42,15 @@ class DesktopSteamLaunchTest(unittest.TestCase):
self.assertEqual(result.stdout.splitlines(), ['1', 'desktop', ':7', 'steam', 'steam://open/library'])
self.assertFalse((self.session / 'steam-launch').exists())
def test_desktop_games_present_without_dri3(self):
(self.root / 'supervisor').write_text('#!/bin/bash\nprintf "%s\\n" "$MESA_VK_WSI_DEBUG"\n')
self.env.pop('MESA_VK_WSI_DEBUG', None)
self.assertEqual(self.launch('desktop', '945360').stdout.splitlines(), ['sw'])
self.env['MESA_VK_WSI_DEBUG'] = 'noshm'
self.assertEqual(self.launch('desktop', '945360').stdout.splitlines(), ['noshm,sw'])
self.env['MESA_VK_WSI_DEBUG'] = 'sw,noshm'
self.assertEqual(self.launch('desktop', '945360').stdout.splitlines(), ['sw,noshm'])
def test_desktop_game_url_goes_to_client(self):
result = self.launch('desktop', '501590')
self.assertEqual(result.returncode, 0, result.stderr)
+142
View File
@@ -0,0 +1,142 @@
import io
import json
import os
import runpy
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat"))
HARNESS = r"""
const assert = require('assert');
globalThis.window = globalThis;
const native = () => Promise.reject({ result: 2, message: '' });
const popupCallbacks = [];
const popup = { window: { SteamClient: { System: { OpenFileDialog: native } } } };
const later = { window: { SteamClient: { System: { OpenFileDialog: native } } } };
globalThis.SteamClient = { System: { OpenFileDialog: native } };
window.g_PopupManager = { GetPopups: () => [popup], AddPopupCreatedCallback: cb => popupCallbacks.push(cb) };
const asked = [];
window.droiddeckOpenFileDialog = payload => asked.push(JSON.parse(payload));
const script = require('fs').readFileSync(process.argv[2], 'utf8');
(async () => {
assert.strictEqual(eval(script), 'installed');
const orphan = SteamClient.System.OpenFileDialog({ strTitle: 'Before reconnect' });
assert.strictEqual(eval(script), 'present');
await assert.rejects(orphan, e => e.result === 2);
assert.strictEqual(window.__droiddeckFiles.done(1, '/late'), false);
asked.length = 0;
assert.notStrictEqual(SteamClient.System.OpenFileDialog, native);
assert.strictEqual(popup.window.SteamClient.System.OpenFileDialog, SteamClient.System.OpenFileDialog);
popupCallbacks.forEach(cb => cb(later));
assert.strictEqual(later.window.SteamClient.System.OpenFileDialog, SteamClient.System.OpenFileDialog);
const options = { strTitle: 'Pick', bChooseDirectory: true };
const chosen = SteamClient.System.OpenFileDialog(options);
const cancelled = later.window.SteamClient.System.OpenFileDialog({ strTitle: 'Other' });
assert.deepStrictEqual(asked, [{ id: 2, options }, { id: 3, options: { strTitle: 'Other' } }]);
assert.strictEqual(window.__droiddeckFiles.done(2, '/root/Storage/Games'), true);
assert.strictEqual(window.__droiddeckFiles.done(2, '/again'), false);
assert.strictEqual(await chosen, '/root/Storage/Games');
window.__droiddeckFiles.done(3, null);
await assert.rejects(cancelled, e => e.result === 2);
delete window.droiddeckOpenFileDialog;
await assert.rejects(SteamClient.System.OpenFileDialog({}), e => e.result === 2);
})().catch(e => { console.error(e); process.exit(1); });
"""
def bound(payload):
return {"method": "Runtime.bindingCalled", "params": {"name": LIVE["FILE_BINDING"], "payload": payload}}
class FileDialogScriptTest(unittest.TestCase):
def test_every_window_asks_the_bridge_and_gets_the_path_or_a_cancel(self):
with tempfile.TemporaryDirectory() as tmp:
script = Path(tmp) / "files.js"
script.write_text(LIVE["FILE_JS"])
harness = Path(tmp) / "harness.js"
harness.write_text(HARNESS)
result = subprocess.run(["node", str(harness), str(script)], capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
class FileDialogBridgeTest(unittest.TestCase):
def setUp(self):
self.globals = LIVE["Helper"].attach.__globals__
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.helper = LIVE["Helper"](str(self.root), 1)
self.helper.page = mock.Mock()
def answer(self):
return self.helper.page.evaluate.call_args.args[0]
def test_the_chooser_runs_under_a_steam_reaper_with_the_options_on_stdin(self):
reaper = self.root / "steamrtarm64/reaper"
reaper.parent.mkdir()
reaper.write_text("#!/bin/sh\n")
reaper.chmod(0o755)
proc = mock.Mock(stdin=io.BytesIO())
proc.stdin.close = lambda: None
with mock.patch.object(self.globals["subprocess"], "Popen", return_value=proc) as popen:
self.helper.page.drain.return_value = [bound(json.dumps({"id": 3, "options": {"strTitle": "Pick"}}))]
self.helper.drain()
command = popen.call_args.args[0]
self.assertEqual(command[:4], [str(reaper), "SteamLaunch", "AppId=769", "--"])
self.assertEqual(command[-1], "--choose-file")
self.assertEqual(json.loads(proc.stdin.getvalue()), {"strTitle": "Pick"})
self.assertEqual(self.helper.chooser, (3, proc))
def test_a_second_request_while_one_is_open_is_cancelled(self):
first = mock.Mock()
self.helper.chooser = (1, first)
self.helper.open_chooser(json.dumps({"id": 2, "options": {}}))
self.assertEqual(self.answer(), "window.__droiddeckFiles?.done(2, null)")
self.assertEqual(self.helper.chooser, (1, first))
def test_the_chosen_path_or_a_cancel_goes_back_to_the_page(self):
for code, out, expected in ((0, b'"/root/Storage/My Game/game.sh"\n', '"/root/Storage/My Game/game.sh"'),
(0, b'" spaced name "\n', '" spaced name "'),
(1, b"", "null"), (2, b"", "null"), (0, b"\n", "null"), (0, b"not json\n", "null")):
proc = mock.Mock(stdout=io.BytesIO(out), returncode=code)
self.helper.chooser = (7, proc)
self.helper.chooser_done()
self.assertEqual(self.answer(), "window.__droiddeckFiles?.done(7, %s)" % expected)
self.assertIsNone(self.helper.chooser)
def test_bad_requests_are_ignored(self):
with mock.patch.object(self.globals["subprocess"], "Popen") as popen:
for payload in ("not json", json.dumps({"options": {}}), json.dumps({"id": 1, "options": []})):
self.helper.open_chooser(payload)
popen.assert_not_called()
self.helper.page.evaluate.assert_not_called()
def test_choose_file_mode_prints_the_path_and_fails_on_cancel(self):
for chooser, code, printed in ((mock.Mock(return_value="/root/Storage/a.exe "), 0, '"/root/Storage/a.exe "\n'),
(mock.Mock(return_value=None), 1, ""),
(mock.Mock(side_effect=ValueError("Namespace Gtk not available for version 3.0")), 2, ""),
(mock.Mock(side_effect=ImportError("No module named 'gi'")), 2, "")):
with mock.patch.dict(LIVE["chooser_main"].__globals__, {"choose_file": chooser}), \
mock.patch.object(sys, "stdin", io.StringIO('{"strTitle": "Pick"}')), \
mock.patch.object(sys, "stdout", io.StringIO()) as out:
self.assertEqual(LIVE["chooser_main"](), code)
self.assertEqual(out.getvalue(), printed)
def test_attach_installs_the_file_dialog_bridge(self):
page = mock.Mock()
page.evaluate.return_value = True
with mock.patch.dict(self.globals, {"shared_context": lambda port: "/devtools/page/1",
"Page": mock.Mock(return_value=page)}):
self.helper.attach()
page.call.assert_any_call("Runtime.addBinding", {"name": LIVE["FILE_BINDING"]})
page.evaluate.assert_any_call(LIVE["FILE_JS"])
if __name__ == "__main__":
unittest.main()
+179 -18
View File
@@ -26,25 +26,48 @@ class SteamInstallTest(unittest.TestCase):
self.bin = self.root / 'bin'
self.bin.mkdir()
curl = self.bin / 'curl'
curl.write_text('''#!/bin/bash
set -eu
url=""
out=""
while [ $# -gt 0 ]; do
case $1 in
-o) out=$2; shift 2 ;;
--connect-timeout|--max-time|--speed-limit|--speed-time|--retry|--retry-delay) shift 2 ;;
-*) shift ;;
*) url=$1; shift ;;
esac
done
printf '%s\\n' "$url" >> "$TEST_REQUESTS"
if [ -n "${TEST_FAIL_HOST:-}" ]; then
case $url in *"$TEST_FAIL_HOST"*) exit 22 ;; esac
fi
cp "$TEST_CDN/${url##*/}" "$out"
curl.write_text('''#!/usr/bin/env python3
import os, sys
args = sys.argv[1:]
url = next(a for a in args if a.startswith('https://'))
out = args[args.index('-o') + 1]
name = url.rsplit('/', 1)[1]
offset = os.path.getsize(out) if '-C' in args and os.path.exists(out) else 0
with open(os.environ['TEST_REQUESTS'], 'a') as log:
log.write(url + '\\n')
with open(os.environ['TEST_REQUESTS'] + '.offsets', 'a') as log:
log.write(f'{name} {offset}\\n')
def done(status, code='200'):
if '-w' in args:
sys.stdout.write(code)
sys.exit(status)
host_fail = os.environ.get('TEST_FAIL_HOST')
if host_fail and host_fail in url:
done(22, '000')
action = []
plan = os.environ.get('TEST_PLAN')
if plan and os.path.exists(plan):
lines = open(plan).read().splitlines()
for n, line in enumerate(lines):
if line.split()[0] == name:
action = line.split()[1:]
del lines[n]
open(plan, 'w').write(''.join(l + '\\n' for l in lines))
break
if action[:1] == ['fail']:
done(int(action[1]), '000')
if action[:1] == ['http']:
done(22, action[1])
if action[:1] == ['norange'] and offset:
done(33)
data = open(os.path.join(os.environ['TEST_CDN'], name), 'rb').read()
end = int(action[1]) if action[:1] == ['cut'] else len(data)
with open(out, 'ab' if offset else 'wb') as target:
target.write(data[offset:end])
done(28 if end < len(data) else 0)
''')
curl.chmod(0o755)
self.plan = self.root / 'plan'
if shutil.which('sha256sum') is None:
sha = self.bin / 'sha256sum'
sha.write_text('#!/bin/bash\nexec shasum -a 256 "$@"\n')
@@ -55,7 +78,8 @@ cp "$TEST_CDN/${url##*/}" "$out"
sha1.chmod(0o755)
self.env = dict(os.environ, HOME=str(self.home), XDG_DATA_HOME=str(self.data),
PATH=str(self.bin) + os.pathsep + os.environ['PATH'],
TEST_CDN=str(self.cdn), TEST_REQUESTS=str(self.requests))
TEST_CDN=str(self.cdn), TEST_REQUESTS=str(self.requests),
TEST_PLAN=str(self.plan), BL_STEAM_RETRY_DELAYS='0 0 0')
for channel in ('steamdeck_publicbeta', 'steamdeck_stable'):
archive = self.cdn / (channel + '.zip')
with zipfile.ZipFile(archive, 'w') as package:
@@ -255,6 +279,143 @@ cp "$TEST_CDN/${url##*/}" "$out"
self.assertEqual(0, self.install().returncode)
self.assertFalse(self.requests.exists())
def publish(self, **parts):
"""The CDN's client as these parts (block name -> byte count of incompressible content),
listed with sizes as Valve's manifest lists them."""
files = {}
blocks = ''
for block, length in parts.items():
archive = self.cdn / f'{block}.zip.{hashlib.sha1(block.encode()).hexdigest()}'
with zipfile.ZipFile(archive, 'w', zipfile.ZIP_STORED) as package:
package.writestr(f'parts/{block}', os.urandom(length))
if block.endswith('_linuxarm64_linuxarm64'):
package.writestr('steamrtarm64/steam', 'steamdeck_publicbeta')
data = archive.read_bytes()
files[block] = archive.name
blocks += (f'\t"{block}"\n\t{{\n\t\t"file"\t\t"{archive.name}"\n\t\t"size"\t\t"{len(data)}"\n'
f'\t\t"sha2"\t\t"{hashlib.sha256(data).hexdigest()}"\n\t}}\n')
(self.cdn / 'steam_client_steamdeck_publicbeta_linuxarm64').write_text(
'"linuxarm64"\n{\n\t"version"\t\t"123456"\n' + blocks + '}\n')
return files
def two_parts(self):
return self.publish(a_all=1_200_000, client_linuxarm64_linuxarm64=1_300_000)
def plan_for(self, name, *actions):
with self.plan.open('a') as plan:
plan.writelines(f'{name} {action}\n' for action in actions)
def offsets(self, name):
log = Path(str(self.requests) + '.offsets')
return [int(line.split()[1]) for line in log.read_text().splitlines() if line.split()[0] == name]
def requested(self):
return [line.rsplit('/', 1)[1] for line in self.requests.read_text().splitlines()]
@property
def download(self):
return self.steam / 'package/droiddeck-download'
def test_progress_is_counted_in_megabytes_across_parts(self):
self.two_parts()
result = self.install()
self.assertEqual(0, result.returncode, result.stderr)
self.assertIn('downloading Steam: a_all (1/2), 0 of 2 MB\n', result.stdout)
self.assertIn('downloading Steam: client_linuxarm64_linuxarm64 (2/2), 1 of 2 MB\n', result.stdout)
self.assertTrue((self.steam / 'parts/a_all').is_file())
self.assertFalse(self.download.exists())
def test_a_dropped_connection_resumes_from_what_arrived(self):
files = self.two_parts()
client = files['client_linuxarm64_linuxarm64']
self.plan_for(client, 'cut 500000')
result = self.install()
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual([0, 500000], self.offsets(client))
self.assertIn('interrupted (curl exit 28), trying again in 0 s', result.stdout)
self.assertEqual('123456\n', (self.steam / 'package/droiddeck-installed').read_text())
def test_a_failed_session_keeps_what_it_finished_and_fetched(self):
files = self.two_parts()
client = files['client_linuxarm64_linuxarm64']
self.plan_for(client, 'cut 400000', *['fail 6'] * 12)
result = self.install()
self.assertNotEqual(0, result.returncode)
self.assertIn('could not download client_linuxarm64_linuxarm64 (curl exit 6)', result.stderr)
self.assertFalse((self.steam / 'package/droiddeck-installed').exists())
self.assertTrue((self.download / (files['a_all'] + '.unpacked')).is_file())
self.assertFalse((self.download / files['a_all']).exists())
self.assertEqual(400000, (self.download / client).stat().st_size)
self.requests.unlink()
Path(str(self.requests) + '.offsets').unlink()
self.assertEqual(0, self.install().returncode)
self.assertEqual(['steam_client_steamdeck_publicbeta_linuxarm64', client], self.requested())
self.assertEqual([400000], self.offsets(client))
self.assertFalse(self.download.exists())
def test_a_server_that_will_not_resume_starts_the_part_over(self):
files = self.two_parts()
client = files['client_linuxarm64_linuxarm64']
self.plan_for(client, 'cut 400000', 'norange')
result = self.install()
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual([0, 400000, 0], self.offsets(client))
def test_a_missing_part_hands_over_to_the_next_cdn_at_once(self):
files = self.two_parts()
client = files['client_linuxarm64_linuxarm64']
self.plan_for(client, 'http 404')
result = self.install()
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual(['https://client-update.steamstatic.com/' + client,
'https://client-update.akamai.steamstatic.com/' + client],
[line for line in self.requests.read_text().splitlines() if line.endswith(client)])
self.assertIn('HTTP 404 from https://client-update.steamstatic.com', result.stderr)
self.assertNotIn('trying again', result.stdout)
def test_a_server_error_is_retried_on_the_same_cdn(self):
files = self.two_parts()
client = files['client_linuxarm64_linuxarm64']
self.plan_for(client, 'http 503')
result = self.install()
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual(['https://client-update.steamstatic.com/' + client] * 2,
[line for line in self.requests.read_text().splitlines() if line.endswith(client)])
self.assertIn('interrupted (curl exit 22), trying again in 0 s', result.stdout)
def test_bytes_that_do_not_check_out_are_fetched_again(self):
files = self.two_parts()
client = files['client_linuxarm64_linuxarm64']
self.download.mkdir(parents=True)
(self.download / client).write_bytes(b'x' * (self.cdn / client).stat().st_size)
result = self.install()
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual([0], self.offsets(client))
def test_parts_left_for_another_client_version_are_dropped(self):
files = self.two_parts()
self.download.mkdir(parents=True)
(self.download / 'a_all.zip.0123').write_bytes(b'older')
(self.download / 'b_all.zip.4567.unpacked').write_bytes(b'')
self.plan_for(files['client_linuxarm64_linuxarm64'], *['fail 7'] * 12)
self.assertNotEqual(0, self.install().returncode)
self.assertEqual([files['a_all'] + '.unpacked'], sorted(p.name for p in self.download.iterdir()))
def test_a_repair_unpacks_every_part_again_once(self):
files = self.two_parts()
self.assertEqual(0, self.install().returncode)
(self.home / '.bl-steam-repair').write_text('1\n')
self.requests.unlink()
self.plan_for(files['client_linuxarm64_linuxarm64'], *['fail 7'] * 12)
self.assertNotEqual(0, self.install().returncode)
self.assertIn(files['a_all'], self.requested())
self.requests.unlink()
self.assertEqual(0, self.install().returncode)
self.assertEqual(['steam_client_steamdeck_publicbeta_linuxarm64', files['client_linuxarm64_linuxarm64']],
self.requested())
self.assertFalse((self.home / '.bl-steam-repair').exists())
self.assertFalse(self.download.exists())
if __name__ == '__main__':
unittest.main()
+2
View File
@@ -153,6 +153,8 @@ class DesktopGamesTest(unittest.TestCase):
steam = root / "Steam"
manifest(steam / "steamapps", 40, name="Game")
manifest(steam / "steamapps", 1628350, name="Steam Linux Runtime 3.0 (sniper)", installdir="SteamLinuxRuntime_sniper")
manifest(steam / "steamapps", 1826330, name="Proton EasyAntiCheat Runtime", installdir="Proton EasyAntiCheat Runtime")
manifest(steam / "steamapps", 1161040, name="Proton BattlEye Runtime", installdir="Proton BattlEye Runtime")
manifest(steam / "steamapps", 5000, name="Some Proton", installdir="Some Proton")
(steam / "steamapps/common/Some Proton").mkdir(parents=True)
(steam / "steamapps/common/Some Proton/toolmanifest.vdf").write_text('"manifest"\n{\n}\n')
+167
View File
@@ -0,0 +1,167 @@
from pathlib import Path
import contextlib
import io
import json
import os
import runpy
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-share'
SHARE = runpy.run_path(str(SCRIPT))
CONFIG = ('"InstallConfigStore"\n{\n\t"Software"\n\t{\n\t\t"Valve"\n\t\t{\n\t\t\t"Steam"\n\t\t\t{\n'
'\t\t\t\t"CompatToolMapping"\n\t\t\t\t{\n%s\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n')
def mapping(**tools):
return ''.join('\t\t\t\t\t"%s"\n\t\t\t\t\t{\n\t\t\t\t\t\t"name"\t\t"%s"\n\t\t\t\t\t\t"config"\t\t""\n'
'\t\t\t\t\t\t"priority"\t\t"250"\n\t\t\t\t\t}\n' % (app.lstrip('_'), name)
for app, name in tools.items())
def manifest(app, folder, updated=100, flags=4):
return ('"AppState"\n{\n\t"appid"\t\t"%s"\n\t"name"\t\t"%s"\n\t"StateFlags"\t\t"%d"\n'
'\t"installdir"\t\t"%s"\n\t"LastUpdated"\t\t"%d"\n}\n' % (app, folder, flags, folder, updated))
class SteamShareTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
home = Path(self.temp.name)
self.arm = home / 'arm/Steam'
self.x64 = home / 'x64/Steam'
self.card = home / 'card'
self.shared = home / 'x64/shared'
for root, tool in ((self.arm, 'droiddeck-proton-arm64'), (self.x64, 'droiddeck-proton-a64')):
(root / 'steamapps/common').mkdir(parents=True)
(root / 'config').mkdir()
(root / 'compatibilitytools.d/proton').mkdir(parents=True)
(root / 'compatibilitytools.d/proton/compatibilitytool.vdf').write_text(
'"compatibilitytools"\n{\n\t"compat_tools"\n\t{\n\t\t"%s"\n\t\t{\n\t\t}\n\t}\n}\n' % tool)
(self.arm / 'config/config.vdf').write_text(CONFIG % mapping(_0='droiddeck-proton-arm64', _413150='droiddeck-fex'))
(self.x64 / 'config/config.vdf').write_text(CONFIG % '')
self.install(self.arm, '413150', 'Stardew Valley')
self.install(self.arm, '13210', 'Unreal Tournament 3')
self.install(self.arm, '1493710', 'Proton - Experimental')
def install(self, root, app, folder, updated=100):
(root / 'steamapps/common' / folder).mkdir(parents=True, exist_ok=True)
(root / 'steamapps/common' / folder / 'game.bin').write_text('x')
(root / ('steamapps/appmanifest_%s.acf' % app)).write_text(manifest(app, folder, updated))
def run_share(self, here):
with contextlib.redirect_stdout(io.StringIO()):
return SHARE['main']([here, str(self.arm), str(self.x64), str(self.card), str(self.shared)])
def view(self, *parts):
return self.shared.joinpath('arm64', 'steamapps', *parts)
def test_x64_client_sees_arm64_games_in_place(self):
self.assertEqual(self.run_share('x86-64'), 0)
self.assertEqual(os.readlink(self.view('common/Stardew Valley')), str(self.arm / 'steamapps/common/Stardew Valley'))
self.assertTrue(self.view('appmanifest_413150.acf').is_file())
self.assertTrue(self.view('appmanifest_13210.acf').is_file())
self.assertFalse(self.view('appmanifest_1493710.acf').exists())
folders = (self.x64 / 'steamapps/libraryfolders.vdf').read_text()
self.assertIn(str(self.shared / 'arm64'), folders)
self.assertIn('ARM64 client games', folders)
def test_tools_follow_the_other_client(self):
self.run_share('x86-64')
tools = SHARE['entries']((self.x64 / 'config/config.vdf').read_text())
self.assertEqual(tools['413150'], 'droiddeck-direct')
self.assertEqual(tools['13210'], 'droiddeck-proton-a64')
def test_a_proton_pick_stays_when_the_other_client_uses_another_proton(self):
(self.x64 / 'config/config.vdf').write_text(CONFIG % mapping(_13210='droiddeck-proton-11-a64'))
self.run_share('x86-64')
self.assertEqual(SHARE['entries']((self.x64 / 'config/config.vdf').read_text())['13210'], 'droiddeck-proton-11-a64')
def test_an_automatic_proton_gives_way_to_the_installed_linux_build(self):
self.install(self.x64, '550', 'Left 4 Dead 2')
(self.x64 / 'config/config.vdf').write_text(CONFIG % mapping(_550='droiddeck-direct'))
(self.arm / 'config/config.vdf').write_text(CONFIG % mapping(_0='droiddeck-proton-arm64', _550='droiddeck-proton-arm64'))
self.run_share('arm64')
self.assertEqual(SHARE['entries']((self.arm / 'config/config.vdf').read_text())['550'], 'droiddeck-fex')
def test_an_x64_proton_pick_reaches_the_arm64_client(self):
self.install(self.x64, '550', 'Left 4 Dead 2')
(self.x64 / 'config/config.vdf').write_text(CONFIG % mapping(_550='droiddeck-proton-a64'))
self.run_share('arm64')
self.assertEqual(SHARE['entries']((self.arm / 'config/config.vdf').read_text())['550'], 'droiddeck-proton-arm64')
def test_a_tool_the_user_chose_is_kept(self):
(self.x64 / 'config/config.vdf').write_text(CONFIG % mapping(_13210='my-proton'))
self.run_share('x86-64')
self.assertEqual(SHARE['entries']((self.x64 / 'config/config.vdf').read_text())['13210'], 'my-proton')
def test_own_install_wins(self):
self.install(self.x64, '413150', 'Stardew Valley')
self.run_share('x86-64')
self.assertFalse(self.view('appmanifest_413150.acf').exists())
self.assertFalse(os.path.lexists(self.view('common/Stardew Valley')))
def test_newer_update_goes_back_to_the_source(self):
self.run_share('x86-64')
self.view('appmanifest_413150.acf').write_text(manifest('413150', 'Stardew Valley', 200))
self.run_share('x86-64')
self.assertIn('"LastUpdated"\t\t"200"', (self.arm / 'steamapps/appmanifest_413150.acf').read_text())
def test_uninstall_from_the_view_hides_until_reinstalled(self):
self.run_share('x86-64')
self.view('appmanifest_13210.acf').unlink()
self.run_share('x86-64')
self.assertFalse(os.path.lexists(self.view('common/Unreal Tournament 3')))
self.assertTrue((self.arm / 'steamapps/common/Unreal Tournament 3/game.bin').is_file())
self.run_share('x86-64')
self.assertFalse(self.view('appmanifest_13210.acf').exists())
self.install(self.arm, '13210', 'Unreal Tournament 3', 300)
self.run_share('x86-64')
self.assertTrue(self.view('appmanifest_13210.acf').is_file())
def test_files_deleted_through_the_view_drop_the_source_manifest(self):
self.run_share('x86-64')
(self.arm / 'steamapps/common/Unreal Tournament 3/game.bin').unlink()
self.view('appmanifest_13210.acf').unlink()
self.run_share('x86-64')
self.assertFalse((self.arm / 'steamapps/appmanifest_13210.acf').exists())
def test_removed_source_leaves_the_view(self):
self.run_share('x86-64')
(self.arm / 'steamapps/appmanifest_413150.acf').unlink()
self.run_share('x86-64')
self.assertFalse(self.view('appmanifest_413150.acf').exists())
self.assertFalse(os.path.lexists(self.view('common/Stardew Valley')))
state = json.loads((self.shared / 'arm64/.droiddeck-shared.json').read_text())
self.assertNotIn('413150', state['shared'])
def test_arm64_client_sees_x64_games(self):
self.install(self.x64, '550', 'Left 4 Dead 2')
(self.x64 / 'config/config.vdf').write_text(CONFIG % mapping(_550='droiddeck-direct'))
self.run_share('arm64')
self.assertTrue(self.shared.joinpath('x86-64/steamapps/appmanifest_550.acf').is_file())
self.assertEqual(SHARE['entries']((self.arm / 'config/config.vdf').read_text())['550'], 'droiddeck-fex')
self.assertIn('x86-64 client games', (self.arm / 'steamapps/libraryfolders.vdf').read_text())
def test_an_empty_view_is_not_offered(self):
self.run_share('x86-64')
for app in ('413150', '13210', '1493710'):
(self.arm / ('steamapps/appmanifest_%s.acf' % app)).unlink()
self.run_share('x86-64')
self.assertNotIn(str(self.shared / 'arm64'), (self.x64 / 'steamapps/libraryfolders.vdf').read_text())
def test_unfinished_installs_are_not_shared(self):
(self.arm / 'steamapps/appmanifest_413150.acf').write_text(manifest('413150', 'Stardew Valley', flags=1026))
self.run_share('x86-64')
self.assertFalse(self.view('appmanifest_413150.acf').exists())
def test_bad_arguments(self):
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(SHARE['main'](['mips']), 2)
if __name__ == '__main__':
unittest.main()
+24
View File
@@ -203,6 +203,30 @@ class ShortcutsTest(unittest.TestCase):
self.assertEqual('-vulkan', steam['LaunchOptions'])
self.assertEqual('Mine', steam['AppName'])
def users(self, *blocks):
body = ''.join('\t"%d"\n\t{\n%s\t}\n' % (76561197960265728 + acct, ''.join('\t\t"%s"\t\t"%s"\n' % kv for kv in keys.items()))
for acct, keys in blocks)
(self.steam / 'config').mkdir(exist_ok=True)
(self.steam / 'config/loginusers.vdf').write_text('"users"\n{\n%s}\n' % body)
(self.steam / 'userdata/456/config').mkdir(parents=True, exist_ok=True)
def test_the_account_marked_most_recent_is_used(self):
self.users((123, dict(MostRecent='1', AutoLogin='0', timestamp='100')), (456, dict(MostRecent='0', AutoLogin='1', timestamp='200')))
self.assertEqual(str(self.steam / 'userdata/123'), shortcuts.account_dir(str(self.steam)))
def test_without_most_recent_the_account_that_signs_in_is_used(self):
self.users((123, dict(AutoLogin='1', timestamp='100')), (456, dict(AutoLogin='0', timestamp='200')))
self.assertEqual(str(self.steam / 'userdata/123'), shortcuts.account_dir(str(self.steam)))
self.assertIn(APPID, self.run_writer(self.game()))
def test_without_either_mark_the_account_used_last_is_used(self):
self.users((456, dict(AutoLogin='0', timestamp='100')), (123, dict(AutoLogin='0', timestamp='200')))
self.assertEqual(str(self.steam / 'userdata/123'), shortcuts.account_dir(str(self.steam)))
def test_two_accounts_without_any_mark_write_nothing(self):
self.users((123, dict(AccountName='a')), (456, dict(AccountName='b')))
self.assertIsNone(shortcuts.account_dir(str(self.steam)))
def test_an_older_record_without_launch_options_still_takes_the_apps(self):
self.run_writer(self.game())
record = self.record()
+30 -1
View File
@@ -277,11 +277,40 @@ class CloudHooks(unittest.TestCase):
for sh in (compat.LAUNCHER_SH, compat.EXTRA_WRAPPER_SH):
self.assertIn('bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh)
self.assertNotIn('exec ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh)
self.assertIn('[ $? -eq 10 ] && BL_STORE_EXIT=1', compat.BL_STORE_SETUP)
self.assertIn('[ $rc -eq 10 ] && BL_STORE_EXIT=1', compat.BL_STORE_SETUP)
self.assertIn('droiddeck-store-launch --exited --code "$rc" "${BL_STORE_ARGS[@]}"', compat.BL_STORE_SETUP)
self.assertIn('exec "$@"', compat.BL_STORE_SETUP)
BNET_EXE = '/root/.local/share/Steam/steamapps/compatdata/2596113170/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe'
class BattleNet(unittest.TestCase):
def test_a_games_shortcut_is_handed_to_droiddeck_battlenet(self):
self.assertEqual([store.BATTLENET, 'launch', 'Fen'], store.battlenet(['waitforexitandrun', BNET_EXE, '--exec=launch Fen'], env={}))
self.assertEqual([store.BATTLENET, 'launch', 'OSI'], store.battlenet(['"%s"' % BNET_EXE, '--exec="launch OSI"'], env={}))
self.assertEqual([store.BATTLENET, 'open'], store.battlenet([BNET_EXE], env={}))
def test_anything_else_and_its_own_starts_are_left_alone(self):
other = BNET_EXE.replace('2596113170', '123')
self.assertIsNone(store.battlenet([other, '--exec=launch Fen'], env={}))
self.assertIsNone(store.battlenet(['/x/Diablo IV/Diablo IV.exe'], env={}))
self.assertIsNone(store.battlenet([BNET_EXE, '--exec=launch Fen'], env={'BL_BATTLENET': '1'}))
self.assertEqual([store.BATTLENET, 'open'], store.battlenet([BNET_EXE, '--exec=launch Fen;rm'], env={}))
def test_the_launch_runs_there_and_the_wrapper_ends_with_it(self):
with patch.dict(os.environ, {}, clear=False), patch.object(store.subprocess, 'call', return_value=0) as call:
os.environ.pop('BL_BATTLENET', None)
self.assertEqual(store.RAN, store.main([BNET_EXE, '--exec=launch Pro']))
call.assert_called_once_with([store.BATTLENET, 'launch', 'Pro'])
with patch.dict(os.environ, {}, clear=False), patch.object(store.subprocess, 'call', return_value=1):
os.environ.pop('BL_BATTLENET', None)
self.assertEqual(store.RAN_FAILED, store.main([BNET_EXE, '--exec=launch Pro']))
self.assertIn('[ $rc -eq 11 ] && exit 0', compat.BL_STORE_SETUP)
self.assertIn('[ $rc -eq 12 ] && exit 1', compat.BL_STORE_SETUP)
self.assertLess(compat.BL_STORE_SETUP.index('droiddeck-store-launch "$@"'), compat.BL_STORE_SETUP.index('[ $rc -eq 11 ] && exit 0'))
class Launchers(unittest.TestCase):
def test_both_proton_launchers_ask_before_proton_starts(self):
sh = compat.LAUNCHER_SH
+17 -1
View File
@@ -28,7 +28,8 @@ class ValidateApkTest(unittest.TestCase):
def git(self, *args):
return subprocess.check_output(["git", "-C", self.root, *args], text=True).strip()
def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt"):
def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt", permission="write", role_name="write"):
(self.root / filename).parent.mkdir(parents=True, exist_ok=True)
(self.root / filename).write_text(message)
self.git("add", filename)
self.git("commit", "--allow-empty", "-qm", message)
@@ -42,6 +43,8 @@ class ValidateApkTest(unittest.TestCase):
path.write_text(json.dumps(event))
def api(path, *args):
if path.endswith("/collaborators/human/permission"):
return {"permission": permission, "role_name": role_name}
if "/statuses/" in path:
self.statuses.append(dict(value.split("=", 1) for value in args if "=" in value))
return {}
@@ -96,6 +99,19 @@ class ValidateApkTest(unittest.TestCase):
self.validate(filename="README.md", result="pending")
self.assertEqual(self.statuses[-1]["state"], "success")
def test_trusted_list_requires_maintainer_pr_opener(self):
with self.assertRaisesRegex(RuntimeError, "Only a maintainer"):
self.validate(filename=".github/trusted-test-builds.txt")
self.assertEqual(self.statuses[-1]["state"], "failure")
def test_maintainer_can_change_trusted_list(self):
self.validate(filename=".github/trusted-test-builds.txt", permission="write", role_name="maintain")
self.assertEqual(self.statuses[-1]["state"], "success")
def test_admin_can_change_trusted_list(self):
self.validate(filename=".github/trusted-test-builds.txt", permission="admin", role_name="admin")
self.assertEqual(self.statuses[-1]["state"], "success")
def test_renaming_code_to_documentation_still_requires_compilation(self):
(self.root / "source.kt").write_text("source")
self.git("add", "source.kt")
+282
View File
@@ -0,0 +1,282 @@
import array
import mmap
import os
import socket
import struct
import subprocess
import tempfile
import threading
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
VDEC = ROOT / 'tools/linuxfs/preload/vdec.c'
VENC = ROOT / 'tools/linuxfs/preload/venc.c'
DRIVER = r'''
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/videodev2.h>
#include <poll.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
int bl_vdec_open(const char *path, int flags);
int bl_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc);
void bl_vdec_closed(int fd);
void *SDL_LoadObject(const char *name);
void *SDL_LoadFunction(void *handle, const char *name);
struct heap_alloc { uint64_t len; uint32_t fd, fd_flags; uint64_t heap_flags; };
struct create_dumb { uint32_t height, width, bpp, flags, handle, pitch; uint64_t size; };
struct prime_handle { uint32_t handle, flags; int32_t fd; };
struct destroy_dumb { uint32_t handle; };
struct drm_device { char **nodes; int available_nodes; };
static int heap = -1;
int open(const char *path, int flags, ...) {
static int (*real)(const char *, int, ...);
va_list ap;
va_start(ap, flags);
int mode = va_arg(ap, int);
va_end(ap);
if (!real) real = dlsym(RTLD_NEXT, "open");
if (strcmp(path, "/dev/dma_heap/system") == 0) return heap = memfd_create("heap", 0);
return real(path, flags, mode);
}
int ioctl(int fd, unsigned long req, ...) {
static int (*real)(int, unsigned long, ...);
va_list ap;
va_start(ap, req);
void *arg = va_arg(ap, void *);
va_end(ap);
if (!real) real = dlsym(RTLD_NEXT, "ioctl");
if (fd == heap && req == _IOWR('H', 0, struct heap_alloc)) {
struct heap_alloc *a = arg;
int buf = memfd_create("dmabuf", 0);
if (ftruncate(buf, (off_t)a->len) != 0) return -1;
a->fd = (uint32_t)buf;
return 0;
}
if (req == _IOW('b', 0, uint64_t)) return 0;
return real(fd, req, arg);
}
static int vfd;
static int call(unsigned long req, void *arg) {
int rc;
if (!bl_vdec_ioctl(vfd, req, arg, &rc)) return -100;
return rc < 0 ? -errno : 0;
}
int main(void) {
if (bl_vdec_open("/dev/video0", O_RDWR) != -2) return 2;
void *drm = SDL_LoadObject("libdrm.so.2");
if (!drm) return 3;
int (*devices)(uint32_t, struct drm_device **, int) = SDL_LoadFunction(drm, "drmGetDevices2");
int (*drm_ioctl)(int, unsigned long, void *) = SDL_LoadFunction(drm, "drmIoctl");
if (!devices || !drm_ioctl || !SDL_LoadFunction(drm, "drmModeAtomicCommit")) return 4;
struct drm_device *dev[1];
if (devices(0, NULL, 0) != 1 || devices(0, dev, 1) != 1 || !(dev[0]->available_nodes & 1)) return 5;
int card = open(dev[0]->nodes[0], O_RDWR | O_CLOEXEC);
if (card < 0) return 6;
vfd = bl_vdec_open("/dev/video-dec0", O_RDWR);
if (vfd < 0) return 7;
struct v4l2_capability cap;
if (call(VIDIOC_QUERYCAP, &cap) || (cap.capabilities & 0x04004000) != 0x04004000) return 8;
struct v4l2_fmtdesc d = { .index = 1, .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE };
if (call(VIDIOC_ENUM_FMT, &d) || d.pixelformat != V4L2_PIX_FMT_HEVC) return 9;
struct v4l2_format f = { .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE };
f.fmt.pix_mp.width = 1280; f.fmt.pix_mp.height = 720; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_HEVC;
if (call(VIDIOC_S_FMT, &f)) return 10;
struct v4l2_requestbuffers r = { .count = 4, .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, .memory = V4L2_MEMORY_MMAP };
if (call(VIDIOC_REQBUFS, &r) || r.count != 4) return 11;
unsigned char *in[4];
for (int i = 0; i < 4; i++) {
struct v4l2_plane p = { 0 };
struct v4l2_buffer b = { .index = i, .type = r.type, .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &p };
if (call(VIDIOC_QUERYBUF, &b)) return 12;
in[i] = mmap(NULL, p.length, PROT_READ | PROT_WRITE, MAP_SHARED, vfd, p.m.mem_offset);
if (in[i] == MAP_FAILED) return 13;
}
f = (struct v4l2_format){ .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
f.fmt.pix_mp.width = 1280; f.fmt.pix_mp.height = 736; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12;
if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.num_planes != 1) return 14;
uint32_t bpl = f.fmt.pix_mp.plane_fmt[0].bytesperline, size = f.fmt.pix_mp.plane_fmt[0].sizeimage;
if (bpl != 1280 || size != 1280 * 736 * 3 / 2) return 15;
r = (struct v4l2_requestbuffers){ .count = 3, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, .memory = V4L2_MEMORY_DMABUF };
if (call(VIDIOC_REQBUFS, &r) || r.count != 3) return 16;
int out[3];
for (int i = 0; i < 3; i++) {
struct create_dumb c = { .height = 736, .width = 1280, .bpp = 16 };
if (drm_ioctl(card, 0xc02064b2, &c) || !c.handle || c.size < size) return 17;
struct prime_handle h = { .handle = c.handle, .flags = O_CLOEXEC };
if (drm_ioctl(card, 0xc00c642d, &h)) return 18;
struct destroy_dumb x = { .handle = c.handle };
if (drm_ioctl(card, 0xc00464b4, &x)) return 19;
out[i] = h.fd;
}
unsigned types[2] = { V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
if (call(VIDIOC_STREAMON, &types[0]) || call(VIDIOC_STREAMON, &types[1])) return 20;
for (int i = 0; i < 3; i++) {
struct v4l2_plane p = { .m.fd = out[i] };
struct v4l2_buffer b = { .index = i, .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &p };
if (call(VIDIOC_QBUF, &b)) return 21;
}
struct pollfd pf = { .fd = vfd, .events = 0xc9 };
if (poll(&pf, 1, 0) != 0) return 22;
for (int frame = 1; frame <= 5; frame++) {
int slot = frame % 4;
memset(in[slot], 'a' + frame, 100 + frame);
struct v4l2_plane p = { .bytesused = 100 + frame };
struct v4l2_buffer b = { .index = slot, .type = types[0], .memory = V4L2_MEMORY_MMAP, .flags = 0x4008, .length = 1, .m.planes = &p };
b.timestamp.tv_usec = frame;
if (call(VIDIOC_QBUF, &b)) return 23;
pf = (struct pollfd){ .fd = vfd, .events = 0xc9 };
if (poll(&pf, 1, 30) != 1 || !(pf.revents & POLLIN)) return 24;
struct v4l2_plane cp = { 0 };
struct v4l2_buffer cb = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &cp };
if (call(VIDIOC_DQBUF, &cb)) return 25;
unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, out[cb.index], 0);
printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 736], cp.bytesused == size);
munmap(m, size);
pf = (struct pollfd){ .fd = vfd, .events = 0x306 };
if (poll(&pf, 1, 0) != 1) return 26;
struct v4l2_plane op = { 0 };
struct v4l2_buffer ob = { .type = types[0], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &op };
if (call(VIDIOC_DQBUF, &ob) || ob.index != (unsigned)slot) return 27;
struct v4l2_plane rp = { .m.fd = out[cb.index] };
struct v4l2_buffer rb = { .index = cb.index, .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &rp };
if (call(VIDIOC_QBUF, &rb)) return 28;
}
if (call(VIDIOC_STREAMOFF, &types[1])) return 29;
f = (struct v4l2_format){ .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
f.fmt.pix_mp.width = 1920; f.fmt.pix_mp.height = 1088; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12;
if (call(VIDIOC_S_FMT, &f)) return 30;
size = f.fmt.pix_mp.plane_fmt[0].sizeimage;
r = (struct v4l2_requestbuffers){ .count = 1, .type = types[1], .memory = V4L2_MEMORY_DMABUF };
if (call(VIDIOC_REQBUFS, &r)) return 31;
struct create_dumb big = { .height = 1088, .width = 1920, .bpp = 16 };
if (drm_ioctl(card, 0xc02064b2, &big)) return 32;
struct prime_handle bh = { .handle = big.handle, .flags = O_CLOEXEC };
if (drm_ioctl(card, 0xc00c642d, &bh)) return 33;
if (call(VIDIOC_STREAMON, &types[1])) return 34;
struct v4l2_plane bp = { .m.fd = bh.fd };
struct v4l2_buffer bb = { .index = 0, .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &bp };
if (call(VIDIOC_QBUF, &bb)) return 35;
memset(in[2], 'z', 50);
struct v4l2_plane zp = { .bytesused = 50 };
struct v4l2_buffer zb = { .index = 2, .type = types[0], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &zp };
zb.timestamp.tv_usec = 6;
if (call(VIDIOC_QBUF, &zb)) return 36;
struct v4l2_plane dp = { 0 };
struct v4l2_buffer db = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &dp };
if (call(VIDIOC_DQBUF, &db)) return 37;
unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, bh.fd, 0);
printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)1920 * 1088]);
bl_vdec_closed(vfd);
return 0;
}
'''
CONFIG = struct.Struct('<IIIIIIII')
CAPTURE = struct.Struct('<III')
PACKET = struct.Struct('<IIII q')
RESULT = struct.Struct('<IiI')
class FakeDecoder(threading.Thread):
def __init__(self, path):
super().__init__(daemon=True)
self.listener = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
self.listener.bind(path)
self.listener.listen(1)
self.configs, self.packets = [], []
def run(self):
while True:
try:
conn, _ = self.listener.accept()
except OSError:
return
threading.Thread(target=self.serve, args=(conn,), daemon=True).start()
def serve(self, conn):
bitstream, captures, config = None, {}, None
while True:
fds = array.array('i')
msg, ancdata, _, _ = conn.recvmsg(256, socket.CMSG_LEN(4 * fds.itemsize))
if not msg:
return
for level, kind, data in ancdata:
if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS:
fds.frombytes(data[:len(data) - len(data) % fds.itemsize])
kind = struct.unpack_from('<I', msg)[0]
if kind == 6:
config = CONFIG.unpack(msg)
self.configs.append(config)
bitstream = mmap.mmap(fds[0], config[6] * config[7], prot=mmap.PROT_READ)
os.close(fds[0])
conn.send(RESULT.pack(9, 0, 0))
elif kind == 7:
_, index, size = CAPTURE.unpack(msg)
captures[index] = mmap.mmap(fds[0], size)
os.close(fds[0])
elif kind == 8:
_, source, nbytes, target, pts = PACKET.unpack(msg)
self.packets.append((source, nbytes, target, pts))
first = bitstream[source * config[7]]
frame = captures[target]
frame[0] = first
frame[config[4] * config[5]] = ord('u')
conn.send(RESULT.pack(9, 0, 1))
class VdecEmulatorTest(unittest.TestCase):
def test_remote_play_client_decodes_through_the_app_socket(self):
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
driver = tmp / 'driver.c'
driver.write_text(DRIVER)
binary = tmp / 'streaming_client'
subprocess.run(['cc', '-O1', '-pthread', '-DBL_VDEC_ANY_ARCH', '-o', str(binary), str(driver), str(VDEC),
str(VENC), '-ldl'], check=True)
sock = tmp / 'venc.sock'
server = FakeDecoder(str(sock))
self.addCleanup(server.listener.close)
server.start()
done = subprocess.run([str(binary)], env=dict(os.environ, BL_VENC_SOCKET=str(sock)),
capture_output=True, text=True, timeout=20)
self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
self.assertEqual(done.stdout.split('\n')[:6],
['1 0 bu 1', '2 1 cu 1', '3 2 du 1', '4 0 eu 1', '5 1 fu 1', '6 0 zu'])
self.assertEqual([c[1:6] for c in server.configs],
[(1, 1280, 720, 1280, 736), (1, 1280, 720, 1920, 1088)])
self.assertEqual([p[:3] for p in server.packets],
[(1, 101, 0), (2, 102, 1), (3, 103, 2), (0, 104, 0), (1, 105, 1), (2, 50, 0)])
def test_other_programs_keep_the_real_libdrm(self):
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
(tmp / 'main.c').write_text(
'void *SDL_LoadObject(const char *);\n'
'int main(void) { return SDL_LoadObject("libdrm.so.2") != 0; }\n')
binary = tmp / 'steam'
subprocess.run(['cc', '-O1', '-pthread', '-DBL_VDEC_ANY_ARCH', '-o', str(binary), str(tmp / 'main.c'),
str(VDEC), str(VENC), '-ldl'], check=True)
done = subprocess.run([str(binary)], capture_output=True, text=True, timeout=20)
self.assertEqual(done.returncode, 0, done.stderr)
if __name__ == '__main__':
unittest.main()
+30
View File
@@ -223,5 +223,35 @@ class VencEmulatorTest(unittest.TestCase):
self.assertEqual(server.touches, [(0, 65535, 32767), (1, 32767, 0), (2, 32767, 0)])
def test_xtest_calls_from_a_locally_loaded_library_still_reach_libxtst(self):
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
(tmp / 'xtst.c').write_text(
'int XTestFakeButtonEvent(void *d, unsigned b, int p, unsigned long t) { return 7; }\n'
'int XTestFakeMotionEvent(void *d, int s, int x, int y, unsigned long t) { return 7; }\n')
(tmp / 'ui.c').write_text(
'int XTestFakeButtonEvent(void *, unsigned, int, unsigned long);\n'
'int XTestFakeMotionEvent(void *, int, int, int, unsigned long);\n'
'int ui_click(void) { return XTestFakeButtonEvent(0, 1, 1, 0) + XTestFakeButtonEvent(0, 3, 0, 0); }\n'
'int ui_move(void) { return XTestFakeMotionEvent(0, 0, 10, 20, 0); }\n')
(tmp / 'main.c').write_text(
'#include <dlfcn.h>\n#include <stdio.h>\n'
'int main(int argc, char **argv) {\n'
' void *ui = dlopen(argv[1], RTLD_NOW | RTLD_LOCAL);\n'
' if (!ui) return 2;\n'
' int (*click)(void) = dlsym(ui, "ui_click"), (*move)(void) = dlsym(ui, "ui_move");\n'
' printf("%d %d\\n", click(), move());\n'
' return click() == 14 && move() == 7 ? 0 : 1;\n'
'}\n')
run = lambda *a: subprocess.run(['cc', *a], check=True, cwd=tmp)
run('-shared', '-fPIC', '-Wl,-soname,libXtst.so.6', '-o', 'libXtst.so.6', 'xtst.c')
run('-shared', '-fPIC', '-o', 'libui.so', 'ui.c', '-L.', '-l:libXtst.so.6', "-Wl,-rpath,$ORIGIN")
run('-shared', '-fPIC', '-pthread', '-o', 'libhook.so', str(VENC), str(TOUCH), '-ldl')
run('-o', 'main', 'main.c', '-ldl')
done = subprocess.run([str(tmp / 'main'), str(tmp / 'libui.so')],
env=dict(os.environ, LD_PRELOAD=str(tmp / 'libhook.so')),
capture_output=True, text=True, timeout=20)
self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
if __name__ == '__main__':
unittest.main()
+86 -4
View File
@@ -1,8 +1,10 @@
import io
import json
import os
from pathlib import Path
import runpy
import socket
import subprocess
import tempfile
import threading
import unittest
@@ -54,11 +56,13 @@ class XboxLaunchTest(unittest.TestCase):
patch.dict(xbox['launch'].__globals__, wine=unittest.mock.Mock(return_value=7)):
launch = xbox['launch']
self.assertEqual(launch(['/proton', 'waitforexitandrun', '/encrypted/Game.exe'],
{'BL_LAUNCH_DIR': '/launch', 'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'stale'}), 7)
{'BL_LAUNCH_DIR': '/launch', 'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'stale',
'DROIDDECK_XBOX_CREDENTIAL_PORT': '4100', 'DROIDDECK_XBOX_CREDENTIAL_KEY': 'stale-key'}), 7)
wine = launch.__globals__['wine']
self.assertEqual(wine.call_args.args[0], ['/private/Game.exe'])
env = wine.call_args.args[1]
self.assertNotIn('DROIDDECK_XBOX_CREDENTIAL_SOCKET', env)
for name in ('DROIDDECK_XBOX_CREDENTIAL_SOCKET', 'DROIDDECK_XBOX_CREDENTIAL_PORT', 'DROIDDECK_XBOX_CREDENTIAL_KEY'):
self.assertNotIn(name, env)
self.assertEqual(env['XODUS_XSTS_PLAYFAB'], 'game-token')
close.assert_called_once()
self.assertEqual(store['ask'].call_args.args[1], {'op': 'xbox-released', 'lease': 'lease-1'})
@@ -115,7 +119,8 @@ class XboxLaunchTest(unittest.TestCase):
command = root / 'command.json'
command.write_text(json.dumps(['/selected/proton', 'waitforexitandrun', '/encrypted/Game.exe', '--custom', 'two words']))
env = {'STEAM_COMPAT_DATA_PATH': str(prefix.parent), 'DROIDDECK_XBOX_COMMAND_FILE': str(command),
'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'private-account-channel', 'XODUS_BRIDGE_KEY': 'runtime-key'}
'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'private-account-channel', 'DROIDDECK_XBOX_CREDENTIAL_PORT': '4100',
'DROIDDECK_XBOX_CREDENTIAL_KEY': 'private-key', 'XODUS_BRIDGE_KEY': 'runtime-key'}
with patch.dict(os.environ, env), patch.dict(xbox['wine'].__globals__, RUNTIME=runtime.parent), patch('subprocess.run') as initialize, patch('subprocess.call', return_value=7) as call:
initialize.return_value.returncode = 0
self.assertEqual(xbox['wine'](['/private-view/Game.exe']), 7)
@@ -126,6 +131,83 @@ class XboxLaunchTest(unittest.TestCase):
initialize.assert_called_once()
for child in (initialize, call):
child_env = child.call_args.kwargs['env']
self.assertNotIn('DROIDDECK_XBOX_CREDENTIAL_SOCKET', child_env)
for name in ('DROIDDECK_XBOX_CREDENTIAL_SOCKET', 'DROIDDECK_XBOX_CREDENTIAL_PORT', 'DROIDDECK_XBOX_CREDENTIAL_KEY'):
self.assertNotIn(name, child_env)
self.assertNotIn('DROIDDECK_XBOX_COMMAND_FILE', child_env)
self.assertEqual(child_env['XODUS_BRIDGE_KEY'], 'runtime-key')
def test_launch_view_runs_from_a_short_drive_letter(self):
with tempfile.TemporaryDirectory() as root:
root = Path(root)
prefix = root / 'compat/pfx'
prefix.mkdir(parents=True)
runtime = root / 'runtime/windows'; runtime.mkdir(parents=True)
for name in xbox['DLLS']:
(runtime / name).write_bytes(b'MZ-synthetic')
view = root / 'files/xbox-runtime/views/launch-4093691424/droiddeck-xbox-1ZpM3D'
(view / 'Bin').mkdir(parents=True)
command = root / 'command.json'
command.write_text(json.dumps(['/selected/proton', 'waitforexitandrun', '/encrypted/Game.exe']))
env = {'STEAM_COMPAT_DATA_PATH': str(prefix.parent), 'DROIDDECK_XBOX_COMMAND_FILE': str(command)}
seen = []
def call(argv, **kwargs):
seen.append((argv, os.readlink(prefix / 'dosdevices/x:')))
return 0
with patch.dict(os.environ, env), patch.dict(xbox['wine'].__globals__, RUNTIME=runtime.parent), patch('subprocess.run') as initialize, patch('subprocess.call', side_effect=call):
initialize.return_value.returncode = 0
self.assertEqual(xbox['wine']([str(view / 'Bin/Game.exe')]), 0)
self.assertEqual(seen, [(['/selected/proton', 'waitforexitandrun', 'X:\\Bin\\Game.exe'], str(view))])
self.assertFalse(os.path.lexists(prefix / 'dosdevices/x:'))
def test_view_drive_keeps_drives_in_use_and_reuses_a_stale_view(self):
with tempfile.TemporaryDirectory() as root:
root = Path(root)
devices = root / 'pfx/dosdevices'; devices.mkdir(parents=True)
views = root / 'views'
live = views / 'launch-1/droiddeck-xbox-live'; live.mkdir(parents=True)
view = views / 'launch-2/droiddeck-xbox-new'; view.mkdir(parents=True)
(devices / 'x:').symlink_to(live)
(devices / 'w:').symlink_to(root / 'games')
(devices / 'v:').symlink_to(views / 'launch-0/droiddeck-xbox-gone')
exe, link = xbox['view_drive'](root / 'pfx', str(view / 'Game.exe'))
self.assertEqual((exe, link), ('V:\\Game.exe', devices / 'v:'))
self.assertEqual(os.readlink(devices / 'v:'), str(view))
self.assertEqual(os.readlink(devices / 'x:'), str(live))
self.assertEqual(sorted(p.name for p in devices.iterdir()), ['v:', 'w:', 'x:'])
self.assertEqual(xbox['view_drive'](root / 'pfx', '/games/Game.exe'), ('/games/Game.exe', None))
def test_missing_runtime_classes_are_registered_once(self):
with tempfile.TemporaryDirectory() as root:
prefix = Path(root)
key = xbox['CLASS_KEY'].replace('\\', '\\\\')
present = [name for names in xbox['CLASSES'].values() for name in names
if name != 'Windows.ApplicationModel.DataTransfer.DataTransferManager']
(prefix / 'system.reg').write_text(''.join('[%s%s] 1\n"DllPath"="x"\n\n' % (key, name) for name in present))
imported = []
def run(argv, **kwargs):
imported.append(Path(argv[4][2:].replace('\\', '/')).read_bytes()[2:].decode('utf-16-le'))
return subprocess.CompletedProcess(argv, 0)
with patch('subprocess.run', side_effect=run) as child:
xbox['register_classes']('/selected/proton', prefix, {'A': '1'})
self.assertEqual(child.call_args.args[0][:4], ['/selected/proton', 'run', 'reg.exe', 'import'])
self.assertEqual(child.call_args.kwargs['env'], {'A': '1'})
self.assertEqual(imported, ['Windows Registry Editor Version 5.00\r\n\r\n[HKEY_LOCAL_MACHINE\\Software\\Microsoft\\WindowsRuntime'
'\\ActivatableClassId\\Windows.ApplicationModel.DataTransfer.DataTransferManager]\r\n'
'"DllPath"="C:\\\\windows\\\\system32\\\\twinapi.appcore.dll"\r\n\r\n'])
with (prefix / 'system.reg').open('a') as file:
file.write('[%sWindows.ApplicationModel.DataTransfer.DataTransferManager] 1\n' % key)
with patch('subprocess.run') as child:
xbox['register_classes']('/selected/proton', prefix, {})
(prefix / 'system.reg').unlink()
xbox['register_classes']('/selected/proton', prefix, {})
child.assert_not_called()
def test_failed_class_registration_is_reported_and_launch_continues(self):
with tempfile.TemporaryDirectory() as root:
prefix = Path(root)
(prefix / 'system.reg').write_text('')
for outcome in ({'return_value': subprocess.CompletedProcess([], 1)},
{'side_effect': subprocess.TimeoutExpired('reg.exe', 90)}):
with patch('subprocess.run', **outcome), patch('sys.stderr', new_callable=io.StringIO) as err:
self.assertIsNone(xbox['register_classes']('/selected/proton', prefix, {}))
self.assertIn('registration failed', err.getvalue())