mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f639a08eb | ||
|
|
82f806ad84 | ||
|
|
7771a87695 | ||
|
|
3419391940 | ||
|
|
c46bb72631 | ||
|
|
0cd42b7217 | ||
|
|
f68a78c577 | ||
|
|
6638a7dac8 | ||
|
|
c6333350ae | ||
|
|
fbf1788647 | ||
|
|
48f587bb41 | ||
|
|
088e9994a0 | ||
|
|
29350f1bd5 | ||
|
|
498a3a653a | ||
|
|
644f8e655f | ||
|
|
7ad52166a2 | ||
|
|
872c5e1834 | ||
|
|
2d25fb91c5 | ||
|
|
56213d74b3 | ||
|
|
9c6fafec4c | ||
|
|
f06c37e279 | ||
|
|
f17406effc | ||
|
|
b072cedd16 | ||
|
|
77fffa7592 | ||
|
|
de3ed8b986 | ||
|
|
86b8ae3c99 | ||
|
|
ad6bb159d3 | ||
|
|
fe6f8638c6 |
No files matched your search
@@ -68,6 +68,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
||||
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
|
||||
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
|
||||
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
|
||||
- Anti-cheat support under FEX is the work of [StonkGuy](https://github.com/StonkGuy): the x86-64 ptrace, seccomp and `/proc` emulation from his [FEX fork](https://github.com/StonkGuy/FEX) (`eac-2611` branch, MIT) is carried as build patch 0021 with his authorship, patches 0022 to 0029 build on it, and his `eac-tests` regression suite verifies them.
|
||||
- x86-64 programs on Wayland reach the GPU through FEX's Wayland client, wayland-egl and EGL thunks. The guest `wl_list` and `wl_array` helpers follow [libwayland](https://gitlab.freedesktop.org/wayland/wayland)'s `src/wayland-util.c` (MIT). The EGL extension table comes from the [Khronos EGL registry](https://github.com/KhronosGroup/EGL-Registry) (Apache-2.0) and Mesa's `egl_other.xml` (MIT).
|
||||
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
|
||||
- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence.
|
||||
|
||||
@@ -15,7 +15,6 @@ import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.SecondScreenMode
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
/** The launcher as a whole: rail and page, opened on each tab through FrontEndState.navigate. */
|
||||
@Composable
|
||||
@@ -26,23 +25,6 @@ private fun Launcher(tab: String, games: List<com.droiddeck.launcher.frontend.Li
|
||||
@DroidDeckPreviews @Composable private fun SteamEmptyPreview() = Launcher("steam", games = emptyList())
|
||||
@DroidDeckPreviews @Composable private fun LibraryPreview() = Launcher("games")
|
||||
@DroidDeckPreviews @Composable private fun LibraryEmptyPreview() = Launcher("games", games = emptyList())
|
||||
|
||||
/** The Library in [view] with its display options set as given, the way the eye menu saves them. */
|
||||
@Composable
|
||||
private fun LibraryShown(view: String, title: Boolean, size: Boolean, store: Boolean = true) {
|
||||
val ctx = androidx.compose.ui.platform.LocalContext.current
|
||||
androidx.compose.runtime.remember {
|
||||
SessionPrefs.setLibraryShowTitle(ctx, title)
|
||||
SessionPrefs.setLibraryShowSize(ctx, size)
|
||||
SessionPrefs.setLibraryShowStore(ctx, store)
|
||||
}
|
||||
PreviewHost { FrontEndScreen(sampleState(navigate = "games", storesView = view), sampleActions) }
|
||||
}
|
||||
|
||||
@DroidDeckPreviews @Composable private fun LibraryCapsulesPreview() = LibraryShown("capsules", title = true, size = true)
|
||||
@DroidDeckPreviews @Composable private fun LibraryCardsTitlePreview() = LibraryShown("cards", title = true, size = false)
|
||||
@DroidDeckPreviews @Composable private fun LibraryCapsulesNoStorePreview() = LibraryShown("capsules", title = false, size = false, store = false)
|
||||
|
||||
@DroidDeckPreviews @Composable private fun StoresPreview() = Launcher("stores")
|
||||
@DroidDeckPreviews @Composable private fun DownloadsPreview() = Launcher("downloads")
|
||||
@DroidDeckPreviews @Composable private fun SettingsPreview() = Launcher("setup")
|
||||
@@ -133,11 +115,6 @@ private val storesLoaded = { com.droiddeck.launcher.stores.StoresState.accountsL
|
||||
internal val previewCases: List<PreviewCase> = listOf(
|
||||
PreviewCase("steam-tab") { Launcher("steam") },
|
||||
PreviewCase("library", storesLoaded) { Launcher("games") },
|
||||
PreviewCase("library-capsules-title-size", storesLoaded) { LibraryShown("capsules", title = true, size = true) },
|
||||
PreviewCase("library-cards-title", storesLoaded) { LibraryShown("cards", title = true, size = false) },
|
||||
PreviewCase("library-cards-size", storesLoaded) { LibraryShown("cards", title = false, size = true) },
|
||||
PreviewCase("library-capsules-bare", storesLoaded) { LibraryShown("capsules", title = false, size = false, store = false) },
|
||||
PreviewCase("library-capsules-store-title-off", storesLoaded) { LibraryShown("capsules", title = true, size = false, store = false) },
|
||||
PreviewCase("library-empty", storesLoaded) { Launcher("games", games = emptyList()) },
|
||||
PreviewCase("stores", storesLoaded) { Launcher("stores") },
|
||||
PreviewCase("downloads") { Launcher("downloads") },
|
||||
|
||||
@@ -50,11 +50,10 @@ internal fun sampleState(
|
||||
games: List<Library.SteamGame> = sampleGames,
|
||||
navigate: String? = null,
|
||||
ready: Boolean = true,
|
||||
storesView: String = SessionPrefs.DEFAULT_STORES_VIEW,
|
||||
): FrontEndState = FrontEndState(
|
||||
installed = "ubuntu-r1", ready = ready, available = "ubuntu-r1", busy = false, stage = "", percent = 0,
|
||||
desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "Off", romsDir = null, logsEnabled = true,
|
||||
steamGames = games, emulators = emptyList(), running = null, navigate = navigate, storesView = storesView,
|
||||
steamGames = games, emulators = emptyList(), running = null, navigate = navigate,
|
||||
)
|
||||
|
||||
internal val sampleActions: FrontEndActions = FrontEndActions(
|
||||
|
||||
@@ -40,6 +40,8 @@
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.HIGH_SAMPLING_RATE_SENSORS" />
|
||||
|
||||
@@ -329,16 +329,28 @@ static constexpr int kWatchedFds = 1 << 16;
|
||||
static constexpr int kWatchedBits = sizeof(unsigned long) * 8;
|
||||
static std::atomic<unsigned long> watched_fds[kWatchedFds / kWatchedBits];
|
||||
static std::atomic<bool> watched_beyond{false};
|
||||
static std::atomic<int> watched_count{0};
|
||||
|
||||
static void watch_fd(int fd) {
|
||||
if (fd < 0) return;
|
||||
if (fd >= kWatchedFds) watched_beyond.store(true, std::memory_order_release);
|
||||
else watched_fds[fd / kWatchedBits].fetch_or(1UL << (fd % kWatchedBits), std::memory_order_release);
|
||||
if (fd >= kWatchedFds) {
|
||||
watched_beyond.store(true, std::memory_order_release);
|
||||
return;
|
||||
}
|
||||
const unsigned long bit = 1UL << (fd % kWatchedBits);
|
||||
if (!(watched_fds[fd / kWatchedBits].fetch_or(bit, std::memory_order_acq_rel) & bit))
|
||||
watched_count.fetch_add(1, std::memory_order_acq_rel);
|
||||
}
|
||||
|
||||
static void unwatch_fd(int fd) {
|
||||
if (fd >= 0 && fd < kWatchedFds)
|
||||
watched_fds[fd / kWatchedBits].fetch_and(~(1UL << (fd % kWatchedBits)), std::memory_order_release);
|
||||
if (fd < 0 || fd >= kWatchedFds) return;
|
||||
const unsigned long bit = 1UL << (fd % kWatchedBits);
|
||||
if (watched_fds[fd / kWatchedBits].fetch_and(~bit, std::memory_order_acq_rel) & bit)
|
||||
watched_count.fetch_sub(1, std::memory_order_acq_rel);
|
||||
}
|
||||
|
||||
static bool any_watched() {
|
||||
return watched_count.load(std::memory_order_acquire) > 0 || watched_beyond.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
static bool watched(int fd) {
|
||||
@@ -4269,7 +4281,7 @@ static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout,
|
||||
const auto my_poll = next_symbol<decltype(&::poll)>(Next::poll);
|
||||
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
|
||||
|
||||
nfds_t first = 0;
|
||||
nfds_t first = any_watched() ? 0 : nfds;
|
||||
while (first < nfds && !watched(fds[first].fd)) first++;
|
||||
bool has_fake_fds = false;
|
||||
std::vector<struct pollfd> real_fds;
|
||||
@@ -4372,12 +4384,12 @@ EXPORT int poll(struct pollfd *fds, nfds_t nfds, int timeout) {
|
||||
EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
|
||||
const struct timespec *timeout, const sigset_t *sigmask) {
|
||||
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
|
||||
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
for (nfds_t i = 0; i < nfds; ++i) {
|
||||
for (nfds_t i = 0; any_watched() && i < nfds; ++i) {
|
||||
if (!is_fake_input_fd(fds[i].fd)) continue;
|
||||
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
if (!sigmask)
|
||||
return poll_fake(fds, nfds, static_cast<int>(timespec_to_ms(timeout)), nullptr);
|
||||
sigset_t all_signals, original_mask;
|
||||
@@ -4410,6 +4422,8 @@ EXPORT int __ppoll_chk(struct pollfd *fds, nfds_t nfds, const struct timespec *t
|
||||
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
|
||||
fd_set *exceptfds, struct timeval *timeout) {
|
||||
const auto my_select = next_symbol<decltype(&::select)>(Next::select);
|
||||
if (!any_watched())
|
||||
return my_select ? my_select(nfds, readfds, writefds, exceptfds, timeout) : -1;
|
||||
|
||||
fd_set original_readfds;
|
||||
fd_set original_writefds;
|
||||
|
||||
@@ -343,6 +343,7 @@ volatile int g_hide_shell;
|
||||
|
||||
volatile int g_zero_copy;
|
||||
static int g_zero_copy_paused;
|
||||
static int g_mirror_capture;
|
||||
extern volatile int g_display_buffer_driver;
|
||||
extern void droiddeck_on_overlay_planes(int planes);
|
||||
static int g_overlay_planes_told = -1;
|
||||
@@ -2961,7 +2962,7 @@ static void hdr_note_route(int route, const struct hdr_scene *hs) {
|
||||
static int said = -1, said_tm = -1;
|
||||
static const char *said_why;
|
||||
const int tm = route != 0 && !droiddeck_color_output();
|
||||
if (route == said && tm == said_tm && (route != 1 || hs->why == said_why)) return;
|
||||
if (route == said && tm == said_tm && (route < 1 || route > 2 || hs->why == said_why)) return;
|
||||
int was = said;
|
||||
said = route; said_why = hs->why; said_tm = tm;
|
||||
char name[160] = "the HDR game";
|
||||
@@ -2978,6 +2979,10 @@ static void hdr_note_route(int route, const struct hdr_scene *hs) {
|
||||
"BT2020_PQ", name, hs->why ? hs->why : "?", droiddeck_color_sdr_white());
|
||||
break;
|
||||
case 2:
|
||||
if (g_mirror_capture) {
|
||||
droiddeck_log("color", "Mirror: %s is composed through the screen swapchain", name);
|
||||
break;
|
||||
}
|
||||
if (tm)
|
||||
droiddeck_log("color", "HDR with frame generation for %s, HDR output switched off: the scene is tone-mapped to "
|
||||
"SDR and presented through an SDR screen swapchain", name);
|
||||
@@ -3198,6 +3203,11 @@ static void render_scene(void) {
|
||||
const int cardboard = vkp_cardboard_active();
|
||||
struct hdr_scene hs;
|
||||
int hdr_route = hdr_plan(&dl, w, h, fx_on, framegen, &hs);
|
||||
/* Mirror's PixelCopy cannot see the separate game layer. Keep unimportable frames visible on top. */
|
||||
if (g_mirror_capture && hdr_route != 3 && hs.n_hdr > 0) {
|
||||
hdr_route = 2;
|
||||
hs.why = "Mirror needs the screen swapchain";
|
||||
}
|
||||
const char *hdr_copy = NULL;
|
||||
if (droiddeck_color_hdr_open()) {
|
||||
hdr_note_route(hdr_route, &hs);
|
||||
@@ -3263,16 +3273,16 @@ static void render_scene(void) {
|
||||
else if (rendered && how == 2) droiddeck_color_frame_shown(hs.color, DROIDDECK_HDR_TONEMAPPED, 0);
|
||||
else if (rendered) hdr_copy = "the HDR composition pass is unavailable on this driver";
|
||||
}
|
||||
if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
|
||||
if (hdr_route == 0 && !g_mirror_capture && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
|
||||
!ahb_only) {
|
||||
settle_unwaited();
|
||||
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
|
||||
} else if (hdr_route == 0 || hdr_route == 3) {
|
||||
const int pass_on = fx_on || framegen;
|
||||
tell_overlay_planes();
|
||||
const int fg_layer = framegen && hdr_route == 0 && framegen_fits_layer();
|
||||
const int fg_layer = framegen && !g_mirror_capture && hdr_route == 0 && framegen_fits_layer();
|
||||
g_framegen_layer = fg_layer;
|
||||
int li = (g_zero_copy && (!framegen || fg_layer) && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1;
|
||||
int li = (g_zero_copy && !g_mirror_capture && (!framegen || fg_layer) && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1;
|
||||
int over = li >= 0 ? dl.n - 1 - li : 0;
|
||||
const int fx_blocks = (li >= 0 && fx_on && over > 0);
|
||||
if (fx_blocks) { li = -1; over = 0; }
|
||||
@@ -5002,6 +5012,12 @@ const char *droiddeck_client_name(struct wl_client *client) { return client_name
|
||||
struct wl_display *droiddeck_get_display(void) { return g_display; }
|
||||
void droiddeck_request_redraw(void) { schedule_render(); }
|
||||
|
||||
void droiddeck_set_mirror_capture(int on) {
|
||||
if (g_mirror_capture == on) return;
|
||||
g_mirror_capture = on;
|
||||
schedule_render();
|
||||
}
|
||||
|
||||
struct wl_resource *droiddeck_ime_target(void) {
|
||||
struct surface *s;
|
||||
if (g_ime_click && g_ime_click->mapped) return g_ime_click->resource;
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
#include "ahb_swapchain.h"
|
||||
#include "droiddeck_color.h"
|
||||
|
||||
enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD };
|
||||
enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD, HOST_MIRROR_CAPTURE };
|
||||
|
||||
struct host_msg {
|
||||
enum host_kind kind;
|
||||
@@ -91,6 +91,9 @@ void droiddeck_host_text_delete(int before, int after) {
|
||||
void droiddeck_host_zero_copy(int on, int live) {
|
||||
host_post(HOST_ZERO_COPY, NULL, 0, on, live);
|
||||
}
|
||||
void droiddeck_host_mirror_capture(int on) {
|
||||
host_post(HOST_MIRROR_CAPTURE, NULL, 0, on, 0);
|
||||
}
|
||||
void droiddeck_host_hdr_output(int on) {
|
||||
host_post(HOST_HDR_OUTPUT, NULL, 0, on, 0);
|
||||
}
|
||||
@@ -271,6 +274,9 @@ static int on_wake(int fd, uint32_t mask, void *data) {
|
||||
case HOST_ZERO_COPY:
|
||||
ahb_swapchain_set_mode(m->a, m->b);
|
||||
break;
|
||||
case HOST_MIRROR_CAPTURE:
|
||||
droiddeck_set_mirror_capture(m->a);
|
||||
break;
|
||||
case HOST_HDR_OUTPUT:
|
||||
droiddeck_color_set_output(m->a);
|
||||
break;
|
||||
|
||||
@@ -29,6 +29,8 @@ void droiddeck_host_text_commit_and_submit(const char *utf8, int len);
|
||||
void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end);
|
||||
void droiddeck_host_text_delete(int before, int after);
|
||||
void droiddeck_host_zero_copy(int on, int live);
|
||||
void droiddeck_host_mirror_capture(int on);
|
||||
void droiddeck_set_mirror_capture(int on);
|
||||
void droiddeck_host_hdr_output(int on);
|
||||
void droiddeck_host_key(int evdev, int state);
|
||||
void droiddeck_host_select_game_field(int copy);
|
||||
|
||||
@@ -461,6 +461,11 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetZeroCopy(JNIEnv *
|
||||
__android_log_print(ANDROID_LOG_INFO, TAG, "zero-copy layer mode %s%s", on ? "on" : "off", live ? " (live)" : "");
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetMirrorCapture(JNIEnv *env, jclass clazz, jboolean on) {
|
||||
droiddeck_host_mirror_capture(on ? 1 : 0);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetDisplayBufferDriver(JNIEnv *env, jclass clazz, jboolean on) {
|
||||
g_display_buffer_driver = on ? 1 : 0;
|
||||
|
||||
@@ -661,6 +661,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var effects by mutableStateOf(ScreenEffects.OFF)
|
||||
private var observedScreenEffectsProfileId by mutableStateOf<String?>(null)
|
||||
private var screenEffectsTarget by mutableStateOf(SCREEN_EFFECTS_TARGET_AUTO)
|
||||
private var screenEffectsProfileRevision by mutableIntStateOf(0)
|
||||
private var cardboard by mutableStateOf(Cardboard.OFF)
|
||||
private var headTracker: HeadTracker? = null
|
||||
private var steamVrStatus by mutableStateOf<SteamVr.Status?>(null)
|
||||
@@ -1641,8 +1642,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
effects = effects,
|
||||
screenEffectsTarget = screenEffectsTarget,
|
||||
screenEffectsTargets = screenEffectsTargetOptions(),
|
||||
screenEffectsCanDelete = screenEffectsProfileIdForTarget(screenEffectsTarget)?.let {
|
||||
SessionPrefs.hasScreenEffectsOverride(this@SessionActivity, it)
|
||||
screenEffectsCanDelete = screenEffectsProfileRevision.let {
|
||||
screenEffectsProfileIdForTarget(screenEffectsTarget)?.let {
|
||||
SessionPrefs.hasScreenEffectsOverride(this@SessionActivity, it) ||
|
||||
SessionPrefs.hasScreenEffectsUpscalerOverride(this@SessionActivity, it)
|
||||
}
|
||||
} == true,
|
||||
cardboard = cardboard,
|
||||
cardboardSensor = hasRotationSensor,
|
||||
@@ -1748,6 +1752,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
} else {
|
||||
val profileId = screenEffectsProfileIdForTarget(target)
|
||||
SessionPrefs.setScreenEffectsUpscaler(this@SessionActivity, profileId, m)
|
||||
screenEffectsProfileRevision++
|
||||
|
||||
if (target == screenEffectsTarget) {
|
||||
upscaler = m
|
||||
@@ -1783,6 +1788,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
} else {
|
||||
val profileId = screenEffectsProfileIdForTarget(target)
|
||||
SessionPrefs.setScreenEffectsUpscaler(this@SessionActivity, profileId, m)
|
||||
screenEffectsProfileRevision++
|
||||
if (target == screenEffectsTarget) {
|
||||
upscaler = m
|
||||
if (screenEffectsUpscalerTargetAppliesToLiveOutput(target)) {
|
||||
@@ -1829,7 +1835,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
val profileId = screenEffectsProfileIdForTarget(editorTarget)
|
||||
SessionPrefs.setScreenEffects(this@SessionActivity, profileId, e)
|
||||
effects = e
|
||||
if (screenEffectsTargetAppliesToLiveOutput(editorTarget)) e.push(upscaler)
|
||||
if (screenEffectsTargetAppliesToLiveOutput(editorTarget)) {
|
||||
val upscalerAppliesToLiveOutput =
|
||||
screenEffectsUpscalerTargetAppliesToLiveOutput(editorTarget)
|
||||
val liveUpscaler = if (upscalerAppliesToLiveOutput) {
|
||||
SessionPrefs.screenEffectsUpscaler(
|
||||
this@SessionActivity,
|
||||
screenEffectsProfileIdForTarget(editorTarget)
|
||||
)
|
||||
} else {
|
||||
SessionPrefs.screenEffectsUpscaler(
|
||||
this@SessionActivity,
|
||||
currentScreenEffectsProfileId()
|
||||
)
|
||||
}
|
||||
e.push(liveUpscaler)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -2648,10 +2669,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
val targetUpscaler = SessionPrefs.screenEffectsUpscaler(this, profileId)
|
||||
effects = targetEffects
|
||||
upscaler = targetUpscaler
|
||||
val upscalerAppliesToLiveOutput = screenEffectsUpscalerTargetAppliesToLiveOutput(target)
|
||||
val liveUpscaler = if (upscalerAppliesToLiveOutput) {
|
||||
targetUpscaler
|
||||
} else {
|
||||
SessionPrefs.screenEffectsUpscaler(this, currentScreenEffectsProfileId())
|
||||
}
|
||||
if (upscalerAppliesToLiveOutput) {
|
||||
WaylandCompositor.nativeSetUpscaler(liveUpscaler)
|
||||
}
|
||||
if (screenEffectsTargetAppliesToLiveOutput(target)) {
|
||||
WaylandCompositor.nativeSetUpscaler(targetUpscaler)
|
||||
WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(targetEffects, targetUpscaler)?.name)
|
||||
targetEffects.push(targetUpscaler)
|
||||
WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(targetEffects, liveUpscaler)?.name)
|
||||
targetEffects.push(liveUpscaler)
|
||||
} else if (upscalerAppliesToLiveOutput) {
|
||||
val liveEffects = SessionPrefs.screenEffects(this, currentScreenEffectsProfileId())
|
||||
WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(liveEffects, liveUpscaler)?.name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2664,6 +2696,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private fun resetScreenEffectsTarget(target: String) {
|
||||
if (target != screenEffectsTarget) return
|
||||
SessionPrefs.resetScreenEffectsProfile(this, screenEffectsProfileIdForTarget(target))
|
||||
screenEffectsProfileRevision++
|
||||
syncScreenEffectsTarget(target)
|
||||
}
|
||||
|
||||
@@ -2671,6 +2704,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (target != screenEffectsTarget) return
|
||||
val profileId = screenEffectsProfileIdForTarget(target) ?: return
|
||||
SessionPrefs.deleteScreenEffectsProfile(this, profileId)
|
||||
screenEffectsProfileRevision++
|
||||
syncScreenEffectsTarget(target)
|
||||
}
|
||||
|
||||
@@ -6348,7 +6382,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
private fun holdComposedOutput(hold: Boolean) {
|
||||
val wasHeld = composedHolds > 0
|
||||
composedHolds = (composedHolds + if (hold) 1 else -1).coerceAtLeast(0)
|
||||
val held = composedHolds > 0
|
||||
if (held == wasHeld) return
|
||||
WaylandCompositor.nativeSetMirrorCapture(held)
|
||||
// Importable HDR is redirected by the compositor hold. Keep its layer-only fallback available.
|
||||
if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy(composedOutputFree())
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,12 @@ object AgentAttachments {
|
||||
/** True while the file picker is open over a session: it answers the drawer's agent page, so the drawer must stay. */
|
||||
@Volatile var picking = false
|
||||
|
||||
/** Launches a system screen that answers the agent page, keeping the drawer for it; the result callback clears [picking]. */
|
||||
fun pick(launch: () -> Unit) {
|
||||
picking = true
|
||||
if (runCatching(launch).isFailure) picking = false
|
||||
}
|
||||
|
||||
private const val NEW = "new"
|
||||
private const val GUEST_DIR = "/root/.cache/droiddeck/attachments"
|
||||
private val IMAGE = setOf("png", "jpg", "jpeg", "webp", "gif", "bmp")
|
||||
@@ -38,14 +44,17 @@ object AgentAttachments {
|
||||
val folder = chat ?: NEW
|
||||
val dir = File(hostDir(app), folder).apply { mkdirs() }
|
||||
return uris.mapNotNull { uri ->
|
||||
var target: File? = null
|
||||
runCatching {
|
||||
val name = displayName(app, uri).replace(Regex("[^A-Za-z0-9._-]"), "_").ifEmpty { "file" }
|
||||
var target = File(dir, name)
|
||||
var candidate = File(dir, name)
|
||||
var n = 1
|
||||
while (target.exists()) target = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}")
|
||||
app.contentResolver.openInputStream(uri)!!.use { input -> target.outputStream().use { input.copyTo(it) } }
|
||||
"$GUEST_DIR/$folder/${target.name}"
|
||||
}.getOrNull()
|
||||
// Created atomically, so copies running side by side never pick the same name.
|
||||
while (!candidate.createNewFile()) candidate = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}")
|
||||
target = candidate
|
||||
app.contentResolver.openInputStream(uri)!!.use { input -> candidate.outputStream().use { input.copyTo(it) } }
|
||||
"$GUEST_DIR/$folder/${candidate.name}"
|
||||
}.onFailure { target?.delete() }.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -66,11 +66,14 @@ object ProtonExtras {
|
||||
|
||||
internal fun installedIn(dir: File, tool: Tool): List<String> =
|
||||
dir.listFiles()
|
||||
?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && usable(it) }
|
||||
?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && !x86_64Build(it) && usable(it) }
|
||||
?.map { it.name }
|
||||
?.sortedWith { a, b -> compareVersions(a, b) }
|
||||
?: emptyList()
|
||||
|
||||
internal fun x86_64Build(dir: File): Boolean =
|
||||
File(dir, "files/lib/wine/x86_64-unix").isDirectory && !File(dir, "files/bin-arm64").isDirectory
|
||||
|
||||
private fun usable(dir: File): Boolean {
|
||||
val manifest = runCatching { File(dir, "toolmanifest.vdf").readText() }.getOrNull() ?: return false
|
||||
val command = Regex("\\\"commandline\\\"\\s+\\\"/?([^\\\" ]+)").find(manifest)?.groupValues?.getOrNull(1) ?: return false
|
||||
|
||||
@@ -376,12 +376,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("libraryShowSize", show).apply()
|
||||
}
|
||||
|
||||
fun libraryShowStore(context: Context): Boolean = prefs(context).getBoolean("libraryShowStore", true)
|
||||
|
||||
fun setLibraryShowStore(context: Context, show: Boolean) {
|
||||
prefs(context).edit().putBoolean("libraryShowStore", show).apply()
|
||||
}
|
||||
|
||||
fun libraryShowHidden(context: Context): Boolean = prefs(context).getBoolean("libraryShowHidden", false)
|
||||
|
||||
fun setLibraryShowHidden(context: Context, show: Boolean) {
|
||||
@@ -978,6 +972,9 @@ object SessionPrefs {
|
||||
|
||||
fun returnAfterGame(context: Context): Boolean = prefs(context).getBoolean("returnAfterGame", true)
|
||||
|
||||
/** A sleeping session writes its memory to storage instead of zram. */
|
||||
fun diskSpill(context: Context): Boolean = prefs(context).getBoolean("diskSpill", false)
|
||||
|
||||
fun valveProtonOnDemand(context: Context): Boolean = prefs(context).getBoolean("valveProtonOnDemand", true)
|
||||
|
||||
fun setValveProtonOnDemand(context: Context, on: Boolean) {
|
||||
@@ -2017,24 +2014,84 @@ object SessionPrefs {
|
||||
sessionPrefs.edit().putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString()).apply()
|
||||
}
|
||||
|
||||
private const val GAME_UPSCALER_OVERRIDES_KEY = "upscaler.gameOverrides"
|
||||
|
||||
private fun gameUpscalerOverrides(context: Context): JSONObject = runCatching {
|
||||
JSONObject(prefs(context).getString(GAME_UPSCALER_OVERRIDES_KEY, null) ?: "{}")
|
||||
}.getOrDefault(JSONObject())
|
||||
|
||||
private fun legacyScreenEffectsUpscaler(context: Context, profileId: String): Int? =
|
||||
runCatching {
|
||||
val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
|
||||
val profile = profiles.optJSONObject(profileId)
|
||||
if (profile?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true) {
|
||||
profile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, -1).takeIf { it >= 0 }
|
||||
} else null
|
||||
}.getOrNull()?.let(::canonicalUpscaler)
|
||||
|
||||
private fun clearLegacyScreenEffectsUpscaler(context: Context, profileId: String) {
|
||||
val sessionPrefs = prefs(context)
|
||||
val profiles = runCatching {
|
||||
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
|
||||
}.getOrNull() ?: return
|
||||
val profile = profiles.optJSONObject(profileId) ?: return
|
||||
if (!profile.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY)) return
|
||||
profile.remove(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY)
|
||||
if (profile.length() == 0) profiles.remove(profileId)
|
||||
sessionPrefs.edit().apply {
|
||||
if (profiles.length() == 0) remove(SCREEN_EFFECTS_PROFILES_KEY)
|
||||
else putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString())
|
||||
}.apply()
|
||||
}
|
||||
|
||||
fun hasGameUpscalerOverride(context: Context, gameId: String): Boolean {
|
||||
if (gameId.isBlank()) return false
|
||||
val stored = gameUpscalerOverrides(context)
|
||||
return (stored.has(gameId) && stored.optInt(gameId, -1) >= 0) ||
|
||||
legacyScreenEffectsUpscaler(context, "game:$gameId") != null
|
||||
}
|
||||
|
||||
fun setGameUpscaler(context: Context, gameId: String, mode: Int) {
|
||||
if (gameId.isBlank()) return
|
||||
val overrides = gameUpscalerOverrides(context)
|
||||
overrides.put(gameId, canonicalUpscaler(mode))
|
||||
prefs(context).edit().putString(GAME_UPSCALER_OVERRIDES_KEY, overrides.toString()).apply()
|
||||
clearLegacyScreenEffectsUpscaler(context, "game:$gameId")
|
||||
}
|
||||
|
||||
fun clearGameUpscaler(context: Context, gameId: String) {
|
||||
if (gameId.isBlank()) return
|
||||
val sessionPrefs = prefs(context)
|
||||
val overrides = gameUpscalerOverrides(context)
|
||||
if (overrides.has(gameId)) {
|
||||
overrides.remove(gameId)
|
||||
sessionPrefs.edit().apply {
|
||||
if (overrides.length() == 0) remove(GAME_UPSCALER_OVERRIDES_KEY)
|
||||
else putString(GAME_UPSCALER_OVERRIDES_KEY, overrides.toString())
|
||||
}.apply()
|
||||
}
|
||||
clearLegacyScreenEffectsUpscaler(context, "game:$gameId")
|
||||
}
|
||||
|
||||
fun hasScreenEffectsUpscalerOverride(context: Context, profileId: String?): Boolean {
|
||||
if (profileId.isNullOrBlank()) return false
|
||||
return runCatching {
|
||||
val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
|
||||
profiles.optJSONObject(profileId)?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true
|
||||
}.getOrDefault(false)
|
||||
if (profileId.startsWith("game:")) {
|
||||
return hasGameUpscalerOverride(context, profileId.removePrefix("game:"))
|
||||
}
|
||||
return legacyScreenEffectsUpscaler(context, profileId) != null
|
||||
}
|
||||
|
||||
fun screenEffectsUpscaler(context: Context, profileId: String?): Int {
|
||||
if (profileId.isNullOrBlank()) return upscaler(context)
|
||||
val stored = runCatching {
|
||||
val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
|
||||
val profile = profiles.optJSONObject(profileId)
|
||||
if (profile?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true) {
|
||||
profile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, -1)
|
||||
} else -1
|
||||
}.getOrDefault(-1)
|
||||
return if (stored >= 0) canonicalUpscaler(stored) else upscaler(context)
|
||||
if (profileId.startsWith("game:")) {
|
||||
val gameId = profileId.removePrefix("game:")
|
||||
val overrides = gameUpscalerOverrides(context)
|
||||
if (overrides.has(gameId)) {
|
||||
val stored = overrides.optInt(gameId, -1)
|
||||
if (stored >= 0) return canonicalUpscaler(stored)
|
||||
}
|
||||
}
|
||||
return legacyScreenEffectsUpscaler(context, profileId) ?: upscaler(context)
|
||||
}
|
||||
|
||||
fun setScreenEffectsUpscaler(context: Context, profileId: String?, mode: Int) {
|
||||
@@ -2042,6 +2099,10 @@ object SessionPrefs {
|
||||
setUpscaler(context, mode)
|
||||
return
|
||||
}
|
||||
if (profileId.startsWith("game:")) {
|
||||
setGameUpscaler(context, profileId.removePrefix("game:"), mode)
|
||||
return
|
||||
}
|
||||
val sessionPrefs = prefs(context)
|
||||
val profiles = runCatching {
|
||||
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
|
||||
@@ -2078,6 +2139,7 @@ object SessionPrefs {
|
||||
val profiles = runCatching {
|
||||
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
|
||||
}.getOrElse { JSONObject() }
|
||||
if (profileId.startsWith("game:")) clearGameUpscaler(context, profileId.removePrefix("game:"))
|
||||
if (!profiles.has(profileId)) return
|
||||
profiles.remove(profileId)
|
||||
sessionPrefs.edit().apply {
|
||||
|
||||
@@ -111,6 +111,8 @@ class SessionService : Service() {
|
||||
private var suspendOperationPending = false
|
||||
private var pipTask = false
|
||||
private var suspendAttemptFailed = false
|
||||
private val resumeRecovery = SuspendRecovery()
|
||||
private val retryResume = Runnable { updateSuspendPolicy() }
|
||||
private var freezePending = false
|
||||
private var freezeCancelled = false
|
||||
private var pendingSteamGameId: String? = null
|
||||
@@ -276,7 +278,7 @@ class SessionService : Service() {
|
||||
}
|
||||
ACTION_XR_ACTIVITY_VISIBLE -> {
|
||||
xrActivityVisible = true
|
||||
resumeSession(panelVisible = false)
|
||||
resumeSession(panelVisible = false, restartRecovery = false)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_XR_ACTIVITY_HIDDEN -> {
|
||||
@@ -380,6 +382,8 @@ class SessionService : Service() {
|
||||
suspendOperationPending = false
|
||||
freezePending = false
|
||||
suspendAttemptFailed = false
|
||||
resumeRecovery.reset()
|
||||
mainHandler.removeCallbacks(retryResume)
|
||||
suspendController = null
|
||||
SessionState.micAvailable = false
|
||||
SessionState.micEnabled = false
|
||||
@@ -977,7 +981,7 @@ class SessionService : Service() {
|
||||
SessionEvents.record("session.paged_out", mapOf(
|
||||
"processes" to processes, "unacknowledged" to unacknowledged, "residentMb" to residentKb / 1024,
|
||||
"swapMb" to swapKb / 1024, "swapBeforeMb" to swapBeforeKb / 1024, "ms" to millis,
|
||||
))
|
||||
), sessionDir)
|
||||
}
|
||||
},
|
||||
pagedIn = { processes, swapKb, swapBeforeKb, availableKb, millis ->
|
||||
@@ -990,7 +994,27 @@ class SessionService : Service() {
|
||||
SessionEvents.record("session.paged_in", mapOf(
|
||||
"processes" to processes, "swapMb" to swapKb / 1024, "swapBeforeMb" to swapBeforeKb / 1024,
|
||||
"availableMb" to availableKb / 1024, "ms" to millis,
|
||||
))
|
||||
), sessionDir)
|
||||
}
|
||||
},
|
||||
spilled = { processes, spilledKb, residentKb, millis ->
|
||||
Log.i(TAG, "wrote $processes processes to storage in $millis ms: ${spilledKb / 1024} MB, " +
|
||||
"resident ${residentKb / 1024} MB")
|
||||
mainHandler.post {
|
||||
SessionEvents.record("session.spilled", mapOf(
|
||||
"processes" to processes, "spilledMb" to spilledKb / 1024, "residentMb" to residentKb / 1024,
|
||||
"ms" to millis,
|
||||
), sessionDir)
|
||||
}
|
||||
},
|
||||
restored = { processes, unacknowledged, residentKb, millis ->
|
||||
Log.i(TAG, "restored $processes processes ($unacknowledged unacknowledged) from storage in $millis ms: " +
|
||||
"resident ${residentKb / 1024} MB")
|
||||
mainHandler.post {
|
||||
SessionEvents.record("session.restored", mapOf(
|
||||
"processes" to processes, "unacknowledged" to unacknowledged,
|
||||
"residentMb" to residentKb / 1024, "ms" to millis,
|
||||
), sessionDir)
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -1761,7 +1785,7 @@ class SessionService : Service() {
|
||||
return
|
||||
}
|
||||
if (SessionState.suspended) {
|
||||
resumeSession()
|
||||
resumeSession(restartRecovery = false)
|
||||
mainHandler.postDelayed(flushSteamGame, GAME_LAUNCH_RETRY_MS)
|
||||
return
|
||||
}
|
||||
@@ -1930,8 +1954,10 @@ class SessionService : Service() {
|
||||
private fun steamGameRunning(gameId: String): Boolean =
|
||||
SteamGameProcess.running(gameId)
|
||||
|
||||
private fun resumeSession(panelVisible: Boolean = true) {
|
||||
if (SessionState.suspended) SessionState.resumeRequested = true
|
||||
private fun resumeSession(panelVisible: Boolean = true, restartRecovery: Boolean = true) {
|
||||
if (SessionState.suspended && (restartRecovery || resumeRecovery.due(SystemClock.elapsedRealtime()))) {
|
||||
SessionState.resumeRequested = true
|
||||
}
|
||||
if (panelVisible) activityVisible = true
|
||||
screenOn = readScreenOn()
|
||||
manualPauseRequested = false
|
||||
@@ -1942,6 +1968,7 @@ class SessionService : Service() {
|
||||
completeNativeSleep()
|
||||
completeSteamSleep()
|
||||
suspendAttemptFailed = false
|
||||
if (restartRecovery) resumeRecovery.reset()
|
||||
updateSuspendPolicy()
|
||||
}
|
||||
|
||||
@@ -2160,7 +2187,12 @@ class SessionService : Service() {
|
||||
controller.cancelFreeze()
|
||||
}
|
||||
if (shouldSuspend && SessionState.suspended && !suspendOperationPending) SessionState.resumeRequested = false
|
||||
if (suspendOperationPending || suspendAttemptFailed || shouldSuspend == SessionState.suspended) return
|
||||
// A session still held after a failed suspend or resume is released by paced resumes, whatever clears or
|
||||
// sets the latch; only an explicit resume (resumeSession) restarts the pacing.
|
||||
val held = SessionState.suspended && SessionState.resumeFailed && !shouldSuspend
|
||||
if (!suspendOperationPending && resumeRecovery.holds(held, SystemClock.elapsedRealtime())) return
|
||||
val recovering = suspendAttemptFailed && held
|
||||
if (suspendOperationPending || (suspendAttemptFailed && !recovering) || shouldSuspend == SessionState.suspended) return
|
||||
val gen = sessionGen
|
||||
suspendOperationPending = true
|
||||
SessionEvents.record(if (shouldSuspend) "session.suspend_requested" else "session.resume_requested", mapOf(
|
||||
@@ -2175,9 +2207,9 @@ class SessionService : Service() {
|
||||
freezeCancelled = false
|
||||
val freezeSteamToken = steamSleepToken
|
||||
val freezeNativeToken = nativeSleepToken
|
||||
controller.freeze(
|
||||
pageOut = steamSleepToken != null || nativeSleepToken != null || !activityVisible || !screenOn,
|
||||
) { success ->
|
||||
val pageOut = steamSleepToken != null || nativeSleepToken != null || !activityVisible || !screenOn
|
||||
controller.freeze(pageOut = pageOut, spill = pageOut && SessionPrefs.diskSpill(this)) { success ->
|
||||
val rollbackPending = !success && controller.rollbackPending
|
||||
mainHandler.post {
|
||||
if (gen != sessionGen || !SessionState.running) return@post
|
||||
SessionState.suspending = false
|
||||
@@ -2186,6 +2218,7 @@ class SessionService : Service() {
|
||||
if (success) {
|
||||
SessionState.suspended = true
|
||||
SessionState.resumeFailed = false
|
||||
resumeRecovery.reset()
|
||||
SessionEvents.transition(SessionPhase.SUSPENDED, "session.suspended")
|
||||
releaseLocks()
|
||||
refreshNotification()
|
||||
@@ -2200,6 +2233,12 @@ class SessionService : Service() {
|
||||
SessionState.manualPause = false
|
||||
Log.w(TAG, "could not confirm that the session stopped")
|
||||
}
|
||||
// Some processes are still held: only a resume can release them.
|
||||
if (rollbackPending) {
|
||||
SessionState.suspended = true
|
||||
SessionState.resumeFailed = true
|
||||
Log.w(TAG, "could not return the session to running after the suspend failed")
|
||||
}
|
||||
}
|
||||
updateSuspendPolicy()
|
||||
}
|
||||
@@ -2208,6 +2247,8 @@ class SessionService : Service() {
|
||||
acquireLocks()
|
||||
SessionState.resuming = true
|
||||
controller.resume { success ->
|
||||
// A loss with another spill still reading back is retried for that one; the loss is kept.
|
||||
val lost = !success && controller.guestLost && !controller.restoreOutstanding
|
||||
mainHandler.post {
|
||||
if (gen != sessionGen || !SessionState.running) return@post
|
||||
suspendOperationPending = false
|
||||
@@ -2216,13 +2257,28 @@ class SessionService : Service() {
|
||||
if (success) {
|
||||
SessionState.suspended = false
|
||||
SessionState.resumeFailed = false
|
||||
suspendAttemptFailed = false
|
||||
resumeRecovery.reset()
|
||||
mainHandler.removeCallbacks(retryResume)
|
||||
SessionEvents.transition(SessionEvents.resumePhase(), "session.resumed")
|
||||
refreshNotification()
|
||||
} else if (lost) {
|
||||
// Everything was continued, but a game ended without its memory back: no retry restores
|
||||
// it, and the failure stays reported.
|
||||
SessionState.suspended = false
|
||||
SessionState.resumeFailures++
|
||||
SessionState.resumeFailed = true
|
||||
resumeRecovery.reset()
|
||||
mainHandler.removeCallbacks(retryResume)
|
||||
SessionEvents.transition(SessionEvents.resumePhase(), "session.resume_lost_guest")
|
||||
Log.w(TAG, "a game ended before its memory was read back from storage")
|
||||
refreshNotification()
|
||||
} else {
|
||||
suspendAttemptFailed = true
|
||||
SessionState.resumeFailures++
|
||||
SessionState.resumeFailed = true
|
||||
Log.w(TAG, "could not confirm that the session resumed")
|
||||
resumeRecovery.failed(SystemClock.elapsedRealtime())?.let { mainHandler.postDelayed(retryResume, it) }
|
||||
}
|
||||
updateSuspendPolicy()
|
||||
}
|
||||
|
||||
@@ -29,6 +29,8 @@ internal class SessionSuspendController(
|
||||
{ _, _, _, _, _, _ -> },
|
||||
private val pagedIn: (processes: Int, swapKb: Long, swapBeforeKb: Long, availableKb: Long, millis: Long) -> Unit =
|
||||
{ _, _, _, _, _ -> },
|
||||
private val spilled: (processes: Int, spilledKb: Long, residentKb: Long, millis: Long) -> Unit = { _, _, _, _ -> },
|
||||
private val restored: (processes: Int, unacknowledged: Int, residentKb: Long, millis: Long) -> Unit = { _, _, _, _ -> },
|
||||
) {
|
||||
private enum class Role { SESSION_ROOT, SESSION_CHILD, HELPER_ROOT, HELPER_CHILD }
|
||||
|
||||
@@ -53,10 +55,34 @@ internal class SessionSuspendController(
|
||||
private var frozen = emptyList<ProcessRecord>()
|
||||
private var frozenSince: Long? = null
|
||||
private var pagedOutTargets = emptyList<ProcessRecord>()
|
||||
private var spilledTargets = emptyList<ProcessRecord>()
|
||||
// Asked to spill and not yet released by a resume count they saw: acknowledged or not, each may park its process.
|
||||
private var spillAsked = emptyList<ProcessRecord>()
|
||||
private var counterUnpublished = false
|
||||
// Spilled targets whose positive answer was taken (and its acknowledgement removed).
|
||||
private var spillWritten = emptyList<ProcessRecord>()
|
||||
// Taken into the restore wait by this resume: alive then, so one that ends without its memory back is lost.
|
||||
private var adopted = emptyList<ProcessRecord>()
|
||||
// Released by this attempt on a late answer of 0 or a cancellation: not lost if they end afterwards.
|
||||
private var answeredLate = emptyList<ProcessRecord>()
|
||||
|
||||
fun freeze(pageOut: Boolean = false, completion: (Boolean) -> Unit) {
|
||||
// A spilled process ended without its memory back since the last suspend began: retrying cannot bring it
|
||||
// back, so no later resume of this suspension reports success.
|
||||
@Volatile var guestLost = false
|
||||
private set
|
||||
|
||||
// Spilled processes still reading back, which a later resume waits for again.
|
||||
@Volatile var restoreOutstanding = false
|
||||
private set
|
||||
|
||||
// A failed freeze that could not return every process to running: only a resume releases them.
|
||||
@Volatile var rollbackPending = false
|
||||
private set
|
||||
|
||||
fun freeze(pageOut: Boolean = false, spill: Boolean = false, completion: (Boolean) -> Unit) {
|
||||
cancelled = false
|
||||
submit({
|
||||
guestLost = false
|
||||
val records = frozen.associateByTo(LinkedHashMap()) { it.pid to it.started }
|
||||
var complete = false
|
||||
var interrupted = false
|
||||
@@ -74,7 +100,7 @@ internal class SessionSuspendController(
|
||||
records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.HELPER_ROOT)
|
||||
}
|
||||
}
|
||||
if (pageOut) pageOut(records, root.pid, helpers)
|
||||
if (pageOut) pageOut(records, root.pid, helpers, spill)
|
||||
val deadline = nowMillis() + FREEZE_TIMEOUT_MS
|
||||
var previous: Map<TaskIdentity, Long>? = null
|
||||
for (pass in 0 until FREEZE_MAX_PASSES) {
|
||||
@@ -105,9 +131,14 @@ internal class SessionSuspendController(
|
||||
frozen = records.values.toList()
|
||||
if (complete && frozenSince == null) frozenSince = nowNanos()
|
||||
if (!complete) {
|
||||
if (restoreSafely(frozen)) frozen = emptyList()
|
||||
// A spilled process is back only once its helper has read it back: until then a resume retries.
|
||||
adopted = emptyList()
|
||||
answeredLate = emptyList()
|
||||
val running = startedAlive()
|
||||
if (restoreSafely(frozen) && awaitRestored(running)) frozen = emptyList()
|
||||
runAudio(resumeAudio)
|
||||
}
|
||||
rollbackPending = !complete && frozen.isNotEmpty()
|
||||
if (interrupted) Thread.currentThread().interrupt()
|
||||
}
|
||||
completion(complete)
|
||||
@@ -122,12 +153,23 @@ internal class SessionSuspendController(
|
||||
fun resume(completion: (Boolean) -> Unit) {
|
||||
submit({
|
||||
val records = frozen
|
||||
advanceClock()
|
||||
val advancedTo = advanceClock()
|
||||
adopted = emptyList()
|
||||
answeredLate = emptyList()
|
||||
val running = startedAlive()
|
||||
runAudio(resumeAudio)
|
||||
val resumed = restoreSafely(records)
|
||||
if (resumed) frozen = emptyList()
|
||||
completion(resumed)
|
||||
if (resumed) readBack()
|
||||
if (resumed) {
|
||||
frozen = emptyList()
|
||||
rollbackPending = false
|
||||
}
|
||||
// nothing was continued: the guest clock owes the time from here to the next attempt
|
||||
if (!resumed && counterUnpublished && advancedTo != null) frozenSince = advancedTo
|
||||
// a spilled process runs again only once its helper has read its memory back
|
||||
val restoredAll = resumed && awaitRestored(running)
|
||||
restoreOutstanding = frozen.isNotEmpty() || spilledTargets.isNotEmpty()
|
||||
completion(restoredAll && !guestLost)
|
||||
if (resumed) readBack(waitForRestore = false)
|
||||
}, { completion(false) })
|
||||
}
|
||||
|
||||
@@ -135,7 +177,10 @@ internal class SessionSuspendController(
|
||||
closing = true
|
||||
submit({
|
||||
advanceClock()
|
||||
val running = startedAlive()
|
||||
if (restoreSafely(frozen)) frozen = emptyList()
|
||||
// the teardown asks the guests to exit, which a process still reading back cannot answer
|
||||
if (frozen.isEmpty()) awaitRestored(running, whileClosing = true)
|
||||
completion()
|
||||
executor.shutdown()
|
||||
}, completion)
|
||||
@@ -149,22 +194,25 @@ internal class SessionSuspendController(
|
||||
}
|
||||
}
|
||||
|
||||
private fun advanceClock() {
|
||||
val since = frozenSince ?: return
|
||||
// Returns the moment the guest clock now accounts for, or null when no frozen interval was open.
|
||||
private fun advanceClock(): Long? {
|
||||
val since = frozenSince ?: return null
|
||||
frozenSince = null
|
||||
val control = clockControl?.takeIf { it.isFile && it.length() >= Long.SIZE_BYTES } ?: return
|
||||
val now = nowNanos()
|
||||
val control = clockControl?.takeIf { it.isFile && it.length() >= Long.SIZE_BYTES } ?: return now
|
||||
try {
|
||||
mapClockControl(control)
|
||||
RandomAccessFile(control, "rw").use { file ->
|
||||
val bytes = ByteArray(Long.SIZE_BYTES)
|
||||
file.readFully(bytes)
|
||||
val shift = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).long.coerceAtLeast(0L) +
|
||||
(nowNanos() - since).coerceAtLeast(0L)
|
||||
(now - since).coerceAtLeast(0L)
|
||||
file.seek(0L)
|
||||
file.write(ByteBuffer.allocate(Long.SIZE_BYTES).order(ByteOrder.LITTLE_ENDIAN).putLong(shift).array())
|
||||
}
|
||||
} catch (_: IOException) {
|
||||
}
|
||||
return now
|
||||
}
|
||||
|
||||
private fun runAudio(action: () -> Unit) {
|
||||
@@ -275,13 +323,15 @@ internal class SessionSuspendController(
|
||||
return tasks.takeIf { stopped && it.isNotEmpty() }
|
||||
}
|
||||
|
||||
private fun pageOut(records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
|
||||
private fun pageOut(records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>, spill: Boolean) {
|
||||
val control = zramControl?.takeIf { it.isFile } ?: return
|
||||
val hold = holdFile(control)
|
||||
try {
|
||||
hold.writeText(PAGE_OUT_REQUEST)
|
||||
// A spill names the resume count it was asked under: any later count releases the helper, however
|
||||
// late it starts reading.
|
||||
hold.writeText(if (spill) "$SPILL_REQUEST ${resumeCount(control)}" else PAGE_OUT_REQUEST)
|
||||
sleep(PAGE_OUT_POLL_MS)
|
||||
pageOut(control, records, root, helpers)
|
||||
if (spill) spill(control, records, root, helpers) else pageOut(control, records, root, helpers)
|
||||
} catch (_: IOException) {
|
||||
} finally {
|
||||
hold.delete()
|
||||
@@ -290,15 +340,208 @@ internal class SessionSuspendController(
|
||||
|
||||
private fun holdFile(control: File) = File(control.parentFile, "${control.name}.hold")
|
||||
|
||||
private fun pageOut(control: File, records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
|
||||
private fun ackFile(control: File, kind: String, record: ProcessRecord) =
|
||||
File(control.parentFile, "${control.name}.$kind.${record.pid}")
|
||||
|
||||
private fun preloaded(records: Collection<ProcessRecord>) = records.filter { record ->
|
||||
try {
|
||||
File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libddsession.so") } }
|
||||
} catch (_: IOException) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun readAck(ack: File): Long? = try {
|
||||
ack.readText().trim().toLongOrNull()
|
||||
} catch (_: IOException) {
|
||||
null
|
||||
}
|
||||
|
||||
// Each process parks its threads, writes its private memory to an unlinked file and stays parked until
|
||||
// the resume counter changes; its acknowledgement is the kB it wrote, 0 when it paged out to zram instead.
|
||||
private fun spill(control: File, records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
|
||||
addSnapshot(records, root, helpers)
|
||||
val targets = records.values.filter { record ->
|
||||
try {
|
||||
File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libddsession.so") } }
|
||||
// A restore that finished after the last resume stopped waiting is counted before its marker goes; one
|
||||
// still reading is not asked to spill again.
|
||||
val (done, still) = spilledTargets.partition { settled(control, it) }
|
||||
release(control, done)
|
||||
spilledTargets = still
|
||||
val targets = preloaded(records.values).filterNot { it in spilledTargets }
|
||||
if (targets.isEmpty()) return
|
||||
targets.forEach { ackFile(control, "ack", it).delete(); ackFile(control, "restored", it).delete() }
|
||||
val start = nowMillis()
|
||||
spillAsked = (spillAsked + targets).distinct()
|
||||
for (record in targets) send(record, SIGURG)
|
||||
val waiting = targets.toMutableList()
|
||||
while (!closing && !cancelled && nowMillis() - start < SPILL_TIMEOUT_MS) {
|
||||
val started = nowMillis() - start >= PAGE_OUT_START_MS
|
||||
waiting.removeAll { val ack = ackFile(control, "ack", it); readAck(ack) != null || (started && !ack.exists()) || isGone(it) }
|
||||
if (waiting.isEmpty()) break
|
||||
sleep(PAGE_OUT_POLL_MS)
|
||||
}
|
||||
var total = 0L
|
||||
val acks = targets.associateWith { readAck(ackFile(control, "ack", it)) }
|
||||
val written = targets.filter { record ->
|
||||
val kb = acks[record]?.coerceAtLeast(0L) ?: 0L
|
||||
total += kb
|
||||
kb > 0L
|
||||
}
|
||||
// A process that answered 0 paged out to zram instead and has no spill to release. One whose handler
|
||||
// started (its acknowledgement is there, still empty) may still be writing: it is waited for like a
|
||||
// spilled one, its acknowledgement kept. One with no acknowledgement may have no handler, or one that has
|
||||
// not got that far: it is not waited for, but stays asked, so a resume count that cannot be written still
|
||||
// fails (a late spill waits for any count other than the one it was asked with).
|
||||
val unanswered = targets.filter { acks[it] == null && ackFile(control, "ack", it).exists() && !isGone(it) }
|
||||
spillAsked = spillAsked.filterNot { acks[it] == 0L || acks[it] == SPILL_CANCELLED }
|
||||
spilledTargets = (spilledTargets + written + unanswered).distinct()
|
||||
spillWritten = (spillWritten + written).distinct()
|
||||
pagedOutTargets = (pagedOutTargets + targets.filter { acks[it] == 0L }).distinct()
|
||||
targets.filterNot { it in unanswered }.forEach { ackFile(control, "ack", it).delete() }
|
||||
spilled(written.size, total, memoryKb(targets).first, nowMillis() - start)
|
||||
}
|
||||
|
||||
// Its memory is back, it paged out to zram after all (an answer of 0 that came late), a resume cancelled
|
||||
// it before it wrote anything, or it is gone.
|
||||
private fun settled(control: File, record: ProcessRecord): Boolean {
|
||||
val ack = readAck(ackFile(control, "ack", record))
|
||||
return readAck(ackFile(control, "restored", record)) != null || ack == 0L || ack == SPILL_CANCELLED ||
|
||||
ended(record)
|
||||
}
|
||||
|
||||
// Gone, or every thread has exited and only an unreaped zombie is left.
|
||||
private fun ended(record: ProcessRecord): Boolean {
|
||||
if (isGone(record)) return true
|
||||
val tasks = File(procRoot, "${record.pid}/task").listFiles()?.filter { it.name.toIntOrNull() != null } ?: return false
|
||||
return tasks.all { entry ->
|
||||
try { readStat(File(entry, "stat"))[0].first().let { it == 'Z' || it == 'X' } } catch (_: IOException) { false }
|
||||
}
|
||||
}
|
||||
|
||||
// Settled targets stop being tracked; one that fell back to zram late is read back like any paged-out one.
|
||||
private fun release(control: File, settledTargets: List<ProcessRecord>) {
|
||||
val lateZram = settledTargets.filter { readAck(ackFile(control, "ack", it)) == 0L && !isGone(it) }
|
||||
pagedOutTargets = (pagedOutTargets + lateZram).distinct()
|
||||
spillAsked = spillAsked.filterNot { it in settledTargets }
|
||||
spillWritten = spillWritten.filterNot { it in settledTargets }
|
||||
settledTargets.forEach {
|
||||
ackFile(control, "restored", it).delete()
|
||||
ackFile(control, "ack", it).delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun resumeFile(control: File) = File(control.parentFile, "${control.name}.resume")
|
||||
|
||||
private fun resumeCount(control: File): Long = try {
|
||||
resumeFile(control).takeIf { it.isFile }?.readText()?.trim()?.toLongOrNull() ?: 0L
|
||||
} catch (_: IOException) {
|
||||
0L
|
||||
}
|
||||
|
||||
// False when a process asked to spill may not have seen the new count: it would stay stopped. The count is
|
||||
// put in place whole, so a failed write leaves the one before.
|
||||
private fun bumpResume(): Boolean {
|
||||
val control = zramControl?.takeIf { it.isFile } ?: return spillAsked.isEmpty()
|
||||
// A late answer of 0 or a cancellation already let its process go: it needs no count.
|
||||
val answered = spillAsked.filter {
|
||||
val ack = readAck(ackFile(control, "ack", it))
|
||||
ack == 0L || ack == SPILL_CANCELLED
|
||||
}
|
||||
if (answered.isNotEmpty()) {
|
||||
answeredLate = (answeredLate + answered).distinct()
|
||||
spilledTargets = spilledTargets.filterNot { it in answered }
|
||||
release(control, answered)
|
||||
}
|
||||
val counter = resumeFile(control)
|
||||
val ok = try {
|
||||
val next = resumeCount(control) + 1
|
||||
val fresh = File(counter.parentFile, "${counter.name}.new")
|
||||
fresh.writeText(next.toString())
|
||||
java.nio.file.Files.move(fresh.toPath(), counter.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING,
|
||||
java.nio.file.StandardCopyOption.ATOMIC_MOVE)
|
||||
resumeCount(control) == next
|
||||
} catch (_: IOException) {
|
||||
false
|
||||
}
|
||||
if (ok) spillAsked = emptyList()
|
||||
return ok || spillAsked.isEmpty()
|
||||
}
|
||||
|
||||
// True when every spilled process has its memory back (or was gone already). Ones still reading stay
|
||||
// tracked, so a later resume waits for them again. One of [running] that ends without its memory back fails
|
||||
// this resume.
|
||||
private fun awaitRestored(running: Collection<ProcessRecord> = emptyList(), whileClosing: Boolean = false): Boolean {
|
||||
val control = zramControl ?: return true
|
||||
val targets = spilledTargets
|
||||
val start = nowMillis()
|
||||
val waiting = targets.toMutableList()
|
||||
val untraced = HashMap<ProcessRecord, Long>()
|
||||
val releasedWithoutMarker = HashSet<ProcessRecord>()
|
||||
try {
|
||||
while (targets.isNotEmpty() && (whileClosing || !closing) && nowMillis() - start < RESTORE_TIMEOUT_MS) {
|
||||
waiting.removeAll {
|
||||
settled(control, it) || detached(control, it, untraced).also { done -> if (done) releasedWithoutMarker += it }
|
||||
}
|
||||
if (waiting.isEmpty()) break
|
||||
sleep(PAGE_OUT_POLL_MS)
|
||||
}
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
}
|
||||
val lost = (running + adopted).distinct().filterNot { it in answeredLate || it in releasedWithoutMarker }.filter { record ->
|
||||
val ack = readAck(ackFile(control, "ack", record))
|
||||
ended(record) && readAck(ackFile(control, "restored", record)) == null && ack != 0L && ack != SPILL_CANCELLED
|
||||
}
|
||||
adopted = emptyList()
|
||||
answeredLate = emptyList()
|
||||
if (lost.isNotEmpty()) guestLost = true
|
||||
if (targets.isNotEmpty()) {
|
||||
release(control, targets.filterNot { it in waiting })
|
||||
spilledTargets = waiting.toList()
|
||||
restored(targets.size, waiting.size, memoryKb(targets).first, nowMillis() - start)
|
||||
}
|
||||
return waiting.isEmpty() && lost.isEmpty()
|
||||
}
|
||||
|
||||
// A process that wrote its spill is traced by its helper until the read-back ends; one that stays untraced
|
||||
// and alive for a while has its memory back even if the helper could not write its marker (a helper that
|
||||
// dies first has its owner killed).
|
||||
private fun detached(control: File, record: ProcessRecord, untraced: MutableMap<ProcessRecord, Long>): Boolean {
|
||||
if (record !in spillWritten && (readAck(ackFile(control, "ack", record)) ?: 0L) <= 0L) return false
|
||||
// The helper detaches thread by thread, so every live thread must be out of its trace.
|
||||
val current = try { readProcess(record.pid) } catch (_: IOException) { null }
|
||||
if (current == null || current.started != record.started || ended(record) || anyThreadTraced(record)) {
|
||||
untraced.remove(record)
|
||||
return false
|
||||
}
|
||||
return nowMillis() - untraced.getOrPut(record) { nowMillis() } >= MARKER_GRACE_MS
|
||||
}
|
||||
|
||||
private fun anyThreadTraced(record: ProcessRecord): Boolean {
|
||||
val tasks = File(procRoot, "${record.pid}/task").listFiles() ?: return true
|
||||
return tasks.any { entry ->
|
||||
entry.name.toIntOrNull() != null && try {
|
||||
File(entry, "status").useLines { lines ->
|
||||
lines.firstOrNull { it.startsWith("TracerPid:") }?.substringAfter(':')?.trim()?.toIntOrNull() != 0
|
||||
}
|
||||
} catch (_: IOException) {
|
||||
false
|
||||
File(entry, "stat").exists()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Asked, started or written spills of processes alive now: one that ends without its memory back (or a 0 or
|
||||
// cancelled answer) is lost.
|
||||
private fun startedAlive(): List<ProcessRecord> {
|
||||
val control = zramControl ?: return emptyList()
|
||||
return (spilledTargets + spillAsked).distinct().filter {
|
||||
val ack = readAck(ackFile(control, "ack", it))
|
||||
ack != 0L && ack != SPILL_CANCELLED && !ended(it)
|
||||
}
|
||||
}
|
||||
|
||||
private fun pageOut(control: File, records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
|
||||
addSnapshot(records, root, helpers)
|
||||
val targets = preloaded(records.values)
|
||||
if (targets.isEmpty()) return
|
||||
pagedOutTargets = (pagedOutTargets + targets).distinct()
|
||||
val acks = targets.associateWith { File(control.parentFile, "${control.name}.ack.${it.pid}") }
|
||||
@@ -325,7 +568,8 @@ internal class SessionSuspendController(
|
||||
false
|
||||
}
|
||||
|
||||
private fun readBack() {
|
||||
private fun readBack(waitForRestore: Boolean = true) {
|
||||
if (waitForRestore) awaitRestored()
|
||||
val targets = pagedOutTargets.filterNot { isGone(it) }
|
||||
pagedOutTargets = emptyList()
|
||||
val control = zramControl?.takeIf { it.isFile } ?: return
|
||||
@@ -411,10 +655,12 @@ internal class SessionSuspendController(
|
||||
private fun stopThreads(record: ProcessRecord) {
|
||||
val current = try { readProcess(record.pid) } catch (_: Exception) { return }
|
||||
if (current == null || current.started != record.started) return
|
||||
// A spill helper's tracing stop ends when it detaches after reading back: the pending SIGSTOP holds then.
|
||||
val helperHeld = record in spilledTargets
|
||||
for (entry in File(procRoot, "${record.pid}/task").listFiles().orEmpty()) {
|
||||
val tid = entry.name.toIntOrNull() ?: continue
|
||||
val state = try { readStat(File(entry, "stat"))[0].first() } catch (_: IOException) { continue }
|
||||
if (state == 'T' || state == 't' || state == 'Z' || state == 'X') continue
|
||||
if (state == 'T' || (state == 't' && !helperHeld) || state == 'Z' || state == 'X') continue
|
||||
try {
|
||||
threadSignal(record.pid, tid, SIGSTOP)
|
||||
} catch (_: Throwable) {
|
||||
@@ -431,6 +677,10 @@ internal class SessionSuspendController(
|
||||
Role.HELPER_CHILD -> 3
|
||||
}
|
||||
}
|
||||
val asked = spillAsked
|
||||
counterUnpublished = !bumpResume()
|
||||
if (counterUnpublished) return false
|
||||
adoptStartedSpills(asked)
|
||||
for (record in ordered) send(record, SIGCONT)
|
||||
val waiting = ordered.toMutableList()
|
||||
repeat(RESTORE_CHECKS) { check ->
|
||||
@@ -442,6 +692,15 @@ internal class SessionSuspendController(
|
||||
return false
|
||||
}
|
||||
|
||||
// A handler that started after the spill wait ended parks its process until it has read back, like one
|
||||
// that answered in time.
|
||||
private fun adoptStartedSpills(asked: List<ProcessRecord>) {
|
||||
val control = zramControl ?: return
|
||||
val started = asked.filter { it !in spilledTargets && ackFile(control, "ack", it).exists() && !ended(it) }
|
||||
if (started.isNotEmpty()) spilledTargets = spilledTargets + started
|
||||
adopted = started
|
||||
}
|
||||
|
||||
private fun restoreSafely(records: List<ProcessRecord>): Boolean = try {
|
||||
restore(records)
|
||||
} catch (_: InterruptedException) {
|
||||
@@ -460,10 +719,12 @@ internal class SessionSuspendController(
|
||||
}
|
||||
}
|
||||
|
||||
// A spilled process's threads stay in a tracing stop until its helper has read its memory back.
|
||||
private fun isRunningOrGone(record: ProcessRecord): Boolean {
|
||||
val current = try { readProcess(record.pid) } catch (_: Exception) { return false }
|
||||
if (current == null || current.started != record.started) return true
|
||||
if (current.state == 'T' || current.state == 't') return false
|
||||
val spilled = record in spilledTargets
|
||||
if (current.state == 'T' || (current.state == 't' && !spilled)) return false
|
||||
return File(procRoot, "${record.pid}/task").listFiles().orEmpty().none { entry ->
|
||||
entry.name.toIntOrNull() != null &&
|
||||
try { readStat(File(entry, "stat"))[0].first() == 'T' } catch (_: IOException) { false }
|
||||
@@ -477,6 +738,11 @@ internal class SessionSuspendController(
|
||||
const val PAGE_OUT_ACK = "1"
|
||||
const val PAGE_OUT_REQUEST = "1"
|
||||
const val READ_BACK_REQUEST = "0"
|
||||
const val SPILL_REQUEST = "4"
|
||||
const val SPILL_CANCELLED = -2L
|
||||
const val SPILL_TIMEOUT_MS = 30_000L
|
||||
const val RESTORE_TIMEOUT_MS = 30_000L
|
||||
const val MARKER_GRACE_MS = 1_000L
|
||||
const val PAGE_OUT_POLL_MS = 100L
|
||||
const val PAGE_OUT_START_MS = 2_000L
|
||||
const val PAGE_OUT_TIMEOUT_MS = 12_000L
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
// Paced resume retries for a session that is still held after a failed suspend or resume.
|
||||
internal class SuspendRecovery(
|
||||
private val maxAttempts: Int = 5,
|
||||
private val firstDelayMs: Long = 5_000L,
|
||||
) {
|
||||
private var attempts = 0
|
||||
private var nextAt = 0L
|
||||
|
||||
fun due(now: Long): Boolean = attempts < maxAttempts && now >= nextAt
|
||||
|
||||
// Whether a session that is still held must wait instead of starting another resume now.
|
||||
fun holds(held: Boolean, now: Long): Boolean = held && !due(now)
|
||||
|
||||
// The delay before the next attempt is due, or null when no attempt is left.
|
||||
fun failed(now: Long): Long? {
|
||||
attempts++
|
||||
if (attempts >= maxAttempts) return null
|
||||
val delay = firstDelayMs shl (attempts - 1)
|
||||
nextAt = now + delay
|
||||
return delay
|
||||
}
|
||||
|
||||
fun reset() {
|
||||
attempts = 0
|
||||
nextAt = 0L
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,9 @@ import android.content.ContextWrapper
|
||||
import android.os.Build
|
||||
import android.view.KeyEvent
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.LocalActivityResultRegistryOwner
|
||||
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.animation.expandVertically
|
||||
@@ -50,12 +52,12 @@ import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.outlined.Send
|
||||
import androidx.compose.material.icons.outlined.Extension
|
||||
import androidx.compose.material.icons.outlined.PhotoCamera
|
||||
import androidx.compose.material.icons.outlined.MicOff
|
||||
import androidx.compose.material.icons.outlined.Mic
|
||||
import androidx.compose.material.icons.outlined.Add
|
||||
import androidx.compose.material.icons.outlined.ArrowDownward
|
||||
import androidx.compose.material.icons.outlined.AttachFile
|
||||
import androidx.compose.material.icons.outlined.Keyboard
|
||||
import androidx.compose.material.icons.outlined.Terminal
|
||||
import androidx.compose.material.icons.outlined.Build
|
||||
import androidx.compose.material.icons.outlined.Close
|
||||
@@ -79,6 +81,7 @@ import androidx.compose.runtime.MutableState
|
||||
import androidx.compose.runtime.Stable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
@@ -108,6 +111,7 @@ import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.platform.testTag
|
||||
@@ -301,7 +305,7 @@ private fun AgentPageContent(
|
||||
readingBack = false
|
||||
scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) }
|
||||
}
|
||||
val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() &&
|
||||
val hidden = !composer.focused && !composer.tray && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() &&
|
||||
AgentHost.approvals.isEmpty()
|
||||
var listHeight by remember { mutableIntStateOf(0) }
|
||||
Box(
|
||||
@@ -319,6 +323,7 @@ private fun AgentPageContent(
|
||||
awaitEachGesture {
|
||||
awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
|
||||
if (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE) panel = AgentPanel.NONE
|
||||
composer.tray = false
|
||||
// Forced: the unforced path walks the focus chain and throws ("ActiveParent with no focused child") when a tap lands while focus is moving.
|
||||
if (composer.focused) focusManager.clearFocus(force = true)
|
||||
}
|
||||
@@ -344,6 +349,12 @@ private fun AgentPageContent(
|
||||
@Stable
|
||||
private class ComposerState {
|
||||
var focused by mutableStateOf(false)
|
||||
/** The photo tray stands in for the keyboard, at the height the keyboard last had. */
|
||||
var tray by mutableStateOf(false)
|
||||
var keyboardHeight by mutableStateOf(0.dp)
|
||||
/** Tray photos copied, or being copied, for this conversation, so reopening the tray keeps their marks and copies nothing twice. */
|
||||
val photoCopies = mutableStateMapOf<android.net.Uri, String>()
|
||||
val photosCopying = mutableStateMapOf<android.net.Uri, Any>()
|
||||
var focusRequests by mutableIntStateOf(0)
|
||||
private set
|
||||
private var consumedFocusRequests by mutableIntStateOf(0)
|
||||
@@ -390,7 +401,7 @@ private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstCon
|
||||
.clickable { onPanel(AgentPanel.MODEL) }.padding(horizontal = 8.dp).testTag("agent-model"),
|
||||
) {
|
||||
val mode = AgentHost.harness.permissions.drop(1).firstOrNull { it.id == AgentHost.permission }?.let { stringResource(it.label) }
|
||||
val parts = if (compact) listOfNotNull(mode ?: model)
|
||||
val parts = if (compact) listOf(model)
|
||||
else listOfNotNull(
|
||||
AgentHost.harness.name, model, AgentHost.effort, mode,
|
||||
stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans },
|
||||
@@ -748,6 +759,8 @@ private fun AgentComposer(
|
||||
if (text.isEmpty() && AgentAttachments.pending.isEmpty()) return@send
|
||||
AgentHost.send(context, text, AgentAttachments.pending.toList())
|
||||
AgentAttachments.pending.clear()
|
||||
composer.photosCopying.clear()
|
||||
composer.tray = false
|
||||
onSent()
|
||||
}
|
||||
}
|
||||
@@ -813,7 +826,34 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
val field = remember { FocusRequester() }
|
||||
LaunchedEffect(composer.focusRequests) { if (composer.hasUnconsumedFocusRequest()) runCatching { field.requestFocus() } }
|
||||
val attach = LocalActivityResultRegistryOwner.current != null
|
||||
val picks = LocalActivityResultRegistryOwner.current != null
|
||||
val density = LocalDensity.current
|
||||
val imeHeight = WindowInsets.ime.getBottom(density)
|
||||
LaunchedEffect(imeHeight) {
|
||||
val height = with(density) { imeHeight.toDp() }
|
||||
if (height > composer.keyboardHeight) composer.keyboardHeight = height
|
||||
}
|
||||
LaunchedEffect(hideAttach) { if (hideAttach) composer.tray = false }
|
||||
LaunchedEffect(AgentHost.chat) {
|
||||
composer.photoCopies.clear()
|
||||
composer.photosCopying.clear()
|
||||
}
|
||||
// BackHandler throws where the host provides no back dispatcher: the front end and the floating pet.
|
||||
if (LocalOnBackPressedDispatcherOwner.current != null) BackHandler(composer.tray) { composer.tray = false }
|
||||
val focusManager = LocalFocusManager.current
|
||||
val files = if (picks) rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) {
|
||||
AgentAttachments.picking = false
|
||||
attachUris(context, it)
|
||||
} else null
|
||||
val toggleTray = {
|
||||
if (composer.tray) {
|
||||
composer.tray = false
|
||||
composer.open()
|
||||
} else {
|
||||
focusManager.clearFocus(force = true)
|
||||
composer.tray = true
|
||||
}
|
||||
}
|
||||
BoxWithConstraints(
|
||||
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape16).background(colors.surface)
|
||||
.border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16).padding(6.dp),
|
||||
@@ -841,6 +881,7 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
|
||||
Modifier.fillMaxWidth().focusRequester(field).onFocusChanged {
|
||||
focused = it.isFocused
|
||||
composer.focused = it.isFocused
|
||||
if (it.isFocused) composer.tray = false
|
||||
if (it.isFocused) composer.consumeFocusRequest()
|
||||
}.testTag("agent-input"),
|
||||
textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface),
|
||||
@@ -866,19 +907,22 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
|
||||
if (stacked) Column {
|
||||
text(Modifier.fillMaxWidth())
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
|
||||
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
|
||||
AnimatedVisibility(!hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton(composer.tray, toggleTray) }
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp).horizontalScroll(rememberScrollState(), reverseScrolling = true)) { if (controls != null && !focused) controls() }
|
||||
actions()
|
||||
}
|
||||
} else Row(verticalAlignment = Alignment.Bottom) {
|
||||
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
|
||||
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
|
||||
AnimatedVisibility(!hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton(composer.tray, toggleTray) }
|
||||
text(Modifier.weight(1f))
|
||||
if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() }
|
||||
actions()
|
||||
}
|
||||
}
|
||||
AnimatedVisibility(composer.tray, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
|
||||
val most = LocalConfiguration.current.screenHeightDp.dp * 0.45f
|
||||
val height = (if (composer.keyboardHeight > 0.dp) composer.keyboardHeight else 280.dp).coerceAtLeast(160.dp).coerceAtMost(most)
|
||||
AgentPhotoTray(height, composer.photoCopies, composer.photosCopying, files?.let { { AgentAttachments.pick { it.launch(arrayOf("*/*")) } } })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -974,53 +1018,15 @@ private fun VoiceButton(voice: AgentVoice, onStart: () -> Unit, onSend: () -> Un
|
||||
}
|
||||
}
|
||||
|
||||
/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */
|
||||
/** Opens the photo tray in place of the keyboard; while it is open, brings the keyboard back. */
|
||||
@Composable
|
||||
private fun GameFrameButton() {
|
||||
val context = LocalContext.current
|
||||
private fun AttachButton(trayOpen: Boolean, onClick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
RoundButton(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), pal.surfaceVariant, pal.onBackground, "agent-game-frame") {
|
||||
val grab = AgentAttachments.gameFrame ?: return@RoundButton
|
||||
val chat = AgentHost.chat
|
||||
grab frame@{ frame ->
|
||||
if (frame == null) {
|
||||
android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return@frame
|
||||
}
|
||||
Thread({
|
||||
val path = AgentAttachments.saveFrame(context, chat, frame)
|
||||
frame.recycle()
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).post {
|
||||
when {
|
||||
path == null -> android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
|
||||
AgentHost.chat == chat -> AgentAttachments.pending.add(path)
|
||||
else -> AgentAttachments.discard(context, listOf(path))
|
||||
}
|
||||
}
|
||||
}, "agent-game-frame").start()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AttachButton() {
|
||||
val context = LocalContext.current
|
||||
val pal = LocalPalette.current
|
||||
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
|
||||
AgentAttachments.picking = false
|
||||
if (uris.isEmpty()) return@rememberLauncherForActivityResult
|
||||
val chat = AgentHost.chat
|
||||
Thread({
|
||||
val paths = AgentAttachments.copy(context, chat, uris)
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).post {
|
||||
if (AgentHost.chat == chat) AgentAttachments.pending.addAll(paths) else AgentAttachments.discard(context, paths)
|
||||
}
|
||||
}, "agent-attach").start()
|
||||
}
|
||||
RoundButton(Icons.Outlined.AttachFile, stringResource(R.string.agent_attach), pal.surfaceVariant, pal.onBackground, "agent-attach") {
|
||||
AgentAttachments.picking = true
|
||||
if (runCatching { picker.launch(arrayOf("*/*")) }.isFailure) AgentAttachments.picking = false
|
||||
}
|
||||
RoundButton(
|
||||
if (trayOpen) Icons.Outlined.Keyboard else Icons.Outlined.AttachFile,
|
||||
stringResource(if (trayOpen) R.string.agent_keyboard else R.string.agent_attach),
|
||||
if (trayOpen) pal.primary else pal.surfaceVariant, if (trayOpen) pal.onPrimary else pal.onBackground, "agent-attach", onClick = onClick,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.Manifest
|
||||
import android.content.ContentUris
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.MediaStore
|
||||
import android.provider.Settings
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.LocalActivityResultRegistryOwner
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.GridItemSpan
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Check
|
||||
import androidx.compose.material.icons.outlined.FolderOpen
|
||||
import androidx.compose.material.icons.outlined.PhotoCamera
|
||||
import androidx.compose.material.icons.outlined.PhotoLibrary
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshots.SnapshotStateMap
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.selected
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import coil.compose.AsyncImage
|
||||
import coil.request.ImageRequest
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.agent.AgentAttachments
|
||||
import com.droiddeck.launcher.agent.AgentHost
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** The device's photos, newest first, as MediaStore lets the app see them. */
|
||||
internal object AgentPhotos {
|
||||
enum class Access { NONE, SELECTED, ALL }
|
||||
|
||||
/** Android stops showing the request after repeated denials and answers it at once, so a denied request sends later ones to Settings. */
|
||||
var refused = false
|
||||
|
||||
fun permissions(sdk: Int = Build.VERSION.SDK_INT): Array<String> = when {
|
||||
sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE -> arrayOf(Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED)
|
||||
sdk >= Build.VERSION_CODES.TIRAMISU -> arrayOf(Manifest.permission.READ_MEDIA_IMAGES)
|
||||
else -> arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
|
||||
}
|
||||
|
||||
fun access(context: Context): Access {
|
||||
fun granted(permission: String) = context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
|
||||
val all = permissions().first()
|
||||
return when {
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && Environment.isExternalStorageManager() -> Access.ALL
|
||||
granted(all) -> Access.ALL
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && granted(Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED) -> Access.SELECTED
|
||||
else -> Access.NONE
|
||||
}
|
||||
}
|
||||
|
||||
class Photo(val uri: Uri, val name: String)
|
||||
|
||||
fun recent(context: Context, limit: Int = 300): List<Photo> = runCatching {
|
||||
val images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
|
||||
context.contentResolver.query(
|
||||
images, arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME), null, null, "${MediaStore.Images.Media.DATE_ADDED} DESC",
|
||||
)?.use { c ->
|
||||
buildList {
|
||||
while (size < limit && c.moveToNext()) add(Photo(ContentUris.withAppendedId(images, c.getLong(0)), c.getString(1).orEmpty()))
|
||||
}
|
||||
}.orEmpty()
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies [uris] into the conversation's attachments off the main thread, then hands [onCopied] what was attached: nothing if the
|
||||
* conversation changed meanwhile or [current] says the copy was superseded.
|
||||
*/
|
||||
internal fun attachUris(context: Context, uris: List<Uri>, current: () -> Boolean = { true }, onCopied: (List<Pair<Uri, String>>) -> Unit = {}) {
|
||||
if (uris.isEmpty()) return
|
||||
val chat = AgentHost.chat
|
||||
Thread({
|
||||
val copied = uris.mapNotNull { uri -> AgentAttachments.copy(context, chat, listOf(uri)).firstOrNull()?.let { uri to it } }
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).post {
|
||||
val paths = copied.map { it.second }
|
||||
if (AgentHost.chat == chat && current()) {
|
||||
AgentAttachments.pending.addAll(paths)
|
||||
onCopied(copied)
|
||||
} else {
|
||||
AgentAttachments.discard(context, paths)
|
||||
onCopied(emptyList())
|
||||
}
|
||||
}
|
||||
}, "agent-attach").start()
|
||||
}
|
||||
|
||||
/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */
|
||||
private fun attachGameFrame(context: Context) {
|
||||
val grab = AgentAttachments.gameFrame ?: return
|
||||
val chat = AgentHost.chat
|
||||
grab frame@{ frame ->
|
||||
if (frame == null) {
|
||||
Toast.makeText(context, R.string.agent_attach_game_failed, Toast.LENGTH_SHORT).show()
|
||||
return@frame
|
||||
}
|
||||
Thread({
|
||||
val path = AgentAttachments.saveFrame(context, chat, frame)
|
||||
frame.recycle()
|
||||
android.os.Handler(android.os.Looper.getMainLooper()).post {
|
||||
when {
|
||||
path == null -> Toast.makeText(context, R.string.agent_attach_game_failed, Toast.LENGTH_SHORT).show()
|
||||
AgentHost.chat == chat -> AgentAttachments.pending.add(path)
|
||||
else -> AgentAttachments.discard(context, listOf(path))
|
||||
}
|
||||
}
|
||||
}, "agent-game-frame").start()
|
||||
}
|
||||
}
|
||||
|
||||
/** Shown in place of the keyboard: recent photos to tap onto the message, and the system picker for anything else. */
|
||||
@Composable
|
||||
internal fun AgentPhotoTray(height: Dp, copies: SnapshotStateMap<Uri, String>, copying: SnapshotStateMap<Uri, Any>, onFiles: (() -> Unit)?) {
|
||||
val context = LocalContext.current
|
||||
val pal = LocalPalette.current
|
||||
var access by remember { mutableStateOf(AgentPhotos.access(context)) }
|
||||
var photos by remember { mutableStateOf<List<AgentPhotos.Photo>?>(null) }
|
||||
var reloads by remember { mutableStateOf(0) }
|
||||
// A window no activity owns (the floating pet's chat) cannot ask for a permission, so it sends the user to the app's settings.
|
||||
val launcher = if (LocalActivityResultRegistryOwner.current != null) {
|
||||
rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
|
||||
AgentAttachments.picking = false
|
||||
access = AgentPhotos.access(context)
|
||||
if (access == AgentPhotos.Access.NONE) AgentPhotos.refused = true
|
||||
reloads++
|
||||
}
|
||||
} else null
|
||||
val request = {
|
||||
if (launcher != null && !AgentPhotos.refused) {
|
||||
AgentAttachments.pick { launcher.launch(AgentPhotos.permissions()) }
|
||||
} else {
|
||||
val details = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + context.packageName)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(details) }
|
||||
}
|
||||
Unit
|
||||
}
|
||||
// Access can change in Settings, and new pictures arrive, while the app is in the background.
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
DisposableEffect(lifecycle) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME) {
|
||||
access = AgentPhotos.access(context)
|
||||
reloads++
|
||||
}
|
||||
}
|
||||
lifecycle.addObserver(observer)
|
||||
onDispose { lifecycle.removeObserver(observer) }
|
||||
}
|
||||
LaunchedEffect(access, reloads) {
|
||||
photos = if (access == AgentPhotos.Access.NONE) emptyList() else withContext(Dispatchers.IO) { AgentPhotos.recent(context) }
|
||||
}
|
||||
LazyVerticalGrid(
|
||||
GridCells.Adaptive(96.dp),
|
||||
Modifier.fillMaxWidth().height(height).padding(top = 8.dp).testTag("agent-photo-tray"),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
if (AgentAttachments.gameFrame != null) item {
|
||||
TrayTile(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), "agent-game-frame") { attachGameFrame(context) }
|
||||
}
|
||||
if (onFiles != null) item { TrayTile(Icons.Outlined.FolderOpen, stringResource(R.string.agent_attach_files), "agent-attach-files", onFiles) }
|
||||
if (access != AgentPhotos.Access.ALL) item {
|
||||
TrayTile(
|
||||
Icons.Outlined.PhotoLibrary,
|
||||
stringResource(if (access == AgentPhotos.Access.NONE) R.string.agent_photos_allow else R.string.agent_photos_more),
|
||||
"agent-photos-allow",
|
||||
onClick = request,
|
||||
)
|
||||
}
|
||||
val list = photos
|
||||
if (list != null && list.isEmpty() && access != AgentPhotos.Access.NONE) item(span = { GridItemSpan(maxLineSpan) }) {
|
||||
Text(
|
||||
stringResource(R.string.agent_photos_empty), fontSize = 13.sp, color = pal.onSurfaceVariant, textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp),
|
||||
)
|
||||
}
|
||||
items(list.orEmpty(), key = { it.uri.toString() }) { photo ->
|
||||
val uri = photo.uri
|
||||
val path = copies[uri]
|
||||
val selected = path != null && path in AgentAttachments.pending
|
||||
Box(
|
||||
Modifier.aspectRatio(1f).clip(Shape12).background(pal.surfaceVariant)
|
||||
.then(if (selected) Modifier.border(3.dp, pal.primary, Shape12) else Modifier)
|
||||
.clickable {
|
||||
when {
|
||||
selected -> AgentAttachments.pending.remove(path)
|
||||
path != null && AgentAttachments.host(context, path).exists() -> AgentAttachments.pending.add(path)
|
||||
uri in copying -> Unit
|
||||
else -> {
|
||||
// Leaving the conversation clears the markers, so a copy started before that is no longer current even back in it.
|
||||
val copy = Any()
|
||||
copying[uri] = copy
|
||||
attachUris(context, listOf(uri), current = { copying[uri] === copy }) { copied ->
|
||||
copied.forEach { (u, p) -> copies[u] = p }
|
||||
if (copying[uri] === copy) copying.remove(uri)
|
||||
}
|
||||
}
|
||||
}
|
||||
}.semantics {
|
||||
contentDescription = photo.name
|
||||
this.selected = selected
|
||||
}.testTag("agent-photo"),
|
||||
) {
|
||||
AsyncImage(
|
||||
model = ImageRequest.Builder(context).data(uri).size(320).build(), contentDescription = null,
|
||||
contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
if (selected) Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.align(Alignment.TopEnd).padding(6.dp).size(22.dp).clip(CircleShape).background(pal.primary),
|
||||
) {
|
||||
Icon(Icons.Outlined.Check, null, tint = pal.onPrimary, modifier = Modifier.size(16.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TrayTile(icon: ImageVector, label: String, tag: String, onClick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center,
|
||||
modifier = Modifier.aspectRatio(1f).clip(Shape12).background(pal.surfaceVariant).clickable(onClick = onClick).padding(8.dp).testTag(tag),
|
||||
) {
|
||||
Icon(icon, null, tint = pal.onBackground, modifier = Modifier.size(26.dp))
|
||||
Text(
|
||||
label, fontSize = 12.sp, color = pal.onBackground, textAlign = TextAlign.Center, maxLines = 3, overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.padding(top = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -881,6 +881,28 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
com.droiddeck.launcher.gpu.FrameGen.hasGameOverride(context, it)
|
||||
} ?: false)
|
||||
}
|
||||
val scalingFilterChoices = SessionPrefs.upscalerChoices(context)
|
||||
var gameUpscaler by remember(frameGenProfileKey) {
|
||||
mutableStateOf(frameGenProfileKey?.let {
|
||||
SessionPrefs.screenEffectsUpscaler(context, "game:$it")
|
||||
} ?: SessionPrefs.upscaler(context))
|
||||
}
|
||||
var gameUpscalerOverride by remember(frameGenProfileKey) {
|
||||
mutableStateOf(frameGenProfileKey?.let { SessionPrefs.hasGameUpscalerOverride(context, it) } ?: false)
|
||||
}
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
DisposableEffect(lifecycleOwner, frameGenProfileKey) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME) {
|
||||
frameGenProfileKey?.let { key ->
|
||||
gameUpscaler = SessionPrefs.screenEffectsUpscaler(context, "game:$key")
|
||||
gameUpscalerOverride = SessionPrefs.hasGameUpscalerOverride(context, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
var wincompOpen by remember(wincompKey) { mutableStateOf<Boolean?>(null) }
|
||||
val wincompPicks = remember(wincompKey, wincompOpen) { wincompKey?.let { com.droiddeck.launcher.session.WinComponents.picks(context, it) }.orEmpty() }
|
||||
val steamScope = game?.let { com.droiddeck.launcher.session.NoSteamLaunch.scope(it) }
|
||||
@@ -914,6 +936,25 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
},
|
||||
)
|
||||
}
|
||||
val scalingFilterMenuContent: @Composable () -> Unit = {
|
||||
val key = frameGenProfileKey
|
||||
if (key != null) ScalingFilterMenu(
|
||||
mode = gameUpscaler,
|
||||
options = scalingFilterChoices,
|
||||
hasGameOverride = gameUpscalerOverride,
|
||||
onPick = { mode ->
|
||||
SessionPrefs.setGameUpscaler(context, key, mode)
|
||||
gameUpscaler = SessionPrefs.screenEffectsUpscaler(context, "game:$key")
|
||||
gameUpscalerOverride = SessionPrefs.hasGameUpscalerOverride(context, key)
|
||||
},
|
||||
onResetGame = {
|
||||
SessionPrefs.clearGameUpscaler(context, key)
|
||||
gameUpscaler = SessionPrefs.upscaler(context)
|
||||
gameUpscalerOverride = false
|
||||
},
|
||||
gameName = game?.name,
|
||||
)
|
||||
}
|
||||
val cards = if (game?.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER) listOfNotNull(steamCard) else buildList<@Composable (Modifier) -> Unit> {
|
||||
add { m ->
|
||||
val back = stringResource(R.string.hop_from_games)
|
||||
@@ -938,6 +979,17 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
|
||||
}
|
||||
}
|
||||
if (frameGenProfileKey != null) add { m ->
|
||||
Box(m) {
|
||||
SettingCard(
|
||||
stringResource(R.string.display_filter),
|
||||
scalingFilterChoices.firstOrNull { it.first == gameUpscaler }?.second ?: scalingFilterChoices.first().second,
|
||||
"card:scaling-filter", Modifier.fillMaxSize(),
|
||||
) {
|
||||
host.open = if (host.open == "scaling-filter") null else "scaling-filter"
|
||||
}
|
||||
}
|
||||
}
|
||||
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
|
||||
if (steamCard != null) add(steamCard)
|
||||
val cardStore = com.droiddeck.launcher.stores.Store.byId(game?.source.orEmpty())?.takeIf { it == com.droiddeck.launcher.stores.Store.EPIC || it == com.droiddeck.launcher.stores.Store.GOG }
|
||||
@@ -972,6 +1024,11 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
frameGenMenuContent()
|
||||
}
|
||||
}
|
||||
if (host.open == "scaling-filter") {
|
||||
Box(Modifier.fillMaxWidth().padding(top = 4.dp)) {
|
||||
scalingFilterMenuContent()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -66,11 +66,9 @@ import androidx.compose.material.icons.filled.ViewModule
|
||||
import androidx.compose.material.icons.filled.Visibility
|
||||
import androidx.compose.material.icons.outlined.Download
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LocalContentColor
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -211,14 +209,11 @@ internal object LibraryDisplay {
|
||||
private set
|
||||
var size by mutableStateOf(false)
|
||||
private set
|
||||
var store by mutableStateOf(true)
|
||||
private set
|
||||
|
||||
fun load(context: android.content.Context) {
|
||||
level = SessionPrefs.libraryCardLevel(context).coerceIn(0, scales.lastIndex)
|
||||
title = SessionPrefs.libraryShowTitle(context)
|
||||
size = SessionPrefs.libraryShowSize(context)
|
||||
store = SessionPrefs.libraryShowStore(context)
|
||||
}
|
||||
|
||||
fun step(context: android.content.Context, by: Int) {
|
||||
@@ -235,16 +230,8 @@ internal object LibraryDisplay {
|
||||
size = !size
|
||||
SessionPrefs.setLibraryShowSize(context, size)
|
||||
}
|
||||
|
||||
fun toggleStore(context: android.content.Context) {
|
||||
store = !store
|
||||
SessionPrefs.setLibraryShowStore(context, store)
|
||||
}
|
||||
}
|
||||
|
||||
/** Views that mix stores, where each card says which store it comes from. */
|
||||
private fun showsSource(source: String) = source == LIBRARY_ALL || source == LIBRARY_FAVORITES || source == LIBRARY_HIDDEN
|
||||
|
||||
private enum class ToggleAt { NONE, TOP, SPLIT, BOTTOM }
|
||||
|
||||
private const val NOT_INSTALLED_ROW = "library-not-installed"
|
||||
@@ -722,7 +709,7 @@ private fun LibraryGrid(
|
||||
enter.animateTo(1f, Motion.tw(320))
|
||||
}
|
||||
Box(Modifier.graphicsLayer { alpha = enter.value; translationY = (1f - enter.value) * 18.dp.toPx() }) {
|
||||
if (listMode) LibraryRow(e, first, navigation, choose, onOpen) else LibraryTile(e, capsules, first, navigation, choose, onOpen, showSource = showsSource(source))
|
||||
if (listMode) LibraryRow(e, first, navigation, choose, onOpen) else LibraryTile(e, capsules, first, navigation, choose, onOpen, showSource = source == LIBRARY_ALL || source == LIBRARY_FAVORITES || source == LIBRARY_HIDDEN)
|
||||
}
|
||||
}
|
||||
var rowFocused by remember { mutableStateOf(false) }
|
||||
@@ -910,7 +897,7 @@ private fun LibraryHeader(
|
||||
}
|
||||
if (soundMode) HeaderIconButton(stringResource(R.string.soundtracks_saved), Icons.Filled.BookmarkBorder, "collections", onClick = onCollections)
|
||||
if (!soundMode && DeveloperTools.on && DevPreview.shortcuts) LibraryPreviewButton()
|
||||
DisplayButton(storeOption = !soundMode && showsSource(source))
|
||||
DisplayButton()
|
||||
if (!soundMode && xbox) LibraryFilterButton(null, onShowUninstalled, xbox)
|
||||
if (collections != null) CollectionsButton(collections)
|
||||
SortButton(s, a)
|
||||
@@ -1101,13 +1088,13 @@ private fun LibraryTile(e: LibraryEntry, capsule: Boolean, first: Boolean, navig
|
||||
onOpen(e.key)
|
||||
}
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
modifier = Modifier.fillMaxWidth().onGloballyPositioned { placed[0] = it }
|
||||
.then(navigation).paneItem("card:${e.key}").then(if (first) Modifier.firstTile().paneEntry() else Modifier).graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
.clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line)
|
||||
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = open)
|
||||
.controllerConfirm(onClick = choose ?: open),
|
||||
) {
|
||||
LibraryArt(e, wide, tall, download, hot, capsule, showSource) { placed[0] = it }
|
||||
LibraryArt(e, wide, tall, download, hot, capsule, showSource)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1116,10 +1103,7 @@ internal val LibraryCardWidth = 150.dp
|
||||
internal fun libraryTileWidth() = LibraryCardWidth * LibraryDisplay.scales[LibraryDisplay.level]
|
||||
|
||||
@Composable
|
||||
private fun LibraryArt(
|
||||
e: LibraryEntry, wide: Any?, tall: Any?, download: DownloadEntry?, hot: Boolean, capsule: Boolean, showSource: Boolean,
|
||||
onArtPlaced: (androidx.compose.ui.layout.LayoutCoordinates) -> Unit,
|
||||
) {
|
||||
private fun LibraryArt(e: LibraryEntry, wide: Any?, tall: Any?, download: DownloadEntry?, hot: Boolean, capsule: Boolean, showSource: Boolean) {
|
||||
val chip = when {
|
||||
download != null -> "${(steadyProgress(download) * 100).toInt()}%"
|
||||
e.item != null && StoresState.isUnfinished(e.item) -> stringResource(R.string.stores_resume)
|
||||
@@ -1128,86 +1112,65 @@ private fun LibraryArt(
|
||||
}
|
||||
ArtCard(
|
||||
e.title, wide, tall, download, hot, capsule, chip,
|
||||
banner = if (showSource && LibraryDisplay.store) ({ SourceBanner(e.source, label = favoritesBadge(e), colours = favoritesColours(e)) }) else null,
|
||||
onArtPlaced = onArtPlaced,
|
||||
badge = if (showSource) ({ SourceChip(e.source, small = true, modifier = Modifier.align(Alignment.TopStart).padding(6.dp), label = favoritesBadge(e), colours = favoritesColours(e)) }) else null,
|
||||
) { LibrarySize(e) }
|
||||
}
|
||||
|
||||
/**
|
||||
* A game's art with an optional [banner] above it. The title and [detail] the display options turn on sit in a caption
|
||||
* below the art; a focused card shows the ones that are off over the bottom of the art instead, so its height never changes.
|
||||
*/
|
||||
@Composable
|
||||
internal fun ArtCard(
|
||||
title: String, wide: Any?, tall: Any?, download: DownloadEntry?, hot: Boolean, capsule: Boolean, chip: String?,
|
||||
badge: (@Composable BoxScope.() -> Unit)? = null, banner: (@Composable () -> Unit)? = null,
|
||||
onArtPlaced: (androidx.compose.ui.layout.LayoutCoordinates) -> Unit = {}, detail: @Composable () -> Unit,
|
||||
badge: (@Composable BoxScope.() -> Unit)? = null, detail: @Composable () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val url = if (capsule) tall ?: wide else wide ?: tall
|
||||
val art = cardArtRequest(url, tall)
|
||||
val ratio = if (capsule) 5f / 7f else 16f / 9f
|
||||
var offRatio by remember(url) { mutableStateOf(false) }
|
||||
var trim by remember(url) { mutableStateOf(false) }
|
||||
val blurs = android.os.Build.VERSION.SDK_INT >= 31
|
||||
val captionName = LibraryDisplay.title
|
||||
val captionDetail = LibraryDisplay.size
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
banner?.invoke()
|
||||
Box(
|
||||
Modifier.fillMaxWidth().aspectRatio(ratio).onGloballyPositioned(onArtPlaced).background(Color(0xFF101318))
|
||||
.then(if (url == null) Modifier.background(artBrush(hueOf(title))) else Modifier),
|
||||
) {
|
||||
if (art != null && offRatio) {
|
||||
AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize().blur(32.dp))
|
||||
Spacer(Modifier.matchParentSize().background(Color.Black.copy(alpha = if (blurs) 0.18f else 0.6f)))
|
||||
}
|
||||
if (art != null) AsyncImage(
|
||||
model = art, contentDescription = null, contentScale = if (trim) ContentScale.Crop else ContentScale.Fit, modifier = Modifier.matchParentSize(),
|
||||
onSuccess = { r ->
|
||||
val d = r.result.drawable
|
||||
if (d.intrinsicWidth > 0 && d.intrinsicHeight > 0) {
|
||||
val shape = d.intrinsicWidth.toFloat() / d.intrinsicHeight
|
||||
trim = !capsule && shape > ratio * 1.25f
|
||||
offRatio = !trim && kotlin.math.abs(shape / ratio - 1f) > 0.03f
|
||||
}
|
||||
},
|
||||
)
|
||||
badge?.invoke(this)
|
||||
if (chip != null) Box(Modifier.align(Alignment.TopEnd).padding(6.dp)) {
|
||||
StateChip(chip, ChipTone.BUSY, small = true, fraction = download?.let { steadyProgress(it) }, key = download?.key)
|
||||
}
|
||||
val overlayName = hot && !captionName
|
||||
val overlayDetail = hot && !captionDetail
|
||||
if (overlayName || overlayDetail) {
|
||||
val top = with(androidx.compose.ui.platform.LocalDensity.current) { 20.dp.roundToPx() }
|
||||
val bottom = with(androidx.compose.ui.platform.LocalDensity.current) { (if (download != null) 14.dp else 6.dp).roundToPx() }
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(1.dp),
|
||||
modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth()
|
||||
.background(Brush.verticalGradient(0f to Color.Transparent, 0.6f to Color.Black.copy(alpha = 0.78f), 1f to Color.Black.copy(alpha = 0.92f)))
|
||||
.layout { measurable, constraints ->
|
||||
val inner = measurable.measure(constraints)
|
||||
if (inner.height == 0) layout(inner.width, 0) {} else layout(inner.width, inner.height + top + bottom) { inner.place(0, top) }
|
||||
}
|
||||
.padding(horizontal = 8.dp),
|
||||
) {
|
||||
if (overlayName) Text(title, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 2, overflow = TextOverflow.Ellipsis, lineHeight = 13.sp)
|
||||
if (overlayDetail) CompositionLocalProvider(LocalContentColor provides Color.White) { detail() }
|
||||
Box(
|
||||
Modifier.fillMaxWidth().aspectRatio(ratio).background(Color(0xFF101318))
|
||||
.then(if (url == null) Modifier.background(artBrush(hueOf(title))) else Modifier),
|
||||
) {
|
||||
if (art != null && offRatio) {
|
||||
AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize().blur(32.dp))
|
||||
Spacer(Modifier.matchParentSize().background(Color.Black.copy(alpha = if (blurs) 0.18f else 0.6f)))
|
||||
}
|
||||
if (art != null) AsyncImage(
|
||||
model = art, contentDescription = null, contentScale = if (trim) ContentScale.Crop else ContentScale.Fit, modifier = Modifier.matchParentSize(),
|
||||
onSuccess = { r ->
|
||||
val d = r.result.drawable
|
||||
if (d.intrinsicWidth > 0 && d.intrinsicHeight > 0) {
|
||||
val shape = d.intrinsicWidth.toFloat() / d.intrinsicHeight
|
||||
trim = !capsule && shape > ratio * 1.25f
|
||||
offRatio = !trim && kotlin.math.abs(shape / ratio - 1f) > 0.03f
|
||||
}
|
||||
}
|
||||
if (download != null) Box(Modifier.align(Alignment.BottomCenter).padding(start = 6.dp, end = 6.dp, bottom = 5.dp)) {
|
||||
ProgressBarThin(download.fraction, paused = download.state == DownloadState.PAUSED, verify = download.stage == DownloadStage.VERIFY)
|
||||
},
|
||||
)
|
||||
badge?.invoke(this)
|
||||
if (chip != null) Box(Modifier.align(Alignment.TopEnd).padding(6.dp)) {
|
||||
StateChip(chip, ChipTone.BUSY, small = true, fraction = download?.let { steadyProgress(it) }, key = download?.key)
|
||||
}
|
||||
val showName = LibraryDisplay.title || hot
|
||||
val showDetail = LibraryDisplay.size || hot
|
||||
if (showName || showDetail) {
|
||||
val top = with(androidx.compose.ui.platform.LocalDensity.current) { 20.dp.roundToPx() }
|
||||
val bottom = with(androidx.compose.ui.platform.LocalDensity.current) { (if (download != null) 14.dp else 6.dp).roundToPx() }
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(1.dp),
|
||||
modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth()
|
||||
.background(Brush.verticalGradient(0f to Color.Transparent, 0.6f to Color.Black.copy(alpha = 0.78f), 1f to Color.Black.copy(alpha = 0.92f)))
|
||||
.layout { measurable, constraints ->
|
||||
val inner = measurable.measure(constraints)
|
||||
if (inner.height == 0) layout(inner.width, 0) {} else layout(inner.width, inner.height + top + bottom) { inner.place(0, top) }
|
||||
}
|
||||
.padding(horizontal = 8.dp),
|
||||
) {
|
||||
if (showName) Text(title, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = if (hot) 2 else 1, overflow = TextOverflow.Ellipsis, lineHeight = 13.sp)
|
||||
if (showDetail) detail()
|
||||
}
|
||||
}
|
||||
if (captionName || captionDetail) Column(
|
||||
verticalArrangement = Arrangement.spacedBy(1.dp),
|
||||
modifier = Modifier.fillMaxWidth().background(colors.surface).padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
) {
|
||||
if (captionName) Text(title, fontSize = 12.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, lineHeight = 15.sp)
|
||||
if (captionDetail) Box(Modifier.fillMaxWidth().height(15.dp), contentAlignment = Alignment.CenterStart) {
|
||||
CompositionLocalProvider(LocalContentColor provides colors.onSurfaceVariant) { detail() }
|
||||
}
|
||||
if (download != null) Box(Modifier.align(Alignment.BottomCenter).padding(start = 6.dp, end = 6.dp, bottom = 5.dp)) {
|
||||
ProgressBarThin(download.fraction, paused = download.state == DownloadState.PAUSED, verify = download.stage == DownloadStage.VERIFY)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1234,7 +1197,7 @@ private fun librarySize(e: LibraryEntry): Long? = if (e.installed) e.storeKey?.l
|
||||
@Composable
|
||||
private fun LibrarySize(e: LibraryEntry) {
|
||||
val size = librarySize(e)?.takeIf { it > 0 } ?: return
|
||||
Text(formatBytes(size), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = LocalContentColor.current, maxLines = 1)
|
||||
Text(formatBytes(size), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1)
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -1428,7 +1391,7 @@ private fun CollectionsButton(store: Store) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun DisplayButton(storeOption: Boolean = false) {
|
||||
internal fun DisplayButton() {
|
||||
val pal = LocalPalette.current
|
||||
val ctx = LocalContext.current
|
||||
val title = stringResource(R.string.library_display)
|
||||
@@ -1437,7 +1400,7 @@ internal fun DisplayButton(storeOption: Boolean = false) {
|
||||
HeaderIconButton(title, Icons.Filled.Visibility, "display") {
|
||||
val from = at ?: return@HeaderIconButton
|
||||
Steps.ask(StepAsk(
|
||||
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = if (storeOption) 5 else 4,
|
||||
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = 4,
|
||||
handle = { Icon(Icons.Filled.Visibility, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
|
||||
) {
|
||||
StepTitle(title)
|
||||
@@ -1460,10 +1423,6 @@ internal fun DisplayButton(storeOption: Boolean = false) {
|
||||
stringResource(R.string.library_display_size), selected = LibraryDisplay.size, enabled = open,
|
||||
modifier = Modifier.fillMaxWidth().stepItem(3),
|
||||
) { LibraryDisplay.toggleSize(ctx) }
|
||||
if (storeOption) StepChoice(
|
||||
stringResource(R.string.library_display_store), selected = LibraryDisplay.store, enabled = open,
|
||||
modifier = Modifier.fillMaxWidth().stepItem(4),
|
||||
) { LibraryDisplay.toggleStore(ctx) }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
@Composable
|
||||
internal fun ScalingFilterMenu(
|
||||
mode: Int,
|
||||
options: List<Pair<Int, String>>,
|
||||
hasGameOverride: Boolean,
|
||||
onPick: (Int) -> Unit,
|
||||
onResetGame: () -> Unit,
|
||||
gameName: String? = null,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, bottom = 8.dp)) {
|
||||
val selectedLabel = options.firstOrNull { it.first == mode }?.second ?: mode.toString()
|
||||
Text(
|
||||
stringResource(
|
||||
if (hasGameOverride) R.string.display_filter_game_profile else R.string.display_filter_default_profile,
|
||||
if (hasGameOverride) gameName.orEmpty() else selectedLabel,
|
||||
selectedLabel,
|
||||
),
|
||||
color = colors.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.padding(bottom = 6.dp),
|
||||
)
|
||||
options.forEachIndexed { index, (option, label) ->
|
||||
val selected = mode == option
|
||||
val pick = { onPick(option) }
|
||||
OutlinedButton(
|
||||
onClick = pick,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
.padding(top = if (index == 0) 0.dp else 6.dp)
|
||||
.controllerConfirm(onClick = pick),
|
||||
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
|
||||
colors = ButtonDefaults.outlinedButtonColors(
|
||||
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
|
||||
contentColor = if (selected) colors.primary else colors.onSurface,
|
||||
),
|
||||
) { Text(label) }
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.display_filter_note),
|
||||
color = colors.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.padding(top = 6.dp),
|
||||
)
|
||||
OutlinedButton(
|
||||
onClick = onResetGame,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
|
||||
.controllerConfirm(onClick = onResetGame),
|
||||
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@ import androidx.compose.ui.input.key.key
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.layout.LayoutCoordinates
|
||||
import androidx.compose.ui.unit.Constraints
|
||||
import androidx.compose.ui.layout.Layout
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalLayoutDirection
|
||||
@@ -75,6 +77,7 @@ import androidx.compose.foundation.interaction.PressInteraction
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
@@ -666,6 +669,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
val track: (String) -> Modifier = { key -> focus.track(page, key) }
|
||||
val sections = remember(page) { DrawerSections(drawerContext, track) }
|
||||
CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true, LocalDrawerSections provides sections) {
|
||||
DrawerColumns(two = sheetWidth >= DRAWER_TWO_COLUMN_WIDTH && page.inColumns) {
|
||||
when (page) {
|
||||
SessionDrawerPage.CONTROLLER -> DrawerControllerPage(host, a, a.controllerConnected || controllerActive, track)
|
||||
SessionDrawerPage.HUD -> DrawerPerformancePage(host, a, track)
|
||||
@@ -682,6 +686,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
SessionDrawerPage.ACHIEVEMENTS -> a.achievementsGame?.let { DrawerAchievementsPage(it, a.achievementsTitle, track) }
|
||||
SessionDrawerPage.AGENT -> Unit
|
||||
}
|
||||
}
|
||||
} }
|
||||
}
|
||||
}
|
||||
@@ -1557,6 +1562,44 @@ internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boole
|
||||
|
||||
private val DRAWER_MIN_WIDTH = 300.dp
|
||||
private val DRAWER_HANDLE_STRIP = 24.dp
|
||||
private val DRAWER_COLUMN_GAP = 10.dp
|
||||
// Two columns once each would be as wide as the narrowest single-column sheet.
|
||||
private val DRAWER_TWO_COLUMN_WIDTH = DRAWER_MIN_WIDTH * 2 + DRAWER_COLUMN_GAP
|
||||
|
||||
private val SessionDrawerPage.inColumns: Boolean
|
||||
get() = this != SessionDrawerPage.MORE && this != SessionDrawerPage.ACHIEVEMENTS
|
||||
|
||||
/**
|
||||
* On a wide sheet, lays a page's groups out in two columns, the first half on the left. The split is by count, not
|
||||
* height, so a group keeps its column while others fold and unfold.
|
||||
*/
|
||||
@Composable
|
||||
internal fun DrawerColumns(two: Boolean, content: @Composable () -> Unit) {
|
||||
// Keep a single composition so resizing only remeasures existing children.
|
||||
Layout(content, Modifier.fillMaxWidth()) { measurables, constraints ->
|
||||
val width = constraints.maxWidth
|
||||
if (!two || measurables.size < 2) {
|
||||
val placeables = measurables.map { it.measure(constraints.copy(minWidth = 0, minHeight = 0)) }
|
||||
return@Layout layout(width, placeables.sumOf { it.height }) {
|
||||
var y = 0
|
||||
placeables.forEach { it.placeRelative(0, y); y += it.height }
|
||||
}
|
||||
}
|
||||
val gap = DRAWER_COLUMN_GAP.roundToPx()
|
||||
val column = ((width - gap) / 2).coerceAtLeast(0)
|
||||
val child = Constraints(maxWidth = column)
|
||||
val placeables = measurables.map { it.measure(child) }
|
||||
val half = (placeables.size + 1) / 2
|
||||
val left = placeables.take(half)
|
||||
val right = placeables.drop(half)
|
||||
layout(width, maxOf(left.sumOf { it.height }, right.sumOf { it.height })) {
|
||||
var y = 0
|
||||
left.forEach { it.placeRelative(0, y); y += it.height }
|
||||
y = 0
|
||||
right.forEach { it.placeRelative(column + gap, y); y += it.height }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A grip on the sheet's left edge: dragging it, or pressing left and right on a controller, resizes the sheet. */
|
||||
@Composable
|
||||
@@ -1893,7 +1936,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
||||
}
|
||||
return
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components") {
|
||||
DrawerComponentSettingsGroup(stringResource(R.string.drawer_game_components_note, gameProfile.name)) {
|
||||
DrawerStackedChoice(
|
||||
host = host,
|
||||
key = "game-cmp-proton",
|
||||
@@ -1936,12 +1979,6 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.drawer_game_components_note, gameProfile.name),
|
||||
fontSize = 12.sp,
|
||||
color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp),
|
||||
)
|
||||
return
|
||||
}
|
||||
val running = snap.protons.filter { it.inUseByGame }
|
||||
@@ -1982,7 +2019,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
||||
return
|
||||
}
|
||||
val p = view.proton
|
||||
SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components") {
|
||||
DrawerComponentSettingsGroup(stringResource(R.string.drawer_components_note)) {
|
||||
DrawerStackedChoice(
|
||||
host, "cmp-proton", stringResource(R.string.comp_proton),
|
||||
listOfNotNull(
|
||||
@@ -2018,10 +2055,16 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.drawer_components_note),
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun DrawerComponentSettingsGroup(note: String, content: @Composable ColumnScope.() -> Unit) {
|
||||
// The note stays visible when collapsed, but both belong to one drawer column item.
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components", content = content)
|
||||
Text(note, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -2,20 +2,16 @@ package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
@@ -77,18 +73,6 @@ internal fun SourceChip(source: String, small: Boolean = false, modifier: Modifi
|
||||
)
|
||||
}
|
||||
|
||||
/** The store a card comes from, as a full-width band above its art. */
|
||||
@Composable
|
||||
internal fun SourceBanner(source: String, modifier: Modifier = Modifier, label: String? = null, colours: SourceColours? = null) {
|
||||
val c = colours ?: sourceColours(source)
|
||||
Box(modifier.fillMaxWidth().heightIn(min = 20.dp).background(c.fill).padding(horizontal = 8.dp, vertical = 3.dp), contentAlignment = Alignment.CenterStart) {
|
||||
Text(
|
||||
label ?: sourceLabel(source), fontSize = 10.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.5.sp, lineHeight = 12.sp,
|
||||
color = c.ink, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun StateChip(text: String, tone: ChipTone, small: Boolean = false, fraction: Float? = null, key: Any? = null) {
|
||||
val pal = LocalPalette.current
|
||||
|
||||
@@ -1190,6 +1190,7 @@ private fun GameCard(
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
.onGloballyPositioned { c ->
|
||||
placed[0] = c
|
||||
if (item.accessible && item.sizeBytes <= 0) {
|
||||
val b = c.boundsInWindow()
|
||||
if (b.bottom > -ahead && b.top < screen + ahead && b.width > 0f) com.droiddeck.launcher.stores.StoreSizes.request(ctx, item)
|
||||
@@ -1208,10 +1209,10 @@ private fun GameCard(
|
||||
val priced = installed || item.isFree || item.isDiscounted || item.hasPrice
|
||||
val pill: (@Composable BoxScope.() -> Unit)? = if (priced && !LibraryDisplay.size && !hot) ({
|
||||
Box(Modifier.align(Alignment.TopStart).padding(6.dp).clip(RoundedCornerShape(6.dp)).background(Color.Black.copy(alpha = 0.82f)).padding(horizontal = 6.dp, vertical = 2.dp)) {
|
||||
CompositionLocalProvider(androidx.compose.material3.LocalContentColor provides Color.White) { CardMarker(item, installed, download, compact = true, status = false) }
|
||||
CardMarker(item, installed, download, compact = true, status = false)
|
||||
}
|
||||
}) else null
|
||||
ArtCard(item.title, item.imageUrl, item.tallImageUrl, download, hot, capsule = false, chip = chip, badge = pill, onArtPlaced = { placed[0] = it }) { CardMarker(item, installed, download, status = false) }
|
||||
ArtCard(item.title, item.imageUrl, item.tallImageUrl, download, hot, capsule = false, chip = chip, badge = pill) { CardMarker(item, installed, download, status = false) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1255,19 +1256,19 @@ private fun CardMarker(item: CatalogItem, installed: Boolean, download: com.droi
|
||||
val ctx = LocalContext.current
|
||||
val game = StoresState.installedGame(item.store, item.id)
|
||||
if (game != null && !compact) androidx.compose.runtime.LaunchedEffect(item.key) { com.droiddeck.launcher.stores.StoreSizes.requestDisk(ctx, item.key, game) }
|
||||
if (!compact) com.droiddeck.launcher.stores.StoreSizes.onDisk[item.key]?.let { Text(formatBytes(it), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = androidx.compose.material3.LocalContentColor.current, maxLines = 1) }
|
||||
if (!compact) com.droiddeck.launcher.stores.StoreSizes.onDisk[item.key]?.let { Text(formatBytes(it), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1) }
|
||||
Icon(Icons.Filled.Check, stringResource(R.string.stores_installed_chip), tint = pal.good, modifier = Modifier.size(11.dp))
|
||||
}
|
||||
status && download != null -> Text("${download.percent}%", fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
status && item.accessible && StoresState.isUnfinished(item) -> Text(stringResource(R.string.stores_resume), fontSize = small, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
item.accessible && compact -> Unit
|
||||
item.accessible -> com.droiddeck.launcher.stores.StoreSizes.size(item).takeIf { it > 0 }?.let { Text(formatBytes(it), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = androidx.compose.material3.LocalContentColor.current, maxLines = 1) }
|
||||
item.accessible -> com.droiddeck.launcher.stores.StoreSizes.size(item).takeIf { it > 0 }?.let { Text(formatBytes(it), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1) }
|
||||
item.isFree -> Text(stringResource(R.string.stores_free), fontSize = small, fontWeight = FontWeight.Bold, color = pal.good, maxLines = 1)
|
||||
item.isDiscounted -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
StateChip("-${item.discountPercent}%", ChipTone.DEAL, small = true)
|
||||
Text(item.finalPrice, fontSize = small, fontWeight = FontWeight.Bold, color = androidx.compose.material3.LocalContentColor.current, maxLines = 1)
|
||||
Text(item.finalPrice, fontSize = small, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1)
|
||||
}
|
||||
item.hasPrice -> Text(item.finalPrice, fontSize = small, fontWeight = FontWeight.Bold, color = androidx.compose.material3.LocalContentColor.current, maxLines = 1)
|
||||
item.hasPrice -> Text(item.finalPrice, fontSize = small, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -706,7 +706,8 @@ private fun TestList(tests: List<Release>, me: AppUpdates.Installed, u: UpdatesS
|
||||
val followed = u.follow.pr.takeIf { u.follow.channel == Channel.TEST }
|
||||
val rowShown = followed != null && (ready.any { it.pr == followed } || (oldShown && old.any { it.pr == followed }))
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
if (!rowShown) status(false)
|
||||
// A followed test's row carries the status; browsing Tests while following Stable or Preview shows it only for an install running or failed.
|
||||
if (if (followed != null) !rowShown else u.stage != null || u.error != null) status(false)
|
||||
Column(Modifier.padding(start = 18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
if (tests.size > 5 || query.isNotEmpty()) AdbTextField(
|
||||
value = query, onValueChange = { query = it }, label = stringResource(R.string.upd_tests_find),
|
||||
|
||||
@@ -333,6 +333,8 @@ public final class WaylandCompositor {
|
||||
|
||||
public static native void nativeSetZeroCopy(boolean on);
|
||||
|
||||
public static native void nativeSetMirrorCapture(boolean on);
|
||||
|
||||
public static native void nativeSetDisplayBufferDriver(boolean on);
|
||||
|
||||
public static native int nativeZeroCopyFrames();
|
||||
|
||||
@@ -1180,6 +1180,11 @@
|
||||
<string name="agent_tools_missing">أدوات الوكيل غير مثبتة: %1$s</string>
|
||||
<string name="agent_unqueue">لا تُرسل</string>
|
||||
<string name="agent_attach">إرفاق</string>
|
||||
<string name="agent_attach_files">الملفات</string>
|
||||
<string name="agent_photos_allow">السماح بالوصول إلى الصور</string>
|
||||
<string name="agent_photos_more">اختيار المزيد من الصور</string>
|
||||
<string name="agent_photos_empty">لا توجد صور بعد</string>
|
||||
<string name="agent_keyboard">لوحة المفاتيح</string>
|
||||
<string name="agent_remove_attachment">إزالة</string>
|
||||
<string name="agent_model_default">الافتراضي</string>
|
||||
<string name="agent_effort">جهد الاستدلال</string>
|
||||
@@ -2732,7 +2737,6 @@
|
||||
<string name="library_display_smaller">بطاقات أصغر</string>
|
||||
<string name="library_display_title">إظهار العنوان</string>
|
||||
<string name="library_display_size">إظهار الحجم</string>
|
||||
<string name="library_display_store">إظهار المتجر</string>
|
||||
<string name="stores_sort_last_played">لُعب مؤخرًا</string>
|
||||
<string name="stores_sort_recently_installed">ثُبت مؤخرًا</string>
|
||||
<string name="stores_sort_title_asc">العنوان أ–ي</string>
|
||||
@@ -4326,4 +4330,6 @@
|
||||
<string name="glasses_shortcut_group">اختصار داخل اللعبة</string>
|
||||
<string name="glasses_show_shortcut">إظهار اختصار النظارات الذكية</string>
|
||||
<string name="glasses_show_shortcut_hint">إظهار زر النظارات الذكية العائم فوق اللعبة.</string>
|
||||
<string name="display_filter_game_profile">استخدام ملف تعريف %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">استخدام الملف التعريفي الافتراضي: %1$s</string>
|
||||
</resources>
|
||||
@@ -1198,6 +1198,11 @@
|
||||
<string name="agent_tools_missing">Herramientas del agente sin instalar: %1$s</string>
|
||||
<string name="agent_unqueue">No enviar</string>
|
||||
<string name="agent_attach">Adjuntar</string>
|
||||
<string name="agent_attach_files">Archivos</string>
|
||||
<string name="agent_photos_allow">Permitir acceso a fotos</string>
|
||||
<string name="agent_photos_more">Elegir más fotos</string>
|
||||
<string name="agent_photos_empty">Aún no hay fotos</string>
|
||||
<string name="agent_keyboard">Teclado</string>
|
||||
<string name="agent_remove_attachment">Quitar</string>
|
||||
<string name="agent_model_default">Predeterminado</string>
|
||||
<string name="agent_effort">Esfuerzo de razonamiento</string>
|
||||
@@ -2690,7 +2695,6 @@
|
||||
<string name="library_display_smaller">Tarjetas más pequeñas</string>
|
||||
<string name="library_display_title">Mostrar título</string>
|
||||
<string name="library_display_size">Mostrar tamaño</string>
|
||||
<string name="library_display_store">Mostrar tienda</string>
|
||||
<string name="stores_sort_last_played">Jugados recientemente</string>
|
||||
<string name="stores_sort_recently_installed">Instalados recientemente</string>
|
||||
<string name="stores_sort_title_asc">Título A–Z</string>
|
||||
@@ -4204,4 +4208,6 @@
|
||||
<string name="glasses_shortcut_group">Acceso directo en el juego</string>
|
||||
<string name="glasses_show_shortcut">Mostrar acceso directo de Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Mostrar el botón flotante de Smart Glasses sobre el juego.</string>
|
||||
<string name="display_filter_game_profile">Usando el perfil %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Usando el perfil predeterminado: %1$s</string>
|
||||
</resources>
|
||||
@@ -1168,6 +1168,11 @@
|
||||
<string name="agent_tools_missing">Инструментите на агента не са инсталирани: %1$s</string>
|
||||
<string name="agent_unqueue">Не изпращай</string>
|
||||
<string name="agent_attach">Прикачи</string>
|
||||
<string name="agent_attach_files">Файлове</string>
|
||||
<string name="agent_photos_allow">Разрешаване на достъп до снимки</string>
|
||||
<string name="agent_photos_more">Избор на още снимки</string>
|
||||
<string name="agent_photos_empty">Все още няма снимки</string>
|
||||
<string name="agent_keyboard">Клавиатура</string>
|
||||
<string name="agent_remove_attachment">Премахни</string>
|
||||
<string name="agent_model_default">По подразбиране</string>
|
||||
<string name="agent_effort">Усилие за разсъждение</string>
|
||||
@@ -2628,7 +2633,6 @@
|
||||
<string name="library_display_smaller">По-малки карти</string>
|
||||
<string name="library_display_title">Показване на заглавието</string>
|
||||
<string name="library_display_size">Показване на размера</string>
|
||||
<string name="library_display_store">Показване на магазина</string>
|
||||
<string name="stores_sort_last_played">Играни наскоро</string>
|
||||
<string name="stores_sort_recently_installed">Инсталирани наскоро</string>
|
||||
<string name="stores_sort_title_asc">Заглавие А–Я</string>
|
||||
@@ -4166,4 +4170,6 @@
|
||||
<string name="glasses_shortcut_group">Пряк път в играта</string>
|
||||
<string name="glasses_show_shortcut">Показване на прекия път за Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Показва плаващия бутон за Smart Glasses върху играта.</string>
|
||||
<string name="display_filter_game_profile">Използва се профил %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Използва се профилът по подразбиране: %1$s</string>
|
||||
</resources>
|
||||
@@ -1174,6 +1174,11 @@
|
||||
<string name="agent_tools_missing">Nástroje agenta nejsou nainstalované: %1$s</string>
|
||||
<string name="agent_unqueue">Neposílat</string>
|
||||
<string name="agent_attach">Přiložit</string>
|
||||
<string name="agent_attach_files">Soubory</string>
|
||||
<string name="agent_photos_allow">Povolit přístup k fotkám</string>
|
||||
<string name="agent_photos_more">Vybrat další fotky</string>
|
||||
<string name="agent_photos_empty">Zatím žádné fotky</string>
|
||||
<string name="agent_keyboard">Klávesnice</string>
|
||||
<string name="agent_remove_attachment">Odebrat</string>
|
||||
<string name="agent_model_default">Výchozí</string>
|
||||
<string name="agent_effort">Náročnost uvažování</string>
|
||||
@@ -2680,7 +2685,6 @@
|
||||
<string name="library_display_smaller">Menší karty</string>
|
||||
<string name="library_display_title">Zobrazit název</string>
|
||||
<string name="library_display_size">Zobrazit velikost</string>
|
||||
<string name="library_display_store">Zobrazit obchod</string>
|
||||
<string name="stores_sort_last_played">Nedávno hrané</string>
|
||||
<string name="stores_sort_recently_installed">Nedávno nainstalované</string>
|
||||
<string name="stores_sort_title_asc">Název A–Z</string>
|
||||
@@ -4246,4 +4250,6 @@
|
||||
<string name="glasses_shortcut_group">Zkratka ve hře</string>
|
||||
<string name="glasses_show_shortcut">Zobrazit zkratku Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Zobrazit plovoucí tlačítko Smart Glasses nad hrou.</string>
|
||||
<string name="display_filter_game_profile">Používá se profil %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Používá se výchozí profil: %1$s</string>
|
||||
</resources>
|
||||
@@ -1168,6 +1168,11 @@
|
||||
<string name="agent_tools_missing">Agentens værktøjer er ikke installeret: %1$s</string>
|
||||
<string name="agent_unqueue">Send ikke</string>
|
||||
<string name="agent_attach">Vedhæft</string>
|
||||
<string name="agent_attach_files">Filer</string>
|
||||
<string name="agent_photos_allow">Tillad adgang til billeder</string>
|
||||
<string name="agent_photos_more">Vælg flere billeder</string>
|
||||
<string name="agent_photos_empty">Ingen billeder endnu</string>
|
||||
<string name="agent_keyboard">Tastatur</string>
|
||||
<string name="agent_remove_attachment">Fjern</string>
|
||||
<string name="agent_model_default">Standard</string>
|
||||
<string name="agent_effort">Ræsonneringsindsats</string>
|
||||
@@ -2628,7 +2633,6 @@
|
||||
<string name="library_display_smaller">Mindre kort</string>
|
||||
<string name="library_display_title">Vis titel</string>
|
||||
<string name="library_display_size">Vis størrelse</string>
|
||||
<string name="library_display_store">Vis butik</string>
|
||||
<string name="stores_sort_last_played">Senest spillet</string>
|
||||
<string name="stores_sort_recently_installed">Senest installeret</string>
|
||||
<string name="stores_sort_title_asc">Titel A–Å</string>
|
||||
@@ -4166,4 +4170,6 @@
|
||||
<string name="glasses_shortcut_group">Genvej i spillet</string>
|
||||
<string name="glasses_show_shortcut">Vis Smart Glasses-genvej</string>
|
||||
<string name="glasses_show_shortcut_hint">Vis den flydende Smart Glasses-knap oven på spillet.</string>
|
||||
<string name="display_filter_game_profile">Bruger profilen %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Bruger standardprofilen: %1$s</string>
|
||||
</resources>
|
||||
@@ -1160,6 +1160,11 @@
|
||||
<string name="agent_tools_missing">Agent-Werkzeuge nicht installiert: %1$s</string>
|
||||
<string name="agent_unqueue">Nicht senden</string>
|
||||
<string name="agent_attach">Anhängen</string>
|
||||
<string name="agent_attach_files">Dateien</string>
|
||||
<string name="agent_photos_allow">Zugriff auf Fotos erlauben</string>
|
||||
<string name="agent_photos_more">Weitere Fotos auswählen</string>
|
||||
<string name="agent_photos_empty">Noch keine Fotos</string>
|
||||
<string name="agent_keyboard">Tastatur</string>
|
||||
<string name="agent_remove_attachment">Entfernen</string>
|
||||
<string name="agent_model_default">Standard</string>
|
||||
<string name="agent_effort">Denkaufwand</string>
|
||||
@@ -2620,7 +2625,6 @@
|
||||
<string name="library_display_smaller">Kleinere Karten</string>
|
||||
<string name="library_display_title">Titel anzeigen</string>
|
||||
<string name="library_display_size">Größe anzeigen</string>
|
||||
<string name="library_display_store">Store anzeigen</string>
|
||||
<string name="stores_sort_last_played">Zuletzt gespielt</string>
|
||||
<string name="stores_sort_recently_installed">Zuletzt installiert</string>
|
||||
<string name="stores_sort_title_asc">Titel A–Z</string>
|
||||
@@ -4166,4 +4170,6 @@
|
||||
<string name="glasses_shortcut_group">Ingame-Verknüpfung</string>
|
||||
<string name="glasses_show_shortcut">Smart-Glasses-Verknüpfung anzeigen</string>
|
||||
<string name="glasses_show_shortcut_hint">Die schwebende Smart-Glasses-Schaltfläche über dem Spiel anzeigen.</string>
|
||||
<string name="display_filter_game_profile">Profil %1$s wird verwendet: %2$s</string>
|
||||
<string name="display_filter_default_profile">Standardprofil wird verwendet: %1$s</string>
|
||||
</resources>
|
||||
@@ -1168,6 +1168,11 @@
|
||||
<string name="agent_tools_missing">Τα εργαλεία του πράκτορα δεν εγκαταστάθηκαν: %1$s</string>
|
||||
<string name="agent_unqueue">Να μην σταλεί</string>
|
||||
<string name="agent_attach">Επισύναψη</string>
|
||||
<string name="agent_attach_files">Αρχεία</string>
|
||||
<string name="agent_photos_allow">Να επιτρέπεται η πρόσβαση στις φωτογραφίες</string>
|
||||
<string name="agent_photos_more">Επιλογή περισσότερων φωτογραφιών</string>
|
||||
<string name="agent_photos_empty">Δεν υπάρχουν φωτογραφίες ακόμα</string>
|
||||
<string name="agent_keyboard">Πληκτρολόγιο</string>
|
||||
<string name="agent_remove_attachment">Αφαίρεση</string>
|
||||
<string name="agent_model_default">Προεπιλογή</string>
|
||||
<string name="agent_effort">Προσπάθεια συλλογισμού</string>
|
||||
@@ -2628,7 +2633,6 @@
|
||||
<string name="library_display_smaller">Μικρότερες κάρτες</string>
|
||||
<string name="library_display_title">Εμφάνιση τίτλου</string>
|
||||
<string name="library_display_size">Εμφάνιση μεγέθους</string>
|
||||
<string name="library_display_store">Εμφάνιση καταστήματος</string>
|
||||
<string name="stores_sort_last_played">Παίχτηκαν πρόσφατα</string>
|
||||
<string name="stores_sort_recently_installed">Εγκαταστήθηκαν πρόσφατα</string>
|
||||
<string name="stores_sort_title_asc">Τίτλος Α–Ω</string>
|
||||
@@ -4166,4 +4170,6 @@
|
||||
<string name="glasses_shortcut_group">Συντόμευση μέσα στο παιχνίδι</string>
|
||||
<string name="glasses_show_shortcut">Εμφάνιση συντόμευσης Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Εμφάνιση του αιωρούμενου κουμπιού Smart Glasses πάνω από το παιχνίδι.</string>
|
||||
<string name="display_filter_game_profile">Χρήση προφίλ %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Χρήση προεπιλεγμένου προφίλ: %1$s</string>
|
||||
</resources>
|
||||
@@ -1171,6 +1171,11 @@
|
||||
<string name="agent_tools_missing">Herramientas del agente sin instalar: %1$s</string>
|
||||
<string name="agent_unqueue">No enviar</string>
|
||||
<string name="agent_attach">Adjuntar</string>
|
||||
<string name="agent_attach_files">Archivos</string>
|
||||
<string name="agent_photos_allow">Permitir acceso a las fotos</string>
|
||||
<string name="agent_photos_more">Elegir más fotos</string>
|
||||
<string name="agent_photos_empty">Aún no hay fotos</string>
|
||||
<string name="agent_keyboard">Teclado</string>
|
||||
<string name="agent_remove_attachment">Quitar</string>
|
||||
<string name="agent_model_default">Predeterminado</string>
|
||||
<string name="agent_effort">Esfuerzo de razonamiento</string>
|
||||
@@ -2654,7 +2659,6 @@
|
||||
<string name="library_display_smaller">Tarjetas más pequeñas</string>
|
||||
<string name="library_display_title">Mostrar título</string>
|
||||
<string name="library_display_size">Mostrar tamaño</string>
|
||||
<string name="library_display_store">Mostrar tienda</string>
|
||||
<string name="stores_sort_last_played">Jugados recientemente</string>
|
||||
<string name="stores_sort_recently_installed">Instalados recientemente</string>
|
||||
<string name="stores_sort_title_asc">Título A–Z</string>
|
||||
@@ -4206,4 +4210,6 @@
|
||||
<string name="glasses_shortcut_group">Acceso directo en el juego</string>
|
||||
<string name="glasses_show_shortcut">Mostrar acceso directo de Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Mostrar el botón flotante de Smart Glasses sobre el juego.</string>
|
||||
<string name="display_filter_game_profile">Usando el perfil %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Usando el perfil predeterminado: %1$s</string>
|
||||
</resources>
|
||||
@@ -1168,6 +1168,11 @@
|
||||
<string name="agent_tools_missing">Agentin työkaluja ei ole asennettu: %1$s</string>
|
||||
<string name="agent_unqueue">Älä lähetä</string>
|
||||
<string name="agent_attach">Liitä</string>
|
||||
<string name="agent_attach_files">Tiedostot</string>
|
||||
<string name="agent_photos_allow">Salli kuvien käyttö</string>
|
||||
<string name="agent_photos_more">Valitse lisää kuvia</string>
|
||||
<string name="agent_photos_empty">Ei vielä kuvia</string>
|
||||
<string name="agent_keyboard">Näppäimistö</string>
|
||||
<string name="agent_remove_attachment">Poista</string>
|
||||
<string name="agent_model_default">Oletus</string>
|
||||
<string name="agent_effort">Päättelyteho</string>
|
||||
@@ -2628,7 +2633,6 @@
|
||||
<string name="library_display_smaller">Pienemmät kortit</string>
|
||||
<string name="library_display_title">Näytä nimi</string>
|
||||
<string name="library_display_size">Näytä koko</string>
|
||||
<string name="library_display_store">Näytä kauppa</string>
|
||||
<string name="stores_sort_last_played">Viimeksi pelatut</string>
|
||||
<string name="stores_sort_recently_installed">Viimeksi asennetut</string>
|
||||
<string name="stores_sort_title_asc">Nimi A–Ö</string>
|
||||
@@ -4166,4 +4170,6 @@
|
||||
<string name="glasses_shortcut_group">Pelin aikainen pikakuvake</string>
|
||||
<string name="glasses_show_shortcut">Näytä Smart Glasses -pikakuvake</string>
|
||||
<string name="glasses_show_shortcut_hint">Näytä pelin päällä kelluva Smart Glasses -painike.</string>
|
||||
<string name="display_filter_game_profile">Käytössä profiili %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Käytössä oletusprofiili: %1$s</string>
|
||||
</resources>
|
||||
@@ -1171,6 +1171,11 @@
|
||||
<string name="agent_tools_missing">Outils de l’agent non installés : %1$s</string>
|
||||
<string name="agent_unqueue">Ne pas envoyer</string>
|
||||
<string name="agent_attach">Joindre</string>
|
||||
<string name="agent_attach_files">Fichiers</string>
|
||||
<string name="agent_photos_allow">Autoriser l\'accès aux photos</string>
|
||||
<string name="agent_photos_more">Choisir d\'autres photos</string>
|
||||
<string name="agent_photos_empty">Aucune photo pour l\'instant</string>
|
||||
<string name="agent_keyboard">Clavier</string>
|
||||
<string name="agent_remove_attachment">Supprimer</string>
|
||||
<string name="agent_model_default">Par défaut</string>
|
||||
<string name="agent_effort">Effort de raisonnement</string>
|
||||
@@ -2653,7 +2658,6 @@
|
||||
<string name="library_display_smaller">Cartes plus petites</string>
|
||||
<string name="library_display_title">Afficher le titre</string>
|
||||
<string name="library_display_size">Afficher la taille</string>
|
||||
<string name="library_display_store">Afficher la boutique</string>
|
||||
<string name="stores_sort_last_played">Joués récemment</string>
|
||||
<string name="stores_sort_recently_installed">Installés récemment</string>
|
||||
<string name="stores_sort_title_asc">Titre A–Z</string>
|
||||
@@ -4205,4 +4209,6 @@
|
||||
<string name="glasses_shortcut_group">Raccourci en jeu</string>
|
||||
<string name="glasses_show_shortcut">Afficher le raccourci Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Afficher le bouton flottant Smart Glasses par-dessus le jeu.</string>
|
||||
<string name="display_filter_game_profile">Profil %1$s utilisé : %2$s</string>
|
||||
<string name="display_filter_default_profile">Profil par défaut utilisé : %1$s</string>
|
||||
</resources>
|
||||
@@ -1168,6 +1168,11 @@
|
||||
<string name="agent_tools_missing">एजेंट टूल इंस्टॉल नहीं हुए: %1$s</string>
|
||||
<string name="agent_unqueue">न भेजें</string>
|
||||
<string name="agent_attach">संलग्न करें</string>
|
||||
<string name="agent_attach_files">फ़ाइलें</string>
|
||||
<string name="agent_photos_allow">फ़ोटो की अनुमति दें</string>
|
||||
<string name="agent_photos_more">और फ़ोटो चुनें</string>
|
||||
<string name="agent_photos_empty">अभी कोई फ़ोटो नहीं</string>
|
||||
<string name="agent_keyboard">कीबोर्ड</string>
|
||||
<string name="agent_remove_attachment">हटाएँ</string>
|
||||
<string name="agent_model_default">डिफ़ॉल्ट</string>
|
||||
<string name="agent_effort">सोचने का स्तर</string>
|
||||
@@ -2628,7 +2633,6 @@
|
||||
<string name="library_display_smaller">छोटे कार्ड</string>
|
||||
<string name="library_display_title">टाइटल दिखाएं</string>
|
||||
<string name="library_display_size">साइज़ दिखाएं</string>
|
||||
<string name="library_display_store">स्टोर दिखाएं</string>
|
||||
<string name="stores_sort_last_played">हाल में खेले गए</string>
|
||||
<string name="stores_sort_recently_installed">हाल में इंस्टॉल किए गए</string>
|
||||
<string name="stores_sort_title_asc">शीर्षक A–Z</string>
|
||||
@@ -4166,4 +4170,6 @@
|
||||
<string name="glasses_shortcut_group">गेम में शॉर्टकट</string>
|
||||
<string name="glasses_show_shortcut">Smart Glasses शॉर्टकट दिखाएँ</string>
|
||||
<string name="glasses_show_shortcut_hint">गेम के ऊपर तैरता हुआ Smart Glasses बटन दिखाएँ।</string>
|
||||
<string name="display_filter_game_profile">%1$s प्रोफ़ाइल का उपयोग: %2$s</string>
|
||||
<string name="display_filter_default_profile">डिफ़ॉल्ट प्रोफ़ाइल का उपयोग: %1$s</string>
|
||||
</resources>
|
||||
@@ -1168,6 +1168,11 @@
|
||||
<string name="agent_tools_missing">Az ügynök eszközei nincsenek telepítve: %1$s</string>
|
||||
<string name="agent_unqueue">Ne küldd el</string>
|
||||
<string name="agent_attach">Csatolás</string>
|
||||
<string name="agent_attach_files">Fájlok</string>
|
||||
<string name="agent_photos_allow">Fotókhoz való hozzáférés engedélyezése</string>
|
||||
<string name="agent_photos_more">További fotók kiválasztása</string>
|
||||
<string name="agent_photos_empty">Még nincsenek fotók</string>
|
||||
<string name="agent_keyboard">Billentyűzet</string>
|
||||
<string name="agent_remove_attachment">Eltávolítás</string>
|
||||
<string name="agent_model_default">Alapértelmezett</string>
|
||||
<string name="agent_effort">Gondolkodási erőfeszítés</string>
|
||||
@@ -2628,7 +2633,6 @@
|
||||
<string name="library_display_smaller">Kisebb kártyák</string>
|
||||
<string name="library_display_title">Cím megjelenítése</string>
|
||||
<string name="library_display_size">Méret megjelenítése</string>
|
||||
<string name="library_display_store">Áruház megjelenítése</string>
|
||||
<string name="stores_sort_last_played">Nemrég játszott</string>
|
||||
<string name="stores_sort_recently_installed">Nemrég telepített</string>
|
||||
<string name="stores_sort_title_asc">Cím A–Z</string>
|
||||
@@ -4166,4 +4170,6 @@
|
||||
<string name="glasses_shortcut_group">Játékon belüli parancsikon</string>
|
||||
<string name="glasses_show_shortcut">Smart Glasses parancsikon megjelenítése</string>
|
||||
<string name="glasses_show_shortcut_hint">A játék fölött lebegő Smart Glasses gomb megjelenítése.</string>
|
||||
<string name="display_filter_game_profile">Használt profil: %1$s – %2$s</string>
|
||||
<string name="display_filter_default_profile">Alapértelmezett profil használata: %1$s</string>
|
||||
</resources>
|
||||
@@ -1165,6 +1165,11 @@
|
||||
<string name="agent_tools_missing">Alat agen tidak terpasang: %1$s</string>
|
||||
<string name="agent_unqueue">Jangan kirim</string>
|
||||
<string name="agent_attach">Lampirkan</string>
|
||||
<string name="agent_attach_files">File</string>
|
||||
<string name="agent_photos_allow">Izinkan akses foto</string>
|
||||
<string name="agent_photos_more">Pilih foto lainnya</string>
|
||||
<string name="agent_photos_empty">Belum ada foto</string>
|
||||
<string name="agent_keyboard">Keyboard</string>
|
||||
<string name="agent_remove_attachment">Hapus</string>
|
||||
<string name="agent_model_default">Default</string>
|
||||
<string name="agent_effort">Upaya penalaran</string>
|
||||
@@ -2603,7 +2608,6 @@
|
||||
<string name="library_display_smaller">Kartu lebih kecil</string>
|
||||
<string name="library_display_title">Tampilkan judul</string>
|
||||
<string name="library_display_size">Tampilkan ukuran</string>
|
||||
<string name="library_display_store">Tampilkan toko</string>
|
||||
<string name="stores_sort_last_played">Baru dimainkan</string>
|
||||
<string name="stores_sort_recently_installed">Baru dipasang</string>
|
||||
<string name="stores_sort_title_asc">Judul A–Z</string>
|
||||
@@ -4136,4 +4140,6 @@
|
||||
<string name="glasses_shortcut_group">Pintasan dalam game</string>
|
||||
<string name="glasses_show_shortcut">Tampilkan pintasan Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Tampilkan tombol Smart Glasses mengambang di atas game.</string>
|
||||
<string name="display_filter_game_profile">Menggunakan profil %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Menggunakan profil default: %1$s</string>
|
||||
</resources>
|
||||
@@ -1163,6 +1163,11 @@
|
||||
<string name="agent_tools_missing">Strumenti dell’agente non installati: %1$s</string>
|
||||
<string name="agent_unqueue">Non inviare</string>
|
||||
<string name="agent_attach">Allega</string>
|
||||
<string name="agent_attach_files">File</string>
|
||||
<string name="agent_photos_allow">Consenti accesso alle foto</string>
|
||||
<string name="agent_photos_more">Scegli altre foto</string>
|
||||
<string name="agent_photos_empty">Ancora nessuna foto</string>
|
||||
<string name="agent_keyboard">Tastiera</string>
|
||||
<string name="agent_remove_attachment">Rimuovi</string>
|
||||
<string name="agent_model_default">Predefinito</string>
|
||||
<string name="agent_effort">Livello di ragionamento</string>
|
||||
@@ -2645,7 +2650,6 @@
|
||||
<string name="library_display_smaller">Schede più piccole</string>
|
||||
<string name="library_display_title">Mostra titolo</string>
|
||||
<string name="library_display_size">Mostra dimensione</string>
|
||||
<string name="library_display_store">Mostra negozio</string>
|
||||
<string name="stores_sort_last_played">Giocate di recente</string>
|
||||
<string name="stores_sort_recently_installed">Installate di recente</string>
|
||||
<string name="stores_sort_title_asc">Titolo A–Z</string>
|
||||
@@ -4205,4 +4209,6 @@
|
||||
<string name="glasses_shortcut_group">Scorciatoia nel gioco</string>
|
||||
<string name="glasses_show_shortcut">Mostra scorciatoia Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Mostra il pulsante mobile Smart Glasses sopra il gioco.</string>
|
||||
<string name="display_filter_game_profile">Profilo %1$s in uso: %2$s</string>
|
||||
<string name="display_filter_default_profile">Profilo predefinito in uso: %1$s</string>
|
||||
</resources>
|
||||
@@ -1165,6 +1165,11 @@
|
||||
<string name="agent_tools_missing">エージェントのツールが未インストール: %1$s</string>
|
||||
<string name="agent_unqueue">送信しない</string>
|
||||
<string name="agent_attach">添付</string>
|
||||
<string name="agent_attach_files">ファイル</string>
|
||||
<string name="agent_photos_allow">写真へのアクセスを許可</string>
|
||||
<string name="agent_photos_more">写真をさらに選択</string>
|
||||
<string name="agent_photos_empty">まだ写真がありません</string>
|
||||
<string name="agent_keyboard">キーボード</string>
|
||||
<string name="agent_remove_attachment">削除</string>
|
||||
<string name="agent_model_default">デフォルト</string>
|
||||
<string name="agent_effort">推論レベル</string>
|
||||
@@ -2603,7 +2608,6 @@
|
||||
<string name="library_display_smaller">小さいカード</string>
|
||||
<string name="library_display_title">タイトルを表示</string>
|
||||
<string name="library_display_size">サイズを表示</string>
|
||||
<string name="library_display_store">ストアを表示</string>
|
||||
<string name="stores_sort_last_played">最近プレイ</string>
|
||||
<string name="stores_sort_recently_installed">最近インストール</string>
|
||||
<string name="stores_sort_title_asc">タイトル A–Z</string>
|
||||
@@ -4136,4 +4140,6 @@
|
||||
<string name="glasses_shortcut_group">ゲーム内ショートカット</string>
|
||||
<string name="glasses_show_shortcut">Smart Glasses のショートカットを表示</string>
|
||||
<string name="glasses_show_shortcut_hint">ゲーム画面上に Smart Glasses のフローティングボタンを表示します。</string>
|
||||
<string name="display_filter_game_profile">%1$s プロファイルを使用中: %2$s</string>
|
||||
<string name="display_filter_default_profile">デフォルトプロファイルを使用中: %1$s</string>
|
||||
</resources>
|
||||
@@ -1165,6 +1165,11 @@
|
||||
<string name="agent_tools_missing">에이전트 도구가 설치되지 않음: %1$s</string>
|
||||
<string name="agent_unqueue">보내지 않기</string>
|
||||
<string name="agent_attach">첨부</string>
|
||||
<string name="agent_attach_files">파일</string>
|
||||
<string name="agent_photos_allow">사진 접근 허용</string>
|
||||
<string name="agent_photos_more">사진 더 선택</string>
|
||||
<string name="agent_photos_empty">아직 사진이 없습니다</string>
|
||||
<string name="agent_keyboard">키보드</string>
|
||||
<string name="agent_remove_attachment">제거</string>
|
||||
<string name="agent_model_default">기본</string>
|
||||
<string name="agent_effort">추론 수준</string>
|
||||
@@ -2603,7 +2608,6 @@
|
||||
<string name="library_display_smaller">카드 작게</string>
|
||||
<string name="library_display_title">제목 표시</string>
|
||||
<string name="library_display_size">크기 표시</string>
|
||||
<string name="library_display_store">스토어 표시</string>
|
||||
<string name="stores_sort_last_played">최근 플레이</string>
|
||||
<string name="stores_sort_recently_installed">최근 설치</string>
|
||||
<string name="stores_sort_title_asc">제목 A–Z</string>
|
||||
@@ -4136,4 +4140,6 @@
|
||||
<string name="glasses_shortcut_group">게임 내 바로가기</string>
|
||||
<string name="glasses_show_shortcut">Smart Glasses 바로가기 표시</string>
|
||||
<string name="glasses_show_shortcut_hint">게임 위에 떠 있는 Smart Glasses 버튼을 표시합니다.</string>
|
||||
<string name="display_filter_game_profile">%1$s 프로필 사용 중: %2$s</string>
|
||||
<string name="display_filter_default_profile">기본 프로필 사용 중: %1$s</string>
|
||||
</resources>
|
||||
@@ -1165,6 +1165,11 @@
|
||||
<string name="agent_tools_missing">Alat ejen tidak dipasang: %1$s</string>
|
||||
<string name="agent_unqueue">Jangan hantar</string>
|
||||
<string name="agent_attach">Lampirkan</string>
|
||||
<string name="agent_attach_files">Fail</string>
|
||||
<string name="agent_photos_allow">Benarkan akses foto</string>
|
||||
<string name="agent_photos_more">Pilih lebih banyak foto</string>
|
||||
<string name="agent_photos_empty">Belum ada foto</string>
|
||||
<string name="agent_keyboard">Papan kekunci</string>
|
||||
<string name="agent_remove_attachment">Alih keluar</string>
|
||||
<string name="agent_model_default">Lalai</string>
|
||||
<string name="agent_effort">Usaha penaakulan</string>
|
||||
@@ -2603,7 +2608,6 @@
|
||||
<string name="library_display_smaller">Kad lebih kecil</string>
|
||||
<string name="library_display_title">Paparkan tajuk</string>
|
||||
<string name="library_display_size">Paparkan saiz</string>
|
||||
<string name="library_display_store">Paparkan kedai</string>
|
||||
<string name="stores_sort_last_played">Baru dimainkan</string>
|
||||
<string name="stores_sort_recently_installed">Baru dipasang</string>
|
||||
<string name="stores_sort_title_asc">Tajuk A–Z</string>
|
||||
@@ -4136,4 +4140,6 @@
|
||||
<string name="glasses_shortcut_group">Pintasan dalam permainan</string>
|
||||
<string name="glasses_show_shortcut">Tunjukkan pintasan Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Tunjukkan butang Smart Glasses terapung di atas permainan.</string>
|
||||
<string name="display_filter_game_profile">Menggunakan profil %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Menggunakan profil lalai: %1$s</string>
|
||||
</resources>
|
||||
@@ -1168,6 +1168,11 @@
|
||||
<string name="agent_tools_missing">Agentverktøy er ikke installert: %1$s</string>
|
||||
<string name="agent_unqueue">Ikke send</string>
|
||||
<string name="agent_attach">Legg ved</string>
|
||||
<string name="agent_attach_files">Filer</string>
|
||||
<string name="agent_photos_allow">Tillat tilgang til bilder</string>
|
||||
<string name="agent_photos_more">Velg flere bilder</string>
|
||||
<string name="agent_photos_empty">Ingen bilder ennå</string>
|
||||
<string name="agent_keyboard">Tastatur</string>
|
||||
<string name="agent_remove_attachment">Fjern</string>
|
||||
<string name="agent_model_default">Standard</string>
|
||||
<string name="agent_effort">Resonneringsinnsats</string>
|
||||
@@ -2628,7 +2633,6 @@
|
||||
<string name="library_display_smaller">Mindre kort</string>
|
||||
<string name="library_display_title">Vis tittel</string>
|
||||
<string name="library_display_size">Vis størrelse</string>
|
||||
<string name="library_display_store">Vis butikk</string>
|
||||
<string name="stores_sort_last_played">Nylig spilt</string>
|
||||
<string name="stores_sort_recently_installed">Nylig installert</string>
|
||||
<string name="stores_sort_title_asc">Tittel A–Å</string>
|
||||
@@ -4166,4 +4170,6 @@
|
||||
<string name="glasses_shortcut_group">Snarvei i spillet</string>
|
||||
<string name="glasses_show_shortcut">Vis Smart Glasses-snarvei</string>
|
||||
<string name="glasses_show_shortcut_hint">Vis den flytende Smart Glasses-knappen over spillet.</string>
|
||||
<string name="display_filter_game_profile">Bruker profilen %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Bruker standardprofilen: %1$s</string>
|
||||
</resources>
|
||||
@@ -1168,6 +1168,11 @@
|
||||
<string name="agent_tools_missing">Agenttools niet geïnstalleerd: %1$s</string>
|
||||
<string name="agent_unqueue">Niet verzenden</string>
|
||||
<string name="agent_attach">Bijvoegen</string>
|
||||
<string name="agent_attach_files">Bestanden</string>
|
||||
<string name="agent_photos_allow">Toegang tot foto\'s toestaan</string>
|
||||
<string name="agent_photos_more">Meer foto\'s kiezen</string>
|
||||
<string name="agent_photos_empty">Nog geen foto\'s</string>
|
||||
<string name="agent_keyboard">Toetsenbord</string>
|
||||
<string name="agent_remove_attachment">Verwijderen</string>
|
||||
<string name="agent_model_default">Standaard</string>
|
||||
<string name="agent_effort">Redeneerinspanning</string>
|
||||
@@ -2628,7 +2633,6 @@
|
||||
<string name="library_display_smaller">Kleinere kaarten</string>
|
||||
<string name="library_display_title">Titel tonen</string>
|
||||
<string name="library_display_size">Grootte tonen</string>
|
||||
<string name="library_display_store">Winkel tonen</string>
|
||||
<string name="stores_sort_last_played">Onlangs gespeeld</string>
|
||||
<string name="stores_sort_recently_installed">Onlangs geïnstalleerd</string>
|
||||
<string name="stores_sort_title_asc">Titel A–Z</string>
|
||||
@@ -4166,4 +4170,6 @@
|
||||
<string name="glasses_shortcut_group">Snelkoppeling in game</string>
|
||||
<string name="glasses_show_shortcut">Smart Glasses-snelkoppeling tonen</string>
|
||||
<string name="glasses_show_shortcut_hint">Toon de zwevende Smart Glasses-knop boven het spel.</string>
|
||||
<string name="display_filter_game_profile">Profiel %1$s in gebruik: %2$s</string>
|
||||
<string name="display_filter_default_profile">Standaardprofiel in gebruik: %1$s</string>
|
||||
</resources>
|
||||
@@ -1174,6 +1174,11 @@
|
||||
<string name="agent_tools_missing">Narzędzia agenta nie są zainstalowane: %1$s</string>
|
||||
<string name="agent_unqueue">Nie wysyłaj</string>
|
||||
<string name="agent_attach">Załącz</string>
|
||||
<string name="agent_attach_files">Pliki</string>
|
||||
<string name="agent_photos_allow">Zezwól na dostęp do zdjęć</string>
|
||||
<string name="agent_photos_more">Wybierz więcej zdjęć</string>
|
||||
<string name="agent_photos_empty">Brak zdjęć</string>
|
||||
<string name="agent_keyboard">Klawiatura</string>
|
||||
<string name="agent_remove_attachment">Usuń</string>
|
||||
<string name="agent_model_default">Domyślny</string>
|
||||
<string name="agent_effort">Poziom rozumowania</string>
|
||||
@@ -2680,7 +2685,6 @@
|
||||
<string name="library_display_smaller">Mniejsze karty</string>
|
||||
<string name="library_display_title">Pokazuj tytuł</string>
|
||||
<string name="library_display_size">Pokazuj rozmiar</string>
|
||||
<string name="library_display_store">Pokazuj sklep</string>
|
||||
<string name="stores_sort_last_played">Ostatnio grane</string>
|
||||
<string name="stores_sort_recently_installed">Ostatnio zainstalowane</string>
|
||||
<string name="stores_sort_title_asc">Tytuł A–Z</string>
|
||||
@@ -4246,4 +4250,6 @@
|
||||
<string name="glasses_shortcut_group">Skrót w grze</string>
|
||||
<string name="glasses_show_shortcut">Pokaż skrót Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Pokaż pływający przycisk Smart Glasses nad grą.</string>
|
||||
<string name="display_filter_game_profile">Używany profil %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Używany profil domyślny: %1$s</string>
|
||||
</resources>
|
||||
@@ -1163,6 +1163,11 @@
|
||||
<string name="agent_tools_missing">Ferramentas do agente não instaladas: %1$s</string>
|
||||
<string name="agent_unqueue">Não enviar</string>
|
||||
<string name="agent_attach">Anexar</string>
|
||||
<string name="agent_attach_files">Ficheiros</string>
|
||||
<string name="agent_photos_allow">Permitir acesso às fotos</string>
|
||||
<string name="agent_photos_more">Escolher mais fotos</string>
|
||||
<string name="agent_photos_empty">Ainda não há fotos</string>
|
||||
<string name="agent_keyboard">Teclado</string>
|
||||
<string name="agent_remove_attachment">Remover</string>
|
||||
<string name="agent_model_default">Predefinido</string>
|
||||
<string name="agent_effort">Esforço de raciocínio</string>
|
||||
@@ -2660,7 +2665,6 @@
|
||||
<string name="library_display_smaller">Cartões mais pequenos</string>
|
||||
<string name="library_display_title">Mostrar título</string>
|
||||
<string name="library_display_size">Mostrar tamanho</string>
|
||||
<string name="library_display_store">Mostrar loja</string>
|
||||
<string name="stores_sort_last_played">Jogados recentemente</string>
|
||||
<string name="stores_sort_recently_installed">Instalados recentemente</string>
|
||||
<string name="stores_sort_title_asc">Título A–Z</string>
|
||||
@@ -4205,4 +4209,6 @@
|
||||
<string name="glasses_shortcut_group">Atalho no jogo</string>
|
||||
<string name="glasses_show_shortcut">Mostrar atalho do Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Mostrar o botão flutuante do Smart Glasses sobre o jogo.</string>
|
||||
<string name="display_filter_game_profile">Perfil %1$s em utilização: %2$s</string>
|
||||
<string name="display_filter_default_profile">Perfil predefinido em utilização: %1$s</string>
|
||||
</resources>
|
||||
@@ -1170,6 +1170,11 @@
|
||||
<string name="agent_tools_missing">Ferramentas do agente não instaladas: %1$s</string>
|
||||
<string name="agent_unqueue">Não enviar</string>
|
||||
<string name="agent_attach">Anexar</string>
|
||||
<string name="agent_attach_files">Arquivos</string>
|
||||
<string name="agent_photos_allow">Permitir acesso às fotos</string>
|
||||
<string name="agent_photos_more">Escolher mais fotos</string>
|
||||
<string name="agent_photos_empty">Ainda não há fotos</string>
|
||||
<string name="agent_keyboard">Teclado</string>
|
||||
<string name="agent_remove_attachment">Remover</string>
|
||||
<string name="agent_model_default">Padrão</string>
|
||||
<string name="agent_effort">Esforço de raciocínio</string>
|
||||
@@ -2670,7 +2675,6 @@
|
||||
<string name="library_display_smaller">Cards menores</string>
|
||||
<string name="library_display_title">Mostrar título</string>
|
||||
<string name="library_display_size">Mostrar tamanho</string>
|
||||
<string name="library_display_store">Mostrar loja</string>
|
||||
<string name="stores_sort_last_played">Jogados recentemente</string>
|
||||
<string name="stores_sort_recently_installed">Instalados recentemente</string>
|
||||
<string name="stores_sort_title_asc">Título A–Z</string>
|
||||
@@ -4213,4 +4217,6 @@
|
||||
<string name="glasses_shortcut_group">Atalho durante o jogo</string>
|
||||
<string name="glasses_show_shortcut">Mostrar atalho do Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Mostrar o botão flutuante do Smart Glasses sobre o jogo.</string>
|
||||
<string name="display_filter_game_profile">Perfil %1$s em uso: %2$s</string>
|
||||
<string name="display_filter_default_profile">Perfil predefinido em uso: %1$s</string>
|
||||
</resources>
|
||||
@@ -1171,6 +1171,11 @@
|
||||
<string name="agent_tools_missing">Instrumentele agentului nu sunt instalate: %1$s</string>
|
||||
<string name="agent_unqueue">Nu trimite</string>
|
||||
<string name="agent_attach">Atașează</string>
|
||||
<string name="agent_attach_files">Fișiere</string>
|
||||
<string name="agent_photos_allow">Permite accesul la fotografii</string>
|
||||
<string name="agent_photos_more">Alege mai multe fotografii</string>
|
||||
<string name="agent_photos_empty">Încă nu există fotografii</string>
|
||||
<string name="agent_keyboard">Tastatură</string>
|
||||
<string name="agent_remove_attachment">Elimină</string>
|
||||
<string name="agent_model_default">Implicit</string>
|
||||
<string name="agent_effort">Efort de raționament</string>
|
||||
@@ -2654,7 +2659,6 @@
|
||||
<string name="library_display_smaller">Carduri mai mici</string>
|
||||
<string name="library_display_title">Afișează titlul</string>
|
||||
<string name="library_display_size">Afișează dimensiunea</string>
|
||||
<string name="library_display_store">Afișează magazinul</string>
|
||||
<string name="stores_sort_last_played">Jucate recent</string>
|
||||
<string name="stores_sort_recently_installed">Instalate recent</string>
|
||||
<string name="stores_sort_title_asc">Titlu A–Z</string>
|
||||
@@ -4206,4 +4210,6 @@
|
||||
<string name="glasses_shortcut_group">Comandă rapidă în joc</string>
|
||||
<string name="glasses_show_shortcut">Afișează comanda rapidă Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Afișează butonul plutitor Smart Glasses peste joc.</string>
|
||||
<string name="display_filter_game_profile">Se folosește profilul %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Se folosește profilul implicit: %1$s</string>
|
||||
</resources>
|
||||
@@ -1174,6 +1174,11 @@
|
||||
<string name="agent_tools_missing">Инструменты агента не установлены: %1$s</string>
|
||||
<string name="agent_unqueue">Не отправлять</string>
|
||||
<string name="agent_attach">Прикрепить</string>
|
||||
<string name="agent_attach_files">Файлы</string>
|
||||
<string name="agent_photos_allow">Разрешить доступ к фото</string>
|
||||
<string name="agent_photos_more">Выбрать ещё фото</string>
|
||||
<string name="agent_photos_empty">Пока нет фото</string>
|
||||
<string name="agent_keyboard">Клавиатура</string>
|
||||
<string name="agent_remove_attachment">Удалить</string>
|
||||
<string name="agent_model_default">По умолчанию</string>
|
||||
<string name="agent_effort">Уровень рассуждений</string>
|
||||
@@ -2681,7 +2686,6 @@
|
||||
<string name="library_display_smaller">Мелкие карточки</string>
|
||||
<string name="library_display_title">Показывать название</string>
|
||||
<string name="library_display_size">Показывать размер</string>
|
||||
<string name="library_display_store">Показывать магазин</string>
|
||||
<string name="stores_sort_last_played">Недавно запущенные</string>
|
||||
<string name="stores_sort_recently_installed">Недавно установленные</string>
|
||||
<string name="stores_sort_title_asc">Название А–Я</string>
|
||||
@@ -4247,4 +4251,6 @@
|
||||
<string name="glasses_shortcut_group">Ярлык в игре</string>
|
||||
<string name="glasses_show_shortcut">Показывать ярлык Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Показывать плавающую кнопку Smart Glasses поверх игры.</string>
|
||||
<string name="display_filter_game_profile">Используется профиль %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Используется профиль по умолчанию: %1$s</string>
|
||||
</resources>
|
||||
@@ -1168,6 +1168,11 @@
|
||||
<string name="agent_tools_missing">Agentens verktyg är inte installerade: %1$s</string>
|
||||
<string name="agent_unqueue">Skicka inte</string>
|
||||
<string name="agent_attach">Bifoga</string>
|
||||
<string name="agent_attach_files">Filer</string>
|
||||
<string name="agent_photos_allow">Tillåt åtkomst till bilder</string>
|
||||
<string name="agent_photos_more">Välj fler bilder</string>
|
||||
<string name="agent_photos_empty">Inga bilder än</string>
|
||||
<string name="agent_keyboard">Tangentbord</string>
|
||||
<string name="agent_remove_attachment">Ta bort</string>
|
||||
<string name="agent_model_default">Standard</string>
|
||||
<string name="agent_effort">Resonemangsnivå</string>
|
||||
@@ -2628,7 +2633,6 @@
|
||||
<string name="library_display_smaller">Mindre kort</string>
|
||||
<string name="library_display_title">Visa titel</string>
|
||||
<string name="library_display_size">Visa storlek</string>
|
||||
<string name="library_display_store">Visa butik</string>
|
||||
<string name="stores_sort_last_played">Senast spelade</string>
|
||||
<string name="stores_sort_recently_installed">Senast installerade</string>
|
||||
<string name="stores_sort_title_asc">Titel A–Ö</string>
|
||||
@@ -4166,4 +4170,6 @@
|
||||
<string name="glasses_shortcut_group">Genväg i spelet</string>
|
||||
<string name="glasses_show_shortcut">Visa Smart Glasses-genväg</string>
|
||||
<string name="glasses_show_shortcut_hint">Visa den flytande Smart Glasses-knappen ovanpå spelet.</string>
|
||||
<string name="display_filter_game_profile">Använder profilen %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Använder standardprofilen: %1$s</string>
|
||||
</resources>
|
||||
@@ -1165,6 +1165,11 @@
|
||||
<string name="agent_tools_missing">ยังไม่ได้ติดตั้งเครื่องมือของเอเจนต์: %1$s</string>
|
||||
<string name="agent_unqueue">ไม่ต้องส่ง</string>
|
||||
<string name="agent_attach">แนบ</string>
|
||||
<string name="agent_attach_files">ไฟล์</string>
|
||||
<string name="agent_photos_allow">อนุญาตให้เข้าถึงรูปภาพ</string>
|
||||
<string name="agent_photos_more">เลือกรูปภาพเพิ่ม</string>
|
||||
<string name="agent_photos_empty">ยังไม่มีรูปภาพ</string>
|
||||
<string name="agent_keyboard">แป้นพิมพ์</string>
|
||||
<string name="agent_remove_attachment">นำออก</string>
|
||||
<string name="agent_model_default">ค่าเริ่มต้น</string>
|
||||
<string name="agent_effort">ระดับการใช้เหตุผล</string>
|
||||
@@ -2603,7 +2608,6 @@
|
||||
<string name="library_display_smaller">การ์ดเล็กลง</string>
|
||||
<string name="library_display_title">แสดงชื่อ</string>
|
||||
<string name="library_display_size">แสดงขนาด</string>
|
||||
<string name="library_display_store">แสดงร้านค้า</string>
|
||||
<string name="stores_sort_last_played">เล่นล่าสุด</string>
|
||||
<string name="stores_sort_recently_installed">เพิ่งติดตั้ง</string>
|
||||
<string name="stores_sort_title_asc">ชื่อ A–Z</string>
|
||||
@@ -4136,4 +4140,6 @@
|
||||
<string name="glasses_shortcut_group">ทางลัดในเกม</string>
|
||||
<string name="glasses_show_shortcut">แสดงทางลัด Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">แสดงปุ่ม Smart Glasses แบบลอยทับบนเกม</string>
|
||||
<string name="display_filter_game_profile">ใช้โปรไฟล์ %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">ใช้โปรไฟล์เริ่มต้น: %1$s</string>
|
||||
</resources>
|
||||
@@ -1160,6 +1160,11 @@
|
||||
<string name="agent_tools_missing">Ajan araçları yüklenmedi: %1$s</string>
|
||||
<string name="agent_unqueue">Gönderme</string>
|
||||
<string name="agent_attach">Ekle</string>
|
||||
<string name="agent_attach_files">Dosyalar</string>
|
||||
<string name="agent_photos_allow">Fotoğraflara erişime izin ver</string>
|
||||
<string name="agent_photos_more">Daha fazla fotoğraf seç</string>
|
||||
<string name="agent_photos_empty">Henüz fotoğraf yok</string>
|
||||
<string name="agent_keyboard">Klavye</string>
|
||||
<string name="agent_remove_attachment">Kaldır</string>
|
||||
<string name="agent_model_default">Varsayılan</string>
|
||||
<string name="agent_effort">Akıl yürütme çabası</string>
|
||||
@@ -2620,7 +2625,6 @@
|
||||
<string name="library_display_smaller">Daha küçük kartlar</string>
|
||||
<string name="library_display_title">Başlığı göster</string>
|
||||
<string name="library_display_size">Boyutu göster</string>
|
||||
<string name="library_display_store">Mağazayı göster</string>
|
||||
<string name="stores_sort_last_played">Son oynanan</string>
|
||||
<string name="stores_sort_recently_installed">Son yüklenen</string>
|
||||
<string name="stores_sort_title_asc">Başlık A–Z</string>
|
||||
@@ -4166,4 +4170,6 @@
|
||||
<string name="glasses_shortcut_group">Oyun içi kısayol</string>
|
||||
<string name="glasses_show_shortcut">Smart Glasses kısayolunu göster</string>
|
||||
<string name="glasses_show_shortcut_hint">Oyun üzerinde yüzen Smart Glasses düğmesini göster.</string>
|
||||
<string name="display_filter_game_profile">%1$s profili kullanılıyor: %2$s</string>
|
||||
<string name="display_filter_default_profile">Varsayılan profil kullanılıyor: %1$s</string>
|
||||
</resources>
|
||||
@@ -1174,6 +1174,11 @@
|
||||
<string name="agent_tools_missing">Інструменти агента не встановлено: %1$s</string>
|
||||
<string name="agent_unqueue">Не надсилати</string>
|
||||
<string name="agent_attach">Прикріпити</string>
|
||||
<string name="agent_attach_files">Файли</string>
|
||||
<string name="agent_photos_allow">Дозволити доступ до фото</string>
|
||||
<string name="agent_photos_more">Вибрати ще фото</string>
|
||||
<string name="agent_photos_empty">Поки немає фото</string>
|
||||
<string name="agent_keyboard">Клавіатура</string>
|
||||
<string name="agent_remove_attachment">Видалити</string>
|
||||
<string name="agent_model_default">За замовчуванням</string>
|
||||
<string name="agent_effort">Рівень міркувань</string>
|
||||
@@ -2680,7 +2685,6 @@
|
||||
<string name="library_display_smaller">Малі картки</string>
|
||||
<string name="library_display_title">Показувати назву</string>
|
||||
<string name="library_display_size">Показувати розмір</string>
|
||||
<string name="library_display_store">Показувати магазин</string>
|
||||
<string name="stores_sort_last_played">Нещодавно запущені</string>
|
||||
<string name="stores_sort_recently_installed">Нещодавно встановлені</string>
|
||||
<string name="stores_sort_title_asc">Назва А–Я</string>
|
||||
@@ -4246,4 +4250,6 @@
|
||||
<string name="glasses_shortcut_group">Ярлик у грі</string>
|
||||
<string name="glasses_show_shortcut">Показувати ярлик Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Показувати плаваючу кнопку Smart Glasses поверх гри.</string>
|
||||
<string name="display_filter_game_profile">Використовується профіль %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Використовується профіль за замовчуванням: %1$s</string>
|
||||
</resources>
|
||||
@@ -1165,6 +1165,11 @@
|
||||
<string name="agent_tools_missing">Chưa cài công cụ của tác tử: %1$s</string>
|
||||
<string name="agent_unqueue">Không gửi</string>
|
||||
<string name="agent_attach">Đính kèm</string>
|
||||
<string name="agent_attach_files">Tệp</string>
|
||||
<string name="agent_photos_allow">Cho phép truy cập ảnh</string>
|
||||
<string name="agent_photos_more">Chọn thêm ảnh</string>
|
||||
<string name="agent_photos_empty">Chưa có ảnh</string>
|
||||
<string name="agent_keyboard">Bàn phím</string>
|
||||
<string name="agent_remove_attachment">Xóa</string>
|
||||
<string name="agent_model_default">Mặc định</string>
|
||||
<string name="agent_effort">Mức độ lập luận</string>
|
||||
@@ -2603,7 +2608,6 @@
|
||||
<string name="library_display_smaller">Thẻ nhỏ hơn</string>
|
||||
<string name="library_display_title">Hiện tiêu đề</string>
|
||||
<string name="library_display_size">Hiện kích thước</string>
|
||||
<string name="library_display_store">Hiện cửa hàng</string>
|
||||
<string name="stores_sort_last_played">Chơi gần đây</string>
|
||||
<string name="stores_sort_recently_installed">Cài gần đây</string>
|
||||
<string name="stores_sort_title_asc">Tên A–Z</string>
|
||||
@@ -4136,4 +4140,6 @@
|
||||
<string name="glasses_shortcut_group">Lối tắt trong trò chơi</string>
|
||||
<string name="glasses_show_shortcut">Hiển thị lối tắt Smart Glasses</string>
|
||||
<string name="glasses_show_shortcut_hint">Hiển thị nút Smart Glasses nổi phía trên trò chơi.</string>
|
||||
<string name="display_filter_game_profile">Đang dùng hồ sơ %1$s: %2$s</string>
|
||||
<string name="display_filter_default_profile">Đang dùng hồ sơ mặc định: %1$s</string>
|
||||
</resources>
|
||||
@@ -1248,6 +1248,11 @@
|
||||
<string name="agent_tools_missing">智能体工具未安装:%1$s</string>
|
||||
<string name="agent_unqueue">不发送</string>
|
||||
<string name="agent_attach">添加附件</string>
|
||||
<string name="agent_attach_files">文件</string>
|
||||
<string name="agent_photos_allow">允许访问照片</string>
|
||||
<string name="agent_photos_more">选择更多照片</string>
|
||||
<string name="agent_photos_empty">还没有照片</string>
|
||||
<string name="agent_keyboard">键盘</string>
|
||||
<string name="agent_remove_attachment">移除</string>
|
||||
<string name="agent_model_default">默认</string>
|
||||
<string name="agent_effort">推理强度</string>
|
||||
@@ -2680,7 +2685,6 @@
|
||||
<string name="library_display_smaller">较小卡片</string>
|
||||
<string name="library_display_title">显示标题</string>
|
||||
<string name="library_display_size">显示大小</string>
|
||||
<string name="library_display_store">显示商店</string>
|
||||
<string name="stores_sort_last_played">最近游玩</string>
|
||||
<string name="stores_sort_recently_installed">最近安装</string>
|
||||
<string name="stores_sort_title_asc">标题 A–Z</string>
|
||||
@@ -4134,4 +4138,6 @@
|
||||
<string name="glasses_shortcut_group">游戏内快捷方式</string>
|
||||
<string name="glasses_show_shortcut">显示 Smart Glasses 快捷方式</string>
|
||||
<string name="glasses_show_shortcut_hint">在游戏画面上显示悬浮的 Smart Glasses 按钮。</string>
|
||||
<string name="display_filter_game_profile">正在使用 %1$s 配置:%2$s</string>
|
||||
<string name="display_filter_default_profile">正在使用默认配置:%1$s</string>
|
||||
</resources>
|
||||
@@ -1164,6 +1164,11 @@
|
||||
<string name="agent_tools_missing">智能體工具未安裝:%1$s</string>
|
||||
<string name="agent_unqueue">不要傳送</string>
|
||||
<string name="agent_attach">附加</string>
|
||||
<string name="agent_attach_files">檔案</string>
|
||||
<string name="agent_photos_allow">允許存取相片</string>
|
||||
<string name="agent_photos_more">選擇更多相片</string>
|
||||
<string name="agent_photos_empty">尚未有相片</string>
|
||||
<string name="agent_keyboard">鍵盤</string>
|
||||
<string name="agent_remove_attachment">移除</string>
|
||||
<string name="agent_model_default">預設</string>
|
||||
<string name="agent_effort">推理強度</string>
|
||||
@@ -2600,7 +2605,6 @@
|
||||
<string name="library_display_smaller">較小卡片</string>
|
||||
<string name="library_display_title">顯示標題</string>
|
||||
<string name="library_display_size">顯示大小</string>
|
||||
<string name="library_display_store">顯示商店</string>
|
||||
<string name="stores_sort_last_played">最近遊玩</string>
|
||||
<string name="stores_sort_recently_installed">最近安裝</string>
|
||||
<string name="stores_sort_title_asc">標題 A–Z</string>
|
||||
@@ -4134,4 +4138,6 @@
|
||||
<string name="glasses_shortcut_group">遊戲內捷徑</string>
|
||||
<string name="glasses_show_shortcut">顯示 Smart Glasses 捷徑</string>
|
||||
<string name="glasses_show_shortcut_hint">在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。</string>
|
||||
<string name="display_filter_game_profile">正在使用 %1$s 設定檔:%2$s</string>
|
||||
<string name="display_filter_default_profile">正在使用預設設定檔:%1$s</string>
|
||||
</resources>
|
||||
@@ -1164,6 +1164,11 @@
|
||||
<string name="agent_tools_missing">智慧代理工具未安裝:%1$s</string>
|
||||
<string name="agent_unqueue">不要傳送</string>
|
||||
<string name="agent_attach">附加</string>
|
||||
<string name="agent_attach_files">檔案</string>
|
||||
<string name="agent_photos_allow">允許存取相片</string>
|
||||
<string name="agent_photos_more">選擇更多相片</string>
|
||||
<string name="agent_photos_empty">還沒有相片</string>
|
||||
<string name="agent_keyboard">鍵盤</string>
|
||||
<string name="agent_remove_attachment">移除</string>
|
||||
<string name="agent_model_default">預設</string>
|
||||
<string name="agent_effort">推理強度</string>
|
||||
@@ -2600,7 +2605,6 @@
|
||||
<string name="library_display_smaller">較小的卡片</string>
|
||||
<string name="library_display_title">顯示標題</string>
|
||||
<string name="library_display_size">顯示大小</string>
|
||||
<string name="library_display_store">顯示商店</string>
|
||||
<string name="stores_sort_last_played">最近遊玩</string>
|
||||
<string name="stores_sort_recently_installed">最近安裝</string>
|
||||
<string name="stores_sort_title_asc">標題 A–Z</string>
|
||||
@@ -4134,4 +4138,6 @@
|
||||
<string name="glasses_shortcut_group">遊戲內捷徑</string>
|
||||
<string name="glasses_show_shortcut">顯示 Smart Glasses 捷徑</string>
|
||||
<string name="glasses_show_shortcut_hint">在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。</string>
|
||||
<string name="display_filter_game_profile">正在使用 %1$s 設定檔:%2$s</string>
|
||||
<string name="display_filter_default_profile">正在使用預設設定檔:%1$s</string>
|
||||
</resources>
|
||||
@@ -1330,6 +1330,11 @@
|
||||
<string name="agent_tools_missing">Agent tools not installed: %1$s</string>
|
||||
<string name="agent_unqueue">Don\'t send</string>
|
||||
<string name="agent_attach">Attach</string>
|
||||
<string name="agent_attach_files">Files</string>
|
||||
<string name="agent_photos_allow">Allow photo access</string>
|
||||
<string name="agent_photos_more">Choose more photos</string>
|
||||
<string name="agent_photos_empty">No photos yet</string>
|
||||
<string name="agent_keyboard">Keyboard</string>
|
||||
<string name="agent_remove_attachment">Remove</string>
|
||||
<string name="agent_model_default">Default</string>
|
||||
<string name="agent_effort">Reasoning effort</string>
|
||||
@@ -2852,6 +2857,8 @@
|
||||
<string name="display_filter_hint">Shared by Steam and Desktop.</string>
|
||||
<string name="display_filter_live">Applies live. Shared by Steam and Desktop.</string>
|
||||
<string name="display_filter_note">FSR, GSR and NIS apply when enlarging the session image. Sharpen only also works without enlargement.</string>
|
||||
<string name="display_filter_game_profile">Using %1$s profile: %2$s</string>
|
||||
<string name="display_filter_default_profile">Using Default profile: %1$s</string>
|
||||
<string name="display_sharpness">Filter sharpness</string>
|
||||
<string name="display_look_filter">%1$s Sets scaling to %2$s.</string>
|
||||
<string name="display_match_screen">Match screen (%1$d×%2$d)</string>
|
||||
@@ -2985,7 +2992,6 @@
|
||||
<string name="library_display_smaller">Smaller cards</string>
|
||||
<string name="library_display_title">Show title</string>
|
||||
<string name="library_display_size">Show size</string>
|
||||
<string name="library_display_store">Show store</string>
|
||||
<string name="stores_sort_last_played">Recently played</string>
|
||||
<string name="stores_sort_recently_installed">Recently installed</string>
|
||||
<string name="stores_sort_title_asc">Title A–Z</string>
|
||||
|
||||
@@ -181,6 +181,17 @@ class ProtonExtrasTest {
|
||||
assertEquals(emptyList<String>(), ProtonExtras.installedIn(File(tools, "missing"), tool("ge")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun x86_64BuildsAreNotTakenForTheArm64Tool() {
|
||||
val tools = temp.newFolder("compatibilitytools.d")
|
||||
for (name in listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton-11-14.2-x86_64")) installTool(tools, name)
|
||||
File(tools, "DroidDeck-Proton-11-14.2-x86_64/files/lib/wine/x86_64-unix").mkdirs()
|
||||
File(tools, "DroidDeck-Proton 11-7.5/files/lib/wine/x86_64-unix").mkdirs()
|
||||
File(tools, "DroidDeck-Proton 11-7.5/files/bin-arm64").mkdirs()
|
||||
assertEquals(listOf("DroidDeck-Proton 11-7.5"), ProtonExtras.installedIn(tools, tool("droiddeck")))
|
||||
assertTrue(ProtonExtras.x86_64Build(File(tools, "DroidDeck-Proton-11-14.2-x86_64")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun interruptedBuildsAreNotReportedAsInstalled() {
|
||||
val tools = temp.newFolder("compatibilitytools.d")
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class SessionPrefsUpscalerTest {
|
||||
private lateinit var context: Context
|
||||
|
||||
@Before fun setUp() {
|
||||
context = RuntimeEnvironment.getApplication()
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
}
|
||||
|
||||
@Test fun gameOverridesAreIsolatedAndFallBackToTheGlobalFilter() {
|
||||
SessionPrefs.setUpscaler(context, 4)
|
||||
SessionPrefs.setGameUpscaler(context, "12345", 7)
|
||||
|
||||
assertEquals(4, SessionPrefs.upscaler(context))
|
||||
assertEquals(7, SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
|
||||
assertEquals(4, SessionPrefs.screenEffectsUpscaler(context, "game:54321"))
|
||||
assertTrue(SessionPrefs.hasGameUpscalerOverride(context, "12345"))
|
||||
assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "54321"))
|
||||
assertFalse(SessionPrefs.hasScreenEffectsOverride(context, "game:12345"))
|
||||
}
|
||||
|
||||
@Test fun resettingGameOverrideRestoresTheGlobalFilter() {
|
||||
SessionPrefs.setUpscaler(context, 3)
|
||||
SessionPrefs.setGameUpscaler(context, "12345", 6)
|
||||
|
||||
SessionPrefs.clearGameUpscaler(context, "12345")
|
||||
|
||||
assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "12345"))
|
||||
assertEquals(3, SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
|
||||
}
|
||||
|
||||
@Test fun screenEffectsUpscalerApiKeepsGameFiltersSeparateFromScreenEffects() {
|
||||
SessionPrefs.setUpscaler(context, 4)
|
||||
SessionPrefs.setScreenEffectsUpscaler(context, "game:12345", 8)
|
||||
|
||||
assertEquals(8, SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
|
||||
assertFalse(SessionPrefs.hasScreenEffectsOverride(context, "game:12345"))
|
||||
}
|
||||
|
||||
@Test fun legacyGameFilterOverridesRemainReadableAndCanBeReset() {
|
||||
val profile = JSONObject().put("upscaler", 6)
|
||||
val profiles = JSONObject().put("game:12345", profile)
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
|
||||
.putString("screenEffects.profiles", profiles.toString()).commit()
|
||||
|
||||
assertTrue(SessionPrefs.hasGameUpscalerOverride(context, "12345"))
|
||||
assertEquals(6, SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
|
||||
|
||||
SessionPrefs.clearGameUpscaler(context, "12345")
|
||||
|
||||
assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "12345"))
|
||||
assertEquals(2, SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
|
||||
assertFalse(SessionPrefs.hasScreenEffectsOverride(context, "game:12345"))
|
||||
}
|
||||
|
||||
@Test fun deletingGameScreenEffectsProfileClearsUpscalerOverrideEvenWithoutEffectsProfile() {
|
||||
SessionPrefs.setGameUpscaler(context, "12345", 6)
|
||||
|
||||
SessionPrefs.deleteScreenEffectsProfile(context, "game:12345")
|
||||
|
||||
assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "12345"))
|
||||
assertEquals(SessionPrefs.upscaler(context), SessionPrefs.screenEffectsUpscaler(context, "game:12345"))
|
||||
}
|
||||
}
|
||||
@@ -124,6 +124,450 @@ class SessionSuspendControllerTest {
|
||||
assertEquals(1, fixture.pagedIn.size)
|
||||
}
|
||||
|
||||
@Test fun aSpillWritesThePreloadedGuestsToStorageBeforeTheyStop() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
assertEquals(listOf<String?>("4 0"), fixture.held)
|
||||
assertTrue(fixture.signals.indexOfFirst { it.signal == URG } < fixture.signals.indexOfFirst { it.signal == STOP })
|
||||
assertEquals(listOf(1 to 4_000_000L), fixture.spills)
|
||||
assertTrue(fixture.pagedOut.isEmpty())
|
||||
assertTrue(fixture.game.threads.all { it.state == 't' })
|
||||
assertFalse(File(fixture.control.parentFile, ".dd-zram.ack.$GAME").exists())
|
||||
assertFalse(File(fixture.control.parentFile, ".dd-zram.hold").exists())
|
||||
}
|
||||
|
||||
@Test fun resumeMovesTheCounterBeforeContinuingAndWaitsForTheRestore() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
val before = fixture.signals.size
|
||||
var called = false
|
||||
fixture.controller.resume {
|
||||
// success is reported once the guest has its memory back and has left its tracing stop
|
||||
assertTrue(it)
|
||||
assertEquals(listOf(1 to 0), fixture.restores)
|
||||
assertTrue(fixture.game.threads.none { thread -> thread.state == 't' })
|
||||
called = true
|
||||
}
|
||||
assertTrue(called)
|
||||
assertEquals(listOf<String?>("1"), fixture.resumeAtContinue)
|
||||
assertFalse(fixture.signals.drop(before).any { it.signal == URG })
|
||||
assertEquals(listOf(1 to 0), fixture.restores)
|
||||
assertTrue(fixture.pagedIn.isEmpty())
|
||||
assertFalse(File(fixture.control.parentFile, ".dd-zram.restored.$GAME").exists())
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertEquals(listOf<String?>("1", "2"), fixture.resumeAtContinue)
|
||||
assertEquals(2, fixture.restores.size)
|
||||
}
|
||||
|
||||
@Test fun aRestoreThatOutlastsTheWaitIsWaitedForAgainByTheNextResume() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
fixture.restoreDelayMs = 60_000L
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
assertEquals(listOf(1 to 1), fixture.restores)
|
||||
assertTrue(fixture.game.threads.all { it.state == 't' })
|
||||
fixture.restoreDelayMs = 0L
|
||||
var called = false
|
||||
fixture.controller.resume {
|
||||
assertTrue(it)
|
||||
assertTrue(fixture.game.threads.none { thread -> thread.state == 't' })
|
||||
called = true
|
||||
}
|
||||
assertTrue(called)
|
||||
assertEquals(listOf(1 to 1, 1 to 0), fixture.restores)
|
||||
}
|
||||
|
||||
@Test fun aResumeCountThatCannotBeWrittenFailsWhileASpillHasNotAnswered() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.spillSilent = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { }
|
||||
File(fixture.control.parentFile, ".dd-zram.resume.new").mkdirs()
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
assertFalse(File(fixture.control.parentFile, ".dd-zram.resume").isFile)
|
||||
}
|
||||
|
||||
@Test fun aSpillThatAnswersAfterTheWaitIsStillRestoredOnResume() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.spillSilent = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { }
|
||||
fixture.spillSilent = false
|
||||
fixture.advance(1_000L)
|
||||
assertTrue(File(fixture.control.parentFile, ".dd-zram.ack.$GAME").isFile)
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertEquals(listOf(1 to 0), fixture.restores)
|
||||
assertTrue(fixture.pagedIn.isEmpty())
|
||||
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
|
||||
}
|
||||
|
||||
@Test fun aGuestWithoutTheSpillHandlerIsNotWaitedForOnResume() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.handlerReplaced = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { }
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertTrue(fixture.restores.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aSpillThatStartsAfterTheWaitFailsAResumeCountThatCannotBeWritten() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.handlerReplaced = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { }
|
||||
File(fixture.control.parentFile, ".dd-zram.resume.new").mkdirs()
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
}
|
||||
|
||||
@Test fun aSpillThatStartsAfterTheWaitIsReleasedByTheNextCount() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.handlerReplaced = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { }
|
||||
fixture.startLateSpill()
|
||||
var called = false
|
||||
fixture.controller.resume {
|
||||
assertTrue(it)
|
||||
assertEquals(listOf(1 to 0), fixture.restores)
|
||||
assertEquals(4_000_000L, fixture.gameResident)
|
||||
assertEquals(1, fixture.readBacks)
|
||||
assertTrue(fixture.game.threads.none { thread -> thread.state == 't' || thread.state == 'T' })
|
||||
called = true
|
||||
}
|
||||
assertTrue(called)
|
||||
}
|
||||
|
||||
@Test fun aLateSpillThatSeesTheNewCountIsCancelledWithoutAReadBack() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.handlerReplaced = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { }
|
||||
fixture.lateSpillSeesTheCount = true
|
||||
fixture.startLateSpill()
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertEquals(listOf(1 to 0), fixture.restores)
|
||||
assertEquals(0, fixture.readBacks)
|
||||
assertEquals(4_000_000L, fixture.gameResident)
|
||||
assertTrue(fixture.pagedIn.isEmpty())
|
||||
assertFalse(File(fixture.control.parentFile, ".dd-zram.ack.$GAME").exists())
|
||||
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
|
||||
}
|
||||
|
||||
@Test fun aHelperThatReadsBackBeforeTheContinueStillResumes() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
fixture.restoreDelayMs = 0L
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertTrue(fixture.releasedBeforeContinue)
|
||||
assertEquals(listOf(1 to 0), fixture.restores)
|
||||
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
|
||||
}
|
||||
|
||||
@Test fun aLateSpillWithoutAnAcknowledgementFailsTheResumeUntilItsHelperLetsGo() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.handlerReplaced = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { }
|
||||
fixture.ackFails = true
|
||||
fixture.startLateSpill()
|
||||
fixture.restoreDelayMs = 5_000L
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
assertTrue(fixture.game.threads.all { it.state == 't' })
|
||||
fixture.advance(5_000L)
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertEquals(1, fixture.readBacks)
|
||||
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
|
||||
}
|
||||
|
||||
@Test fun aReadBackWhoseMarkerCouldNotBeWrittenEndsWhenTheHelperLetsGo() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.game.tracer = HELPER
|
||||
fixture.sync()
|
||||
fixture.markerFails = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
val start = fixture.now
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertTrue(fixture.now - start < 5_000L)
|
||||
fixture.controller.freeze { assertTrue(it) }
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
}
|
||||
|
||||
@Test fun aLateFallbackDoesNotNeedTheCountWritten() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.spillSilent = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { }
|
||||
fixture.spillSilent = false
|
||||
fixture.spillFallsBack = true
|
||||
fixture.advance(1_000L)
|
||||
File(fixture.control.parentFile, ".dd-zram.resume.new").mkdirs()
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertEquals(1, fixture.pagedIn.size)
|
||||
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
|
||||
}
|
||||
|
||||
@Test fun aCancelledFreezeWhoseRestoreDoesNotFinishLeavesTheRollbackPending() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.restoreDelayMs = 60_000L
|
||||
fixture.afterSleep = { if (fixture.spills.isNotEmpty()) fixture.controller.cancelFreeze() }
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertFalse(it) }
|
||||
assertTrue(fixture.controller.rollbackPending)
|
||||
assertEquals(listOf(1 to 1), fixture.restores)
|
||||
fixture.afterSleep = null
|
||||
fixture.restoreDelayMs = 0L
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertFalse(fixture.controller.rollbackPending)
|
||||
}
|
||||
|
||||
@Test fun aSpilledGuestThatEndsWhileReadingBackFailsTheResume() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
fixture.restoreDelayMs = 60_000L
|
||||
fixture.afterSleep = {
|
||||
if (fixture.signals.any { it.signal == CONT } && fixture.game.threads.first().started == 2000L) {
|
||||
fixture.game.threads.first().started++
|
||||
}
|
||||
}
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
assertTrue(fixture.controller.guestLost)
|
||||
}
|
||||
|
||||
@Test fun aLossWithAnotherSpillStillReadingBackKeepsBothTheRetryAndTheFailure() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.addSecondSpiller()
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
fixture.readBackKills = true
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
assertTrue(fixture.controller.guestLost)
|
||||
assertTrue(fixture.controller.restoreOutstanding)
|
||||
assertTrue(fixture.other.threads.all { it.state == 't' })
|
||||
fixture.releaseSecondSpiller()
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
assertTrue(fixture.controller.guestLost)
|
||||
assertFalse(fixture.controller.restoreOutstanding)
|
||||
fixture.controller.freeze { assertTrue(it) }
|
||||
assertFalse(fixture.controller.guestLost)
|
||||
}
|
||||
|
||||
@Test fun aGuestReleasedWithoutItsMarkerThatEndsLaterIsNotLost() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.addSecondSpiller()
|
||||
fixture.game.tracer = HELPER
|
||||
fixture.sync()
|
||||
fixture.markerFails = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
val start = fixture.now
|
||||
fixture.afterSleep = {
|
||||
if (fixture.now - start >= 3_000L && fixture.game.threads.first().started == 2000L) {
|
||||
fixture.game.threads.first().started++
|
||||
}
|
||||
if (fixture.now - start >= 4_000L && fixture.otherHeld) fixture.releaseSecondSpiller()
|
||||
}
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertFalse(fixture.controller.guestLost)
|
||||
}
|
||||
|
||||
@Test fun anAskedGuestThatStartsAndEndsBeforeItIsTakenIsLost() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.handlerReplaced = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { }
|
||||
fixture.onAudioResume = {
|
||||
File(fixture.control.parentFile, ".dd-zram.ack.$GAME").writeText("")
|
||||
fixture.game.threads.first().started++
|
||||
fixture.sync()
|
||||
}
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
assertTrue(fixture.controller.guestLost)
|
||||
}
|
||||
|
||||
@Test fun aGuestLostInACancelledFreezesRollbackStaysLost() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.readBackKills = true
|
||||
fixture.afterSleep = { if (fixture.spills.isNotEmpty()) fixture.controller.cancelFreeze() }
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertFalse(it) }
|
||||
assertTrue(fixture.controller.guestLost)
|
||||
fixture.afterSleep = null
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
assertTrue(fixture.controller.guestLost)
|
||||
assertFalse(fixture.controller.restoreOutstanding)
|
||||
}
|
||||
|
||||
@Test fun aSpillThatStartsDuringTheResumeAndIsLostFailsIt() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.handlerReplaced = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { }
|
||||
// after the resume took its snapshot, before it publishes the count
|
||||
fixture.onAudioResume = {
|
||||
fixture.startLateSpill()
|
||||
fixture.readBackKills = true
|
||||
}
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
assertTrue(fixture.controller.guestLost)
|
||||
}
|
||||
|
||||
@Test fun aGuestThatFellBackLateAndEndedIsNotLost() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.spillSilent = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { }
|
||||
fixture.onAudioResume = {
|
||||
File(fixture.control.parentFile, ".dd-zram.ack.$GAME").writeText("0")
|
||||
fixture.game.threads.forEach { it.state = 'Z' }
|
||||
fixture.sync()
|
||||
}
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertFalse(fixture.controller.guestLost)
|
||||
}
|
||||
|
||||
@Test fun aSpilledGuestKilledByAFailedReadBackIsLostWhileStillAZombie() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.game.tracer = HELPER
|
||||
fixture.sync()
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
fixture.readBackKills = true
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
assertTrue(fixture.controller.guestLost)
|
||||
assertTrue(fixture.game.threads.all { it.state == 'Z' })
|
||||
}
|
||||
|
||||
@Test fun theMarkerlessFallbackWaitsForEveryThreadToLeaveTheTrace() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.game.tracer = HELPER
|
||||
fixture.sync()
|
||||
fixture.markerFails = true
|
||||
fixture.workerStaysTraced = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
var called = false
|
||||
fixture.controller.resume {
|
||||
assertTrue(it)
|
||||
assertTrue(fixture.workerReleaseAt < 0)
|
||||
called = true
|
||||
}
|
||||
assertTrue(called)
|
||||
}
|
||||
|
||||
@Test fun aRefreezeStopsAGuestThatOnlyItsHelperStillHolds() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
fixture.restoreDelayMs = 60_000L
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
val before = fixture.signals.size
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
assertTrue(fixture.signals.drop(before).count { it.pid == GAME && it.signal == STOP } >= 17)
|
||||
fixture.restoreDelayMs = 0L
|
||||
fixture.advance(1_000L)
|
||||
assertTrue(fixture.game.threads.all { it.state == 'T' })
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
|
||||
}
|
||||
|
||||
@Test fun aResumeThatCannotPublishItsCountKeepsTheFrozenTimeOwed() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.clock.writeBytes(shift(0L))
|
||||
fixture.handlerReplaced = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
val frozenAt = fixture.now
|
||||
val blocked = File(fixture.control.parentFile, ".dd-zram.resume.new").apply { mkdirs() }
|
||||
fixture.now += 90_000L
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
blocked.delete()
|
||||
fixture.now += 10_000L
|
||||
val resumedAt = fixture.now
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertEquals((resumedAt - frozenAt) * 1_000_000L, shift(fixture.clock))
|
||||
}
|
||||
|
||||
@Test fun aRollbackThatCannotPublishItsCountStaysPendingUntilAResume() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
val blocked = File(fixture.control.parentFile, ".dd-zram.resume.new").apply { mkdirs() }
|
||||
fixture.afterSleep = { if (fixture.spills.isNotEmpty()) fixture.controller.cancelFreeze() }
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertFalse(it) }
|
||||
assertTrue(fixture.controller.rollbackPending)
|
||||
assertTrue(fixture.resumeAtContinue.isEmpty())
|
||||
blocked.delete()
|
||||
fixture.afterSleep = null
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertFalse(fixture.controller.rollbackPending)
|
||||
assertEquals(listOf(1 to 0), fixture.restores)
|
||||
}
|
||||
|
||||
@Test fun aLateFallbackToZramIsReadBack() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.spillSilent = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { }
|
||||
fixture.spillSilent = false
|
||||
fixture.spillFallsBack = true
|
||||
fixture.advance(1_000L)
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertEquals(1, fixture.pagedIn.size)
|
||||
}
|
||||
|
||||
@Test fun aGuestThatFellBackToZramResumesWhenTheCountCannotBeWritten() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.spillFallsBack = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
File(fixture.control.parentFile, ".dd-zram.resume.new").mkdirs()
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
|
||||
}
|
||||
|
||||
@Test fun aRestoreThatFinishedLateDoesNotHoldBackTheNextResume() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
fixture.restoreDelayMs = 60_000L
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
fixture.restoreDelayMs = 0L
|
||||
fixture.advance(1_000L)
|
||||
fixture.advance(100L)
|
||||
assertTrue(File(fixture.control.parentFile, ".dd-zram.restored.$GAME").isFile)
|
||||
fixture.spillFallsBack = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
}
|
||||
|
||||
@Test fun aGuestThatCouldNotSpillIsReadBackFromZram() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.spillFallsBack = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
assertEquals(listOf(0 to 0L), fixture.spills)
|
||||
val before = fixture.signals.size
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertEquals(listOf(GAME), fixture.signals.drop(before).filter { it.signal == URG }.map { it.pid })
|
||||
assertTrue(fixture.restores.isEmpty())
|
||||
assertEquals(1, fixture.pagedIn.size)
|
||||
}
|
||||
|
||||
@Test fun aSpillCutShortByACancelledFreezeIsStillRestored() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.afterSleep = { if (fixture.spills.isNotEmpty()) fixture.controller.cancelFreeze() }
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertFalse(it) }
|
||||
assertEquals(listOf<String?>("1"), fixture.resumeAtContinue)
|
||||
assertEquals(listOf(1 to 0), fixture.restores)
|
||||
}
|
||||
|
||||
@Test fun theMonitorIsHeldOffWhilePagingOutAndReadingBack() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
@@ -485,7 +929,7 @@ class SessionSuspendControllerTest {
|
||||
private fun fixture(count: Int, executor: QueueExecutor = InlineExecutor()) =
|
||||
Fixture(temporary.newFolder(), temporary.newFolder(), count, executor)
|
||||
|
||||
private data class Task(val tid: Int, var started: Long, var state: Char, var cpu: Long = 0)
|
||||
private data class Task(val tid: Int, var started: Long, var state: Char, var cpu: Long = 0, var tracer: Int? = null)
|
||||
private data class Group(val pid: Int, var parent: Int, var tracer: Int, val threads: MutableList<Task>)
|
||||
private data class SentSignal(val pid: Int, val signal: Int)
|
||||
|
||||
@@ -493,6 +937,20 @@ class SessionSuspendControllerTest {
|
||||
val root = Group(ROOT, 9000, 0, mutableListOf(Task(ROOT, 1000, 'S')))
|
||||
val game = Group(GAME, ROOT, ROOT, MutableList(count) { Task(GAME + it, 2000L + it, 'S') })
|
||||
val groups = mutableListOf(root, game)
|
||||
val other = Group(OTHER, ROOT, ROOT, mutableListOf(Task(OTHER, 4000, 'S')))
|
||||
var otherHeld = false
|
||||
|
||||
fun addSecondSpiller() {
|
||||
groups += other
|
||||
sync()
|
||||
}
|
||||
|
||||
fun releaseSecondSpiller() {
|
||||
otherHeld = false
|
||||
other.threads.forEach { it.state = 'S' }
|
||||
File(control.parentFile, "${control.name}.restored.$OTHER").writeText("50")
|
||||
sync()
|
||||
}
|
||||
val helpers = mutableListOf<Int>()
|
||||
val signals = mutableListOf<SentSignal>()
|
||||
val held = mutableListOf<String?>()
|
||||
@@ -507,6 +965,7 @@ class SessionSuspendControllerTest {
|
||||
var emptyGameTasks = false
|
||||
var rootGone = false
|
||||
var afterSleep: (() -> Unit)? = null
|
||||
var onAudioResume: (() -> Unit)? = null
|
||||
val control = File(tmp, ".dd-zram")
|
||||
val clock = File(tmp, ".dd-clock")
|
||||
var clockAtContinue: Long? = null
|
||||
@@ -522,9 +981,32 @@ class SessionSuspendControllerTest {
|
||||
var unacknowledged = -1
|
||||
var handlerStalls = false
|
||||
var handlerReplaced = false
|
||||
var spillFallsBack = false
|
||||
var spillSilent = false
|
||||
var restoreDelayMs = RESTORE_DELAY_MS
|
||||
val spills = mutableListOf<Pair<Int, Long>>()
|
||||
val restores = mutableListOf<Pair<Int, Int>>()
|
||||
val resumeAtContinue = mutableListOf<String?>()
|
||||
var lateSpillSeesTheCount = false
|
||||
var markerFails = false
|
||||
var workerStaysTraced = false
|
||||
var workerReleaseAt = -1L
|
||||
var readBackKills = false
|
||||
var readBacks = 0
|
||||
val gameResident get() = gameResidentKb
|
||||
private var spilling = false
|
||||
private var spilledBase: String? = null
|
||||
private var restoring = false
|
||||
private var restoredPending = false
|
||||
private var gameStopPending = false
|
||||
private var countSeenAt = -1L
|
||||
private var gameContinued = false
|
||||
var releasedBeforeContinue = false
|
||||
var ackFails = false
|
||||
private val resume = File(tmp, ".dd-zram.resume")
|
||||
private var continuing = false
|
||||
val controller = SessionSuspendController(
|
||||
{ rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++ },
|
||||
{ rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++; onAudioResume?.invoke() },
|
||||
proc, ::signal, ::threadSignal, ::sleep, { now }, executor,
|
||||
zramControl = control,
|
||||
clockControl = clock,
|
||||
@@ -535,12 +1017,15 @@ class SessionSuspendControllerTest {
|
||||
this.unacknowledged = unacknowledged
|
||||
},
|
||||
pagedIn = { processes, swap, swapBefore, _, _ -> pagedIn += Triple(processes, swap, swapBefore) },
|
||||
spilled = { processes, spilledKb, _, _ -> spills += processes to spilledKb },
|
||||
restored = { processes, unacknowledged, _, _ -> restores += processes to unacknowledged },
|
||||
)
|
||||
|
||||
init { sync() }
|
||||
|
||||
private fun signal(pid: Int, signal: Int) {
|
||||
signals += SentSignal(pid, signal)
|
||||
helperStep()
|
||||
val request = if (signal == URG) File(control.parentFile, "${control.name}.hold").takeIf { it.isFile }?.readText() else null
|
||||
if (signal == URG) held += request
|
||||
val group = groups.first { it.pid == pid }
|
||||
@@ -550,14 +1035,34 @@ class SessionSuspendControllerTest {
|
||||
else group.threads.firstOrNull {
|
||||
it.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && it == game.threads.last())
|
||||
}?.state = 't'
|
||||
} else if (signal == URG && pid == OTHER) {
|
||||
// a second guest that spills at once and whose helper reads back only when the test lets it
|
||||
if (request?.startsWith("4") == true) {
|
||||
File(control.parentFile, "${control.name}.ack.$OTHER").writeText("1000")
|
||||
otherHeld = true
|
||||
other.threads.forEach { it.state = 't' }
|
||||
}
|
||||
} else if (signal == URG) {
|
||||
if (request == "0") { pagingOut = false; pagingIn = true } else pagingOut = true
|
||||
if (request?.startsWith("4") == true) {
|
||||
if (!handlerReplaced) {
|
||||
spilling = true
|
||||
File(control.parentFile, "${control.name}.ack.$GAME").writeText("")
|
||||
}
|
||||
spilledBase = request.substringAfter(' ', "0").trim()
|
||||
}
|
||||
else if (request == "0") { pagingOut = false; pagingIn = true } else pagingOut = true
|
||||
} else if (signal == CONT) {
|
||||
if (pid == GAME) resumeAtContinue += resume.takeIf { it.isFile }?.readText()
|
||||
if (clockAtContinue == null && clock.isFile) {
|
||||
clockAtContinue = ByteBuffer.wrap(clock.readBytes()).order(ByteOrder.LITTLE_ENDIAN).long
|
||||
}
|
||||
continuing = true
|
||||
if (!(pid == GAME && blockGameContinue)) group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
|
||||
if (pid == GAME) gameStopPending = false
|
||||
if (pid == GAME) gameContinued = true
|
||||
// a spilled guest stays in its tracing stop until its helper has read the memory back
|
||||
if (!(pid == GAME && (blockGameContinue || parked)) && !(pid == OTHER && otherHeld)) {
|
||||
group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
|
||||
}
|
||||
}
|
||||
sync()
|
||||
}
|
||||
@@ -565,14 +1070,88 @@ class SessionSuspendControllerTest {
|
||||
private fun threadSignal(pid: Int, tid: Int, signal: Int) {
|
||||
signals += SentSignal(pid, signal)
|
||||
val task = groups.first { it.pid == pid }.threads.first { it.tid == tid }
|
||||
// held by the helper's trace: the stop stays pending until the helper detaches
|
||||
if (signal == STOP && pid == GAME && parked && task.state == 't') gameStopPending = true
|
||||
if (signal == STOP && task.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && task == game.threads.last())) {
|
||||
task.state = 't'
|
||||
}
|
||||
sync()
|
||||
}
|
||||
|
||||
private val parked get() = spilling || restoring
|
||||
|
||||
private fun releaseGame() {
|
||||
countSeenAt = -1L
|
||||
game.threads.forEach { if (it.state != 'Z') it.state = if (gameStopPending) 'T' else 'S' }
|
||||
}
|
||||
|
||||
fun advance(millis: Long) = sleep(millis)
|
||||
|
||||
// the handler takes the spill request only now, after the controller stopped waiting for it
|
||||
fun startLateSpill() {
|
||||
handlerReplaced = false
|
||||
spilling = true
|
||||
if (!ackFails) File(control.parentFile, "${control.name}.ack.$GAME").writeText("")
|
||||
}
|
||||
|
||||
// The helper reads back as soon as it sees a new count, SIGCONT or not; it detaches first and publishes
|
||||
// its marker on a later step.
|
||||
private fun helperStep() {
|
||||
val count = resume.takeIf { it.isFile }?.readText()?.trim() ?: "0"
|
||||
if (restoredPending) {
|
||||
restoredPending = false
|
||||
if (!markerFails) File(control.parentFile, "${control.name}.restored.$GAME").writeText("120")
|
||||
}
|
||||
if (workerReleaseAt in 0..now) {
|
||||
game.threads.last().tracer = null
|
||||
workerReleaseAt = -1L
|
||||
}
|
||||
if (!restoring || count == spilledBase) return
|
||||
if (countSeenAt < 0) {
|
||||
countSeenAt = now
|
||||
gameContinued = false
|
||||
}
|
||||
if (now - countSeenAt < restoreDelayMs) return
|
||||
restoring = false
|
||||
if (readBackKills) {
|
||||
// the helper kills its owner on a failed read-back; nobody has reaped it yet
|
||||
game.tracer = 0
|
||||
game.threads.forEach { it.state = 'Z' }
|
||||
countSeenAt = -1L
|
||||
return
|
||||
}
|
||||
readBacks++
|
||||
gameResidentKb = 4_000_000L
|
||||
if (markerFails) game.tracer = 0
|
||||
if (markerFails && workerStaysTraced) {
|
||||
game.threads.last().tracer = HELPER
|
||||
workerReleaseAt = now + 3_000L
|
||||
}
|
||||
if (!gameContinued) releasedBeforeContinue = true
|
||||
releaseGame()
|
||||
restoredPending = true
|
||||
}
|
||||
|
||||
private fun sleep(millis: Long) {
|
||||
now += millis
|
||||
val count = resume.takeIf { it.isFile }?.readText()?.trim() ?: "0"
|
||||
if (spilling && !spillSilent) {
|
||||
spilling = false
|
||||
val ack = File(control.parentFile, "${control.name}.ack.$GAME")
|
||||
if (lateSpillSeesTheCount && count != spilledBase) {
|
||||
ack.writeText("-2")
|
||||
releaseGame()
|
||||
} else if (spillFallsBack) {
|
||||
gameSwapKb += gameResidentKb
|
||||
gameResidentKb = 0L
|
||||
ack.writeText("0")
|
||||
} else {
|
||||
if (!ackFails) ack.writeText(gameResidentKb.toString())
|
||||
gameResidentKb = 0L
|
||||
restoring = true
|
||||
}
|
||||
}
|
||||
helperStep()
|
||||
if (pagingOut && !handlerReplaced) {
|
||||
File(control.parentFile, "${control.name}.ack.$GAME").apply { if (!exists()) writeText("") }
|
||||
}
|
||||
@@ -591,7 +1170,7 @@ class SessionSuspendControllerTest {
|
||||
gameResidentKb += moved
|
||||
if (gameSwapKb == 0L) pagingIn = false
|
||||
}
|
||||
if (root.threads.first().state != 'T' && !continuing) game.threads.forEach {
|
||||
if (root.threads.first().state != 'T' && !continuing && !parked) game.threads.forEach {
|
||||
if (it.state != 'Z') { it.state = 'S'; it.cpu++ }
|
||||
}
|
||||
afterSleep?.invoke()
|
||||
@@ -611,7 +1190,7 @@ class SessionSuspendControllerTest {
|
||||
"TracerPid: ${group.tracer}\n" +
|
||||
if (group == game) "VmRSS:\t$gameResidentKb kB\nVmSwap:\t$gameSwapKb kB\n" else "",
|
||||
)
|
||||
if (group == game) File(dir, "maps").writeText("7f00000000-7f00001000 r-xp 00000000 fe:05 42 /usr/local/lib/libddsession.so\n")
|
||||
if (group == game || group == other) File(dir, "maps").writeText("7f00000000-7f00001000 r-xp 00000000 fe:05 42 /usr/local/lib/libddsession.so\n")
|
||||
val taskDir = File(dir, "task")
|
||||
if (group == game && missingGameTasks) { taskDir.deleteRecursively(); continue }
|
||||
taskDir.mkdirs()
|
||||
@@ -619,6 +1198,7 @@ class SessionSuspendControllerTest {
|
||||
for (task in group.threads) {
|
||||
val entry = File(taskDir, task.tid.toString()).apply { mkdirs() }
|
||||
File(entry, "stat").writeText(stat(group, task))
|
||||
File(entry, "status").writeText("TracerPid: ${task.tracer ?: group.tracer}\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -661,5 +1241,8 @@ class SessionSuspendControllerTest {
|
||||
const val STOP = 19
|
||||
const val CONT = 18
|
||||
const val URG = 23
|
||||
const val RESTORE_DELAY_MS = 300L
|
||||
const val HELPER = 300
|
||||
const val OTHER = 400
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SuspendRecoveryTest {
|
||||
@Test fun theFirstAttemptIsDueAtOnceAndLaterOnesBackOff() {
|
||||
val recovery = SuspendRecovery(maxAttempts = 3, firstDelayMs = 1_000L)
|
||||
assertTrue(recovery.due(0L))
|
||||
assertEquals(1_000L, recovery.failed(0L))
|
||||
assertFalse(recovery.due(999L))
|
||||
assertTrue(recovery.due(1_000L))
|
||||
assertEquals(2_000L, recovery.failed(1_000L))
|
||||
assertFalse(recovery.due(2_999L))
|
||||
assertTrue(recovery.due(3_000L))
|
||||
}
|
||||
|
||||
// The service's loop: every policy pass (a 250 ms queued-launch poll, a display event or a scheduled retry)
|
||||
// starts a resume unless the recovery holds it; a failed resume schedules the next pass.
|
||||
private class Service(val recovery: SuspendRecovery = SuspendRecovery()) {
|
||||
var now = 0L
|
||||
var suspended = true
|
||||
var counterWritable = false
|
||||
var resumes = 0
|
||||
val scheduled = sortedSetOf<Long>()
|
||||
|
||||
fun pass() {
|
||||
if (!suspended || recovery.holds(true, now)) return
|
||||
resumes++
|
||||
if (counterWritable) {
|
||||
suspended = false
|
||||
recovery.reset()
|
||||
scheduled.clear()
|
||||
} else {
|
||||
recovery.failed(now)?.let { scheduled += now + it }
|
||||
}
|
||||
}
|
||||
|
||||
// Only a scheduled retry or a poll runs a pass; time with neither runs nothing.
|
||||
fun runUntil(end: Long, pollMs: Long? = null) {
|
||||
while (true) {
|
||||
val nextPoll = pollMs?.let { now - now % it + it } ?: Long.MAX_VALUE
|
||||
val next = minOf(nextPoll, scheduled.firstOrNull() ?: Long.MAX_VALUE)
|
||||
if (next > end) break
|
||||
now = next
|
||||
scheduled.remove(next)
|
||||
pass()
|
||||
}
|
||||
now = end
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun queuedLaunchPollsCannotExceedTheRetryBudget() {
|
||||
val service = Service()
|
||||
service.pass()
|
||||
service.runUntil(600_000L, pollMs = 250L)
|
||||
assertEquals(5, service.resumes)
|
||||
assertTrue(service.suspended)
|
||||
}
|
||||
|
||||
@Test fun aScheduledRetryResumesOnceTheCountCanBeWrittenWithoutAnotherEvent() {
|
||||
val service = Service()
|
||||
service.pass()
|
||||
assertEquals(1, service.resumes)
|
||||
assertEquals(listOf(5_000L), service.scheduled.toList())
|
||||
service.counterWritable = true
|
||||
service.runUntil(4_999L)
|
||||
assertTrue(service.suspended)
|
||||
service.runUntil(5_000L)
|
||||
assertFalse(service.suspended)
|
||||
assertEquals(2, service.resumes)
|
||||
}
|
||||
|
||||
@Test fun nothingResumesWithoutAScheduledRetryOrAnEvent() {
|
||||
val service = Service(SuspendRecovery(maxAttempts = 1))
|
||||
service.pass()
|
||||
assertTrue(service.scheduled.isEmpty())
|
||||
service.counterWritable = true
|
||||
service.runUntil(600_000L)
|
||||
assertTrue(service.suspended)
|
||||
assertEquals(1, service.resumes)
|
||||
}
|
||||
|
||||
@Test fun attemptsAreBoundedUntilAResumeSucceeds() {
|
||||
val recovery = SuspendRecovery(maxAttempts = 2, firstDelayMs = 1_000L)
|
||||
recovery.failed(0L)
|
||||
assertNull(recovery.failed(1_000L))
|
||||
assertFalse(recovery.due(1_000_000L))
|
||||
recovery.reset()
|
||||
assertTrue(recovery.due(0L))
|
||||
}
|
||||
}
|
||||
@@ -3,24 +3,31 @@ package com.droiddeck.launcher.ui
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.State
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.input.InputModeManager
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.semantics.SemanticsActions
|
||||
import androidx.compose.ui.test.assertIsFocused
|
||||
import androidx.compose.ui.test.ExperimentalTestApi
|
||||
import androidx.compose.ui.test.assertIsNotEnabled
|
||||
import androidx.compose.ui.test.getUnclippedBoundsInRoot
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performKeyInput
|
||||
import androidx.compose.ui.test.performSemanticsAction
|
||||
import androidx.compose.ui.test.pressKey
|
||||
import androidx.compose.ui.test.requestFocus
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.session.ComponentsManager
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
@@ -67,6 +74,29 @@ class ComponentDownloadsDrawerTest {
|
||||
assertEquals(listOf(nightly), requested)
|
||||
}
|
||||
|
||||
@Config(qualifiers = "w800dp-h800dp")
|
||||
@Test fun nightlySelectionSurvivesCrossingTheColumnThreshold() {
|
||||
val stable = ComponentsManager.CatalogItem("dxvk-3.1.1-linux.wcp", "dxvk", "Dxvk-Linux", "https://github.com/example/s", 100, "sha256:test")
|
||||
val nightly = ComponentsManager.CatalogItem("DD-dxvk-3.1.1+153-nightly.wcp", "dxvk", ComponentsManager.DD_NIGHTLY, "https://github.com/example/n", 100, "sha256:test")
|
||||
val twoColumns = mutableStateOf(false)
|
||||
lateinit var menu: MenuHost
|
||||
show(catalog = listOf(stable, nightly), twoColumns = twoColumns, captureHost = { menu = it })
|
||||
val chooser = compose.onNodeWithTag("cmp-download-dxvk")
|
||||
val nightlyRow = compose.onNodeWithText(nightly.file.removeSuffix(".wcp"))
|
||||
val narrowLeft = chooser.getUnclippedBoundsInRoot().left
|
||||
chooser.performSemanticsAction(SemanticsActions.OnClick)
|
||||
compose.onNodeWithText(RuntimeEnvironment.getApplication().getString(R.string.comp_channel_nightly)).performClick()
|
||||
nightlyRow.assertExists()
|
||||
compose.runOnIdle { menu.open = null; twoColumns.value = true }
|
||||
assertTrue(chooser.getUnclippedBoundsInRoot().left > narrowLeft)
|
||||
chooser.performSemanticsAction(SemanticsActions.OnClick)
|
||||
nightlyRow.assertExists()
|
||||
compose.runOnIdle { menu.open = null; twoColumns.value = false }
|
||||
assertEquals(narrowLeft, chooser.getUnclippedBoundsInRoot().left)
|
||||
chooser.performSemanticsAction(SemanticsActions.OnClick)
|
||||
nightlyRow.assertExists()
|
||||
}
|
||||
|
||||
@Test fun controllerPicksNightlyOnItsTabThenDownloadsItFromTheRow() {
|
||||
val stable = ComponentsManager.CatalogItem("dxvk-3.1.1-linux.wcp", "dxvk", "Dxvk-Linux", "https://github.com/example/s", 100, "sha256:test")
|
||||
val nightly = ComponentsManager.CatalogItem("DD-dxvk-3.1.1+153-nightly.wcp", "dxvk", ComponentsManager.DD_NIGHTLY, "https://github.com/example/n", 100, "sha256:test")
|
||||
@@ -107,18 +137,28 @@ class ComponentDownloadsDrawerTest {
|
||||
checking: Boolean = false,
|
||||
onRefresh: () -> Unit = {},
|
||||
onDownload: (ComponentsManager.CatalogItem) -> Unit = {},
|
||||
twoColumns: State<Boolean>? = null,
|
||||
captureHost: (MenuHost) -> Unit = {},
|
||||
) {
|
||||
compose.setContent {
|
||||
inputMode = LocalInputModeManager.current
|
||||
DroidDeckTheme {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
ComponentDownloadsDrawerGroup(
|
||||
host = rememberMenuHost(), catalog = catalog, catalogAt = 0,
|
||||
checking = checking,
|
||||
packages = listOf(ComponentsManager.Package(stored.file, "dxvk", "2.3", "", 100)),
|
||||
downloads = downloads, onRefresh = onRefresh, onDownload = onDownload,
|
||||
track = { Modifier.testTag(it) },
|
||||
)
|
||||
val host = rememberMenuHost()
|
||||
captureHost(host)
|
||||
val content: @androidx.compose.runtime.Composable () -> Unit = {
|
||||
ComponentDownloadsDrawerGroup(
|
||||
host = host, catalog = catalog, catalogAt = 0,
|
||||
checking = checking,
|
||||
packages = listOf(ComponentsManager.Package(stored.file, "dxvk", "2.3", "", 100)),
|
||||
downloads = downloads, onRefresh = onRefresh, onDownload = onDownload,
|
||||
track = { Modifier.testTag(it) },
|
||||
)
|
||||
}
|
||||
if (twoColumns == null) content() else DrawerColumns(twoColumns.value) {
|
||||
SettingsGroup("Profile") { Text("Profile settings") }
|
||||
content()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.test.getUnclippedBoundsInRoot
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], qualifiers = "w800dp-h600dp")
|
||||
class DrawerColumnsTest {
|
||||
@get:Rule val compose = createRobolectricComposeRule()
|
||||
|
||||
@Test fun theComponentNoteStaysInItsGroupAndSixGroupsSplitEvenly() {
|
||||
val note = "Component note"
|
||||
val componentRow = "Component row"
|
||||
compose.setContent {
|
||||
DroidDeckTheme {
|
||||
DrawerColumns(two = true) {
|
||||
repeat(3) { index -> Box(Modifier.height(32.dp).testTag("left-$index")) }
|
||||
DrawerComponentSettingsGroup(note) { Text(componentRow) }
|
||||
repeat(2) { index -> Box(Modifier.height(32.dp).testTag("right-$index")) }
|
||||
}
|
||||
}
|
||||
}
|
||||
val left = (0..2).map { compose.onNodeWithTag("left-$it").getUnclippedBoundsInRoot() }
|
||||
val right = (0..1).map { compose.onNodeWithTag("right-$it").getUnclippedBoundsInRoot() }
|
||||
val group = compose.onNodeWithText(componentRow).getUnclippedBoundsInRoot()
|
||||
val footer = compose.onNodeWithText(note).getUnclippedBoundsInRoot()
|
||||
assertTrue(left.all { it.left == left.first().left })
|
||||
assertTrue(right.all { it.left == right.first().left && it.left > left.first().left })
|
||||
assertTrue(group.left >= right.first().left)
|
||||
assertTrue(footer.left >= right.first().left)
|
||||
assertTrue(footer.top >= group.bottom)
|
||||
assertTrue(right.first().top >= footer.bottom)
|
||||
assertTrue(left.zipWithNext().all { (first, next) -> first.bottom <= next.top })
|
||||
}
|
||||
}
|
||||
@@ -25,17 +25,11 @@ class LibraryDisplayTest {
|
||||
assertFalse(LibraryDisplay.size)
|
||||
}
|
||||
|
||||
@Test fun storeBannerDefaultsOn() {
|
||||
assertTrue(LibraryDisplay.store)
|
||||
}
|
||||
|
||||
@Test fun savedChoicesStillLoad() {
|
||||
LibraryDisplay.toggleTitle(context)
|
||||
LibraryDisplay.toggleSize(context)
|
||||
LibraryDisplay.toggleStore(context)
|
||||
LibraryDisplay.load(context)
|
||||
assertTrue(LibraryDisplay.title)
|
||||
assertTrue(LibraryDisplay.size)
|
||||
assertFalse(LibraryDisplay.store)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
# Easy Anti-Cheat and BattlEye
|
||||
|
||||
On a Steam Deck, Proton loads Valve's anti-cheat runtimes (Proton EasyAntiCheat Runtime, app 1826330, and
|
||||
Proton BattlEye Runtime, app 1161040). Their bridge libraries are x86 only, so the ARM64 DroidDeck-Proton
|
||||
cannot load them. Games that need them run an x86-64 DroidDeck-Proton under FEX instead.
|
||||
|
||||
## Routing
|
||||
|
||||
The Proton launchers (`steam-compatibility`: the built-in DroidDeck-Proton launcher and the wrapper put around
|
||||
every tool in `compatibilitytools.d`) check each `run` and `waitforexitandrun` before any ARM64 setup:
|
||||
|
||||
- **Condition.** The game folder (`STEAM_COMPAT_INSTALL_PATH`, three levels deep) holds one of
|
||||
`EasyAntiCheat/Settings.json`, `easyanticheat_x64.so`, `BEClient_x64.so` or `BEService_x64.exe`. No
|
||||
title, app ID or device list is involved.
|
||||
- **Chosen tool.** Only launches through DroidDeck's own Proton (the built-in launcher or a `DroidDeck-Proton*`
|
||||
folder) are moved. A game set to any other tool, such as GE-Proton, Bionic or Valve's Proton, in DroidDeck or
|
||||
in Steam's Properties, runs on that tool and the launcher logs that it was chosen.
|
||||
- **Tool.** The newest `compatibilitytools.d/DroidDeck-Proton*` whose layout is x86-64
|
||||
(`files/lib/wine/x86_64-unix`, no `files/bin-arm64`).
|
||||
- **Runtime.** `PROTON_EAC_RUNTIME` or `PROTON_BATTLEYE_RUNTIME` when it already points at a folder with the
|
||||
bridge libraries, otherwise the runtime's folder in any Steam library.
|
||||
- **Launch.** `droiddeck-fex proton <tool>/proton <verb> <args>`: FEX with the Steam Linux Runtime rootfs,
|
||||
keeping the game's own `STEAM_COMPAT_DATA_PATH` prefix.
|
||||
|
||||
Without the x86-64 tool or the runtime files the launch stays on ARM64 and the launcher logs why.
|
||||
`DROIDDECK_ANTICHEAT=off` in the game's launch options keeps it on ARM64. Picking the x86-64 tool for a
|
||||
game in Steam always runs it under FEX.
|
||||
|
||||
## Why the x86-64 build needs its own Wine patches
|
||||
|
||||
Android kernels use 39-bit user address spaces. Easy Anti-Cheat's launcher maps fixed memory at
|
||||
`0x7001_0000_0000`, which FEX serves from emulated guest pages (`tools/fex/patches/0027`). Exclusive load and store pairs on that
|
||||
memory are emulated as a compare-and-swap, so hosts without LSE atomics work too. `tools/fex/probes/guest-high-memory.c`
|
||||
checks loads, stores, atomics, iovec system calls, `madvise` and code written through a high alias. The x86-64 Wine
|
||||
in DroidDeck-Proton carries `ntdll-fixed-allocations-above-host-address-limit.patch` (fixed mappings above
|
||||
the host limit go to the emulator) and `ntdll-keep-libc-in-native-syscall-dispatch-range.patch` (the
|
||||
re-armed syscall user dispatch range keeps libc native). Stock x86-64 Proton stops after "Hack native
|
||||
syscalls" on the same game.
|
||||
|
||||
Easy Anti-Cheat's launcher attaches to the game with ptrace, stops it on a `rt_sigprocmask` call, runs its
|
||||
own loader and restores the registers it saved at the stop. The call then returns `ENOSYS` without writing
|
||||
the old mask, as it does on a desktop kernel. `ntdll-retry-blocking-signals-dropped-by-a-tracer.patch`
|
||||
retries the block once when it fails, so Wine never restores an uninitialised mask that blocks `SIGSYS`.
|
||||
|
||||
## The container's procfs
|
||||
|
||||
Android mounts `/proc` with `hidepid=invisible,gid=3009`, and Easy Anti-Cheat refuses that mount with
|
||||
launch error 261. Without root, user namespaces or PID namespaces, no procfs instance without those options
|
||||
can be mounted. Every program in the container runs as the app's user and already sees all of the
|
||||
container's processes, as it would in a PID-namespaced sandbox on a desktop, so FEX's emulated
|
||||
`/proc/<pid>/mounts` and `/proc/<pid>/mountinfo` show the proc mount without `hidepid=`, `gid=` and
|
||||
`subset=` (`tools/fex/patches/0029`). Only x86 programs under FEX see this view; every other line of the
|
||||
table is the host's. Processes of other Android users stay hidden, as host processes do from a desktop
|
||||
sandbox.
|
||||
@@ -97,6 +97,22 @@ out, and resuming reads it back when available memory is at least twice what tho
|
||||
have in swap at that moment and, after it, 1 GiB or a tenth of RAM, whichever is larger, stays
|
||||
available.
|
||||
|
||||
## Writing a sleeping session to storage
|
||||
|
||||
With the `diskSpill` session pref on, the suspend for sleep writes each preloaded process's
|
||||
private memory to storage instead of zram (request `4`). The preload's worker starts a helper
|
||||
process that shares the process's memory, stops every other thread with ptrace (which also holds
|
||||
threads that block every signal, as Mesa's queue threads do, and which `SIGCONT` does not undo),
|
||||
writes readable private anonymous memory to an unlinked file next to the control file, drops it,
|
||||
and answers the kB it wrote in `/tmp/.dd-zram.ack.<pid>`. Regions registered with userfaultfd,
|
||||
locked or I/O memory and the preload's own memory stay. The app adds one to
|
||||
`/tmp/.dd-zram.resume` before it continues any process; the helper then reads everything back
|
||||
(through `/proc/<pid>/mem` where the pages are not writable), answers `/tmp/.dd-zram.restored.<pid>`
|
||||
and lets the threads go. A process that cannot be traced answers `0` and pages out to zram instead.
|
||||
|
||||
On an AYN Thor with Bully at its menu, 30 processes wrote 1,227 MB in 2.1 seconds and read it
|
||||
back in 1.3 seconds; system anonymous memory fell from 2.53 to 1.21 GB while asleep.
|
||||
|
||||
## Threads
|
||||
|
||||
When a worker can be started, page-out runs outside the game's threads. The preload's signal
|
||||
|
||||
@@ -216,9 +216,10 @@ alone would then read as an installed client.
|
||||
NullReferenceException, internal CLR errors). A writable mapping or mprotect now write-protects the
|
||||
overlapping part of any alias that is already executable, so the first write faults and invalidates.
|
||||
`FEX_SMCCHECKS=full` was the only workaround; no setting is needed with the patch.
|
||||
- `0007-cmake-install-code-without-depends`: CMake 4.5 rejects the `DEPENDS` argument FEX passes to
|
||||
`install(CODE ...)` for the guest thunk libraries, so builds with host thunks stopped at configure.
|
||||
The guest libraries are external projects in the default build, which `install` already follows.
|
||||
- `0007-cmake-install-code-without-depends` (`Fixed-upstream: FEX-2612`): CMake 4.5 rejects the
|
||||
`DEPENDS` argument FEX passes to `install(CODE ...)` for the guest thunk libraries, so builds with
|
||||
host thunks stopped at configure. The guest libraries are external projects in the default build,
|
||||
which `install` already follows.
|
||||
- `0008-signal-return-restores-syscall-state`: a guest `rt_sigreturn` is a system call, so FEX's
|
||||
syscall stub marks every static register as spilled (`InSyscallInfo = 0xFFFF`). When the handler
|
||||
left RIP alone, the return resumed the interrupted JIT code without passing the stub's reset, and
|
||||
|
||||
+10
-3
@@ -44,8 +44,10 @@ from what tripped agents up on real devices.
|
||||
running makes Steam show "Game already running" and `launch` time out.
|
||||
- Session scripts are APK assets, copied into the rootfs at every session start over any local
|
||||
edit. A Lab build (`dd-lab-build`, see `docs/lab-builds.md`) carries app code and resources only:
|
||||
session scripts, native code and assets need a new APK, such as the pull request's CI test build
|
||||
(DroidDeck > Updates > Test builds).
|
||||
session scripts, native code, assets and `AndroidManifest.xml` need a new APK, such as the pull
|
||||
request's CI test build (DroidDeck > Updates > Test builds). `dd-lab-build` refuses changes to the
|
||||
manifest, native code, Gradle files and a few startup classes, but builds session script and asset
|
||||
changes without them. To try the rest of a branch, build a copy without those changes.
|
||||
|
||||
## Changing DroidDeck
|
||||
|
||||
@@ -56,7 +58,12 @@ The source is checked out at `/root/DroidDeck` once the Agent tab's build tools
|
||||
- `dd-lab-build` builds the checkout as a Lab build and restarts DroidDeck on it. DroidDeck runs the
|
||||
build in a process of its own and shows its progress; `dd-lab-build` follows its log. Run it in
|
||||
the background and keep checking, so the user can talk to you meanwhile. The restart ends your
|
||||
process, and the conversation continues on the new build.
|
||||
process; DroidDeck starts you again on the new build, in the same conversation, so tell the user
|
||||
what you will check then instead of asking them to message you.
|
||||
- To try a change, commit it and go straight to `dd-lab-build`: it compiles the app, so a Gradle
|
||||
compile first only adds time. It refuses changes since the installed build (`apkCommit` in
|
||||
`droiddeckctl state`) that need a new APK. For a branch from a newer `origin/main`, cherry-pick
|
||||
its commits onto a branch from `apkCommit` and build that.
|
||||
- Python tests run from the repository root: `python3 -m unittest tools.tests.test_x`. Some fail on
|
||||
the device on `origin/main` too; run them on a worktree of `origin/main` before blaming a change.
|
||||
- Gradle runs on the device once the build tools are set up, but slowly: run the test classes that cover
|
||||
|
||||
@@ -63,6 +63,11 @@ cmake -S fex-src -B fex-build -G Ninja \
|
||||
${FEX_EXTRA_CXXFLAGS:+-DCMAKE_CXX_FLAGS="$FEX_EXTRA_CXXFLAGS"}
|
||||
ninja -C fex-build
|
||||
DESTDIR="$WORK/out" ninja -C fex-build install
|
||||
mkdir -p out/usr/local/share/fex-emu
|
||||
for p in tools/fex/patches/*.patch; do
|
||||
p=$(basename "$p" .patch)
|
||||
echo "${p#*-}"
|
||||
done > out/usr/local/share/fex-emu/.droiddeck-patches
|
||||
install -Dm755 /usr/bin/unsquashfs out/usr/local/bin/unsquashfs
|
||||
install -Dm644 "$(readlink -f /usr/lib/libxxhash.so.0)" out/usr/local/lib/libxxhash.so.0
|
||||
bundled=$(cd out/usr/local/lib && ls -- *.so* | sort -u)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
Fixed-upstream: FEX-2612
|
||||
diff --git a/CMakeLists.txt b/CMakeLists.txt
|
||||
index 8976588..3ae54f4 100644
|
||||
--- a/CMakeLists.txt
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
index b4c7b24..643185d 100644
|
||||
index 345f4d834..085ff00a2 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
@@ -264,12 +264,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
|
||||
@@ -283,12 +283,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
|
||||
auto Frame = Thread->CurrentFrame;
|
||||
|
||||
if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
|
||||
index 02bb6bf..2e72492 100644
|
||||
index 02bb6bfef..2e724929f 100644
|
||||
--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
|
||||
+++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
|
||||
@@ -49,6 +49,11 @@ struct X86ContextBackup {
|
||||
@@ -27,10 +27,10 @@ index 02bb6bf..2e72492 100644
|
||||
|
||||
// Arm64 doesn't have a red zone
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
index 643185d..53179c4 100644
|
||||
index 085ff00a2..5c79d1092 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
@@ -136,6 +136,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
|
||||
@@ -155,6 +155,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ index 643185d..53179c4 100644
|
||||
ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore::Core::InternalThreadState* Thread, int Signal, void* ucontext) {
|
||||
// We can end up getting a signal at any point in our host state
|
||||
// Jump to a handler that saves all state so we can safely return
|
||||
@@ -249,6 +274,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
|
||||
@@ -268,6 +293,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
|
||||
}
|
||||
|
||||
OldSP = *reinterpret_cast<uint64_t*>(GuestSP);
|
||||
@@ -82,7 +82,7 @@ index 643185d..53179c4 100644
|
||||
}
|
||||
|
||||
uintptr_t NewSP = OldSP;
|
||||
@@ -287,6 +325,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
@@ -306,6 +344,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
auto ContextBackup = StoreThreadState(Thread, Signal, ucontext);
|
||||
|
||||
auto Frame = Thread->CurrentFrame;
|
||||
@@ -90,7 +90,7 @@ index 643185d..53179c4 100644
|
||||
|
||||
// Ref count our faults
|
||||
// We use this to track if it is safe to clear cache
|
||||
@@ -336,6 +375,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
@@ -355,6 +394,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
|
||||
uint64_t OldGuestSP = Frame->State.gregs[FEXCore::X86State::REG_RSP];
|
||||
uint64_t NewGuestSP = OldGuestSP;
|
||||
@@ -99,7 +99,7 @@ index 643185d..53179c4 100644
|
||||
|
||||
// altstack is only used if the signal handler was setup with SA_ONSTACK
|
||||
if (GuestAction->sa_flags & SA_ONSTACK) {
|
||||
@@ -345,6 +386,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
@@ -364,6 +405,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
// Then that means we are hitting recursive signals and we need to walk back the stack correctly
|
||||
uint64_t AltStackBase = reinterpret_cast<uint64_t>(GuestStack->ss_sp);
|
||||
uint64_t AltStackEnd = AltStackBase + GuestStack->ss_size;
|
||||
@@ -108,7 +108,7 @@ index 643185d..53179c4 100644
|
||||
if (OldGuestSP >= AltStackBase && OldGuestSP <= AltStackEnd) {
|
||||
// We are already in the alt stack, the rest of the code will handle adjusting this
|
||||
} else {
|
||||
@@ -353,6 +396,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
@@ -372,6 +415,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,7 +149,7 @@ index 643185d..53179c4 100644
|
||||
// siginfo_t
|
||||
siginfo_t* HostSigInfo = reinterpret_cast<siginfo_t*>(info);
|
||||
|
||||
@@ -491,6 +568,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre
|
||||
@@ -510,6 +587,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre
|
||||
|
||||
// Our ref counting doesn't matter anymore
|
||||
Thread->CurrentFrame->SignalHandlerRefCounter = 0;
|
||||
@@ -159,7 +159,7 @@ index 643185d..53179c4 100644
|
||||
// Set the new PC
|
||||
if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext))) {
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
index dfcd4b0..e4a86a9 100644
|
||||
index 0f45cf68d..408cddf71 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
@@ -83,6 +83,9 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp
|
||||
index 1946dc946..9f04358c5 100644
|
||||
--- a/FEXCore/Source/Interface/Core/Core.cpp
|
||||
+++ b/FEXCore/Source/Interface/Core/Core.cpp
|
||||
@@ -383,7 +383,11 @@
|
||||
@@ -383,7 +383,11 @@ bool ContextImpl::InitCore() {
|
||||
}
|
||||
|
||||
void ContextImpl::HandleCallback(FEXCore::Core::InternalThreadState* Thread, uint64_t RIP) {
|
||||
@@ -15,9 +16,10 @@ diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/C
|
||||
|
||||
void ContextImpl::ExecuteThread(FEXCore::Core::InternalThreadState* Thread) {
|
||||
diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
||||
index ae3ed51e4..c5e656d2c 100644
|
||||
--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
||||
+++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
|
||||
@@ -305,6 +305,9 @@
|
||||
@@ -306,6 +306,9 @@ DEF_OP(Thunk) {
|
||||
|
||||
PushDynamicRegs(TMP1);
|
||||
|
||||
@@ -27,7 +29,7 @@ diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/In
|
||||
mov(ARMEmitter::Size::i64Bit, ARMEmitter::Reg::r0, GetReg(Op->ArgPtr));
|
||||
|
||||
InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash);
|
||||
@@ -320,6 +323,8 @@
|
||||
@@ -321,6 +324,8 @@ DEF_OP(Thunk) {
|
||||
FillStaticRegs({
|
||||
.NZCV = false,
|
||||
});
|
||||
@@ -37,9 +39,10 @@ diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/In
|
||||
|
||||
DEF_OP(ValidateCode) {
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
index 5c79d1092..e8e04b056 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
@@ -107,6 +107,10 @@
|
||||
@@ -126,6 +126,10 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
|
||||
#ifdef ARCHITECTURE_arm64
|
||||
Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext));
|
||||
|
||||
@@ -50,7 +53,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou
|
||||
for (size_t i = 0; i < Config.SRAGPRCount; i++) {
|
||||
const uint8_t SRAIdxMap = Config.SRAGPRMapping[i];
|
||||
if (IgnoreMask & (1U << SRAIdxMap)) {
|
||||
@@ -301,12 +305,10 @@
|
||||
@@ -320,12 +324,10 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
|
||||
if (Context->UContextLocation) {
|
||||
auto Frame = Thread->CurrentFrame;
|
||||
|
||||
@@ -67,7 +70,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou
|
||||
|
||||
if (Is64BitMode) {
|
||||
RestoreFrame_x64(Thread, Context, Frame, ucontext);
|
||||
@@ -361,6 +363,9 @@
|
||||
@@ -380,6 +382,9 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
|
||||
ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo;
|
||||
Thread->CurrentFrame->InSyscallInfo = 0;
|
||||
} else {
|
||||
@@ -78,9 +81,10 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou
|
||||
// This is likely to cause issues but in some cases it isn't fatal
|
||||
// This can also happen if we have put a signal on hold, then we just reenabled the signal
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
index fa6260954..e5d92e7c5 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
@@ -131,7 +131,7 @@
|
||||
@@ -131,7 +131,7 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa
|
||||
if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) {
|
||||
|
||||
// Restore previous `InSyscallInfo` structure.
|
||||
@@ -89,7 +93,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
|
||||
|
||||
// Hack! Go back to the top of the dispatcher top
|
||||
// This is only safe inside the JIT rather than anything outside of it
|
||||
@@ -211,7 +211,7 @@
|
||||
@@ -211,7 +211,7 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre
|
||||
// If the guest modified the RIP then we need to take special precautions here
|
||||
if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) {
|
||||
// Restore previous `InSyscallInfo` structure.
|
||||
@@ -98,7 +102,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
|
||||
|
||||
// Hack! Go back to the top of the dispatcher top
|
||||
// This is only safe inside the JIT rather than anything outside of it
|
||||
@@ -290,7 +290,7 @@
|
||||
@@ -290,7 +290,7 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th
|
||||
if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) {
|
||||
|
||||
// Restore previous `InSyscallInfo` structure.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
|
||||
index 9e6820bf6..43898e700 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
|
||||
@@ -263,6 +263,8 @@
|
||||
@@ -266,6 +266,8 @@ private:
|
||||
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
|
||||
void RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context,
|
||||
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
|
||||
@@ -11,9 +12,10 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Sourc
|
||||
///< Setup the signal frame for x64.
|
||||
uint64_t SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup,
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
index e5d92e7c5..38dc524f1 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
|
||||
@@ -122,6 +122,32 @@
|
||||
@@ -122,6 +122,32 @@ static void SetXStateInfo(T* xstate, bool is_avx_enabled) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +48,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
|
||||
void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context,
|
||||
FEXCore::Core::CpuStateFrame* Frame, void* ucontext) {
|
||||
auto* guest_uctx = reinterpret_cast<FEXCore::x86_64::ucontext_t*>(Context->UContextLocation);
|
||||
@@ -202,6 +228,27 @@
|
||||
@@ -202,6 +228,27 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa
|
||||
const auto modulo_i = (i + CurrentOffset) % 8;
|
||||
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], sizeof(Frame->State.mm[0]));
|
||||
}
|
||||
@@ -74,7 +76,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,6 +327,17 @@
|
||||
@@ -280,6 +327,17 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre
|
||||
const auto modulo_i = (i + CurrentOffset) % 8;
|
||||
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
|
||||
}
|
||||
@@ -92,7 +94,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
|
||||
}
|
||||
}
|
||||
|
||||
@@ -359,6 +417,17 @@
|
||||
@@ -359,6 +417,17 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th
|
||||
const auto modulo_i = (i + CurrentOffset) % 8;
|
||||
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
diff --git a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
|
||||
index 2881ad9..abc84f3 100644
|
||||
index dd2c18303..e7e88f8f2 100644
|
||||
--- a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
|
||||
+++ b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
|
||||
@@ -518,7 +518,7 @@ int main(int argc, char** argv, char** const envp) {
|
||||
@@ -524,7 +524,7 @@ int main(int argc, char** argv, char** const envp) {
|
||||
FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, Program.ProgramName);
|
||||
} else {
|
||||
// Anonymous program.
|
||||
@@ -12,7 +12,7 @@ index 2881ad9..abc84f3 100644
|
||||
}
|
||||
} else {
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
|
||||
index a7a432b..4a77d87 100644
|
||||
index a7a432bbd..4a77d8716 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
|
||||
@@ -441,7 +441,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,132 @@
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Subject: [PATCH] List only guest mappings in /proc/<pid>/maps on hosts below 47 address bits
|
||||
|
||||
Builds on StonkGuy's /proc emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
index eb12945e4..65b0521c9 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
@@ -17,7 +17,11 @@ $end_info$
|
||||
#include <FEXCore/Config/Config.h>
|
||||
#include <FEXCore/Core/Context.h>
|
||||
#include <FEXCore/Core/CPUID.h>
|
||||
+#include <FEXCore/Utils/Allocator.h>
|
||||
#include <FEXCore/Utils/LogManager.h>
|
||||
+#include <FEXCore/Utils/SignalScopeGuards.h>
|
||||
+#include <FEXCore/fextl/unordered_map.h>
|
||||
+#include <FEXCore/fextl/vector.h>
|
||||
#include <FEXCore/fextl/fmt.h>
|
||||
#include <FEXCore/fextl/string.h>
|
||||
#include <FEXCore/fextl/sstream.h>
|
||||
@@ -25,9 +29,13 @@ $end_info$
|
||||
|
||||
#include <git_version.h>
|
||||
|
||||
+#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
+#include <elf.h>
|
||||
+#include <mutex>
|
||||
+#include <shared_mutex>
|
||||
#include <fcntl.h>
|
||||
#include <filesystem>
|
||||
#include <ostream>
|
||||
@@ -609,6 +617,37 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx)
|
||||
|
||||
EmulatedFDManager::~EmulatedFDManager() {}
|
||||
|
||||
+static bool IsSelfProcPath(const char* Path) {
|
||||
+ const char* P = Path + 6;
|
||||
+ if (!isdigit(*P)) {
|
||||
+ return true;
|
||||
+ }
|
||||
+ return strtol(P, nullptr, 10) == ::getpid();
|
||||
+}
|
||||
+
|
||||
+static bool IsHostArchModule(const char* Path, fextl::unordered_map<fextl::string, bool>& Seen) {
|
||||
+ auto Known = Seen.find(Path);
|
||||
+ if (Known != Seen.end()) {
|
||||
+ return Known->second;
|
||||
+ }
|
||||
+ bool Host = false;
|
||||
+ int FD = ::open(Path, O_RDONLY | O_CLOEXEC);
|
||||
+ if (FD >= 0) {
|
||||
+ Elf64_Ehdr Header {};
|
||||
+ if (::pread(FD, &Header, sizeof(Header), 0) >= static_cast<ssize_t>(offsetof(Elf64_Ehdr, e_version)) &&
|
||||
+ memcmp(Header.e_ident, ELFMAG, SELFMAG) == 0) {
|
||||
+#if defined(__aarch64__)
|
||||
+ Host = Header.e_machine == EM_AARCH64;
|
||||
+#else
|
||||
+ Host = Header.e_machine != EM_X86_64 && Header.e_machine != EM_386;
|
||||
+#endif
|
||||
+ }
|
||||
+ ::close(FD);
|
||||
+ }
|
||||
+ Seen.emplace(Path, Host);
|
||||
+ return Host;
|
||||
+}
|
||||
+
|
||||
static bool IsProcMapsPath(const char* Path) {
|
||||
if (strncmp(Path, "/proc/", 6) != 0) {
|
||||
return false;
|
||||
@@ -661,14 +700,56 @@ int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd,
|
||||
::close(HostFD);
|
||||
|
||||
constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096;
|
||||
+ const bool HostSharesGuestRange = FEXCore::Allocator::GetHostVABits() < 47;
|
||||
+ const bool Self = IsSelfProcPath(pathname);
|
||||
+ fextl::vector<std::pair<uint64_t, uint64_t>> GuestRanges;
|
||||
+ if (HostSharesGuestRange && Self && FEX::HLE::_SyscallHandler) {
|
||||
+ auto lk = FEXCore::MaskSignalsAndLockMutex<std::shared_lock>(FEX::HLE::_SyscallHandler->VMATracking.Mutex);
|
||||
+ GuestRanges.reserve(FEX::HLE::_SyscallHandler->VMATracking.VMAs.size());
|
||||
+ for (const auto& [Base, VMA] : FEX::HLE::_SyscallHandler->VMATracking.VMAs) {
|
||||
+ if (!GuestRanges.empty() && GuestRanges.back().second >= Base) {
|
||||
+ GuestRanges.back().second = std::max(GuestRanges.back().second, Base + VMA.Length);
|
||||
+ } else {
|
||||
+ GuestRanges.emplace_back(Base, Base + VMA.Length);
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ auto IsGuestRange = [&GuestRanges](uint64_t Start, uint64_t End) {
|
||||
+ auto It = std::upper_bound(GuestRanges.begin(), GuestRanges.end(), Start,
|
||||
+ [](uint64_t Value, const std::pair<uint64_t, uint64_t>& Range) { return Value < Range.first; });
|
||||
+ if (It != GuestRanges.begin() && std::prev(It)->second > Start) {
|
||||
+ return true;
|
||||
+ }
|
||||
+ return It != GuestRanges.end() && It->first < End;
|
||||
+ };
|
||||
+ fextl::unordered_map<fextl::string, bool> ModuleArch;
|
||||
fextl::string Out;
|
||||
Out.reserve(In.size());
|
||||
size_t Pos = 0;
|
||||
while (Pos < In.size()) {
|
||||
size_t Eol = In.find('\n', Pos);
|
||||
const size_t End = Eol == fextl::string::npos ? In.size() : Eol + 1;
|
||||
- const uint64_t Start = strtoull(In.c_str() + Pos, nullptr, 16);
|
||||
- if (Start < X86_64TaskSizeMax) {
|
||||
+ char* Cursor {};
|
||||
+ const uint64_t Start = strtoull(In.c_str() + Pos, &Cursor, 16);
|
||||
+ const uint64_t Stop = *Cursor == '-' ? strtoull(Cursor + 1, nullptr, 16) : Start;
|
||||
+ bool Keep = Start < X86_64TaskSizeMax;
|
||||
+ if (Keep && HostSharesGuestRange) {
|
||||
+ if (Self) {
|
||||
+ Keep = IsGuestRange(Start, Stop);
|
||||
+ } else {
|
||||
+ const size_t LineEnd = Eol == fextl::string::npos ? In.size() : Eol;
|
||||
+ size_t Name = In.find_first_of("/[", Pos);
|
||||
+ if (Name != fextl::string::npos && Name < LineEnd) {
|
||||
+ fextl::string Path(In, Name, LineEnd - Name);
|
||||
+ if (Path.starts_with("[anon:FEX")) {
|
||||
+ Keep = false;
|
||||
+ } else if (Path[0] == '/') {
|
||||
+ Keep = !IsHostArchModule(Path.c_str(), ModuleArch);
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ if (Keep) {
|
||||
Out.append(In, Pos, End - Pos);
|
||||
}
|
||||
Pos = End;
|
||||
@@ -0,0 +1,53 @@
|
||||
From 597bfab6ff068e0f6c08f63d6940486446967b0d Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 2 Dec 2026 18:21:23 -0500
|
||||
Subject: [PATCH] Report the calling thread's seccomp mode in /proc/self/status
|
||||
|
||||
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
|
||||
---
|
||||
.../LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp | 6 +++++-
|
||||
.../Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h | 10 ++++++++++
|
||||
2 files changed, 15 insertions(+), 1 deletion(-)
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
index 65b0521c9..ce36b988b 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
@@ -797,7 +797,11 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd
|
||||
Buf[Len] = '\0';
|
||||
|
||||
uint32_t SeccompMode = SECCOMP_MODE_DISABLED;
|
||||
- if (auto* Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject()) {
|
||||
+ auto* Thread = FEX::HLE::_SyscallHandler ? FEX::HLE::_SyscallHandler->TM.FindThreadByTID(::gettid()) : nullptr;
|
||||
+ if (!Thread) {
|
||||
+ Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject();
|
||||
+ }
|
||||
+ if (Thread) {
|
||||
SeccompMode = Thread->SeccompMode;
|
||||
}
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
index 0a46703ca..9c5f9f1c2 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
@@ -290,6 +290,16 @@ public:
|
||||
return &Threads;
|
||||
}
|
||||
|
||||
+ FEX::HLE::ThreadStateObject* FindThreadByTID(uint32_t TID) {
|
||||
+ std::lock_guard lk(ThreadCreationMutex);
|
||||
+ for (auto* Thread : Threads) {
|
||||
+ if (Thread->ThreadInfo.TID == TID) {
|
||||
+ return Thread;
|
||||
+ }
|
||||
+ }
|
||||
+ return nullptr;
|
||||
+ }
|
||||
+
|
||||
private:
|
||||
struct InvalidationStats {
|
||||
explicit InvalidationStats(FEXCore::Core::InternalThreadState* Thread)
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
From ab6a01db9e93e7f143b9a3da5b40dcb160b960f3 Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 2 Dec 2026 18:25:20 -0500
|
||||
Subject: [PATCH] Read FEX's own /proc/self/status with a direct openat system
|
||||
call
|
||||
|
||||
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
|
||||
---
|
||||
FEXHeaderUtils/FEXHeaderUtils/Syscalls.h | 30 +++++++++++++++++++
|
||||
.../EmulatedFiles/EmulatedFiles.cpp | 3 +-
|
||||
.../LinuxSyscalls/PtraceEmu.cpp | 3 +-
|
||||
3 files changed, 34 insertions(+), 2 deletions(-)
|
||||
|
||||
diff --git a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h
|
||||
index dae3d3bcc..c0f3eb3ed 100644
|
||||
--- a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h
|
||||
+++ b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <FEXCore/Utils/LogManager.h>
|
||||
|
||||
#include <cstdint>
|
||||
+#include <errno.h>
|
||||
#include <sched.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
@@ -123,4 +124,33 @@ inline int32_t gettid() {
|
||||
|
||||
#endif
|
||||
|
||||
+#ifndef _WIN32
|
||||
+inline int32_t openat_kernel(int dirfd, const char* pathname, int flags) {
|
||||
+#if defined(__aarch64__)
|
||||
+ register long x0 asm("x0") = dirfd;
|
||||
+ register long x1 asm("x1") = reinterpret_cast<long>(pathname);
|
||||
+ register long x2 asm("x2") = flags;
|
||||
+ register long x3 asm("x3") = 0;
|
||||
+ register long x8 asm("x8") = SYS_openat;
|
||||
+ asm volatile("svc #0" : "+r"(x0) : "r"(x1), "r"(x2), "r"(x3), "r"(x8) : "memory");
|
||||
+ if (x0 < 0) {
|
||||
+ errno = static_cast<int>(-x0);
|
||||
+ return -1;
|
||||
+ }
|
||||
+ return static_cast<int32_t>(x0);
|
||||
+#elif defined(__x86_64__)
|
||||
+ long ret;
|
||||
+ register long r10 asm("r10") = 0;
|
||||
+ asm volatile("syscall" : "=a"(ret) : "a"(SYS_openat), "D"(dirfd), "S"(pathname), "d"(flags), "r"(r10) : "rcx", "r11", "memory");
|
||||
+ if (ret < 0) {
|
||||
+ errno = static_cast<int>(-ret);
|
||||
+ return -1;
|
||||
+ }
|
||||
+ return static_cast<int32_t>(ret);
|
||||
+#else
|
||||
+ return static_cast<int32_t>(::syscall(SYS_openat, dirfd, pathname, flags));
|
||||
+#endif
|
||||
+}
|
||||
+#endif
|
||||
+
|
||||
} // namespace FHU::Syscalls
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
index ce36b988b..19bfc814f 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
@@ -14,6 +14,7 @@ $end_info$
|
||||
#include "LinuxSyscalls/Syscalls.h"
|
||||
#include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h"
|
||||
|
||||
+#include <FEXHeaderUtils/Syscalls.h>
|
||||
#include <FEXCore/Config/Config.h>
|
||||
#include <FEXCore/Core/Context.h>
|
||||
#include <FEXCore/Core/CPUID.h>
|
||||
@@ -785,7 +786,7 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd
|
||||
char Buf[8192];
|
||||
ssize_t Len = 0;
|
||||
{
|
||||
- int HostFD = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC);
|
||||
+ int HostFD = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC);
|
||||
if (HostFD >= 0) {
|
||||
Len = ::read(HostFD, Buf, sizeof(Buf) - 1);
|
||||
::close(HostFD);
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
index ca4c86063..49ece24a3 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "LinuxSyscalls/PtraceEmu.h"
|
||||
#include "LinuxSyscalls/Syscalls.h"
|
||||
|
||||
+#include <FEXHeaderUtils/Syscalls.h>
|
||||
#include <FEXCore/Core/CoreState.h>
|
||||
#include <FEXCore/Core/X86Enums.h>
|
||||
|
||||
@@ -133,7 +134,7 @@ namespace {
|
||||
}
|
||||
|
||||
bool HasHostTracer() {
|
||||
- const int fd = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC);
|
||||
+ const int fd = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
return true;
|
||||
}
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
From 38ee3ef08d9bfd8312fccff688290572da82ef2a Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 2 Dec 2026 18:41:52 -0500
|
||||
Subject: [PATCH] Hand the tracee's ptrace state across exec
|
||||
|
||||
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
|
||||
---
|
||||
.../LinuxSyscalls/PtraceEmu.cpp | 54 ++++++++++++++++++-
|
||||
1 file changed, 53 insertions(+), 1 deletion(-)
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
index 49ece24a3..62acdb0da 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
@@ -266,6 +266,38 @@ namespace {
|
||||
::close(fd);
|
||||
}
|
||||
|
||||
+ bool AdoptionTried = false;
|
||||
+
|
||||
+ void AdoptSharedPage() {
|
||||
+ if (AdoptionTried || Current != &StaticState || !IsMainThread()) {
|
||||
+ return;
|
||||
+ }
|
||||
+ AdoptionTried = true;
|
||||
+ const int fd = OpenSidecar("state", ::getpid(), O_RDWR);
|
||||
+ if (fd < 0) {
|
||||
+ return;
|
||||
+ }
|
||||
+ if (!HasHostTracer()) {
|
||||
+ ::close(fd);
|
||||
+ return;
|
||||
+ }
|
||||
+ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
+ ::close(fd);
|
||||
+ if (Page == MAP_FAILED) {
|
||||
+ return;
|
||||
+ }
|
||||
+ auto* S = static_cast<SharedState*>(Page);
|
||||
+ if (S->Magic != SharedState::MagicValue) {
|
||||
+ ::munmap(Page, 4096);
|
||||
+ return;
|
||||
+ }
|
||||
+ S->Pending = 0;
|
||||
+ S->DirtyMask = 0;
|
||||
+ S->SignalNumber = 0;
|
||||
+ S->FlushLen = 0;
|
||||
+ Current = S;
|
||||
+ }
|
||||
+
|
||||
struct Remote {
|
||||
uint8_t* Mapped = nullptr;
|
||||
uintptr_t StaticAddr = 0;
|
||||
@@ -332,6 +364,22 @@ namespace {
|
||||
return &Remotes.emplace(Pid, std::move(R)).first->second;
|
||||
}
|
||||
|
||||
+ bool KeepAcrossExec(pid_t Pid) {
|
||||
+ {
|
||||
+ std::lock_guard lk(RemotesLock);
|
||||
+ auto It = Remotes.find(Pid);
|
||||
+ if (It != Remotes.end()) {
|
||||
+ return It->second.Mapped != nullptr;
|
||||
+ }
|
||||
+ }
|
||||
+ const int fd = OpenSidecar("state", Pid, O_RDONLY);
|
||||
+ if (fd < 0) {
|
||||
+ return false;
|
||||
+ }
|
||||
+ ::close(fd);
|
||||
+ return true;
|
||||
+ }
|
||||
+
|
||||
void Forget(pid_t Pid, bool Exited) {
|
||||
std::lock_guard lk(RemotesLock);
|
||||
auto It = Remotes.find(Pid);
|
||||
@@ -470,10 +518,12 @@ namespace {
|
||||
|
||||
|
||||
bool IsAttached() {
|
||||
+ AdoptSharedPage();
|
||||
return Current->Attached != 0;
|
||||
}
|
||||
|
||||
bool WantsSyscallStops() {
|
||||
+ AdoptSharedPage();
|
||||
return Current->SyscallStops && IsMainThread();
|
||||
}
|
||||
|
||||
@@ -610,7 +660,9 @@ bool FixupWaitStatus(pid_t Pid, int* Status) {
|
||||
|
||||
if ((St >> 16) == X86_PTRACE_EVENT_EXEC) {
|
||||
CaptureExecPath(Pid);
|
||||
- Forget(Pid, false);
|
||||
+ if (!KeepAcrossExec(Pid)) {
|
||||
+ Forget(Pid, false);
|
||||
+ }
|
||||
}
|
||||
|
||||
if (WSTOPSIG(St) == SIGSTOP) {
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
From 834075bdee10fb0a1c7a7f499a0bb97162370b5d Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 2 Dec 2026 18:58:13 -0500
|
||||
Subject: [PATCH] Serve emulated proc files by the requested path when the host
|
||||
returns a memfd
|
||||
|
||||
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
---
|
||||
.../LinuxEmulation/LinuxSyscalls/FileManagement.cpp | 11 +++++++----
|
||||
.../LinuxEmulation/LinuxSyscalls/FileManagement.h | 2 +-
|
||||
2 files changed, 8 insertions(+), 5 deletions(-)
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
|
||||
index 62b6a2d27..b76e96e58 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
|
||||
@@ -785,7 +785,7 @@ static int OpenatWithoutOpenat2(int DirFD, const char* Pathname, int Flags, uint
|
||||
return ::syscall(SYSCALL_DEF(openat), DirFD, Resolved, Flags, Mode);
|
||||
}
|
||||
|
||||
-bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) {
|
||||
+bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath) {
|
||||
char Tmp[PATH_MAX + 1];
|
||||
|
||||
if (fd < 0) {
|
||||
@@ -801,6 +801,9 @@ bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) {
|
||||
|
||||
// And try to open via EmuFD
|
||||
auto EmuFd = EmuFD.Open(Tmp, flags, mode);
|
||||
+ if (EmuFd == -1 && RequestedPath && RequestedPath[0] == '/' && strncmp(Tmp, "/memfd:", 7) == 0) {
|
||||
+ EmuFd = EmuFD.Open(RequestedPath, flags, mode);
|
||||
+ }
|
||||
if (EmuFd == -1) {
|
||||
return false;
|
||||
}
|
||||
@@ -841,7 +844,7 @@ uint64_t FileManager::Open(const char* pathname, int flags, uint32_t mode) {
|
||||
fd = ::open(SelfPath, flags, mode);
|
||||
}
|
||||
|
||||
- ReplaceEmuFd(fd, flags, mode);
|
||||
+ ReplaceEmuFd(fd, flags, mode, SelfPath);
|
||||
} else {
|
||||
fd = ::open(SelfPath, flags, mode);
|
||||
}
|
||||
@@ -1135,7 +1138,7 @@ uint64_t FileManager::Openat([[maybe_unused]] int dirfs, const char* pathname, i
|
||||
fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode);
|
||||
}
|
||||
|
||||
- ReplaceEmuFd(fd, flags, mode);
|
||||
+ ReplaceEmuFd(fd, flags, mode, SelfPath);
|
||||
} else {
|
||||
fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode);
|
||||
}
|
||||
@@ -1173,7 +1176,7 @@ uint64_t FileManager::Openat2(int dirfs, const char* pathname, FEX::HLE::open_ho
|
||||
fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize);
|
||||
}
|
||||
|
||||
- ReplaceEmuFd(fd, how->flags, how->mode);
|
||||
+ ReplaceEmuFd(fd, how->flags, how->mode, SelfPath);
|
||||
} else {
|
||||
fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize);
|
||||
}
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h
|
||||
index b11f096f7..a86539972 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h
|
||||
@@ -102,7 +102,7 @@ public:
|
||||
fextl::string GetEmulatedPath(const char* pathname, bool FollowSymlink = false) const;
|
||||
fextl::string GetHostPath(fextl::string& Path, bool AliasedOnly) const;
|
||||
|
||||
- bool ReplaceEmuFd(int fd, int flags, uint32_t mode);
|
||||
+ bool ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath);
|
||||
|
||||
#if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED
|
||||
void TrackFEXFD(int FD) noexcept {
|
||||
--
|
||||
2.43.0
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,58 @@
|
||||
From 0510284085165d39ef0eabb83e7604fe1bb74c76 Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Thu, 3 Dec 2026 03:26:13 -0500
|
||||
Subject: [PATCH] Show the guest command line when the argument area cannot be
|
||||
remapped
|
||||
|
||||
Kernels built without checkpoint/restore support refuse PR_SET_MM_MAP,
|
||||
so /proc/pid/cmdline kept showing the FEX invocation instead of the
|
||||
guest program and the argv rewrites it makes. For 64-bit guests whose
|
||||
arguments fit, the guest argument strings now live in the original
|
||||
argument area and argv points there, which needs no privilege.
|
||||
---
|
||||
Source/Tools/FEXInterpreter/ELFCodeLoader.h | 23 ++++++++++++++++++++-
|
||||
1 file changed, 22 insertions(+), 1 deletion(-)
|
||||
|
||||
diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
|
||||
index b1a72d227..6d2157365 100644
|
||||
--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h
|
||||
+++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
|
||||
@@ -874,13 +874,34 @@ public:
|
||||
|
||||
int r = prctl(PR_SET_MM, PR_SET_MM_MAP, &map, sizeof(map), 0L);
|
||||
if (r != 0) {
|
||||
- LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (prctl failed: result {}, errno {})", r, errno);
|
||||
+ int Error = errno;
|
||||
+ if (Is64BitMode() && MoveArgumentDataToHostArea(NewArgStart, ArgSize)) {
|
||||
+ return;
|
||||
+ }
|
||||
+ LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (prctl failed: result {}, errno {})", r, Error);
|
||||
}
|
||||
} else {
|
||||
LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (GetCurrentMap failed)");
|
||||
}
|
||||
}
|
||||
|
||||
+ bool MoveArgumentDataToHostArea(uintptr_t GuestArgStart, uint64_t ArgSize) {
|
||||
+ struct prctl_mm_map map {};
|
||||
+ if (!GetCurrentMap(map) || map.arg_end <= map.arg_start || ArgSize > map.arg_end - map.arg_start) {
|
||||
+ return false;
|
||||
+ }
|
||||
+
|
||||
+ auto HostArgs = reinterpret_cast<uint8_t*>(map.arg_start);
|
||||
+ memmove(HostArgs, reinterpret_cast<const void*>(GuestArgStart), ArgSize);
|
||||
+ memset(HostArgs + ArgSize, 0, map.arg_end - map.arg_start - ArgSize);
|
||||
+
|
||||
+ auto ArgumentPointers = reinterpret_cast<uint64_t*>(StackPointer + sizeof(uint64_t));
|
||||
+ for (size_t i = 0; i < ApplicationArgs.size(); ++i) {
|
||||
+ ArgumentPointers[i] = ArgumentPointers[i] - GuestArgStart + map.arg_start;
|
||||
+ }
|
||||
+ return true;
|
||||
+ }
|
||||
+
|
||||
// Setups the stack initial data (argv, envp, auxv)
|
||||
void SetupStack() {
|
||||
StackPointer += StackSize();
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
From fc926d0e9c63a3d5290a5d816029513349de78f6 Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Thu, 3 Dec 2026 08:03:20 -0500
|
||||
Subject: [PATCH] Describe the container's procfs in emulated mount tables
|
||||
|
||||
Android mounts /proc with hidepid=invisible,gid=3009 so an app cannot see the
|
||||
processes of other users. Every process of the container runs as the app's
|
||||
user, so the container sees all of its own processes, as it would through a
|
||||
procfs of its own in a PID namespace. The emulated /proc/<pid>/mounts and
|
||||
mountinfo now list the proc mount without the host instance's access options
|
||||
(hidepid, gid, subset). Every other mount is passed through unchanged.
|
||||
---
|
||||
.../EmulatedFiles/EmulatedFiles.cpp | 230 +++++++++++++-----
|
||||
.../EmulatedFiles/EmulatedFiles.h | 1 +
|
||||
2 files changed, 170 insertions(+), 61 deletions(-)
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
index 19bfc814f..85f1b3e15 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
@@ -37,6 +37,7 @@ $end_info$
|
||||
#include <elf.h>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
+#include <string_view>
|
||||
#include <fcntl.h>
|
||||
#include <filesystem>
|
||||
#include <ostream>
|
||||
@@ -649,6 +650,149 @@ static bool IsHostArchModule(const char* Path, fextl::unordered_map<fextl::strin
|
||||
return Host;
|
||||
}
|
||||
|
||||
+static bool ReadHostFile(const char* Path, fextl::string& Out) {
|
||||
+ int HostFD = ::open(Path, O_RDONLY | O_CLOEXEC);
|
||||
+ if (HostFD < 0) {
|
||||
+ return false;
|
||||
+ }
|
||||
+ char Buf[65536];
|
||||
+ for (;;) {
|
||||
+ const ssize_t Len = ::read(HostFD, Buf, sizeof(Buf));
|
||||
+ if (Len > 0) {
|
||||
+ Out.append(Buf, Len);
|
||||
+ } else if (Len == 0) {
|
||||
+ break;
|
||||
+ } else if (errno != EINTR) {
|
||||
+ LogMan::Msg::EFmt("Emulated /proc file: reading {} failed: {}", Path, errno);
|
||||
+ ::close(HostFD);
|
||||
+ return false;
|
||||
+ }
|
||||
+ }
|
||||
+ ::close(HostFD);
|
||||
+ return true;
|
||||
+}
|
||||
+
|
||||
+static int32_t SealedFileOf(const char* pathname, int32_t flags, const fextl::string& Data) {
|
||||
+ int NewFD = GenTmpFD(pathname, flags);
|
||||
+ if (NewFD < 0) {
|
||||
+ LogMan::Msg::EFmt("Emulated /proc file: memfd_create failed: {}", errno);
|
||||
+ return -1;
|
||||
+ }
|
||||
+ for (size_t Done = 0; Done < Data.size();) {
|
||||
+ const ssize_t Wrote = ::write(NewFD, Data.data() + Done, Data.size() - Done);
|
||||
+ if (Wrote > 0) {
|
||||
+ Done += Wrote;
|
||||
+ } else if (Wrote < 0 && errno == EINTR) {
|
||||
+ continue;
|
||||
+ } else {
|
||||
+ LogMan::Msg::EFmt("Emulated /proc file: writing the synthesized file failed: {}", errno);
|
||||
+ ::close(NewFD);
|
||||
+ return -1;
|
||||
+ }
|
||||
+ }
|
||||
+ if (::lseek(NewFD, 0, SEEK_SET) != 0) {
|
||||
+ LogMan::Msg::EFmt("Emulated /proc file: lseek failed: {}", errno);
|
||||
+ ::close(NewFD);
|
||||
+ return -1;
|
||||
+ }
|
||||
+ SealTmpFD(NewFD);
|
||||
+ return NewFD;
|
||||
+}
|
||||
+
|
||||
+static const char* ProcFileOfPid(const char* Path) {
|
||||
+ if (strncmp(Path, "/proc/", 6) != 0) {
|
||||
+ return nullptr;
|
||||
+ }
|
||||
+ const char* P = Path + 6;
|
||||
+ if (strncmp(P, "self/", 5) == 0) {
|
||||
+ return P + 5;
|
||||
+ }
|
||||
+ if (strncmp(P, "thread-self/", 12) == 0) {
|
||||
+ return P + 12;
|
||||
+ }
|
||||
+ if (!isdigit(*P)) {
|
||||
+ return P;
|
||||
+ }
|
||||
+ while (isdigit(*P)) {
|
||||
+ ++P;
|
||||
+ }
|
||||
+ if (*P++ != '/') {
|
||||
+ return nullptr;
|
||||
+ }
|
||||
+ if (strncmp(P, "task/", 5) == 0) {
|
||||
+ P += 5;
|
||||
+ if (!isdigit(*P)) {
|
||||
+ return nullptr;
|
||||
+ }
|
||||
+ while (isdigit(*P)) {
|
||||
+ ++P;
|
||||
+ }
|
||||
+ if (*P++ != '/') {
|
||||
+ return nullptr;
|
||||
+ }
|
||||
+ }
|
||||
+ return P;
|
||||
+}
|
||||
+
|
||||
+static bool IsProcMountTablePath(const char* Path) {
|
||||
+ const char* File = ProcFileOfPid(Path);
|
||||
+ return File && (strcmp(File, "mounts") == 0 || strcmp(File, "mountinfo") == 0);
|
||||
+}
|
||||
+
|
||||
+static fextl::string ContainerProcOptions(std::string_view Options) {
|
||||
+ fextl::string Out;
|
||||
+ size_t Pos = 0;
|
||||
+ while (Pos <= Options.size()) {
|
||||
+ size_t Comma = Options.find(',', Pos);
|
||||
+ if (Comma == std::string_view::npos) {
|
||||
+ Comma = Options.size();
|
||||
+ }
|
||||
+ const std::string_view Option = Options.substr(Pos, Comma - Pos);
|
||||
+ if (!Option.empty() && !Option.starts_with("hidepid=") && !Option.starts_with("gid=") && !Option.starts_with("subset=")) {
|
||||
+ if (!Out.empty()) {
|
||||
+ Out += ',';
|
||||
+ }
|
||||
+ Out.append(Option);
|
||||
+ }
|
||||
+ Pos = Comma + 1;
|
||||
+ }
|
||||
+ return Out;
|
||||
+}
|
||||
+
|
||||
+static fextl::string ContainerMountLine(std::string_view Line, bool MountInfo) {
|
||||
+ fextl::vector<std::string_view> Fields;
|
||||
+ size_t Pos = 0;
|
||||
+ while (Pos < Line.size()) {
|
||||
+ size_t Space = Line.find(' ', Pos);
|
||||
+ if (Space == std::string_view::npos) {
|
||||
+ Space = Line.size();
|
||||
+ }
|
||||
+ Fields.push_back(Line.substr(Pos, Space - Pos));
|
||||
+ Pos = Space + 1;
|
||||
+ }
|
||||
+ size_t Type = 2;
|
||||
+ if (MountInfo) {
|
||||
+ auto Dash = std::find(Fields.begin(), Fields.end(), std::string_view("-"));
|
||||
+ Type = static_cast<size_t>(Dash - Fields.begin()) + 1;
|
||||
+ }
|
||||
+ const size_t Options = MountInfo ? Type + 2 : Type + 1;
|
||||
+ if (Options >= Fields.size() || Fields[Type] != "proc") {
|
||||
+ return fextl::string(Line);
|
||||
+ }
|
||||
+ fextl::string Out;
|
||||
+ for (size_t i = 0; i < Fields.size(); ++i) {
|
||||
+ if (i) {
|
||||
+ Out += ' ';
|
||||
+ }
|
||||
+ if (i == Options) {
|
||||
+ Out += ContainerProcOptions(Fields[i]);
|
||||
+ } else {
|
||||
+ Out.append(Fields[i]);
|
||||
+ }
|
||||
+ }
|
||||
+ return Out;
|
||||
+}
|
||||
+
|
||||
static bool IsProcMapsPath(const char* Path) {
|
||||
if (strncmp(Path, "/proc/", 6) != 0) {
|
||||
return false;
|
||||
@@ -673,6 +817,9 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode)
|
||||
if (pathname && IsProcMapsPath(pathname)) {
|
||||
return ProcMaps(CTX, AT_FDCWD, pathname, flags, mode);
|
||||
}
|
||||
+ if (pathname && IsProcMountTablePath(pathname)) {
|
||||
+ return ProcMounts(CTX, AT_FDCWD, pathname, flags, mode);
|
||||
+ }
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -680,25 +827,10 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode)
|
||||
}
|
||||
|
||||
int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
|
||||
- int HostFD = ::open(pathname, O_RDONLY | O_CLOEXEC);
|
||||
- if (HostFD < 0) {
|
||||
- return -1;
|
||||
- }
|
||||
fextl::string In;
|
||||
- char Buf[65536];
|
||||
- for (;;) {
|
||||
- const ssize_t Len = ::read(HostFD, Buf, sizeof(Buf));
|
||||
- if (Len > 0) {
|
||||
- In.append(Buf, Len);
|
||||
- } else if (Len == 0) {
|
||||
- break;
|
||||
- } else if (errno != EINTR) {
|
||||
- LogMan::Msg::EFmt("ProcMaps: reading {} failed: {}", pathname, errno);
|
||||
- ::close(HostFD);
|
||||
- return -1;
|
||||
- }
|
||||
+ if (!ReadHostFile(pathname, In)) {
|
||||
+ return -1;
|
||||
}
|
||||
- ::close(HostFD);
|
||||
|
||||
constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096;
|
||||
const bool HostSharesGuestRange = FEXCore::Allocator::GetHostVABits() < 47;
|
||||
@@ -756,30 +888,29 @@ int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd,
|
||||
Pos = End;
|
||||
}
|
||||
|
||||
- int NewFD = GenTmpFD(pathname, flags);
|
||||
- if (NewFD < 0) {
|
||||
- LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno);
|
||||
+ return SealedFileOf(pathname, flags, Out);
|
||||
+}
|
||||
+
|
||||
+int32_t EmulatedFDManager::ProcMounts(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
|
||||
+ fextl::string In;
|
||||
+ if (!ReadHostFile(pathname, In)) {
|
||||
return -1;
|
||||
}
|
||||
- for (size_t Done = 0; Done < Out.size();) {
|
||||
- const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done);
|
||||
- if (Wrote > 0) {
|
||||
- Done += Wrote;
|
||||
- } else if (Wrote < 0 && errno == EINTR) {
|
||||
- continue;
|
||||
- } else {
|
||||
- LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno);
|
||||
- ::close(NewFD);
|
||||
- return -1;
|
||||
+ const char* File = ProcFileOfPid(pathname);
|
||||
+ const bool MountInfo = File && strcmp(File, "mountinfo") == 0;
|
||||
+ fextl::string Out;
|
||||
+ Out.reserve(In.size());
|
||||
+ size_t Pos = 0;
|
||||
+ while (Pos < In.size()) {
|
||||
+ size_t Eol = In.find('\n', Pos);
|
||||
+ const size_t LineEnd = Eol == fextl::string::npos ? In.size() : Eol;
|
||||
+ Out += ContainerMountLine(std::string_view(In).substr(Pos, LineEnd - Pos), MountInfo);
|
||||
+ if (Eol != fextl::string::npos) {
|
||||
+ Out += '\n';
|
||||
}
|
||||
+ Pos = LineEnd + 1;
|
||||
}
|
||||
- if (::lseek(NewFD, 0, SEEK_SET) != 0) {
|
||||
- LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno);
|
||||
- ::close(NewFD);
|
||||
- return -1;
|
||||
- }
|
||||
- SealTmpFD(NewFD);
|
||||
- return NewFD;
|
||||
+ return SealedFileOf(pathname, flags, Out);
|
||||
}
|
||||
|
||||
int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
|
||||
@@ -832,30 +963,7 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd
|
||||
Cursor = Eol + 1;
|
||||
}
|
||||
|
||||
- int NewFD = GenTmpFD(pathname, flags);
|
||||
- if (NewFD < 0) {
|
||||
- LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno);
|
||||
- return -1;
|
||||
- }
|
||||
- for (size_t Done = 0; Done < Out.size();) {
|
||||
- const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done);
|
||||
- if (Wrote > 0) {
|
||||
- Done += Wrote;
|
||||
- } else if (Wrote < 0 && errno == EINTR) {
|
||||
- continue;
|
||||
- } else {
|
||||
- LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno);
|
||||
- ::close(NewFD);
|
||||
- return -1;
|
||||
- }
|
||||
- }
|
||||
- if (::lseek(NewFD, 0, SEEK_SET) != 0) {
|
||||
- LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno);
|
||||
- ::close(NewFD);
|
||||
- return -1;
|
||||
- }
|
||||
- SealTmpFD(NewFD);
|
||||
- return NewFD;
|
||||
+ return SealedFileOf(pathname, flags, Out);
|
||||
}
|
||||
|
||||
int32_t EmulatedFDManager::ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h
|
||||
index b98ef4bda..b1ec241a7 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h
|
||||
@@ -35,6 +35,7 @@ private:
|
||||
|
||||
static int32_t ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
|
||||
static int32_t ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
|
||||
+ static int32_t ProcMounts(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
|
||||
static int32_t ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
|
||||
const uint32_t ThreadsConfig;
|
||||
};
|
||||
@@ -0,0 +1,92 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/uio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define HIGH ((uintptr_t)0x7e0000000000ULL)
|
||||
#define ALIAS ((uintptr_t)0x7e0000100000ULL)
|
||||
#define THREADS 4
|
||||
#define ITERS 200000
|
||||
|
||||
static volatile uint64_t *counter;
|
||||
static volatile uint64_t *cas;
|
||||
static int fails;
|
||||
|
||||
static void check(const char *name, int ok) {
|
||||
printf("%s %s\n", ok ? "PASS" : "FAIL", name);
|
||||
if (!ok) fails++;
|
||||
}
|
||||
|
||||
static void *worker(void *arg) {
|
||||
(void)arg;
|
||||
for (int i = 0; i < ITERS; i++) {
|
||||
__atomic_fetch_add(counter, 1, __ATOMIC_SEQ_CST);
|
||||
uint64_t old = __atomic_load_n(cas, __ATOMIC_RELAXED);
|
||||
while (!__atomic_compare_exchange_n(cas, &old, old + 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) {
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
alarm(60);
|
||||
uint8_t *high = mmap((void *)HIGH, 65536, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
|
||||
if (high == MAP_FAILED) {
|
||||
printf("NOTCLAIMED errno=%d\n", errno);
|
||||
return 0;
|
||||
}
|
||||
check("fixed-high-map", high == (uint8_t *)HIGH);
|
||||
memset(high, 0x5a, 65536);
|
||||
check("load-store", high[100] == 0x5a && high[65535] == 0x5a);
|
||||
|
||||
counter = (uint64_t *)(high + 64);
|
||||
cas = (uint64_t *)(high + 128);
|
||||
*counter = 0;
|
||||
*cas = 0;
|
||||
pthread_t t[THREADS];
|
||||
for (int i = 0; i < THREADS; i++) pthread_create(&t[i], NULL, worker, NULL);
|
||||
for (int i = 0; i < THREADS; i++) pthread_join(t[i], NULL);
|
||||
check("atomic-add", *counter == (uint64_t)THREADS * ITERS);
|
||||
check("atomic-cmpxchg", *cas == (uint64_t)THREADS * ITERS);
|
||||
|
||||
int p[2];
|
||||
check("pipe", pipe(p) == 0);
|
||||
memcpy(high + 4096, "hello ", 6);
|
||||
memcpy(high + 8192, "world", 5);
|
||||
struct iovec out[2] = {{high + 4096, 6}, {high + 8192, 5}};
|
||||
ssize_t w = writev(p[1], out, 2);
|
||||
memset(high + 12288, 0, 64);
|
||||
struct iovec in[2] = {{high + 12288, 3}, {high + 12291, 8}};
|
||||
ssize_t r = w == 11 ? readv(p[0], in, 2) : -1;
|
||||
check("writev-readv", w == 11 && r == 11 && memcmp(high + 12288, "hello world", 11) == 0);
|
||||
|
||||
int wrote = write(p[1], "abcdef", 6) == 6;
|
||||
check("write", wrote);
|
||||
check("read", wrote && read(p[0], high + 20000, 6) == 6 && memcmp(high + 20000, "abcdef", 6) == 0);
|
||||
|
||||
high[30000] = 7;
|
||||
check("madvise-dontneed", madvise(high + 28672, 4096, MADV_DONTNEED) == 0 && high[30000] == 0);
|
||||
|
||||
int fd = memfd_create("code", 0);
|
||||
check("memfd", fd >= 0 && ftruncate(fd, 4096) == 0);
|
||||
static const uint8_t code[] = {0xb8, 0x01, 0x00, 0x00, 0x00, 0xc3};
|
||||
check("pwrite", pwrite(fd, code, sizeof code, 0) == (ssize_t)sizeof code);
|
||||
uint8_t *low = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0);
|
||||
uint8_t *alias = mmap((void *)ALIAS, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0);
|
||||
check("alias-map", low != MAP_FAILED && alias == (uint8_t *)ALIAS);
|
||||
int (*fn)(void) = (int (*)(void))low;
|
||||
int before = fn();
|
||||
alias[1] = 2;
|
||||
__atomic_thread_fence(__ATOMIC_SEQ_CST);
|
||||
int after = fn();
|
||||
printf("alias before=%d after=%d\n", before, after);
|
||||
check("smc-through-high-alias", before == 1 && after == 2);
|
||||
|
||||
printf("%s\n", fails ? "RESULT FAIL" : "RESULT PASS");
|
||||
return fails != 0;
|
||||
}
|
||||
@@ -664,7 +664,7 @@ def data_dir(env):
|
||||
return DATA_DIR
|
||||
|
||||
|
||||
def guest_environment(fex, env):
|
||||
def guest_environment(fex, env, keep_compat=False):
|
||||
result = dict(env)
|
||||
data = data_dir(env)
|
||||
for directory in (CONFIG_DIR, data, CACHE_DIR):
|
||||
@@ -672,7 +672,7 @@ def guest_environment(fex, env):
|
||||
result["FEX_APP_CONFIG_LOCATION"] = CONFIG_DIR + "/"
|
||||
result["FEX_APP_DATA_LOCATION"] = data + "/"
|
||||
result["FEX_APP_CACHE_LOCATION"] = CACHE_DIR + "/"
|
||||
if result.get("STEAM_COMPAT_DATA_PATH"):
|
||||
if result.get("STEAM_COMPAT_DATA_PATH") and not keep_compat:
|
||||
short = data if data != DATA_DIR else "/tmp/fex"
|
||||
os.makedirs(short, exist_ok=True)
|
||||
result["STEAM_COMPAT_DATA_PATH"] = short
|
||||
@@ -750,9 +750,12 @@ def vulkan_thunk_loads(fex, folder):
|
||||
|
||||
|
||||
def required_runtime(program):
|
||||
text = read_text(os.path.join(os.path.dirname(program), "toolmanifest.vdf")) or ""
|
||||
match = re.search(r'"require_tool_appid"\s+"(\d+)"', text)
|
||||
return match.group(1) if match and match.group(1) in RUNTIMES else SNIPER_APPID
|
||||
folder = os.path.dirname(program)
|
||||
for name in ("toolmanifest.vdf.droiddeck-orig", "toolmanifest.vdf"):
|
||||
match = re.search(r'"require_tool_appid"\s+"(\d+)"', read_text(os.path.join(folder, name)) or "")
|
||||
if match and match.group(1) in RUNTIMES:
|
||||
return match.group(1)
|
||||
return SNIPER_APPID
|
||||
|
||||
|
||||
def resolve(program, env):
|
||||
@@ -761,7 +764,7 @@ def resolve(program, env):
|
||||
return shutil.which(program, path=env.get("PATH")) or program
|
||||
|
||||
|
||||
def launch(command, env, mode, decide=None):
|
||||
def launch(command, env, mode, decide=None, keep_compat=False):
|
||||
program = resolve(command[0], env)
|
||||
use = mode == "on" or (mode == "auto" and needs_fex(decide or program))
|
||||
if not use:
|
||||
@@ -769,7 +772,7 @@ def launch(command, env, mode, decide=None):
|
||||
fex = prepare(required_runtime(program))
|
||||
if fex is None:
|
||||
return 126
|
||||
guest = guest_environment(fex, env)
|
||||
guest = guest_environment(fex, env, keep_compat)
|
||||
x86_64 = elf_arch(program) != "i386"
|
||||
thunks = "on" if "FEX_THUNKCONFIG" in guest else "off"
|
||||
folder = decide if decide and os.path.isdir(decide) else os.path.dirname(program)
|
||||
@@ -963,7 +966,7 @@ def parse_run(args):
|
||||
|
||||
def main(argv):
|
||||
if not argv:
|
||||
say("usage: droiddeck-fex steam VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | status")
|
||||
say("usage: droiddeck-fex steam VERB CMD... | proton PROTON VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | update | status")
|
||||
return 2
|
||||
action, args = argv[0], list(argv[1:])
|
||||
if action == "steam":
|
||||
@@ -975,6 +978,10 @@ def main(argv):
|
||||
if not command:
|
||||
return 2
|
||||
return launch(command, game_environment(dict(os.environ), command), os.environ.get("DROIDDECK_FEX", "auto"))
|
||||
if action == "proton":
|
||||
if len(args) < 2:
|
||||
return 2
|
||||
return launch(args, game_environment(dict(os.environ), args[2:] or args), "on", keep_compat=True)
|
||||
if action == "run":
|
||||
try:
|
||||
mode, decide, command = parse_run(args)
|
||||
@@ -996,6 +1003,10 @@ def main(argv):
|
||||
return extract(args[0])
|
||||
if action == "prepare":
|
||||
return 0 if prepare() else 1
|
||||
if action == "update":
|
||||
with locked():
|
||||
update_own_fex()
|
||||
return 0
|
||||
if action == "status":
|
||||
with locked():
|
||||
status = describe(fex_install(), runtime_platform(), graphics_platform())
|
||||
|
||||
@@ -29,10 +29,14 @@ fex_install() {
|
||||
return 1
|
||||
fi
|
||||
(cd "$tmp/root" && find . ! -type d) > "$tmp/files"
|
||||
for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do
|
||||
[ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue
|
||||
(cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done
|
||||
done > "$tmp/stale"
|
||||
{
|
||||
for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do
|
||||
[ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue
|
||||
(cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done
|
||||
done
|
||||
f=usr/local/share/fex-emu/.droiddeck-patches
|
||||
if [ -e "$dst$f" ] && ! grep -qxF "./$f" "$tmp/files"; then echo "$f"; fi
|
||||
} > "$tmp/stale"
|
||||
mkdir "$tmp/old"
|
||||
while IFS= read -r f; do
|
||||
f=${f#./}
|
||||
|
||||
@@ -318,12 +318,72 @@ dd_vacdiag() {
|
||||
}
|
||||
"""
|
||||
|
||||
DD_ANTICHEAT_SETUP = """
|
||||
dd_anticheat_runtime() {
|
||||
local current=$1 name=$2 bridge=$3 library
|
||||
if [ -n "$current" ] && [ -n "$(find -L "$current" -iname "$bridge" -print -quit 2>/dev/null)" ]; then
|
||||
printf '%s' "$current"; return 0
|
||||
fi
|
||||
while IFS= read -r library; do
|
||||
[ -n "$(find "$library/steamapps/common/$name" -iname "$bridge" -print -quit 2>/dev/null)" ] || continue
|
||||
printf '%s' "$library/steamapps/common/$name"; return 0
|
||||
done < <(printf '%s\\n' "$DD_AC_ROOT" /mnt/droiddeck-sd; sed -n 's/^[[:space:]]*"path"[[:space:]]*"\\(.*\\)"[[:space:]]*$/\\1/p' "$DD_AC_ROOT/steamapps/libraryfolders.vdf" 2>/dev/null)
|
||||
return 1
|
||||
}
|
||||
|
||||
dd_x86_64_proton() {
|
||||
[ -d "$1/files/lib/wine/x86_64-unix" ] && [ ! -d "$1/files/bin-arm64" ]
|
||||
}
|
||||
|
||||
dd_anticheat() {
|
||||
case ${verb:-} in waitforexitandrun | run) ;; *) return 0 ;; esac
|
||||
case ${DROIDDECK_ANTICHEAT:-auto} in off | 0 | false) return 0 ;; esac
|
||||
local game=${STEAM_COMPAT_INSTALL_PATH:-} found tool runtime
|
||||
[ -d "$game" ] || return 0
|
||||
found=$(find "$game" -maxdepth 3 \\( -ipath '*/easyanticheat/settings.json' -o -iname 'easyanticheat_x64.so' \\
|
||||
-o -iname 'beclient_x64.so' -o -iname 'beservice_x64.exe' \\) -print -quit 2>/dev/null)
|
||||
[ -n "$found" ] || return 0
|
||||
case ${DD_AC_TOOL:-DroidDeck-Proton} in
|
||||
DroidDeck-Proton*) ;;
|
||||
*)
|
||||
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; ${DD_AC_TOOL} was chosen for this game, so it runs as chosen" >&2
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
/usr/local/bin/droiddeck-fex update || true
|
||||
if ! grep -qx fixed-guest-memory-above-host-address-limit /usr/local/share/fex-emu/.droiddeck-patches 2>/dev/null; then
|
||||
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; the installed FEX build cannot run anti-cheat, so this launch stays on ARM64" >&2
|
||||
return 0
|
||||
fi
|
||||
DD_AC_ROOT=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam}
|
||||
tool=$(cd "$DD_AC_ROOT/compatibilitytools.d" 2>/dev/null && for d in DroidDeck-Proton*; do
|
||||
[ -x "$d/proton" ] && dd_x86_64_proton "$d" && printf '%s/%s\\n' "$PWD" "$d"
|
||||
done | sort -V | tail -n 1)
|
||||
if [ -z "$tool" ]; then
|
||||
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; no x86-64 DroidDeck-Proton is installed, so this launch stays on ARM64" >&2
|
||||
return 0
|
||||
fi
|
||||
case ${found,,} in
|
||||
*easyanticheat*) runtime=$(dd_anticheat_runtime "${PROTON_EAC_RUNTIME:-}" "Proton EasyAntiCheat Runtime" easyanticheat_x64.so) && export PROTON_EAC_RUNTIME="$runtime" ;;
|
||||
*) runtime=$(dd_anticheat_runtime "${PROTON_BATTLEYE_RUNTIME:-}" "Proton BattlEye Runtime" beclient_x64.so) && export PROTON_BATTLEYE_RUNTIME="$runtime" ;;
|
||||
esac
|
||||
if [ -z "$runtime" ]; then
|
||||
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; its Proton runtime is not installed, so this launch stays on ARM64" >&2
|
||||
return 0
|
||||
fi
|
||||
dd_game_cpus
|
||||
declare -F dd_components >/dev/null && dd_components "$tool"
|
||||
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; running ${tool##*/} under FEX" >&2
|
||||
exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$tool/proton" "$verb" "$@"
|
||||
}
|
||||
"""
|
||||
|
||||
# DroidDeck-Bionic runs only without proot. With proot on, a launch Steam sends to a DroidDeck-Bionic tool goes to the
|
||||
# newest DroidDeck-Proton's wrapper before anything else runs, as if that Proton had been picked; the picks stay as set.
|
||||
DD_BIONIC_PROOT_FALLBACK = """
|
||||
if [ -f "$here/bionic/launch.sh" ] && [ -z "${DDNATV_ROOT:-}" ]; then
|
||||
dd_fallback=$(cd "$here/.." 2>/dev/null && for d in DroidDeck-Proton*; do
|
||||
[ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] || continue
|
||||
[ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] && ! dd_x86_64_proton "$d" || continue
|
||||
v=${d#DroidDeck-Proton}; printf '%s\\t%s/%s\\n' "${v#[ -]}" "$PWD" "$d"
|
||||
done | sort -V | tail -n 1 | cut -f 2-)
|
||||
if [ -n "$dd_fallback" ]; then
|
||||
@@ -461,6 +521,7 @@ for name in %s; do
|
||||
[ -n "$depot" ] && break
|
||||
done
|
||||
if [ -n "$depot" ]; then
|
||||
dd_anticheat "$@"
|
||||
dd_components "$depot"
|
||||
dd_directaudio "$depot" "$@"
|
||||
dd_game_cpus
|
||||
@@ -481,7 +542,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH
|
||||
def launcher_sh(sources=SOURCES):
|
||||
return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace(
|
||||
"verb=$1; shift", "verb=$1; shift\n" + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + DD_IDTECH3_SETUP
|
||||
+ DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1)
|
||||
+ DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP + DD_ANTICHEAT_SETUP, 1)
|
||||
|
||||
|
||||
LAUNCHER_SH = launcher_sh()
|
||||
@@ -516,6 +577,11 @@ if [ -n "${PROOT_FP_KEY:-}" ] && [ -f "$audit" ]; then
|
||||
*) LD_AUDIT="$audit${LD_AUDIT:+:$LD_AUDIT}"; export LD_AUDIT ;;
|
||||
esac
|
||||
fi
|
||||
if dd_x86_64_proton "$here"; then
|
||||
dd_game_cpus
|
||||
exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$here/%s" "$verb" "$@"
|
||||
fi
|
||||
DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@"
|
||||
dd_components "$here"
|
||||
dd_directaudio "$here" "$@"
|
||||
dd_game_cpus
|
||||
@@ -530,9 +596,9 @@ dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env "$DD_STORE_PROTON" "$ve
|
||||
|
||||
|
||||
def extra_wrapper_sh(entry_point):
|
||||
return (EXTRA_WRAPPER_SH % entry_point).replace(
|
||||
return (EXTRA_WRAPPER_SH % (entry_point, entry_point)).replace(
|
||||
'here=$(dirname "$0")',
|
||||
'here=$(dirname "$0")\n' + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
|
||||
'here=$(dirname "$0")\n' + DD_ANTICHEAT_SETUP + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
|
||||
+ DD_IDTECH3_SETUP + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1)
|
||||
|
||||
|
||||
@@ -1332,10 +1398,18 @@ def tool_catalog(steam_root, extras=None):
|
||||
continue
|
||||
extras[first_key(os.path.join(tool_dir, "compatibilitytool.vdf"), ["compatibilitytools", "compat_tools"]) or entry] = entry
|
||||
for name, entry in sorted(extras.items()):
|
||||
catalog.append(tool_entry(name, display_name(entry), os.path.join(tools, entry), False))
|
||||
tool = tool_entry(name, display_name(entry), os.path.join(tools, entry), False)
|
||||
if x86_64_layout(os.path.join(tools, entry)):
|
||||
tool["x86_64"] = True
|
||||
catalog.append(tool)
|
||||
return catalog
|
||||
|
||||
|
||||
def x86_64_layout(path):
|
||||
return (os.path.isdir(os.path.join(path, "files", "lib", "wine", "x86_64-unix")) and
|
||||
not os.path.isdir(os.path.join(path, "files", "bin-arm64")))
|
||||
|
||||
|
||||
def built_from(name, catalog, runnable=None):
|
||||
depot = VALVE_DEPOTS.get(name)
|
||||
tools = [t["name"] for t in catalog if depot and t["valve"] and t["dir"] == depot and
|
||||
@@ -1474,7 +1548,7 @@ ARCH_WORDS = re.compile(r"(?i)aarch64|arm64|x86_64|x86-64|amd64")
|
||||
|
||||
def own_builds(tools):
|
||||
return [t for t in tools if isinstance(t, dict) and not t.get("valve") and
|
||||
isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name")]
|
||||
isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name") and not t.get("x86_64")]
|
||||
|
||||
|
||||
def build_key(name):
|
||||
@@ -1512,7 +1586,8 @@ def choose_default(steam_default, state, request, catalog, adopt_steam=True, app
|
||||
wanted = requested_tool(request, catalog)
|
||||
state["applied"] = seq
|
||||
if wanted:
|
||||
if wanted != state.get("default"):
|
||||
if wanted != state.get("default") or (state.get("source") not in ("app", "steam") and any(
|
||||
t["name"] == wanted and t.get("x86_64") for t in catalog)):
|
||||
state.update(default=wanted, seq=now or now_ms(), source="app")
|
||||
else:
|
||||
print("steam-compatibility: the app asked for %s, which is not installed; kept %s" % (
|
||||
@@ -1709,7 +1784,11 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
|
||||
read_json(state_path("request.json", directory)), catalog)
|
||||
else:
|
||||
default = state.get("default") if state.get("default") in names else TOOL
|
||||
if settle and newest and default == TOOL and state.get("source") not in ("app", "steam"):
|
||||
automatic = state.get("source") not in ("app", "steam")
|
||||
if settle and automatic and default in {t["name"] for t in catalog if t.get("x86_64")}:
|
||||
default = newest or TOOL
|
||||
state.update(default=default, seq=now_ms(), source="update")
|
||||
elif settle and newest and default == TOOL and automatic:
|
||||
default = newest
|
||||
state.update(default=newest, seq=now_ms(), source="update")
|
||||
state.pop("own_proton", None)
|
||||
|
||||
@@ -957,8 +957,9 @@ __attribute__((visibility("hidden"))) void dd_vdec_closed(int fd) {
|
||||
|
||||
__attribute__((visibility("hidden"))) int dd_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms,
|
||||
int (*real)(struct pollfd *, nfds_t, int), int *ret) {
|
||||
if (n != 1 || vd_find(fds[0].fd) == NULL) return 0;
|
||||
if (n != 1 || __atomic_load_n(&vd_open_count, __ATOMIC_ACQUIRE) == 0) return 0;
|
||||
struct vdec *v = vd_find(fds[0].fd);
|
||||
if (v == NULL) return 0;
|
||||
pthread_mutex_lock(&vd_lock);
|
||||
short ready = (v->n_cap_done ? POLLIN | POLLRDNORM : 0) | (v->n_out_done ? POLLOUT | POLLWRNORM : 0);
|
||||
pthread_mutex_unlock(&vd_lock);
|
||||
|
||||
+495
-10
@@ -5,6 +5,7 @@
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
#include <signal.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -12,12 +13,17 @@
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/uio.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#if defined(__i386__)
|
||||
#include <asm/ldt.h>
|
||||
#endif
|
||||
#include <unistd.h>
|
||||
|
||||
|
||||
#ifndef PR_SET_SYSCALL_USER_DISPATCH
|
||||
#define PR_SET_SYSCALL_USER_DISPATCH 59
|
||||
#endif
|
||||
#ifndef MADV_PAGEOUT
|
||||
#define MADV_PAGEOUT 21
|
||||
#endif
|
||||
@@ -36,7 +42,18 @@
|
||||
#define ZR_INLINE_KB (32UL << 10)
|
||||
#define ZR_INLINE_CHUNKS 512UL
|
||||
#define ZR_FAILED (~0UL)
|
||||
#define ZR_CANCELLED (-2L)
|
||||
#define ZR_FUTEX_WAIT 0
|
||||
#define ZR_PTRACE_DETACH 17
|
||||
#define ZR_PTRACE_SEIZE 0x4206
|
||||
#define ZR_PTRACE_INTERRUPT 0x4207
|
||||
#define ZR_PTRACE_SETOPTIONS 0x4200
|
||||
#define ZR_PTRACE_O_EXITKILL (1 << 20)
|
||||
#define ZR_SPILL_CHUNK (8UL << 20)
|
||||
#define ZR_SPILL_RUNS ((16UL << 20) / sizeof(struct zr_run))
|
||||
#define ZR_SPILL_TIDS 8192
|
||||
#define ZR_PARK_MS 3000
|
||||
#define ZR_RESUME_POLL_MS 50
|
||||
#define ZR_STACK (128UL << 10)
|
||||
#define ZR_THREAD (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM | \
|
||||
CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID)
|
||||
@@ -202,6 +219,23 @@ static struct zr_slot {
|
||||
static uint16_t zr_gen = 1;
|
||||
static unsigned long zr_cursor;
|
||||
static unsigned long zr_visits;
|
||||
static struct zr_run {
|
||||
unsigned long addr, len, off, writable;
|
||||
} *zr_runs;
|
||||
static char *zr_bounce;
|
||||
static unsigned long zr_run_count;
|
||||
static long zr_owner;
|
||||
static long zr_reaper;
|
||||
static int zr_seized;
|
||||
static int zr_tids[ZR_SPILL_TIDS];
|
||||
static signed char zr_stopped[ZR_SPILL_TIDS];
|
||||
static unsigned char zr_signals[ZR_SPILL_TIDS];
|
||||
static char *zr_helper_stack;
|
||||
static int zr_helper_done;
|
||||
static int zr_helper_discarded;
|
||||
static int zr_helper_released;
|
||||
static unsigned long zr_helper_spilled;
|
||||
static unsigned long zr_baseline; // the resume count the spill was asked under
|
||||
|
||||
static int zr_prefix(const char *text, const char *prefix) {
|
||||
while (*prefix)
|
||||
@@ -209,6 +243,11 @@ static int zr_prefix(const char *text, const char *prefix) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// A named mapping never merges with the game's anonymous memory, so excluding it from a spill excludes only it.
|
||||
static void zr_name(long addr, unsigned long len) {
|
||||
zr_sys(SYS_prctl, 0x53564d41, 0, addr, len, "dd-zram");
|
||||
}
|
||||
|
||||
static char *zr_find(char *text, char c, size_t n) {
|
||||
for (; n > 0; n--, text++)
|
||||
if (*text == c) return text;
|
||||
@@ -217,11 +256,15 @@ static char *zr_find(char *text, char c, size_t n) {
|
||||
|
||||
static char zr_ctl[ZR_PATH] = ZR_CTL;
|
||||
static char zr_hold[ZR_PATH + sizeof(".hold")];
|
||||
static char zr_resume[ZR_PATH + sizeof(".resume")];
|
||||
|
||||
static int zr_open(const char *path) {
|
||||
return (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC, 0);
|
||||
}
|
||||
|
||||
// The number after a request's mode: kB to trim, or for a spill the resume count it was asked under.
|
||||
static unsigned long zr_request_arg;
|
||||
|
||||
static int zr_mode(unsigned long *want) {
|
||||
char text[24];
|
||||
long n = 0;
|
||||
@@ -236,12 +279,13 @@ static int zr_mode(unsigned long *want) {
|
||||
n = zr_sys(SYS_read, fd, text, sizeof(text));
|
||||
zr_sys(SYS_close, fd);
|
||||
}
|
||||
if (n < 1 || text[0] < '0' || text[0] > '3') return -1;
|
||||
if (n < 1 || text[0] < '0' || text[0] > '4') return -1;
|
||||
unsigned long kb = 0;
|
||||
for (long i = 2; i < n && text[i] >= '0' && text[i] <= '9'; i++)
|
||||
kb = kb * 10 + (unsigned long)(text[i] - '0');
|
||||
zr_request_arg = kb;
|
||||
*want = kb / (zr_page / 1024);
|
||||
if (text[0] >= '2' && *want == 0) return -1;
|
||||
if ((text[0] == '2' || text[0] == '3') && *want == 0) return -1;
|
||||
return text[0] - '0';
|
||||
}
|
||||
|
||||
@@ -416,42 +460,445 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns
|
||||
return done;
|
||||
}
|
||||
|
||||
static void zr_ack(long value, int trim) {
|
||||
const char *suffix = trim ? ".trim." : ".ack.";
|
||||
char path[sizeof(zr_ctl) + sizeof(".trim.") + 20];
|
||||
static void zr_ack(long value, const char *suffix) {
|
||||
char path[sizeof(zr_ctl) + sizeof(".restored.") + 20];
|
||||
char digits[20];
|
||||
size_t n = 0, d = 0;
|
||||
for (const char *p = zr_ctl; *p; p++) path[n++] = *p;
|
||||
for (const char *p = suffix; *p; p++) path[n++] = *p;
|
||||
long pid = zr_sys(SYS_getpid);
|
||||
long pid = __atomic_load_n(&zr_owner, __ATOMIC_ACQUIRE);
|
||||
if (pid == 0) pid = zr_sys(SYS_getpid);
|
||||
do digits[d++] = (char)('0' + pid % 10); while ((pid /= 10) > 0);
|
||||
while (d > 0) path[n++] = digits[--d];
|
||||
path[n] = 0;
|
||||
int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
|
||||
if (fd < 0) return;
|
||||
n = 0;
|
||||
if (value < -1) {
|
||||
path[n++] = '-';
|
||||
value = -value;
|
||||
}
|
||||
for (d = 0; value >= 0 && (d == 0 || value > 0); value /= 10) digits[d++] = (char)('0' + value % 10);
|
||||
for (n = 0; d > 0;) path[n++] = digits[--d];
|
||||
while (d > 0) path[n++] = digits[--d];
|
||||
if (n > 0) zr_sys(SYS_write, fd, path, n);
|
||||
zr_sys(SYS_close, fd);
|
||||
}
|
||||
|
||||
#if defined(__aarch64__)
|
||||
static int zr_read_small(const char *path, char *text, long size) {
|
||||
int fd = zr_open(path);
|
||||
if (fd < 0) return 0;
|
||||
long n;
|
||||
do n = zr_sys(SYS_read, fd, text, size); while (n == -EINTR);
|
||||
zr_sys(SYS_close, fd);
|
||||
return n > 0 ? (int)n : 0;
|
||||
}
|
||||
|
||||
static void zr_nap(int *word, int value, long ms) {
|
||||
struct { long sec, nsec; } wait = {ms / 1000, ms % 1000 * 1000000};
|
||||
zr_sys(SYS_futex, word, ZR_FUTEX_WAIT, value, &wait, NULL, 0);
|
||||
}
|
||||
|
||||
static long zr_now_ms(void) {
|
||||
struct { long sec, nsec; } now = {0, 0};
|
||||
zr_sys(SYS_clock_gettime, CLOCK_MONOTONIC, &now);
|
||||
return now.sec * 1000 + now.nsec / 1000000;
|
||||
}
|
||||
|
||||
static size_t zr_digits(char *out, long value) {
|
||||
char digits[20];
|
||||
size_t d = 0, n = 0;
|
||||
do digits[d++] = (char)('0' + value % 10); while ((value /= 10) > 0);
|
||||
while (d > 0) out[n++] = digits[--d];
|
||||
return n;
|
||||
}
|
||||
|
||||
static int zr_seized_index(long tid) {
|
||||
for (int i = 0; i < zr_seized; i++)
|
||||
if (zr_tids[i] == tid) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Seizes and interrupts the owner's threads it has not seized yet; returns how many it added, or -1.
|
||||
static long zr_seize_new(void) {
|
||||
char path[48] = "/proc/";
|
||||
size_t n = 6 + zr_digits(path + 6, zr_owner);
|
||||
for (const char *p = "/task"; *p; p++) path[n++] = *p;
|
||||
path[n] = 0;
|
||||
int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0);
|
||||
if (fd < 0) return -1;
|
||||
long added = 0, got;
|
||||
while ((got = zr_sys(SYS_getdents64, fd, zr_maps, sizeof(zr_maps))) > 0) {
|
||||
for (long at = 0; at < got;) {
|
||||
unsigned short reclen = *(unsigned short *)(zr_maps + at + 16);
|
||||
const char *name = zr_maps + at + 19;
|
||||
at += reclen;
|
||||
long tid = 0;
|
||||
for (const char *p = name; *p >= '0' && *p <= '9'; p++) tid = tid * 10 + (*p - '0');
|
||||
if (tid <= 0 || tid == zr_reaper || zr_seized_index(tid) >= 0) continue;
|
||||
if (zr_seized == ZR_SPILL_TIDS) {
|
||||
added = -1;
|
||||
break;
|
||||
}
|
||||
long r = zr_sys(SYS_ptrace, ZR_PTRACE_SEIZE, tid, 0, 0);
|
||||
if (r == -ESRCH) continue;
|
||||
if (r < 0) {
|
||||
added = -1;
|
||||
break;
|
||||
}
|
||||
zr_tids[zr_seized] = (int)tid;
|
||||
zr_signals[zr_seized] = 0;
|
||||
zr_stopped[zr_seized++] = 0;
|
||||
zr_sys(SYS_ptrace, ZR_PTRACE_INTERRUPT, tid, 0, 0);
|
||||
added++;
|
||||
}
|
||||
if (added < 0) break;
|
||||
}
|
||||
zr_sys(SYS_close, fd);
|
||||
return got < 0 ? -1 : added;
|
||||
}
|
||||
|
||||
static void zr_detach_all(void) {
|
||||
for (int i = 0; i < zr_seized; i++)
|
||||
if (zr_stopped[i] >= 0) zr_sys(SYS_ptrace, ZR_PTRACE_DETACH, zr_tids[i], 0, zr_signals[i]);
|
||||
zr_seized = 0;
|
||||
}
|
||||
|
||||
// A thread stopped by ptrace stays stopped whatever its signal mask, and SIGCONT does not start it again:
|
||||
// only the detach after the restore does.
|
||||
static int zr_seize_all(void) {
|
||||
zr_seized = 0;
|
||||
long start = zr_now_ms(), added;
|
||||
int idle = 0;
|
||||
do {
|
||||
added = zr_seize_new();
|
||||
if (added < 0) return 0;
|
||||
for (;;) {
|
||||
int status, waiting = 0;
|
||||
long tid;
|
||||
while ((tid = zr_sys(SYS_wait4, -1, &status, __WALL | WNOHANG, NULL)) > 0) {
|
||||
int i = zr_seized_index(tid);
|
||||
if (i < 0) continue;
|
||||
zr_stopped[i] = WIFSTOPPED(status) ? 1 : -1;
|
||||
// A signal that reached the thread before the interrupt stops it in that signal's delivery, which a
|
||||
// detach without the signal would drop.
|
||||
if (WIFSTOPPED(status) && (status >> 16) == 0) zr_signals[i] = (unsigned char)WSTOPSIG(status);
|
||||
}
|
||||
for (int i = 0; i < zr_seized; i++) waiting += zr_stopped[i] == 0;
|
||||
if (waiting == 0) break;
|
||||
if (zr_now_ms() - start >= ZR_PARK_MS) return 0;
|
||||
zr_nap(&idle, 0, 2);
|
||||
}
|
||||
} while (added > 0);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// The spill must not drop the memory it runs on: the stacks, this file's state and the run index.
|
||||
static int zr_own(unsigned long start, unsigned long end) {
|
||||
const unsigned long marks[] = {
|
||||
(unsigned long)zr_slots, (unsigned long)&zr_owner, (unsigned long)zr_maps, (unsigned long)zr_entries,
|
||||
(unsigned long)zr_tids, (unsigned long)zr_stack, (unsigned long)zr_runs, (unsigned long)zr_helper_stack,
|
||||
(unsigned long)zr_bounce,
|
||||
};
|
||||
for (unsigned long i = 0; i < sizeof(marks) / sizeof(marks[0]); i++)
|
||||
if (marks[i] >= start && marks[i] < end) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int zr_flag(const char *flags, char a, char b) {
|
||||
for (const char *p = flags; p[0] && p[1]; p++)
|
||||
if (p[0] == a && p[1] == b && (p == flags || p[-1] == ' ') && (p[2] == ' ' || p[2] == 0 || p[2] == '\n'))
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Private anonymous memory that can be read, whatever else its protection allows now.
|
||||
static int zr_spillable(const char *line, unsigned long *start, unsigned long *end, int *writable) {
|
||||
const char *p = line;
|
||||
*start = zr_hex(&p);
|
||||
if (*p++ != '-') return 0;
|
||||
*end = zr_hex(&p);
|
||||
if (*p++ != ' ' || p[0] != 'r' || p[3] != 'p') return 0;
|
||||
*writable = p[1] == 'w';
|
||||
for (int field = 0; field < 4; field++) {
|
||||
while (*p && *p != ' ') p++;
|
||||
while (*p == ' ') p++;
|
||||
}
|
||||
return *p == 0 || zr_prefix(p, "[heap]") || zr_prefix(p, "[stack]") || zr_prefix(p, "[anon:");
|
||||
}
|
||||
|
||||
static long zr_io(long call, int fd, unsigned long addr, unsigned long len, unsigned long off, int *direct) {
|
||||
unsigned long done = 0;
|
||||
while (done < len) {
|
||||
unsigned long step = len - done > ZR_SPILL_CHUNK ? ZR_SPILL_CHUNK : len - done;
|
||||
long n = zr_sys(call, fd, addr + done, step, off + done);
|
||||
if (n == -EINTR) continue;
|
||||
if (n == -EINVAL && *direct) {
|
||||
long flags = zr_sys(SYS_fcntl, fd, F_GETFL);
|
||||
if (flags < 0 || zr_sys(SYS_fcntl, fd, F_SETFL, flags & ~O_DIRECT) < 0) return -1;
|
||||
*direct = 0;
|
||||
continue;
|
||||
}
|
||||
if (n <= 0) return -1;
|
||||
// f2fs on an encrypted volume may serve O_DIRECT through the page cache without saying so.
|
||||
if (call == SYS_pwrite64) zr_sys(SYS_sync_file_range, fd, off + done, n, 7);
|
||||
zr_sys(SYS_fadvise64, fd, off + done, n, 4);
|
||||
done += (unsigned long)n;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Pages that cannot be written in place go back through /proc/<pid>/mem, which the tracer may write.
|
||||
static int zr_restore_run(int fd, int mem, const struct zr_run *run, int *direct) {
|
||||
if (run->writable) return (int)zr_io(SYS_pread64, fd, run->addr, run->len, run->off, direct);
|
||||
for (unsigned long done = 0; done < run->len; done += ZR_SPILL_CHUNK) {
|
||||
unsigned long step = run->len - done > ZR_SPILL_CHUNK ? ZR_SPILL_CHUNK : run->len - done;
|
||||
if (mem < 0 || zr_io(SYS_pread64, fd, (unsigned long)zr_bounce, step, run->off + done, direct) < 0) return -1;
|
||||
for (unsigned long put = 0; put < step;) {
|
||||
long n = zr_sys(SYS_pwrite64, mem, zr_bounce + put, step - put, run->addr + done + put);
|
||||
if (n == -EINTR) continue;
|
||||
if (n <= 0) return -1;
|
||||
put += (unsigned long)n;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static unsigned long zr_spill_range(int pagemap, int fd, unsigned long start, unsigned long end, int writable,
|
||||
unsigned long *off, int *direct, int *full) {
|
||||
unsigned long spilled = 0;
|
||||
for (unsigned long addr = start; addr < end && !*full;) {
|
||||
unsigned long count = (end - addr) / zr_page;
|
||||
if (count > ZR_BATCH) count = ZR_BATCH;
|
||||
if (zr_sys(SYS_lseek, pagemap, (long)(addr / zr_page * sizeof(uint64_t)), SEEK_SET) < 0) return spilled;
|
||||
long got = zr_sys(SYS_read, pagemap, zr_entries, count * sizeof(uint64_t));
|
||||
if (got < (long)sizeof(uint64_t)) return spilled;
|
||||
unsigned long pages = (unsigned long)got / sizeof(uint64_t);
|
||||
for (unsigned long i = 0; i < pages && !*full;) {
|
||||
if (!(zr_entries[i] & (ZR_PRESENT | ZR_SWAPPED))) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
unsigned long j = i;
|
||||
while (j < pages && (zr_entries[j] & (ZR_PRESENT | ZR_SWAPPED))) j++;
|
||||
unsigned long from = addr + i * zr_page, len = (j - i) * zr_page;
|
||||
if (zr_run_count == ZR_SPILL_RUNS || zr_io(SYS_pwrite64, fd, from, len, *off, direct) < 0) {
|
||||
*full = 1;
|
||||
break;
|
||||
}
|
||||
zr_helper_discarded = 1;
|
||||
if (zr_sys(SYS_madvise, from, len, MADV_DONTNEED) == 0) {
|
||||
zr_runs[zr_run_count++] = (struct zr_run){from, len, *off, (unsigned long)writable};
|
||||
*off += len;
|
||||
spilled += len;
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
addr += pages * zr_page;
|
||||
}
|
||||
return spilled;
|
||||
}
|
||||
|
||||
static unsigned long zr_spill_all(int fd, int *direct) {
|
||||
int smaps = zr_open("/proc/self/smaps");
|
||||
int pagemap = zr_open("/proc/self/pagemap");
|
||||
unsigned long spilled = 0, off = 0, s = 0, e = 0;
|
||||
int take = 0, full = 0, writable = 0;
|
||||
size_t have = 0;
|
||||
while (smaps >= 0 && pagemap >= 0 && !full) {
|
||||
long n = zr_sys(SYS_read, smaps, zr_maps + have, sizeof(zr_maps) - 1 - have);
|
||||
if (n == -EINTR) continue;
|
||||
if (n <= 0) break;
|
||||
have += (size_t)n;
|
||||
zr_maps[have] = 0;
|
||||
char *line = zr_maps, *nl;
|
||||
while (!full && (nl = zr_find(line, '\n', have - (size_t)(line - zr_maps))) != NULL) {
|
||||
*nl = 0;
|
||||
if ((line[0] >= '0' && line[0] <= '9') || (line[0] >= 'a' && line[0] <= 'f')) {
|
||||
take = zr_spillable(line, &s, &e, &writable) && e > s && !zr_own(s, e);
|
||||
} else if (take && zr_prefix(line, "VmFlags:")) {
|
||||
const char *flags = line + 8;
|
||||
// Tagged memory (mt) stays: dropping its pages drops the tags, which reading the bytes back cannot restore.
|
||||
if (!zr_flag(flags, 'u', 'm') && !zr_flag(flags, 'u', 'w') && !zr_flag(flags, 'l', 'o') &&
|
||||
!zr_flag(flags, 'i', 'o') && !zr_flag(flags, 'p', 'f') && !zr_flag(flags, 'm', 't'))
|
||||
spilled += zr_spill_range(pagemap, fd, s, e, writable, &off, direct, &full);
|
||||
take = 0;
|
||||
}
|
||||
line = nl + 1;
|
||||
}
|
||||
have -= (size_t)(line - zr_maps);
|
||||
for (size_t i = 0; i < have; i++) zr_maps[i] = line[i];
|
||||
if (have == sizeof(zr_maps) - 1) have = 0;
|
||||
}
|
||||
if (pagemap >= 0) zr_sys(SYS_close, pagemap);
|
||||
if (smaps >= 0) zr_sys(SYS_close, smaps);
|
||||
return spilled;
|
||||
}
|
||||
|
||||
static int zr_spill_file(void) {
|
||||
char path[sizeof(zr_ctl) + sizeof(".spill.") + 20];
|
||||
char digits[20];
|
||||
size_t n = 0, d = 0;
|
||||
for (const char *p = zr_ctl; *p; p++) path[n++] = *p;
|
||||
for (const char *p = ".spill."; *p; p++) path[n++] = *p;
|
||||
long pid = zr_sys(SYS_getpid);
|
||||
do digits[d++] = (char)('0' + pid % 10); while ((pid /= 10) > 0);
|
||||
while (d > 0) path[n++] = digits[--d];
|
||||
path[n] = 0;
|
||||
int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC | O_DIRECT, 0600);
|
||||
if (fd >= 0 && zr_sys(SYS_unlinkat, AT_FDCWD, path, 0) < 0) {
|
||||
zr_sys(SYS_close, fd);
|
||||
return -1;
|
||||
}
|
||||
return fd;
|
||||
}
|
||||
|
||||
// A count other than the request's; a marker that cannot be read is no resume.
|
||||
static int zr_resumed(void) {
|
||||
char now[24];
|
||||
int got = zr_read_small(zr_resume, now, sizeof(now));
|
||||
unsigned long count = 0;
|
||||
int digits = 0;
|
||||
for (int i = 0; i < got && now[i] >= '0' && now[i] <= '9'; i++, digits++) count = count * 10 + (unsigned long)(now[i] - '0');
|
||||
return digits > 0 && count != zr_baseline;
|
||||
}
|
||||
|
||||
// Runs in a process that shares the owner's memory, so it keeps running while every owner thread is stopped.
|
||||
// Once pages are dropped, the owner must not outlive a helper that ends without detaching: the kernel kills
|
||||
// every thread still traced when its tracer exits. Only a stopped tracee takes options, which all are here.
|
||||
static int zr_exit_kill(void) {
|
||||
for (int i = 0; i < zr_seized; i++) {
|
||||
if (zr_stopped[i] <= 0) continue;
|
||||
long r = zr_sys(SYS_ptrace, ZR_PTRACE_SETOPTIONS, zr_tids[i], 0, ZR_PTRACE_O_EXITKILL);
|
||||
if (r < 0 && r != -ESRCH) return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void zr_helper(void) {
|
||||
zr_sys(SYS_prctl, PR_SET_NAME, "zr-spill");
|
||||
if (!zr_seize_all() || zr_resumed() || !zr_exit_kill()) {
|
||||
zr_detach_all();
|
||||
return;
|
||||
}
|
||||
int fd = zr_spill_file();
|
||||
if (fd < 0) {
|
||||
zr_detach_all();
|
||||
return;
|
||||
}
|
||||
int direct = 1, idle = 0;
|
||||
zr_run_count = 0;
|
||||
unsigned long spilled = zr_spill_all(fd, &direct);
|
||||
zr_helper_spilled = spilled;
|
||||
zr_helper_done = 1;
|
||||
// nothing written (a full volume): the owner pages out to zram instead and acknowledges that
|
||||
if (spilled > 0) {
|
||||
zr_ack((long)(spilled / 1024), ".ack.");
|
||||
while (!zr_resumed()) {
|
||||
// reparented: the owner is gone and there is nothing to read back into
|
||||
if (zr_sys(SYS_getppid) != zr_owner) {
|
||||
zr_sys(SYS_close, fd);
|
||||
return;
|
||||
}
|
||||
zr_nap(&idle, 0, ZR_RESUME_POLL_MS);
|
||||
}
|
||||
long start = zr_now_ms();
|
||||
char path[48] = "/proc/";
|
||||
size_t n = 6 + zr_digits(path + 6, zr_owner);
|
||||
for (const char *p = "/mem"; *p; p++) path[n++] = *p;
|
||||
path[n] = 0;
|
||||
int mem = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDWR | O_CLOEXEC, 0);
|
||||
int restored = 1;
|
||||
for (unsigned long i = 0; i < zr_run_count; i++) {
|
||||
if (zr_restore_run(fd, mem, &zr_runs[i], &direct) < 0) {
|
||||
zr_sys(SYS_kill, zr_owner, SIGKILL);
|
||||
restored = 0;
|
||||
}
|
||||
}
|
||||
if (mem >= 0) zr_sys(SYS_close, mem);
|
||||
zr_sys(SYS_close, fd);
|
||||
zr_helper_released = restored;
|
||||
zr_detach_all();
|
||||
// after the detach, so a controller that sees the marker finds the process out of its tracing stop
|
||||
if (restored) zr_ack(zr_now_ms() - start, ".restored.");
|
||||
return;
|
||||
}
|
||||
zr_helper_released = 1;
|
||||
zr_sys(SYS_close, fd);
|
||||
zr_detach_all();
|
||||
}
|
||||
|
||||
static void *zr_area(unsigned long len) {
|
||||
long area = zr_sys(ZR_MMAP, 0, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
|
||||
if ((unsigned long)area > -4096UL) return NULL;
|
||||
zr_name(area, len);
|
||||
return (void *)area;
|
||||
}
|
||||
|
||||
static int zr_spill(void) {
|
||||
if (zr_runs == NULL) zr_runs = zr_area(ZR_SPILL_RUNS * sizeof(struct zr_run));
|
||||
if (zr_helper_stack == NULL) zr_helper_stack = zr_area(ZR_STACK);
|
||||
if (zr_bounce == NULL) zr_bounce = zr_area(ZR_SPILL_CHUNK);
|
||||
if (zr_runs == NULL || zr_helper_stack == NULL || zr_bounce == NULL) return 0;
|
||||
zr_baseline = zr_request_arg;
|
||||
zr_helper_done = 0;
|
||||
zr_helper_spilled = 0;
|
||||
zr_helper_discarded = 0;
|
||||
zr_helper_released = 0;
|
||||
zr_reaper = zr_sys(SYS_gettid);
|
||||
__atomic_store_n(&zr_owner, zr_sys(SYS_getpid), __ATOMIC_RELEASE);
|
||||
long child = zr_clone(CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SYSVSEM, zr_helper_stack + ZR_STACK, NULL, NULL, NULL);
|
||||
if (child > 0) {
|
||||
int status;
|
||||
while (zr_sys(SYS_wait4, child, &status, __WALL, NULL) == -EINTR) {
|
||||
}
|
||||
// A helper that ended between dropping pages and reading them back took them with it.
|
||||
if (zr_helper_discarded && !zr_helper_released) zr_sys(SYS_kill, zr_sys(SYS_getpid), SIGKILL);
|
||||
}
|
||||
__atomic_store_n(&zr_owner, 0, __ATOMIC_RELEASE);
|
||||
return child > 0 && zr_helper_done && zr_helper_spilled > 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
static void zr_request(int worker) {
|
||||
unsigned long want = 0;
|
||||
int mode = zr_mode(&want);
|
||||
if (mode < 0) return;
|
||||
if (mode == 4) {
|
||||
// A request that reaches this after the resume it was asked before has nothing left to do: the
|
||||
// controller no longer waits for it, and holding the process now would stop it after the resume.
|
||||
#if defined(__aarch64__)
|
||||
zr_baseline = zr_request_arg;
|
||||
if (zr_resumed()) return;
|
||||
#endif
|
||||
zr_ack(-1, ".ack.");
|
||||
#if defined(__aarch64__)
|
||||
if (worker && zr_spill()) return;
|
||||
// it acknowledged the start, so the controller waits for a final answer
|
||||
if (zr_resumed()) {
|
||||
zr_ack(ZR_CANCELLED, ".ack.");
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
zr_visits = worker ? ZR_FAILED : ZR_INLINE_CHUNKS;
|
||||
zr_walk(1, 1, 0, 0);
|
||||
zr_gen++;
|
||||
zr_ack(0, ".ack.");
|
||||
return;
|
||||
}
|
||||
if (!worker && want > ZR_INLINE_KB / (zr_page / 1024)) want = ZR_INLINE_KB / (zr_page / 1024);
|
||||
zr_visits = worker ? ZR_FAILED : ZR_INLINE_CHUNKS;
|
||||
if (mode > 0) zr_ack(-1, mode > 1);
|
||||
if (mode > 0) zr_ack(-1, mode > 1 ? ".trim." : ".ack.");
|
||||
if (mode < 2) {
|
||||
zr_walk(mode, 1, 0, 0);
|
||||
zr_gen++;
|
||||
if (mode == 1) zr_ack(1, 0);
|
||||
if (mode == 1) zr_ack(1, ".ack.");
|
||||
return;
|
||||
}
|
||||
unsigned long from = zr_cursor;
|
||||
unsigned long done = zr_walk(mode, want, from, ~0UL);
|
||||
if (done < want && from > 0) done += zr_walk(mode, want - done, 0, from);
|
||||
zr_ack((long)(done * (zr_page / 1024)), 1);
|
||||
zr_ack((long)(done * (zr_page / 1024)), ".trim.");
|
||||
}
|
||||
|
||||
static void zr_drain(int worker) {
|
||||
@@ -463,6 +910,13 @@ static void zr_drain(int worker) {
|
||||
}
|
||||
|
||||
void zr_thread(void) {
|
||||
#if defined(__aarch64__)
|
||||
long owner = __atomic_load_n(&zr_owner, __ATOMIC_ACQUIRE);
|
||||
if (owner != 0 && zr_sys(SYS_getpid) != owner) {
|
||||
zr_helper();
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
zr_sys(SYS_prctl, PR_SET_NAME, "zr-worker");
|
||||
zr_drain(1);
|
||||
}
|
||||
@@ -520,6 +974,7 @@ static int zr_start(void) {
|
||||
MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_NORESERVE, -1, 0);
|
||||
if ((unsigned long)base > -4096UL) return 0;
|
||||
zr_stack = (char *)base;
|
||||
zr_name(base, ZR_STACK);
|
||||
}
|
||||
struct { long sec, nsec; } wait = {0, 5000000};
|
||||
for (int i = 0; i < 20 && __atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE); i++)
|
||||
@@ -538,16 +993,44 @@ static int zr_start(void) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static __thread volatile unsigned char *zr_dispatch __attribute__((tls_model("initial-exec")));
|
||||
|
||||
int prctl(int option, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, option);
|
||||
unsigned long arg2 = va_arg(ap, unsigned long);
|
||||
unsigned long arg3 = va_arg(ap, unsigned long);
|
||||
unsigned long arg4 = va_arg(ap, unsigned long);
|
||||
unsigned long arg5 = va_arg(ap, unsigned long);
|
||||
va_end(ap);
|
||||
volatile unsigned char *dispatch = zr_dispatch;
|
||||
unsigned char selector = dispatch != NULL ? *dispatch : 0;
|
||||
if (selector) *dispatch = 0;
|
||||
long result = zr_sys(SYS_prctl, option, arg2, arg3, arg4, arg5);
|
||||
if (selector) *dispatch = selector;
|
||||
if ((unsigned long)result > -4096UL) {
|
||||
errno = (int)-result;
|
||||
return -1;
|
||||
}
|
||||
if (option == PR_SET_SYSCALL_USER_DISPATCH) zr_dispatch = arg2 ? (volatile unsigned char *)arg5 : NULL;
|
||||
return (int)result;
|
||||
}
|
||||
|
||||
static void zr_handler(int sig, siginfo_t *info, void *context) {
|
||||
(void)sig;
|
||||
(void)context;
|
||||
if (info == NULL || info->si_code != SI_USER) return;
|
||||
volatile unsigned char *dispatch = zr_dispatch;
|
||||
unsigned char selector = dispatch != NULL ? *dispatch : 0;
|
||||
if (selector) *dispatch = 0;
|
||||
int saved = errno;
|
||||
if (__atomic_fetch_add(&zr_requests, 1, __ATOMIC_ACQ_REL) == 0 && !zr_start()) zr_drain(0);
|
||||
errno = saved;
|
||||
if (selector) *dispatch = selector;
|
||||
}
|
||||
|
||||
static void zr_child(void) {
|
||||
__atomic_store_n(&zr_owner, 0, __ATOMIC_RELEASE);
|
||||
__atomic_store_n(&zr_requests, 0, __ATOMIC_RELEASE);
|
||||
__atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE);
|
||||
}
|
||||
@@ -564,6 +1047,8 @@ static void zr_paths(void) {
|
||||
size_t n = strlen(zr_ctl);
|
||||
memcpy(zr_hold, zr_ctl, n);
|
||||
memcpy(zr_hold + n, ".hold", sizeof(".hold"));
|
||||
memcpy(zr_resume, zr_ctl, n);
|
||||
memcpy(zr_resume + n, ".resume", sizeof(".resume"));
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void zr_init(void) {
|
||||
|
||||
@@ -374,6 +374,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
}
|
||||
if (is_proc_self_exe(filename) && g_real_exe[0] != '\0') filename = g_real_exe;
|
||||
if (depth == 0 && !in_exec_rehearsal()) ddh_try(filename, argv, envp);
|
||||
|
||||
// Scripts get the path exactly as the caller wrote it ("./x.sh" stays "./x.sh" in $0),
|
||||
|
||||
@@ -422,6 +422,7 @@ static ssize_t copy_readlink_result(char *buf, size_t bufsiz, const char *out, s
|
||||
if (ret <= 0 || out == buf) return ret;
|
||||
size_t n = (size_t)ret < bufsiz ? (size_t)ret : bufsiz;
|
||||
memcpy(buf, out, n);
|
||||
if (n < bufsiz) buf[n] = '\0';
|
||||
return (ssize_t)n;
|
||||
}
|
||||
|
||||
@@ -454,6 +455,7 @@ ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) {
|
||||
ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) {
|
||||
static ssize_t (*orig_readlinkat)(int, const char *, char *, size_t) = NULL;
|
||||
if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat");
|
||||
const char *given = pathname;
|
||||
DDNATV_AT_REMAP(dirfd, pathname);
|
||||
// after the remap: "proc/self/exe" relative to a descriptor for "/" is /proc/self/exe as well
|
||||
{
|
||||
@@ -478,7 +480,7 @@ ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) {
|
||||
const char *retry = usrmerge_retry_path(target, alt, sizeof(alt));
|
||||
if (retry) ret = orig_readlinkat(dirfd, retry, out, outsiz);
|
||||
}
|
||||
return copy_readlink_result(buf, bufsiz, out, postprocess_readlink(pathname, out, ret, outsiz));
|
||||
return copy_readlink_result(buf, bufsiz, out, postprocess_named_readlink(pathname, pathname == given ? pathname : NULL, out, ret, outsiz));
|
||||
}
|
||||
|
||||
// Fortified readlink variants used by dpkg / update-alternatives
|
||||
@@ -776,7 +778,7 @@ char *realpath(const char *path, char *resolved_path) {
|
||||
char pbuf[PATH_MAX];
|
||||
const char *target = rewrite_path(path, pbuf, sizeof(pbuf));
|
||||
char *res = orig_realpath ? orig_realpath(target, resolved_path) : NULL;
|
||||
if (res && g_ddnatv_root[0] != '\0') {
|
||||
if (res && g_ddnatv_root[0] != '\0' && !is_rootfs_real_path(path)) {
|
||||
size_t rlen = g_ddnatv_root_len;
|
||||
if (strncmp(res, g_ddnatv_root, rlen) == 0 && (res[rlen] == '/' || res[rlen] == '\0')) {
|
||||
size_t rem_len = strlen(res + rlen);
|
||||
|
||||
@@ -197,6 +197,116 @@ static int open_proc_status_at(int dirfd, const char *name, int flags) {
|
||||
return open_proc_status(dir, flags);
|
||||
}
|
||||
|
||||
static long call_orig_syscall(long number, unsigned long a1, unsigned long a2, unsigned long a3, unsigned long a4, unsigned long a5, unsigned long a6);
|
||||
|
||||
#ifndef F_SEAL_EXEC
|
||||
#define F_SEAL_EXEC 0x0020
|
||||
#endif
|
||||
#ifndef MFD_EXEC
|
||||
#define MFD_EXEC 0x0010U
|
||||
#endif
|
||||
|
||||
static int own_fd_of_path(const char *path) {
|
||||
if (!path) return -1;
|
||||
const char *p;
|
||||
if (strncmp(path, "/dev/fd/", 8) == 0) {
|
||||
p = path + 8;
|
||||
} else {
|
||||
if (!is_proc_fd_link(path)) return -1;
|
||||
const char *who = path + 6;
|
||||
if (*who >= '0' && *who <= '9') {
|
||||
long pid = 0;
|
||||
while (*who >= '0' && *who <= '9') pid = pid * 10 + (*who++ - '0');
|
||||
if (pid != (long)call_orig_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0)) {
|
||||
char task[48];
|
||||
snprintf(task, sizeof(task), "/proc/self/task/%ld", pid);
|
||||
if (call_orig_syscall(SYS_faccessat, (unsigned long)AT_FDCWD, (unsigned long)task, F_OK, 0, 0, 0) != 0) return -1;
|
||||
}
|
||||
}
|
||||
p = strstr(path + 6, "/fd/") + 4;
|
||||
}
|
||||
if (*p < '0' || *p > '9') return -1;
|
||||
long fd = 0;
|
||||
while (*p >= '0' && *p <= '9') {
|
||||
fd = fd * 10 + (*p++ - '0');
|
||||
if (fd > INT_MAX) return -1;
|
||||
}
|
||||
return *p == '\0' ? (int)fd : -1;
|
||||
}
|
||||
|
||||
static int copy_memfd_contents(int from, int to, off_t size) {
|
||||
char chunk[32768];
|
||||
off_t at = 0;
|
||||
while (at < size) {
|
||||
size_t want = (size_t)(size - at) < sizeof(chunk) ? (size_t)(size - at) : sizeof(chunk);
|
||||
long got = call_orig_syscall(SYS_pread64, (unsigned long)from, (unsigned long)chunk, want, (unsigned long)at, 0, 0);
|
||||
if (got < 0 && errno == EINTR) continue;
|
||||
if (got <= 0) return -1;
|
||||
long done = 0;
|
||||
while (done < got) {
|
||||
long put = call_orig_syscall(SYS_write, (unsigned long)to, (unsigned long)(chunk + done), (unsigned long)(got - done), 0, 0, 0);
|
||||
if (put < 0 && errno == EINTR) continue;
|
||||
if (put <= 0) return -1;
|
||||
done += put;
|
||||
}
|
||||
at += got;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int copy_of_memfd(int src, int flags) {
|
||||
char link[48], target[PATH_MAX];
|
||||
snprintf(link, sizeof(link), "/proc/thread-self/fd/%d", src);
|
||||
long n = call_orig_syscall(SYS_readlinkat, (unsigned long)AT_FDCWD, (unsigned long)link, (unsigned long)target, sizeof(target) - 1, 0, 0);
|
||||
if (n <= 7 || strncmp(target, "/memfd:", 7) != 0) return -1;
|
||||
target[n] = '\0';
|
||||
char *name = target + 7;
|
||||
size_t name_len = (size_t)n - 7;
|
||||
if (name_len >= 10 && strcmp(name + name_len - 10, " (deleted)") == 0) name[name_len -= 10] = '\0';
|
||||
if (name_len > 249) name[249] = '\0';
|
||||
struct stat st;
|
||||
if (call_orig_syscall(SYS_fstat, (unsigned long)src, (unsigned long)&st, 0, 0, 0, 0) != 0 || !S_ISREG(st.st_mode)) return -1;
|
||||
long seals = call_orig_syscall(SYS_fcntl, (unsigned long)src, F_GET_SEALS, 0, 0, 0, 0);
|
||||
if (seals < 0) return -1;
|
||||
unsigned long mfd_flags = MFD_ALLOW_SEALING | ((flags & O_CLOEXEC) ? MFD_CLOEXEC : 0);
|
||||
long copy = -1;
|
||||
if (st.st_mode & 0111) copy = call_orig_syscall(SYS_memfd_create, (unsigned long)name, mfd_flags | MFD_EXEC, 0, 0, 0, 0);
|
||||
if (copy < 0) copy = call_orig_syscall(SYS_memfd_create, (unsigned long)name, mfd_flags, 0, 0, 0, 0);
|
||||
if (copy < 0) return -1;
|
||||
int ok = copy_memfd_contents(src, (int)copy, st.st_size) == 0 &&
|
||||
call_orig_syscall(SYS_lseek, (unsigned long)copy, 0, SEEK_SET, 0, 0, 0) == 0 &&
|
||||
call_orig_syscall(SYS_fchmod, (unsigned long)copy, st.st_mode & 07777, 0, 0, 0, 0) == 0 &&
|
||||
call_orig_syscall(SYS_fcntl, (unsigned long)copy, F_ADD_SEALS, (unsigned long)(seals | F_SEAL_WRITE | F_SEAL_GROW | F_SEAL_SHRINK), 0, 0, 0) == 0;
|
||||
if (!ok) {
|
||||
call_orig_syscall(SYS_close, (unsigned long)copy, 0, 0, 0, 0, 0);
|
||||
return -1;
|
||||
}
|
||||
return (int)copy;
|
||||
}
|
||||
|
||||
static int reopen_denied_memfd(const char *path, int flags) {
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || (flags & (O_CREAT | O_TRUNC | O_DIRECTORY | O_PATH))) return -1;
|
||||
int named = own_fd_of_path(path);
|
||||
if (named < 0) return -1;
|
||||
long src = call_orig_syscall(SYS_fcntl, (unsigned long)named, F_DUPFD_CLOEXEC, 0, 0, 0, 0);
|
||||
if (src < 0) return -1;
|
||||
struct stat by_path, by_fd;
|
||||
int same = call_orig_syscall(SYS_newfstatat, (unsigned long)AT_FDCWD, (unsigned long)path, (unsigned long)&by_path, 0, 0, 0) == 0 &&
|
||||
call_orig_syscall(SYS_fstat, (unsigned long)src, (unsigned long)&by_fd, 0, 0, 0, 0) == 0 &&
|
||||
by_path.st_dev == by_fd.st_dev && by_path.st_ino == by_fd.st_ino;
|
||||
int copy = same ? copy_of_memfd((int)src, flags) : -1;
|
||||
call_orig_syscall(SYS_close, (unsigned long)src, 0, 0, 0, 0, 0);
|
||||
return copy;
|
||||
}
|
||||
|
||||
static int open_or_reopen_memfd(int fd, const char *path, int flags) {
|
||||
if (fd >= 0 || errno != EACCES) return fd;
|
||||
int copy = reopen_denied_memfd(path, flags);
|
||||
if (copy >= 0) return copy;
|
||||
errno = EACCES;
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Hook open
|
||||
int open(const char *pathname, int flags, ...) {
|
||||
static int (*orig_open)(const char *, int, ...) = NULL;
|
||||
@@ -225,7 +335,7 @@ int open(const char *pathname, int flags, ...) {
|
||||
forget_proc_root_fd(fd);
|
||||
return fd;
|
||||
}
|
||||
int fd = orig_open(target, flags);
|
||||
int fd = open_or_reopen_memfd(orig_open(target, flags), pathname, flags);
|
||||
remember_proc_root_fd(fd, pathname);
|
||||
return fd;
|
||||
}
|
||||
@@ -259,7 +369,7 @@ int openat(int dirfd, const char *pathname, int flags, ...) {
|
||||
forget_proc_root_fd(fd);
|
||||
return fd;
|
||||
}
|
||||
int fd = orig_openat(dirfd, target, flags);
|
||||
int fd = open_or_reopen_memfd(orig_openat(dirfd, target, flags), (pathname && pathname[0] == '/') ? pathname : NULL, flags);
|
||||
remember_proc_root_fd(fd, pathname);
|
||||
return fd;
|
||||
}
|
||||
@@ -304,6 +414,11 @@ static long call_orig_syscall(long number, unsigned long a1, unsigned long a2, u
|
||||
return orig_syscall ? orig_syscall(number, a1, a2, a3, a4, a5, a6) : syscall(number, a1, a2, a3, a4, a5, a6);
|
||||
}
|
||||
|
||||
static int openat2_or_reopen_memfd(int fd, const char *pathname, const struct ddnatv_open_how *how) {
|
||||
if (fd >= 0 || errno != EACCES || pathname[0] != '/' || !how || how->resolve) return fd;
|
||||
return open_or_reopen_memfd(fd, pathname, (int)how->flags);
|
||||
}
|
||||
|
||||
// Hook openat2 (used by GNU tar 1.35+/gnulib for RESOLVE_BENEATH traversal).
|
||||
// Rewrites absolute paths like openat, then delegates; on ENOSYS (kernels
|
||||
// without openat2, e.g. Android < 5.6) emulates with plain openat instead of
|
||||
@@ -334,12 +449,12 @@ int openat2(int dirfd, const char *pathname, struct ddnatv_open_how *how, size_t
|
||||
const char *target = (pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
|
||||
if (orig_openat2) {
|
||||
int ret = orig_openat2(dirfd, target, how, usize);
|
||||
if (ret >= 0 || errno != ENOSYS) return ret;
|
||||
if (ret >= 0 || errno != ENOSYS) return openat2_or_reopen_memfd(ret, pathname, how);
|
||||
}
|
||||
#ifdef __NR_openat2
|
||||
long sret = call_orig_syscall(__NR_openat2, (unsigned long)dirfd, (unsigned long)target, (unsigned long)how, (unsigned long)usize, 0, 0);
|
||||
if (sret >= 0 || errno != ENOSYS) {
|
||||
return (int)sret;
|
||||
return openat2_or_reopen_memfd((int)sret, pathname, how);
|
||||
}
|
||||
#endif
|
||||
if (!how || usize < 16) {
|
||||
@@ -646,6 +761,7 @@ int lstat(const char *pathname, struct stat *statbuf) {
|
||||
int fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags) {
|
||||
static int (*orig_fstatat)(int, const char *, struct stat *, int) = NULL;
|
||||
if (!orig_fstatat) orig_fstatat = (int (*)(int, const char *, struct stat *, int))dlsym(RTLD_NEXT, "fstatat");
|
||||
const char *given = pathname;
|
||||
DDNATV_AT_REMAP(dirfd, pathname);
|
||||
char buf[PATH_MAX];
|
||||
const char *target = (pathname && pathname[0] == '/') ? ((flags & AT_SYMLINK_NOFOLLOW) ? rewrite_path : rewrite_path_follow)(pathname, buf, sizeof(buf)) : pathname;
|
||||
@@ -665,7 +781,7 @@ int fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags) {
|
||||
if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat");
|
||||
ssize_t llen = orig_readlinkat ? orig_readlinkat(dirfd, target, link_buf, sizeof(link_buf) - 1) : -1;
|
||||
if (llen > 0) {
|
||||
ssize_t post_len = postprocess_readlink(pathname, link_buf, llen, sizeof(link_buf));
|
||||
ssize_t post_len = postprocess_named_readlink(pathname, pathname == given ? pathname : NULL, link_buf, llen, sizeof(link_buf));
|
||||
if (post_len > 0) {
|
||||
statbuf->st_size = post_len;
|
||||
}
|
||||
|
||||
@@ -952,6 +952,30 @@ static int is_proc_fd_link(const char *path) {
|
||||
return *p == '\0';
|
||||
}
|
||||
|
||||
static int is_proc_cwd_link(const char *path) {
|
||||
if (!path || strncmp(path, "/proc/", 6) != 0) return 0;
|
||||
const char *p = path + 6;
|
||||
if (strncmp(p, "self/", 5) == 0) {
|
||||
p += 5;
|
||||
} else if (strncmp(p, "thread-self/", 12) == 0) {
|
||||
p += 12;
|
||||
} else {
|
||||
if (*p < '0' || *p > '9') return 0;
|
||||
while (*p >= '0' && *p <= '9') p++;
|
||||
if (*p != '/') return 0;
|
||||
p++;
|
||||
}
|
||||
return strcmp(p, "cwd") == 0;
|
||||
}
|
||||
|
||||
static int is_rootfs_real_path(const char *path) {
|
||||
return path && g_ddnatv_root_len > 0 && is_path_prefix(path, g_ddnatv_root, g_ddnatv_root_len);
|
||||
}
|
||||
|
||||
static int link_answers_in_kernel_form(const char *linkpath, const char *named) {
|
||||
return is_proc_fd_link(linkpath) || is_proc_cwd_link(linkpath) || is_rootfs_real_path(named);
|
||||
}
|
||||
|
||||
// The guest path of a folder that a session mount puts outside the rootfs, for what the kernel
|
||||
// reports as its real place (getcwd(), /proc/self/cwd and fd links). Wine found no DOS drive for
|
||||
// Sekiro's folder on the SD card library ("starting in the Windows directory"), and the game quit.
|
||||
@@ -989,7 +1013,7 @@ static char *guest_path_of_allocated_mount_source(char *res) {
|
||||
return grown;
|
||||
}
|
||||
|
||||
static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret, size_t bufsiz) {
|
||||
static ssize_t postprocess_named_readlink(const char *linkpath, const char *named, char *buf, ssize_t ret, size_t bufsiz) {
|
||||
if (ret <= 0) return ret;
|
||||
if ((size_t)ret < bufsiz) {
|
||||
buf[ret] = '\0';
|
||||
@@ -998,7 +1022,7 @@ static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret
|
||||
ret = (ssize_t)guest_path_of_mount_source(buf, (size_t)ret, bufsiz, NULL);
|
||||
|
||||
// 1. Strip g_ddnatv_root if target starts with it
|
||||
if (g_ddnatv_root_len > 0 && !is_proc_fd_link(linkpath)) {
|
||||
if (g_ddnatv_root_len > 0 && !link_answers_in_kernel_form(linkpath, named)) {
|
||||
size_t rlen = g_ddnatv_root_len;
|
||||
if ((size_t)ret >= rlen && memcmp(buf, g_ddnatv_root, rlen) == 0 &&
|
||||
((size_t)ret == rlen || buf[rlen] == '/')) {
|
||||
@@ -1053,6 +1077,10 @@ static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret
|
||||
return ret;
|
||||
}
|
||||
|
||||
static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret, size_t bufsiz) {
|
||||
return postprocess_named_readlink(linkpath, linkpath, buf, ret, bufsiz);
|
||||
}
|
||||
|
||||
// Android's SELinux label, which the xattr hooks keep away from Ubuntu programs.
|
||||
static const char k_selinux_xattr[] = "security.selinux";
|
||||
|
||||
|
||||
@@ -235,8 +235,16 @@ static int sandbox_only_limit(int resource, const struct rlimit *rlim) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The kernel checks RLIMIT_RTTIME on a thread that is realtime or has a CPU-time timer armed, and a
|
||||
// limit of 0 is reached at once: SIGXCPU at the soft limit, SIGKILL at the hard one. SDL sets the
|
||||
// RTTimeUSecMax it reads from org.freedesktop.portal.Realtime before it asks for a realtime thread,
|
||||
// and xdg-desktop-portal reports 0 when it reaches no RealtimeKit, as in a session with no system bus.
|
||||
static int fatal_limit(int resource, const struct rlimit *rlim) {
|
||||
return rlim && resource == RLIMIT_RTTIME && rlim->rlim_cur == 0;
|
||||
}
|
||||
|
||||
int setrlimit(__rlimit_resource_t resource, const struct rlimit *rlim) {
|
||||
if (sandbox_only_limit((int)resource, rlim)) return 0;
|
||||
if (sandbox_only_limit((int)resource, rlim) || fatal_limit((int)resource, rlim)) return 0;
|
||||
static int (*orig_setrlimit)(__rlimit_resource_t, const struct rlimit *) = NULL;
|
||||
#if defined(__USE_FILE_OFFSET64) && !defined(__LP64__)
|
||||
// With 64-bit file offsets on a 32-bit system this function is setrlimit64
|
||||
@@ -660,6 +668,19 @@ long syscall(long number, ...) {
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef __NR_execve
|
||||
if (number == __NR_execve) {
|
||||
return (long)execve((const char *)arg1, (char *const *)arg2, (char *const *)arg3);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef __NR_execveat
|
||||
if (number == __NR_execveat && arg2 && ((const char *)arg2)[0] != '\0' &&
|
||||
(((const char *)arg2)[0] == '/' || (int)arg1 == AT_FDCWD) && (arg5 & ~(unsigned long)AT_EMPTY_PATH) == 0) {
|
||||
return (long)execve((const char *)arg2, (char *const *)arg3, (char *const *)arg4);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef __NR_clone3
|
||||
if (number == __NR_clone3) {
|
||||
errno = ENOSYS;
|
||||
|
||||
@@ -307,6 +307,7 @@ static ssize_t copy_guest_exe(const char *real_exe, char *buf, size_t bufsiz) {
|
||||
size_t len = strlen(out_path);
|
||||
size_t copy_len = (len < bufsiz) ? len : bufsiz;
|
||||
memcpy(buf, out_path, copy_len);
|
||||
if (copy_len < bufsiz) buf[copy_len] = '\0';
|
||||
return (ssize_t)copy_len;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,12 @@
|
||||
#define SYS_SECCOMP 1
|
||||
#endif
|
||||
|
||||
#if defined(__aarch64__)
|
||||
#define DDNATV_HOST_AUDIT_ARCH 0xC00000B7U
|
||||
#else
|
||||
#define DDNATV_HOST_AUDIT_ARCH 0x40000028U
|
||||
#endif
|
||||
|
||||
static int (*get_real_sigaction(void))(int, const struct sigaction *, struct sigaction *);
|
||||
|
||||
// A program's own SIGSYS handler, for the traps of a seccomp filter it installed itself (Firefox's
|
||||
@@ -57,7 +63,13 @@ static long sigsys_id_change(int nr, const unsigned long long *regs, long ret_va
|
||||
// Intercept SECCOMP blocked syscalls (SIGSYS), resolve sandbox/landlock gracefully, and advance PC
|
||||
static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) {
|
||||
if (!ctx || !info) return;
|
||||
if (info->si_code != SYS_SECCOMP) {
|
||||
int host_trap = info->si_code == SYS_SECCOMP && info->si_errno == 0 && info->si_arch == DDNATV_HOST_AUDIT_ARCH;
|
||||
if (!host_trap && g_app_sigsys_set) {
|
||||
if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx);
|
||||
else g_app_sigsys.sa_handler(sig);
|
||||
return;
|
||||
}
|
||||
if (!host_trap) {
|
||||
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
|
||||
if (real_sig) {
|
||||
struct sigaction sa_dfl;
|
||||
@@ -69,11 +81,6 @@ static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) {
|
||||
raise(sig);
|
||||
return;
|
||||
}
|
||||
if (info->si_errno != 0 && g_app_sigsys_set) {
|
||||
if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx);
|
||||
else g_app_sigsys.sa_handler(sig);
|
||||
return;
|
||||
}
|
||||
ucontext_t *uctx = (ucontext_t *)ctx;
|
||||
|
||||
int sys_nr = info->si_syscall;
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"), run_name="steam_compatibility")
|
||||
SETUP = COMPAT["DD_ANTICHEAT_SETUP"]
|
||||
|
||||
|
||||
class AntiCheatRoutingTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = Path(temp.name)
|
||||
self.steam = self.root / "Steam"
|
||||
self.common = self.steam / "steamapps" / "common"
|
||||
self.tools = self.steam / "compatibilitytools.d"
|
||||
self.game = self.common / "Some Game"
|
||||
self.game.mkdir(parents=True)
|
||||
self.tools.mkdir(parents=True)
|
||||
self.record = self.root / "record.json"
|
||||
self.fex = self.root / "droiddeck-fex"
|
||||
self.fex.write_text("#!/bin/bash\nif [ \"$1\" = update ]; then echo \"$1\" >> \"$DD_RECORD.update\"; "
|
||||
"[ -n \"${DD_UPDATED_PATCHES:-}\" ] && printf '%s\\n' \"$DD_UPDATED_PATCHES\" > \"$DD_PATCHES\"; exit 0; fi\n"
|
||||
"python3 -c 'import json,os,sys; json.dump({\"argv\": sys.argv[2:], "
|
||||
"\"eac\": os.environ.get(\"PROTON_EAC_RUNTIME\"), \"be\": os.environ.get(\"PROTON_BATTLEYE_RUNTIME\")}, "
|
||||
"open(sys.argv[1], \"w\"))' \"$DD_RECORD\" \"$@\"\n")
|
||||
self.fex.chmod(0o755)
|
||||
self.patches = self.root / "fex-patches"
|
||||
self.patches.write_text("openat2-enosys-fallback\nfixed-guest-memory-above-host-address-limit\n")
|
||||
|
||||
def tool(self, name, x86_64=True):
|
||||
tool = self.tools / name
|
||||
(tool / "files" / "lib" / "wine" / ("x86_64-unix" if x86_64 else "aarch64-unix")).mkdir(parents=True)
|
||||
if not x86_64:
|
||||
(tool / "files" / "bin-arm64").mkdir()
|
||||
(tool / "proton").write_text("#!/bin/sh\n")
|
||||
(tool / "proton").chmod(0o755)
|
||||
return tool
|
||||
|
||||
def runtime(self, name, library):
|
||||
folder = self.common / name / "v2" / "lib64"
|
||||
folder.mkdir(parents=True)
|
||||
(folder / library).write_text("")
|
||||
return self.common / name
|
||||
|
||||
def file(self, relative):
|
||||
path = self.game / relative
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("{}")
|
||||
|
||||
def launch(self, verb="waitforexitandrun", extra=None):
|
||||
script = SETUP.replace("/usr/local/bin/droiddeck-fex", str(self.fex)).replace(
|
||||
"/usr/local/share/fex-emu/.droiddeck-patches", str(self.patches)) + (
|
||||
"dd_game_cpus() { :; }\n"
|
||||
"verb=$1; shift\n"
|
||||
"dd_anticheat \"$@\"\n"
|
||||
"echo stayed\n")
|
||||
env = {"PATH": os.environ["PATH"], "HOME": str(self.root), "DD_RECORD": str(self.record), "DD_PATCHES": str(self.patches),
|
||||
"STEAM_COMPAT_INSTALL_PATH": str(self.game), "STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.steam)}
|
||||
env.update(extra or {})
|
||||
result = subprocess.run(["bash", "-c", script, "launcher", verb, str(self.game / "game.exe")],
|
||||
env=env, capture_output=True, text=True, timeout=30)
|
||||
routed = json.loads(self.record.read_text()) if self.record.exists() else None
|
||||
return result, routed
|
||||
|
||||
def test_eos_easy_anti_cheat_runs_the_newest_x86_64_build_under_fex(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
newest = self.tool("DroidDeck-Proton-11.0-10-x86_64")
|
||||
self.tool("DroidDeck-Proton-11.0-20", x86_64=False)
|
||||
runtime = self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
result, routed = self.launch()
|
||||
self.assertNotIn("stayed", result.stdout)
|
||||
self.assertEqual(routed["argv"], ["proton", str(newest / "proton"), "waitforexitandrun", str(self.game / "game.exe")])
|
||||
self.assertEqual(routed["eac"], str(runtime))
|
||||
self.assertIn("running DroidDeck-Proton-11.0-10-x86_64 under FEX", result.stderr)
|
||||
|
||||
def test_battleye_sets_its_own_runtime(self):
|
||||
self.file("BattlEye/BEClient_x64.so")
|
||||
tool = self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
runtime = self.runtime("Proton BattlEye Runtime", "beclient_x64.so")
|
||||
_, routed = self.launch()
|
||||
self.assertEqual((routed["argv"][1], routed["be"], routed["eac"]), (str(tool / "proton"), str(runtime), None))
|
||||
|
||||
def test_a_runtime_already_set_with_files_is_kept(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
own = self.root / "own-eac"
|
||||
(own / "v2").mkdir(parents=True)
|
||||
(own / "v2" / "easyanticheat_x64.so").write_text("")
|
||||
_, routed = self.launch(extra={"PROTON_EAC_RUNTIME": str(own)})
|
||||
self.assertEqual(routed["eac"], str(own))
|
||||
|
||||
def test_games_without_anti_cheat_files_stay_on_arm64(self):
|
||||
self.file("Data/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
result, routed = self.launch()
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
self.assertEqual(result.stderr, "")
|
||||
|
||||
def test_without_an_x86_64_build_the_launch_stays_on_arm64(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-20", x86_64=False)
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
result, routed = self.launch()
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
self.assertIn("no x86-64 DroidDeck-Proton is installed", result.stderr)
|
||||
|
||||
def test_without_the_runtime_files_the_launch_stays_on_arm64(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
(self.common / "Proton EasyAntiCheat Runtime").mkdir(parents=True)
|
||||
result, routed = self.launch()
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("its Proton runtime is not installed", result.stderr)
|
||||
|
||||
def test_the_user_can_turn_routing_off(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"})
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
|
||||
def test_a_tool_the_user_chose_is_kept(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
for chosen in ("GE-Proton11-15-aarch64", "DroidDeck-Bionic-14.1-r85", "proton_experimental"):
|
||||
result, routed = self.launch(extra={"DD_AC_TOOL": chosen})
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
self.assertIn("%s was chosen for this game, so it runs as chosen" % chosen, result.stderr)
|
||||
|
||||
def test_droiddeck_proton_builds_still_route(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
newest = self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
for own in ("DroidDeck-Proton 11-14.1", "DroidDeck-Proton-11-14.2"):
|
||||
self.record.unlink(missing_ok=True)
|
||||
result, routed = self.launch(extra={"DD_AC_TOOL": own})
|
||||
self.assertEqual(routed["argv"][1], str(newest / "proton"))
|
||||
|
||||
def test_a_fex_build_without_high_guest_memory_stays_on_arm64(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
for patches in ("openat2-enosys-fallback\n", None):
|
||||
if patches is None:
|
||||
self.patches.unlink()
|
||||
else:
|
||||
self.patches.write_text(patches)
|
||||
result, routed = self.launch()
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
self.assertIn("the installed FEX build cannot run anti-cheat", result.stderr)
|
||||
|
||||
def test_an_older_fex_build_is_updated_before_routing(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
tool = self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
self.patches.unlink()
|
||||
result, routed = self.launch(extra={"DD_UPDATED_PATCHES": "fixed-guest-memory-above-host-address-limit"})
|
||||
self.assertEqual(routed["argv"][1], str(tool / "proton"))
|
||||
self.assertNotIn("cannot run anti-cheat", result.stderr)
|
||||
self.assertTrue((self.root / "record.json.update").exists())
|
||||
|
||||
def test_games_without_anti_cheat_files_do_not_update_fex(self):
|
||||
self.file("Data/Settings.json")
|
||||
self.launch()
|
||||
self.assertFalse((self.root / "record.json.update").exists())
|
||||
|
||||
def test_choices_are_kept_the_same_with_an_older_fex_build(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
self.patches.unlink()
|
||||
result, routed = self.launch(extra={"DD_AC_TOOL": "GE-Proton11-15-aarch64"})
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("GE-Proton11-15-aarch64 was chosen for this game, so it runs as chosen", result.stderr)
|
||||
result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"})
|
||||
self.assertIsNone(routed)
|
||||
self.assertEqual(result.stderr, "")
|
||||
|
||||
def test_the_fex_build_lists_its_patches(self):
|
||||
build = (BIN.parents[4] / "fex" / "build-in-arch.sh").read_text()
|
||||
self.assertIn("> out/usr/local/share/fex-emu/.droiddeck-patches", build)
|
||||
names = {p.stem.split("-", 1)[1] for p in (BIN.parents[4] / "fex" / "patches").glob("*.patch")}
|
||||
self.assertIn("fixed-guest-memory-above-host-address-limit", names)
|
||||
|
||||
def test_adopted_tools_pass_their_own_folder_name(self):
|
||||
wrapper = COMPAT["extra_wrapper_sh"]("proton")
|
||||
self.assertIn('DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@"', wrapper)
|
||||
self.assertNotIn("DD_AC_TOOL=", COMPAT["LAUNCHER_SH"])
|
||||
|
||||
def test_other_verbs_are_left_alone(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
result, routed = self.launch(verb="getcompatpath")
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
|
||||
def test_launchers_check_before_arm64_setup_and_x86_64_tools_run_under_fex(self):
|
||||
launcher = COMPAT["LAUNCHER_SH"]
|
||||
self.assertLess(launcher.index('dd_anticheat "$@"'), launcher.index('dd_components "$depot"'))
|
||||
wrapper = COMPAT["extra_wrapper_sh"]("proton")
|
||||
self.assertLess(wrapper.index("dd_x86_64_proton() {"), wrapper.index("dd_fallback="))
|
||||
self.assertLess(wrapper.index('droiddeck-fex proton "$here/proton"'), wrapper.index('dd_components "$here"'))
|
||||
self.assertIn('! dd_x86_64_proton "$d"', wrapper)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user