Compare commits

...
Author SHA1 Message Date
Kurt Himebauch 9e2e0215fa Give each fixture run in a test its own spawner socket 2026-12-04 17:43:20 -05:00
Kurt Himebauch 3211c91e30 Keep Windows games out of their own Android process
Wine's loader was handed to a worker for every Windows program, so a game ran as an
app process of its own and Android sampled its whole RSS alone. ZTE's ROM
(DefendManagerService) SIGKILLs a background non-system app process whose last two
RSS samples are past 3.2 GB on a 16 GB device, foreground service or not: Like a
Dragon: Pirate Yakuza in Hawaii (3.6 GB) died six minutes after the screen went off
during sleep, and the session found it gone on wake.

Hand Wine's loader off only for Wine's own programs, whose command line starts with
C:\windows\. A game, its launcher and its tools stay children of the Wine process
that started them.
2026-12-04 17:31:11 -05:00
Kurt Himebauch b072cedd16 Fix black bottom-screen Mirror with HDR enabled (#3710)
* Keep Mirror frames readable with HDR enabled

* Exercise mirror capture messages in the native host queue test

* Preserve the HDR display fallback while Mirror is open
2026-12-04 14:01:37 -05:00
Kurt Himebauch 77fffa7592 Show recent photos in place of the keyboard when attaching to the agent (#3702)
* Show recent photos in place of the keyboard in the agent composer

The attach button opens a tray, at the keyboard's height, of the device's
recent pictures; a tap attaches or detaches one. The tray also opens the
system file picker and asks for photo access when the app has none.

* Agent instructions: manifest needs an APK; the agent resumes after a Lab build restart

* Skip the tray's back handler where the host has no back dispatcher

* Offer the photo tray in windows that cannot open pickers, such as the floating pet

* Fix the tray's permission request for windows without a registry

* Move the game screenshot button into the photo tray

* Name only the model in the agent's compact chip

* Keep the session drawer open while the tray's picker or photo permission prompt is up

* Address review: tray height on short screens, denied photo access, kept photo marks, tile labels, Lab build refusals

* Keep tray photos being copied across the tray closing

* Let a tray photo copy clear only its own in-progress marker

* Review: one attachment file per copy, photo tile labels, superseded copies attach nothing

* Drop tray photo copies still running when the message is sent
2026-12-04 13:42:17 -05:00
Kurt Himebauch de3ed8b986 Keep the followed channel's offer off the Tests list while browsing it (#3707)
* Show the followed channel's update offer above the test list only when following a test

* Keep install progress and errors on the Tests list while following Stable or Preview
2026-12-04 13:25:24 -05:00
JRAlmonte 86b8ae3c99 fix(nativeguest): do not apply a realtime limit of zero (#3704)
Flatpak emulators that use SDL (Flycast, Rosalie's Mupen GUI, xemu) were
killed with status 137 a second or two after a game started. Without a
RealtimeKit, xdg-desktop-portal reports RTTimeUSecMax 0, and SDL sets that
as RLIMIT_RTTIME before asking for a realtime thread. The kernel checks the
limit on a thread that is realtime or has a CPU-time timer armed, and a
limit of 0 is reached at once: SIGKILL at the hard limit.

Fixes #3672
2026-12-04 13:02:07 -05:00
Kurt Himebauch fe6f8638c6 Lay wide session drawer pages out in two columns (#3694)
Keep drawer content composed when changing width, and keep component notes within their groups so columns stay balanced.
2026-12-04 12:15:50 -05:00
Kurt Himebauch 26b11c6838 Keep the session drawer open while the agent's file picker is up (#3696)
Preserve the Agent page and its result handler while the system picker covers the session, including on a docked second screen.
2026-12-04 11:00:09 -05:00
Kurt Himebauch a9f2017aa3 Draw the outline of enabled secondary buttons under the agent's latest reply (#3697)
* Draw the outline of enabled secondary buttons under the agent's latest reply

* Count only the index fetch's own connections in DesktopLanguageIndexSourceTest
2026-12-04 10:25:37 -05:00
Kurt Himebauch bc8a970520 Stop re-arming frame generation after repeated GPU loss (#3659)
Disable frame generation after repeated startup device losses, while preserving recovery for engines that had been working. Keep the current ZeroFG-compatible submission path.
2026-12-04 09:41:39 -05:00
Kurt Himebauch eefd8088dc Merge original Snapdragon X detection contribution (#524)
Retain the implementation and tests already merged in #3671. This merge preserves the original contribution history without changing the current source tree.
2026-12-04 09:38:53 -05:00
Kurt Himebauch 442f1f83bf Resolve Snapdragon X conflicts against main
Keep the implementation and tests from #3671 while retaining the original contributor branch history.
2026-12-04 09:38:36 -05:00
Kurt Himebauch 1d1c29517a Revert "Feat:Add Snapdragon X Elite and Adreno X1 GPU detection" (#3695)
Revert "Feat:Add Snapdragon X Elite and Adreno X1 GPU detection (#3671)"

This reverts commit be98982cfc.
2026-12-04 09:30:22 -05:00
LunaDL be98982cfc Feat:Add Snapdragon X Elite and Adreno X1 GPU detection (#3671)
* feat(gpu): add Snapdragon X and Adreno X1 detection

* fix: resolve Snapdragon X PR conflicts and review findings

* fix: resolve Snapdragon X PR conflicts and review findings

* fix: resolve Snapdragon X PR conflicts and review findings

* fix: resolve Snapdragon X PR conflicts and review findings

* fix: resolve Snapdragon X PR conflicts and review findings

* fix: resolve Snapdragon X PR conflicts and review findings

* test: preserve current SoC mappings and cover QTI X1 fallback

* test: preserve current SoC mappings and cover QTI X1 fallback

* test: preserve current SoC mappings and cover QTI X1 fallback

* fix: keep session TU_DEBUG policy authoritative

* test: preserve explicit TU_DEBUG environment overrides

* chore: remove unused GPU detection import

* test: verify TU_DEBUG defaults stay session-owned

* chore: restart PR CI

* fix: remove duplicate game environment resolver

* fix: preserve session TU_DEBUG defaults for Flatpak and Snap

* fix: only export explicit game TU_DEBUG overrides

* test: correct SoC platform fallback assertions

* test: cover inherited session TU_DEBUG defaults

* test: remove redundant GameEnvironment comment

* fix: preserve Venus game sysmem setting

* test: cover persisted Venus sysmem setting
2026-12-04 09:29:44 -05:00
Kurt Himebauch ed763ecb9b Let the session drawer expand to the screen's left edge (#3691)
Keep the resize grip usable at full width and reserve its touch area from Android Back gestures.
2026-12-04 09:22:27 -05:00
Kurt Himebauch ecbda604e2 ci: save the Robolectric jar cache from main only (#3604)
A pull request's cache entry is visible only to that pull request, so each
PR stored its own ~830 MB copy that no other PR could restore, while new
PRs started from main's incomplete set and downloaded the rest from Maven
Central, where the 429s come from. The copies also kept the repository at
its 10 GB cache limit and pushed out other caches.
2026-12-04 08:56:53 -05:00
Kurt Himebauch c514c59018 Settings search: open the result's row, scroll to it and flash it (#3657)
* Settings search: open the result's row, scroll to it and flash it

* Opt in to the foundation API the search target uses
2026-12-04 08:56:05 -05:00
Kurt Himebauch b6efc4d44a Updates: Lab builds under the installed build, two panes in landscape (#3667)
* feat(updates): Lab builds under the installed build, two panes in landscape

Lab builds sit under the installed build instead of below the test list,
with kept builds folded behind a toggle while one runs. In landscape the
page splits into two panes that scroll on their own: the installed build,
checks, Lab builds and tester options on the left, the channel picker and
its status on the right. The selected test build expands in place with its
status, notes and install button.

* fix(updates): stack the fallback status above the test list
2026-12-04 08:55:44 -05:00
Kurt Himebauch b61f766b66 fix(session): sleep freezes the programs that run in worker processes (#3665)
With the native session, gamescope, Xwayland, wineserver and the game each run
in a worker process of their own: none descends from the session root, so the
freeze on sleep left them running. On wake the resume still added the frozen
time to the guest clock shift, and every one of them saw its monotonic clock
jump back by the length of the sleep. Unreal games abort on that:
KINGDOM HEARTS III failed with "Detected negative delta time" (DeltaTime
-10.05 s after a 13 s sleep).

The freeze now treats the session's worker programs as helper roots, as the
teardown already does.
2026-12-04 08:54:51 -05:00
Kurt Himebauch 01c8991049 Fix initial controller focus in the frame generation picker (#3689)
Keep engine choices in the session drawer focus tree so the selected engine receives focus on open and the Engine control regains focus on close.
2026-12-04 07:43:45 -05:00
Kurt Himebauch bf8faf06e1 Make frame generation and game zoom controller-friendly (#3669)
Add the session engine picker and the stepped Game zoom slider. Keep Frame Generation in its own tab and use the standard controller focus ring on its buttons.
2026-12-04 07:20:03 -05:00
Ben Pfeiffer 2f16ea63aa fix(gpu): distinguish Adreno X1-45 and remove generic renderD128 check
- Distinguish Adreno X1-45 (Snapdragon X Plus / purwa) from Adreno X1-85
  (Snapdragon X Elite / hamoa) in GpuInfo, falling back to neutral 'Adreno X1'
  when the exact variant is unspecified.
- Remove generic /sys/class/drm/renderD128 check from DeviceSupport.adreno()
  so non-Qualcomm DRM GPUs are not erroneously marked as Adreno.
- Add unit tests verifying X1 variant name resolution.
2026-10-24 00:31:49 +00:00
Kurt Himebauch 151b2c304f Merge current main into PR #524 2026-10-22 13:11:01 -04:00
Kurt Himebauch b3e9ea5620 Merge current main into PR #524 2026-10-22 12:13:45 -04:00
Kurt Himebauch a4a5a88ab2 Merge remote-tracking branch 'origin/main' into fix/pr-524-authorship-conflict 2026-10-22 11:36:38 -04:00
Kurt Himebauch 839a00a8aa Merge remote-tracking branch 'origin/main' into fix/pr-524-authorship-conflict
# Conflicts:
#	app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt
2026-10-22 11:36:01 -04:00
xXJsonDeruloXx a7f7a17a69 Merge main into Adreno X1 detection PR 2026-10-22 10:04:51 -04:00
xXJsonDeruloXx 74a77c1402 fix: keep the GPU hardware fallback non-null when Build.HARDWARE is unset 2026-10-18 17:49:52 -04:00
xXJsonDeruloXx 673c9869f8 chore: merge main to catch up with 0.5.0 2026-10-18 16:49:16 -04:00
BenPfeiffer-TX 215ed5aaed Merge branch 'main' into feat/adreno-x185-detection 2026-10-11 15:11:04 -05:00
BenPfeiffer-TX 7b91aea0fc Merge branch 'main' into feat/adreno-x185-detection 2026-10-11 09:22:07 -05:00
Ben Pfeiffer 2b424bdfe7 feat(gpu): default to nolrz and nolrzfc on Adreno X1-85 to prevent depth dithering
Turnip's Low-Resolution Z (LRZ / early-Z) depth tile cache can desynchronize
on Adreno 741 (X1-85 / X1-45), leading to checkerboard or dithering depth
artifacts in 3D titles and Vulkan presentation.

Default TU_DEBUG to 'nolrz,nolrzfc' on GPU model 741 in both GameEnvironment
defaults (Proton games) and SessionService (Gamescope/Steam session), while
preserving user overrides.
2026-10-10 17:22:07 +00:00
Ben Pfeiffer a4e6279a8d feat(gpu): add Snapdragon X Elite and Adreno X1-85 detection 2026-10-09 02:51:29 +00:00
71 changed files with 1781 additions and 257 deletions

No files matched your search

+3 -1
View File
@@ -178,8 +178,10 @@ jobs:
PY
after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)
[ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true
# A pull request's cache is visible only to that pull request, and each copy is hundreds of megabytes against the
# repository's 10 GB cache limit. Only main saves, so every pull request restores main's set.
- name: Store Robolectric's Android jars
if: always() && steps.robolectric-jars-final.outputs.save == 'true'
if: always() && github.event_name != 'pull_request' && steps.robolectric-jars-final.outputs.save == 'true'
uses: actions/cache/save@v4
with:
path: ${{ steps.robolectric-jars.outputs.path }}
+2
View File
@@ -40,6 +40,8 @@
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.HIGH_SAMPLING_RATE_SENSORS" />
+20 -4
View File
@@ -343,6 +343,7 @@ volatile int g_hide_shell;
volatile int g_zero_copy;
static int g_zero_copy_paused;
static int g_mirror_capture;
extern volatile int g_display_buffer_driver;
extern void droiddeck_on_overlay_planes(int planes);
static int g_overlay_planes_told = -1;
@@ -2961,7 +2962,7 @@ static void hdr_note_route(int route, const struct hdr_scene *hs) {
static int said = -1, said_tm = -1;
static const char *said_why;
const int tm = route != 0 && !droiddeck_color_output();
if (route == said && tm == said_tm && (route != 1 || hs->why == said_why)) return;
if (route == said && tm == said_tm && (route < 1 || route > 2 || hs->why == said_why)) return;
int was = said;
said = route; said_why = hs->why; said_tm = tm;
char name[160] = "the HDR game";
@@ -2978,6 +2979,10 @@ static void hdr_note_route(int route, const struct hdr_scene *hs) {
"BT2020_PQ", name, hs->why ? hs->why : "?", droiddeck_color_sdr_white());
break;
case 2:
if (g_mirror_capture) {
droiddeck_log("color", "Mirror: %s is composed through the screen swapchain", name);
break;
}
if (tm)
droiddeck_log("color", "HDR with frame generation for %s, HDR output switched off: the scene is tone-mapped to "
"SDR and presented through an SDR screen swapchain", name);
@@ -3198,6 +3203,11 @@ static void render_scene(void) {
const int cardboard = vkp_cardboard_active();
struct hdr_scene hs;
int hdr_route = hdr_plan(&dl, w, h, fx_on, framegen, &hs);
/* Mirror's PixelCopy cannot see the separate game layer. Keep unimportable frames visible on top. */
if (g_mirror_capture && hdr_route != 3 && hs.n_hdr > 0) {
hdr_route = 2;
hs.why = "Mirror needs the screen swapchain";
}
const char *hdr_copy = NULL;
if (droiddeck_color_hdr_open()) {
hdr_note_route(hdr_route, &hs);
@@ -3263,16 +3273,16 @@ static void render_scene(void) {
else if (rendered && how == 2) droiddeck_color_frame_shown(hs.color, DROIDDECK_HDR_TONEMAPPED, 0);
else if (rendered) hdr_copy = "the HDR composition pass is unavailable on this driver";
}
if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
if (hdr_route == 0 && !g_mirror_capture && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
!ahb_only) {
settle_unwaited();
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
} else if (hdr_route == 0 || hdr_route == 3) {
const int pass_on = fx_on || framegen;
tell_overlay_planes();
const int fg_layer = framegen && hdr_route == 0 && framegen_fits_layer();
const int fg_layer = framegen && !g_mirror_capture && hdr_route == 0 && framegen_fits_layer();
g_framegen_layer = fg_layer;
int li = (g_zero_copy && (!framegen || fg_layer) && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1;
int li = (g_zero_copy && !g_mirror_capture && (!framegen || fg_layer) && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1;
int over = li >= 0 ? dl.n - 1 - li : 0;
const int fx_blocks = (li >= 0 && fx_on && over > 0);
if (fx_blocks) { li = -1; over = 0; }
@@ -5002,6 +5012,12 @@ const char *droiddeck_client_name(struct wl_client *client) { return client_name
struct wl_display *droiddeck_get_display(void) { return g_display; }
void droiddeck_request_redraw(void) { schedule_render(); }
void droiddeck_set_mirror_capture(int on) {
if (g_mirror_capture == on) return;
g_mirror_capture = on;
schedule_render();
}
struct wl_resource *droiddeck_ime_target(void) {
struct surface *s;
if (g_ime_click && g_ime_click->mapped) return g_ime_click->resource;
@@ -11,7 +11,7 @@
#include "ahb_swapchain.h"
#include "droiddeck_color.h"
enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD };
enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD, HOST_MIRROR_CAPTURE };
struct host_msg {
enum host_kind kind;
@@ -91,6 +91,9 @@ void droiddeck_host_text_delete(int before, int after) {
void droiddeck_host_zero_copy(int on, int live) {
host_post(HOST_ZERO_COPY, NULL, 0, on, live);
}
void droiddeck_host_mirror_capture(int on) {
host_post(HOST_MIRROR_CAPTURE, NULL, 0, on, 0);
}
void droiddeck_host_hdr_output(int on) {
host_post(HOST_HDR_OUTPUT, NULL, 0, on, 0);
}
@@ -271,6 +274,9 @@ static int on_wake(int fd, uint32_t mask, void *data) {
case HOST_ZERO_COPY:
ahb_swapchain_set_mode(m->a, m->b);
break;
case HOST_MIRROR_CAPTURE:
droiddeck_set_mirror_capture(m->a);
break;
case HOST_HDR_OUTPUT:
droiddeck_color_set_output(m->a);
break;
@@ -29,6 +29,8 @@ void droiddeck_host_text_commit_and_submit(const char *utf8, int len);
void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end);
void droiddeck_host_text_delete(int before, int after);
void droiddeck_host_zero_copy(int on, int live);
void droiddeck_host_mirror_capture(int on);
void droiddeck_set_mirror_capture(int on);
void droiddeck_host_hdr_output(int on);
void droiddeck_host_key(int evdev, int state);
void droiddeck_host_select_game_field(int copy);
@@ -79,6 +79,24 @@ static int format_refused(VkFormat f) {
static _Atomic unsigned g_stat_generated;
static uint64_t g_total_generated;
#define FG_PROVEN_FRAMES 120
#define FG_HANG_STRIKES 2
static _Atomic int g_hang_strikes;
static int g_submitted_since_ready;
static uint64_t g_generated_at_ready;
// A driver that hangs on the engine's shaders loses the device on its first generated frame after every
// recovery, so the compositor would recover and hang again for as long as frame generation stays armed.
static int framegen_loss_strike(int submitted, uint64_t completed_since_ready) {
if (!submitted || completed_since_ready >= FG_PROVEN_FRAMES) {
atomic_store(&g_hang_strikes, 0);
return 0;
}
if (atomic_fetch_add(&g_hang_strikes, 1) + 1 < FG_HANG_STRIKES) return 0;
atomic_store(&g_hang_strikes, 0);
return 1;
}
static float g_presented_rate, g_source_rate;
static uint32_t g_present_accum, g_source_accum;
static int64_t g_window_start_ns;
@@ -129,6 +147,7 @@ void vkp_framegen_set_engine(int kind) {
atomic_store(&g_kind, kind);
atomic_store(&g_failed_kind, -1);
atomic_store(&g_cfg_dirty, 1);
atomic_store(&g_hang_strikes, 0);
}
void vkp_framegen_set_armed(int armed, int multiplier, int target_fps) {
@@ -230,6 +249,8 @@ void vkp_framegen_device_ready(VkDevice dev, VkQueue queue, uint32_t qfam, int f
atomic_store(&g_caps_ddfg_ok, fge_caps_ok(VKP_FG_ENGINE_DDFG));
atomic_store(&g_caps_zero_ok, fge_caps_ok(VKP_FG_ENGINE_ZEROFG));
atomic_store(&g_dev_lost, 0);
g_submitted_since_ready = 0;
g_generated_at_ready = g_total_generated;
atomic_store(&g_dev_ready,
vk.CreateImage && vk.CreateImageView && vk.CmdPipelineBarrier);
FGLOG("engines ready on compositor device: LSFG %s, DD-FG %s, ZeroFG %s",
@@ -238,8 +259,21 @@ void vkp_framegen_device_ready(VkDevice dev, VkQueue queue, uint32_t qfam, int f
fge_caps_ok(VKP_FG_ENGINE_ZEROFG) ? "available" : "unavailable");
}
// The compositor reports one loss twice: when it happens and again while releasing the lost device.
static int framegen_count_loss(void) {
if (atomic_exchange(&g_dev_lost, 1)) return 0;
int failed = framegen_loss_strike(g_submitted_since_ready, g_total_generated - g_generated_at_ready);
g_submitted_since_ready = 0;
return failed;
}
void vkp_framegen_device_lost(void) {
atomic_store(&g_dev_lost, 1);
if (framegen_count_loss()) {
int kind = atomic_load(&g_kind);
mark_failed(kind);
FGLOG("%s lost the GPU %d times in a row before its frames completed; frame generation stays off "
"until it is set again", fge_engine_name(kind), FG_HANG_STRIKES);
}
atomic_store(&g_dev_ready, 0);
fge_device_lost();
if (g_dev) {
@@ -523,6 +557,7 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view,
VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
0, 0, NULL, 0, NULL, nb, bars);
if (n_gen) g_submitted_since_ready = 1;
fge_process(cmd, scene, scene_view, (uint32_t)w, (uint32_t)h, fmt, planning_sequence, n_gen);
for (uint32_t g = 0; g < n_gen; g++) {
fge_generate(cmd, g, n_gen, g_ring[g].img, g_ring[g].view, (uint32_t)w, (uint32_t)h);
@@ -461,6 +461,11 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetZeroCopy(JNIEnv *
__android_log_print(ANDROID_LOG_INFO, TAG, "zero-copy layer mode %s%s", on ? "on" : "off", live ? " (live)" : "");
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetMirrorCapture(JNIEnv *env, jclass clazz, jboolean on) {
droiddeck_host_mirror_capture(on ? 1 : 0);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetDisplayBufferDriver(JNIEnv *env, jclass clazz, jboolean on) {
g_display_buffer_driver = on ? 1 : 0;
@@ -6348,7 +6348,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun holdComposedOutput(hold: Boolean) {
val wasHeld = composedHolds > 0
composedHolds = (composedHolds + if (hold) 1 else -1).coerceAtLeast(0)
val held = composedHolds > 0
if (held == wasHeld) return
WaylandCompositor.nativeSetMirrorCapture(held)
// Importable HDR is redirected by the compositor hold. Keep its layer-only fallback available.
if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy(composedOutputFree())
}
@@ -6495,7 +6500,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
displayManager.unregisterDisplayListener(displayListener)
com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener)
contentResolver.unregisterContentObserver(refreshSettingObserver)
if (!screenIsOff()) closeSecondScreen(reset = false)
// Closing the presentation removes the docked Agent page and unregisters its picker.
if (com.droiddeck.launcher.session.SessionVisibilityPolicy.shouldCloseSecondScreenOnStop(
screenOff = screenIsOff(),
dockedDrawerOpen = menuShownOnBottom(),
attachmentPickerOpen = com.droiddeck.launcher.agent.AgentAttachments.picking,
)
) closeSecondScreen(reset = false)
sessionTextInput.stop()
startedScreens = (startedScreens - 1).coerceAtLeast(0)
updateGlassesScreen()
@@ -6532,6 +6543,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onResume() {
super.onResume()
com.droiddeck.launcher.agent.AgentAttachments.picking = false
drawerGameInventoryRevision++
com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event ->
com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) }
@@ -6645,7 +6657,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
heldButtons.clear()
if (!screenOff) {
val menuUp = menuShownOnBottom()
drawerOpen = false
if (!com.droiddeck.launcher.agent.AgentAttachments.picking) drawerOpen = false
if (menuUp) SessionState.bottomMenu = true
pcKeyboardOpen = false
achievementsOpen = false
@@ -19,6 +19,15 @@ object AgentAttachments {
/** Guest paths waiting to go with the next message. */
val pending = mutableStateListOf<String>()
/** True while the file picker is open over a session: it answers the drawer's agent page, so the drawer must stay. */
@Volatile var picking = false
/** Launches a system screen that answers the agent page, keeping the drawer for it; the result callback clears [picking]. */
fun pick(launch: () -> Unit) {
picking = true
if (runCatching(launch).isFailure) picking = false
}
private const val NEW = "new"
private const val GUEST_DIR = "/root/.cache/droiddeck/attachments"
private val IMAGE = setOf("png", "jpg", "jpeg", "webp", "gif", "bmp")
@@ -35,14 +44,17 @@ object AgentAttachments {
val folder = chat ?: NEW
val dir = File(hostDir(app), folder).apply { mkdirs() }
return uris.mapNotNull { uri ->
var target: File? = null
runCatching {
val name = displayName(app, uri).replace(Regex("[^A-Za-z0-9._-]"), "_").ifEmpty { "file" }
var target = File(dir, name)
var candidate = File(dir, name)
var n = 1
while (target.exists()) target = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}")
app.contentResolver.openInputStream(uri)!!.use { input -> target.outputStream().use { input.copyTo(it) } }
"$GUEST_DIR/$folder/${target.name}"
}.getOrNull()
// Created atomically, so copies running side by side never pick the same name.
while (!candidate.createNewFile()) candidate = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}")
target = candidate
app.contentResolver.openInputStream(uri)!!.use { input -> candidate.outputStream().use { input.copyTo(it) } }
"$GUEST_DIR/$folder/${candidate.name}"
}.onFailure { target?.delete() }.getOrNull()
}
}
@@ -945,11 +945,15 @@ class SessionService : Service() {
return
}
if (gen == sessionGen && SessionState.running) {
val workers = ownWorkers
suspendController = SessionSuspendController(
sessionRoot = { sessionPid },
// Programs handed off to worker processes are not descendants of the session root, and
// the clock shift applied at resume would move their monotonic time backwards.
helperRoots = {
components.mapNotNull { it.suspendPid().takeIf { pid -> pid > 1 } } +
listOfNotNull(BottomDesktop.suspendPid.takeIf { it > 1 })
listOfNotNull(BottomDesktop.suspendPid.takeIf { it > 1 }) +
(if (workers > 0) com.droiddeck.launcher.runtime.GuestWorkers.guestPids(workers) else emptyList())
},
suspendAudio = {
if (!pulse.setSinkSuspended(true)) Log.w(TAG, "could not suspend audio sink")
@@ -1,6 +1,12 @@
package com.droiddeck.launcher.session
internal object SessionVisibilityPolicy {
fun shouldCloseSecondScreenOnStop(
screenOff: Boolean,
dockedDrawerOpen: Boolean,
attachmentPickerOpen: Boolean,
): Boolean = !screenOff && !(dockedDrawerOpen && attachmentPickerOpen)
fun isHidden(
activityStarted: Boolean,
defaultDisplayOn: Boolean,
@@ -5,7 +5,9 @@ import android.content.ContextWrapper
import android.os.Build
import android.view.KeyEvent
import android.view.WindowManager
import androidx.activity.compose.BackHandler
import androidx.activity.compose.LocalActivityResultRegistryOwner
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.expandVertically
@@ -50,12 +52,12 @@ import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Send
import androidx.compose.material.icons.outlined.Extension
import androidx.compose.material.icons.outlined.PhotoCamera
import androidx.compose.material.icons.outlined.MicOff
import androidx.compose.material.icons.outlined.Mic
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.ArrowDownward
import androidx.compose.material.icons.outlined.AttachFile
import androidx.compose.material.icons.outlined.Keyboard
import androidx.compose.material.icons.outlined.Terminal
import androidx.compose.material.icons.outlined.Build
import androidx.compose.material.icons.outlined.Close
@@ -79,6 +81,7 @@ import androidx.compose.runtime.MutableState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
@@ -108,6 +111,7 @@ import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.testTag
@@ -301,7 +305,7 @@ private fun AgentPageContent(
readingBack = false
scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) }
}
val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() &&
val hidden = !composer.focused && !composer.tray && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() &&
AgentHost.approvals.isEmpty()
var listHeight by remember { mutableIntStateOf(0) }
Box(
@@ -319,6 +323,7 @@ private fun AgentPageContent(
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
if (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE) panel = AgentPanel.NONE
composer.tray = false
// Forced: the unforced path walks the focus chain and throws ("ActiveParent with no focused child") when a tap lands while focus is moving.
if (composer.focused) focusManager.clearFocus(force = true)
}
@@ -344,6 +349,12 @@ private fun AgentPageContent(
@Stable
private class ComposerState {
var focused by mutableStateOf(false)
/** The photo tray stands in for the keyboard, at the height the keyboard last had. */
var tray by mutableStateOf(false)
var keyboardHeight by mutableStateOf(0.dp)
/** Tray photos copied, or being copied, for this conversation, so reopening the tray keeps their marks and copies nothing twice. */
val photoCopies = mutableStateMapOf<android.net.Uri, String>()
val photosCopying = mutableStateMapOf<android.net.Uri, Any>()
var focusRequests by mutableIntStateOf(0)
private set
private var consumedFocusRequests by mutableIntStateOf(0)
@@ -390,7 +401,7 @@ private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstCon
.clickable { onPanel(AgentPanel.MODEL) }.padding(horizontal = 8.dp).testTag("agent-model"),
) {
val mode = AgentHost.harness.permissions.drop(1).firstOrNull { it.id == AgentHost.permission }?.let { stringResource(it.label) }
val parts = if (compact) listOfNotNull(mode ?: model)
val parts = if (compact) listOf(model)
else listOfNotNull(
AgentHost.harness.name, model, AgentHost.effort, mode,
stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans },
@@ -748,6 +759,8 @@ private fun AgentComposer(
if (text.isEmpty() && AgentAttachments.pending.isEmpty()) return@send
AgentHost.send(context, text, AgentAttachments.pending.toList())
AgentAttachments.pending.clear()
composer.photosCopying.clear()
composer.tray = false
onSent()
}
}
@@ -813,7 +826,34 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
var focused by remember { mutableStateOf(false) }
val field = remember { FocusRequester() }
LaunchedEffect(composer.focusRequests) { if (composer.hasUnconsumedFocusRequest()) runCatching { field.requestFocus() } }
val attach = LocalActivityResultRegistryOwner.current != null
val picks = LocalActivityResultRegistryOwner.current != null
val density = LocalDensity.current
val imeHeight = WindowInsets.ime.getBottom(density)
LaunchedEffect(imeHeight) {
val height = with(density) { imeHeight.toDp() }
if (height > composer.keyboardHeight) composer.keyboardHeight = height
}
LaunchedEffect(hideAttach) { if (hideAttach) composer.tray = false }
LaunchedEffect(AgentHost.chat) {
composer.photoCopies.clear()
composer.photosCopying.clear()
}
// BackHandler throws where the host provides no back dispatcher: the front end and the floating pet.
if (LocalOnBackPressedDispatcherOwner.current != null) BackHandler(composer.tray) { composer.tray = false }
val focusManager = LocalFocusManager.current
val files = if (picks) rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) {
AgentAttachments.picking = false
attachUris(context, it)
} else null
val toggleTray = {
if (composer.tray) {
composer.tray = false
composer.open()
} else {
focusManager.clearFocus(force = true)
composer.tray = true
}
}
BoxWithConstraints(
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape16).background(colors.surface)
.border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16).padding(6.dp),
@@ -841,6 +881,7 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
Modifier.fillMaxWidth().focusRequester(field).onFocusChanged {
focused = it.isFocused
composer.focused = it.isFocused
if (it.isFocused) composer.tray = false
if (it.isFocused) composer.consumeFocusRequest()
}.testTag("agent-input"),
textStyle = TextStyle(fontSize = 16.sp, color = colors.onSurface),
@@ -866,19 +907,22 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
if (stacked) Column {
text(Modifier.fillMaxWidth())
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
AnimatedVisibility(!hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton(composer.tray, toggleTray) }
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp).horizontalScroll(rememberScrollState(), reverseScrolling = true)) { if (controls != null && !focused) controls() }
actions()
}
} else Row(verticalAlignment = Alignment.Bottom) {
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() }
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() }
AnimatedVisibility(!hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton(composer.tray, toggleTray) }
text(Modifier.weight(1f))
if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() }
actions()
}
}
AnimatedVisibility(composer.tray, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
val most = LocalConfiguration.current.screenHeightDp.dp * 0.45f
val height = (if (composer.keyboardHeight > 0.dp) composer.keyboardHeight else 280.dp).coerceAtLeast(160.dp).coerceAtMost(most)
AgentPhotoTray(height, composer.photoCopies, composer.photosCopying, files?.let { { AgentAttachments.pick { it.launch(arrayOf("*/*")) } } })
}
}
/**
@@ -974,51 +1018,15 @@ private fun VoiceButton(voice: AgentVoice, onStart: () -> Unit, onSend: () -> Un
}
}
/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */
/** Opens the photo tray in place of the keyboard; while it is open, brings the keyboard back. */
@Composable
private fun GameFrameButton() {
val context = LocalContext.current
private fun AttachButton(trayOpen: Boolean, onClick: () -> Unit) {
val pal = LocalPalette.current
RoundButton(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), pal.surfaceVariant, pal.onBackground, "agent-game-frame") {
val grab = AgentAttachments.gameFrame ?: return@RoundButton
val chat = AgentHost.chat
grab frame@{ frame ->
if (frame == null) {
android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
return@frame
}
Thread({
val path = AgentAttachments.saveFrame(context, chat, frame)
frame.recycle()
android.os.Handler(android.os.Looper.getMainLooper()).post {
when {
path == null -> android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show()
AgentHost.chat == chat -> AgentAttachments.pending.add(path)
else -> AgentAttachments.discard(context, listOf(path))
}
}
}, "agent-game-frame").start()
}
}
}
@Composable
private fun AttachButton() {
val context = LocalContext.current
val pal = LocalPalette.current
val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
if (uris.isEmpty()) return@rememberLauncherForActivityResult
val chat = AgentHost.chat
Thread({
val paths = AgentAttachments.copy(context, chat, uris)
android.os.Handler(android.os.Looper.getMainLooper()).post {
if (AgentHost.chat == chat) AgentAttachments.pending.addAll(paths) else AgentAttachments.discard(context, paths)
}
}, "agent-attach").start()
}
RoundButton(Icons.Outlined.AttachFile, stringResource(R.string.agent_attach), pal.surfaceVariant, pal.onBackground, "agent-attach") {
runCatching { picker.launch(arrayOf("*/*")) }
}
RoundButton(
if (trayOpen) Icons.Outlined.Keyboard else Icons.Outlined.AttachFile,
stringResource(if (trayOpen) R.string.agent_keyboard else R.string.agent_attach),
if (trayOpen) pal.primary else pal.surfaceVariant, if (trayOpen) pal.onPrimary else pal.onBackground, "agent-attach", onClick = onClick,
)
}
@Composable
@@ -0,0 +1,280 @@
package com.droiddeck.launcher.ui
import android.Manifest
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.widget.Toast
import androidx.activity.compose.LocalActivityResultRegistryOwner
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Check
import androidx.compose.material.icons.outlined.FolderOpen
import androidx.compose.material.icons.outlined.PhotoCamera
import androidx.compose.material.icons.outlined.PhotoLibrary
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateMap
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.selected
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentAttachments
import com.droiddeck.launcher.agent.AgentHost
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/** The device's photos, newest first, as MediaStore lets the app see them. */
internal object AgentPhotos {
enum class Access { NONE, SELECTED, ALL }
/** Android stops showing the request after repeated denials and answers it at once, so a denied request sends later ones to Settings. */
var refused = false
fun permissions(sdk: Int = Build.VERSION.SDK_INT): Array<String> = when {
sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE -> arrayOf(Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED)
sdk >= Build.VERSION_CODES.TIRAMISU -> arrayOf(Manifest.permission.READ_MEDIA_IMAGES)
else -> arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
}
fun access(context: Context): Access {
fun granted(permission: String) = context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
val all = permissions().first()
return when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && Environment.isExternalStorageManager() -> Access.ALL
granted(all) -> Access.ALL
Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && granted(Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED) -> Access.SELECTED
else -> Access.NONE
}
}
class Photo(val uri: Uri, val name: String)
fun recent(context: Context, limit: Int = 300): List<Photo> = runCatching {
val images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
context.contentResolver.query(
images, arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME), null, null, "${MediaStore.Images.Media.DATE_ADDED} DESC",
)?.use { c ->
buildList {
while (size < limit && c.moveToNext()) add(Photo(ContentUris.withAppendedId(images, c.getLong(0)), c.getString(1).orEmpty()))
}
}.orEmpty()
}.getOrDefault(emptyList())
}
/**
* Copies [uris] into the conversation's attachments off the main thread, then hands [onCopied] what was attached: nothing if the
* conversation changed meanwhile or [current] says the copy was superseded.
*/
internal fun attachUris(context: Context, uris: List<Uri>, current: () -> Boolean = { true }, onCopied: (List<Pair<Uri, String>>) -> Unit = {}) {
if (uris.isEmpty()) return
val chat = AgentHost.chat
Thread({
val copied = uris.mapNotNull { uri -> AgentAttachments.copy(context, chat, listOf(uri)).firstOrNull()?.let { uri to it } }
android.os.Handler(android.os.Looper.getMainLooper()).post {
val paths = copied.map { it.second }
if (AgentHost.chat == chat && current()) {
AgentAttachments.pending.addAll(paths)
onCopied(copied)
} else {
AgentAttachments.discard(context, paths)
onCopied(emptyList())
}
}
}, "agent-attach").start()
}
/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */
private fun attachGameFrame(context: Context) {
val grab = AgentAttachments.gameFrame ?: return
val chat = AgentHost.chat
grab frame@{ frame ->
if (frame == null) {
Toast.makeText(context, R.string.agent_attach_game_failed, Toast.LENGTH_SHORT).show()
return@frame
}
Thread({
val path = AgentAttachments.saveFrame(context, chat, frame)
frame.recycle()
android.os.Handler(android.os.Looper.getMainLooper()).post {
when {
path == null -> Toast.makeText(context, R.string.agent_attach_game_failed, Toast.LENGTH_SHORT).show()
AgentHost.chat == chat -> AgentAttachments.pending.add(path)
else -> AgentAttachments.discard(context, listOf(path))
}
}
}, "agent-game-frame").start()
}
}
/** Shown in place of the keyboard: recent photos to tap onto the message, and the system picker for anything else. */
@Composable
internal fun AgentPhotoTray(height: Dp, copies: SnapshotStateMap<Uri, String>, copying: SnapshotStateMap<Uri, Any>, onFiles: (() -> Unit)?) {
val context = LocalContext.current
val pal = LocalPalette.current
var access by remember { mutableStateOf(AgentPhotos.access(context)) }
var photos by remember { mutableStateOf<List<AgentPhotos.Photo>?>(null) }
var reloads by remember { mutableStateOf(0) }
// A window no activity owns (the floating pet's chat) cannot ask for a permission, so it sends the user to the app's settings.
val launcher = if (LocalActivityResultRegistryOwner.current != null) {
rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
AgentAttachments.picking = false
access = AgentPhotos.access(context)
if (access == AgentPhotos.Access.NONE) AgentPhotos.refused = true
reloads++
}
} else null
val request = {
if (launcher != null && !AgentPhotos.refused) {
AgentAttachments.pick { launcher.launch(AgentPhotos.permissions()) }
} else {
val details = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + context.packageName)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
runCatching { context.startActivity(details) }
}
Unit
}
// Access can change in Settings, and new pictures arrive, while the app is in the background.
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
access = AgentPhotos.access(context)
reloads++
}
}
lifecycle.addObserver(observer)
onDispose { lifecycle.removeObserver(observer) }
}
LaunchedEffect(access, reloads) {
photos = if (access == AgentPhotos.Access.NONE) emptyList() else withContext(Dispatchers.IO) { AgentPhotos.recent(context) }
}
LazyVerticalGrid(
GridCells.Adaptive(96.dp),
Modifier.fillMaxWidth().height(height).padding(top = 8.dp).testTag("agent-photo-tray"),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
if (AgentAttachments.gameFrame != null) item {
TrayTile(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), "agent-game-frame") { attachGameFrame(context) }
}
if (onFiles != null) item { TrayTile(Icons.Outlined.FolderOpen, stringResource(R.string.agent_attach_files), "agent-attach-files", onFiles) }
if (access != AgentPhotos.Access.ALL) item {
TrayTile(
Icons.Outlined.PhotoLibrary,
stringResource(if (access == AgentPhotos.Access.NONE) R.string.agent_photos_allow else R.string.agent_photos_more),
"agent-photos-allow",
onClick = request,
)
}
val list = photos
if (list != null && list.isEmpty() && access != AgentPhotos.Access.NONE) item(span = { GridItemSpan(maxLineSpan) }) {
Text(
stringResource(R.string.agent_photos_empty), fontSize = 13.sp, color = pal.onSurfaceVariant, textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth().padding(16.dp),
)
}
items(list.orEmpty(), key = { it.uri.toString() }) { photo ->
val uri = photo.uri
val path = copies[uri]
val selected = path != null && path in AgentAttachments.pending
Box(
Modifier.aspectRatio(1f).clip(Shape12).background(pal.surfaceVariant)
.then(if (selected) Modifier.border(3.dp, pal.primary, Shape12) else Modifier)
.clickable {
when {
selected -> AgentAttachments.pending.remove(path)
path != null && AgentAttachments.host(context, path).exists() -> AgentAttachments.pending.add(path)
uri in copying -> Unit
else -> {
// Leaving the conversation clears the markers, so a copy started before that is no longer current even back in it.
val copy = Any()
copying[uri] = copy
attachUris(context, listOf(uri), current = { copying[uri] === copy }) { copied ->
copied.forEach { (u, p) -> copies[u] = p }
if (copying[uri] === copy) copying.remove(uri)
}
}
}
}.semantics {
contentDescription = photo.name
this.selected = selected
}.testTag("agent-photo"),
) {
AsyncImage(
model = ImageRequest.Builder(context).data(uri).size(320).build(), contentDescription = null,
contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize(),
)
if (selected) Box(
contentAlignment = Alignment.Center,
modifier = Modifier.align(Alignment.TopEnd).padding(6.dp).size(22.dp).clip(CircleShape).background(pal.primary),
) {
Icon(Icons.Outlined.Check, null, tint = pal.onPrimary, modifier = Modifier.size(16.dp))
}
}
}
}
}
@Composable
private fun TrayTile(icon: ImageVector, label: String, tag: String, onClick: () -> Unit) {
val pal = LocalPalette.current
Column(
horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center,
modifier = Modifier.aspectRatio(1f).clip(Shape12).background(pal.surfaceVariant).clickable(onClick = onClick).padding(8.dp).testTag(tag),
) {
Icon(icon, null, tint = pal.onBackground, modifier = Modifier.size(26.dp))
Text(
label, fontSize = 12.sp, color = pal.onBackground, textAlign = TextAlign.Center, maxLines = 3, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 6.dp),
)
}
}
@@ -5,17 +5,30 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.withFrameNanos
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
@@ -34,7 +47,9 @@ internal fun FrameGenMenu(
focusModifier: Modifier = Modifier,
legacyButtons: Boolean = false,
listLayout: Boolean = false,
sessionHost: MenuHost? = null,
) {
val sessionEngineAnchor = remember { FocusRequester() }
val need = stringResource(R.string.lsfg_needs_steam)
val selectedEngine = mode.engine.takeIf { it != FrameGen.ENGINE_OFF }
val offLabel = FrameGen.label(LocalContext.current, FrameGen.Mode.OFF)
@@ -95,60 +110,67 @@ internal fun FrameGenMenu(
}
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 0.dp, bottom = 8.dp)) {
OutlinedButton(
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
modifier = Modifier.fillMaxWidth().controllerConfirm(
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selectedEngine == null) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selectedEngine == null) colors.primary else colors.onSurface,
),
) { Text(offLabel) }
if (listLayout) {
Column(Modifier.fillMaxWidth().padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
engines.forEach { (engine, label) ->
val selected = selectedEngine == engine
val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready
val pick = {
onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4)))
}
OutlinedButton(
onClick = pick,
enabled = enabled,
modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = enabled, onClick = pick),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selected) colors.primary else colors.onSurface,
),
) { Text(label) }
}
}
if (sessionHost != null) {
SessionFrameGenEngine(
sessionHost, mode, listOf(FrameGen.ENGINE_OFF to offLabel) + engines,
lossless.ready, need, focusModifier, sessionEngineAnchor, onPick,
)
} else {
Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
val focusIndex = engines.indexOfFirst { (engine, _) ->
selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready
OutlinedButton(
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
modifier = Modifier.fillMaxWidth().controllerConfirm(
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selectedEngine == null) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selectedEngine == null) colors.primary else colors.onSurface,
),
) { Text(offLabel) }
if (listLayout) {
Column(Modifier.fillMaxWidth().padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
engines.forEach { (engine, label) ->
val selected = selectedEngine == engine
val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready
val pick = {
onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4)))
}
OutlinedButton(
onClick = pick,
enabled = enabled,
modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = enabled, onClick = pick),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selected) colors.primary else colors.onSurface,
),
) { Text(label) }
}
}
engines.forEachIndexed { index, (engine, label) ->
val selected = selectedEngine == engine
val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready
val pick = {
onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4)))
} else {
Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
val focusIndex = engines.indexOfFirst { (engine, _) ->
selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready
}
engines.forEachIndexed { index, (engine, label) ->
val selected = selectedEngine == engine
val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready
val pick = {
onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4)))
}
OutlinedButton(
onClick = pick,
enabled = enabled,
modifier = (if (index == focusIndex) focusModifier else Modifier)
.weight(1f).controllerConfirm(enabled = enabled, onClick = pick),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selected) colors.primary else colors.onSurface,
),
) { Text(label) }
}
OutlinedButton(
onClick = pick,
enabled = enabled,
modifier = (if (index == focusIndex) focusModifier else Modifier)
.weight(1f).controllerConfirm(enabled = enabled, onClick = pick),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selected) colors.primary else colors.onSurface,
),
) { Text(label) }
}
}
}
@@ -165,7 +187,8 @@ internal fun FrameGenMenu(
OutlinedButton(
onClick = pickMultiplier,
enabled = multiplierEnabled,
modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier),
modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier)
.frameGenFocus(sessionHost),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface,
@@ -185,7 +208,8 @@ internal fun FrameGenMenu(
OutlinedButton(
onClick = pickMultiplier,
enabled = multiplierEnabled,
modifier = Modifier.weight(1f).controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier),
modifier = Modifier.weight(1f).controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier)
.frameGenFocus(sessionHost),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface,
@@ -204,7 +228,7 @@ internal fun FrameGenMenu(
OutlinedButton(
onClick = togglePacer,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
.controllerConfirm(onClick = togglePacer),
.controllerConfirm(onClick = togglePacer).frameGenFocus(sessionHost),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (pacerEnabled) colors.primary.copy(alpha = 0.16f) else colors.surface,
@@ -230,7 +254,7 @@ internal fun FrameGenMenu(
modifier = Modifier.weight(1f).controllerConfirm(
enabled = lossless.ready,
onClick = pickTarget,
),
).frameGenFocus(sessionHost),
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface,
@@ -243,21 +267,104 @@ internal fun FrameGenMenu(
}
}
if (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) {
if (sessionHost == null && selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) {
Text(need, color = colors.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 6.dp))
}
if (gameProfileId != null) {
val resetGame = onResetGame
if (gameProfileId != null && (sessionHost == null || hasGameOverride)) {
val input = LocalInputModeManager.current
val resetGame = {
if (sessionHost != null && input.inputMode == InputMode.Keyboard) {
sessionEngineAnchor.requestFocus()
}
onResetGame()
}
OutlinedButton(
onClick = resetGame,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
.controllerConfirm(onClick = resetGame),
.testTag("framegen-use-global").controllerConfirm(onClick = resetGame)
.frameGenFocus(sessionHost),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
) {
Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓")
Text(if (sessionHost != null) stringResource(R.string.frame_gen_use_global)
else stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓")
}
}
}
}
@Composable
private fun Modifier.frameGenFocus(sessionHost: MenuHost?): Modifier =
if (sessionHost != null) focusGlide(RoundedCornerShape(percent = 50)) else this
@Composable
private fun SessionFrameGenEngine(
host: MenuHost,
mode: FrameGen.Mode,
options: List<Pair<String, String>>,
losslessReady: Boolean,
losslessNote: String,
focusModifier: Modifier,
anchor: FocusRequester,
onPick: (FrameGen.Mode) -> Unit,
) {
val label = stringResource(R.string.frame_gen_engine)
val selectedLabel = options.firstOrNull { (engine, _) -> engine == mode.engine }?.second
?: options.first().second
val key = "frame-generation-engine"
val open = host.open == key
val input = LocalInputModeManager.current
var anchorFocused by remember { mutableStateOf(false) }
val selectedOption = remember { FocusRequester() }
var keyboardOpened by remember { mutableStateOf(false) }
val initial = options.firstOrNull { (engine, _) -> engine == mode.engine }?.first
?: FrameGen.ENGINE_OFF
val close = { if (host.open == key) host.open = null }
// Keep the options in the drawer's focus tree. A separate popup window can
// steal focus from the controller before Compose can focus the selected row.
LaunchedEffect(open) {
if (!keyboardOpened || (!open && host.open != null)) return@LaunchedEffect
val target = if (open) selectedOption else anchor
withFrameNanos { }
target.requestFocus()
if (!open) keyboardOpened = false
}
val blockedSelection = !losslessReady && mode.engine == FrameGen.ENGINE_LSFG
SettingsRow(label, losslessNote.takeIf { blockedSelection && !open }, highlighted = open) {
ValueChip(
selectedLabel, open,
modifier = focusModifier.focusRequester(anchor).onFocusChanged { anchorFocused = it.isFocused }
.heightIn(min = 48.dp).testTag("setting-$key")
.semantics { contentDescription = label; stateDescription = selectedLabel },
) {
if (open) close()
else {
keyboardOpened = anchorFocused || input.inputMode == InputMode.Keyboard
host.open = key
}
}
}
if (open) {
Column(Modifier.fillMaxWidth().padding(horizontal = 8.dp).controllerBack(close)) {
options.forEach { (engine, text) ->
val selected = engine == mode.engine
val enabled = selected || engine != FrameGen.ENGINE_LSFG || losslessReady
MenuItem(
label = text, checked = selected, enabled = enabled,
detail = losslessNote.takeIf { engine == FrameGen.ENGINE_LSFG && !losslessReady },
focusRequester = selectedOption.takeIf { engine == initial },
modifier = Modifier.heightIn(min = 48.dp).testTag("framegen-engine:$engine"),
) {
close()
if (!selected) {
onPick(if (engine == FrameGen.ENGINE_OFF) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)
else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4)))
}
}
}
}
}
@@ -308,7 +308,8 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boo
Box(
contentAlignment = Alignment.Center,
modifier = modifier.paneItem("btn:$text").downToFirstTile().heightIn(min = if (pill) 40.dp else if (compact) 44.dp else 48.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(shape).background(fill).glideBorder(hot, shape, pal.signal, if (pill) Color.White.copy(alpha = 0.14f) else pal.line2)
.alpha(if (enabled) 1f else 0.5f)
// The label always gets a layer of its own: sharing one with the fill and outline, they did not draw under the agent's latest reply.
.graphicsLayer { alpha = if (enabled) 1f else 0.5f }
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
.controllerConfirm(enabled = enabled, onClick = onClick)
.padding(horizontal = if (pill) 16.dp else if (compact) 10.dp else 16.dp, vertical = if (pill) 8.dp else if (compact) 7.dp else 11.dp),
@@ -3,6 +3,9 @@ package com.droiddeck.launcher.ui
import android.text.format.DateUtils
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -26,8 +29,11 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@@ -41,7 +47,7 @@ import com.droiddeck.launcher.lab.LabOverlay
* [onRebuild] offers to build a kept one again for this install, when something can.
*/
@Composable
internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay.Info) -> Unit)? = null) {
internal fun LabBuilds(sessionRunning: Boolean = false, header: (@Composable () -> Unit)? = null, onRebuild: ((LabOverlay.Info) -> Unit)? = null) {
val context = LocalContext.current
var version by remember { mutableIntStateOf(0) }
var busy by remember { mutableStateOf(false) }
@@ -54,6 +60,7 @@ internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay.
val paused = active == null && current != null && LabOverlay.skipped == LabOverlay.SKIPPED_APP_IMAGE
val restartFailed = stringResource(R.string.lab_restart_failed)
val canRestart = !busy && !sessionRunning
var showKept by androidx.compose.runtime.saveable.rememberSaveable { mutableStateOf(false) }
/** Android may have given the APK an app image again, which a Lab build cannot load over. */
fun restart() {
@@ -73,8 +80,8 @@ internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay.
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(Modifier.fillMaxWidth().padding(top = 18.dp)) {
Text(
Column(Modifier.fillMaxWidth().padding(top = if (header == null) 18.dp else 0.dp)) {
if (header != null) header() else Text(
stringResource(R.string.lab_builds).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp,
color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 10.dp),
)
@@ -99,7 +106,29 @@ internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay.
PrimaryButton(stringResource(R.string.lab_restart), compact = true, enabled = canRestart) { restart() }
}
}
for (build in saved) rows += {
val foldKept = (current != null || pending != null) && saved.isNotEmpty()
if (foldKept) rows += {
val src = remember { MutableInteractionSource() }
val toggle = { showKept = !showKept }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().paneItem("lab:kept")
.background(if (rememberHot(src)) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = toggle)
.controllerConfirm(onClick = toggle)
.padding(horizontal = 14.dp, vertical = 12.dp),
) {
Text(
pluralStringResource(R.plurals.lab_kept_count, saved.size, saved.size), fontSize = 14.sp,
color = colors.onSurfaceVariant, modifier = Modifier.weight(1f),
)
Text(
stringResource(if (showKept) R.string.common_hide else R.string.common_show), fontSize = 13.5.sp,
fontWeight = FontWeight.SemiBold, color = pal.signal,
)
}
}
if (!foldKept || showKept) for (build in saved) rows += {
var armed by remember(build.dir) { mutableStateOf(false) }
val info = build.info
BuildRow(
@@ -16,11 +16,15 @@ import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import kotlin.math.roundToInt
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
@@ -73,6 +77,7 @@ import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
@@ -82,6 +87,7 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.systemGestureExclusion
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.rememberScrollState
@@ -89,6 +95,7 @@ import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
@@ -545,8 +552,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) {
val short = maxHeight < 440.dp
// The handle keeps a strip on the left free, so a sheet dragged wide can always be dragged back.
val maxSheet = (maxWidth - DRAWER_EDGE_GAP).coerceAtLeast(0.dp)
// At full width the handle's strip sits on the screen's left edge, so the sheet can still be dragged back.
val maxSheet = (maxWidth - DRAWER_HANDLE_STRIP).coerceAtLeast(0.dp)
val minSheet = minOf(DRAWER_MIN_WIDTH, maxSheet)
val defaultSheet = minOf(420.dp, maxWidth * 0.92f)
val sheetWidth = if (docked) maxWidth else (savedWidth?.dp ?: defaultSheet).coerceIn(minSheet, maxSheet)
@@ -662,6 +669,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
val track: (String) -> Modifier = { key -> focus.track(page, key) }
val sections = remember(page) { DrawerSections(drawerContext, track) }
CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true, LocalDrawerSections provides sections) {
DrawerColumns(two = sheetWidth >= DRAWER_TWO_COLUMN_WIDTH && page.inColumns) {
when (page) {
SessionDrawerPage.CONTROLLER -> DrawerControllerPage(host, a, a.controllerConnected || controllerActive, track)
SessionDrawerPage.HUD -> DrawerPerformancePage(host, a, track)
@@ -678,6 +686,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
SessionDrawerPage.ACHIEVEMENTS -> a.achievementsGame?.let { DrawerAchievementsPage(it, a.achievementsTitle, track) }
SessionDrawerPage.AGENT -> Unit
}
}
} }
}
}
@@ -933,6 +942,7 @@ private fun DrawerFrameGenSettings(host: MenuHost, a: DrawerActions, track: (Str
hasGameOverride = a.hasGameOverride,
onResetGame = a.onFrameGenReset,
focusModifier = track("frame-generation"),
sessionHost = host,
)
}
}
@@ -948,7 +958,7 @@ private fun DrawerDisplayPage(host: MenuHost, a: DrawerActions, track: (String)
val orientations = SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) }
SettingsGroup(stringResource(R.string.drawer_page_display), key = "display",
detail = summary(if (a.gameZoomAvailable) "${(a.gameZoom * 100.0f).toInt()}%" else null, orientations.labelOf(a.orientation))) {
if (a.gameZoomAvailable) GameZoomRow(a, track)
if (a.gameZoomAvailable) GameZoomRow(a.gameZoom, track, a.onGameZoom)
ChoiceRow(host, "orientation", stringResource(R.string.setup_session_orientation), null,
orientations, a.orientation, chipModifier = track("orientation"), onPick = a.onOrientation)
if (a.steam) PicturePositionRow(host, a.picturePosition, track("picture-position"), onPick = a.onPicturePosition)
@@ -970,27 +980,66 @@ private fun DrawerDisplayPage(host: MenuHost, a: DrawerActions, track: (String)
SecondScreenGroup(host, a, track)
}
private const val GAME_ZOOM_MIN = 100
private const val GAME_ZOOM_MAX = 300
private const val GAME_ZOOM_STEP = 25
private const val GAME_ZOOM_INTERVALS = (GAME_ZOOM_MAX - GAME_ZOOM_MIN) / GAME_ZOOM_STEP
@Composable
private fun GameZoomRow(a: DrawerActions, track: (String) -> Modifier) {
SettingsRow(stringResource(R.string.game_zoom_title), stringResource(R.string.game_zoom_hint)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
val zoomOutEnabled = a.gameZoom > 1.0f
val zoomInEnabled = a.gameZoom < 3.0f
val zoomOut = { a.onGameZoom((a.gameZoom - 0.25f).coerceAtLeast(1.0f)) }
val zoomIn = { a.onGameZoom((a.gameZoom + 0.25f).coerceAtMost(3.0f)) }
val zoomReset = { a.onGameZoom(1.0f) }
OutlinedButton(onClick = zoomOut, enabled = zoomOutEnabled,
modifier = track("game-zoom-out").width(42.dp).controllerConfirm(enabled = zoomOutEnabled, onClick = zoomOut),
contentPadding = PaddingValues(horizontal = 4.dp, vertical = 0.dp)) { Text("−") }
Text("${(a.gameZoom * 100.0f).toInt()}%", fontSize = 12.sp)
OutlinedButton(onClick = zoomIn, enabled = zoomInEnabled,
modifier = track("game-zoom-in").width(42.dp).controllerConfirm(enabled = zoomInEnabled, onClick = zoomIn),
contentPadding = PaddingValues(horizontal = 4.dp, vertical = 0.dp)) { Text("+") }
OutlinedButton(onClick = zoomReset, enabled = zoomOutEnabled,
modifier = track("game-zoom-reset").width(48.dp).controllerConfirm(enabled = zoomOutEnabled, onClick = zoomReset),
contentPadding = PaddingValues(horizontal = 2.dp, vertical = 0.dp)) { Text("1×") }
}
internal fun GameZoomRow(
zoom: Float,
track: (String) -> Modifier,
onZoom: (Float) -> Unit,
) {
val source = remember { MutableInteractionSource() }
val focused by source.collectIsFocusedAsState()
val label = stringResource(R.string.game_zoom_title)
val percent = (zoom * 100f).roundToInt().coerceIn(GAME_ZOOM_MIN, GAME_ZOOM_MAX)
val value = stringResource(R.string.game_zoom_value, percent)
fun detent(value: Float): Int = ((value - GAME_ZOOM_MIN) / GAME_ZOOM_STEP).roundToInt()
val selectedDetent = detent(percent.toFloat())
val rtl = LocalLayoutDirection.current == LayoutDirection.Rtl
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
fun chooseDetent(index: Int) {
val next = GAME_ZOOM_MIN + index.coerceIn(0, GAME_ZOOM_INTERVALS) * GAME_ZOOM_STEP
if (next != percent) onZoom(next / 100f)
}
Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) {
Row(
Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(value, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold,
color = colors.onSurface, modifier = Modifier.testTag("game-zoom-value"))
}
Slider(
value = (GAME_ZOOM_MIN + selectedDetent * GAME_ZOOM_STEP).toFloat(),
onValueChange = { chooseDetent(detent(it)) },
valueRange = GAME_ZOOM_MIN.toFloat()..GAME_ZOOM_MAX.toFloat(),
steps = GAME_ZOOM_INTERVALS - 1,
interactionSource = source,
modifier = track("game-zoom-slider").fillMaxWidth().heightIn(min = 48.dp)
.glideBorder(focused, RoundedCornerShape(10.dp), pal.signal)
.testTag("game-zoom-slider")
.semantics { contentDescription = label; stateDescription = value }
.onPreviewKeyEvent { event ->
val delta = when (event.key) {
Key.DirectionLeft -> if (rtl) 1 else -1
Key.DirectionRight -> if (rtl) -1 else 1
else -> return@onPreviewKeyEvent false
}
if (event.type == KeyEventType.KeyDown && event.nativeKeyEvent.repeatCount == 0) {
chooseDetent(selectedDetent + delta)
}
true
},
)
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
@Composable
@@ -1513,7 +1562,44 @@ internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boole
private val DRAWER_MIN_WIDTH = 300.dp
private val DRAWER_HANDLE_STRIP = 24.dp
private val DRAWER_EDGE_GAP = 80.dp
private val DRAWER_COLUMN_GAP = 10.dp
// Two columns once each would be as wide as the narrowest single-column sheet.
private val DRAWER_TWO_COLUMN_WIDTH = DRAWER_MIN_WIDTH * 2 + DRAWER_COLUMN_GAP
private val SessionDrawerPage.inColumns: Boolean
get() = this != SessionDrawerPage.MORE && this != SessionDrawerPage.ACHIEVEMENTS
/**
* On a wide sheet, lays a page's groups out in two columns, the first half on the left. The split is by count, not
* height, so a group keeps its column while others fold and unfold.
*/
@Composable
internal fun DrawerColumns(two: Boolean, content: @Composable () -> Unit) {
// Keep a single composition so resizing only remeasures existing children.
Layout(content, Modifier.fillMaxWidth()) { measurables, constraints ->
val width = constraints.maxWidth
if (!two || measurables.size < 2) {
val placeables = measurables.map { it.measure(constraints.copy(minWidth = 0, minHeight = 0)) }
return@Layout layout(width, placeables.sumOf { it.height }) {
var y = 0
placeables.forEach { it.placeRelative(0, y); y += it.height }
}
}
val gap = DRAWER_COLUMN_GAP.roundToPx()
val column = ((width - gap) / 2).coerceAtLeast(0)
val child = Constraints(maxWidth = column)
val placeables = measurables.map { it.measure(child) }
val half = (placeables.size + 1) / 2
val left = placeables.take(half)
val right = placeables.drop(half)
layout(width, maxOf(left.sumOf { it.height }, right.sumOf { it.height })) {
var y = 0
left.forEach { it.placeRelative(0, y); y += it.height }
y = 0
right.forEach { it.placeRelative(column + gap, y); y += it.height }
}
}
}
/** A grip on the sheet's left edge: dragging it, or pressing left and right on a controller, resizes the sheet. */
@Composable
@@ -1535,6 +1621,8 @@ private fun DrawerResizeHandle(width: Dp, min: Dp, max: Dp, onWidth: (Dp) -> Uni
contentAlignment = Alignment.Center,
modifier = modifier.width(24.dp).height(96.dp)
.onGloballyPositioned { coords = it }
// On the screen's edge, Android's back swipe would take the drag.
.systemGestureExclusion()
.focusable(true, source)
.onPreviewKeyEvent { event ->
val key = event.nativeKeyEvent
@@ -1848,7 +1936,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
}
return
}
SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components") {
DrawerComponentSettingsGroup(stringResource(R.string.drawer_game_components_note, gameProfile.name)) {
DrawerStackedChoice(
host = host,
key = "game-cmp-proton",
@@ -1891,12 +1979,6 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
)
}
}
Text(
stringResource(R.string.drawer_game_components_note, gameProfile.name),
fontSize = 12.sp,
color = colors.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp),
)
return
}
val running = snap.protons.filter { it.inUseByGame }
@@ -1937,7 +2019,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
return
}
val p = view.proton
SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components") {
DrawerComponentSettingsGroup(stringResource(R.string.drawer_components_note)) {
DrawerStackedChoice(
host, "cmp-proton", stringResource(R.string.comp_proton),
listOfNotNull(
@@ -1973,10 +2055,16 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
)
}
}
Text(
stringResource(R.string.drawer_components_note),
fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp),
)
}
@Composable
internal fun DrawerComponentSettingsGroup(note: String, content: @Composable ColumnScope.() -> Unit) {
// The note stays visible when collapsed, but both belong to one drawer column item.
Column(Modifier.fillMaxWidth()) {
SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components", content = content)
Text(note, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp))
}
}
@Composable
@@ -0,0 +1,62 @@
package com.droiddeck.launcher.ui
import android.os.SystemClock
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
/** The row a settings search result opens, so the page it lands on can scroll to it and flash it. */
internal object SettingsJump {
class Target(val label: String, val at: Long = SystemClock.uptimeMillis())
var target: Target? by mutableStateOf(null)
fun to(label: String) { target = Target(label) }
}
private const val JUMP_WINDOW_MS = 5_000L
/** False in the search results, whose rows carry the same labels as the rows they open. */
internal val LocalSearchTargets = staticCompositionLocalOf { true }
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
internal fun Modifier.searchTarget(label: String): Modifier {
val pal = LocalPalette.current
val flash = remember { Animatable(0f) }
val reveal = remember { BringIntoViewRequester() }
var claimed by remember { mutableStateOf<SettingsJump.Target?>(null) }
val target = SettingsJump.target.takeIf { LocalSearchTargets.current }
if (target != null && target.label == label) SideEffect {
if (SettingsJump.target === target) {
SettingsJump.target = null
if (SystemClock.uptimeMillis() - target.at <= JUMP_WINDOW_MS) claimed = target
}
}
claimed?.let { mine ->
LaunchedEffect(mine) {
withFrameNanos { }
reveal.bringIntoView()
repeat(2) {
flash.animateTo(1f, tween(220))
flash.animateTo(0f, tween(420))
}
claimed = null
}
}
return bringIntoViewRequester(reveal).drawBehind {
if (flash.value > 0f) drawRect(pal.signal.copy(alpha = 0.28f * flash.value))
}
}
@@ -103,7 +103,7 @@ internal fun SettingsSearchResults(query: String, frost: Boolean, onOpen: (Setti
Note(stringResource(R.string.settings_search_none, query.trim()))
return
}
Column {
androidx.compose.runtime.CompositionLocalProvider(LocalSearchTargets provides false) { Column {
found.groupBy { it.place }.forEach { (place, entries) ->
SettingsGroup(stringResource(place.title)) {
entries.forEach { entry ->
@@ -112,9 +112,10 @@ internal fun SettingsSearchResults(query: String, frost: Boolean, onOpen: (Setti
val section = entry.section
val tab = entry.tab
if (section != null) {
ActionRow(title, within, stringResource(R.string.store_open), onClick = { onOpen(section) })
ActionRow(title, within, stringResource(R.string.store_open), onClick = { SettingsJump.to(title); onOpen(section) })
} else if (tab != null) {
ActionRow(title, within, stringResource(R.string.store_open), onClick = {
SettingsJump.to(title)
if (tab == NavTabs.MORE) MoreTabs.editing = true
if (tab == "downloads") DownloadsNav.showSettings = true
RailRequest.key = tab
@@ -125,5 +126,5 @@ internal fun SettingsSearchResults(query: String, frost: Boolean, onOpen: (Setti
}
}
}
}
} }
}
@@ -536,7 +536,7 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint
minLines = hintLines ?: 1, maxLines = hintLines ?: Int.MAX_VALUE, overflow = TextOverflow.Ellipsis)
}
if (compact && !stacked) Column(
modifier = Modifier.fillMaxWidth().background(bg).padding(horizontal = 10.dp, vertical = 6.dp),
modifier = Modifier.searchTarget(label).fillMaxWidth().background(bg).padding(horizontal = 10.dp, vertical = 6.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(label, fontSize = 13.sp, lineHeight = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
@@ -545,7 +545,7 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint
}
if (hint != null || hintLines != null) hintText(11.sp)
} else if (stacked || LocalNarrowPane.current) Column(
modifier = Modifier.fillMaxWidth().background(bg).padding(
modifier = Modifier.searchTarget(label).fillMaxWidth().background(bg).padding(
horizontal = if (compact) 10.dp else 14.dp,
vertical = if (tightControlSpacing) 2.dp else if (compact) 6.dp else 12.dp),
) {
@@ -556,7 +556,7 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint
Box(Modifier.padding(top = if (tightControlSpacing) 2.dp else if (compact) 6.dp else 8.dp)) { control() }
} else Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().background(bg).padding(horizontal = 14.dp, vertical = 11.dp),
modifier = Modifier.searchTarget(label).fillMaxWidth().background(bg).padding(horizontal = 14.dp, vertical = 11.dp),
) {
Column(modifier = Modifier.weight(1f).padding(end = 12.dp)) {
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
@@ -660,7 +660,7 @@ fun SliderRow(
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(Modifier.fillMaxWidth()) {
Column(Modifier.searchTarget(label).fillMaxWidth()) {
ValueSlider(value, range, step, enabled, label, format,
modifier = modifier.padding(horizontal = 6.dp, vertical = 3.dp), onChange = onChange)
if (hint != null) Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant,
@@ -20,6 +20,7 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
@@ -114,36 +115,49 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
Column(modifier = modifier) {
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
val stacked = LocalNarrowPane.current || maxWidth < 600.dp
Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
val context = LocalContext.current
val agentReady = com.droiddeck.launcher.agent.AgentHost.installed &&
(com.droiddeck.launcher.agent.AgentSetup.ready || com.droiddeck.launcher.agent.AgentSetup.completed(context))
val installed: @Composable () -> Unit = {
SectionLabel(stringResource(R.string.upd_installed_label))
InstalledCard(s, u, me)
CheckRow(u, ua)
SectionLabel(stringResource(R.string.upd_channel))
if (stacked) {
ChannelPicker(u, ua)
Box(Modifier.height(14.dp))
StatusPanel(s, u, ua, me)
} else {
Row(horizontalArrangement = Arrangement.spacedBy(18.dp)) {
Box(Modifier.weight(1f)) { ChannelPicker(u, ua) }
Box(Modifier.weight(1.15f)) { StatusPanel(s, u, ua, me) }
}
}
SectionLabel(stringResource(R.string.upd_testers), top = 22.dp)
ToggleRow(
host, "build-watermark", stringResource(R.string.setup_build_watermark),
stringResource(R.string.setup_build_watermark_hint), s.buildWatermark,
) { a.onBuildWatermark() }
val context = LocalContext.current
val agentReady = com.droiddeck.launcher.agent.AgentHost.installed &&
(com.droiddeck.launcher.agent.AgentSetup.ready || com.droiddeck.launcher.agent.AgentSetup.completed(context))
LabBuilds(s.sessionRunning, onRebuild = if (agentReady) { info ->
LabBuilds(s.sessionRunning, header = { SectionLabel(stringResource(R.string.lab_builds)) }, onRebuild = if (agentReady) { info ->
com.droiddeck.launcher.agent.AgentHost.send(context, context.getString(R.string.agent_rebuild_lab, info.label))
context.startActivity(android.content.Intent(context, com.droiddeck.launcher.FrontEndActivity::class.java)
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "agent")
.addFlags(android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP or android.content.Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
} else null)
}
val channel: @Composable () -> Unit = {
SectionLabel(stringResource(R.string.upd_channel))
ChannelPicker(u, ua) { StatusPanel(s, u, ua, me, embedded = it) }
}
val testers: @Composable () -> Unit = {
SectionLabel(stringResource(R.string.upd_testers), top = 22.dp)
ToggleRow(
host, "build-watermark", stringResource(R.string.setup_build_watermark),
stringResource(R.string.setup_build_watermark_hint), s.buildWatermark,
) { a.onBuildWatermark() }
}
if (stacked) {
Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
installed()
Box(Modifier.height(18.dp))
channel()
testers()
}
} else {
Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(24.dp)) {
Column(Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
installed()
testers()
}
Column(Modifier.weight(1.15f).fillMaxHeight().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
channel()
}
}
}
}
}
if (u.askPermission) AlertDialog(
@@ -266,7 +280,7 @@ private fun CheckRow(u: UpdatesState, ua: UpdatesActions) {
}
@Composable
private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, me: AppUpdates.Installed) {
private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, me: AppUpdates.Installed, embedded: Boolean = false) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val catalog = u.catalog
@@ -292,13 +306,14 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m
else -> Look(pal.good, stringResource(R.string.upd_current_status), stringResource(R.string.upd_current_headline, name), null)
}
Column(
modifier = Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(18.dp),
modifier = if (embedded) Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, bottom = 14.dp)
else Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(18.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp)) {
Box(Modifier.size(7.dp).clip(CircleShape).background(look.tint))
Text(look.status, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = look.tint)
}
Text(look.headline, fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.padding(top = 4.dp))
if (!embedded) Text(look.headline, fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.padding(top = 4.dp))
if (offered) {
val size = release!!.apk?.size?.takeIf { it > 0 }?.let { megabytes(it) }
Text(
@@ -419,7 +434,7 @@ private fun changeTitle(t: String): String =
private fun megabytes(bytes: Long) = stringResource(R.string.upd_mb, ((bytes + 524_288) / 1_048_576).toInt())
@Composable
private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions) {
private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions, status: @Composable (embedded: Boolean) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val catalog = u.catalog
@@ -455,8 +470,9 @@ private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions) {
}
Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp))
if (tests.isEmpty() && catalog != null && showTests) Text(stringResource(R.string.upd_tests_none), fontSize = 12.5.sp, color = colors.onSurfaceVariant)
if (!listing) status(false)
AnimatedVisibility(listing, enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) {
TestList(tests, me, u, ua)
TestList(tests, me, u, ua, status)
}
}
}
@@ -675,7 +691,7 @@ private fun LinkPill(label: String, url: String) {
}
@Composable
private fun TestList(tests: List<Release>, me: AppUpdates.Installed, u: UpdatesState, ua: UpdatesActions) {
private fun TestList(tests: List<Release>, me: AppUpdates.Installed, u: UpdatesState, ua: UpdatesActions, status: @Composable (embedded: Boolean) -> Unit) {
val colors = MaterialTheme.colorScheme
var query by rememberSaveable { mutableStateOf("") }
val needle = query.trim().removePrefix("#").removePrefix("@")
@@ -686,18 +702,25 @@ private fun TestList(tests: List<Release>, me: AppUpdates.Installed, u: UpdatesS
val (ready, old) = matches.partition { it.versionCode >= me.versionCode }
val followedOld = u.follow.channel == Channel.TEST && old.any { it.pr == u.follow.pr }
var showOld by rememberSaveable { mutableStateOf(false) }
Column(Modifier.padding(start = 18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (tests.size > 5 || query.isNotEmpty()) AdbTextField(
value = query, onValueChange = { query = it }, label = stringResource(R.string.upd_tests_find),
keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, compact = true, showLabel = false,
placeholder = stringResource(R.string.upd_tests_find), modifier = Modifier.fillMaxWidth(),
)
if (matches.isEmpty()) Text(stringResource(R.string.upd_tests_no_match), fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(4.dp))
ready.forEach { t -> TestRow(t, u.follow.pr == t.pr && u.follow.channel == Channel.TEST) { ua.onFollow(Follow(Channel.TEST, t.pr)) } }
if (old.isNotEmpty()) {
MoreLink(stringResource(R.string.upd_tests_old, old.size, me.versionCode), "tests:old") { showOld = !showOld }
if (showOld || followedOld || needle.isNotEmpty()) old.forEach { t ->
TestRow(t, u.follow.pr == t.pr && u.follow.channel == Channel.TEST, tooOld = true) { ua.onFollow(Follow(Channel.TEST, t.pr)) }
val oldShown = showOld || followedOld || needle.isNotEmpty()
val followed = u.follow.pr.takeIf { u.follow.channel == Channel.TEST }
val rowShown = followed != null && (ready.any { it.pr == followed } || (oldShown && old.any { it.pr == followed }))
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
// A followed test's row carries the status; browsing Tests while following Stable or Preview shows it only for an install running or failed.
if (if (followed != null) !rowShown else u.stage != null || u.error != null) status(false)
Column(Modifier.padding(start = 18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
if (tests.size > 5 || query.isNotEmpty()) AdbTextField(
value = query, onValueChange = { query = it }, label = stringResource(R.string.upd_tests_find),
keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, compact = true, showLabel = false,
placeholder = stringResource(R.string.upd_tests_find), modifier = Modifier.fillMaxWidth(),
)
if (matches.isEmpty()) Text(stringResource(R.string.upd_tests_no_match), fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(4.dp))
ready.forEach { t -> TestRow(t, followed == t.pr, status = status) { ua.onFollow(Follow(Channel.TEST, t.pr)) } }
if (old.isNotEmpty()) {
MoreLink(stringResource(R.string.upd_tests_old, old.size, me.versionCode), "tests:old") { showOld = !showOld }
if (oldShown) old.forEach { t ->
TestRow(t, followed == t.pr, tooOld = true, status = status) { ua.onFollow(Follow(Channel.TEST, t.pr)) }
}
}
}
}
@@ -712,40 +735,46 @@ private fun RadioDot(selected: Boolean, size: androidx.compose.ui.unit.Dp = 22.d
}
@Composable
private fun TestRow(t: Release, selected: Boolean, tooOld: Boolean = false, onClick: () -> Unit) {
private fun TestRow(t: Release, selected: Boolean, tooOld: Boolean = false, status: @Composable (embedded: Boolean) -> Unit, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().paneItem("test:${t.pr}")
.heightIn(min = 52.dp)
.clip(Shape12)
.background(colors.surface).background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(hot, Shape12, pal.signal, pal.line)
.alpha(if (tooOld && !selected) 0.6f else 1f)
.hoverable(src)
.clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 12.dp, vertical = 8.dp),
Column(
Modifier.fillMaxWidth().clip(Shape12).background(colors.surface)
.glideBorder(hot, Shape12, pal.signal, if (selected) pal.signal.copy(alpha = 0.5f) else pal.line),
) {
Text("#${t.pr}", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = if (selected) pal.signal else colors.onSurfaceVariant)
Column(Modifier.weight(1f)) {
Text(changeTitle(t.title.ifBlank { stringResource(R.string.upd_pr, t.pr) }), fontSize = 13.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
val detail = when {
t.apk == null -> stringResource(R.string.upd_not_built)
tooOld -> stringResource(R.string.upd_tests_old_row, t.versionCode)
else -> stringResource(R.string.upd_updated, ago(t.builtAt.takeIf { it > 0 } ?: t.publishedAt))
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().paneItem("test:${t.pr}")
.heightIn(min = 52.dp)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.alpha(if (tooOld && !selected) 0.6f else 1f)
.hoverable(src)
.clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 12.dp, vertical = 8.dp),
) {
Text("#${t.pr}", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = if (selected) pal.signal else colors.onSurfaceVariant)
Column(Modifier.weight(1f)) {
Text(changeTitle(t.title.ifBlank { stringResource(R.string.upd_pr, t.pr) }), fontSize = 13.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
val detail = when {
t.apk == null -> stringResource(R.string.upd_not_built)
tooOld -> stringResource(R.string.upd_tests_old_row, t.versionCode)
else -> stringResource(R.string.upd_updated, ago(t.builtAt.takeIf { it > 0 } ?: t.publishedAt))
}
Text(
listOfNotNull(detail, t.author.takeIf { it.isNotEmpty() }?.let { "@$it" }, t.shortCommit).joinToString(" · "),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
if (t.newerCommitPushed) Text(stringResource(R.string.upd_newer_commit_short), fontSize = 12.sp, color = AttentionAmber, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
Text(
listOfNotNull(detail, t.author.takeIf { it.isNotEmpty() }?.let { "@$it" }, t.shortCommit).joinToString(" · "),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
if (t.newerCommitPushed) Text(stringResource(R.string.upd_newer_commit_short), fontSize = 12.sp, color = AttentionAmber, maxLines = 1, overflow = TextOverflow.Ellipsis)
RadioDot(selected, 20.dp)
}
AnimatedVisibility(selected, enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) {
status(true)
}
RadioDot(selected, 20.dp)
}
}
@@ -333,6 +333,8 @@ public final class WaylandCompositor {
public static native void nativeSetZeroCopy(boolean on);
public static native void nativeSetMirrorCapture(boolean on);
public static native void nativeSetDisplayBufferDriver(boolean on);
public static native int nativeZeroCopyFrames();
@@ -2,7 +2,13 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="512"
android:viewportHeight="512">
<path android:fillColor="#FFFFFFFF" android:fillType="evenOdd" android:pathData="M 142 335 L 148 343 L 148 345 L 155 352 L 165 365 L 166 368 L 169 370 L 171 374 L 176 379 L 177 382 L 179 383 L 181 387 L 187 393 L 187 395 L 193 401 L 196 400 L 200 392 L 206 386 L 259 419 L 262 418 L 266 411 L 264 406 L 250 398 L 249 396 L 242 391 L 237 389 L 236 387 L 231 385 L 227 381 L 215 374 L 215 371 L 222 361 L 222 356 L 220 353 Z M 472 198 L 463 195 L 446 195 L 436 198 L 431 198 L 426 200 L 418 201 L 415 203 L 382 209 L 375 212 L 361 214 L 353 217 L 349 224 L 349 226 L 346 229 L 339 245 L 336 248 L 281 354 L 274 365 L 275 370 L 279 376 L 279 379 L 311 450 L 311 453 L 317 465 L 325 473 L 327 474 L 339 474 L 348 470 L 353 465 L 360 454 L 369 436 L 369 434 L 372 430 L 374 424 L 385 404 L 388 396 L 399 376 L 463 246 L 466 243 L 470 232 L 480 214 L 479 205 Z M 444 224 L 445 226 L 337 439 L 334 435 L 332 428 L 316 393 L 315 388 L 312 384 L 312 381 L 305 367 L 305 364 L 307 362 L 348 282 L 369 244 L 369 242 L 372 239 L 381 238 L 386 236 L 390 236 L 395 234 L 409 232 L 423 228 L 432 227 L 440 224 Z M 211 187 L 201 192 L 201 194 L 203 196 L 203 198 L 228 249 L 225 251 L 166 265 L 165 266 L 169 280 L 234 264 L 242 278 L 242 280 L 265 327 L 278 321 L 278 319 L 250 261 L 252 259 L 313 244 L 310 229 L 244 246 L 235 230 L 235 228 L 226 211 L 226 209 L 224 207 L 215 186 Z M 233 127 L 233 129 L 235 131 L 240 133 L 243 136 L 248 138 L 287 162 L 287 165 L 279 178 L 281 181 L 288 183 L 290 182 L 304 186 L 310 186 L 313 188 L 316 187 L 320 189 L 343 192 L 350 195 L 352 194 L 357 196 L 362 196 L 354 186 L 351 184 L 350 181 L 347 179 L 339 168 L 335 165 L 335 163 L 324 152 L 323 149 L 320 147 L 311 135 L 307 134 L 302 136 L 302 138 L 297 144 L 297 146 L 295 148 L 292 148 L 282 141 L 276 139 L 266 132 L 264 132 L 253 125 L 247 123 L 242 119 L 237 120 Z M 221 73 L 212 70 L 195 70 L 175 75 L 170 75 L 154 80 L 140 82 L 135 84 L 130 84 L 123 87 L 103 91 L 95 103 L 88 119 L 86 121 L 79 136 L 75 141 L 73 147 L 66 158 L 59 174 L 56 177 L 23 240 L 24 245 L 34 266 L 34 269 L 44 289 L 44 292 L 60 326 L 63 335 L 67 342 L 72 347 L 76 349 L 91 348 L 95 346 L 106 334 L 118 310 L 118 308 L 120 306 L 229 88 L 228 80 Z M 193 99 L 194 100 L 190 107 L 190 109 L 183 121 L 183 123 L 181 125 L 176 137 L 174 139 L 132 224 L 130 226 L 123 242 L 112 261 L 89 307 L 88 311 L 85 314 L 58 250 L 53 241 L 62 223 L 74 202 L 118 117 L 121 114 L 129 113 L 134 111 L 139 111 L 162 105 L 167 105 L 188 99 Z" />
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M4.5,7.5 H13.8 Q15.5,7.5 15.5,9.2 V18.8 Q15.5,20.5 13.8,20.5 H4.5 Q2.8,20.5 2.8,18.8 V9.2 Q2.8,7.5 4.5,7.5 Z M7.2,4 H18.2 Q20,4 20,5.8 V9 M20,12.2 V18.2 M17,15.2 H23"
android:fillColor="@android:color/transparent"
android:strokeColor="#FFFFFFFF"
android:strokeWidth="1.75"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+5
View File
@@ -1180,6 +1180,11 @@
<string name="agent_tools_missing">أدوات الوكيل غير مثبتة: %1$s</string>
<string name="agent_unqueue">لا تُرسل</string>
<string name="agent_attach">إرفاق</string>
<string name="agent_attach_files">الملفات</string>
<string name="agent_photos_allow">السماح بالوصول إلى الصور</string>
<string name="agent_photos_more">اختيار المزيد من الصور</string>
<string name="agent_photos_empty">لا توجد صور بعد</string>
<string name="agent_keyboard">لوحة المفاتيح</string>
<string name="agent_remove_attachment">إزالة</string>
<string name="agent_model_default">الافتراضي</string>
<string name="agent_effort">جهد الاستدلال</string>
@@ -1198,6 +1198,11 @@
<string name="agent_tools_missing">Herramientas del agente sin instalar: %1$s</string>
<string name="agent_unqueue">No enviar</string>
<string name="agent_attach">Adjuntar</string>
<string name="agent_attach_files">Archivos</string>
<string name="agent_photos_allow">Permitir acceso a fotos</string>
<string name="agent_photos_more">Elegir más fotos</string>
<string name="agent_photos_empty">Aún no hay fotos</string>
<string name="agent_keyboard">Teclado</string>
<string name="agent_remove_attachment">Quitar</string>
<string name="agent_model_default">Predeterminado</string>
<string name="agent_effort">Esfuerzo de razonamiento</string>
+5
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Инструментите на агента не са инсталирани: %1$s</string>
<string name="agent_unqueue">Не изпращай</string>
<string name="agent_attach">Прикачи</string>
<string name="agent_attach_files">Файлове</string>
<string name="agent_photos_allow">Разрешаване на достъп до снимки</string>
<string name="agent_photos_more">Избор на още снимки</string>
<string name="agent_photos_empty">Все още няма снимки</string>
<string name="agent_keyboard">Клавиатура</string>
<string name="agent_remove_attachment">Премахни</string>
<string name="agent_model_default">По подразбиране</string>
<string name="agent_effort">Усилие за разсъждение</string>
+5
View File
@@ -1174,6 +1174,11 @@
<string name="agent_tools_missing">Nástroje agenta nejsou nainstalované: %1$s</string>
<string name="agent_unqueue">Neposílat</string>
<string name="agent_attach">Přiložit</string>
<string name="agent_attach_files">Soubory</string>
<string name="agent_photos_allow">Povolit přístup k fotkám</string>
<string name="agent_photos_more">Vybrat další fotky</string>
<string name="agent_photos_empty">Zatím žádné fotky</string>
<string name="agent_keyboard">Klávesnice</string>
<string name="agent_remove_attachment">Odebrat</string>
<string name="agent_model_default">Výchozí</string>
<string name="agent_effort">Náročnost uvažování</string>
+5
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Agentens værktøjer er ikke installeret: %1$s</string>
<string name="agent_unqueue">Send ikke</string>
<string name="agent_attach">Vedhæft</string>
<string name="agent_attach_files">Filer</string>
<string name="agent_photos_allow">Tillad adgang til billeder</string>
<string name="agent_photos_more">Vælg flere billeder</string>
<string name="agent_photos_empty">Ingen billeder endnu</string>
<string name="agent_keyboard">Tastatur</string>
<string name="agent_remove_attachment">Fjern</string>
<string name="agent_model_default">Standard</string>
<string name="agent_effort">Ræsonneringsindsats</string>
+5
View File
@@ -1160,6 +1160,11 @@
<string name="agent_tools_missing">Agent-Werkzeuge nicht installiert: %1$s</string>
<string name="agent_unqueue">Nicht senden</string>
<string name="agent_attach">Anhängen</string>
<string name="agent_attach_files">Dateien</string>
<string name="agent_photos_allow">Zugriff auf Fotos erlauben</string>
<string name="agent_photos_more">Weitere Fotos auswählen</string>
<string name="agent_photos_empty">Noch keine Fotos</string>
<string name="agent_keyboard">Tastatur</string>
<string name="agent_remove_attachment">Entfernen</string>
<string name="agent_model_default">Standard</string>
<string name="agent_effort">Denkaufwand</string>
+5
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Τα εργαλεία του πράκτορα δεν εγκαταστάθηκαν: %1$s</string>
<string name="agent_unqueue">Να μην σταλεί</string>
<string name="agent_attach">Επισύναψη</string>
<string name="agent_attach_files">Αρχεία</string>
<string name="agent_photos_allow">Να επιτρέπεται η πρόσβαση στις φωτογραφίες</string>
<string name="agent_photos_more">Επιλογή περισσότερων φωτογραφιών</string>
<string name="agent_photos_empty">Δεν υπάρχουν φωτογραφίες ακόμα</string>
<string name="agent_keyboard">Πληκτρολόγιο</string>
<string name="agent_remove_attachment">Αφαίρεση</string>
<string name="agent_model_default">Προεπιλογή</string>
<string name="agent_effort">Προσπάθεια συλλογισμού</string>
+5
View File
@@ -1171,6 +1171,11 @@
<string name="agent_tools_missing">Herramientas del agente sin instalar: %1$s</string>
<string name="agent_unqueue">No enviar</string>
<string name="agent_attach">Adjuntar</string>
<string name="agent_attach_files">Archivos</string>
<string name="agent_photos_allow">Permitir acceso a las fotos</string>
<string name="agent_photos_more">Elegir más fotos</string>
<string name="agent_photos_empty">Aún no hay fotos</string>
<string name="agent_keyboard">Teclado</string>
<string name="agent_remove_attachment">Quitar</string>
<string name="agent_model_default">Predeterminado</string>
<string name="agent_effort">Esfuerzo de razonamiento</string>
+5
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Agentin työkaluja ei ole asennettu: %1$s</string>
<string name="agent_unqueue">Älä lähetä</string>
<string name="agent_attach">Liitä</string>
<string name="agent_attach_files">Tiedostot</string>
<string name="agent_photos_allow">Salli kuvien käyttö</string>
<string name="agent_photos_more">Valitse lisää kuvia</string>
<string name="agent_photos_empty">Ei vielä kuvia</string>
<string name="agent_keyboard">Näppäimistö</string>
<string name="agent_remove_attachment">Poista</string>
<string name="agent_model_default">Oletus</string>
<string name="agent_effort">Päättelyteho</string>
+5
View File
@@ -1171,6 +1171,11 @@
<string name="agent_tools_missing">Outils de l’agent non installés : %1$s</string>
<string name="agent_unqueue">Ne pas envoyer</string>
<string name="agent_attach">Joindre</string>
<string name="agent_attach_files">Fichiers</string>
<string name="agent_photos_allow">Autoriser l\'accès aux photos</string>
<string name="agent_photos_more">Choisir d\'autres photos</string>
<string name="agent_photos_empty">Aucune photo pour l\'instant</string>
<string name="agent_keyboard">Clavier</string>
<string name="agent_remove_attachment">Supprimer</string>
<string name="agent_model_default">Par défaut</string>
<string name="agent_effort">Effort de raisonnement</string>
+5
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">एजेंट टूल इंस्टॉल नहीं हुए: %1$s</string>
<string name="agent_unqueue">न भेजें</string>
<string name="agent_attach">संलग्न करें</string>
<string name="agent_attach_files">फ़ाइलें</string>
<string name="agent_photos_allow">फ़ोटो की अनुमति दें</string>
<string name="agent_photos_more">और फ़ोटो चुनें</string>
<string name="agent_photos_empty">अभी कोई फ़ोटो नहीं</string>
<string name="agent_keyboard">कीबोर्ड</string>
<string name="agent_remove_attachment">हटाएँ</string>
<string name="agent_model_default">डिफ़ॉल्ट</string>
<string name="agent_effort">सोचने का स्तर</string>
+5
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Az ügynök eszközei nincsenek telepítve: %1$s</string>
<string name="agent_unqueue">Ne küldd el</string>
<string name="agent_attach">Csatolás</string>
<string name="agent_attach_files">Fájlok</string>
<string name="agent_photos_allow">Fotókhoz való hozzáférés engedélyezése</string>
<string name="agent_photos_more">További fotók kiválasztása</string>
<string name="agent_photos_empty">Még nincsenek fotók</string>
<string name="agent_keyboard">Billentyűzet</string>
<string name="agent_remove_attachment">Eltávolítás</string>
<string name="agent_model_default">Alapértelmezett</string>
<string name="agent_effort">Gondolkodási erőfeszítés</string>
+5
View File
@@ -1165,6 +1165,11 @@
<string name="agent_tools_missing">Alat agen tidak terpasang: %1$s</string>
<string name="agent_unqueue">Jangan kirim</string>
<string name="agent_attach">Lampirkan</string>
<string name="agent_attach_files">File</string>
<string name="agent_photos_allow">Izinkan akses foto</string>
<string name="agent_photos_more">Pilih foto lainnya</string>
<string name="agent_photos_empty">Belum ada foto</string>
<string name="agent_keyboard">Keyboard</string>
<string name="agent_remove_attachment">Hapus</string>
<string name="agent_model_default">Default</string>
<string name="agent_effort">Upaya penalaran</string>
+5
View File
@@ -1163,6 +1163,11 @@
<string name="agent_tools_missing">Strumenti dell’agente non installati: %1$s</string>
<string name="agent_unqueue">Non inviare</string>
<string name="agent_attach">Allega</string>
<string name="agent_attach_files">File</string>
<string name="agent_photos_allow">Consenti accesso alle foto</string>
<string name="agent_photos_more">Scegli altre foto</string>
<string name="agent_photos_empty">Ancora nessuna foto</string>
<string name="agent_keyboard">Tastiera</string>
<string name="agent_remove_attachment">Rimuovi</string>
<string name="agent_model_default">Predefinito</string>
<string name="agent_effort">Livello di ragionamento</string>
+5
View File
@@ -1165,6 +1165,11 @@
<string name="agent_tools_missing">エージェントのツールが未インストール: %1$s</string>
<string name="agent_unqueue">送信しない</string>
<string name="agent_attach">添付</string>
<string name="agent_attach_files">ファイル</string>
<string name="agent_photos_allow">写真へのアクセスを許可</string>
<string name="agent_photos_more">写真をさらに選択</string>
<string name="agent_photos_empty">まだ写真がありません</string>
<string name="agent_keyboard">キーボード</string>
<string name="agent_remove_attachment">削除</string>
<string name="agent_model_default">デフォルト</string>
<string name="agent_effort">推論レベル</string>
+5
View File
@@ -1165,6 +1165,11 @@
<string name="agent_tools_missing">에이전트 도구가 설치되지 않음: %1$s</string>
<string name="agent_unqueue">보내지 않기</string>
<string name="agent_attach">첨부</string>
<string name="agent_attach_files">파일</string>
<string name="agent_photos_allow">사진 접근 허용</string>
<string name="agent_photos_more">사진 더 선택</string>
<string name="agent_photos_empty">아직 사진이 없습니다</string>
<string name="agent_keyboard">키보드</string>
<string name="agent_remove_attachment">제거</string>
<string name="agent_model_default">기본</string>
<string name="agent_effort">추론 수준</string>
+5
View File
@@ -1165,6 +1165,11 @@
<string name="agent_tools_missing">Alat ejen tidak dipasang: %1$s</string>
<string name="agent_unqueue">Jangan hantar</string>
<string name="agent_attach">Lampirkan</string>
<string name="agent_attach_files">Fail</string>
<string name="agent_photos_allow">Benarkan akses foto</string>
<string name="agent_photos_more">Pilih lebih banyak foto</string>
<string name="agent_photos_empty">Belum ada foto</string>
<string name="agent_keyboard">Papan kekunci</string>
<string name="agent_remove_attachment">Alih keluar</string>
<string name="agent_model_default">Lalai</string>
<string name="agent_effort">Usaha penaakulan</string>
+5
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Agentverktøy er ikke installert: %1$s</string>
<string name="agent_unqueue">Ikke send</string>
<string name="agent_attach">Legg ved</string>
<string name="agent_attach_files">Filer</string>
<string name="agent_photos_allow">Tillat tilgang til bilder</string>
<string name="agent_photos_more">Velg flere bilder</string>
<string name="agent_photos_empty">Ingen bilder ennå</string>
<string name="agent_keyboard">Tastatur</string>
<string name="agent_remove_attachment">Fjern</string>
<string name="agent_model_default">Standard</string>
<string name="agent_effort">Resonneringsinnsats</string>
+5
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Agenttools niet geïnstalleerd: %1$s</string>
<string name="agent_unqueue">Niet verzenden</string>
<string name="agent_attach">Bijvoegen</string>
<string name="agent_attach_files">Bestanden</string>
<string name="agent_photos_allow">Toegang tot foto\'s toestaan</string>
<string name="agent_photos_more">Meer foto\'s kiezen</string>
<string name="agent_photos_empty">Nog geen foto\'s</string>
<string name="agent_keyboard">Toetsenbord</string>
<string name="agent_remove_attachment">Verwijderen</string>
<string name="agent_model_default">Standaard</string>
<string name="agent_effort">Redeneerinspanning</string>
+5
View File
@@ -1174,6 +1174,11 @@
<string name="agent_tools_missing">Narzędzia agenta nie są zainstalowane: %1$s</string>
<string name="agent_unqueue">Nie wysyłaj</string>
<string name="agent_attach">Załącz</string>
<string name="agent_attach_files">Pliki</string>
<string name="agent_photos_allow">Zezwól na dostęp do zdjęć</string>
<string name="agent_photos_more">Wybierz więcej zdjęć</string>
<string name="agent_photos_empty">Brak zdjęć</string>
<string name="agent_keyboard">Klawiatura</string>
<string name="agent_remove_attachment">Usuń</string>
<string name="agent_model_default">Domyślny</string>
<string name="agent_effort">Poziom rozumowania</string>
@@ -1163,6 +1163,11 @@
<string name="agent_tools_missing">Ferramentas do agente não instaladas: %1$s</string>
<string name="agent_unqueue">Não enviar</string>
<string name="agent_attach">Anexar</string>
<string name="agent_attach_files">Ficheiros</string>
<string name="agent_photos_allow">Permitir acesso às fotos</string>
<string name="agent_photos_more">Escolher mais fotos</string>
<string name="agent_photos_empty">Ainda não há fotos</string>
<string name="agent_keyboard">Teclado</string>
<string name="agent_remove_attachment">Remover</string>
<string name="agent_model_default">Predefinido</string>
<string name="agent_effort">Esforço de raciocínio</string>
+5
View File
@@ -1170,6 +1170,11 @@
<string name="agent_tools_missing">Ferramentas do agente não instaladas: %1$s</string>
<string name="agent_unqueue">Não enviar</string>
<string name="agent_attach">Anexar</string>
<string name="agent_attach_files">Arquivos</string>
<string name="agent_photos_allow">Permitir acesso às fotos</string>
<string name="agent_photos_more">Escolher mais fotos</string>
<string name="agent_photos_empty">Ainda não há fotos</string>
<string name="agent_keyboard">Teclado</string>
<string name="agent_remove_attachment">Remover</string>
<string name="agent_model_default">Padrão</string>
<string name="agent_effort">Esforço de raciocínio</string>
+5
View File
@@ -1171,6 +1171,11 @@
<string name="agent_tools_missing">Instrumentele agentului nu sunt instalate: %1$s</string>
<string name="agent_unqueue">Nu trimite</string>
<string name="agent_attach">Atașează</string>
<string name="agent_attach_files">Fișiere</string>
<string name="agent_photos_allow">Permite accesul la fotografii</string>
<string name="agent_photos_more">Alege mai multe fotografii</string>
<string name="agent_photos_empty">Încă nu există fotografii</string>
<string name="agent_keyboard">Tastatură</string>
<string name="agent_remove_attachment">Elimină</string>
<string name="agent_model_default">Implicit</string>
<string name="agent_effort">Efort de raționament</string>
+5
View File
@@ -1174,6 +1174,11 @@
<string name="agent_tools_missing">Инструменты агента не установлены: %1$s</string>
<string name="agent_unqueue">Не отправлять</string>
<string name="agent_attach">Прикрепить</string>
<string name="agent_attach_files">Файлы</string>
<string name="agent_photos_allow">Разрешить доступ к фото</string>
<string name="agent_photos_more">Выбрать ещё фото</string>
<string name="agent_photos_empty">Пока нет фото</string>
<string name="agent_keyboard">Клавиатура</string>
<string name="agent_remove_attachment">Удалить</string>
<string name="agent_model_default">По умолчанию</string>
<string name="agent_effort">Уровень рассуждений</string>
+5
View File
@@ -1168,6 +1168,11 @@
<string name="agent_tools_missing">Agentens verktyg är inte installerade: %1$s</string>
<string name="agent_unqueue">Skicka inte</string>
<string name="agent_attach">Bifoga</string>
<string name="agent_attach_files">Filer</string>
<string name="agent_photos_allow">Tillåt åtkomst till bilder</string>
<string name="agent_photos_more">Välj fler bilder</string>
<string name="agent_photos_empty">Inga bilder än</string>
<string name="agent_keyboard">Tangentbord</string>
<string name="agent_remove_attachment">Ta bort</string>
<string name="agent_model_default">Standard</string>
<string name="agent_effort">Resonemangsnivå</string>
+5
View File
@@ -1165,6 +1165,11 @@
<string name="agent_tools_missing">ยังไม่ได้ติดตั้งเครื่องมือของเอเจนต์: %1$s</string>
<string name="agent_unqueue">ไม่ต้องส่ง</string>
<string name="agent_attach">แนบ</string>
<string name="agent_attach_files">ไฟล์</string>
<string name="agent_photos_allow">อนุญาตให้เข้าถึงรูปภาพ</string>
<string name="agent_photos_more">เลือกรูปภาพเพิ่ม</string>
<string name="agent_photos_empty">ยังไม่มีรูปภาพ</string>
<string name="agent_keyboard">แป้นพิมพ์</string>
<string name="agent_remove_attachment">นำออก</string>
<string name="agent_model_default">ค่าเริ่มต้น</string>
<string name="agent_effort">ระดับการใช้เหตุผล</string>
+5
View File
@@ -1160,6 +1160,11 @@
<string name="agent_tools_missing">Ajan araçları yüklenmedi: %1$s</string>
<string name="agent_unqueue">Gönderme</string>
<string name="agent_attach">Ekle</string>
<string name="agent_attach_files">Dosyalar</string>
<string name="agent_photos_allow">Fotoğraflara erişime izin ver</string>
<string name="agent_photos_more">Daha fazla fotoğraf seç</string>
<string name="agent_photos_empty">Henüz fotoğraf yok</string>
<string name="agent_keyboard">Klavye</string>
<string name="agent_remove_attachment">Kaldır</string>
<string name="agent_model_default">Varsayılan</string>
<string name="agent_effort">Akıl yürütme çabası</string>
+5
View File
@@ -1174,6 +1174,11 @@
<string name="agent_tools_missing">Інструменти агента не встановлено: %1$s</string>
<string name="agent_unqueue">Не надсилати</string>
<string name="agent_attach">Прикріпити</string>
<string name="agent_attach_files">Файли</string>
<string name="agent_photos_allow">Дозволити доступ до фото</string>
<string name="agent_photos_more">Вибрати ще фото</string>
<string name="agent_photos_empty">Поки немає фото</string>
<string name="agent_keyboard">Клавіатура</string>
<string name="agent_remove_attachment">Видалити</string>
<string name="agent_model_default">За замовчуванням</string>
<string name="agent_effort">Рівень міркувань</string>
+5
View File
@@ -1165,6 +1165,11 @@
<string name="agent_tools_missing">Chưa cài công cụ của tác tử: %1$s</string>
<string name="agent_unqueue">Không gửi</string>
<string name="agent_attach">Đính kèm</string>
<string name="agent_attach_files">Tệp</string>
<string name="agent_photos_allow">Cho phép truy cập ảnh</string>
<string name="agent_photos_more">Chọn thêm ảnh</string>
<string name="agent_photos_empty">Chưa có ảnh</string>
<string name="agent_keyboard">Bàn phím</string>
<string name="agent_remove_attachment">Xóa</string>
<string name="agent_model_default">Mặc định</string>
<string name="agent_effort">Mức độ lập luận</string>
@@ -1248,6 +1248,11 @@
<string name="agent_tools_missing">智能体工具未安装:%1$s</string>
<string name="agent_unqueue">不发送</string>
<string name="agent_attach">添加附件</string>
<string name="agent_attach_files">文件</string>
<string name="agent_photos_allow">允许访问照片</string>
<string name="agent_photos_more">选择更多照片</string>
<string name="agent_photos_empty">还没有照片</string>
<string name="agent_keyboard">键盘</string>
<string name="agent_remove_attachment">移除</string>
<string name="agent_model_default">默认</string>
<string name="agent_effort">推理强度</string>
@@ -1164,6 +1164,11 @@
<string name="agent_tools_missing">智能體工具未安裝:%1$s</string>
<string name="agent_unqueue">不要傳送</string>
<string name="agent_attach">附加</string>
<string name="agent_attach_files">檔案</string>
<string name="agent_photos_allow">允許存取相片</string>
<string name="agent_photos_more">選擇更多相片</string>
<string name="agent_photos_empty">尚未有相片</string>
<string name="agent_keyboard">鍵盤</string>
<string name="agent_remove_attachment">移除</string>
<string name="agent_model_default">預設</string>
<string name="agent_effort">推理強度</string>
@@ -1164,6 +1164,11 @@
<string name="agent_tools_missing">智慧代理工具未安裝:%1$s</string>
<string name="agent_unqueue">不要傳送</string>
<string name="agent_attach">附加</string>
<string name="agent_attach_files">檔案</string>
<string name="agent_photos_allow">允許存取相片</string>
<string name="agent_photos_more">選擇更多相片</string>
<string name="agent_photos_empty">還沒有相片</string>
<string name="agent_keyboard">鍵盤</string>
<string name="agent_remove_attachment">移除</string>
<string name="agent_model_default">預設</string>
<string name="agent_effort">推理強度</string>
+12
View File
@@ -1224,6 +1224,10 @@
<string name="lab_not_loaded">Not loaded: %1$s</string>
<string name="lab_waiting">Waiting for a restart</string>
<string name="lab_kept">Kept</string>
<plurals name="lab_kept_count">
<item quantity="one">%d kept build</item>
<item quantity="other">%d kept builds</item>
</plurals>
<string name="lab_other_install">For another version</string>
<string name="lab_rebuild">Rebuild</string>
<string name="lab_delete_warning">Deletes this build from the device</string>
@@ -1326,6 +1330,11 @@
<string name="agent_tools_missing">Agent tools not installed: %1$s</string>
<string name="agent_unqueue">Don\'t send</string>
<string name="agent_attach">Attach</string>
<string name="agent_attach_files">Files</string>
<string name="agent_photos_allow">Allow photo access</string>
<string name="agent_photos_more">Choose more photos</string>
<string name="agent_photos_empty">No photos yet</string>
<string name="agent_keyboard">Keyboard</string>
<string name="agent_remove_attachment">Remove</string>
<string name="agent_model_default">Default</string>
<string name="agent_effort">Reasoning effort</string>
@@ -2838,6 +2847,9 @@
<string name="display_image_scaling">Image scaling</string>
<string name="game_zoom_hint">Adjust game magnification from 100% to 300%</string>
<string name="game_zoom_title">Game zoom</string>
<string name="game_zoom_value">%1$d%%</string>
<string name="frame_gen_engine">Engine</string>
<string name="frame_gen_use_global">Use global setting</string>
<string name="display_integer_scaling">Integer scaling</string>
<string name="display_integer_scaling_hint">Uses the largest whole-number scale that fits. May crop screen edges. If the source is larger than the output, fractional scaling fits the full image. Resolution is configured separately.</string>
<string name="display_scaling_fit">Fit</string>
@@ -41,7 +41,18 @@ class DesktopLanguageIndexSourceTest {
context = ApplicationProvider.getApplicationContext()
DownloadSource.init(context)
DownloadSource.setMode(context, DownloadSource.MODE_MIRROR)
}
// Downloads other tests leave running also go through this proxy while it is set, so it is set only around [block].
private fun tunnelsDuring(block: () -> Unit): List<String> {
DownloadSource.setProxy(context, "127.0.0.1:${proxy.localPort}")
tunnels.clear()
try {
block()
} finally {
DownloadSource.setProxy(context, "")
}
return tunnels.toList()
}
@After fun tearDown() {
@@ -51,12 +62,12 @@ class DesktopLanguageIndexSourceTest {
}
@Test fun mirrorModeWouldOtherwiseSendTheIndexThroughAMirror() {
Downloader.downloadString(base + "desktop-kde.i18n.txt")
assertTrue(tunnels.toString(), tunnels.any { host -> DownloadSource.MIRRORS.any { it.host == host } })
val seen = tunnelsDuring { Downloader.downloadString(base + "desktop-kde.i18n.txt") }
assertTrue(seen.toString(), seen.any { host -> DownloadSource.MIRRORS.any { it.host == host } })
}
@Test fun indexIsFetchedOnlyFromGithubInMirrorMode() {
assertNull(DesktopLanguage.fetchIndex(base))
assertEquals(listOf("github.com"), tunnels.toList())
val seen = tunnelsDuring { assertNull(DesktopLanguage.fetchIndex(base)) }
assertEquals(listOf("github.com"), seen)
}
}
@@ -5,6 +5,21 @@ import org.junit.Assert.assertTrue
import org.junit.Test
class SessionVisibilityPolicyTest {
@Test fun attachmentPickerKeepsTheDockedDrawerAliveDuringActivityStop() {
assertFalse(SessionVisibilityPolicy.shouldCloseSecondScreenOnStop(
screenOff = false, dockedDrawerOpen = true, attachmentPickerOpen = true,
))
assertTrue(SessionVisibilityPolicy.shouldCloseSecondScreenOnStop(
screenOff = false, dockedDrawerOpen = true, attachmentPickerOpen = false,
))
assertTrue(SessionVisibilityPolicy.shouldCloseSecondScreenOnStop(
screenOff = false, dockedDrawerOpen = false, attachmentPickerOpen = true,
))
assertFalse(SessionVisibilityPolicy.shouldCloseSecondScreenOnStop(
screenOff = true, dockedDrawerOpen = false, attachmentPickerOpen = false,
))
}
@Test fun handsetScreenStateControlsActivityOnDefaultDisplay() {
assertFalse(SessionVisibilityPolicy.isHidden(true, true, true, false))
assertTrue(SessionVisibilityPolicy.isHidden(true, false, true, true))
@@ -3,24 +3,31 @@ package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.input.InputModeManager
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.SemanticsActions
import androidx.compose.ui.test.assertIsFocused
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.getUnclippedBoundsInRoot
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performKeyInput
import androidx.compose.ui.test.performSemanticsAction
import androidx.compose.ui.test.pressKey
import androidx.compose.ui.test.requestFocus
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.ComponentsManager
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@@ -67,6 +74,29 @@ class ComponentDownloadsDrawerTest {
assertEquals(listOf(nightly), requested)
}
@Config(qualifiers = "w800dp-h800dp")
@Test fun nightlySelectionSurvivesCrossingTheColumnThreshold() {
val stable = ComponentsManager.CatalogItem("dxvk-3.1.1-linux.wcp", "dxvk", "Dxvk-Linux", "https://github.com/example/s", 100, "sha256:test")
val nightly = ComponentsManager.CatalogItem("DD-dxvk-3.1.1+153-nightly.wcp", "dxvk", ComponentsManager.DD_NIGHTLY, "https://github.com/example/n", 100, "sha256:test")
val twoColumns = mutableStateOf(false)
lateinit var menu: MenuHost
show(catalog = listOf(stable, nightly), twoColumns = twoColumns, captureHost = { menu = it })
val chooser = compose.onNodeWithTag("cmp-download-dxvk")
val nightlyRow = compose.onNodeWithText(nightly.file.removeSuffix(".wcp"))
val narrowLeft = chooser.getUnclippedBoundsInRoot().left
chooser.performSemanticsAction(SemanticsActions.OnClick)
compose.onNodeWithText(RuntimeEnvironment.getApplication().getString(R.string.comp_channel_nightly)).performClick()
nightlyRow.assertExists()
compose.runOnIdle { menu.open = null; twoColumns.value = true }
assertTrue(chooser.getUnclippedBoundsInRoot().left > narrowLeft)
chooser.performSemanticsAction(SemanticsActions.OnClick)
nightlyRow.assertExists()
compose.runOnIdle { menu.open = null; twoColumns.value = false }
assertEquals(narrowLeft, chooser.getUnclippedBoundsInRoot().left)
chooser.performSemanticsAction(SemanticsActions.OnClick)
nightlyRow.assertExists()
}
@Test fun controllerPicksNightlyOnItsTabThenDownloadsItFromTheRow() {
val stable = ComponentsManager.CatalogItem("dxvk-3.1.1-linux.wcp", "dxvk", "Dxvk-Linux", "https://github.com/example/s", 100, "sha256:test")
val nightly = ComponentsManager.CatalogItem("DD-dxvk-3.1.1+153-nightly.wcp", "dxvk", ComponentsManager.DD_NIGHTLY, "https://github.com/example/n", 100, "sha256:test")
@@ -107,18 +137,28 @@ class ComponentDownloadsDrawerTest {
checking: Boolean = false,
onRefresh: () -> Unit = {},
onDownload: (ComponentsManager.CatalogItem) -> Unit = {},
twoColumns: State<Boolean>? = null,
captureHost: (MenuHost) -> Unit = {},
) {
compose.setContent {
inputMode = LocalInputModeManager.current
DroidDeckTheme {
Column(Modifier.verticalScroll(rememberScrollState())) {
ComponentDownloadsDrawerGroup(
host = rememberMenuHost(), catalog = catalog, catalogAt = 0,
checking = checking,
packages = listOf(ComponentsManager.Package(stored.file, "dxvk", "2.3", "", 100)),
downloads = downloads, onRefresh = onRefresh, onDownload = onDownload,
track = { Modifier.testTag(it) },
)
val host = rememberMenuHost()
captureHost(host)
val content: @androidx.compose.runtime.Composable () -> Unit = {
ComponentDownloadsDrawerGroup(
host = host, catalog = catalog, catalogAt = 0,
checking = checking,
packages = listOf(ComponentsManager.Package(stored.file, "dxvk", "2.3", "", 100)),
downloads = downloads, onRefresh = onRefresh, onDownload = onDownload,
track = { Modifier.testTag(it) },
)
}
if (twoColumns == null) content() else DrawerColumns(twoColumns.value) {
SettingsGroup("Profile") { Text("Profile settings") }
content()
}
}
}
}
@@ -0,0 +1,48 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.getUnclippedBoundsInRoot
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.unit.dp
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], qualifiers = "w800dp-h600dp")
class DrawerColumnsTest {
@get:Rule val compose = createRobolectricComposeRule()
@Test fun theComponentNoteStaysInItsGroupAndSixGroupsSplitEvenly() {
val note = "Component note"
val componentRow = "Component row"
compose.setContent {
DroidDeckTheme {
DrawerColumns(two = true) {
repeat(3) { index -> Box(Modifier.height(32.dp).testTag("left-$index")) }
DrawerComponentSettingsGroup(note) { Text(componentRow) }
repeat(2) { index -> Box(Modifier.height(32.dp).testTag("right-$index")) }
}
}
}
val left = (0..2).map { compose.onNodeWithTag("left-$it").getUnclippedBoundsInRoot() }
val right = (0..1).map { compose.onNodeWithTag("right-$it").getUnclippedBoundsInRoot() }
val group = compose.onNodeWithText(componentRow).getUnclippedBoundsInRoot()
val footer = compose.onNodeWithText(note).getUnclippedBoundsInRoot()
assertTrue(left.all { it.left == left.first().left })
assertTrue(right.all { it.left == right.first().left && it.left > left.first().left })
assertTrue(group.left >= right.first().left)
assertTrue(footer.left >= right.first().left)
assertTrue(footer.top >= group.bottom)
assertTrue(right.first().top >= footer.bottom)
assertTrue(left.zipWithNext().all { (first, next) -> first.bottom <= next.top })
}
}
@@ -0,0 +1,232 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.input.InputModeManager
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.SemanticsActions
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsFocused
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.assertTextEquals
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.click
import androidx.compose.ui.test.performTouchInput
import androidx.compose.ui.test.swipe
import androidx.compose.ui.test.performKeyInput
import androidx.compose.ui.test.performSemanticsAction
import androidx.compose.ui.test.pressKey
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNotSame
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
@OptIn(ExperimentalTestApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class)
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], qualifiers = "w360dp-h640dp-port", application = android.app.Application::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class SessionControlDesignTest {
@get:Rule val compose = createRobolectricComposeRule()
private val engineAnchor get() = compose.onNodeWithTag("setting-frame-generation-engine")
private fun engine(name: String) = compose.onNodeWithTag("framegen-engine:$name")
private fun zoom(name: String) = compose.onNodeWithTag("game-zoom-$name")
private fun zoomValue(value: Int) = zoom("value").assertTextEquals("$value%")
@Test
fun enginePickerStartsOnSelectionSkipsUnavailableEngineAndRestoresFocus() {
val mode = mutableStateOf(FrameGen.Mode(FrameGen.ENGINE_DDFG, 3))
lateinit var input: InputModeManager
compose.setContent {
DroidDeckTheme {
input = LocalInputModeManager.current
Box(Modifier.width(300.dp)) {
FrameGenMenu(mode.value, Lossless.State.NONE, { mode.value = it }, sessionHost = rememberMenuHost())
}
}
}
compose.runOnIdle { input.requestInputMode(InputMode.Keyboard) }
engineAnchor.performSemanticsAction(SemanticsActions.RequestFocus)
engineAnchor.assertIsFocused().performKeyInput { pressKey(Key.ButtonA) }
compose.mainClock.advanceTimeByFrame()
engine(FrameGen.ENGINE_LSFG).assertIsNotEnabled()
engine(FrameGen.ENGINE_DDFG).assertIsFocused().performKeyInput { pressKey(Key.DirectionUp) }
engine(FrameGen.ENGINE_OFF).assertIsFocused().performKeyInput { pressKey(Key.DirectionDown) }
engine(FrameGen.ENGINE_DDFG).assertIsFocused().performKeyInput { pressKey(Key.DirectionDown) }
engine(FrameGen.ENGINE_ZEROFG).assertIsFocused().performKeyInput { pressKey(Key.ButtonA) }
compose.mainClock.advanceTimeByFrame()
engine(FrameGen.ENGINE_ZEROFG).assertDoesNotExist()
assertEquals(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 3), mode.value)
engineAnchor.assertIsFocused().performKeyInput { pressKey(Key.ButtonA) }
compose.mainClock.advanceTimeByFrame()
engine(FrameGen.ENGINE_ZEROFG).assertIsFocused().performKeyInput { pressKey(Key.ButtonB) }
compose.mainClock.advanceTimeByFrame()
engine(FrameGen.ENGINE_ZEROFG).assertDoesNotExist()
assertEquals(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 3), mode.value)
engineAnchor.assertIsFocused()
}
@Test
fun gameOverrideCanReturnToGlobalWithoutLosingControllerFocus() {
val override = mutableStateOf(true)
lateinit var input: InputModeManager
compose.setContent {
DroidDeckTheme {
input = LocalInputModeManager.current
FrameGenMenu(
mode = if (override.value) FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 2) else FrameGen.Mode.OFF,
lossless = Lossless.State.NONE,
onPick = {},
gameProfileId = "8400",
hasGameOverride = override.value,
onResetGame = { override.value = false },
sessionHost = rememberMenuHost(),
)
}
}
compose.runOnIdle { input.requestInputMode(InputMode.Keyboard) }
val reset = compose.onNodeWithTag("framegen-use-global")
reset.assertTextEquals("Use global setting").performSemanticsAction(SemanticsActions.RequestFocus)
reset.assertIsFocused().performKeyInput { pressKey(Key.ButtonA) }
reset.assertDoesNotExist()
engineAnchor.assertIsFocused()
}
@Test
fun frameGenButtonsMoveTheDrawerFocusRing() {
lateinit var input: InputModeManager
lateinit var glide: FocusGlide
compose.setContent {
DroidDeckTheme {
FocusGlideHost {
input = LocalInputModeManager.current
glide = checkNotNull(LocalFocusGlide.current)
FrameGenMenu(
mode = FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 2),
lossless = Lossless.State.NONE,
onPick = {},
gameProfileId = "8400",
hasGameOverride = true,
sessionHost = rememberMenuHost(),
)
}
}
}
compose.runOnIdle { input.requestInputMode(InputMode.Keyboard) }
var previous: GlideSource? = null
for (label in listOf("2×", "3×", "4×", "ZeroPacer", "Use global setting")) {
val button = if (label == "ZeroPacer") compose.onNodeWithText(label, substring = true)
else compose.onNodeWithText(label)
button.performSemanticsAction(SemanticsActions.RequestFocus).assertIsFocused()
compose.runOnIdle {
assertNotNull("Missing focus ring for $label", glide.current)
assertNotSame("Focus ring did not move to $label", previous, glide.current)
previous = glide.current
}
}
}
@Test
fun legacyFrameGenerationStillUsesTheFlatOptions() {
compose.setContent {
DroidDeckTheme {
FrameGenMenu(FrameGen.Mode.OFF, Lossless.State.NONE, {}, legacyButtons = true)
}
}
engineAnchor.assertDoesNotExist()
compose.onNodeWithText("ZeroFG 2×").assertExists()
}
@Test
fun zoomStepsBy25PercentAndDpadCanLeaveIt() {
val value = mutableStateOf(1f)
val changes = mutableListOf<Float>()
lateinit var input: InputModeManager
compose.setContent {
DroidDeckTheme {
input = LocalInputModeManager.current
Column(Modifier.width(300.dp)) {
OutlinedButton(onClick = {}, modifier = Modifier.fillMaxWidth().testTag("above")) { Text("Above") }
GameZoomRow(value.value, { Modifier }) { changes += it; value.value = it }
OutlinedButton(onClick = {}, modifier = Modifier.fillMaxWidth().testTag("below")) { Text("Below") }
}
}
}
compose.runOnIdle { input.requestInputMode(InputMode.Keyboard) }
val slider = zoom("slider")
zoomValue(100)
zoom("reset").assertDoesNotExist()
slider.performSemanticsAction(SemanticsActions.RequestFocus)
slider.assertIsFocused().performKeyInput { pressKey(Key.DirectionLeft) }
zoomValue(100)
assertEquals(emptyList<Float>(), changes)
slider.assertIsFocused().performKeyInput { pressKey(Key.DirectionUp) }
compose.onNodeWithTag("above").assertIsFocused().performKeyInput { pressKey(Key.DirectionDown) }
slider.assertIsFocused().performKeyInput { pressKey(Key.DirectionDown) }
compose.onNodeWithTag("below").assertIsFocused().performKeyInput { pressKey(Key.DirectionUp) }
slider.assertIsFocused()
for (percent in 125..300 step 25) {
slider.performKeyInput { pressKey(Key.DirectionRight) }
zoomValue(percent)
slider.assertIsFocused()
}
slider.performKeyInput { pressKey(Key.DirectionRight) }
zoomValue(300)
assertEquals((125..300 step 25).map { it / 100f }, changes)
slider.performKeyInput { pressKey(Key.DirectionLeft) }
zoomValue(275)
zoom("reset").assertDoesNotExist()
slider.performKeyInput { pressKey(Key.DirectionDown) }
compose.onNodeWithTag("below").assertIsFocused().performKeyInput { pressKey(Key.DirectionUp) }
slider.assertIsFocused()
for (percent in 250 downTo 100 step 25) {
slider.performKeyInput { pressKey(Key.DirectionLeft) }
zoomValue(percent)
}
}
@Test
fun touchTapAndDragSnapToTheNineValues() {
val value = mutableStateOf(1f)
val changes = mutableListOf<Float>()
compose.setContent {
DroidDeckTheme {
Box(Modifier.width(300.dp)) {
GameZoomRow(value.value, { Modifier }) { changes += it; value.value = it }
}
}
}
val slider = zoom("slider").assertIsDisplayed()
slider.performTouchInput { click(center) }
zoomValue(200)
slider.performTouchInput { swipe(center, Offset(width - 2f, center.y)) }
zoomValue(300)
slider.performTouchInput { click(Offset(2f, center.y)) }
zoomValue(100)
val allowed = (100..300 step 25).map { it / 100f }.toSet()
assertEquals(true, changes.all { it in allowed })
}
}
+8
View File
@@ -289,6 +289,14 @@ vfork-safe (Python's subprocess execs under `vfork`). Details that mattered:
Default list: the portals, at-spi, `python3`, PipeWire, WirePlumber, Decky's PluginLoader, the log's
`gnudd`, `xprop -spy`, the web helper's renderers, `wine`, `wine-preloader`, `wineserver`.
Wine's loader is handed off only for Wine's own programs, those whose command line starts with
`C:\windows\` (its services, `explorer.exe`, Proton's `steam.exe`). A game, its launcher and its
tools stay children of the Wine process that started them and are counted. Android samples a
worker's RSS as an app process's own, and ZTE's ROM (`DefendManagerService`, on Nubia and
Red Magic devices) SIGKILLs a non-system app's process whose last two samples, five minutes apart, are
past a size set by the device's RAM (3.2 GB at 16 GB) while the app shows no window, foreground
service or not. A game in a worker died that way six minutes after the screen went off.
Measured on the Thor, same session and game as above:
| | counted children, idle | counted, Bully (Proton) running |
+10 -3
View File
@@ -44,8 +44,10 @@ from what tripped agents up on real devices.
running makes Steam show "Game already running" and `launch` time out.
- Session scripts are APK assets, copied into the rootfs at every session start over any local
edit. A Lab build (`dd-lab-build`, see `docs/lab-builds.md`) carries app code and resources only:
session scripts, native code and assets need a new APK, such as the pull request's CI test build
(DroidDeck > Updates > Test builds).
session scripts, native code, assets and `AndroidManifest.xml` need a new APK, such as the pull
request's CI test build (DroidDeck > Updates > Test builds). `dd-lab-build` refuses changes to the
manifest, native code, Gradle files and a few startup classes, but builds session script and asset
changes without them. To try the rest of a branch, build a copy without those changes.
## Changing DroidDeck
@@ -56,7 +58,12 @@ The source is checked out at `/root/DroidDeck` once the Agent tab's build tools
- `dd-lab-build` builds the checkout as a Lab build and restarts DroidDeck on it. DroidDeck runs the
build in a process of its own and shows its progress; `dd-lab-build` follows its log. Run it in
the background and keep checking, so the user can talk to you meanwhile. The restart ends your
process, and the conversation continues on the new build.
process; DroidDeck starts you again on the new build, in the same conversation, so tell the user
what you will check then instead of asking them to message you.
- To try a change, commit it and go straight to `dd-lab-build`: it compiles the app, so a Gradle
compile first only adds time. It refuses changes since the installed build (`apkCommit` in
`droiddeckctl state`) that need a new APK. For a branch from a newer `origin/main`, cherry-pick
its commits onto a branch from `apkCommit` and build that.
- Python tests run from the repository root: `python3 -m unittest tools.tests.test_x`. Some fail on
the device on `origin/main` too; run them on a worktree of `origin/main` before blaming a change.
- Gradle runs on the device once the build tools are set up, but slowly: run the test classes that cover
+31
View File
@@ -1132,9 +1132,37 @@ static int ddh_all_utf8(char *const v[]) {
return 1;
}
// A Wine loader starting a Windows program from outside C:\windows: a game, its launcher or its tools,
// as opposed to Wine's own services and Proton's steam.exe. Wine execs its loader with the program's
// command line after the loader paths (dlls/ntdll/unix/process.c), so the first argument that is not an
// absolute Linux path names the program. Such a program stays a child of the Wine process that started
// it: Android samples an app process's RSS on its own, and some ROMs kill a background app process past
// a fixed size whatever its importance (ZTE's DefendManagerService: 3.2 GB on a 16 GB device, checked
// every 5 minutes), while a child's memory is in no app process's sample.
static int ddh_windows_program_outside_wine(const char *filename, char *const argv[]) {
static const char *const loaders[] = {"wine", "wine64", "wine-preloader", "wine64-preloader"};
static const char windir[] = "c:\\windows\\";
const char *prog = ddh_base(filename);
size_t k = 0;
while (k < sizeof(loaders) / sizeof(loaders[0]) && (!prog || strcmp(prog, loaders[k]) != 0)) k++;
if (k == sizeof(loaders) / sizeof(loaders[0])) return 0;
for (int i = 1; argv && argv[i]; i++) {
const char *arg = argv[i];
if (arg[0] == '/') continue;
for (size_t j = 0; j < sizeof(windir) - 1; j++) {
char c = arg[j] >= 'A' && arg[j] <= 'Z' ? (char)(arg[j] - 'A' + 'a') : arg[j] == '/' ? '\\' : arg[j];
if (c != windir[j]) return 1;
}
return 0;
}
return 0;
}
static int ddh_program_listed(const char *list, const char *filename, char *const argv[]) {
char shebang[256];
const char *interp;
if (ddh_windows_program_outside_wine(filename, argv) || ddh_windows_program_outside_wine(argv ? argv[0] : NULL, argv))
return 0;
// "python3 SCRIPT" and "sh SCRIPT" are matched by the script's name too (and only an
// interpreter's: "pidof wineserver" is not wineserver)
const char *prog = ddh_base(filename);
@@ -1248,6 +1276,8 @@ static int ddh_waiter(pid_t pid) {
// (droiddeck-seed-redists alone about 17 within a second), and each would be an app process of its own,
// a zygote fork and a bind, for a few milliseconds of work while the game starts. Counted for those
// milliseconds instead. Only tools that end on their own: not tail (-f), tee, sleep, timeout or env.
//
// Nor a Windows program from outside C:\windows (ddh_windows_program_outside_wine).
static int ddh_pressure_keeps(const char *filename, char *const argv[]) {
static const char *const kept[] = {"steam", "steam.sh", "steamwebhelper", "droiddeck-steam-x64", "reaper",
"steam-launch-wrapper", "pw-audio-namespace", "gamescope", "gamescopereaper"};
@@ -1255,6 +1285,7 @@ static int ddh_pressure_keeps(const char *filename, char *const argv[]) {
"gawk", "grep", "head", "id", "jq", "ls", "mawk", "mkdir", "mktemp", "pgrep",
"pidof", "printf", "ps", "readlink", "realpath", "rm", "sed", "seq", "sort",
"stat", "touch", "tr", "uname", "uniq", "wc", "xprop"};
if (ddh_windows_program_outside_wine(filename, argv)) return 1;
if (filename) {
for (size_t k = 0; k < sizeof(quick) / sizeof(quick[0]); k++) {
if (strcmp(ddh_base(filename), quick[k]) == 0) return 1;
+9 -1
View File
@@ -235,8 +235,16 @@ static int sandbox_only_limit(int resource, const struct rlimit *rlim) {
return 0;
}
// The kernel checks RLIMIT_RTTIME on a thread that is realtime or has a CPU-time timer armed, and a
// limit of 0 is reached at once: SIGXCPU at the soft limit, SIGKILL at the hard one. SDL sets the
// RTTimeUSecMax it reads from org.freedesktop.portal.Realtime before it asks for a realtime thread,
// and xdg-desktop-portal reports 0 when it reaches no RealtimeKit, as in a session with no system bus.
static int fatal_limit(int resource, const struct rlimit *rlim) {
return rlim && resource == RLIMIT_RTTIME && rlim->rlim_cur == 0;
}
int setrlimit(__rlimit_resource_t resource, const struct rlimit *rlim) {
if (sandbox_only_limit((int)resource, rlim)) return 0;
if (sandbox_only_limit((int)resource, rlim) || fatal_limit((int)resource, rlim)) return 0;
static int (*orig_setrlimit)(__rlimit_resource_t, const struct rlimit *) = NULL;
#if defined(__USE_FILE_OFFSET64) && !defined(__LP64__)
// With 64-bit file offsets on a 32-bit system this function is setrlimit64
@@ -0,0 +1,38 @@
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[2]
NATIVE = ROOT / "app/src/main/cpp/waylandcomp/src"
APP = ROOT / "app/src/main/java/com/droiddeck/launcher"
class BottomMirrorCompositionTest(unittest.TestCase):
def test_mirror_requests_composition_until_its_last_consumer_leaves(self):
panel = (APP / "ui/BottomMirrorPage.kt").read_text()
self.assertIn("actions.holdComposed(true)", panel)
self.assertIn("onDispose { actions.holdComposed(false) }", panel)
activity = (APP / "SessionActivity.kt").read_text()
hold = activity.split("private fun holdComposedOutput(", 1)[1].split("private fun zeroCopyActive", 1)[0]
self.assertIn("if (held == wasHeld) return", hold)
self.assertIn("nativeSetMirrorCapture(held)", hold)
self.assertIn("if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy", hold)
self.assertIn("CompositorHost.isStarted && !SessionState.hdr && SessionPrefs.zeroCopy", activity)
self.assertIn("nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode) && composedOutputFree())", activity)
self.assertIn("nativeSetZeroCopy(composedOutputFree())", hold)
self.assertNotIn("SessionPrefs.set", hold)
def test_compositor_selects_readable_surface_without_dropping_unimportable_hdr(self):
jni = (NATIVE / "waylandcomp_jni.c").read_text()
self.assertIn("droiddeck_host_mirror_capture(on ? 1 : 0);", jni)
host = (NATIVE / "droiddeck_ext.c").read_text()
self.assertIn("case HOST_MIRROR_CAPTURE:\n droiddeck_set_mirror_capture(m->a);", host)
compositor = (NATIVE / "compositor.c").read_text()
self.assertIn("if (g_mirror_capture && hdr_route != 3 && hs.n_hdr > 0) {\n hdr_route = 2;", compositor)
self.assertIn("g_zero_copy && !g_mirror_capture && (!framegen || fg_layer)", compositor)
self.assertIn("if (un && g_zero_copy)", compositor)
self.assertIn("if (g_zero_copy && droiddeck_color_hdr_open()) note_hdr_unimported", compositor)
self.assertNotIn("if (g_mirror_capture) ls = NULL", compositor)
if __name__ == "__main__":
unittest.main()
+7
View File
@@ -33,6 +33,13 @@ class CiChecksTest(unittest.TestCase):
robolectric = [cache['path'] for cache in caches if cache['key'].startswith('robolectric-')]
self.assertEqual(robolectric, ['${{ steps.robolectric-jars.outputs.path }}'] * 2)
def test_only_main_saves_the_robolectric_cache(self):
steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']
saves = [step for step in steps if step.get('uses', '').startswith('actions/cache/save')
and step['with']['key'].startswith('robolectric-')]
self.assertEqual(len(saves), 1)
self.assertIn("github.event_name != 'pull_request'", saves[0]['if'])
def test_unit_test_retry_requires_maven_exception(self):
steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']
run = next(step['run'] for step in steps if step.get('id') == 'unit-tests')
+69
View File
@@ -0,0 +1,69 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from tools.tests.test_vk_pending_completion import function
class FramegenHangBreakerTest(unittest.TestCase):
def run_c(self, body):
compiler = shutil.which(os.environ.get('CC', 'cc'))
if not compiler:
self.skipTest('A host C compiler is required')
root = Path(__file__).resolve().parents[2]
source = (root / 'app/src/main/cpp/waylandcomp/src/framegen_bridge.c').read_text()
code = '#include <assert.h>\n#include <stdatomic.h>\n#include <stdint.h>\n'
code += '#define FG_PROVEN_FRAMES 120\n#define FG_HANG_STRIKES 2\n'
code += 'static _Atomic int g_hang_strikes, g_dev_lost;\n'
code += 'static int g_submitted_since_ready;\nstatic uint64_t g_total_generated, g_generated_at_ready;\n'
code += function(source, 'framegen_loss_strike')
code += function(source, 'framegen_count_loss')
code += 'int main(void) {\n' + body + '\n}\n'
with tempfile.TemporaryDirectory() as tmp:
folder = Path(tmp)
probe = folder / 'breaker.c'
binary = folder / 'breaker'
probe.write_text(code)
subprocess.run([compiler, '-std=c11', str(probe), '-o', str(binary)], check=True,
capture_output=True, text=True)
subprocess.run([str(binary)], check=True, capture_output=True, timeout=10)
def test_losses_before_any_generated_frame_completes_switch_generation_off(self):
self.run_c('''
assert(framegen_loss_strike(1, 0) == 0);
assert(framegen_loss_strike(1, 0) == 1);
assert(framegen_loss_strike(1, 0) == 0);
''')
def test_a_loss_after_generation_worked_keeps_it_armed(self):
self.run_c('''
assert(framegen_loss_strike(1, 0) == 0);
assert(framegen_loss_strike(1, 500) == 0);
assert(framegen_loss_strike(1, 0) == 0);
''')
def test_a_loss_without_generation_work_is_not_a_strike(self):
self.run_c('''
assert(framegen_loss_strike(1, 0) == 0);
assert(framegen_loss_strike(0, 0) == 0);
assert(framegen_loss_strike(1, 0) == 0);
''')
def test_a_loss_reported_twice_counts_once(self):
self.run_c('''
for (int loss = 0; loss < 2; loss++) {
g_dev_lost = 0;
g_submitted_since_ready = 1;
int first = framegen_count_loss();
int again = framegen_count_loss();
assert(again == 0);
assert(first == (loss == 1));
}
''')
if __name__ == '__main__':
unittest.main()
+34
View File
@@ -952,6 +952,11 @@ int main(int argc, char **argv) {
execv("/bin/target", args);
_exit(127);
}
if (strcmp(argv[1], "wine") == 0) {
// as Wine starts a Windows program: its loader's path, then the program's command line
execl("/bin/wine", "wine", "/opt/wine/bin/wine", argv[3], argv[2], (char *)NULL);
_exit(127);
}
execl(argc > 3 ? argv[3] : "/bin/target", "target", argv[2], (char *)NULL);
_exit(127);
}
@@ -1582,6 +1587,9 @@ class NativeHookHandoffTest(unittest.TestCase):
def run_parent(self, *argv, handoff="target", hook=True, reports=True, pressure=None, as_shell=False, terminal=False,
delay=0, extra_env=None, parent_name=None):
name = "dd-handoff-test-%d-%s-%s-%d" % (os.getpid(), self.id().rsplit(".", 1)[-1], handoff, hook)
self.runs = getattr(self, "runs", 0) + 1 # subtests run the fixture again under the same test id
if self.runs > 1:
name += "-%d" % self.runs
spawner = FakeSpawner(name, self.prefix or [], self.root, reports, delay)
spawner.start()
self.addCleanup(spawner.sock.close)
@@ -1902,6 +1910,32 @@ class NativeHookHandoffTest(unittest.TestCase):
self.assertEqual("1", result.get("same"), out.stdout)
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
def run_wine(self, command_line, **kwargs):
wine = self.root / "bin/wine"
if not wine.exists():
shutil.copy(self.root / "bin/target", wine)
return self.run_parent("wine", "7", command_line, handoff="wine", **kwargs)
def test_wines_own_program_is_handed_off(self):
for command_line in ("C:\\windows\\system32\\services.exe", "c:\\windows\\system32\\steam.exe"):
with self.subTest(command_line):
result, requests, out = self.run_wine(command_line)
self.assertEqual(1, len(requests), out.stderr)
self.assertEqual(["wine", "/opt/wine/bin/wine", command_line, "7"], requests[0]["argv"])
def test_a_game_under_wine_is_not_handed_off(self):
# a game: Android would sample its memory as an app process's own
for command_line in ("LikeADragonPirates.exe", "S:\\steamapps\\common\\Game\\startup.exe",
".\\crashreport\\crashpad_handler.exe", "C:\\windowsapps\\game.exe"):
with self.subTest(command_line):
result, requests, out = self.run_wine(command_line)
self.assertEqual([], requests, out.stderr)
self.assertEqual("1", result.get("same"), out.stdout)
def test_near_the_limit_a_game_under_wine_is_not_handed_off(self):
result, requests, out = self.run_wine("LikeADragonPirates.exe", pressure=0, as_shell=True)
self.assertEqual([], requests, out.stderr)
def test_a_wait_of_another_thread_with_wnothread_does_not_take_the_program(self):
result, requests, out = self.run_parent("nothread", "7")
self.assertEqual(1, len(requests), out.stderr)
@@ -0,0 +1,81 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
PROBE = r"""
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
static void show(const char *name, int ret) {
struct rlimit now;
if (getrlimit(RLIMIT_RTTIME, &now) != 0) exit(2);
printf("%s\t%d\t%lld\t%lld\n", name, ret, (long long)now.rlim_cur, (long long)now.rlim_max);
}
int main(void) {
struct rlimit zero = {0, 0}, soft_zero = {0, 200000}, usable = {100000, 200000};
show("start", 0);
show("zero", setrlimit(RLIMIT_RTTIME, &zero));
show("soft_zero", setrlimit(RLIMIT_RTTIME, &soft_zero));
show("usable", setrlimit(RLIMIT_RTTIME, &usable));
return 0;
}
"""
class NativeHookRttimeLimitTest(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)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
cls.root.mkdir()
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def limits(self):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
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.probe)], env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(0, out.returncode, out.stdout + out.stderr)
return {name: (int(ret), int(cur), int(hard))
for name, ret, cur, hard in (line.split("\t") for line in out.stdout.splitlines())}
def test_a_realtime_limit_of_zero_is_reported_set_and_not_applied(self):
limits = self.limits()
self.assertEqual(0, limits["zero"][0])
self.assertEqual(limits["start"][1:], limits["zero"][1:])
def test_a_soft_realtime_limit_of_zero_is_not_applied(self):
limits = self.limits()
self.assertEqual(0, limits["soft_zero"][0])
self.assertEqual(limits["start"][1:], limits["soft_zero"][1:])
def test_a_usable_realtime_limit_is_applied(self):
self.assertEqual((0, 100000, 200000), self.limits()["usable"])
if __name__ == "__main__":
unittest.main()
+8
View File
@@ -78,6 +78,7 @@ static int g_loop_stub;
static int g_fallback_accept;
static int g_fallback_token;
static int g_hdr_count;
static int g_mirror_count, g_mirror_capture;
int text_input_host_commit(const char *u, size_t n)
{
@@ -143,6 +144,7 @@ void toplevel_icon_init(struct wl_display *d) { (void)d; }
void single_pixel_init(struct wl_display *d) { (void)d; }
void ahb_swapchain_set_mode(int a, int b) { (void)a; (void)b; }
void droiddeck_color_set_output(int a) { (void)a; g_hdr_count++; }
void droiddeck_set_mirror_capture(int on) { g_mirror_capture = on; g_mirror_count++; }
struct wl_display *droiddeck_get_display(void) { return (struct wl_display *)&g_display_stub; }
void wl_display_flush_clients(struct wl_display *d) { (void)d; }
@@ -216,7 +218,10 @@ int main(void)
droiddeck_host_key(29, 0);
droiddeck_host_text_commit("later", 5);
droiddeck_host_hdr_output(1);
droiddeck_host_mirror_capture(1);
CHECK(g_mirror_count == 0);
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
CHECK(g_mirror_count == 1 && g_mirror_capture == 1);
CHECK(g_n == saved);
CHECK(g_hdr_count == 1);
CHECK(g_fallback_token > 0);
@@ -259,7 +264,10 @@ int main(void)
droiddeck_host_key(32, 1);
droiddeck_host_key(32, 0);
droiddeck_host_hdr_output(0);
droiddeck_host_mirror_capture(0);
CHECK(g_mirror_count == 1);
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
CHECK(g_mirror_count == 2 && g_mirror_capture == 0);
CHECK(g_n == saved + 1);
CHECK(g_hdr_count == 2);
CHECK(g_fallback_token > 0);