mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 04:25:38 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93dd562e14 | ||
|
|
c0abf31a6b | ||
|
|
ab99c1a3b3 | ||
|
|
049ded1812 | ||
|
|
ef1c208ed7 | ||
|
|
27171d8ffd | ||
|
|
47ae756748 | ||
|
|
d34ef11bf4 |
No files matched your search
@@ -25,6 +25,7 @@
|
||||
#include <gnu/lib-names.h>
|
||||
#endif
|
||||
#include <fcntl.h>
|
||||
#include <linux/futex.h>
|
||||
#include <linux/input.h>
|
||||
#include <linux/joystick.h>
|
||||
#include <linux/uinput.h>
|
||||
@@ -711,6 +712,19 @@ ring_header_is_valid(const FakeInputRingHeader *ring) {
|
||||
ring->capacity == FAKE_INPUT_RING_CAPACITY;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static int ring_wait(const FakeInputRingHeader *ring, uint64_t seen, long ns) {
|
||||
struct timespec wait = {0, ns};
|
||||
if (syscall(SYS_futex, &ring->write_seq, FUTEX_WAIT, static_cast<uint32_t>(seen), &wait, nullptr, 0) == 0 ||
|
||||
errno == EAGAIN || errno == ETIMEDOUT)
|
||||
return 0;
|
||||
if (errno == EINTR) return -1;
|
||||
return nanosleep(&wait, nullptr);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static void ring_wake(const FakeInputRingHeader *ring) {
|
||||
syscall(SYS_futex, &ring->write_seq, FUTEX_WAKE, INT_MAX, nullptr, nullptr, 0);
|
||||
}
|
||||
|
||||
struct SnapshotState {
|
||||
uint64_t sequence = 0;
|
||||
uint64_t write_seq = 0;
|
||||
@@ -1167,6 +1181,7 @@ __attribute__((visibility("hidden"))) static void flush_uinput(UinputWriter &w)
|
||||
__atomic_thread_fence(__ATOMIC_RELEASE);
|
||||
__atomic_store_n(&ring->snapshot_seq, sequence + 2, __ATOMIC_RELEASE);
|
||||
__atomic_store_n(&ring->write_seq, write_seq, __ATOMIC_RELEASE);
|
||||
ring_wake(ring);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static ssize_t
|
||||
@@ -1540,6 +1555,12 @@ __attribute__((visibility("hidden"))) static void sleep_us(int us) {
|
||||
nanosleep(&interval, nullptr);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static void
|
||||
report_wait(const FakeInputRingHeader *ring, bool fresh, uint64_t seen, int us) {
|
||||
if (fresh) ring_wait(ring, seen, us * 1000L);
|
||||
else sleep_us(us);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static uint64_t monotonic_us() {
|
||||
struct timespec now;
|
||||
clock_gettime(CLOCK_MONOTONIC, &now);
|
||||
@@ -1712,7 +1733,8 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg)
|
||||
int32_t axes[8] = {};
|
||||
DeckExtras extras;
|
||||
while (live_pad_type() == PAD_TYPE_DECK) {
|
||||
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
|
||||
bool fresh = read_snapshot(self->ring, snap);
|
||||
if (fresh && snap.generation == ring_generation(self->ring)) {
|
||||
buttons = snap.buttons;
|
||||
memcpy(axes, snap.axes, sizeof(axes));
|
||||
}
|
||||
@@ -1722,7 +1744,7 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg)
|
||||
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
|
||||
errno != EAGAIN && errno != EWOULDBLOCK)
|
||||
break;
|
||||
sleep_us(controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
}
|
||||
syscall(SYS_close, self->peer);
|
||||
munmap(self->ring, self->mapping_size);
|
||||
@@ -1828,7 +1850,8 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
|
||||
SonyTouch touch;
|
||||
const uint64_t start_us = monotonic_us();
|
||||
while (live_pad_type() == type) {
|
||||
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
|
||||
bool fresh = read_snapshot(self->ring, snap);
|
||||
if (fresh && snap.generation == ring_generation(self->ring)) {
|
||||
buttons = snap.buttons;
|
||||
memcpy(axes, snap.axes, sizeof(axes));
|
||||
}
|
||||
@@ -1838,7 +1861,7 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
|
||||
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
|
||||
errno != EAGAIN && errno != EWOULDBLOCK)
|
||||
break;
|
||||
sleep_us(controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
}
|
||||
syscall(SYS_close, self->peer);
|
||||
munmap(self->ring, self->mapping_size);
|
||||
@@ -2037,7 +2060,8 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
|
||||
DeckExtras extras;
|
||||
const uint64_t start_us = monotonic_us();
|
||||
while (live_pad_type() == PAD_TYPE_STEAM) {
|
||||
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
|
||||
bool fresh = read_snapshot(self->ring, snap);
|
||||
if (fresh && snap.generation == ring_generation(self->ring)) {
|
||||
buttons = snap.buttons;
|
||||
memcpy(axes, snap.axes, sizeof(axes));
|
||||
}
|
||||
@@ -2048,7 +2072,7 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
|
||||
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
|
||||
errno != EAGAIN && errno != EWOULDBLOCK)
|
||||
break;
|
||||
sleep_us(controller_report_interval_us(TRITON_REPORT_INTERVAL_US));
|
||||
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(TRITON_REPORT_INTERVAL_US));
|
||||
}
|
||||
syscall(SYS_close, self->peer);
|
||||
munmap(self->ring, self->mapping_size);
|
||||
@@ -4016,6 +4040,7 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
|
||||
errno = ENODEV;
|
||||
return -1;
|
||||
}
|
||||
bool idle = false;
|
||||
for (int attempt = 0; attempt < 8; ++attempt) {
|
||||
size_t requested = count / sizeof(struct input_event);
|
||||
if (fake.keyframe_remaining == 0) {
|
||||
@@ -4037,7 +4062,10 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
|
||||
capture_keyframe(fake, snap);
|
||||
} else {
|
||||
size_t events = std::min<uint64_t>(requested, snap.write_seq - fake.read_seq);
|
||||
if (events == 0) break;
|
||||
if (events == 0) {
|
||||
idle = true;
|
||||
break;
|
||||
}
|
||||
const uint8_t *ring_events = reinterpret_cast<const uint8_t *>(fake.ring) +
|
||||
FAKE_INPUT_RING_HEADER_SIZE;
|
||||
std::vector<struct input_event> input_events(events);
|
||||
@@ -4083,9 +4111,14 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
|
||||
errno = EAGAIN;
|
||||
return -1;
|
||||
}
|
||||
const FakeInputRingHeader *ring = fake.ring;
|
||||
uint64_t seen = fake.read_seq;
|
||||
guard.unlock();
|
||||
#ifdef __GLIBC__
|
||||
pthread_testcancel();
|
||||
#endif
|
||||
struct timespec sleep_time = {0, backoff_ns};
|
||||
int result = nanosleep(&sleep_time, nullptr);
|
||||
int result = idle ? ring_wait(ring, seen, backoff_ns) : nanosleep(&sleep_time, nullptr);
|
||||
guard.lock();
|
||||
if (result < 0) return -1;
|
||||
if (low_latency(LATENCY_CONTROLLER)) backoff_ns = kLowLatencyRingWaitUs * 1000;
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
#include <errno.h>
|
||||
#include <jni.h>
|
||||
#include <limits.h>
|
||||
#include <linux/futex.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
@@ -11,6 +14,13 @@ Java_com_droiddeck_launcher_input_FakeInputWriter_nativeStoreFence(JNIEnv *env,
|
||||
atomic_thread_fence(memory_order_release);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_input_FakeInputWriter_nativeWake(JNIEnv *env, jclass clazz, jobject buffer, jint offset) {
|
||||
(void)clazz;
|
||||
uint8_t *base = (*env)->GetDirectBufferAddress(env, buffer);
|
||||
if (base) syscall(SYS_futex, base + offset, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_session_ThreadSignals_tgkill(JNIEnv *env, jclass clazz, jint tgid, jint tid, jint signal) {
|
||||
(void)env;
|
||||
|
||||
@@ -349,7 +349,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var gestureSettingsOpen by mutableStateOf(false)
|
||||
private var steamImportAsk by mutableStateOf<com.droiddeck.launcher.session.SteamImportPrompt.Ask?>(null)
|
||||
private var steamImportAnswered: String? = null
|
||||
private var directHoldBehavior by mutableStateOf(com.droiddeck.launcher.input.TouchGestureConfig.MOUSE_BEHAVIOR_NONE)
|
||||
private var directHoldBehavior by mutableStateOf(com.droiddeck.launcher.input.TouchGestureConfig.MOUSE_BEHAVIOR_CLICK)
|
||||
private var relativeMouseMode by mutableIntStateOf(0)
|
||||
@Volatile private var appliedRelativeMouseMode: Int? = null
|
||||
private val agentReadyListener: () -> Unit = {
|
||||
@@ -6960,9 +6960,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (!hasFocus && ::padMouse.isInitialized) padMouse.reset()
|
||||
if (runtimeRemovalBlocked) return
|
||||
if (!hasFocus) {
|
||||
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
|
||||
if (::touchpad.isInitialized) touchpad.cancel()
|
||||
if (::scrollTouch.isInitialized) scrollTouch.cancel()
|
||||
cancelTouchGestures()
|
||||
releaseHeldGuestInput()
|
||||
}
|
||||
if (hasFocus && !pipUi) {
|
||||
|
||||
@@ -23,7 +23,7 @@ class DirectTouchHold(
|
||||
private var downY = 0f
|
||||
private var downId = 0
|
||||
private var delayMs = 0L
|
||||
private var holdBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_NONE
|
||||
private var holdBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK
|
||||
private var forwarded = false
|
||||
private var forwardedAt = 0L
|
||||
private var held = false
|
||||
|
||||
@@ -149,6 +149,8 @@ public class FakeInputWriter {
|
||||
|
||||
private static native void nativeStoreFence();
|
||||
|
||||
private static native void nativeWake(ByteBuffer ring, int offset);
|
||||
|
||||
public static void storeFence() {
|
||||
nativeStoreFence();
|
||||
}
|
||||
@@ -455,6 +457,7 @@ public class FakeInputWriter {
|
||||
writeSnapshotLocked(ring);
|
||||
nativeStoreFence();
|
||||
ring.putLong(RING_WRITE_SEQ_OFFSET, writeSeq);
|
||||
nativeWake(ring, RING_WRITE_SEQ_OFFSET);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ data class TouchGestureConfig(
|
||||
val longPressAction: String = ACTION_RIGHT_CLICK,
|
||||
val longPressMouseBehavior: String = MOUSE_BEHAVIOR_HOLD,
|
||||
val longPressDelay: Int = DEFAULT_DELAY_MS,
|
||||
val directHoldBehavior: String = MOUSE_BEHAVIOR_NONE,
|
||||
val directHoldBehavior: String = MOUSE_BEHAVIOR_CLICK,
|
||||
val doubleTapEnabled: Boolean = true,
|
||||
val doubleTapDelay: Int = DEFAULT_DELAY_MS,
|
||||
val twoFingerDragEnabled: Boolean = true,
|
||||
@@ -167,7 +167,7 @@ data class TouchGestureConfig(
|
||||
),
|
||||
longPressDelay = obj.optInt(KEY_LONG_PRESS_DELAY, DEFAULT_DELAY_MS),
|
||||
directHoldBehavior = normalizeDirectHoldBehavior(
|
||||
obj.optString(KEY_DIRECT_HOLD_BEHAVIOR, MOUSE_BEHAVIOR_NONE)
|
||||
obj.optString(KEY_DIRECT_HOLD_BEHAVIOR, MOUSE_BEHAVIOR_CLICK)
|
||||
),
|
||||
doubleTapEnabled = obj.optBoolean(KEY_DOUBLE_TAP_ENABLED, true),
|
||||
doubleTapDelay = obj.optInt(KEY_DOUBLE_TAP_DELAY, DEFAULT_DELAY_MS),
|
||||
|
||||
@@ -1735,6 +1735,7 @@ object SessionPrefs {
|
||||
signal = p.getInt("customThemeSignal", defaults.signal),
|
||||
good = p.getInt("customThemeGood", defaults.good),
|
||||
error = p.getInt("customThemeError", defaults.error),
|
||||
warning = p.getInt("customThemeWarning", defaults.warning),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1755,6 +1756,7 @@ object SessionPrefs {
|
||||
.putInt("customThemeSignal", colors.signal)
|
||||
.putInt("customThemeGood", colors.good)
|
||||
.putInt("customThemeError", colors.error)
|
||||
.putInt("customThemeWarning", colors.warning)
|
||||
.apply()
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.withFrameMillis
|
||||
import androidx.compose.runtime.withFrameNanos
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
@@ -99,7 +99,7 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
||||
var vx = speed * 0.8f
|
||||
var vy = -speed * 0.6f
|
||||
while (true) {
|
||||
if (clock.page == Size.Zero) { withFrameMillis { }; continue }
|
||||
if (clock.page == Size.Zero) { withFrameNanos { }; continue }
|
||||
val f = MarkFrame(clock.page, Offset.Zero)
|
||||
if (clock.at == Offset.Unspecified) clock.at = Offset(clock.page.width * 0.64f, clock.page.height * 0.42f)
|
||||
if (Motion.scale == 0f) {
|
||||
@@ -108,8 +108,13 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
||||
clock.wall = 0f
|
||||
return@LaunchedEffect
|
||||
}
|
||||
withFrameMillis { now ->
|
||||
val dt = if (last < 0) 0f else min(50f, (now - last) / Motion.scale)
|
||||
withFrameNanos { nanos ->
|
||||
val scale = Motion.scale
|
||||
if (scale == 0f) return@withFrameNanos
|
||||
val settled = clock.intro >= END && clock.ball >= IMPACT + REVEAL_MS && !clock.poked
|
||||
if (settled && last >= 0 && !IdleFrames.due(nanos)) return@withFrameNanos
|
||||
val now = nanos / 1_000_000L
|
||||
val dt = if (last < 0) 0f else min(50f, (now - last).toFloat()) / scale.coerceAtLeast(0.01f)
|
||||
last = now
|
||||
clock.intro += dt
|
||||
clock.wall += dt
|
||||
@@ -117,34 +122,41 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
||||
val before = clock.ball
|
||||
clock.ball += dt
|
||||
|
||||
var x = clock.at.x + vx * dt / 1000f
|
||||
var y = clock.at.y + vy * dt / 1000f
|
||||
var x = clock.at.x
|
||||
var y = clock.at.y
|
||||
val hw = f.ball
|
||||
val hh = f.ball
|
||||
if (x - hw < 0f) { x = hw; vx = abs(vx) }
|
||||
if (x + hw > clock.page.width) { x = clock.page.width - hw; vx = -abs(vx) }
|
||||
if (y - hh < 0f) { y = hh; vy = abs(vy) }
|
||||
if (y + hh > clock.page.height) { y = clock.page.height - hh; vy = -abs(vy) }
|
||||
keepOff?.inflate(clearance)?.let { r ->
|
||||
val nearX = x.coerceIn(r.left, r.right)
|
||||
val nearY = y.coerceIn(r.top, r.bottom)
|
||||
val gapX = x - nearX
|
||||
val gapY = y - nearY
|
||||
val gap = hypot(gapX, gapY)
|
||||
if (gap in 0.0001f..f.ball) {
|
||||
val nx = gapX / gap
|
||||
val ny = gapY / gap
|
||||
x = nearX + nx * f.ball
|
||||
y = nearY + ny * f.ball
|
||||
val into = vx * nx + vy * ny
|
||||
if (into < 0f) { vx -= 2f * into * nx; vy -= 2f * into * ny }
|
||||
} else if (gap <= 0.0001f) {
|
||||
val outX = if (x < r.center.x) r.left - f.ball - x else r.right + f.ball - x
|
||||
val outY = if (y < r.center.y) r.top - f.ball - y else r.bottom + f.ball - y
|
||||
if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) }
|
||||
else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) }
|
||||
var left = dt
|
||||
do {
|
||||
val step = min(50f, left)
|
||||
left -= step
|
||||
x += vx * step / 1000f
|
||||
y += vy * step / 1000f
|
||||
if (x - hw < 0f) { x = hw; vx = abs(vx) }
|
||||
if (x + hw > clock.page.width) { x = clock.page.width - hw; vx = -abs(vx) }
|
||||
if (y - hh < 0f) { y = hh; vy = abs(vy) }
|
||||
if (y + hh > clock.page.height) { y = clock.page.height - hh; vy = -abs(vy) }
|
||||
keepOff?.inflate(clearance)?.let { r ->
|
||||
val nearX = x.coerceIn(r.left, r.right)
|
||||
val nearY = y.coerceIn(r.top, r.bottom)
|
||||
val gapX = x - nearX
|
||||
val gapY = y - nearY
|
||||
val gap = hypot(gapX, gapY)
|
||||
if (gap in 0.0001f..f.ball) {
|
||||
val nx = gapX / gap
|
||||
val ny = gapY / gap
|
||||
x = nearX + nx * f.ball
|
||||
y = nearY + ny * f.ball
|
||||
val into = vx * nx + vy * ny
|
||||
if (into < 0f) { vx -= 2f * into * nx; vy -= 2f * into * ny }
|
||||
} else if (gap <= 0.0001f) {
|
||||
val outX = if (x < r.center.x) r.left - f.ball - x else r.right + f.ball - x
|
||||
val outY = if (y < r.center.y) r.top - f.ball - y else r.bottom + f.ball - y
|
||||
if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) }
|
||||
else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) }
|
||||
}
|
||||
}
|
||||
}
|
||||
} while (left > 0f)
|
||||
clock.at = Offset(x, y)
|
||||
|
||||
if (before < IMPACT && clock.ball >= IMPACT) {
|
||||
|
||||
@@ -96,8 +96,7 @@ import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.onPlaced
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
|
||||
|
||||
internal val AttentionAmber = Color(0xFFFFB547)
|
||||
internal val AttentionAmber: Color @Composable get() = LocalPalette.current.warning
|
||||
|
||||
@Composable
|
||||
internal fun BottomBar(
|
||||
@@ -308,7 +307,7 @@ private fun RailItem(
|
||||
}
|
||||
if (badge) Box(
|
||||
modifier = Modifier.align(Alignment.TopEnd).padding(top = if (iconOnly) 7.dp else 8.dp, end = if (iconOnly) 9.dp else 18.dp)
|
||||
.size(8.dp).clip(CircleShape).background(AttentionAmber),
|
||||
.size(8.dp).clip(CircleShape).background(pal.warning),
|
||||
)
|
||||
if (count > 0) Text(
|
||||
if (count > 9) "9+" else count.toString(),
|
||||
|
||||
@@ -1254,6 +1254,7 @@ private fun CustomColorRows() {
|
||||
Triple("signal", stringResource(R.string.theme_custom_signal), colors.signal),
|
||||
Triple("good", stringResource(R.string.theme_custom_good), colors.good),
|
||||
Triple("error", stringResource(R.string.theme_custom_error), colors.error),
|
||||
Triple("warning", stringResource(R.string.theme_custom_warning), colors.warning),
|
||||
)
|
||||
|
||||
rows.forEach { (key, label, argb) ->
|
||||
|
||||
@@ -333,7 +333,7 @@ class DrawerActions(
|
||||
val onInputSelection: (com.droiddeck.launcher.input.InputRole?) -> Unit = {},
|
||||
val onGestureSettings: () -> Unit = {},
|
||||
val touchActive: String = "",
|
||||
val directHoldBehavior: String = MOUSE_BEHAVIOR_NONE,
|
||||
val directHoldBehavior: String = MOUSE_BEHAVIOR_CLICK,
|
||||
val onDirectHoldBehavior: (String) -> Unit = {},
|
||||
val onFexPreset: (String) -> Unit,
|
||||
val onUpscaler: (Int) -> Unit = {},
|
||||
|
||||
@@ -82,7 +82,18 @@ import kotlinx.coroutines.withContext
|
||||
private const val WALL_MIN_GAMES = 4
|
||||
private const val WALL_DISTINCT = 40
|
||||
|
||||
private const val DRIFT_STEP_NS = 15_000_000L
|
||||
private const val IDLE_FRAME_NS = 30_000_000L
|
||||
|
||||
internal object IdleFrames {
|
||||
private var shown = 0L
|
||||
|
||||
fun due(nanos: Long): Boolean {
|
||||
if (nanos == shown) return true
|
||||
if (nanos - shown < IDLE_FRAME_NS) return false
|
||||
shown = nanos
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) {
|
||||
@@ -281,7 +292,7 @@ internal fun TiltedWall(
|
||||
var shown = 0L
|
||||
while (true) withFrameNanos { now ->
|
||||
if (shown == 0L) shown = now
|
||||
else if (now - shown >= DRIFT_STEP_NS) {
|
||||
else if (IdleFrames.due(now)) {
|
||||
drift.floatValue = ((drift.floatValue + (now - shown) / (period.value * 1_000_000.0 * Motion.scale)) % 1.0).toFloat()
|
||||
shown = now
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ class Palette(
|
||||
val background: Color, val surface: Color, val surfaceVariant: Color, val line: Color, val line2: Color,
|
||||
val onBackground: Color, val onSurfaceVariant: Color,
|
||||
val primary: Color, val primary2: Color, val onPrimary: Color, val signal: Color,
|
||||
val good: Color, val error: Color = Color(0xFFFF8A80),
|
||||
val good: Color, val error: Color = Color(0xFFFF8A80), val warning: Color = Color(0xFFFFB547),
|
||||
)
|
||||
|
||||
data class CustomThemeColors(
|
||||
@@ -54,6 +54,7 @@ data class CustomThemeColors(
|
||||
val signal: Int = 0xFF1A9FFF.toInt(),
|
||||
val good: Int = 0xFF4CD37F.toInt(),
|
||||
val error: Int = 0xFFFF8A80.toInt(),
|
||||
val warning: Int = 0xFFFFB547.toInt(),
|
||||
)
|
||||
|
||||
object Themes {
|
||||
@@ -144,6 +145,7 @@ object Themes {
|
||||
"signal" -> current.copy(signal = color)
|
||||
"good" -> current.copy(good = color)
|
||||
"error" -> current.copy(error = color)
|
||||
"warning" -> current.copy(warning = color)
|
||||
else -> return
|
||||
}
|
||||
setCustomColors(context, updated)
|
||||
@@ -164,6 +166,7 @@ object Themes {
|
||||
signal = Color(colors.signal),
|
||||
good = Color(colors.good),
|
||||
error = Color(colors.error),
|
||||
warning = Color(colors.warning),
|
||||
)
|
||||
|
||||
fun current(context: Context): Palette {
|
||||
@@ -229,7 +232,9 @@ val Palette.onSignal: Color get() = if (signal.luminance() > 0.18f) Color(0xFF03
|
||||
|
||||
@Composable
|
||||
fun DroidDeckTheme(theme: String? = null, appScale: Int = AppUiPrefs.DEFAULT_SCALE, content: @Composable () -> Unit) {
|
||||
val id = theme ?: SessionPrefs.theme(LocalContext.current)
|
||||
val context = LocalContext.current
|
||||
remember(context) { Themes.loadGradient(context) }
|
||||
val id = theme ?: SessionPrefs.theme(context)
|
||||
if (id == Themes.INNER_GAMER) InnerGamerHue(Themes.rgbSpeed)
|
||||
val p = Themes.byId(id)
|
||||
val scheme = darkColorScheme(
|
||||
|
||||
@@ -4299,6 +4299,7 @@
|
||||
<string name="theme_custom_signal">الإبرازات</string>
|
||||
<string name="theme_custom_good">نجاح</string>
|
||||
<string name="theme_custom_error">خطأ</string>
|
||||
<string name="theme_custom_warning">تحذير</string>
|
||||
<string name="hud_only_during_game">عرض HUD أثناء اللعب فقط</string>
|
||||
<string name="hud_only_during_game_hint">إخفاء HUD عند عدم اكتشاف إطارات اللعبة.</string>
|
||||
<string name="steam_store_close_steam">أغلق Steam أولاً</string>
|
||||
|
||||
@@ -4179,6 +4179,7 @@
|
||||
<string name="theme_custom_signal">Destacados</string>
|
||||
<string name="theme_custom_good">Éxito</string>
|
||||
<string name="theme_custom_error">Error</string>
|
||||
<string name="theme_custom_warning">Advertencia</string>
|
||||
<string name="hud_only_during_game">Mostrar el HUD solo durante una partida</string>
|
||||
<string name="hud_only_during_game_hint">Ocultar el HUD cuando no se detecten fotogramas del juego.</string>
|
||||
<string name="steam_store_close_steam">Cierra Steam primero</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Акценти</string>
|
||||
<string name="theme_custom_good">Успех</string>
|
||||
<string name="theme_custom_error">Грешка</string>
|
||||
<string name="theme_custom_warning">Предупреждение</string>
|
||||
<string name="hud_only_during_game">Показвай HUD само по време на игра</string>
|
||||
<string name="hud_only_during_game_hint">Скривай HUD, когато не се засичат кадри от играта.</string>
|
||||
<string name="steam_store_close_steam">Първо затворете Steam</string>
|
||||
|
||||
@@ -4219,6 +4219,7 @@
|
||||
<string name="theme_custom_signal">Zvýraznění</string>
|
||||
<string name="theme_custom_good">Úspěch</string>
|
||||
<string name="theme_custom_error">Chyba</string>
|
||||
<string name="theme_custom_warning">Varování</string>
|
||||
<string name="hud_only_during_game">Zobrazovat HUD pouze během hry</string>
|
||||
<string name="hud_only_during_game_hint">Skrýt HUD, když nejsou detekovány snímky hry.</string>
|
||||
<string name="steam_store_close_steam">Nejprve zavřete Steam</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Fremhævninger</string>
|
||||
<string name="theme_custom_good">Succes</string>
|
||||
<string name="theme_custom_error">Fejl</string>
|
||||
<string name="theme_custom_warning">Advarsel</string>
|
||||
<string name="hud_only_during_game">Vis kun HUD under spil</string>
|
||||
<string name="hud_only_during_game_hint">Skjul HUD, når der ikke registreres spilbilleder.</string>
|
||||
<string name="steam_store_close_steam">Luk Steam først</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Hervorhebungen</string>
|
||||
<string name="theme_custom_good">Erfolg</string>
|
||||
<string name="theme_custom_error">Fehler</string>
|
||||
<string name="theme_custom_warning">Warnung</string>
|
||||
<string name="hud_only_during_game">HUD nur während eines Spiels anzeigen</string>
|
||||
<string name="hud_only_during_game_hint">HUD ausblenden, wenn keine Spielframes erkannt werden.</string>
|
||||
<string name="steam_store_close_steam">Schließe zuerst Steam</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Επισημάνσεις</string>
|
||||
<string name="theme_custom_good">Επιτυχία</string>
|
||||
<string name="theme_custom_error">Σφάλμα</string>
|
||||
<string name="theme_custom_warning">Προειδοποίηση</string>
|
||||
<string name="hud_only_during_game">Εμφάνιση HUD μόνο κατά τη διάρκεια παιχνιδιού</string>
|
||||
<string name="hud_only_during_game_hint">Απόκρυψη HUD όταν δεν ανιχνεύονται καρέ παιχνιδιού.</string>
|
||||
<string name="steam_store_close_steam">Κλείστε πρώτα το Steam</string>
|
||||
|
||||
@@ -4179,6 +4179,7 @@
|
||||
<string name="theme_custom_signal">Destacados</string>
|
||||
<string name="theme_custom_good">Éxito</string>
|
||||
<string name="theme_custom_error">Error</string>
|
||||
<string name="theme_custom_warning">Advertencia</string>
|
||||
<string name="hud_only_during_game">Mostrar el HUD solo durante una partida</string>
|
||||
<string name="hud_only_during_game_hint">Ocultar el HUD cuando no se detecten fotogramas del juego.</string>
|
||||
<string name="steam_store_close_steam">Cierra Steam primero</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Korostukset</string>
|
||||
<string name="theme_custom_good">Onnistuminen</string>
|
||||
<string name="theme_custom_error">Virhe</string>
|
||||
<string name="theme_custom_warning">Varoitus</string>
|
||||
<string name="hud_only_during_game">Näytä HUD vain pelin aikana</string>
|
||||
<string name="hud_only_during_game_hint">Piilota HUD, kun pelin ruutuja ei havaita.</string>
|
||||
<string name="steam_store_close_steam">Sulje Steam ensin</string>
|
||||
|
||||
@@ -4178,6 +4178,7 @@
|
||||
<string name="theme_custom_signal">Mises en évidence</string>
|
||||
<string name="theme_custom_good">Succès</string>
|
||||
<string name="theme_custom_error">Erreur</string>
|
||||
<string name="theme_custom_warning">Avertissement</string>
|
||||
<string name="hud_only_during_game">Afficher le HUD uniquement pendant une partie</string>
|
||||
<string name="hud_only_during_game_hint">Masquer le HUD lorsqu’aucune image du jeu n’est détectée.</string>
|
||||
<string name="steam_store_close_steam">Fermez d\'abord Steam</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">हाइलाइट</string>
|
||||
<string name="theme_custom_good">सफलता</string>
|
||||
<string name="theme_custom_error">त्रुटि</string>
|
||||
<string name="theme_custom_warning">चेतावनी</string>
|
||||
<string name="hud_only_during_game">HUD केवल गेम के दौरान दिखाएँ</string>
|
||||
<string name="hud_only_during_game_hint">गेम के फ़्रेम का पता न चलने पर HUD छिपाएँ।</string>
|
||||
<string name="steam_store_close_steam">पहले Steam बंद करें</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Kiemelések</string>
|
||||
<string name="theme_custom_good">Siker</string>
|
||||
<string name="theme_custom_error">Hiba</string>
|
||||
<string name="theme_custom_warning">Figyelmeztetés</string>
|
||||
<string name="hud_only_during_game">HUD megjelenítése csak játék közben</string>
|
||||
<string name="hud_only_during_game_hint">HUD elrejtése, ha nem észlelhetők játék képkockái.</string>
|
||||
<string name="steam_store_close_steam">Előbb zárd be a Steamet</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">Sorotan</string>
|
||||
<string name="theme_custom_good">Berhasil</string>
|
||||
<string name="theme_custom_error">Kesalahan</string>
|
||||
<string name="theme_custom_warning">Peringatan</string>
|
||||
<string name="hud_only_during_game">Tampilkan HUD hanya saat bermain</string>
|
||||
<string name="hud_only_during_game_hint">Sembunyikan HUD saat tidak ada frame game yang terdeteksi.</string>
|
||||
<string name="steam_store_close_steam">Tutup Steam terlebih dahulu</string>
|
||||
|
||||
@@ -4178,6 +4178,7 @@
|
||||
<string name="theme_custom_signal">Evidenziazioni</string>
|
||||
<string name="theme_custom_good">Successo</string>
|
||||
<string name="theme_custom_error">Errore</string>
|
||||
<string name="theme_custom_warning">Avviso</string>
|
||||
<string name="hud_only_during_game">Mostra l’HUD solo durante il gioco</string>
|
||||
<string name="hud_only_during_game_hint">Nascondi l’HUD quando non vengono rilevati fotogrammi del gioco.</string>
|
||||
<string name="steam_store_close_steam">Chiudi prima Steam</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">強調表示</string>
|
||||
<string name="theme_custom_good">成功</string>
|
||||
<string name="theme_custom_error">エラー</string>
|
||||
<string name="theme_custom_warning">警告</string>
|
||||
<string name="hud_only_during_game">ゲーム中のみHUDを表示</string>
|
||||
<string name="hud_only_during_game_hint">ゲームのフレームが検出されないときはHUDを非表示にする。</string>
|
||||
<string name="steam_store_close_steam">先に Steam を閉じてください</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">강조 표시</string>
|
||||
<string name="theme_custom_good">성공</string>
|
||||
<string name="theme_custom_error">오류</string>
|
||||
<string name="theme_custom_warning">경고</string>
|
||||
<string name="hud_only_during_game">게임 중에만 HUD 표시</string>
|
||||
<string name="hud_only_during_game_hint">게임 프레임이 감지되지 않으면 HUD 숨기기.</string>
|
||||
<string name="steam_store_close_steam">먼저 Steam을 닫으세요</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">Sorotan</string>
|
||||
<string name="theme_custom_good">Berjaya</string>
|
||||
<string name="theme_custom_error">Ralat</string>
|
||||
<string name="theme_custom_warning">Amaran</string>
|
||||
<string name="hud_only_during_game">Paparkan HUD hanya semasa bermain</string>
|
||||
<string name="hud_only_during_game_hint">Sembunyikan HUD apabila bingkai permainan tidak dikesan.</string>
|
||||
<string name="steam_store_close_steam">Tutup Steam dahulu</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Uthevinger</string>
|
||||
<string name="theme_custom_good">Suksess</string>
|
||||
<string name="theme_custom_error">Feil</string>
|
||||
<string name="theme_custom_warning">Advarsel</string>
|
||||
<string name="hud_only_during_game">Vis HUD bare mens du spiller</string>
|
||||
<string name="hud_only_during_game_hint">Skjul HUD når ingen spillbilder registreres.</string>
|
||||
<string name="steam_store_close_steam">Lukk Steam først</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Accenten</string>
|
||||
<string name="theme_custom_good">Geslaagd</string>
|
||||
<string name="theme_custom_error">Fout</string>
|
||||
<string name="theme_custom_warning">Waarschuwing</string>
|
||||
<string name="hud_only_during_game">HUD alleen tijdens een game weergeven</string>
|
||||
<string name="hud_only_during_game_hint">Verberg de HUD wanneer er geen gameframes worden gedetecteerd.</string>
|
||||
<string name="steam_store_close_steam">Sluit eerst Steam</string>
|
||||
|
||||
@@ -4219,6 +4219,7 @@
|
||||
<string name="theme_custom_signal">Wyróżnienia</string>
|
||||
<string name="theme_custom_good">Sukces</string>
|
||||
<string name="theme_custom_error">Błąd</string>
|
||||
<string name="theme_custom_warning">Ostrzeżenie</string>
|
||||
<string name="hud_only_during_game">Pokazuj HUD tylko podczas gry</string>
|
||||
<string name="hud_only_during_game_hint">Ukryj HUD, gdy nie wykryto klatek gry.</string>
|
||||
<string name="steam_store_close_steam">Najpierw zamknij Steam</string>
|
||||
|
||||
@@ -1812,6 +1812,7 @@
|
||||
<string name="theme_custom_signal">Destaques e indicadores</string>
|
||||
<string name="theme_custom_good">Sucesso</string>
|
||||
<string name="theme_custom_error">Erro</string>
|
||||
<string name="theme_custom_warning">Aviso</string>
|
||||
<string name="pckb_key_esc">Esc</string>
|
||||
<string name="pckb_key_ins">Ins</string>
|
||||
<string name="pckb_key_del">Del</string>
|
||||
|
||||
@@ -1820,6 +1820,7 @@
|
||||
<string name="theme_custom_signal">Destaques e indicadores</string>
|
||||
<string name="theme_custom_good">Sucesso</string>
|
||||
<string name="theme_custom_error">Erro</string>
|
||||
<string name="theme_custom_warning">Aviso</string>
|
||||
<string name="pckb_key_esc">Esc</string>
|
||||
<string name="pckb_key_ins">Ins</string>
|
||||
<string name="pckb_key_del">Del</string>
|
||||
|
||||
@@ -4179,6 +4179,7 @@
|
||||
<string name="theme_custom_signal">Evidențieri</string>
|
||||
<string name="theme_custom_good">Succes</string>
|
||||
<string name="theme_custom_error">Eroare</string>
|
||||
<string name="theme_custom_warning">Avertisment</string>
|
||||
<string name="hud_only_during_game">Afișează HUD-ul doar în timpul jocului</string>
|
||||
<string name="hud_only_during_game_hint">Ascunde HUD-ul când nu sunt detectate cadre ale jocului.</string>
|
||||
<string name="steam_store_close_steam">Închide mai întâi Steam</string>
|
||||
|
||||
@@ -4220,6 +4220,7 @@
|
||||
<string name="theme_custom_signal">Выделения</string>
|
||||
<string name="theme_custom_good">Успех</string>
|
||||
<string name="theme_custom_error">Ошибка</string>
|
||||
<string name="theme_custom_warning">Предупреждение</string>
|
||||
<string name="hud_only_during_game">Показывать HUD только во время игры</string>
|
||||
<string name="hud_only_during_game_hint">Скрывать HUD, когда кадры игры не обнаруживаются.</string>
|
||||
<string name="steam_store_close_steam">Сначала закройте Steam</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Markeringar</string>
|
||||
<string name="theme_custom_good">Lyckades</string>
|
||||
<string name="theme_custom_error">Fel</string>
|
||||
<string name="theme_custom_warning">Varning</string>
|
||||
<string name="hud_only_during_game">Visa HUD endast under spel</string>
|
||||
<string name="hud_only_during_game_hint">Dölj HUD när inga spelbildrutor upptäcks.</string>
|
||||
<string name="steam_store_close_steam">Stäng Steam först</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">จุดเน้น</string>
|
||||
<string name="theme_custom_good">สำเร็จ</string>
|
||||
<string name="theme_custom_error">ข้อผิดพลาด</string>
|
||||
<string name="theme_custom_warning">คำเตือน</string>
|
||||
<string name="hud_only_during_game">แสดง HUD เฉพาะขณะเล่นเกม</string>
|
||||
<string name="hud_only_during_game_hint">ซ่อน HUD เมื่อไม่พบเฟรมของเกม</string>
|
||||
<string name="steam_store_close_steam">ปิด Steam ก่อน</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Vurgular</string>
|
||||
<string name="theme_custom_good">Başarılı</string>
|
||||
<string name="theme_custom_error">Hata</string>
|
||||
<string name="theme_custom_warning">Uyarı</string>
|
||||
<string name="hud_only_during_game">HUD\'yi yalnızca oyun sırasında göster</string>
|
||||
<string name="hud_only_during_game_hint">Oyun kareleri algılanmadığında HUD\'yi gizle.</string>
|
||||
<string name="steam_store_close_steam">Önce Steam\'i kapatın</string>
|
||||
|
||||
@@ -4219,6 +4219,7 @@
|
||||
<string name="theme_custom_signal">Виділення</string>
|
||||
<string name="theme_custom_good">Успіх</string>
|
||||
<string name="theme_custom_error">Помилка</string>
|
||||
<string name="theme_custom_warning">Попередження</string>
|
||||
<string name="hud_only_during_game">Показувати HUD лише під час гри</string>
|
||||
<string name="hud_only_during_game_hint">Приховувати HUD, коли кадри гри не виявляються.</string>
|
||||
<string name="steam_store_close_steam">Спочатку закрийте Steam</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">Điểm nhấn</string>
|
||||
<string name="theme_custom_good">Thành công</string>
|
||||
<string name="theme_custom_error">Lỗi</string>
|
||||
<string name="theme_custom_warning">Cảnh báo</string>
|
||||
<string name="hud_only_during_game">Chỉ hiển thị HUD khi đang chơi</string>
|
||||
<string name="hud_only_during_game_hint">Ẩn HUD khi không phát hiện khung hình trò chơi.</string>
|
||||
<string name="steam_store_close_steam">Hãy đóng Steam trước</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">高亮</string>
|
||||
<string name="theme_custom_good">成功</string>
|
||||
<string name="theme_custom_error">错误</string>
|
||||
<string name="theme_custom_warning">警告</string>
|
||||
<string name="hud_only_during_game">仅在游戏期间显示 HUD</string>
|
||||
<string name="hud_only_during_game_hint">未检测到游戏帧时隐藏 HUD。</string>
|
||||
<string name="steam_store_close_steam">请先关闭 Steam</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">重點標示</string>
|
||||
<string name="theme_custom_good">成功</string>
|
||||
<string name="theme_custom_error">錯誤</string>
|
||||
<string name="theme_custom_warning">警告</string>
|
||||
<string name="hud_only_during_game">只在遊戲期間顯示 HUD</string>
|
||||
<string name="hud_only_during_game_hint">未偵測到遊戲畫面時隱藏 HUD。</string>
|
||||
<string name="steam_store_close_steam">請先關閉 Steam</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">醒目標示</string>
|
||||
<string name="theme_custom_good">成功</string>
|
||||
<string name="theme_custom_error">錯誤</string>
|
||||
<string name="theme_custom_warning">警告</string>
|
||||
<string name="hud_only_during_game">僅在遊戲期間顯示 HUD</string>
|
||||
<string name="hud_only_during_game_hint">未偵測到遊戲畫面時隱藏 HUD。</string>
|
||||
<string name="steam_store_close_steam">請先關閉 Steam</string>
|
||||
|
||||
@@ -2028,6 +2028,7 @@
|
||||
<string name="theme_custom_signal">Highlights</string>
|
||||
<string name="theme_custom_good">Success</string>
|
||||
<string name="theme_custom_error">Error</string>
|
||||
<string name="theme_custom_warning">Warning</string>
|
||||
<string name="pckb_key_esc">Esc</string>
|
||||
<string name="pckb_key_ins">Ins</string>
|
||||
<string name="pckb_key_del">Del</string>
|
||||
|
||||
@@ -29,7 +29,7 @@ class DirectTouchHoldTest {
|
||||
override fun move(pointerId: Int, x: Float, y: Float) { touches += "move $pointerId at $x,$y" }
|
||||
override fun up(pointerId: Int, x: Float, y: Float) { touches += "up $pointerId at $x,$y" }
|
||||
override fun cancel() { touches += "cancel" }
|
||||
}).also { it.configure(TouchGestureConfig(longPressDelay = 500, directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK)) }
|
||||
}).also { it.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 500)) }
|
||||
|
||||
@Test fun holdClicksRightWithoutTouchingTheGame() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
@@ -87,49 +87,18 @@ class DirectTouchHoldTest {
|
||||
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 44.0,30.0"), touches)
|
||||
}
|
||||
|
||||
@Test fun stillHoldStaysHeldWithTheDefaultConfig() {
|
||||
@Test fun stillHoldClicksRightWithTheDefaultConfig() {
|
||||
hold.configure(TouchGestureConfig())
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0"), touches)
|
||||
advance(2000)
|
||||
touch(MotionEvent.ACTION_UP)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 40.0,30.0"), touches)
|
||||
assertTrue(buttons.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aSavedRightClickChoiceIsKept() {
|
||||
val saved = TouchGestureConfig.fromJson(
|
||||
TouchGestureConfig(directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK).toJson())
|
||||
assertEquals(TouchGestureConfig.MOUSE_BEHAVIOR_CLICK, saved.directHoldBehavior)
|
||||
hold.configure(saved)
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
advance(2000)
|
||||
touch(MotionEvent.ACTION_UP)
|
||||
touch(MotionEvent.ACTION_MOVE)
|
||||
assertEquals(listOf("true at 40.0,30.0", "false at 40.0,30.0"), buttons)
|
||||
touch(MotionEvent.ACTION_UP)
|
||||
assertTrue(touches.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aHeldTouchLiftsAtOnce() {
|
||||
hold.configure(TouchGestureConfig())
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
advance(80)
|
||||
touch(MotionEvent.ACTION_UP)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 40.0,30.0"), touches)
|
||||
}
|
||||
|
||||
@Test fun aShortTapStaysPressedLongEnoughToBeSeen() {
|
||||
hold.configure(TouchGestureConfig())
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
advance(10)
|
||||
touch(MotionEvent.ACTION_UP)
|
||||
advance(39)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0"), touches)
|
||||
advance(1)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 40.0,30.0"), touches)
|
||||
}
|
||||
|
||||
@Test fun longPressFollowsTheConfiguredDelay() {
|
||||
hold.configure(TouchGestureConfig(longPressDelay = 800, directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK))
|
||||
hold.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 800))
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
advance(700)
|
||||
assertTrue(buttons.isEmpty())
|
||||
@@ -232,6 +201,25 @@ class DirectTouchHoldTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun aDragLiftsAtOnce() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
touch(MotionEvent.ACTION_MOVE, 80f)
|
||||
advance(80)
|
||||
touches.clear()
|
||||
touch(MotionEvent.ACTION_UP, 80f)
|
||||
assertEquals(listOf("up 0 at 80.0,30.0"), touches)
|
||||
}
|
||||
|
||||
@Test fun aTapStaysPressedLongEnoughToBeSeen() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
advance(10)
|
||||
touch(MotionEvent.ACTION_UP)
|
||||
advance(49)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0"), touches)
|
||||
advance(1)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 40.0,30.0"), touches)
|
||||
}
|
||||
|
||||
private fun advance(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms))
|
||||
private fun touch(action: Int, x: Float = 40f): Boolean {
|
||||
val event = MotionEvent.obtain(0, 0, action, x, 30f, 0)
|
||||
|
||||
@@ -152,8 +152,7 @@ class SessionGestureRoutingTest {
|
||||
|
||||
@Test fun pausingCancelsPendingHoldsInBothTouchModes() {
|
||||
for (mode in listOf(SessionPrefs.TOUCH_GESTURES, SessionPrefs.TOUCH_DIRECT)) {
|
||||
prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E",
|
||||
directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK))
|
||||
prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E"))
|
||||
val now = SystemClock.uptimeMillis()
|
||||
val event = MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN, 400f, 300f, 0)
|
||||
try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() }
|
||||
@@ -168,8 +167,7 @@ class SessionGestureRoutingTest {
|
||||
for (mode in listOf(SessionPrefs.TOUCH_GESTURES, SessionPrefs.TOUCH_DIRECT)) {
|
||||
keys.clear()
|
||||
directButtons.clear()
|
||||
prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E",
|
||||
directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK))
|
||||
prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E"))
|
||||
val now = SystemClock.uptimeMillis()
|
||||
val event = MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN, 400f, 300f, 0)
|
||||
try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() }
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class IdleFramesTest {
|
||||
@Test
|
||||
fun idleLoopsDrawThirtyFramesASecondAndShareEachOne() {
|
||||
val start = 5_000_000_000L
|
||||
val frame = 8_333_333L
|
||||
val drawn = (0 until 120).count { IdleFrames.due(start + it * frame) }
|
||||
assertEquals(30, drawn)
|
||||
|
||||
val later = start + 1_000_000_000L
|
||||
assertEquals(listOf(true, true, true), List(3) { IdleFrames.due(later) })
|
||||
assertEquals(listOf(false, false), List(2) { IdleFrames.due(later + frame) })
|
||||
assertEquals(listOf(true, true), List(2) { IdleFrames.due(later + 4 * frame) })
|
||||
}
|
||||
}
|
||||
@@ -1161,6 +1161,7 @@ int system(const char *command) {
|
||||
|
||||
int status = -1;
|
||||
pid_t pid = start_shell(command, -1, -1, &old, &intr, &quit, 0);
|
||||
if (pid < 0) status = 127 << 8; // as glibc's system() when the shell could not be started
|
||||
if (pid > 0) {
|
||||
while (waitpid(pid, &status, 0) < 0) {
|
||||
if (errno != EINTR) {
|
||||
@@ -1192,28 +1193,52 @@ static pthread_mutex_t g_popen_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
static pid_t start_shell(const char *command, int child_fd, int target_fd, const sigset_t *mask,
|
||||
const struct sigaction *intr, const struct sigaction *quit, int close_popen_streams) {
|
||||
pid_t pid = fork();
|
||||
if (pid != 0) return pid;
|
||||
if (intr) sigaction(SIGINT, intr, NULL);
|
||||
if (quit) sigaction(SIGQUIT, quit, NULL);
|
||||
if (mask) sigprocmask(SIG_SETMASK, mask, NULL);
|
||||
// Through posix_spawn(), as glibc does: its child only makes system calls. A forked child running
|
||||
// the exec code here would take locks that another thread of a multithreaded caller may have held
|
||||
// at fork(), and wait for them forever (Steam's popen()s did, and its main loop stalled).
|
||||
posix_spawn_file_actions_t actions;
|
||||
posix_spawnattr_t attr;
|
||||
if (posix_spawn_file_actions_init(&actions) != 0) return -1;
|
||||
if (posix_spawnattr_init(&attr) != 0) {
|
||||
posix_spawn_file_actions_destroy(&actions);
|
||||
return -1;
|
||||
}
|
||||
int err = 0;
|
||||
if (child_fd >= 0) {
|
||||
if (child_fd == target_fd) {
|
||||
fcntl(target_fd, F_SETFD, 0);
|
||||
} else if (dup2(child_fd, target_fd) < 0) {
|
||||
_exit(127);
|
||||
}
|
||||
// dup2 onto itself clears FD_CLOEXEC in the child (glibc 2.29 and later)
|
||||
err = posix_spawn_file_actions_adddup2(&actions, child_fd, target_fd);
|
||||
}
|
||||
// POSIX: the streams of earlier popen() calls are not open in the new shell
|
||||
if (close_popen_streams) {
|
||||
for (struct ddnatv_popen *p = g_popen_streams; p; p = p->next) {
|
||||
int fd = fileno(p->fp);
|
||||
if (fd >= 0 && fd != target_fd) close(fd);
|
||||
}
|
||||
for (struct ddnatv_popen *p = g_popen_streams; !err && close_popen_streams && p; p = p->next) {
|
||||
int fd = fileno(p->fp);
|
||||
if (fd >= 0 && fd != target_fd) err = posix_spawn_file_actions_addclose(&actions, fd);
|
||||
}
|
||||
short flags = 0;
|
||||
if (!err && mask) {
|
||||
posix_spawnattr_setsigmask(&attr, mask);
|
||||
flags |= POSIX_SPAWN_SETSIGMASK;
|
||||
}
|
||||
// SIGINT and SIGQUIT as they were before system() ignored them: an exec keeps an ignored signal
|
||||
// ignored and puts a handled one back to the default
|
||||
sigset_t defaults;
|
||||
sigemptyset(&defaults);
|
||||
if (intr && intr->sa_handler != SIG_IGN) sigaddset(&defaults, SIGINT);
|
||||
if (quit && quit->sa_handler != SIG_IGN) sigaddset(&defaults, SIGQUIT);
|
||||
if (!err && (intr || quit)) {
|
||||
posix_spawnattr_setsigdefault(&attr, &defaults);
|
||||
flags |= POSIX_SPAWN_SETSIGDEF;
|
||||
}
|
||||
if (!err) err = posix_spawnattr_setflags(&attr, flags);
|
||||
pid_t pid = -1;
|
||||
char *const argv[] = { (char *)"sh", (char *)"-c", (char *)command, NULL };
|
||||
ddnatv_execve("/bin/sh", argv, environ, 0);
|
||||
_exit(127);
|
||||
if (!err) err = posix_spawn(&pid, "/bin/sh", &actions, &attr, argv, environ);
|
||||
posix_spawn_file_actions_destroy(&actions);
|
||||
posix_spawnattr_destroy(&attr);
|
||||
if (err) {
|
||||
errno = err;
|
||||
return -1;
|
||||
}
|
||||
return pid;
|
||||
}
|
||||
|
||||
FILE *popen(const char *command, const char *type) {
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
# The rootfs' /bin/sh for these tests: "sh -c 'echo WORDS'" prints WORDS, "sh -c 'exit N'" exits N.
|
||||
SHELL = r"""
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 3 || strcmp(argv[1], "-c") != 0) return 2;
|
||||
if (strncmp(argv[2], "echo ", 5) == 0) {
|
||||
puts(argv[2] + 5);
|
||||
return 0;
|
||||
}
|
||||
if (strncmp(argv[2], "exit ", 5) == 0) return atoi(argv[2] + 5);
|
||||
return 127;
|
||||
}
|
||||
"""
|
||||
|
||||
# posix_spawn() of argv[1] -c "exit 3", without the hook: prints the exit status it got
|
||||
SPAWN_PROBE = r"""
|
||||
#include <spawn.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/wait.h>
|
||||
|
||||
extern char **environ;
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
pid_t pid;
|
||||
char *args[] = {"sh", "-c", "exit 3", NULL};
|
||||
int status = 0;
|
||||
if (posix_spawn(&pid, argv[1], NULL, NULL, args, environ) != 0 || waitpid(pid, &status, 0) != pid) return 1;
|
||||
printf("%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
# popen() and system() through the hook (which starts the shell with posix_spawn())
|
||||
PROGRAM = r"""
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/wait.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (strcmp(argv[1], "system") == 0) {
|
||||
int status = system("exit 3");
|
||||
printf("system\t%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1);
|
||||
return 0;
|
||||
}
|
||||
// a second stream open while the first is read: the shell of the first must not hold it
|
||||
FILE *other = popen("echo other", "r");
|
||||
FILE *f = popen("echo from the shell", "r");
|
||||
char line[64] = "";
|
||||
if (f && !fgets(line, sizeof(line), f)) line[0] = 0;
|
||||
line[strcspn(line, "\n")] = 0;
|
||||
int status = f ? pclose(f) : -1;
|
||||
if (other) pclose(other);
|
||||
printf("popen\t%s\n", line);
|
||||
printf("pclose\t%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NativeHookPopenTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.cc, cls.prefix = runner()
|
||||
if cls.cc is None:
|
||||
raise unittest.SkipTest("no aarch64 compiler and runner")
|
||||
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
cls.root = tmp / "root"
|
||||
(cls.root / "bin").mkdir(parents=True)
|
||||
(tmp / "sh.c").write_text(SHELL)
|
||||
subprocess.run([cls.cc, "-static", "-O1", "-o", str(cls.root / "bin/sh"), str(tmp / "sh.c")], check=True)
|
||||
# posix_spawn()'s child execs the shell itself. Under qemu-user that exec works only where the
|
||||
# kernel runs aarch64 programs (binfmt_misc), which a plain x86 runner does not.
|
||||
(tmp / "spawn.c").write_text(SPAWN_PROBE)
|
||||
subprocess.run([cls.cc, "-static", "-O1", "-o", str(tmp / "spawn"), str(tmp / "spawn.c")], check=True)
|
||||
probe = subprocess.run(list(cls.prefix or []) + [str(tmp / "spawn"), str(cls.root / "bin/sh")],
|
||||
capture_output=True, text=True, timeout=60)
|
||||
if probe.stdout.strip() != "3":
|
||||
cls.tmp.cleanup()
|
||||
raise unittest.SkipTest("this runner cannot exec an aarch64 program from a posix_spawn() child")
|
||||
(tmp / "prog.c").write_text(PROGRAM)
|
||||
cls.program = tmp / "prog"
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(cls.program), str(tmp / "prog.c")], check=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_program(self, mode):
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)}
|
||||
# Only what the program needs: other test modules in the same run change os.environ
|
||||
env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin")}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(self.program), mode], env=env, capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
return dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line), out
|
||||
|
||||
def test_popen_reads_the_shells_output(self):
|
||||
result, out = self.run_program("popen")
|
||||
self.assertEqual("from the shell", result.get("popen"), out.stdout + out.stderr)
|
||||
self.assertEqual("0", result.get("pclose"), out.stdout)
|
||||
|
||||
def test_system_returns_the_shells_status(self):
|
||||
result, out = self.run_program("system")
|
||||
self.assertEqual("3", result.get("system"), out.stdout + out.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+10
-2
@@ -120,8 +120,16 @@ from the content service. The WU endpoint needs no Xbox credential but chains to
|
||||
Product Root CA 2018, which Android's CA bundle does not carry, so that one public root is
|
||||
pinned in `wu-root.pem` for these requests. Only `.eappx`/`.eappxbundle` files from a WU result
|
||||
are kept; the `.appx` framework packages and `.cab` metadata beside them are dropped. Licensing
|
||||
runs before the first byte and must return content keys. Free space is checked against the
|
||||
download plus two copies of the largest container, and each container is deleted once unpacked.
|
||||
runs before the first byte and must return content keys. Bundle members are read in place, and
|
||||
where the filesystem can punch holes the container blocks already decrypted are freed as the
|
||||
unpack runs, so an install needs about the size of the download free before it starts. After the
|
||||
download, the packages' blockmaps give an exact check before anything is unpacked: growth from
|
||||
inflation, two blocks per file and the data in flight; a failed check keeps the download. Storage
|
||||
that cannot punch holes needs the download plus the largest container and a tenth of it before the
|
||||
download, and the container plus its full unpacked size after it; a package that cannot be measured
|
||||
(a bundle with compressed members) counts its own size and a tenth. A container is renamed to
|
||||
`.unpacking` before its first block is freed, so an interrupted unpack downloads it again, and it is
|
||||
renamed back when the filesystem refuses the first punch. Each container is deleted once unpacked.
|
||||
The download has no control channel: cancelling kills it and the next attempt starts that
|
||||
container from zero.
|
||||
|
||||
|
||||
@@ -57,10 +57,15 @@ index 088a6d0..825c24e 100644
|
||||
pub mod social;
|
||||
pub mod game_activity;
|
||||
diff --git a/crates/xodus-cli/src/commands/extract_eappx.rs b/crates/xodus-cli/src/commands/extract_eappx.rs
|
||||
index 5ea43da..0bad98e 100644
|
||||
index 5ea43da..e236002 100644
|
||||
--- a/crates/xodus-cli/src/commands/extract_eappx.rs
|
||||
+++ b/crates/xodus-cli/src/commands/extract_eappx.rs
|
||||
@@ -51,6 +51,8 @@ pub struct Meter {
|
||||
@@ -1,3 +1,4 @@
|
||||
+use std::os::unix::fs::FileExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
@@ -51,6 +52,8 @@ pub struct Meter {
|
||||
pub banked: std::sync::atomic::AtomicU64,
|
||||
/// Bytes the package being unpacked now will write in total.
|
||||
pub total: std::sync::atomic::AtomicU64,
|
||||
@@ -69,7 +74,7 @@ index 5ea43da..0bad98e 100644
|
||||
turn: std::sync::Mutex<()>,
|
||||
}
|
||||
|
||||
@@ -61,7 +63,14 @@ impl Meter {
|
||||
@@ -61,7 +64,14 @@ impl Meter {
|
||||
let _turn = self.turn.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let banked = self.banked.load(Relaxed);
|
||||
let total = self.total.load(Relaxed);
|
||||
@@ -85,7 +90,7 @@ index 5ea43da..0bad98e 100644
|
||||
}
|
||||
|
||||
pub fn done(&self) -> u64 {
|
||||
@@ -79,6 +88,8 @@ impl Meter {
|
||||
@@ -79,6 +89,8 @@ impl Meter {
|
||||
self.banked.fetch_add(self.total.load(Relaxed), Relaxed);
|
||||
self.written.store(0, Relaxed);
|
||||
self.total.store(total, Relaxed);
|
||||
@@ -94,40 +99,636 @@ index 5ea43da..0bad98e 100644
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,6 +271,9 @@ fn derive(
|
||||
@@ -129,16 +141,30 @@ pub fn run_blocking(
|
||||
}
|
||||
}
|
||||
|
||||
- match derive(
|
||||
- Path::new(&path),
|
||||
- Path::new(&destination),
|
||||
- &key_collection,
|
||||
- 0,
|
||||
- meter,
|
||||
- release,
|
||||
- ) {
|
||||
- Ok(()) => ExitCode::SUCCESS,
|
||||
- Err(failure) => report_failure(&failure, ExitCode::FAILURE),
|
||||
+ let origin = Path::new(&path);
|
||||
+ let container = match std::fs::File::open(origin) {
|
||||
+ Ok(file) => file,
|
||||
+ Err(e) => return report_failure(&Failure::at("open", origin, &e.to_string()), ExitCode::FAILURE),
|
||||
+ };
|
||||
+ let len = match container.metadata() {
|
||||
+ Ok(meta) => meta.len(),
|
||||
+ Err(e) => return report_failure(&Failure::at("open", origin, &e.to_string()), ExitCode::FAILURE),
|
||||
+ };
|
||||
+ let release = release.then(|| Release::open(origin, &container));
|
||||
+ let source = Source { file: &container, origin, name: origin.to_path_buf(), start: 0, len };
|
||||
+ match derive(&source, Path::new(&destination), &key_collection, 0, meter, release.as_ref()) {
|
||||
+ Ok(()) => {
|
||||
+ if let Some(release) = &release {
|
||||
+ release.finish();
|
||||
+ }
|
||||
+ ExitCode::SUCCESS
|
||||
+ }
|
||||
+ Err(failure) => {
|
||||
+ if let Some(release) = &release {
|
||||
+ release.abandon();
|
||||
+ }
|
||||
+ report_failure(&failure, ExitCode::FAILURE)
|
||||
+ }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,17 +223,285 @@ fn is_eappx(path: &Path) -> bool {
|
||||
matches!(&magic, b"EXPH" | b"EXSH" | b"EXBH")
|
||||
}
|
||||
|
||||
+struct Source<'a> {
|
||||
+ file: &'a std::fs::File,
|
||||
+ origin: &'a Path,
|
||||
+ name: PathBuf,
|
||||
+ start: u64,
|
||||
+ len: u64,
|
||||
+}
|
||||
+
|
||||
+impl<'a> Source<'a> {
|
||||
+ fn inner(&self, member: &Member) -> Option<Source<'a>> {
|
||||
+ let info = &member.info;
|
||||
+ if info.compression_type == 1 || info.offset_to_file.checked_add(info.uncompressed_length)? > self.len {
|
||||
+ return None;
|
||||
+ }
|
||||
+ let start = self.start.checked_add(info.offset_to_file)?;
|
||||
+ let mut magic = [0u8; 4];
|
||||
+ self.file.read_exact_at(&mut magic, start).ok()?;
|
||||
+ matches!(&magic, b"EXPH" | b"EXSH" | b"EXBH").then(|| Source {
|
||||
+ file: self.file,
|
||||
+ origin: self.origin,
|
||||
+ name: PathBuf::from(member.name.replace('\\', "/")),
|
||||
+ start,
|
||||
+ len: info.uncompressed_length,
|
||||
+ })
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+struct Window<'r> {
|
||||
+ file: std::fs::File,
|
||||
+ start: u64,
|
||||
+ len: u64,
|
||||
+ pos: u64,
|
||||
+ release: Option<&'r Release>,
|
||||
+ spend: Option<(u64, u64)>,
|
||||
+}
|
||||
+
|
||||
+impl<'r> Window<'r> {
|
||||
+ fn open(source: &Source, release: Option<&'r Release>) -> std::io::Result<Self> {
|
||||
+ Ok(Self { file: source.file.try_clone()?, start: source.start, len: source.len, pos: 0, release, spend: None })
|
||||
+ }
|
||||
+
|
||||
+ fn spend(&mut self, offset: u64, length: u64) {
|
||||
+ let Some(release) = self.release else { return };
|
||||
+ let from = self.start.saturating_add(offset);
|
||||
+ let to = from.saturating_add(length).min(self.start.saturating_add(self.len));
|
||||
+ self.spend = Some((release.align_up(from), to));
|
||||
+ }
|
||||
+
|
||||
+ fn settle(&mut self) {
|
||||
+ if let (Some(release), Some((from, to))) = (self.release, self.spend.take()) {
|
||||
+ release.give_back(from, release.align_down(to));
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ fn advance(&mut self) {
|
||||
+ let (Some(release), Some((from, to))) = (self.release, self.spend) else { return };
|
||||
+ let reached = release.align_down(self.start.saturating_add(self.pos).min(to));
|
||||
+ if reached >= from.saturating_add(SPEND_STEP) {
|
||||
+ release.give_back(from, reached);
|
||||
+ self.spend = Some((reached, to));
|
||||
+ }
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+impl std::io::Read for Window<'_> {
|
||||
+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
+ let left = self.len.saturating_sub(self.pos);
|
||||
+ let wanted = buf.len().min(usize::try_from(left).unwrap_or(usize::MAX));
|
||||
+ if wanted == 0 {
|
||||
+ return Ok(0);
|
||||
+ }
|
||||
+ let read = self.file.read_at(&mut buf[..wanted], self.start + self.pos)?;
|
||||
+ self.pos += read as u64;
|
||||
+ self.advance();
|
||||
+ Ok(read)
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+impl std::io::Seek for Window<'_> {
|
||||
+ fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result<u64> {
|
||||
+ let next = match to {
|
||||
+ std::io::SeekFrom::Start(offset) => Some(offset),
|
||||
+ std::io::SeekFrom::End(delta) => self.len.checked_add_signed(delta),
|
||||
+ std::io::SeekFrom::Current(delta) => self.pos.checked_add_signed(delta),
|
||||
+ };
|
||||
+ self.pos = next.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "seek outside the package"))?;
|
||||
+ Ok(self.pos)
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+const SPEND_STEP: u64 = 64 << 20;
|
||||
+const SPENT_SUFFIX: &str = ".unpacking";
|
||||
+
|
||||
+#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
+enum Spent {
|
||||
+ Intact,
|
||||
+ Moved,
|
||||
+ Punched,
|
||||
+ Kept,
|
||||
+ Spoiled,
|
||||
+}
|
||||
+
|
||||
+struct Release {
|
||||
+ origin: PathBuf,
|
||||
+ spent: PathBuf,
|
||||
+ file: Option<std::fs::File>,
|
||||
+ block: u64,
|
||||
+ state: std::sync::Mutex<Spent>,
|
||||
+}
|
||||
+
|
||||
+impl Release {
|
||||
+ fn open(origin: &Path, container: &std::fs::File) -> Self {
|
||||
+ let mut spent = origin.as_os_str().to_owned();
|
||||
+ spent.push(SPENT_SUFFIX);
|
||||
+ let file = std::fs::OpenOptions::new().write(true).open(origin).ok();
|
||||
+ let state = if file.is_some() { Spent::Intact } else { Spent::Kept };
|
||||
+ Self {
|
||||
+ origin: origin.to_path_buf(),
|
||||
+ spent: PathBuf::from(spent),
|
||||
+ file,
|
||||
+ block: block_size(container),
|
||||
+ state: std::sync::Mutex::new(state),
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ fn align_up(&self, at: u64) -> u64 {
|
||||
+ at.div_ceil(self.block).saturating_mul(self.block)
|
||||
+ }
|
||||
+
|
||||
+ fn align_down(&self, at: u64) -> u64 {
|
||||
+ at - at % self.block
|
||||
+ }
|
||||
+
|
||||
+ fn give_back(&self, from: u64, to: u64) {
|
||||
+ if to <= from {
|
||||
+ return;
|
||||
+ }
|
||||
+ let Some(file) = &self.file else { return };
|
||||
+ let mut state = self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
+ if *state == Spent::Intact {
|
||||
+ *state = if std::fs::rename(&self.origin, &self.spent).is_ok() { Spent::Moved } else { Spent::Kept };
|
||||
+ }
|
||||
+ if !matches!(*state, Spent::Moved | Spent::Punched) {
|
||||
+ return;
|
||||
+ }
|
||||
+ let mode = rustix::fs::FallocateFlags::PUNCH_HOLE | rustix::fs::FallocateFlags::KEEP_SIZE;
|
||||
+ *state = match (rustix::fs::fallocate(file, mode, from, to - from).is_ok(), *state) {
|
||||
+ (true, _) => Spent::Punched,
|
||||
+ (false, Spent::Moved) => self.restore(),
|
||||
+ (false, _) => Spent::Spoiled,
|
||||
+ };
|
||||
+ }
|
||||
+
|
||||
+ fn restore(&self) -> Spent {
|
||||
+ if std::fs::rename(&self.spent, &self.origin).is_ok() { Spent::Kept } else { Spent::Spoiled }
|
||||
+ }
|
||||
+
|
||||
+ fn finish(&self) {
|
||||
+ std::fs::remove_file(&self.origin).ok();
|
||||
+ std::fs::remove_file(&self.spent).ok();
|
||||
+ }
|
||||
+
|
||||
+ fn abandon(&self) {
|
||||
+ let mut state = self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
+ if *state == Spent::Moved {
|
||||
+ *state = self.restore();
|
||||
+ }
|
||||
+ if matches!(*state, Spent::Punched | Spent::Spoiled) {
|
||||
+ std::fs::remove_file(&self.spent).ok();
|
||||
+ }
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+fn block_size(file: &std::fs::File) -> u64 {
|
||||
+ use std::os::unix::fs::MetadataExt;
|
||||
+ file.metadata().map(|meta| meta.blksize()).ok().filter(|size| size.is_power_of_two()).unwrap_or(4096)
|
||||
+}
|
||||
+
|
||||
+pub fn releases_space(dir: &Path) -> bool {
|
||||
+ use std::io::Write;
|
||||
+ let Ok(mut probe) = tempfile::tempfile_in(dir) else { return false };
|
||||
+ if probe.write_all(&[1u8; 1 << 16]).and_then(|()| probe.sync_data()).is_err() {
|
||||
+ return false;
|
||||
+ }
|
||||
+ let mode = rustix::fs::FallocateFlags::PUNCH_HOLE | rustix::fs::FallocateFlags::KEEP_SIZE;
|
||||
+ rustix::fs::fallocate(&probe, mode, 0, 1 << 16).is_ok()
|
||||
+}
|
||||
+
|
||||
+struct Layout {
|
||||
+ bounds: Vec<u64>,
|
||||
+ len: u64,
|
||||
+}
|
||||
+
|
||||
+impl Layout {
|
||||
+ fn of(eappx: &EAppxFile, len: u64) -> Self {
|
||||
+ let header = &eappx.header;
|
||||
+ let mut bounds: Vec<u64> = eappx
|
||||
+ .footers
|
||||
+ .iter()
|
||||
+ .map(|footer| footer.offset_to_file)
|
||||
+ .chain([header.footer_offset, header.signature_offset, header.code_integrity_offset])
|
||||
+ .collect();
|
||||
+ bounds.sort_unstable();
|
||||
+ bounds.dedup();
|
||||
+ Self { bounds, len }
|
||||
+ }
|
||||
+
|
||||
+ fn stored(&self, info: &eappx::FileInfo) -> u64 {
|
||||
+ let size = if info.compression_type == 1 { info.compressed_length } else { info.uncompressed_length };
|
||||
+ let next = self
|
||||
+ .bounds
|
||||
+ .get(self.bounds.partition_point(|&bound| bound <= info.offset_to_file))
|
||||
+ .copied()
|
||||
+ .unwrap_or(self.len);
|
||||
+ info.offset_to_file.saturating_add(size).min(next).min(self.len).saturating_sub(info.offset_to_file)
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+struct Member {
|
||||
+ name: String,
|
||||
+ info: eappx::FileInfo,
|
||||
+}
|
||||
+
|
||||
+fn bundle_members<R: std::io::BufRead + std::io::Seek>(eappx: &EAppxFile, reader: &mut R) -> Result<Vec<Member>, String> {
|
||||
+ let eappx::Manifest::BundleManifest(manifest) = eappx.read_manifest(reader).map_err(|e| e.to_string())? else {
|
||||
+ return Err("the bundle carries no bundle manifest".into());
|
||||
+ };
|
||||
+ manifest
|
||||
+ .packages
|
||||
+ .package
|
||||
+ .into_iter()
|
||||
+ .enumerate()
|
||||
+ .map(|(index, package)| {
|
||||
+ let footer = eappx
|
||||
+ .find_footer_for_file(index as u64)
|
||||
+ .ok_or_else(|| format!("bundle file {} is not in the footers", package.filename))?;
|
||||
+ if footer.offset_to_file != package.offset {
|
||||
+ return Err(format!("bundle file {} disagrees with its footer about its offset", package.filename));
|
||||
+ }
|
||||
+ Ok(Member { name: package.filename, info: eappx::FileInfo::from(footer) })
|
||||
+ })
|
||||
+ .collect()
|
||||
+}
|
||||
+
|
||||
+fn save(
|
||||
+ eappx: &EAppxFile,
|
||||
+ layout: &Layout,
|
||||
+ stream: &mut std::io::BufReader<Window<'_>>,
|
||||
+ info: eappx::FileInfo,
|
||||
+ outdir: &Path,
|
||||
+ name: &str,
|
||||
+) -> Result<(), eappx::error::Error> {
|
||||
+ stream.get_mut().spend(info.offset_to_file, layout.stored(&info));
|
||||
+ let saved = eappx.save_file_to_fs(stream, info, outdir, name);
|
||||
+ if saved.is_ok() {
|
||||
+ stream.get_mut().settle();
|
||||
+ } else {
|
||||
+ stream.get_mut().spend = None;
|
||||
+ }
|
||||
+ saved
|
||||
+}
|
||||
+
|
||||
+fn stem(name: &Path) -> Result<String, Failure> {
|
||||
+ name.file_stem()
|
||||
+ .map(|stem| stem.to_string_lossy().into_owned())
|
||||
+ .ok_or_else(|| Failure::at("no-name", name, "package without a usable name"))
|
||||
+}
|
||||
+
|
||||
fn derive(
|
||||
- infile: &Path,
|
||||
+ source: &Source,
|
||||
outdir: &Path,
|
||||
keys: &KeyCollection,
|
||||
depth: usize,
|
||||
meter: Option<&Meter>,
|
||||
- release: bool,
|
||||
+ release: Option<&Release>,
|
||||
) -> Result<(), Failure> {
|
||||
- let file = std::fs::File::open(infile)
|
||||
- .map_err(|e| Failure::at("open", infile, &e.to_string()))?;
|
||||
- let mut reader = std::io::BufReader::new(file);
|
||||
+ let infile = source.name.as_path();
|
||||
+ let window = Window::open(source, release).map_err(|e| Failure::at("open", infile, &e.to_string()))?;
|
||||
+ let mut reader = std::io::BufReader::new(window);
|
||||
|
||||
let mut eappx = EAppxFile::from_stream(&mut reader)
|
||||
.map_err(|e| Failure::at("header", infile, &e.to_string()))?;
|
||||
@@ -236,8 +530,16 @@ fn derive(
|
||||
std::fs::create_dir_all(outdir)
|
||||
.map_err(|e| Failure::at("create-dir", outdir, &e.to_string()))?;
|
||||
|
||||
- unpack(infile, &eappx, &mut reader, outdir, meter, release)?;
|
||||
- // The handle must close before a released container gives its space back.
|
||||
+ eappx
|
||||
+ .extract_footprint_files(&mut reader, outdir)
|
||||
+ .map_err(|e| Failure::at("extract", infile, &e.to_string()))?;
|
||||
+
|
||||
+ let inner = if eappx.header.is_bundle() {
|
||||
+ unbundle(source, &eappx, &mut reader, outdir, meter)?
|
||||
+ } else {
|
||||
+ unpack(source, &eappx, outdir, meter, release)?;
|
||||
+ Vec::new()
|
||||
+ };
|
||||
drop(reader);
|
||||
|
||||
println!("Extracted {}", infile.file_name().unwrap_or_default().to_string_lossy());
|
||||
@@ -248,33 +550,189 @@ fn derive(
|
||||
// The container being unpacked may itself sit in the destination, which is
|
||||
// what `extract-eappx ./title.eappx .` asks for. Re-entering it would
|
||||
// recurse into the same bytes and then delete the caller's file.
|
||||
- .filter(|path| std::fs::canonicalize(path).ok() != std::fs::canonicalize(infile).ok())
|
||||
+ .filter(|path| std::fs::canonicalize(path).ok() != std::fs::canonicalize(source.origin).ok())
|
||||
.filter(|path| path.is_file() && is_eappx(path))
|
||||
.collect();
|
||||
nested.sort();
|
||||
|
||||
- if nested.is_empty() {
|
||||
+ if inner.is_empty() && nested.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if depth >= MAX_BUNDLE_DEPTH {
|
||||
return Err(Failure::at("nesting", infile, "bundle nesting exceeds the limit"));
|
||||
}
|
||||
|
||||
- for child in nested {
|
||||
- let name = child
|
||||
- .file_stem()
|
||||
- .map(|name| name.to_string_lossy().into_owned())
|
||||
- .ok_or_else(|| Failure::at("no-name", &child, "package without a usable name"))?;
|
||||
- derive(&child, &outdir.join(&name), keys, depth + 1, meter, release)?;
|
||||
+ let opened = nested
|
||||
+ .into_iter()
|
||||
+ .map(|path| {
|
||||
+ let file = std::fs::File::open(&path).map_err(|e| Failure::at("open", &path, &e.to_string()))?;
|
||||
+ let len = file.metadata().map_err(|e| Failure::at("open", &path, &e.to_string()))?.len();
|
||||
+ Ok((path, file, len))
|
||||
+ })
|
||||
+ .collect::<Result<Vec<_>, Failure>>()?;
|
||||
+ let children: Vec<Source> = opened
|
||||
+ .iter()
|
||||
+ .map(|(path, file, len)| Source { file, origin: source.origin, name: path.clone(), start: 0, len: *len })
|
||||
+ .collect();
|
||||
+
|
||||
+ if let Some(meter) = meter {
|
||||
+ meter.expect(nested.iter().map(|child| package_size(child)).sum());
|
||||
+ meter.expect(inner.iter().map(package_size).sum::<u64>() + children.iter().map(package_size).sum::<u64>());
|
||||
+ }
|
||||
for child in nested {
|
||||
let name = child
|
||||
.file_stem()
|
||||
@@ -275,6 +289,14 @@ fn derive(
|
||||
+ for member in &inner {
|
||||
+ derive(member, &outdir.join(stem(&member.name)?), keys, depth + 1, meter, release)?;
|
||||
+ }
|
||||
+ for child in &children {
|
||||
+ derive(child, &outdir.join(stem(&child.name)?), keys, depth + 1, meter, None)?;
|
||||
// The member's bytes are no longer needed once its contents are on disk.
|
||||
// A bundle of a full title holds tens of gigabytes, and keeping every
|
||||
// member beside the decrypted copy doubles what the install occupies.
|
||||
- std::fs::remove_file(&child).ok();
|
||||
+ std::fs::remove_file(&child.name).ok();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+fn unbundle<'a>(
|
||||
+ source: &Source<'a>,
|
||||
+ eappx: &EAppxFile,
|
||||
+ reader: &mut std::io::BufReader<Window<'_>>,
|
||||
+ outdir: &Path,
|
||||
+ meter: Option<&Meter>,
|
||||
+) -> Result<Vec<Source<'a>>, Failure> {
|
||||
+ let infile = source.name.as_path();
|
||||
+ let members = bundle_members(eappx, reader).map_err(|e| Failure::at("extract", infile, &e))?;
|
||||
+ let shared: Vec<u64> = members.iter().map(|member| member.info.offset_to_file).collect();
|
||||
+
|
||||
+ let mut written = Vec::new();
|
||||
+ for file in &eappx.blockmap.files {
|
||||
+ let footer = eappx
|
||||
+ .find_footer_for_file(file.id())
|
||||
+ .ok_or_else(|| Failure::at("extract", infile, "the blockmap names a file the package does not hold"))?;
|
||||
+ if shared.contains(&footer.offset_to_file) {
|
||||
+ continue;
|
||||
+ }
|
||||
+ if footer.uncompressed_length != file.size {
|
||||
+ return Err(Failure::at("extract", infile, "a package entry disagrees with its blockmap about its size"));
|
||||
+ }
|
||||
+ let mut info = eappx::FileInfo::from(footer);
|
||||
+ info.filehash = file.filehash_bytes();
|
||||
+ info.block_hashes = Some(file.block_hashes());
|
||||
+ written.push((info, file.name.clone()));
|
||||
+ }
|
||||
+
|
||||
+ let mut inner = Vec::new();
|
||||
+ for member in members {
|
||||
+ match source.inner(&member) {
|
||||
+ Some(package) => inner.push(package),
|
||||
+ None => written.push((member.info, member.name)),
|
||||
+ }
|
||||
+ }
|
||||
+ inner.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
+
|
||||
+ if let Some(meter) = meter {
|
||||
+ meter.roll(written.iter().map(|(info, _)| info.uncompressed_length).sum());
|
||||
+ }
|
||||
+ let layout = Layout::of(eappx, source.len);
|
||||
+ for (info, name) in written {
|
||||
+ save(eappx, &layout, reader, info, outdir, &name).map_err(|e| Failure::at("extract", infile, &e.to_string()))?;
|
||||
+ }
|
||||
+ Ok(inner)
|
||||
+}
|
||||
+
|
||||
+/// What a package's blockmap says it will write, or nothing when its header is unreadable.
|
||||
+fn package_size(path: &Path) -> u64 {
|
||||
+ let Ok(file) = std::fs::File::open(path) else { return 0 };
|
||||
+ EAppxFile::from_stream(&mut std::io::BufReader::new(file))
|
||||
+fn package_size(source: &Source) -> u64 {
|
||||
+ let Ok(window) = Window::open(source, None) else { return 0 };
|
||||
+ EAppxFile::from_stream(&mut std::io::BufReader::new(window))
|
||||
+ .map(|package| package.blockmap.files.iter().map(|entry| entry.size).sum())
|
||||
+ .unwrap_or(0)
|
||||
+}
|
||||
+
|
||||
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
+pub struct Footprint {
|
||||
+ pub unpacked: u64,
|
||||
+ pub growth: u64,
|
||||
+ pub files: u64,
|
||||
+ pub block: u64,
|
||||
+}
|
||||
+
|
||||
+impl Footprint {
|
||||
+ fn add(&mut self, other: Footprint) {
|
||||
+ self.unpacked = self.unpacked.saturating_add(other.unpacked);
|
||||
+ self.growth = self.growth.saturating_add(other.growth);
|
||||
+ self.files = self.files.saturating_add(other.files);
|
||||
+ }
|
||||
+
|
||||
+ pub fn extra(&self, releases: bool) -> u64 {
|
||||
+ if !releases {
|
||||
+ return self.unpacked;
|
||||
+ }
|
||||
+ self.growth
|
||||
+ .saturating_add(self.files.saturating_mul(2).saturating_mul(self.block))
|
||||
+ .saturating_add(in_flight())
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+pub fn in_flight() -> u64 {
|
||||
+ (workers() as u64).saturating_mul(SPEND_STEP + READ_BUFFER as u64)
|
||||
+}
|
||||
+
|
||||
+pub fn footprint(path: &Path) -> Option<Footprint> {
|
||||
+ if !is_eappx(path) {
|
||||
+ return None;
|
||||
+ }
|
||||
+ let file = std::fs::File::open(path).ok()?;
|
||||
+ let len = file.metadata().ok()?.len();
|
||||
+ let source = Source { file: &file, origin: path, name: path.to_path_buf(), start: 0, len };
|
||||
+ let mut total = measure(&source, 0)?;
|
||||
+ total.block = block_size(&file);
|
||||
+ Some(total)
|
||||
+}
|
||||
+
|
||||
+fn measure(source: &Source, depth: usize) -> Option<Footprint> {
|
||||
+ let mut reader = std::io::BufReader::new(Window::open(source, None).ok()?);
|
||||
+ let eappx = EAppxFile::from_stream(&mut reader).ok()?;
|
||||
+ let layout = Layout::of(&eappx, source.len);
|
||||
+ let header = &eappx.header;
|
||||
+ let packaging = eappx
|
||||
+ .find_footer_for_file(header.block_map_file_id)
|
||||
+ .map_or(0, |footer| footer.uncompressed_length)
|
||||
+ .saturating_add(u64::from(header.signature_uncompressed_length))
|
||||
+ .saturating_add(u64::from(header.code_integrity_uncompressed_length));
|
||||
+ let mut total = Footprint { unpacked: packaging, growth: packaging, files: 3, block: 0 };
|
||||
+ let mut written = Vec::new();
|
||||
+ if header.is_bundle() {
|
||||
+ let members = bundle_members(&eappx, &mut reader).ok()?;
|
||||
+ let shared: Vec<u64> = members.iter().map(|member| member.info.offset_to_file).collect();
|
||||
+ for file in &eappx.blockmap.files {
|
||||
+ let footer = eappx.find_footer_for_file(file.id())?;
|
||||
+ if !shared.contains(&footer.offset_to_file) {
|
||||
+ written.push(eappx::FileInfo::from(footer));
|
||||
+ }
|
||||
+ }
|
||||
+ for member in members {
|
||||
+ match source.inner(&member) {
|
||||
+ Some(_) if depth >= MAX_BUNDLE_DEPTH => return None,
|
||||
+ Some(package) => total.add(measure(&package, depth + 1)?),
|
||||
+ None if member.info.compression_type == 1 => return None,
|
||||
+ None => written.push(member.info),
|
||||
+ }
|
||||
+ }
|
||||
+ } else {
|
||||
+ for file in &eappx.blockmap.files {
|
||||
+ written.push(eappx::FileInfo::from(eappx.find_footer_for_file(file.id())?));
|
||||
+ }
|
||||
+ }
|
||||
+ for info in &written {
|
||||
+ total.add(Footprint {
|
||||
+ unpacked: info.uncompressed_length,
|
||||
+ growth: info.uncompressed_length.saturating_sub(layout.stored(info)),
|
||||
+ files: 1,
|
||||
+ block: 0,
|
||||
+ });
|
||||
+ }
|
||||
+ Some(total)
|
||||
+}
|
||||
+
|
||||
/// Bytes currently on disk under `dir`.
|
||||
///
|
||||
/// A bundle member is written as one file, so a per-file counter says nothing
|
||||
@@ -414,3 +436,29 @@ fn unpack(
|
||||
@@ -319,48 +777,33 @@ fn workers() -> usize {
|
||||
/// goes. The blockmap already totals every file's uncompressed length, so the
|
||||
/// end point is known before the first byte is written.
|
||||
fn unpack(
|
||||
- infile: &Path,
|
||||
+ source: &Source,
|
||||
eappx: &EAppxFile,
|
||||
- reader: &mut std::io::BufReader<std::fs::File>,
|
||||
outdir: &Path,
|
||||
meter: Option<&Meter>,
|
||||
- release: bool,
|
||||
+ release: Option<&Release>,
|
||||
) -> Result<(), Failure> {
|
||||
+ let infile = source.name.as_path();
|
||||
let total: u64 = eappx.blockmap.files.iter().map(|package| package.size).sum();
|
||||
if let Some(meter) = meter {
|
||||
meter.roll(total);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
- eappx
|
||||
- .extract_footprint_files(reader, outdir)
|
||||
- .map_err(|e| Failure::at("extract", infile, &e.to_string()))?;
|
||||
-
|
||||
- if eappx.header.is_bundle() {
|
||||
- eappx
|
||||
- .extract_blockmap_files(reader, outdir)
|
||||
- .map_err(|e| Failure::at("extract", infile, &e.to_string()))?;
|
||||
- eappx
|
||||
- .extract_bundle_files(reader, outdir)
|
||||
- .map_err(|e| Failure::at("extract", infile, &e.to_string()))?;
|
||||
- if release {
|
||||
- std::fs::remove_file(infile).ok();
|
||||
- }
|
||||
- return Ok(());
|
||||
- }
|
||||
-
|
||||
+ let layout = Layout::of(eappx, source.len);
|
||||
let count = workers().min(eappx.blockmap.files.len().max(1));
|
||||
let failure = std::sync::Mutex::new(None::<String>);
|
||||
std::thread::scope(|scope| {
|
||||
for shard in 0..count {
|
||||
let failure = &failure;
|
||||
+ let layout = &layout;
|
||||
scope.spawn(move || {
|
||||
- let Ok(handle) = std::fs::File::open(infile) else {
|
||||
+ let Ok(window) = Window::open(source, release) else {
|
||||
if let Ok(mut slot) = failure.lock() {
|
||||
*slot = Some("a worker could not reopen the package".to_string());
|
||||
}
|
||||
return;
|
||||
};
|
||||
- let mut stream = std::io::BufReader::with_capacity(READ_BUFFER, handle);
|
||||
+ let mut stream = std::io::BufReader::with_capacity(READ_BUFFER, window);
|
||||
for (index, package) in eappx.blockmap.files.iter().enumerate() {
|
||||
if index % count != shard {
|
||||
continue;
|
||||
@@ -387,7 +830,7 @@ fn unpack(
|
||||
}
|
||||
return;
|
||||
}
|
||||
- if let Err(error) = eappx.save_file_to_fs(&mut stream, info, outdir, &package.name) {
|
||||
+ if let Err(error) = save(eappx, layout, &mut stream, info, outdir, &package.name) {
|
||||
if let Ok(mut slot) = failure.lock() {
|
||||
*slot = Some(error.to_string());
|
||||
}
|
||||
@@ -406,11 +849,190 @@ fn unpack(
|
||||
if let Some(reason) = failure.into_inner().unwrap_or(None) {
|
||||
return Err(Failure::at("extract", infile, &reason));
|
||||
}
|
||||
+ Ok(())
|
||||
+}
|
||||
+
|
||||
+#[cfg(test)]
|
||||
+mod meter_tests {
|
||||
+ use super::Meter;
|
||||
+
|
||||
|
||||
- if release {
|
||||
- // The files are on disk; the container is not read again unless the
|
||||
- // install is retried from scratch.
|
||||
- std::fs::remove_file(infile).ok();
|
||||
+ #[test]
|
||||
+ fn announced_packages_keep_the_total_from_growing() {
|
||||
+ let meter = Meter::default();
|
||||
@@ -149,12 +750,172 @@ index 5ea43da..0bad98e 100644
|
||||
+ assert_eq!(meter.snapshot(), (10, 10));
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+#[cfg(test)]
|
||||
+mod release_tests {
|
||||
+ use super::{Footprint, Layout, Release, Source, Window, in_flight, releases_space};
|
||||
+ use std::io::{Read, Seek, SeekFrom};
|
||||
+ use std::path::{Path, PathBuf};
|
||||
+
|
||||
+ fn scratch(name: &str) -> PathBuf {
|
||||
+ let path = std::env::temp_dir().join(format!("xodus-release-{name}-{}", std::process::id()));
|
||||
+ let _ = std::fs::remove_dir_all(&path);
|
||||
+ std::fs::create_dir_all(&path).unwrap();
|
||||
+ path
|
||||
+ }
|
||||
+
|
||||
+ fn pattern(len: usize) -> Vec<u8> {
|
||||
+ (0..len).map(|index| (index % 251) as u8 + 1).collect()
|
||||
+ }
|
||||
+
|
||||
+ fn info(offset: u64, uncompressed: u64, compressed: u64, compression: u16) -> eappx::FileInfo {
|
||||
+ eappx::FileInfo {
|
||||
+ key_id_index: 0,
|
||||
+ compression_type: compression,
|
||||
+ offset_to_file: offset,
|
||||
+ uncompressed_length: uncompressed,
|
||||
+ compressed_length: compressed,
|
||||
+ filehash: None,
|
||||
+ block_hashes: None,
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn a_window_reads_only_the_package_it_covers() {
|
||||
+ let root = scratch("window");
|
||||
+ let path = root.join("bundle.eappxbundle");
|
||||
+ let bytes = pattern(4096);
|
||||
+ std::fs::write(&path, &bytes).unwrap();
|
||||
+ let file = std::fs::File::open(&path).unwrap();
|
||||
+ let source = Source { file: &file, origin: &path, name: PathBuf::from("member.eappx"), start: 100, len: 50 };
|
||||
+ let mut window = Window::open(&source, None).unwrap();
|
||||
+
|
||||
+ let mut all = Vec::new();
|
||||
+ window.read_to_end(&mut all).unwrap();
|
||||
+ assert_eq!(all, bytes[100..150]);
|
||||
+
|
||||
+ assert_eq!(window.seek(SeekFrom::End(-10)).unwrap(), 40);
|
||||
+ let mut tail = Vec::new();
|
||||
+ window.read_to_end(&mut tail).unwrap();
|
||||
+ assert_eq!(tail, bytes[140..150]);
|
||||
+
|
||||
+ window.seek(SeekFrom::Start(5)).unwrap();
|
||||
+ let mut two = [0u8; 2];
|
||||
+ window.read_exact(&mut two).unwrap();
|
||||
+ assert_eq!(two, bytes[105..107]);
|
||||
+ assert!(window.seek(SeekFrom::Current(-10)).is_err());
|
||||
+ std::fs::remove_dir_all(&root).ok();
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn a_file_never_claims_bytes_past_the_next_entry() {
|
||||
+ let layout = Layout { bounds: vec![0, 100, 300, 1000], len: 1200 };
|
||||
+ assert_eq!(layout.stored(&info(100, 150, 0, 0)), 150);
|
||||
+ assert_eq!(layout.stored(&info(100, 900, 0, 0)), 200);
|
||||
+ assert_eq!(layout.stored(&info(100, 900, 120, 1)), 120);
|
||||
+ assert_eq!(layout.stored(&info(1000, 900, 0, 0)), 200);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn released_bytes_stay_inside_the_written_file() {
|
||||
+ let root = scratch("punch");
|
||||
+ if !releases_space(&root) {
|
||||
+ std::fs::remove_dir_all(&root).ok();
|
||||
+ return;
|
||||
+ }
|
||||
+ let path = root.join("game.eappx");
|
||||
+ std::fs::write(&path, pattern(1 << 20)).unwrap();
|
||||
+ let file = std::fs::File::open(&path).unwrap();
|
||||
+ let release = Release::open(&path, &file);
|
||||
+ let block = release.block;
|
||||
+ let source = Source { file: &file, origin: &path, name: path.clone(), start: 0, len: 1 << 20 };
|
||||
+ let mut window = Window::open(&source, Some(&release)).unwrap();
|
||||
+ window.spend(100, 3 * block);
|
||||
+ window.seek(SeekFrom::Start(100)).unwrap();
|
||||
+ let mut consumed = vec![0u8; usize::try_from(3 * block).unwrap()];
|
||||
+ window.read_exact(&mut consumed).unwrap();
|
||||
+ window.settle();
|
||||
+
|
||||
+ assert!(!path.exists(), "a container that lost bytes no longer looks like a finished download");
|
||||
+ let spent = std::fs::read(&release.spent).unwrap();
|
||||
+ let original = pattern(1 << 20);
|
||||
+ let block = usize::try_from(block).unwrap();
|
||||
+ assert_eq!(spent.len(), original.len());
|
||||
+ assert_eq!(spent[..block], original[..block]);
|
||||
+ assert!(spent[block..3 * block].iter().all(|&byte| byte == 0));
|
||||
+ assert_eq!(spent[3 * block..], original[3 * block..]);
|
||||
+
|
||||
+ release.abandon();
|
||||
+ assert!(!release.spent.exists());
|
||||
+ std::fs::remove_dir_all(&root).ok();
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn a_failure_before_any_release_keeps_the_download() {
|
||||
+ let root = scratch("kept");
|
||||
+ let path = root.join("game.eappx");
|
||||
+ std::fs::write(&path, pattern(1 << 16)).unwrap();
|
||||
+ let file = std::fs::File::open(&path).unwrap();
|
||||
+ let release = Release::open(&path, &file);
|
||||
+ release.abandon();
|
||||
+ assert_eq!(std::fs::read(&path).unwrap(), pattern(1 << 16));
|
||||
+ release.finish();
|
||||
+ assert!(!path.exists());
|
||||
+ std::fs::remove_dir_all(&root).ok();
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn a_container_that_cannot_give_bytes_back_is_kept_for_a_retry() {
|
||||
+ let root = scratch("unpunchable");
|
||||
+ let path = root.join("game.eappx");
|
||||
+ std::fs::write(&path, pattern(1 << 20)).unwrap();
|
||||
+ let file = std::fs::File::open(&path).unwrap();
|
||||
+ let mut release = Release::open(&path, &file);
|
||||
+ release.file = Some(std::fs::File::open(&path).unwrap());
|
||||
+ let block = release.block;
|
||||
+ let source = Source { file: &file, origin: &path, name: path.clone(), start: 0, len: 1 << 20 };
|
||||
+ let mut window = Window::open(&source, Some(&release)).unwrap();
|
||||
+ window.spend(0, 3 * block);
|
||||
+ let mut consumed = vec![0u8; usize::try_from(3 * block).unwrap()];
|
||||
+ window.read_exact(&mut consumed).unwrap();
|
||||
+ window.settle();
|
||||
+
|
||||
+ assert!(!release.spent.exists());
|
||||
+ release.abandon();
|
||||
+ assert_eq!(std::fs::read(&path).unwrap(), pattern(1 << 20));
|
||||
+ std::fs::remove_dir_all(&root).ok();
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn reading_without_a_release_leaves_the_container_alone() {
|
||||
+ let root = scratch("plain");
|
||||
+ let path = root.join("game.eappx");
|
||||
+ std::fs::write(&path, pattern(1 << 16)).unwrap();
|
||||
+ let file = std::fs::File::open(&path).unwrap();
|
||||
+ let source = Source { file: &file, origin: Path::new(&path), name: path.clone(), start: 0, len: 1 << 16 };
|
||||
+ let mut window = Window::open(&source, None).unwrap();
|
||||
+ window.spend(0, 1 << 16);
|
||||
+ let mut all = Vec::new();
|
||||
+ window.read_to_end(&mut all).unwrap();
|
||||
+ window.settle();
|
||||
+ assert_eq!(std::fs::read(&path).unwrap(), pattern(1 << 16));
|
||||
+ std::fs::remove_dir_all(&root).ok();
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn the_extra_space_depends_on_whether_bytes_are_given_back() {
|
||||
+ let footprint = Footprint { unpacked: 80_000_000_000, growth: 1_000, files: 10, block: 4096 };
|
||||
+ assert_eq!(footprint.extra(false), 80_000_000_000);
|
||||
+ assert_eq!(footprint.extra(true), 1_000 + 10 * 2 * 4096 + in_flight());
|
||||
}
|
||||
- Ok(())
|
||||
}
|
||||
diff --git a/crates/xodus-cli/src/commands/legacy_install.rs b/crates/xodus-cli/src/commands/legacy_install.rs
|
||||
new file mode 100755
|
||||
index 0000000..d43c5fc
|
||||
index 0000000..a98d0fd
|
||||
--- /dev/null
|
||||
+++ b/crates/xodus-cli/src/commands/legacy_install.rs
|
||||
@@ -0,0 +1,1527 @@
|
||||
@@ -0,0 +1,1603 @@
|
||||
+//! Installs a legacy Store title: resolve, license, download, extract.
|
||||
+//!
|
||||
+//! `streaming` only understands MSIXVC, where the container *is* the game and
|
||||
@@ -215,6 +976,22 @@ index 0000000..d43c5fc
|
||||
+ available.parse::<u64>().ok().map(|kib| kib.saturating_mul(1024))
|
||||
+}
|
||||
+
|
||||
+struct Step {
|
||||
+ container: u64,
|
||||
+ during: u64,
|
||||
+ after: u64,
|
||||
+}
|
||||
+
|
||||
+fn space_to_unpack(steps: &[Step]) -> u64 {
|
||||
+ let mut settled: i128 = 0;
|
||||
+ let mut peak: i128 = 0;
|
||||
+ for step in steps {
|
||||
+ peak = peak.max(settled + i128::from(step.during));
|
||||
+ settled += i128::from(step.after) - i128::from(step.container);
|
||||
+ }
|
||||
+ u64::try_from(peak).unwrap_or(u64::MAX)
|
||||
+}
|
||||
+
|
||||
+/// Reports why the install stopped without disclosing anything sensitive.
|
||||
+///
|
||||
+/// The app only forwards stderr lines that are on a known allowlist, so a bare
|
||||
@@ -621,8 +1398,13 @@ index 0000000..d43c5fc
|
||||
+ return fail("staging-failed", "Could not clear an unfinished download from the staging folder");
|
||||
+ }
|
||||
+ }
|
||||
+ let releases = crate::commands::extract_eappx::releases_space(&destination);
|
||||
+ if let Some(free) = free_bytes(&destination) {
|
||||
+ let needed = total.saturating_add(largest).saturating_add(largest / 10);
|
||||
+ let needed = if releases {
|
||||
+ total.saturating_add(crate::commands::extract_eappx::in_flight())
|
||||
+ } else {
|
||||
+ total.saturating_add(largest).saturating_add(largest / 10)
|
||||
+ };
|
||||
+ if free.saturating_add(held) < needed {
|
||||
+ return fail(
|
||||
+ "insufficient-space",
|
||||
@@ -691,6 +1473,30 @@ index 0000000..d43c5fc
|
||||
+ downloaded.push(target);
|
||||
+ }
|
||||
+
|
||||
+ if let Some(free) = free_bytes(&destination) {
|
||||
+ let steps: Vec<Step> = downloaded
|
||||
+ .iter()
|
||||
+ .map(|container| {
|
||||
+ let size = std::fs::metadata(container).map_or(0, |meta| meta.len());
|
||||
+ match crate::commands::extract_eappx::footprint(container) {
|
||||
+ Some(footprint) => Step { container: size, during: footprint.extra(releases), after: footprint.unpacked },
|
||||
+ None => Step { container: size, during: size.saturating_add(size / 10), after: size },
|
||||
+ }
|
||||
+ })
|
||||
+ .collect();
|
||||
+ let needed = space_to_unpack(&steps);
|
||||
+ if free < needed {
|
||||
+ return fail(
|
||||
+ "insufficient-space",
|
||||
+ &format!(
|
||||
+ "Unpacking needs about {} GB free, and {} GB is available; the download is kept for a retry",
|
||||
+ needed.div_ceil(1_000_000_000),
|
||||
+ free / 1_000_000_000
|
||||
+ ),
|
||||
+ );
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ progress.phase("installing");
|
||||
+ let key_file_text = key_file.display().to_string();
|
||||
+ let meter = std::sync::Arc::new(crate::commands::extract_eappx::Meter::default());
|
||||
@@ -715,7 +1521,7 @@ index 0000000..d43c5fc
|
||||
+ Some(&meter),
|
||||
+ // A full title is tens of gigabytes. Holding the container
|
||||
+ // while its members are decrypted can fill the device.
|
||||
+ true,
|
||||
+ releases,
|
||||
+ )
|
||||
+ }
|
||||
+ });
|
||||
@@ -739,7 +1545,10 @@ index 0000000..d43c5fc
|
||||
+ progress.bytes(high, total);
|
||||
+ };
|
||||
+ if extracted != ExitCode::SUCCESS {
|
||||
+ return fail("extract-failed", "Could not unpack the package; retrying may require downloading the bundle again because containers are removed to save disk space");
|
||||
+ if container.is_file() {
|
||||
+ return fail("extract-failed", "Could not unpack the package; the download is kept for a retry");
|
||||
+ }
|
||||
+ return fail("extract-failed", "Could not unpack the package; resume to download it again");
|
||||
+ }
|
||||
+ // Drop each container as soon as it is unpacked: a full title is tens of
|
||||
+ // gigabytes, and holding the archive and its contents at once can fill
|
||||
@@ -1358,6 +2167,34 @@ index 0000000..d43c5fc
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn a_container_unpacked_in_place_needs_only_its_growth() {
|
||||
+ let size = 85_000_000_000;
|
||||
+ let steps = [Step { container: size, during: 300_000_000, after: size }];
|
||||
+ assert_eq!(space_to_unpack(&steps), 300_000_000);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn a_container_held_while_unpacking_needs_its_full_contents() {
|
||||
+ let size = 85_000_000_000;
|
||||
+ let steps = [Step { container: size, during: size, after: size }];
|
||||
+ assert_eq!(space_to_unpack(&steps), size);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn later_containers_count_what_earlier_ones_left_behind() {
|
||||
+ let steps = [
|
||||
+ Step { container: 10, during: 12, after: 15 },
|
||||
+ Step { container: 5, during: 9, after: 6 },
|
||||
+ ];
|
||||
+ assert_eq!(space_to_unpack(&steps), 14);
|
||||
+ let shrinking = [
|
||||
+ Step { container: 10, during: 12, after: 4 },
|
||||
+ Step { container: 5, during: 9, after: 6 },
|
||||
+ ];
|
||||
+ assert_eq!(space_to_unpack(&shrinking), 12);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn free_bytes_reads_the_available_column() {
|
||||
+ let root = scratch("free");
|
||||
+ let free = free_bytes(&root).expect("df should answer for an existing folder");
|
||||
|
||||
Reference in new issue
Block a user