Compare commits

..
Author SHA1 Message Date
maxjivi05 d0ac30c6a8 Merge main into feat/desktop-pacman 2026-10-30 15:26:05 -04:00
Kurt Himebauch a5b035b247 test: the required-status gate expects the skip-on-superseded condition (#1866) 2026-10-30 15:25:28 -04:00
MaxsTechReview a8cebd024b fix(ci): required-check test matches the gate's !cancelled() condition (#1864)
fix(ci): the required-check test expects the gate's !cancelled() condition
2026-10-30 15:20:30 -04:00
maxjivi05 83efbe3987 Set the scroll midpoint as soon as a finger lands or lifts so the next move still scrolls 2026-10-30 15:05:03 -04:00
MaxsTechReview 7c49eef79f fix(dual-screen): keep the bottom-screen controls up while a game loads (#1840)
* fix(dual-screen): keep the bottom-screen controls up while a game loads

The session opened its bottom-screen trackpad only at the game's first frame. The launcher's bottom menu closes when a game starts, so on dual-screen handhelds the bottom screen showed whatever Android app was behind it for the whole load, which is long for Xbox games while Xodus prepares them. The controls now open when the session starts. Devices without a built-in second screen, and players who turned the in-game controls off, are unchanged.

* fix(dual-screen): pick the bottom-screen panel again once the session's controller is known

Opening the bottom-screen controls at session start can run before SessionService has prepared the Steam Deck pad, while SessionState.deckPad is still false, so the trackpad could be chosen where the Deck controls belong. That early choice is now provisional: at the game's first frame it switches to the panel the remembered choice and the real deckPad give, unless the player has already picked one.

* fix(dual-screen): keep the loading-time panel choice through PiP, background and new sessions

* fix(dual-screen): retry a terminal panel opened before it was ready and keep a manual close made during loading
2026-10-30 14:32:34 -04:00
Kurt Himebauch c8c5e22a34 fix: new Steam installs start with shader pre-caching off (#1861) 2026-10-30 14:17:45 -04:00
Kurt Himebauch fa4a54f64a Default game library to vertical covers (#1857) 2026-10-30 14:09:44 -04:00
maxjivi05 10618b0f60 Keep a scroll steady when a finger lands again, keep the clipboard echo for repeat callbacks, and never follow a linked pacman sync folder 2026-10-30 14:04:06 -04:00
maxjivi05 801e434345 Merge main into feat/desktop-pacman 2026-10-30 14:02:17 -04:00
MaxsTechReview 83980035c6 fix(desktop): video wallpapers no longer race ahead after DroidDeck returns from the background (#1833)
* fix(desktop): video wallpapers no longer race ahead after DroidDeck returns from the background

* test: give the vrclient loader harness the clock syscall hook
2026-10-30 13:58:49 -04:00
MaxsTechReview 8f7cdb7106 fix: Battle.net scales its windows to large desktops instead of opening tiny on high-resolution screens (#1832) 2026-10-30 13:58:44 -04:00
MaxsTechReview 9a1334b73b fix: on dual-screen handhelds DroidDeck no longer jumps back over apps opened from outside it (#1828)
fix: the bottom-screen panel no longer pulls DroidDeck back over an app opened on the main screen from outside DroidDeck

On dual-screen handhelds the panel took focus and moved DroidDeck's task forward whenever another app opened over it on the main screen, unless DroidDeck had opened that app itself. A frontend such as iisu, or Settings opened from a shortcut, was covered again within a fraction of a second. The panel now stops reclaiming once the launcher is paused, and starts again when it resumes.
2026-10-30 13:58:40 -04:00
MaxsTechReview ab949a4a5a fix(runtime): the x86-64 Steam client starts again on the Ubuntu runtime (liblzo2-2 for FEX) (#1825)
* fix(runtime): ship liblzo2-2 so the x86-64 Steam client can install FEX

FEX's unsquashfs links liblzo2. The Ubuntu runtime did not ship it, so the FEX check failed on every build, the x86-64 client was never set up, and the session went straight back to the home screen. Only phones with the desktop installed had it.

* fix: the x86-64 Steam client starts again after it updates itself under FEX

On its first start the x86-64 client downloads a 500 MB update and, under FEX, ends on an illegal instruction (rc=132) instead of asking for a restart with rc=42, so the session ended there. The client is started again once.
2026-10-30 13:58:35 -04:00
MaxsTechReview b91e8fdeab fix: a session in picture-in-picture draws at 30 fps instead of the full refresh (#1842)
* fix: a session in picture-in-picture draws at 30 fps instead of the full refresh

Since auto picture-in-picture became the default (#1727), pressing Home leaves the session running in a small window that takes no input. A game kept drawing at its full rate there: on a REDMAGIC Astra 2 Among Us in picture-in-picture drew 3.31 W, the same as playing it and about 1.05 W more than a suspended session. While in picture-in-picture the compositor now paces the session at 30 fps (or a lower limit already set). Mirroring to glasses keeps the glasses rate, and the display mode request ignores the picture-in-picture limit so the app in front is not slowed.

* fix: keep the no-argument output limit the glasses pacing tests read

* fix: hold scene renders to the output limit and keep frame generation off in picture-in-picture

A frame limit only paced dmabuf buffer releases, so a shared-memory client was still drawn on every vsync with its frame callbacks sent at the panel's rate. The vsync tick now waits until the limit's interval, less half a refresh, has passed since the last scene. Frame generation is disarmed while picture-in-picture is shown and armed again when it ends; frame generation requests are applied in order.

* Give the commit render harness the frame limit hold

* Hold scene renders to a frame limit deadline, also on the fallback timer, and keep frame generation for glasses mirroring in picture in picture
2026-10-30 13:29:10 -04:00
MaxsTechReview 021e7153fa fix: Automatic dual screen needs a real second touch panel (Odin keeps its side rail) (#1801)
* fix: AYN Odin handhelds are single-screen in automatic dual-screen mode

* Use a second screen only when more than one physical screen is lit, instead of excluding AYN models

* fix: open the session panel when the second screen turns on, and keep the On mode's display choice

* fix: let the session panel open again after its screen goes away and returns

* fix: Automatic dual screen needs a touchscreen for the second panel instead of counting lit displays

* fix: check the second screen again when a touchscreen comes back after the display

* fix: check the second screen again when a touchscreen is added or removed, and on resume

* Keep the second screen panel closed once the session has ended
2026-10-30 13:19:21 -04:00
Kurt Himebauch 524292f457 fix: drop the runtime installs on first Play chip from the Steam home (#1854) 2026-10-30 13:04:16 -04:00
Kurt Himebauch 92c1560f63 feat: Steam's sleep-after timers start every session as Disabled (#1848) 2026-10-30 12:13:12 -04:00
MaxsTechReview 41615d2460 fix: Steam's UI runs at the panel's full refresh rate again (#1841)
#1809 held Steam's own UI to an even share of the refresh near 60 fps whenever it had focus. On 120 Hz and faster screens Big Picture then felt locked at 60 while games ran at the full rate, and players reported it as a regression. The compositor now releases Steam UI buffers unpaced again, like a game's. The larger swapchain stays limited to games, so the client UI still uses gamescope's default image count.
2026-10-30 11:10:03 -04:00
maxjivi05 fc8dad5944 Install desktop-kde-r3 2026-10-27 15:17:15 -04:00
maxjivi05 cf86daa154 Scroll two-finger swipes at touchpad speed 2026-10-27 15:17:15 -04:00
maxjivi05 541e2230df Fix the KDE 6.8 desktop on device and make touch scrolling feel like a touchpad
- KWin presents one composited buffer (no overlay layers), so the wallpaper and icons show
- KWin runs without Gallium's threaded context, which crashed it on window uploads
- KWin forwards the host's scroll source, wheel steps and scroll stops (patch 0003)
- Two-finger scrolling sends touchpad scrolling at finger speed and moves the pointer under the fingers
- The first finger is held back briefly so a two-finger gesture never starts a touch in the app
- pacman takes over files other DroidDeck software already installed and won't remove those packages
2026-10-27 15:17:15 -04:00
maxjivi05 2f71916019 Two-finger hold right-clicks and two-finger slide scrolls on the desktop
A two-finger tap or a still two-finger hold right-clicks where the first
finger landed; two fingers sliding together scroll like a mouse wheel,
while a pinch still reaches the app as touch so zooming works.

pacman's backup records take md5 from the package files, since Arch
Linux ARM's .MTREE only carries sha256 now. removal-manifests.py gains
--add to append a new desktop version without regenerating the older
inventories, and covers the overlay's symlinks and pacman files.
2026-10-27 15:17:15 -04:00
maxjivi05 49201e1afa Make the desktop a proper Arch desktop: pacman, sudo, utilities and touch right-click
The KDE desktop package now records every package it ships in pacman's
database and carries a pinned droiddeck repository built from the same
Arch Linux ARM snapshot, so pacman installs software that matches the
desktop's Qt and KDE versions and never upgrades what DroidDeck ships.
sudo, su and sudoedit run commands as root through a small preload, and
pacman hooks refuse to remove or replace DroidDeck's own packages and
remember user installs so they come back after runtime updates.

Adds zip, 7zip, unrar, less, man pages, htop, git, wget, wl-clipboard,
xclip, KCalc, Okular, Filelight, KFind, System Monitor, Elisa and
Discover, pins Kate to the panel, and hides technical menu entries.
Updates KWin to 6.8.1 to match the repository.

A two-finger tap now right-clicks on the desktop, and the Android
clipboard is only pushed into the session when it changed, so files
copied in Dolphin stay pasteable after leaving the app.
2026-10-27 15:17:15 -04:00
75 changed files with 1125 additions and 209 deletions

No files matched your search

+1 -1
View File
@@ -760,7 +760,7 @@ jobs:
checks:
name: Compile and test APK
needs: [build, python-tests]
if: ${{ always() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }}
if: ${{ !cancelled() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }}
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
+1 -1
View File
@@ -69,7 +69,7 @@ Compatibility and performance vary by device; hardware validation is limited. De
## Credits and licence
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. Battle.net support is [@kayakyakr](https://github.com/kayakyakr)'s: it runs Blizzard's own Battle.net client, downloaded from Blizzard and not included, in Proton, and shows the key art from each game's [Battle.net Shop](https://shop.battle.net) page; without the Steam client its games see DroidDeck's pad as an Xbox 360 controller through `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. Its games install from Stores through Blizzard's own Agent and the local HTTP API it serves, driven the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) drives it, with the requests described on [wowdev.wiki](https://wowdev.wiki/Agent); how other launchers find, install and start Blizzard games was read in [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader, without taking their code. The registry entries a GOG game's install script (`goggame-<id>.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. x86 AppImages packed with [sharun](https://github.com/VHSgunzo/sharun) by VHSgunzo (MIT) start because DroidDeck's own [FEX](https://github.com/FEX-Emu/FEX) build (MIT) puts the platform name under `AT_PLATFORM`, which sharun's [userland-execve](https://crates.io/crates/userland-execve) loader (MIT) requires; FEX filed it under `AT_BASE_PLATFORM`. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. The in-game performance HUD is [@The412Banner](https://github.com/The412Banner)'s [FusionHUD](https://github.com/The412Banner/FusionHUD) (GPL-3.0 with an attribution term), Bannerlator's HUD; its frame rate, frame times and readings are taken from the same sources, and worked out the same way, as Valve's [MangoHud](https://github.com/flightlessmango/MangoHud) build (MIT) that runs Steam's performance overlay in a DroidDeck session, with the frame times shared by gamescope patch 0125; when gamescope sends no frames for two seconds, the HUD counts the frames DroidDeck's compositor shows instead, which stop at the screen's refresh rate. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<pid>/mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and isLine truncated
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. Battle.net support is [@kayakyakr](https://github.com/kayakyakr)'s: it runs Blizzard's own Battle.net client, downloaded from Blizzard and not included, in Proton, and shows the key art from each game's [Battle.net Shop](https://shop.battle.net) page; without the Steam client its games see DroidDeck's pad as an Xbox 360 controller through `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. Its games install from Stores through Blizzard's own Agent and the local HTTP API it serves, driven the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) drives it, with the requests described on [wowdev.wiki](https://wowdev.wiki/Agent); how other launchers find, install and start Blizzard games was read in [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader, without taking their code. The registry entries a GOG game's install script (`goggame-<id>.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. x86 AppImages packed with [sharun](https://github.com/VHSgunzo/sharun) by VHSgunzo (MIT) start because DroidDeck's own [FEX](https://github.com/FEX-Emu/FEX) build (MIT) puts the platform name under `AT_PLATFORM`, which sharun's [userland-execve](https://crates.io/crates/userland-execve) loader (MIT) requires; FEX filed it under `AT_BASE_PLATFORM`. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. The in-game performance HUD is [@The412Banner](https://github.com/The412Banner)'s [FusionHUD](https://github.com/The412Banner/FusionHUD) (GPL-3.0 with an attribution term), Bannerlator's HUD; its frame rate, frame times and readings are taken from the same sources, and worked out the same way, as Valve's [MangoHud](https://github.com/flightlessmango/MangoHud) build (MIT) that runs Steam's performance overlay in a DroidDeck session, with the frame times shared by gamescope patch 0125; when gamescope sends no frames for two seconds, the HUD counts the frames DroidDeck's compositor shows instead, which stop at the screen's refresh rate. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<pid>/mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and isLine truncated
XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). Rokid support follows the Rokid protocol notes in [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) and @badicsalex's [Void Computing write-ups](https://voidcomputing.hu/blog/worse-better-prettier/), and [Monado](https://gitlab.freedesktop.org/monado/monado)'s Rokid driver. The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL, Rokid and REDMAGIC are trademarks of their owners; this project is not affiliated with them.
+20 -74
View File
@@ -207,7 +207,6 @@ struct surface {
struct wl_resource *dmabuf;
struct dmabuf_buffer *dmabuf_buf;
struct wl_listener dmabuf_destroy;
int dmabuf_unsynced;
const void *last_dmabuf;
int buf_w, buf_h, has_content;
int buf_alpha;
@@ -283,41 +282,6 @@ static void pace_note_buffer(const void *buffer) {
if (g_pace.distinct < PACE_BUFFERS) g_pace.buffers[g_pace.distinct] = buffer;
g_pace.distinct++;
}
#define ORDER_BUFFERS 8
#define ORDER_RING 24
static struct {
const void *buffers[ORDER_BUFFERS];
unsigned known;
int last;
unsigned commits, in_cycle, breaks, same_again;
char ring[ORDER_RING + 1];
unsigned ring_n;
unsigned poll_ready, poll_busy, poll_timeout;
int64_t poll_wait_ns, poll_wait_max_ns;
} g_ord = { .last = -1 };
/* Records which of the client's buffers each commit carries, so a log shows whether commits arrive in
the swapchain's cyclic order or the order itself breaks before the compositor samples anything. */
static void order_note_commit(const void *buffer) {
int idx = -1;
for (unsigned i = 0; i < g_ord.known; i++)
if (g_ord.buffers[i] == buffer) { idx = (int)i; break; }
if (idx < 0) {
if (g_ord.known >= ORDER_BUFFERS) return;
idx = (int)g_ord.known;
g_ord.buffers[g_ord.known++] = buffer;
}
g_ord.commits++;
if (idx == g_ord.last) g_ord.same_again++;
else if (g_ord.known >= 3 && g_ord.last >= 0) {
if (idx == (g_ord.last + 1) % (int)g_ord.known) g_ord.in_cycle++;
else g_ord.breaks++;
}
g_ord.last = idx;
g_ord.ring[g_ord.ring_n % ORDER_RING] = (char)('0' + idx);
g_ord.ring_n++;
}
static int64_t g_last_vsync_ns;
static int64_t g_tick_vsync_ns;
static int64_t g_refresh_ns = 16666667;
@@ -821,8 +785,6 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
if (!s->dmabuf && s->last_dmabuf == buffer) g_pace.reattaches++;
s->last_dmabuf = buffer;
pace_note_buffer(buffer);
order_note_commit(buffer);
s->dmabuf_unsynced = 1;
drop_dmabuf(s, 1);
s->dmabuf = buffer;
s->dmabuf_buf = b;
@@ -833,7 +795,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
if (!b->img && !b->import_failed && b->n_planes >= 1) {
b->img = vkp_image_from_dmabuf(b->fd[0], b->format, b->modifier, b->width, b->height,
b->stride[0], b->offset[0]);
if (b->img) sc_layer_probe_dmabuf_fd(b->fd[0]);
if (b->img && g_zero_copy) sc_layer_probe_dmabuf_fd(b->fd[0]);
if (!b->img) {
b->import_failed = 1;
WLOGE("dmabuf import failed (%dx%d fmt=0x%08x mod=0x%llx)", b->width, b->height,
@@ -2162,7 +2124,21 @@ void droiddeck_stream_frame(AHardwareBuffer *ahb) {
unsigned droiddeck_stream_frames(void) { return atomic_load(&g_stream_frames); }
static int64_t g_scene_due_ns;
static int scene_held_for_limit(int64_t now, int64_t due, int limit, int unpaced) {
if (limit <= 0 || unpaced || due <= 0) return 0;
return now < due - 1000000LL;
}
static int64_t scene_next_due(int64_t now, int64_t due, int limit) {
if (limit <= 0) return 0;
const int64_t interval = 1000000000LL / limit;
return due > 0 && now - due < interval ? due + interval : now + interval;
}
static void render_scene(void) {
g_scene_due_ns = scene_next_due(now_ns(), g_scene_due_ns, g_fps_limit);
if (atomic_load(&g_stream_on)) { g_dirty_since_ns = 0; render_stream(); return; }
struct draw_list dl = {0};
struct surface *s;
@@ -2182,25 +2158,7 @@ static void render_scene(void) {
g_tick_held = 0;
g_hud_fresh = 0;
g_hdr_unimported = NULL;
wl_list_for_each(s, &g_surfaces, link) {
s->drawn = 0;
if (s->dmabuf_unsynced && s->dmabuf_buf && s->dmabuf_buf->n_planes >= 1) {
struct pollfd p = {.fd = s->dmabuf_buf->fd[0], .events = POLLIN};
const int64_t t0 = now_ns();
int r;
if (poll(&p, 1, 0) > 0) {
g_ord.poll_ready++;
} else {
g_ord.poll_busy++;
do { r = poll(&p, 1, 16); } while (r < 0 && errno == EINTR);
if (r == 0) g_ord.poll_timeout++;
const int64_t d = now_ns() - t0;
g_ord.poll_wait_ns += d;
if (d > g_ord.poll_wait_max_ns) g_ord.poll_wait_max_ns = d;
}
}
s->dmabuf_unsynced = 0;
}
wl_list_for_each(s, &g_surfaces, link) s->drawn = 0;
scene_size(&w, &h);
if (w != g_scene_w || h != g_scene_h) {
if (g_desktop) droiddeck_log("desktop", "size %dx%d", w, h);
@@ -2358,7 +2316,9 @@ static void render_scene(void) {
static int on_fallback_timer(void *data) {
g_fallback_armed = 0;
if (g_dirty) render_scene();
if (!g_dirty) return 0;
if (scene_held_for_limit(now_ns(), g_scene_due_ns, g_fps_limit, g_release_unpaced)) schedule_render();
else render_scene();
return 0;
}
@@ -2433,6 +2393,7 @@ static void on_vsync(int64_t frame_time_ns) {
g_tick_held = 1;
return;
}
if (g_dirty && scene_held_for_limit(now, g_scene_due_ns, g_fps_limit, g_release_unpaced)) return;
if (g_dirty && !scene_waits_for_game(now)) render_scene();
}
@@ -3632,21 +3593,6 @@ static int on_stats_timer(void *data) {
g_pace.renders, g_pace.commit_renders, (unsigned long long)game, g_pace.reattaches, g_pace.null_attaches, g_pace.distinct,
g_pace.presented, g_pace.replaced, g_pace.undrawn);
}
if (g_ord.commits) {
char ring[ORDER_RING + 1];
const unsigned n = g_ord.ring_n < ORDER_RING ? g_ord.ring_n : ORDER_RING;
for (unsigned i = 0; i < n; i++) ring[i] = g_ord.ring[(g_ord.ring_n - n + i) % ORDER_RING];
ring[n] = 0;
droiddeck_log("order", "last 10 s: %u commits over %u buffers, %u followed the cycle, %u broke it, %u repeated the same buffer | "
"producer fence at draw: %u ready, %u still busy (%u timed out, waited %.2f/%.2f ms) | last commits %s",
g_ord.commits, g_ord.known, g_ord.in_cycle, g_ord.breaks, g_ord.same_again,
g_ord.poll_ready, g_ord.poll_busy, g_ord.poll_timeout,
g_ord.poll_busy ? (double)g_ord.poll_wait_ns / 1e6 / g_ord.poll_busy : 0.0,
(double)g_ord.poll_wait_max_ns / 1e6, ring);
g_ord.commits = g_ord.in_cycle = g_ord.breaks = g_ord.same_again = 0;
g_ord.poll_ready = g_ord.poll_busy = g_ord.poll_timeout = 0;
g_ord.poll_wait_ns = g_ord.poll_wait_max_ns = 0;
}
{
const uint64_t seen = g_game_frames;
memset(&g_pace, 0, sizeof(g_pace));
@@ -195,7 +195,7 @@ class FrontEndActivity : ComponentActivity() {
private var navRequest by mutableStateOf<String?>(null)
private var storesShowMature by mutableStateOf(false)
private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first())
private var storesView by mutableStateOf(SessionPrefs.STORES_VIEWS.first())
private var storesView by mutableStateOf(SessionPrefs.DEFAULT_STORES_VIEW)
private var mic by mutableStateOf(false)
private var wifiDiscovery by mutableStateOf(false)
private var wifiDiscoveryPermission by mutableStateOf(false)
@@ -539,6 +539,11 @@ class FrontEndActivity : ComponentActivity() {
override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays()
override fun onDisplayChanged(displayId: Int) = refreshSecondScreenDisplays()
}
private val secondScreenTouchListener = object : android.hardware.input.InputManager.InputDeviceListener {
override fun onInputDeviceAdded(deviceId: Int) = refreshSecondScreenDisplays()
override fun onInputDeviceRemoved(deviceId: Int) = refreshSecondScreenDisplays()
override fun onInputDeviceChanged(deviceId: Int) = refreshSecondScreenDisplays()
}
private val homeRoleRequest = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
refreshHomeAppState()
@@ -1627,6 +1632,7 @@ class FrontEndActivity : ComponentActivity() {
override fun onPause() {
compatLaunchVisible = false
if (android.os.Build.VERSION.SDK_INT >= 29) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true)
super.onPause()
}
@@ -1688,6 +1694,7 @@ class FrontEndActivity : ComponentActivity() {
addDataScheme("file")
})
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
getSystemService(android.hardware.input.InputManager::class.java)?.registerInputDeviceListener(secondScreenTouchListener, ui)
launcherStarted = true
refreshSecondScreenDisplays()
getSystemService(android.content.pm.LauncherApps::class.java).registerCallback(packageCallback, ui)
@@ -1731,6 +1738,7 @@ class FrontEndActivity : ComponentActivity() {
com.droiddeck.launcher.stores.StoresState.libraryListener = null
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
getSystemService(android.hardware.input.InputManager::class.java)?.unregisterInputDeviceListener(secondScreenTouchListener)
launcherStarted = false
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
flood = null
@@ -214,7 +214,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private lateinit var touchscreenGestures: TouchscreenGestures
private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig()
private var gestureGame: String? = null
private var steamUiFocused = false
private var gestureSettingsOpen by mutableStateOf(false)
private var steamImportAsk by mutableStateOf<com.droiddeck.launcher.session.SteamImportPrompt.Ask?>(null)
private var steamImportAnswered: String? = null
@@ -454,6 +453,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
}
private var frameGen by mutableStateOf(FrameGen.Mode.OFF)
private var frameGenPip = false
private val frameGenRequests = java.util.concurrent.atomic.AtomicInteger()
private var fexPreset by mutableStateOf("")
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
private var steamDownloadsInBackground by mutableStateOf(false)
@@ -463,6 +464,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
private var selectedSecondScreenDisplay by mutableStateOf(SessionState.secondScreenDisplay)
private var started = false
private var dualControlsProvisional: Boolean
get() = SessionState.secondScreenProvisional
set(value) { SessionState.secondScreenProvisional = value }
private var sessionActivityDisplayId = Display.DEFAULT_DISPLAY
private lateinit var displayManager: DisplayManager
private var secondScreenPresentation: SecondScreenPresentation? = null
@@ -529,6 +533,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
refreshControls()
updatePointerCapture()
updateHandCamera()
refreshSecondScreenDisplays()
}
override fun onInputDeviceRemoved(deviceId: Int) {
physicalShortcuts.onDeviceRemoved(deviceId)
@@ -540,10 +545,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
refreshControls()
updatePointerCapture()
updateHandCamera()
refreshSecondScreenDisplays()
}
override fun onInputDeviceChanged(deviceId: Int) {
joyConVr?.refresh()
refreshControls()
refreshSecondScreenDisplays()
}
}
@@ -576,6 +583,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionState.steamUi = intent.getStringExtra(SessionService.EXTRA_STEAM_UI)
SessionState.steamUrl = intent.getStringExtra(SessionService.EXTRA_STEAM_URL)
SessionState.steamVr = intent.getBooleanExtra(EXTRA_STEAMVR, false)
SessionState.secondScreenAutoOpened = false
SessionState.secondScreenProvisional = false
} else if (intent.getBooleanExtra(EXTRA_STEAMVR, false) && SessionState.mode == SessionService.MODE_STEAM) {
SessionState.steamVr = true
}
@@ -828,7 +837,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onDispose { com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity, false) }
}
androidx.compose.runtime.LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, pipUi) { updatePointerCapture() }
androidx.compose.runtime.LaunchedEffect(pipUi) { hud.setHidden(pipUi) }
androidx.compose.runtime.LaunchedEffect(pipUi) {
hud.setHidden(pipUi)
applyOutputPacing()
if (pipUi != frameGenPip) {
frameGenPip = pipUi
if (FrameGen.engine(this@SessionActivity) != FrameGen.ENGINE_OFF && ::surfaceView.isInitialized) applyFrameGen()
}
}
androidx.compose.runtime.LaunchedEffect(AgentGuest.steamKeyboard) { updateOnScreenControls() }
androidx.compose.runtime.LaunchedEffect(AgentGuest.desktopTextField) { onDesktopTextField(AgentGuest.desktopTextField) }
androidx.compose.runtime.LaunchedEffect(pipUi, pcKeyboardOpen) { updateDesktopKeyboardButton() }
@@ -847,15 +863,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
androidx.compose.runtime.LaunchedEffect(picturePosition, SessionState.running, pipUi, cardboard.enabled) { applyGameAlignment() }
androidx.compose.runtime.LaunchedEffect(AgentGuest.focusRevision) {
val steamUi = SessionState.mode == SessionService.MODE_STEAM && kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
AgentGuest.focus(this@SessionActivity)?.optLong("focusedApp")?.let { it <= 0 || it == 769L } ?: true
}
if (steamUi != steamUiFocused) {
steamUiFocused = steamUi
applySteamUiPacing()
}
}
DroidDeckTheme {
if (pipUi) {
if (SessionState.suspended) androidx.compose.foundation.layout.Box(
@@ -2094,7 +2101,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
CompositorHost.startOrAttach(
this, holder.surface, runtimeDir.path,
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(), outputFpsLimit(), steamUiLimit(refreshHz()),
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(), outputFpsLimit(),
)
onOutputAttached(holder)
if (SessionState.running && size != previous) {
@@ -2232,25 +2239,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun mirrorRefreshLimit(): Int =
GlassesRendering.mirrorRefreshLimit(glassesSettings, glasses, glassesScreen != null)
private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit(mirrorRefreshLimit(), if (noSteamSession()) SessionState.fpsLimit else 0)
private fun outputFpsLimit(): Int = outputFpsLimit(pipUi)
private fun steamUiLimit(hz: Float): Int =
if (steamUiFocused && SessionPrefs.steamUiPacing(this)) SessionPrefs.steamUiFpsLimit(hz) else 0
private fun applySteamUiPacing() {
if (!CompositorHost.isStarted) return
val hz = refreshHz()
val limit = steamUiLimit(hz)
CompositorHost.updatePacing(hz, outputFpsLimit(), limit)
Log.i(TAG, "pacing: " + if (limit > 0) "Steam UI at $limit fps on a ${Math.round(hz)} Hz screen" else "uncapped")
}
private fun outputFpsLimit(pip: Boolean): Int =
SessionPrefs.compositorFpsLimit(mirrorRefreshLimit(), if (noSteamSession()) SessionState.fpsLimit else 0, pip)
private fun applyOutputPacing() {
Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(), mirrorRefreshLimit()))
Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(false), mirrorRefreshLimit()))
if (CompositorHost.isStarted) {
val hz = refreshHz()
val changed = kotlin.math.abs(SessionState.refreshHz - hz) > 0.1f
CompositorHost.updatePacing(hz, outputFpsLimit(), steamUiLimit(hz))
CompositorHost.updatePacing(hz, outputFpsLimit())
pushCardboard(activeCardboard)
if (changed && ::surfaceView.isInitialized) applyFrameGen()
}
@@ -2258,8 +2257,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun applyFrameGen() {
val hz = refreshHz()
val pip = pipUi && mirrorRefreshLimit() <= 0
val request = frameGenRequests.incrementAndGet()
Thread({
val problem = FrameGen.apply(this, hz)
val problem = synchronized(frameGenRequests) {
if (request != frameGenRequests.get()) return@Thread
if (pip) FrameGen.apply(this, FrameGen.Mode.OFF, hz) else FrameGen.apply(this, hz)
}
val state = Lossless.state(this)
runOnUiThread {
lossless = state
@@ -3011,11 +3015,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val newIds = candidates.map { it.id }.toSet()
if (secondScreenMode != SecondScreenMode.NONE && oldIds.isNotEmpty() && selectedSecondScreenDisplay !in newIds) {
closeSecondScreen(reset = true)
SessionState.secondScreenAutoOpened = false
return
}
if (selectedSecondScreenDisplay !in newIds) selectedSecondScreenDisplay = candidates.firstOrNull()?.id ?: -1
if (secondScreenMode != SecondScreenMode.NONE && candidates.isEmpty()) closeSecondScreen(reset = true)
else if (started && secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
if (secondScreenMode != SecondScreenMode.NONE && candidates.isEmpty()) {
closeSecondScreen(reset = true)
SessionState.secondScreenAutoOpened = false
} else if (started && secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
else if (started && !ended && ::loading.isInitialized && !loading.visible) openDualScreenControls()
updateKeyboardRoute()
}
@@ -3027,6 +3035,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionState.secondScreenAutoOpened = true
selectedSecondScreenDisplay = target.displayId
selectSecondScreenMode(SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this), SessionState.deckPad))
dualControlsProvisional = ::loading.isInitialized && loading.visible
}
private fun settleDualScreenControls() {
if (!dualControlsProvisional || pipUi || !started || (::loading.isInitialized && loading.visible)) return
dualControlsProvisional = false
if (secondScreenMode == SecondScreenMode.NONE) return
val wanted = SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this), SessionState.deckPad)
if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
}
private fun selectSecondScreenDisplay(displayId: Int) {
@@ -3037,6 +3054,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun selectSecondScreenMode(mode: SecondScreenMode) {
dualControlsProvisional = false
if (mode == SecondScreenMode.NONE) {
closeSecondScreen(reset = true)
return
@@ -3815,7 +3833,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
updateOnScreenControls()
if (resumed) { sessionClipboard.start(); updatePadMotion() }
if (started) refreshSecondScreenDisplays()
if (started) {
settleDualScreenControls()
refreshSecondScreenDisplays()
}
if (CompositorHost.isStarted) applyFrameGen()
}
}
@@ -3851,9 +3872,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
for (name in arrayOf("peak_refresh_rate", "min_refresh_rate")) {
contentResolver.registerContentObserver(android.provider.Settings.System.getUriFor(name), false, refreshSettingObserver)
}
settleDualScreenControls()
refreshSecondScreenDisplays()
if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
else if (::loading.isInitialized && !loading.visible) openDualScreenControls()
else openDualScreenControls()
startedScreens++
SessionService.setActivityVisible(this, true, sessionActivityDisplayId)
Glasses.rescan()
@@ -3918,6 +3940,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
(getSystemService(INPUT_SERVICE) as? InputManager)
?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper()))
refreshSecondScreenDisplays()
if (SessionState.guestPid > 1) padBridge?.syncConnectedControllers()
joyConVr?.refresh()
onScreenControls?.reload()
@@ -4380,7 +4403,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
loading.visible = false
hud.start()
memoryHud.start()
if (started) openDualScreenControls()
if (started) {
settleDualScreenControls()
openDualScreenControls()
}
}
}
@@ -4,7 +4,11 @@ import android.content.Context
import android.hardware.display.DisplayManager
import android.os.Build
import android.view.Display
import android.view.InputDevice
import android.view.MotionEvent
import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.abs
import kotlin.math.roundToInt
object DualScreen {
const val MODE_AUTO = "auto"
@@ -13,17 +17,54 @@ object DualScreen {
val modes = listOf(MODE_AUTO, MODE_ON, MODE_OFF)
private const val TYPE_INTERNAL = 1
private val knownModels = setOf("retroid pocket duo", "ayn thor")
private val touchedDisplays = mutableSetOf<Int>()
fun builtInDisplay(displayManager: DisplayManager, primaryDisplayId: Int): Display? =
fun builtInDisplay(displayManager: DisplayManager, primaryDisplayId: Int): Display? {
val primary = displayManager.getDisplay(primaryDisplayId)
val awake = primary?.state != Display.STATE_OFF
val panels = if (awake) touchPanels() else emptyList()
return internalDisplay(displayManager, primaryDisplayId) {
if (awake && it.state == Display.STATE_OFF) return@internalDisplay false
synchronized(touchedDisplays) {
if (awake && hasOwnTouchPanel(size(it), primary?.let(::size), panels)) touchedDisplays += it.displayId
it.displayId in touchedDisplays
}
}
}
private fun internalDisplay(displayManager: DisplayManager, primaryDisplayId: Int, accept: (Display) -> Boolean = { true }): Display? =
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION).firstOrNull {
it.isValid && it.displayId != primaryDisplayId && (it.flags and Display.FLAG_PRESENTATION) != 0 &&
isBuiltIn(displayType(it), Build.MODEL)
isBuiltIn(displayType(it), Build.MODEL) && accept(it)
}
internal fun hasOwnTouchPanel(display: Pair<Int, Int>, primary: Pair<Int, Int>?, panels: List<Pair<Int, Int>>): Boolean {
val matching = panels.count { covers(it, display) }
return if (primary != null && covers(primary, display)) matching >= 2 else matching >= 1
}
private fun covers(panel: Pair<Int, Int>, display: Pair<Int, Int>): Boolean =
(near(panel.first, display.first) && near(panel.second, display.second)) ||
(near(panel.first, display.second) && near(panel.second, display.first))
private fun near(a: Int, b: Int) = abs(a - b) <= 2
private fun size(display: Display): Pair<Int, Int> =
display.mode.let { it.physicalWidth to it.physicalHeight }
private fun touchPanels(): List<Pair<Int, Int>> =
InputDevice.getDeviceIds().toList().mapNotNull { id ->
val device = InputDevice.getDevice(id) ?: return@mapNotNull null
if (device.isVirtual || !device.supportsSource(InputDevice.SOURCE_TOUCHSCREEN)) return@mapNotNull null
val x = device.getMotionRange(MotionEvent.AXIS_X, InputDevice.SOURCE_TOUCHSCREEN) ?: return@mapNotNull null
val y = device.getMotionRange(MotionEvent.AXIS_Y, InputDevice.SOURCE_TOUCHSCREEN) ?: return@mapNotNull null
(x.max - x.min + 1f).roundToInt() to (y.max - y.min + 1f).roundToInt()
}
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? =
when (SessionPrefs.dualScreenMode(context)) {
MODE_OFF -> null
MODE_ON -> builtInDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
MODE_ON -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
else -> builtInDisplay(displayManager, primaryDisplayId)
}
@@ -57,10 +57,7 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
val clip = clipboard.primaryClip
if (clip != null && clip.itemCount == 0) return
val text = clip?.getItemAt(0)?.text?.toString()
if (echo != null && text == echo) {
echo = null
return
}
if (echo != null && text == echo) return
echo = null
if (!changed && published && text == shared) return
publish(text)
@@ -83,7 +83,11 @@ class TwoFingerGestures(private val slopPx: Float, private val listener: Listene
pass(State.PASSING)
return true
}
State.SCROLLING, State.HELD, State.TAPPED -> return true
State.SCROLLING -> {
anchor(event, -1)
return true
}
State.HELD, State.TAPPED -> return true
else -> Unit
}
}
@@ -137,7 +141,11 @@ class TwoFingerGestures(private val slopPx: Float, private val listener: Listene
pass(State.PASSING)
return true
}
State.SCROLLING, State.HELD, State.TAPPED -> return true
State.SCROLLING -> {
anchor(event, event.actionIndex)
return true
}
State.HELD, State.TAPPED -> return true
else -> Unit
}
MotionEvent.ACTION_UP -> {
@@ -193,6 +201,13 @@ class TwoFingerGestures(private val slopPx: Float, private val listener: Listene
hypot(event.getX(i) - start.first, event.getY(i) - start.second) > slopPx
}
private fun anchor(event: MotionEvent, lifted: Int) {
val kept = (0 until event.pointerCount).filter { it != lifted }
if (kept.size < 2) return
lastX = (event.getX(kept[0]) + event.getX(kept[1])) / 2f
lastY = (event.getY(kept[0]) + event.getY(kept[1])) / 2f
}
private fun span(event: MotionEvent) = hypot(event.getX(1) - event.getX(0), event.getY(1) - event.getY(0))
private fun midX(event: MotionEvent) = (event.getX(0) + event.getX(1)) / 2f
private fun midY(event: MotionEvent) = (event.getY(0) + event.getY(1)) / 2f
@@ -97,8 +97,10 @@ internal object DesktopFileRemoval {
}
if (!dir.delete()) throw IOException("Cannot remove $dir")
}
for (name in listOf("sync/droiddeck.db", "droiddeck-desktop")) {
val file = File(lib, name)
val sync = File(lib, "sync")
val files = listOf(File(lib, "droiddeck-desktop")) +
listOfNotNull(File(sync, "droiddeck.db").takeUnless { Files.isSymbolicLink(sync.toPath()) })
for (file in files) {
if (Files.isSymbolicLink(file.toPath()) || file.isFile) Files.delete(file.toPath())
}
}
@@ -290,6 +290,7 @@ object SessionFiles {
"stage session=$startsSession pending=$force choice=${SessionPrefs.bootMovie(context)} movie=${startupMovie?.path} " +
"staged=$bigPictureMovieInstalled done=$done steam=${home.path} config: $before -> ${startupMoviePath(config)}",
)
if (startsSession) disableIdleSleep(home)
if (!done) allDone = false
if (!bigPictureMovieInstalled) allInstalled = false
if (done && home.path.contains(".droiddeck-x64") == activeIsX64) seen = if (bigPictureMovieInstalled) BOOT_MOVIE_PATH else ""
@@ -528,6 +529,43 @@ object SessionFiles {
}
}
private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds")
/**
* Sets Steam's Power > "Sleep after" (battery and plugged in) to Disabled at every session start: Android
* owns the device's sleep, and a client that suspends inside the session only shows a black screen. Dimming stays the user's. Runs
* only before the client starts, which rewrites its config on exit.
*/
internal fun disableIdleSleep(steamHome: File): Boolean {
val config = File(steamHome, "config/config.vdf")
val text = runCatching { config.readText() }.getOrNull() ?: return false
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
val steam = findSteamBlock(text) ?: return false
val system = findObject(text, "system", steam.open + 1, steam.close)
val updated = if (system != null) {
val block = text.substring(system.keyStart, system.close + 1)
text.replaceRange(system.keyStart, system.close + 1, IDLE_SLEEP_TIMERS.fold(block) { acc, key -> setScalar(acc, key, "0", newline) })
} else {
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' } + "\t"
val section = (listOf(indent + "\"system\"", indent + "{") +
IDLE_SLEEP_TIMERS.map { "$indent\t\"$it\"\t\t\"0\"" } + (indent + "}")).joinToString(newline) + newline
text.substring(0, lineStart) + section + text.substring(lineStart)
}
val staged = File(config.parentFile, config.name + ".staged")
return try {
if (updated != text) {
staged.writeText(updated)
if (!staged.renameTo(config)) { staged.delete(); return false }
}
true
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not disable Steam's idle sleep", e)
false
}
}
/** Adds the `Customization` section Steam reads, next to the `Software` section, when the config has none. */
private fun withCustomization(text: String, path: String, newline: String): String {
val root = findObject(text, "InstallConfigStore", 0, text.length) ?: return text
@@ -147,10 +147,10 @@ object SessionPrefs {
}
fun storesView(context: Context): String =
prefs(context).getString("storesView", null)?.takeIf { it in STORES_VIEWS } ?: STORES_VIEWS.first()
prefs(context).getString("storesView", null)?.takeIf { it in STORES_VIEWS } ?: DEFAULT_STORES_VIEW
fun setStoresView(context: Context, view: String) {
prefs(context).edit().putString("storesView", if (view in STORES_VIEWS) view else STORES_VIEWS.first()).apply()
prefs(context).edit().putString("storesView", if (view in STORES_VIEWS) view else DEFAULT_STORES_VIEW).apply()
}
fun libraryCardLevel(context: Context): Int = prefs(context).getInt("libraryCardLevel", 2)
@@ -199,6 +199,7 @@ object SessionPrefs {
val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc")
val STORES_VIEWS = listOf("cards", "capsules", "list")
const val DEFAULT_STORES_VIEW = "capsules"
fun storesInstallTarget(context: Context): String = prefs(context).getString("storesInstallTarget", "") ?: ""
@@ -441,11 +442,15 @@ object SessionPrefs {
/**
* Shader pre-caching as the launcher last set it, until a session reports it written into the
* client's config.vdf; after that the client's own toggle is the user's again.
* client's config.vdf; after that the client's own toggle is the user's again. A client that
* has never written a config.vdf starts with pre-caching off.
*/
fun pendingShaderPrecache(context: Context): Boolean? {
val prefs = prefs(context)
if (!prefs.contains("shaderPrecache")) return null
if (!prefs.contains("shaderPrecache")) {
if (steamConfig(context).exists()) return null
prefs.edit().putBoolean("shaderPrecache", false).apply()
}
val on = prefs.getBoolean("shaderPrecache", true)
val applied = shaderPrecacheApplied(context)
val written = runCatching { applied.readText().trim() }.getOrNull() ?: return on
@@ -460,9 +465,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("shaderPrecache", on).apply()
}
private fun steamConfig(context: Context) =
java.io.File(steamRoot(context, steamClientArch(context)), "config/config.vdf")
fun shaderPrecache(context: Context): Boolean = pendingShaderPrecache(context)
?: runCatching { com.droiddeck.launcher.storage.SteamStorage.shaderPrecache(
java.io.File(steamRoot(context, steamClientArch(context)), "config/config.vdf").readText()) }.getOrDefault(true)
steamConfig(context).readText()) }.getOrDefault(true)
fun stretch16x9(context: Context): Boolean = prefs(context).getBoolean("stretch16x9", false)
@@ -681,7 +689,7 @@ object SessionPrefs {
fun mangoapp(context: Context): Boolean = prefs(context).getBoolean("mangoapp", true)
fun vsyncThread(context: Context): Boolean = prefs(context).getBoolean("vsyncThread", true)
fun renderOnCommit(context: Context): Boolean = prefs(context).getBoolean("renderOnCommit", false)
fun renderOnCommit(context: Context): Boolean = prefs(context).getBoolean("renderOnCommit", true)
fun setMangoapp(context: Context, on: Boolean) { prefs(context).edit().putBoolean("mangoapp", on).apply() }
fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true)
@@ -1096,20 +1104,16 @@ object SessionPrefs {
* Steam's Frame Limit in the Quick Access menu caps Steam games, and the drawer's limit caps games
* launched without Steam. Mirroring still follows the glasses' refresh rate.
*/
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0): Int = when {
mirrorRefreshLimit <= 0 && sessionLimit <= 0 -> FPS_UNPACED
mirrorRefreshLimit <= 0 -> sessionLimit
sessionLimit <= 0 -> mirrorRefreshLimit
else -> minOf(mirrorRefreshLimit, sessionLimit)
}
const val PIP_FPS = 30
private const val STEAM_UI_FPS = 60f
fun steamUiPacing(context: Context): Boolean = prefs(context).getBoolean("steamUiPacing", true)
fun steamUiFpsLimit(refreshHz: Float): Int {
val steps = ((refreshHz + 0.5f) / STEAM_UI_FPS).toInt()
return if (steps < 2) 0 else (refreshHz / steps + 0.01f).toInt()
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0, pip: Boolean = false): Int {
val limit = when {
mirrorRefreshLimit <= 0 && sessionLimit <= 0 -> FPS_UNPACED
mirrorRefreshLimit <= 0 -> sessionLimit
sessionLimit <= 0 -> mirrorRefreshLimit
else -> minOf(mirrorRefreshLimit, sessionLimit)
}
return if (pip && mirrorRefreshLimit <= 0 && (limit <= 0 || limit > PIP_FPS)) PIP_FPS else limit
}
val upscalerChoices = listOf(
@@ -543,7 +543,6 @@ class SessionService : Service() {
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
SessionState.deckPad = false
SessionState.secondScreenAutoOpened = false
deckBinds = emptyList()
inputSysfs = null
if (controllersOn) {
@@ -717,6 +716,7 @@ class SessionService : Service() {
if (!pulse.setMicSuspended(false)) Log.w(TAG, "could not resume microphone source")
},
zramControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.bl-zram"),
clockControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.bl-clock"),
pagedOut = { processes, unacknowledged, residentKb, swapKb, swapBeforeKb, millis ->
Log.i(TAG, "paged out $processes processes ($unacknowledged unacknowledged) in $millis ms: " +
"resident ${residentKb / 1024} MB, zram ${swapBeforeKb / 1024} -> ${swapKb / 1024} MB")
@@ -92,6 +92,7 @@ object SessionState {
@Volatile var secondScreenMode = com.droiddeck.launcher.input.SecondScreenMode.NONE
@Volatile var secondScreenDisplay = -1
@Volatile var secondScreenAutoOpened = false
@Volatile var secondScreenProvisional = false
@Volatile
var mode = "steam"
@@ -3,6 +3,9 @@ package com.droiddeck.launcher.session
import android.os.Process
import java.io.File
import java.io.IOException
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.RejectedExecutionException
@@ -19,6 +22,8 @@ internal class SessionSuspendController(
private val nowMillis: () -> Long = { System.nanoTime() / 1_000_000 },
private val executor: ExecutorService = Executors.newSingleThreadExecutor(),
private val zramControl: File? = null,
private val clockControl: File? = null,
private val nowNanos: () -> Long = System::nanoTime,
private val pagedOut: (processes: Int, unacknowledged: Int, residentKb: Long, swapKb: Long, swapBeforeKb: Long, millis: Long) -> Unit =
{ _, _, _, _, _, _ -> },
) {
@@ -43,6 +48,7 @@ internal class SessionSuspendController(
@Volatile private var closing = false
@Volatile private var cancelled = false
private var frozen = emptyList<ProcessRecord>()
private var frozenSince: Long? = null
fun freeze(pageOut: Boolean = false, completion: (Boolean) -> Unit) {
cancelled = false
@@ -93,6 +99,7 @@ internal class SessionSuspendController(
} catch (_: Exception) {
} finally {
frozen = records.values.toList()
if (complete && frozenSince == null) frozenSince = nowNanos()
if (!complete) {
if (restoreSafely(frozen)) frozen = emptyList()
runAudio(resumeAudio)
@@ -111,6 +118,7 @@ internal class SessionSuspendController(
fun resume(completion: (Boolean) -> Unit) {
submit({
val records = frozen
advanceClock()
runAudio(resumeAudio)
val resumed = restoreSafely(records)
if (resumed) frozen = emptyList()
@@ -121,6 +129,7 @@ internal class SessionSuspendController(
fun closeAndResume(completion: () -> Unit) {
closing = true
submit({
advanceClock()
if (restoreSafely(frozen)) frozen = emptyList()
completion()
executor.shutdown()
@@ -135,6 +144,23 @@ internal class SessionSuspendController(
}
}
private fun advanceClock() {
val since = frozenSince ?: return
frozenSince = null
val control = clockControl?.takeIf { it.isFile && it.length() >= Long.SIZE_BYTES } ?: return
try {
RandomAccessFile(control, "rw").use { file ->
val bytes = ByteArray(Long.SIZE_BYTES)
file.readFully(bytes)
val shift = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).long.coerceAtLeast(0L) +
(nowNanos() - since).coerceAtLeast(0L)
file.seek(0L)
file.write(ByteBuffer.allocate(Long.SIZE_BYTES).order(ByteOrder.LITTLE_ENDIAN).putLong(shift).array())
}
} catch (_: IOException) {
}
}
private fun runAudio(action: () -> Unit) {
try {
action()
@@ -202,7 +202,6 @@ internal fun BusyChip(s: FrontEndState) {
internal fun RuntimeChip(s: FrontEndState) = when {
s.busy -> Chip(if (s.percent >= 0) stringResource(R.string.setup_runtime_progress, s.stage, s.percent) else s.stage, ok = false)
s.removalPending -> Chip(stringResource(R.string.runtime_removal_incomplete), ok = false)
!s.ready -> Chip(stringResource(R.string.games_runtime_first_play), ok = false)
s.available != null && s.available != s.installed -> Chip(stringResource(R.string.games_runtime_update), ok = false)
else -> Chip(stringResource(R.string.games_runtime_ready), ok = true)
}
@@ -166,7 +166,7 @@ class FrontEndState(
val sgdbUserKey: Boolean = false,
val storesShowMature: Boolean = false,
val storesSort: String = SessionPrefs.STORES_SORTS.first(),
val storesView: String = SessionPrefs.STORES_VIEWS.first(),
val storesView: String = SessionPrefs.DEFAULT_STORES_VIEW,
val storeDownloadsActive: Int = 0,
val updates: UpdatesState = UpdatesState(),
)
@@ -141,6 +141,10 @@ class SecondScreenPresentation(
if (created) renderMode()
}
fun retryTerminal() {
if (created && isShowing && currentMode == SecondScreenMode.TERMINAL && terminalSession == null) renderMode()
}
val showsKeyboard: Boolean get() = isShowing && !menuShown && currentMode == SecondScreenMode.KEYBOARD_TRACKPAD
val showsControls: Boolean get() = isShowing && currentMode != SecondScreenMode.NONE
@@ -142,7 +142,7 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
scrim = { if (games.size >= WALL_MIN_GAMES) WallFade() },
words = {
val runtimeStatus: @Composable () -> Unit = {
if (s.busy || !s.ready || (s.available != null && s.available != s.installed)) RuntimeChip(s)
if (s.busy || (s.available != null && s.available != s.installed)) RuntimeChip(s)
else if (s.integration.suggested && signedIn && !com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus))
IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration)
}
@@ -51,11 +51,10 @@ object CompositorHost {
outputHeight: Int,
refreshHz: Float,
fpsLimit: Int,
uiLimit: Int = 0,
): Boolean {
ownVsyncThread = SessionPrefs.vsyncThread(context)
WaylandCompositor.nativeSetRenderOnCommit(SessionPrefs.renderOnCommit(context))
pace(refreshHz, fpsLimit, uiLimit)
pace(refreshHz, fpsLimit)
if (!SessionState.running) WaylandCompositor.nativeSetOutputSize(outputWidth, outputHeight)
if (started) {
attached = surface
@@ -73,16 +72,16 @@ object CompositorHost {
return true
}
private fun pace(refreshHz: Float, fpsLimit: Int, uiLimit: Int = 0) {
WaylandCompositor.nativeSetFpsLimit(if (fpsLimit == SessionPrefs.FPS_UNPACED && uiLimit > 0) uiLimit else fpsLimit)
private fun pace(refreshHz: Float, fpsLimit: Int) {
WaylandCompositor.nativeSetFpsLimit(fpsLimit)
WaylandCompositor.nativeSetLayerFrameRate(if (fpsLimit > 0) fpsLimit.toFloat() else refreshHz)
WaylandCompositor.nativeSetOutputRefreshRate(refreshHz)
SessionState.refreshHz = refreshHz
}
@Synchronized
fun updatePacing(refreshHz: Float, fpsLimit: Int, uiLimit: Int = 0) {
if (started) pace(refreshHz, fpsLimit, uiLimit)
fun updatePacing(refreshHz: Float, fpsLimit: Int) {
if (started) pace(refreshHz, fpsLimit)
}
@Synchronized
-1
View File
@@ -1149,7 +1149,6 @@
<string name="games_never_played">لم يتم تشغيلها أبدًا</string>
<string name="games_runtime_busy_percent">بيئة التشغيل مشغولة · %1$d%%</string>
<string name="games_runtime_busy">بيئة التشغيل مشغولة</string>
<string name="games_runtime_first_play">تُثبَّت بيئة التشغيل عند أول تشغيل</string>
<string name="games_runtime_update">يتوفر تحديث لبيئة التشغيل</string>
<string name="games_runtime_ready">● بيئة التشغيل جاهزة</string>
<string name="games_internal">التخزين الداخلي</string>
@@ -1188,7 +1188,6 @@
<string name="games_never_played">Nunca jugado</string>
<string name="games_runtime_busy_percent">Runtime ocupado · %1$d%%</string>
<string name="games_runtime_busy">Runtime ocupado</string>
<string name="games_runtime_first_play">El runtime se instala al jugar</string>
<string name="games_runtime_update">Actualización del runtime disponible</string>
<string name="games_runtime_ready">● Runtime listo</string>
<string name="games_internal">Almacenamiento interno</string>
-1
View File
@@ -1125,7 +1125,6 @@
<string name="games_never_played">Никога не е играна</string>
<string name="games_runtime_busy_percent">Средата за изпълнение е заета · %1$d%%</string>
<string name="games_runtime_busy">Средата за изпълнение е заета</string>
<string name="games_runtime_first_play">Средата за изпълнение се инсталира при първото Play</string>
<string name="games_runtime_update">Налична актуализация на средата за изпълнение</string>
<string name="games_runtime_ready">● Средата за изпълнение е готова</string>
<string name="games_internal">Вътрешна памет</string>
-1
View File
@@ -1137,7 +1137,6 @@
<string name="games_never_played">Nikdy nehráno</string>
<string name="games_runtime_busy_percent">Runtime zaneprázdněn · %1$d%%</string>
<string name="games_runtime_busy">Runtime zaneprázdněn</string>
<string name="games_runtime_first_play">Runtime se nainstaluje při prvním spuštění hry</string>
<string name="games_runtime_update">K dispozici aktualizace runtime</string>
<string name="games_runtime_ready">● Runtime připraven</string>
<string name="games_internal">Interní úložiště</string>
-1
View File
@@ -1125,7 +1125,6 @@
<string name="games_never_played">Aldrig spillet</string>
<string name="games_runtime_busy_percent">Runtime optaget · %1$d%%</string>
<string name="games_runtime_busy">Runtime optaget</string>
<string name="games_runtime_first_play">Runtime installeres ved første Spil</string>
<string name="games_runtime_update">Runtimeopdatering tilgængelig</string>
<string name="games_runtime_ready">● Runtime klar</string>
<string name="games_internal">Internt lager</string>
-1
View File
@@ -1117,7 +1117,6 @@
<string name="games_never_played">Nie gespielt</string>
<string name="games_runtime_busy_percent">Laufzeit beschäftigt · %1$d %%</string>
<string name="games_runtime_busy">Laufzeit beschäftigt</string>
<string name="games_runtime_first_play">Laufzeit wird beim ersten „Spielen“ installiert</string>
<string name="games_runtime_update">Laufzeit-Update verfügbar</string>
<string name="games_runtime_ready">● Laufzeit bereit</string>
<string name="games_internal">Interner Speicher</string>
-1
View File
@@ -1125,7 +1125,6 @@
<string name="games_never_played">Δεν έχει παιχτεί ποτέ</string>
<string name="games_runtime_busy_percent">Το runtime είναι απασχολημένο · %1$d%%</string>
<string name="games_runtime_busy">Το runtime είναι απασχολημένο</string>
<string name="games_runtime_first_play">Το runtime εγκαθίσταται στο πρώτο Play</string>
<string name="games_runtime_update">Υπάρχει ενημέρωση runtime</string>
<string name="games_runtime_ready">● Το runtime είναι έτοιμο</string>
<string name="games_internal">Εσωτερική αποθήκευση</string>
-1
View File
@@ -1133,7 +1133,6 @@
<string name="games_never_played">Nunca jugado</string>
<string name="games_runtime_busy_percent">Runtime ocupado · %1$d%%</string>
<string name="games_runtime_busy">Runtime ocupado</string>
<string name="games_runtime_first_play">El runtime se instala al jugar</string>
<string name="games_runtime_update">Actualización del runtime disponible</string>
<string name="games_runtime_ready">● Runtime listo</string>
<string name="games_internal">Almacenamiento interno</string>
-1
View File
@@ -1125,7 +1125,6 @@
<string name="games_never_played">Ei pelattu koskaan</string>
<string name="games_runtime_busy_percent">Ajoympäristö varattu · %1$d %%</string>
<string name="games_runtime_busy">Ajoympäristö varattu</string>
<string name="games_runtime_first_play">Ajoympäristö asentuu ensimmäisellä Pelaa-painalluksella</string>
<string name="games_runtime_update">Ajoympäristön päivitys saatavilla</string>
<string name="games_runtime_ready">● Ajoympäristö valmis</string>
<string name="games_internal">Sisäinen tallennustila</string>
-1
View File
@@ -1133,7 +1133,6 @@
<string name="games_never_played">Jamais lancé</string>
<string name="games_runtime_busy_percent">Environnement d\'exécution occupé · %1$d%%</string>
<string name="games_runtime_busy">Environnement d\'exécution occupé</string>
<string name="games_runtime_first_play">Installation de l\'environnement d\'exécution lors du premier lancement du jeu</string>
<string name="games_runtime_update">Mise à jour de l\'environnement d\'exécution disponible</string>
<string name="games_runtime_ready">● Environnement d\'exécution prêt</string>
<string name="games_internal">Stockage interne</string>
-1
View File
@@ -1125,7 +1125,6 @@
<string name="games_never_played">कभी नहीं खेला</string>
<string name="games_runtime_busy_percent">रनटाइम व्यस्त · %1$d%%</string>
<string name="games_runtime_busy">रनटाइम व्यस्त</string>
<string name="games_runtime_first_play">पहली बार Play पर रनटाइम इंस्टॉल होता है</string>
<string name="games_runtime_update">रनटाइम अपडेट उपलब्ध</string>
<string name="games_runtime_ready">● रनटाइम तैयार</string>
<string name="games_internal">इंटरनल स्टोरेज</string>
-1
View File
@@ -1125,7 +1125,6 @@
<string name="games_never_played">Még nem játszott</string>
<string name="games_runtime_busy_percent">Futtatókörnyezet dolgozik · %1$d%%</string>
<string name="games_runtime_busy">Futtatókörnyezet dolgozik</string>
<string name="games_runtime_first_play">A futtatókörnyezet az első Játék gombnyomáskor települ</string>
<string name="games_runtime_update">Elérhető futtatókörnyezet-frissítés</string>
<string name="games_runtime_ready">● A futtatókörnyezet kész</string>
<string name="games_internal">Belső tárhely</string>
-1
View File
@@ -1119,7 +1119,6 @@
<string name="games_never_played">Belum pernah dimainkan</string>
<string name="games_runtime_busy_percent">Runtime sibuk · %1$d%%</string>
<string name="games_runtime_busy">Runtime sibuk</string>
<string name="games_runtime_first_play">Runtime terinstal saat Main pertama kali</string>
<string name="games_runtime_update">Pembaruan runtime tersedia</string>
<string name="games_runtime_ready">● Runtime siap</string>
<string name="games_internal">Penyimpanan internal</string>
-1
View File
@@ -1123,7 +1123,6 @@
<string name="games_never_played">Mai giocato</string>
<string name="games_runtime_busy_percent">Runtime occupato · %1$d%%</string>
<string name="games_runtime_busy">Runtime occupato</string>
<string name="games_runtime_first_play">Il runtime si installa al primo Gioca</string>
<string name="games_runtime_update">Aggiornamento del runtime disponibile</string>
<string name="games_runtime_ready">● Runtime pronto</string>
<string name="games_internal">Memoria interna</string>
-1
View File
@@ -1121,7 +1121,6 @@
<string name="games_never_played">未プレイ</string>
<string name="games_runtime_busy_percent">実行環境は使用中 · %1$d%%</string>
<string name="games_runtime_busy">実行環境は使用中</string>
<string name="games_runtime_first_play">初回実行時に実行環境を導入</string>
<string name="games_runtime_update">実行環境にアップデートがあります</string>
<string name="games_runtime_ready">● 実行環境の準備完了</string>
<string name="games_internal">内部ストレージ</string>
-1
View File
@@ -1121,7 +1121,6 @@
<string name="games_never_played">플레이한 적 없음</string>
<string name="games_runtime_busy_percent">런타임 사용 중 · %1$d%%</string>
<string name="games_runtime_busy">런타임 사용 중</string>
<string name="games_runtime_first_play">처음 \"Steam 실행\" 시 런타임 설치</string>
<string name="games_runtime_update">런타임 업데이트 있음</string>
<string name="games_runtime_ready">● 런타임 준비됨</string>
<string name="games_internal">내부 저장 공간</string>
-1
View File
@@ -1119,7 +1119,6 @@
<string name="games_never_played">Belum pernah dimainkan</string>
<string name="games_runtime_busy_percent">Masa jalan sibuk · %1$d%%</string>
<string name="games_runtime_busy">Masa jalan sibuk</string>
<string name="games_runtime_first_play">Masa jalan dipasang pada Main pertama</string>
<string name="games_runtime_update">Kemas kini masa jalan tersedia</string>
<string name="games_runtime_ready">● Masa jalan sedia</string>
<string name="games_internal">Storan dalaman</string>
-1
View File
@@ -1125,7 +1125,6 @@
<string name="games_never_played">Aldri spilt</string>
<string name="games_runtime_busy_percent">Kjøretid opptatt · %1$d%%</string>
<string name="games_runtime_busy">Kjøretid opptatt</string>
<string name="games_runtime_first_play">Kjøretiden installeres ved første Spill</string>
<string name="games_runtime_update">Kjøretidsoppdatering tilgjengelig</string>
<string name="games_runtime_ready">● Kjøretid klar</string>
<string name="games_internal">Intern lagring</string>
-1
View File
@@ -1125,7 +1125,6 @@
<string name="games_never_played">Nooit gespeeld</string>
<string name="games_runtime_busy_percent">Runtime bezig · %1$d%%</string>
<string name="games_runtime_busy">Runtime bezig</string>
<string name="games_runtime_first_play">Runtime wordt geïnstalleerd bij de eerste keer Spelen</string>
<string name="games_runtime_update">Runtime-update beschikbaar</string>
<string name="games_runtime_ready">● Runtime gereed</string>
<string name="games_internal">Interne opslag</string>
-1
View File
@@ -1137,7 +1137,6 @@
<string name="games_never_played">Nigdy nie grano</string>
<string name="games_runtime_busy_percent">Środowisko zajęte · %1$d%%</string>
<string name="games_runtime_busy">Środowisko zajęte</string>
<string name="games_runtime_first_play">Środowisko instaluje się przy pierwszym uruchomieniu</string>
<string name="games_runtime_update">Dostępna aktualizacja środowiska</string>
<string name="games_runtime_ready">● Środowisko gotowe</string>
<string name="games_internal">Pamięć wewnętrzna</string>
@@ -1123,7 +1123,6 @@
<string name="games_never_played">Nunca jogado</string>
<string name="games_runtime_busy_percent">Ambiente de execução ocupado · %1$d%%</string>
<string name="games_runtime_busy">Ambiente de execução ocupado</string>
<string name="games_runtime_first_play">O ambiente de execução é instalado ao tocar em Jogar pela primeira vez</string>
<string name="games_runtime_update">Atualização do ambiente de execução disponível</string>
<string name="games_runtime_ready">● Ambiente de execução pronto</string>
<string name="games_internal">Armazenamento interno</string>
-1
View File
@@ -1123,7 +1123,6 @@
<string name="games_never_played">Nunca jogado</string>
<string name="games_runtime_busy_percent">Runtime ocupado · %1$d%%</string>
<string name="games_runtime_busy">Runtime ocupado</string>
<string name="games_runtime_first_play">O runtime é instalado no primeiro Jogar</string>
<string name="games_runtime_update">Atualização do runtime disponível</string>
<string name="games_runtime_ready">● Runtime pronto</string>
<string name="games_internal">Armazenamento interno</string>
-1
View File
@@ -1131,7 +1131,6 @@
<string name="games_never_played">Niciodată jucat</string>
<string name="games_runtime_busy_percent">Mediu de execuție ocupat · %1$d%%</string>
<string name="games_runtime_busy">Mediu de execuție ocupat</string>
<string name="games_runtime_first_play">Mediul de execuție se instalează la prima apăsare pe Play</string>
<string name="games_runtime_update">Actualizare disponibilă pentru mediul de execuție</string>
<string name="games_runtime_ready">● Mediu de execuție pregătit</string>
<string name="games_internal">Stocare internă</string>
-1
View File
@@ -1139,7 +1139,6 @@
<string name="games_never_played">Никогда не запускалась</string>
<string name="games_runtime_busy_percent">Среда выполнения занята · %1$d%%</string>
<string name="games_runtime_busy">Среда выполнения занята</string>
<string name="games_runtime_first_play">Среда выполнения установится при первом запуске игры</string>
<string name="games_runtime_update">Доступно обновление среды выполнения</string>
<string name="games_runtime_ready">● Среда выполнения готова</string>
<string name="games_internal">Внутреннее хранилище</string>
-1
View File
@@ -1125,7 +1125,6 @@
<string name="games_never_played">Aldrig spelat</string>
<string name="games_runtime_busy_percent">Körmiljö upptagen · %1$d %%</string>
<string name="games_runtime_busy">Körmiljö upptagen</string>
<string name="games_runtime_first_play">Körmiljön installeras första gången du trycker på Play</string>
<string name="games_runtime_update">Uppdatering av körmiljön tillgänglig</string>
<string name="games_runtime_ready">● Körmiljö redo</string>
<string name="games_internal">Internt lagringsutrymme</string>
-1
View File
@@ -1119,7 +1119,6 @@
<string name="games_never_played">ยังไม่เคยเล่น</string>
<string name="games_runtime_busy_percent">รันไทม์กำลังทำงาน · %1$d%%</string>
<string name="games_runtime_busy">รันไทม์กำลังทำงาน</string>
<string name="games_runtime_first_play">รันไทม์จะติดตั้งเมื่อกด Play ครั้งแรก</string>
<string name="games_runtime_update">มีอัปเดตรันไทม์</string>
<string name="games_runtime_ready">● รันไทม์พร้อมใช้งาน</string>
<string name="games_internal">พื้นที่จัดเก็บภายใน</string>
-1
View File
@@ -1117,7 +1117,6 @@
<string name="games_never_played">Hiç oynanmadı</string>
<string name="games_runtime_busy_percent">Çalışma ortamı meşgul · %1$d%%</string>
<string name="games_runtime_busy">Çalışma ortamı meşgul</string>
<string name="games_runtime_first_play">Çalışma ortamı ilk Oyna\'da yüklenir</string>
<string name="games_runtime_update">Çalışma ortamı güncellemesi var</string>
<string name="games_runtime_ready">● Çalışma ortamı hazır</string>
<string name="games_internal">Dahili depolama</string>
-1
View File
@@ -1137,7 +1137,6 @@
<string name="games_never_played">Ще не грали</string>
<string name="games_runtime_busy_percent">Середовище зайняте · %1$d%%</string>
<string name="games_runtime_busy">Середовище зайняте</string>
<string name="games_runtime_first_play">Середовище встановлюється під час першого натискання «Грати»</string>
<string name="games_runtime_update">Є оновлення середовища</string>
<string name="games_runtime_ready">● Середовище готове</string>
<string name="games_internal">Внутрішнє сховище</string>
-1
View File
@@ -1119,7 +1119,6 @@
<string name="games_never_played">Chưa chơi bao giờ</string>
<string name="games_runtime_busy_percent">Runtime đang bận · %1$d%%</string>
<string name="games_runtime_busy">Runtime đang bận</string>
<string name="games_runtime_first_play">Runtime sẽ cài ở lần Play đầu tiên</string>
<string name="games_runtime_update">Có cập nhật runtime</string>
<string name="games_runtime_ready">● Runtime đã sẵn sàng</string>
<string name="games_internal">Bộ nhớ trong</string>
@@ -1204,7 +1204,6 @@
<string name="games_never_played">从未游玩</string>
<string name="games_runtime_busy_percent">运行时繁忙 · %1$d%%</string>
<string name="games_runtime_busy">运行时繁忙</string>
<string name="games_runtime_first_play">运行时在首次“游玩”时安装</string>
<string name="games_runtime_update">运行时有可用更新</string>
<string name="games_runtime_ready">● 运行时就绪</string>
<string name="games_internal">内部存储</string>
@@ -1121,7 +1121,6 @@
<string name="games_never_played">從未玩過</string>
<string name="games_runtime_busy_percent">運行環境繁忙 · %1$d%%</string>
<string name="games_runtime_busy">運行環境繁忙</string>
<string name="games_runtime_first_play">首次開啟 Steam 時安裝運行環境</string>
<string name="games_runtime_update">運行環境有可用更新</string>
<string name="games_runtime_ready">● 運行環境已就緒</string>
<string name="games_internal">內部儲存空間</string>
@@ -1121,7 +1121,6 @@
<string name="games_never_played">從未執行</string>
<string name="games_runtime_busy_percent">執行環境繁忙 · %1$d%%</string>
<string name="games_runtime_busy">執行環境繁忙</string>
<string name="games_runtime_first_play">首次點擊「執行」時安裝執行環境</string>
<string name="games_runtime_update">執行環境有可用更新</string>
<string name="games_runtime_ready">● 執行環境已就緒</string>
<string name="games_internal">內部儲存空間</string>
-1
View File
@@ -1274,7 +1274,6 @@
<string name="games_never_played">Never played</string>
<string name="games_runtime_busy_percent">Runtime busy · %1$d%%</string>
<string name="games_runtime_busy">Runtime busy</string>
<string name="games_runtime_first_play">Runtime installs on first Play</string>
<string name="games_runtime_update">Runtime update available</string>
<string name="games_runtime_ready">● Runtime ready</string>
<string name="games_internal">Internal storage</string>
@@ -32,6 +32,24 @@ class DualScreenTest {
assertFalse(DualScreen.isBuiltIn(null, "Pixel 8"))
}
@Test fun aSecondPanelNeedsATouchscreenOfItsOwnSize() {
val top = 1920 to 1080
val bottom = 1280 to 960
assertTrue(DualScreen.hasOwnTouchPanel(bottom, top, listOf(1920 to 1080, 1280 to 960)))
assertTrue(DualScreen.hasOwnTouchPanel(bottom, top, listOf(1080 to 1920, 960 to 1280)))
assertTrue(DualScreen.hasOwnTouchPanel(bottom, top, listOf(1920 to 1080, 1279 to 959)))
assertFalse(DualScreen.hasOwnTouchPanel(bottom, top, listOf(1920 to 1080)))
assertFalse(DualScreen.hasOwnTouchPanel(bottom, top, emptyList()))
}
@Test fun aPhantomPanelTheSizeOfTheMainScreenIsNotASecondScreen() {
val main = 1920 to 1080
assertFalse(DualScreen.hasOwnTouchPanel(main, main, listOf(1920 to 1080)))
assertFalse(DualScreen.hasOwnTouchPanel(main, main, listOf(1080 to 1920)))
assertTrue(DualScreen.hasOwnTouchPanel(main, main, listOf(1920 to 1080, 1920 to 1080)))
assertTrue(DualScreen.hasOwnTouchPanel(main, null, listOf(1920 to 1080)))
}
@Test fun oneScreenDevicesGetNoSecondScreenInAnyMode() {
for (mode in DualScreen.modes) {
SessionPrefs.setDualScreenMode(context, mode)
@@ -62,6 +62,32 @@ class TwoFingerGesturesTest {
assertEquals(listOf("cancel", "start 450.0,260.0", "scroll 0.0,60.0", "end"), calls)
}
@Test fun aFingerLandingAgainDuringAScrollDoesNotJump() {
touch(MotionEvent.ACTION_DOWN, 0, a)
time += 20
touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b)
time += 20
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 260f), 2 to (500f to 260f))
assertTrue(touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 260f), 2 to (500f to 260f)))
assertTrue(touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 250f)))
assertTrue(touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 250f), 3 to (800f to 600f)))
assertTrue(touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 230f), 3 to (800f to 580f)))
assertEquals(listOf("cancel", "start 450.0,260.0", "scroll 0.0,20.0"), calls)
}
@Test fun aThirdFingerLiftingDuringAScrollKeepsTheRemainingMidpoint() {
val c = 3 to (450f to 500f)
touch(MotionEvent.ACTION_DOWN, 0, a)
time += 20
touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b)
time += 20
touch(MotionEvent.ACTION_MOVE, 0, 1 to (400f to 260f), 2 to (500f to 260f))
assertTrue(touch(MotionEvent.ACTION_POINTER_DOWN, 2, 1 to (400f to 260f), 2 to (500f to 260f), c))
assertTrue(touch(MotionEvent.ACTION_POINTER_UP, 0, 1 to (400f to 260f), 2 to (500f to 260f), c))
assertTrue(touch(MotionEvent.ACTION_MOVE, 0, 2 to (500f to 250f), c))
assertEquals(listOf("cancel", "start 450.0,260.0", "scroll 0.0,5.0"), calls)
}
@Test fun pinchPassesThroughForZoom() {
touch(MotionEvent.ACTION_DOWN, 0, a)
time += 20
@@ -94,4 +94,12 @@ class DesktopFileRemovalTest {
assertFalse(File(root, "var/lib/pacman/sync/droiddeck.db").exists())
assertFalse(File(root, "var/lib/pacman/droiddeck-desktop").exists())
}
@Test fun aSymlinkedSyncDirectoryIsNotFollowed() {
val outside = File(dir, "outside/droiddeck.db").apply { parentFile.mkdirs(); writeText("keep") }
File(root, "var/lib/pacman/local").mkdirs()
Files.createSymbolicLink(File(root, "var/lib/pacman/sync").toPath(), outside.parentFile.toPath())
DesktopFileRemoval.removeRecords(root, emptySet())
assertEquals("keep", outside.readText())
}
}
@@ -17,6 +17,16 @@ class OutputPacingTest {
assertEquals(30, SessionPrefs.compositorFpsLimit(60, 30))
}
@Test fun pictureInPictureHoldsTheSessionToThirty() {
assertEquals(SessionPrefs.PIP_FPS, SessionPrefs.compositorFpsLimit(0, pip = true))
assertEquals(SessionPrefs.PIP_FPS, SessionPrefs.compositorFpsLimit(0, 60, pip = true))
assertEquals(20, SessionPrefs.compositorFpsLimit(0, 20, pip = true))
}
@Test fun pictureInPictureKeepsTheGlassesRate() {
assertEquals(60, SessionPrefs.compositorFpsLimit(60, pip = true))
}
@Test fun mirroringKeepsTheGlassesRate() {
assertEquals(60, SessionPrefs.compositorFpsLimit(60))
}
@@ -1,6 +1,8 @@
package com.droiddeck.launcher.session
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.AbstractExecutorService
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.TimeUnit
@@ -168,6 +170,40 @@ class SessionSuspendControllerTest {
assertFalse(fixture.signals.drop(before).any { it.pid == helper.pid })
}
@Test fun frozenTimeIsAddedToTheGuestClockBeforeItContinues() {
val fixture = fixture(17)
fixture.clock.writeBytes(shift(5_000_000L))
fixture.controller.freeze { assertTrue(it) }
fixture.now += 90_000L
fixture.controller.resume { assertTrue(it) }
val expected = 5_000_000L + 90_000L * 1_000_000L
assertEquals(expected, fixture.clockAtContinue)
assertEquals(expected, shift(fixture.clock))
fixture.controller.resume { assertTrue(it) }
assertEquals(expected, shift(fixture.clock))
fixture.controller.freeze { assertTrue(it) }
fixture.now += 1_000L
fixture.controller.closeAndResume {}
assertEquals(expected + 1_000L * 1_000_000L, shift(fixture.clock))
}
@Test fun rolledBackFreezeLeavesTheGuestClockAlone() {
val fixture = fixture(17)
fixture.clock.writeBytes(shift(0L))
fixture.neverStop = true
fixture.controller.freeze { assertFalse(it) }
fixture.controller.resume { }
assertEquals(0L, shift(fixture.clock))
}
@Test fun missingClockFileIsNotCreated() {
val fixture = fixture(17)
fixture.controller.freeze { assertTrue(it) }
fixture.now += 5_000L
fixture.controller.resume { assertTrue(it) }
assertFalse(fixture.clock.exists())
}
@Test fun timeoutRollsBackAllKnownProcessesAndAudio() {
val fixture = fixture(17)
fixture.neverStop = true
@@ -312,6 +348,10 @@ class SessionSuspendControllerTest {
assertEquals(0, fixture.audioSuspends)
}
private fun shift(value: Long) = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(value).array()
private fun shift(file: File) = ByteBuffer.wrap(file.readBytes()).order(ByteOrder.LITTLE_ENDIAN).long
private fun fixture(count: Int, executor: QueueExecutor = InlineExecutor()) =
Fixture(temporary.newFolder(), temporary.newFolder(), count, executor)
@@ -337,6 +377,8 @@ class SessionSuspendControllerTest {
var rootGone = false
var afterSleep: (() -> Unit)? = null
val control = File(tmp, ".bl-zram")
val clock = File(tmp, ".bl-clock")
var clockAtContinue: Long? = null
val pagedOut = mutableListOf<Triple<Int, Long, Long>>()
private var gameResidentKb = 4_000_000L
private var gameSwapKb = 0L
@@ -349,6 +391,8 @@ class SessionSuspendControllerTest {
{ rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++ },
proc, ::signal, ::threadSignal, ::sleep, { now }, executor,
zramControl = control,
clockControl = clock,
nowNanos = { now * 1_000_000L },
pagedOut = { processes, unacknowledged, resident, swap, _, _ ->
pagedOut += Triple(processes, resident, swap)
this.unacknowledged = unacknowledged
@@ -369,6 +413,9 @@ class SessionSuspendControllerTest {
} else if (signal == URG) {
pagingOut = true
} else if (signal == CONT) {
if (clockAtContinue == null && clock.isFile) {
clockAtContinue = ByteBuffer.wrap(clock.readBytes()).order(ByteOrder.LITTLE_ENDIAN).long
}
continuing = true
if (!(pid == GAME && blockGameContinue)) group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
}
@@ -0,0 +1,35 @@
package com.droiddeck.launcher.session
import android.content.Context
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class ShaderPrecachePrefsTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
@Before fun reset() {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
SessionPrefs.steamRoot(context, SessionPrefs.steamClientArch(context)).deleteRecursively()
}
@Test fun clientWithoutConfigStartsWithPrecachingOff() {
assertEquals(false, SessionPrefs.pendingShaderPrecache(context))
assertEquals(false, SessionPrefs.shaderPrecache(context))
}
@Test fun existingConfigKeepsTheClientsChoice() {
val config = SessionPrefs.steamRoot(context, SessionPrefs.steamClientArch(context)).resolve("config/config.vdf")
config.parentFile!!.mkdirs()
config.writeText("\"InstallConfigStore\" {}")
assertNull(SessionPrefs.pendingShaderPrecache(context))
assertEquals(true, SessionPrefs.shaderPrecache(context))
}
}
@@ -0,0 +1,56 @@
package com.droiddeck.launcher.session
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
class SteamIdleSleepTest {
@get:Rule val temp = TemporaryFolder()
private val keys = listOf(
"IdleSuspendBatterySeconds", "IdleSuspendACSeconds",
)
private fun home(vararg steamBody: String): File = temp.newFolder().also {
File(it, "config").mkdirs()
File(it, "config/config.vdf").writeText(
"\"InstallConfigStore\"\n{\n\t\"Software\"\n\t{\n\t\t\"Valve\"\n\t\t{\n\t\t\t\"Steam\"\n\t\t\t{\n" +
steamBody.joinToString("") + "\t\t\t}\n\t\t}\n\t}\n}\n",
)
}
private fun text(home: File) = File(home, "config/config.vdf").readText()
private fun value(text: String, key: String) = Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
@Test fun freshClientGetsBothSleepTimersDisabled() {
val home = home()
assertTrue(SessionFiles.disableIdleSleep(home))
keys.forEach { assertEquals(it, "0", value(text(home), it)) }
}
@Test fun existingSleepTimersAreReplacedBesideTheOtherSettings() {
val home = home(
"\t\t\t\t\"system\"\n\t\t\t\t{\n\t\t\t\t\t\"IdleSuspendACSeconds\"\t\t\"900\"\n" +
"\t\t\t\t\t\"IdleScreensaverACSeconds\"\t\t\"300\"\n\t\t\t\t\t\"IdleBacklightDimBatterySeconds\"\t\t\"120\"\n\t\t\t\t}\n",
)
assertTrue(SessionFiles.disableIdleSleep(home))
keys.forEach { assertEquals(it, "0", value(text(home), it)) }
assertEquals("300", value(text(home), "IdleScreensaverACSeconds"))
assertEquals("120", value(text(home), "IdleBacklightDimBatterySeconds"))
}
@Test fun aChoiceMadeInSteamIsResetAtTheNextSession() {
val home = home()
SessionFiles.disableIdleSleep(home)
File(home, "config/config.vdf").writeText(text(home).replace("\"IdleSuspendACSeconds\"\t\t\"0\"", "\"IdleSuspendACSeconds\"\t\t\"600\""))
assertTrue(SessionFiles.disableIdleSleep(home))
assertEquals("0", value(text(home), "IdleSuspendACSeconds"))
}
@Test fun clientWithoutAConfigIsRetriedNextSession() {
val home = temp.newFolder()
assertFalse(SessionFiles.disableIdleSleep(home))
}
}
@@ -1,22 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Test
class SteamUiPacingTest {
@Test fun aSixtyOrNinetyHertzScreenIsLeftUncapped() {
assertEquals(0, SessionPrefs.steamUiFpsLimit(60f))
assertEquals(0, SessionPrefs.steamUiFpsLimit(59.94f))
assertEquals(0, SessionPrefs.steamUiFpsLimit(90f))
}
@Test fun fasterScreensGetAnEvenDivisorOfTheirRefresh() {
assertEquals(60, SessionPrefs.steamUiFpsLimit(120f))
assertEquals(60, SessionPrefs.steamUiFpsLimit(119.99f))
assertEquals(60, SessionPrefs.steamUiFpsLimit(120.00001f))
assertEquals(72, SessionPrefs.steamUiFpsLimit(144.00002f))
assertEquals(82, SessionPrefs.steamUiFpsLimit(165f))
assertEquals(61, SessionPrefs.steamUiFpsLimit(185.00002f))
assertEquals(60, SessionPrefs.steamUiFpsLimit(240f))
}
}
@@ -22,6 +22,7 @@ import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
@@ -72,6 +73,56 @@ class SessionSecondScreenTest {
compose.onNodeWithText(context.getString(R.string.second_mode_keyboard_trackpad)).assertDoesNotExist()
}
@Test fun provisionalBottomScreenPanelSettlesOnlyOnceTheSessionIsInFront() {
SessionState.mode = SessionService.MODE_STEAM
val previousMode = SessionState.secondScreenMode
val previousProvisional = SessionState.secondScreenProvisional
SessionState.secondScreenMode = SecondScreenMode.NONE
try {
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val pip: MutableState<Boolean> = ReflectionHelpers.getField(activity, "pipUi\$delegate")
fun settle() = ReflectionHelpers.callInstanceMethod<Unit>(activity, "settleDualScreenControls")
SessionState.secondScreenProvisional = true
ReflectionHelpers.setField(activity, "started", true)
pip.value = true
settle()
assertTrue(SessionState.secondScreenProvisional)
pip.value = false
ReflectionHelpers.setField(activity, "started", false)
settle()
assertTrue(SessionState.secondScreenProvisional)
ReflectionHelpers.setField(activity, "started", true)
settle()
assertFalse(SessionState.secondScreenProvisional)
} finally {
SessionState.secondScreenMode = previousMode
SessionState.secondScreenProvisional = previousProvisional
}
}
@Test fun terminalOpenedBeforeItWasReadyIsRetriedButOtherPanelsAreLeftAlone() {
SessionState.mode = SessionService.MODE_STEAM
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
val panel = SecondScreenPresentation(activity, display, { _, _, _, _ -> }, { _, _ -> }, {}, {}, {}, {})
try {
panel.show()
panel.showMode(SecondScreenMode.KEYBOARD_TRACKPAD)
val root = panel.window!!.decorView
val trackpad = descendants(root).toList()
panel.retryTerminal()
assertEquals(trackpad, descendants(root).toList())
panel.showMode(SecondScreenMode.TERMINAL)
val notReady = context.getString(R.string.second_terminal_not_ready)
val before = descendants(root).filter { (it as? TextView)?.text == notReady }.single()
panel.retryTerminal()
val after = descendants(root).filter { (it as? TextView)?.text == notReady }.single()
assertTrue(before !== after)
} finally {
panel.closeControls()
}
}
@Test fun desktopTrackpadOmitsSteamShortcuts() = checkShortcuts(steam = false)
@Test fun steamTrackpadKeepsWorkingSteamShortcuts() = checkShortcuts(steam = true)
@@ -322,7 +322,14 @@ def wallpaper_bmp(width, height):
def reg_value(reg, key, name, value):
line = '"%s"="%s"' % (name, value.replace("\\", "\\\\").replace('"', '\\"'))
return reg_line(reg, key, name, '"%s"="%s"' % (name, value.replace("\\", "\\\\").replace('"', '\\"')))
def reg_dword(reg, key, name, number):
return reg_line(reg, key, name, '"%s"=dword:%08x' % (name, number))
def reg_line(reg, key, name, line):
try:
with open(reg, encoding="utf-8", errors="replace") as f:
rows = f.read().splitlines()
@@ -347,6 +354,16 @@ def desktop_size():
return 1280, 720
def desktop_dpi():
width, height = desktop_size()
return 96 * max(4, int(min(width / 1920.0, height / 1080.0) * 4)) // 4
def dpi(root):
reg = os.path.join(prefix(root), "pfx", "user.reg")
return os.path.isfile(reg) and reg_dword(reg, DESKTOP_KEY, "LogPixels", desktop_dpi())
def wallpaper(root):
width, height = desktop_size()
shrink = min(1.0, WALLPAPER_MAX[0] / width, WALLPAPER_MAX[1] / height)
@@ -492,6 +509,10 @@ def configure(root, library=None):
wallpaper(root)
except OSError as error:
say("Battle.net's desktop wallpaper not set: %s" % error)
try:
dpi(root)
except OSError as error:
say("Battle.net's desktop scale not set: %s" % error)
wow_settings(root)
if change == "first":
say("wrote Battle.net's first config: hardware acceleration off, streaming off, closing itself as it launches a game, "
@@ -99,6 +99,8 @@ clear_stale_tmp() {
[ -z "${BL_INSIDE:-}" ] && clear_stale_tmp
if [ -z "${BL_INSIDE:-}" ]; then
if [ "${BL_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.bl-zram; else rm -f /tmp/.bl-zram; fi
rm -f /tmp/.bl-clock
head -c 8 /dev/zero > /tmp/.bl-clock
fi
steam_devtools() {
@@ -1439,6 +1441,12 @@ case $mode in
set --
continue
fi
if [ "$steam_x64" = 1 ] && [ "$rc" -eq 132 ] && [ -z "${_bl_x64_sigill:-}" ]; then
_bl_x64_sigill=1
echo "== steam: the x86-64 client stopped on an illegal instruction after it updated itself; starting it again once"
set --
continue
fi
[ "$rc" -eq 42 ] || break
if steam_update_stuck "$steam_ran"; then
echo "== steam: asked to restart for an update $steam_updates times and it is not installing; the session stops here rather than loop"
+314
View File
@@ -0,0 +1,314 @@
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/futex.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdint.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/timerfd.h>
#include <time.h>
#include <unistd.h>
#if defined(__aarch64__) || defined(BL_CLOCK_ANY_ARCH)
#ifndef CP_CTL
#define CP_CTL "/tmp/.bl-clock"
#endif
#ifndef FUTEX_LOCK_PI2
#define FUTEX_LOCK_PI2 13
#endif
#define CP_FDS 65536
static const int64_t *cp_shift;
static int cp_state;
static size_t cp_cond_byte;
static unsigned char cp_cond_mask;
static unsigned char cp_fds[CP_FDS / 8];
static int (*cp_gettime)(clockid_t, struct timespec *);
static int (*cp_nanosleep)(clockid_t, int, const struct timespec *, struct timespec *);
static int (*cp_cond_timedwait)(pthread_cond_t *, pthread_mutex_t *, const struct timespec *);
static int (*cp_cond_clockwait)(pthread_cond_t *, pthread_mutex_t *, clockid_t, const struct timespec *);
static int (*cp_sem_clockwait)(sem_t *, clockid_t, const struct timespec *);
static int (*cp_mutex_clocklock)(pthread_mutex_t *, clockid_t, const struct timespec *);
static int (*cp_rdlock)(pthread_rwlock_t *, clockid_t, const struct timespec *);
static int (*cp_wrlock)(pthread_rwlock_t *, clockid_t, const struct timespec *);
static int (*cp_join)(pthread_t, void **, clockid_t, const struct timespec *);
static int (*cp_tfd_create)(int, int);
static int (*cp_tfd_settime)(int, int, const struct itimerspec *, struct itimerspec *);
static void *cp_real(const char *name) {
return dlsym(RTLD_NEXT, name);
}
#define CP_REAL(var, name) (var ? var : (var = cp_real(name)))
static int cp_find_cond_bit(void) {
pthread_condattr_t attr;
pthread_cond_t mono, real;
const unsigned char *a = (const unsigned char *)&mono, *b = (const unsigned char *)&real;
int found = 0;
memset(&mono, 0, sizeof(mono));
memset(&real, 0, sizeof(real));
if (pthread_condattr_init(&attr) != 0) return 0;
if (pthread_condattr_setclock(&attr, CLOCK_MONOTONIC) == 0 && pthread_cond_init(&mono, &attr) == 0) {
if (pthread_cond_init(&real, NULL) == 0) {
for (size_t i = 0; i < sizeof(pthread_cond_t); i++) {
unsigned char diff = a[i] ^ b[i];
if (!diff) continue;
if (found || (diff & (diff - 1))) {
found = -1;
break;
}
cp_cond_byte = i;
cp_cond_mask = diff;
found = 1;
}
pthread_cond_destroy(&real);
}
pthread_cond_destroy(&mono);
}
pthread_condattr_destroy(&attr);
return found == 1;
}
static void cp_init(void) {
struct stat st;
void *map;
int fd;
if (strcmp(program_invocation_short_name, "plasmashell") != 0) return;
if (!cp_find_cond_bit()) return;
fd = open(CP_CTL, O_RDONLY | O_CLOEXEC);
if (fd < 0) return;
if (fstat(fd, &st) != 0 || st.st_size < (off_t)sizeof(int64_t)) {
close(fd);
return;
}
map = mmap(NULL, sizeof(int64_t), PROT_READ, MAP_SHARED, fd, 0);
close(fd);
if (map != MAP_FAILED) __atomic_store_n(&cp_shift, (const int64_t *)map, __ATOMIC_RELEASE);
}
static int64_t cp_offset(void) {
const int64_t *shift;
int state = __atomic_load_n(&cp_state, __ATOMIC_ACQUIRE);
if (state == 0) {
int expected = 0;
if (__atomic_compare_exchange_n(&cp_state, &expected, 1, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) {
cp_init();
__atomic_store_n(&cp_state, 2, __ATOMIC_RELEASE);
}
return 0;
}
if (state != 2) return 0;
shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE);
if (!shift) return 0;
int64_t value = __atomic_load_n(shift, __ATOMIC_RELAXED);
return value > 0 ? value : 0;
}
__attribute__((constructor)) static void cp_start(void) {
cp_offset();
}
static int cp_mono(clockid_t clock) {
return clock == CLOCK_MONOTONIC || clock == CLOCK_MONOTONIC_RAW || clock == CLOCK_MONOTONIC_COARSE;
}
static void cp_move(struct timespec *ts, int64_t ns) {
int64_t total = (int64_t)ts->tv_nsec + ns % 1000000000LL;
ts->tv_sec += (time_t)(ns / 1000000000LL);
while (total < 0) {
total += 1000000000LL;
ts->tv_sec--;
}
while (total >= 1000000000LL) {
total -= 1000000000LL;
ts->tv_sec++;
}
ts->tv_nsec = (long)total;
}
static const struct timespec *cp_later(const struct timespec *ts, struct timespec *out, int64_t shift) {
if (!ts || !shift) return ts;
*out = *ts;
cp_move(out, shift);
return out;
}
static void cp_mark(int fd, int mono) {
if (fd < 0 || fd >= CP_FDS) return;
if (mono) __atomic_or_fetch(&cp_fds[fd / 8], (unsigned char)(1u << (fd % 8)), __ATOMIC_RELAXED);
else __atomic_and_fetch(&cp_fds[fd / 8], (unsigned char)~(1u << (fd % 8)), __ATOMIC_RELAXED);
}
static int cp_marked(int fd) {
return fd >= 0 && fd < CP_FDS && (__atomic_load_n(&cp_fds[fd / 8], __ATOMIC_RELAXED) & (1u << (fd % 8)));
}
static int cp_cond_mono(const pthread_cond_t *cond) {
return (((const volatile unsigned char *)cond)[cp_cond_byte] & cp_cond_mask) != 0;
}
int clock_gettime(clockid_t clock, struct timespec *ts) {
if (!CP_REAL(cp_gettime, "clock_gettime")) {
errno = ENOSYS;
return -1;
}
int rc = cp_gettime(clock, ts);
if (rc == 0 && cp_mono(clock)) {
int64_t shift = cp_offset();
if (shift) cp_move(ts, -shift);
}
return rc;
}
int clock_nanosleep(clockid_t clock, int flags, const struct timespec *req, struct timespec *rem) {
struct timespec moved;
if (!CP_REAL(cp_nanosleep, "clock_nanosleep")) return ENOSYS;
if ((flags & TIMER_ABSTIME) && cp_mono(clock)) req = cp_later(req, &moved, cp_offset());
return cp_nanosleep(clock, flags, req, rem);
}
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime) {
struct timespec moved;
if (!CP_REAL(cp_cond_timedwait, "pthread_cond_timedwait")) return ENOSYS;
int64_t shift = cp_offset();
if (shift && cp_cond_mono(cond)) abstime = cp_later(abstime, &moved, shift);
return cp_cond_timedwait(cond, mutex, abstime);
}
int pthread_cond_clockwait(pthread_cond_t *cond, pthread_mutex_t *mutex, clockid_t clock, const struct timespec *abstime) {
struct timespec moved;
if (!CP_REAL(cp_cond_clockwait, "pthread_cond_clockwait")) return ENOSYS;
if (cp_mono(clock)) abstime = cp_later(abstime, &moved, cp_offset());
return cp_cond_clockwait(cond, mutex, clock, abstime);
}
int sem_clockwait(sem_t *sem, clockid_t clock, const struct timespec *abstime) {
struct timespec moved;
if (!CP_REAL(cp_sem_clockwait, "sem_clockwait")) {
errno = ENOSYS;
return -1;
}
if (cp_mono(clock)) abstime = cp_later(abstime, &moved, cp_offset());
return cp_sem_clockwait(sem, clock, abstime);
}
int pthread_mutex_clocklock(pthread_mutex_t *mutex, clockid_t clock, const struct timespec *abstime) {
struct timespec moved;
if (!CP_REAL(cp_mutex_clocklock, "pthread_mutex_clocklock")) return ENOSYS;
if (cp_mono(clock)) abstime = cp_later(abstime, &moved, cp_offset());
return cp_mutex_clocklock(mutex, clock, abstime);
}
int pthread_rwlock_clockrdlock(pthread_rwlock_t *lock, clockid_t clock, const struct timespec *abstime) {
struct timespec moved;
if (!CP_REAL(cp_rdlock, "pthread_rwlock_clockrdlock")) return ENOSYS;
if (cp_mono(clock)) abstime = cp_later(abstime, &moved, cp_offset());
return cp_rdlock(lock, clock, abstime);
}
int pthread_rwlock_clockwrlock(pthread_rwlock_t *lock, clockid_t clock, const struct timespec *abstime) {
struct timespec moved;
if (!CP_REAL(cp_wrlock, "pthread_rwlock_clockwrlock")) return ENOSYS;
if (cp_mono(clock)) abstime = cp_later(abstime, &moved, cp_offset());
return cp_wrlock(lock, clock, abstime);
}
int pthread_clockjoin_np(pthread_t thread, void **result, clockid_t clock, const struct timespec *abstime) {
struct timespec moved;
if (!CP_REAL(cp_join, "pthread_clockjoin_np")) return ENOSYS;
if (cp_mono(clock)) abstime = cp_later(abstime, &moved, cp_offset());
return cp_join(thread, result, clock, abstime);
}
int timerfd_create(int clock, int flags) {
if (!CP_REAL(cp_tfd_create, "timerfd_create")) {
errno = ENOSYS;
return -1;
}
int fd = cp_tfd_create(clock, flags);
cp_mark(fd, cp_mono(clock));
return fd;
}
static const struct itimerspec *cp_timer(int fd, int flags, const struct itimerspec *value, struct itimerspec *out) {
int64_t shift;
if (!value || !(flags & TFD_TIMER_ABSTIME) || !cp_marked(fd)) return value;
if ((value->it_value.tv_sec == 0 && value->it_value.tv_nsec == 0) || !(shift = cp_offset())) return value;
*out = *value;
cp_move(&out->it_value, shift);
return out;
}
int timerfd_settime(int fd, int flags, const struct itimerspec *value, struct itimerspec *old) {
struct itimerspec moved;
if (!CP_REAL(cp_tfd_settime, "timerfd_settime")) {
errno = ENOSYS;
return -1;
}
return cp_tfd_settime(fd, flags, cp_timer(fd, flags, value, &moved), old);
}
__attribute__((visibility("hidden"))) int bl_clock_syscall(long number, const long *args, long (*real)(long, ...), long *ret) {
struct timespec moved;
struct itimerspec timer;
int64_t shift;
if (number == SYS_clock_gettime) {
*ret = real(number, args[0], args[1]);
if (*ret == 0 && args[1] && cp_mono((clockid_t)args[0]) && (shift = cp_offset()))
cp_move((struct timespec *)args[1], -shift);
return 1;
}
if (number == SYS_timerfd_create) {
*ret = real(number, args[0], args[1]);
cp_mark((int)*ret, cp_mono((clockid_t)args[0]));
return 1;
}
if (number == SYS_timerfd_settime) {
const struct itimerspec *value = cp_timer((int)args[0], (int)args[1], (const struct itimerspec *)args[2], &timer);
if (value == (const struct itimerspec *)args[2]) return 0;
*ret = real(number, args[0], args[1], (long)value, args[3]);
return 1;
}
if (number == SYS_clock_nanosleep) {
if (!((int)args[1] & TIMER_ABSTIME) || !cp_mono((clockid_t)args[0]) || !args[2] || !(shift = cp_offset())) return 0;
*ret = real(number, args[0], args[1], (long)cp_later((const struct timespec *)args[2], &moved, shift), args[3]);
return 1;
}
if (number == SYS_futex) {
int op = (int)args[1];
int cmd = op & FUTEX_CMD_MASK;
if (op & FUTEX_CLOCK_REALTIME) return 0;
if (cmd != FUTEX_WAIT_BITSET && cmd != FUTEX_WAIT_REQUEUE_PI && cmd != FUTEX_LOCK_PI2) return 0;
if (!args[3] || !(shift = cp_offset())) return 0;
*ret = real(number, args[0], args[1], args[2], (long)cp_later((const struct timespec *)args[3], &moved, shift), args[4], args[5]);
return 1;
}
#ifdef SYS_futex_waitv
if (number == SYS_futex_waitv) {
if (!args[3] || (clockid_t)args[4] != CLOCK_MONOTONIC || !(shift = cp_offset())) return 0;
*ret = real(number, args[0], args[1], args[2], (long)cp_later((const struct timespec *)args[3], &moved, shift), args[4]);
return 1;
}
#endif
return 0;
}
#else
__attribute__((visibility("hidden"))) int bl_clock_syscall(long number, const long *args, long (*real)(long, ...), long *ret) {
(void)number;
(void)args;
(void)real;
(void)ret;
return 0;
}
#endif
+4
View File
@@ -359,6 +359,7 @@ int bl_openat2(int dirfd, const char *path, void *how, size_t size) {
}
int bl_writewatch_syscall(long number, const long *args, long (*real)(long, ...), long *rc) __attribute__((visibility("hidden")));
int bl_clock_syscall(long number, const long *args, long (*real)(long, ...), long *ret) __attribute__((visibility("hidden")));
long syscall(long number, ...) {
va_list ap;
@@ -385,6 +386,9 @@ long syscall(long number, ...) {
if (!real_syscall) {
real_syscall = (long (*)(long, ...)) dlsym(RTLD_NEXT, "syscall");
}
if (bl_clock_syscall(number, args, real_syscall, &handled)) {
return handled;
}
if (bl_writewatch_syscall(number, args, real_syscall, &handled)) {
return handled;
}
+21
View File
@@ -896,6 +896,27 @@ class LaunchTest(Harness):
self.assertEqual(image.read_bytes(), b"BM1152x720")
self.assertIn('"WallpaperStyle"="2"', (pfx / "user.reg").read_text())
def test_a_large_desktop_scales_battle_net_to_fit_it(self):
sizes = {("1280", "720"): 96, ("1920", "1080"): 96, ("2400", "1504"): 120, ("2448", "1848"): 120,
("1080", "2400"): 96, ("3840", "2160"): 192, ("2560", "1600"): 120}
for (width, height), want in sizes.items():
with mock.patch.dict(os.environ, {"BL_WIDTH": width, "BL_HEIGHT": height}):
self.assertEqual(BNET["desktop_dpi"](), want, (width, height))
def test_battle_nets_desktop_scale_is_written_once_and_follows_the_size(self):
self.install()
pfx = Path(self.root) / ("steamapps/compatdata/%s/pfx" % BNET["APP_ID"])
(pfx / "user.reg").write_text('WINE REGISTRY Version 2\n\n[Control Panel\\\\Desktop] 1\n"LogPixels"=dword:00000060\n')
with mock.patch.dict(os.environ, {"BL_WIDTH": "1280", "BL_HEIGHT": "720"}):
self.assertTrue(BNET["dpi"](self.root))
self.assertEqual((pfx / "user.reg").read_text().count("LogPixels"), 1)
with mock.patch.dict(os.environ, {"BL_WIDTH": "2448", "BL_HEIGHT": "1848"}):
self.assertTrue(BNET["dpi"](self.root))
self.assertTrue(BNET["dpi"](self.root))
reg = (pfx / "user.reg").read_text()
self.assertEqual(reg.count('"LogPixels"=dword:00000078'), 1)
self.assertTrue(reg.rstrip().endswith('"LogPixels"=dword:00000078'))
def test_an_open_battle_net_is_handed_the_game(self):
self.install()
up = self.clients()
+1 -1
View File
@@ -82,7 +82,7 @@ class CiChecksTest(unittest.TestCase):
gate = jobs['checks']
self.assertEqual(gate['name'], 'Compile and test APK')
self.assertEqual(set(gate['needs']), {'build', 'python-tests'})
self.assertIn('always()', gate['if'])
self.assertIn('!cancelled()', gate['if'])
for build, python in itertools.product(('success', 'failure', 'cancelled', 'skipped'), repeat=2):
with self.subTest(build=build, python=python):
result = subprocess.run(
+137
View File
@@ -0,0 +1,137 @@
import os
from pathlib import Path
import shutil
import struct
import subprocess
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
PROGRAM = r"""
#define _GNU_SOURCE
#include <linux/futex.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <sys/timerfd.h>
#include <time.h>
#include <unistd.h>
static int64_t ns(clockid_t clock) {
struct timespec ts;
clock_gettime(clock, &ts);
return (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
}
static struct timespec in(clockid_t clock, int64_t delay) {
int64_t t = ns(clock) + delay;
struct timespec ts = {(time_t)(t / 1000000000LL), (long)(t % 1000000000LL)};
return ts;
}
static int64_t start;
static void begin(void) { start = ns(CLOCK_BOOTTIME); }
static void end(const char *name) { printf("%s %lld\n", name, (long long)((ns(CLOCK_BOOTTIME) - start) / 1000000LL)); }
int main(void) {
const int64_t wait = 60000000LL;
printf("gap %lld\n", (long long)((ns(CLOCK_BOOTTIME) - ns(CLOCK_MONOTONIC)) / 1000000LL));
struct timespec raw;
syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &raw);
printf("rawgap %lld\n", (long long)((ns(CLOCK_BOOTTIME) - ((int64_t)raw.tv_sec * 1000000000LL + raw.tv_nsec)) / 1000000LL));
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_condattr_t attr;
pthread_cond_t mono, real;
pthread_condattr_init(&attr);
pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
pthread_cond_init(&mono, &attr);
pthread_cond_init(&real, NULL);
struct timespec ts;
pthread_mutex_lock(&mutex);
ts = in(CLOCK_MONOTONIC, wait); begin(); pthread_cond_timedwait(&mono, &mutex, &ts); end("cond_mono");
ts = in(CLOCK_REALTIME, wait); begin(); pthread_cond_timedwait(&real, &mutex, &ts); end("cond_real");
ts = in(CLOCK_MONOTONIC, wait); begin(); pthread_cond_clockwait(&real, &mutex, CLOCK_MONOTONIC, &ts); end("clockwait");
pthread_mutex_unlock(&mutex);
sem_t sem;
sem_init(&sem, 0, 0);
ts = in(CLOCK_MONOTONIC, wait); begin(); sem_clockwait(&sem, CLOCK_MONOTONIC, &ts); end("sem");
ts = in(CLOCK_MONOTONIC, wait); begin(); clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL); end("nanosleep");
int fd = timerfd_create(CLOCK_MONOTONIC, 0);
struct itimerspec it = {{0, 0}, in(CLOCK_MONOTONIC, wait)};
uint64_t ticks;
timerfd_settime(fd, TFD_TIMER_ABSTIME, &it, NULL);
begin(); if (read(fd, &ticks, sizeof(ticks)) < 0) ticks = 0; end("timerfd");
static uint32_t word;
ts = in(CLOCK_MONOTONIC, wait); begin();
syscall(SYS_futex, &word, FUTEX_WAIT_BITSET | FUTEX_PRIVATE_FLAG, 0, &ts, NULL, FUTEX_BITSET_MATCH_ANY);
end("futex");
return 0;
}
"""
SHIFT_MS = 10000
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
class ClockPausePreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temp = tempfile.TemporaryDirectory()
cls.dir = Path(cls.temp.name)
cls.control = cls.dir / "clock"
build = cls.dir / "build"
build.mkdir()
(build / "program.c").write_text(PROGRAM)
cls.preload = build / "libblsession.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-DBL_CLOCK_ANY_ARCH",
'-DCP_CTL="%s"' % cls.control, "-o", str(cls.preload),
*map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True)
cls.shell = build / "plasmashell"
subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.shell), str(build / "program.c")], check=True)
cls.other = build / "kwin_wayland"
shutil.copy(cls.shell, cls.other)
@classmethod
def tearDownClass(cls):
cls.temp.cleanup()
def run_program(self, program, shift_ms, preload=True):
self.control.write_bytes(struct.pack("<q", shift_ms * 1000000))
env = dict(os.environ)
if preload:
env["LD_PRELOAD"] = str(self.preload)
result = subprocess.run([str(program)], env=env, capture_output=True, text=True, check=True, timeout=30)
return {name: int(value) for name, value in (line.split() for line in result.stdout.splitlines())}
def test_the_shell_sees_monotonic_time_stopped_for_the_pause(self):
plain = self.run_program(self.shell, 0)
paused = self.run_program(self.shell, SHIFT_MS)
self.assertAlmostEqual(paused["gap"] - plain["gap"], SHIFT_MS, delta=50)
self.assertAlmostEqual(paused["rawgap"] - plain["rawgap"], SHIFT_MS, delta=50)
def test_timed_waits_last_as_long_as_asked_after_a_pause(self):
paused = self.run_program(self.shell, SHIFT_MS)
for name in ("cond_mono", "cond_real", "clockwait", "sem", "nanosleep", "timerfd", "futex"):
self.assertGreaterEqual(paused[name], 50, name)
self.assertLess(paused[name], 1000, name)
def test_other_programs_keep_the_real_clock(self):
plain = self.run_program(self.other, 0, preload=False)
paused = self.run_program(self.other, SHIFT_MS)
self.assertAlmostEqual(paused["gap"], plain["gap"], delta=50)
for name in ("cond_mono", "clockwait", "sem", "nanosleep", "timerfd", "futex"):
self.assertGreaterEqual(paused[name], 50, name)
self.assertLess(paused[name], 1000, name)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -319,7 +319,7 @@ class FsyncPreloadTest(unittest.TestCase):
source = base / "fsync-test.c"
source.write_text(PROGRAM)
subprocess.run(["cc", "-O2", "-Wall", "-fPIC", "-shared", "-pthread", "-o", str(cls.lib),
str(PRELOAD / "fsync.c"), str(PRELOAD / "robust.c"), str(PRELOAD / "noexec.c"), str(PRELOAD / "writewatch.c"), "-ldl"], check=True)
str(PRELOAD / "fsync.c"), str(PRELOAD / "robust.c"), str(PRELOAD / "noexec.c"), str(PRELOAD / "writewatch.c"), str(PRELOAD / "clockpause.c"), "-ldl"], check=True)
subprocess.run(["cc", "-O2", "-Wall", "-pthread", "-o", str(cls.exe), str(source)], check=True)
@classmethod
+1 -1
View File
@@ -43,7 +43,7 @@ class NoexecPreloadTest(unittest.TestCase):
cls.tmp = Path(tempfile.mkdtemp())
cls.lib = cls.tmp / "libnoexec.so"
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-pthread", "-DNOEXEC_TEST", "-o", str(cls.lib),
str(PRELOAD / "noexec.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "robust.c"), str(PRELOAD / "writewatch.c"), "-ldl"], check=True)
str(PRELOAD / "noexec.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "robust.c"), str(PRELOAD / "writewatch.c"), str(PRELOAD / "clockpause.c"), "-ldl"], check=True)
source = cls.tmp / "program.c"
source.write_text(PROGRAM)
for name in ("FEX", "game"):
+1 -1
View File
@@ -312,7 +312,7 @@ class Openat2PreloadTest(unittest.TestCase):
cls.tmp = Path(tempfile.mkdtemp())
cls.lib = cls.tmp / "libopenat2.so"
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-pthread", "-o", str(cls.lib),
str(PRELOAD / "robust.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "noexec.c"), str(PRELOAD / "writewatch.c"), "-ldl"], check=True)
str(PRELOAD / "robust.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "noexec.c"), str(PRELOAD / "writewatch.c"), str(PRELOAD / "clockpause.c"), "-ldl"], check=True)
source = cls.tmp / "openat2.c"
source.write_text(PROGRAM)
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.tmp / "openat2"), str(source), "-ldl"], check=True)
+3 -1
View File
@@ -32,6 +32,8 @@ static int64_t g_hold_missed_ns;
static int64_t g_refresh_ns = 16666667;
volatile int g_render_on_commit = 1;
volatile int g_release_unpaced = 1;
volatile int g_fps_limit;
static int64_t g_scene_due_ns;
static atomic_int g_stream_on;
static struct { unsigned ticks, ticks_late_2ms, commit_renders; int64_t tick_late_ns, tick_late_max_ns; } g_pace;
static struct { unsigned ticks; } g_perf;
@@ -204,7 +206,7 @@ class RenderOnCommitTest(unittest.TestCase):
render = extract_function(source, 'render_scene')
self.assertIn('g_rendered_tick_ns = g_tick_vsync_ns;', render)
self.assertIn('g_tick_held = 0;', render)
functions = ('commit_renders_on', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle', 'on_vsync')
functions = ('scene_held_for_limit', 'commit_renders_on', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle', 'on_vsync')
harness = PREAMBLE + '\n'.join(extract_function(source, name) for name in functions) + CHECKS
with tempfile.TemporaryDirectory(prefix='droiddeck-render-on-commit-') as folder:
path = Path(folder)
+105
View File
@@ -0,0 +1,105 @@
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
SOURCE = ROOT / 'app/src/main/cpp/waylandcomp/src/compositor.c'
def extract_function(source, name):
match = re.search(r'^static int(?:64_t)? ' + re.escape(name) + r'\([^;]*?\) \{', source, re.MULTILINE)
if match is None:
raise AssertionError(f'Missing compositor function: {name}')
cursor, depth = match.end(), 1
while depth:
depth += (source[cursor] == '{') - (source[cursor] == '}')
cursor += 1
return source[match.start():cursor]
HARNESS = r'''
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
@FUNCTIONS@
#define MS 1000000LL
static int run(int64_t refresh, int limit, int64_t jitter, int seconds) {
int renders = 0;
int64_t due = 0;
for (int64_t tick = 0; tick * refresh < seconds * 1000 * MS; tick++) {
int64_t now = 1000 * MS + tick * refresh + (tick % 2 ? jitter : -jitter);
if (scene_held_for_limit(now, due, limit, 0)) continue;
renders++;
due = scene_next_due(now, due, limit);
}
return renders;
}
int main(void) {
assert(!scene_held_for_limit(100 * MS, 0, 30, 0));
assert(!scene_held_for_limit(100 * MS, 130 * MS, 0, 0));
assert(!scene_held_for_limit(100 * MS, 130 * MS, 30, 1));
assert(scene_held_for_limit(100 * MS, 130 * MS, 30, 0));
assert(scene_held_for_limit(100 * MS, 102 * MS, 30, 0));
assert(!scene_held_for_limit(100 * MS, 101 * MS, 30, 0));
assert(!scene_held_for_limit(100 * MS, 90 * MS, 30, 0));
assert(scene_next_due(100 * MS, 0, 0) == 0);
assert(scene_next_due(100 * MS, 0, 25) == 140 * MS);
assert(scene_next_due(101 * MS, 100 * MS, 25) == 140 * MS);
assert(scene_next_due(200 * MS, 100 * MS, 25) == 240 * MS);
const struct { int64_t refresh; int limit; int expected; } cases[] = {
{8333333, 30, 300}, {8333333, 60, 600}, {16666667, 25, 250}, {16666667, 30, 300},
{10000000, 30, 300}, {11111111, 30, 300}, {6944444, 40, 400}, {16666667, 120, 600},
};
for (unsigned i = 0; i < sizeof cases / sizeof cases[0]; i++) {
int got = run(cases[i].refresh, cases[i].limit, 0, 10);
if (got > cases[i].expected + 1 || got < cases[i].expected - 2) {
fprintf(stderr, "refresh %lld limit %d: %d renders, expected %d\n",
(long long)cases[i].refresh, cases[i].limit, got, cases[i].expected);
return 1;
}
got = run(cases[i].refresh, cases[i].limit, 300000, 10);
if (got > cases[i].expected + 1 || got < cases[i].expected - 2) {
fprintf(stderr, "jittered refresh %lld limit %d: %d renders, expected %d\n",
(long long)cases[i].refresh, cases[i].limit, got, cases[i].expected);
return 1;
}
}
int fallback = run(8 * MS, 30, 0, 10);
assert(fallback <= 301 && fallback >= 290);
puts("PASS");
return 0;
}
'''
class SceneLimitHoldTest(unittest.TestCase):
def test_a_frame_limit_holds_scene_renders_to_its_rate_without_slowing_paced_frames(self):
compiler = shutil.which(os.environ.get('CC', 'cc'))
if compiler is None:
self.skipTest('A host C compiler is required')
source = SOURCE.read_text()
harness = HARNESS.replace('@FUNCTIONS@', '\n'.join(extract_function(source, name) for name in ('scene_held_for_limit', 'scene_next_due')))
with tempfile.TemporaryDirectory(prefix='droiddeck-scene-hold-') as folder:
path = Path(folder)
(path / 'hold.c').write_text(harness)
binary = path / 'hold-test'
build = subprocess.run([compiler, '-std=c11', '-Wall', '-Wextra', '-Werror', '-O2',
str(path / 'hold.c'), '-o', str(binary)],
capture_output=True, text=True)
self.assertEqual(0, build.returncode, build.stderr)
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('PASS', result.stdout.strip())
if __name__ == '__main__':
unittest.main()
+1
View File
@@ -33,6 +33,7 @@ int probe(void) {
#include <dlfcn.h>
int bl_fsync_syscall(long n, const long *a, long *r) { (void)n; (void)a; (void)r; return 0; }
int bl_writewatch_syscall(long n, const long *a, long (*real)(long, ...), long *r) { (void)n; (void)a; (void)real; (void)r; return 0; }
int bl_clock_syscall(long n, const long *a, long (*real)(long, ...), long *r) { (void)n; (void)a; (void)real; (void)r; return 0; }
#include """ + '"' + robust.as_posix() + '"' + r"""
int main(int argc, char **argv) {
assert(argc == 3);
+1
View File
@@ -108,6 +108,7 @@ libliftoff0
liblua5.4-0
libluajit-5.1-2
liblzma5
liblzo2-2
libmount1
libmp3lame0
libmpg123-0t64