Compare commits

...
Author SHA1 Message Date
maxjivi05 19b4844998 Check anti-cheat runtime bridges, apply component choices under FEX and honour MAP_FIXED_NOREPLACE above the host limit 2026-12-03 14:22:49 -05:00
maxjivi05 b1fe206215 test(game-env): build the adopted-tool wrapper through extra_wrapper_sh 2026-12-03 14:02:14 -05:00
maxjivi05 19613e6842 Keep anti-cheat games on a tool the user chose instead of moving them to x86-64 2026-12-03 13:01:38 -05:00
maxjivi05 0756e93b8e README: match the StonkGuy credit to the renumbered FEX patches 2026-12-03 13:01:38 -05:00
maxjivi05 98df621d9c Docs: describe the anti-cheat signal mask fix and the container procfs view 2026-12-03 13:01:38 -05:00
maxjivi05 ee432f444d Test the container procfs view of FEX's emulated mount tables 2026-12-03 13:01:38 -05:00
maxjivi05 58fe8bb197 FEX: order the anti-cheat series after the guest stack patch from main 2026-12-03 13:01:38 -05:00
maxjivi05 20e3e9a802 FEX: describe the container's procfs in emulated mount tables 2026-12-03 13:01:38 -05:00
maxjivi05 7648b9ae8f FEX: show the guest command line when the argument area cannot be remapped 2026-12-03 13:01:38 -05:00
maxjivi05 e16a77facb droiddeck-fex: take the runtime from an adopted tool's original manifest 2026-12-03 13:01:38 -05:00
maxjivi05 f802206917 Keep x86-64 DroidDeck-Proton builds out of the ARM64 tool list 2026-12-03 13:01:38 -05:00
maxjivi05 b11bac2539 Run games with anti-cheat files on an x86-64 DroidDeck-Proton under FEX
The Proton launchers look for Easy Anti-Cheat or BattlEye bridge files in
the game folder and, when an x86-64 DroidDeck-Proton and the matching Proton
runtime are installed, hand the launch to that Proton under FEX with the
game's own prefix. Picking the x86-64 tool directly also runs it under FEX.
DROIDDECK_ANTICHEAT=off keeps a game on ARM64.
2026-12-03 13:01:38 -05:00
maxjivi05 6a3cee3ee0 FEX: serve decoder reads from fixed guest memory above the host limit 2026-12-03 13:01:38 -05:00
maxjivi05andStonkGuy c113948dd3 FEX: map fixed guest memory above a small host address space
Co-authored-by: StonkGuy <StonkGuy@users.noreply.github.com>
2026-12-03 13:01:38 -05:00
maxjivi05 a7f3c69987 FEX: serve emulated proc files by the requested path when the host returns a memfd 2026-12-03 13:01:38 -05:00
maxjivi05 b399683502 FEX: open guest paths with the raw openat system call so host preloads cannot replace the file 2026-12-03 13:01:38 -05:00
maxjivi05andStonkGuy 57a6224fcf Credit StonkGuy in the FEX anti-cheat patches and README
Co-authored-by: StonkGuy <68372320+StonkGuy@users.noreply.github.com>
2026-12-03 13:01:38 -05:00
maxjivi05 8bdc6485c8 FEX: hand a traced program's ptrace state across exec 2026-12-03 13:01:38 -05:00
maxjivi05 faf7c7b003 FEX: open the host status file with a direct system call so preloads cannot rewrite it 2026-12-03 13:01:38 -05:00
maxjivi05 7f561f6f92 README: credit StonkGuy's FEX anti-cheat emulation 2026-12-03 13:01:38 -05:00
maxjivi05 06140b0ac4 FEX: read the host status file through the raw openat syscall 2026-12-03 13:01:38 -05:00
maxjivi05 fe95624af6 Emulate only host-architecture seccomp traps in the guest hook; report the calling thread's seccomp mode in FEX's /proc/self/status
A SIGSYS carrying another architecture's seccomp siginfo now takes its default action when the program has no handler, so a process whose emulated filter traps a syscall while SIGSYS is blocked or ignored dies as on Linux.
2026-12-03 13:01:38 -05:00
maxjivi05 3bce42724c Preloads: leave poll, ppoll and select buffers untouched when no emulated device is open
A bad user pointer now reaches the kernel and returns EFAULT instead of crashing the caller inside the wrapper.
2026-12-03 13:01:38 -05:00
maxjivi05 c36804466d FEX: list only guest mappings in /proc/<pid>/maps on hosts below 47 address bits
Credit the anti-cheat emulation source in the patch header.
2026-12-03 13:01:38 -05:00
maxjivi05 6ac2deb1d3 Guest hook: route raw execve/execveat through the exec wrapper and pass self-sent SIGSYS to the program
A program that execs with syscall(SYS_execveat, ...) bypassed the environment the
guest needs, so re-executing /proc/self/exe died in the loader. /proc/self/exe now
maps to the real program on exec as it already does on open.

A SIGSYS the program queues itself, or one from a filter for another architecture,
went to the Android-filter emulation instead of the program's handler.
2026-12-03 13:01:38 -05:00
maxjivi05 8cdb8255de FEX: emulate x86-64 ptrace, seccomp and /proc for anti-cheat launchers 2026-12-03 13:01:38 -05:00
Kurt Himebauch 7138f95c90 fix(onboarding): no wireless-debugging step on first run when the session runs outside the child-process count (#3639)
Before the runtime is installed, the rootfs has no native hook yet, so the
child-process check assumed the next session would be counted and showed
"Finish setup" for wireless debugging. The session stages the hook from the
APK before it starts, so predict the next session from the setting and the
rootfs loader instead; a runtime still to be installed will have one.
2026-12-03 12:45:41 -05:00
Kurt Himebauch 8b3cc7eb15 Wire XR keyboard text into the session input queue (#3631)
Initialize KeyboardHost with the updated key and text callbacks. Keep XR physical-key routing and use the regular ordered compositor queue for text.
2026-12-03 09:54:26 -05:00
Kurt Himebauch f9eeef44ed Keep the last frame visible on manual pause (#3626)
Use the effective zero-copy profile to capture and restore presentation across manual pause and resume, without overriding a disabled preference.
2026-12-03 07:39:12 -05:00
danyi eeb10e02fd Restore Chinese input for Android and Steam keyboards (#1529)
Commit Android IME text through the focused renderer and submit only after delivery is confirmed. Restore Steam pinyin on Ubuntu rc7 and allow older runtimes to start normally without IBus.
2026-12-03 07:36:55 -05:00
Kurt Himebauch e935263ccb Include IBus in the Ubuntu runtime (#3624)
Ship the IBus daemon, client, and Python bindings required for Steam pinyin. Verify these dependencies during runtime assembly.
2026-12-03 07:36:49 -05:00
FryMcNugget 673675b45e feat(quest): DroidDeck's menu, agent pet and keyboards float in the immersive SteamVR view (#3596) 2026-12-03 07:28:05 -05:00
Tushar Gandhe 153c873898 fix(ui): LB, RB, LT and RT close the keyboard and menus of the page they leave (#3619) 2026-12-03 07:26:39 -05:00
MicroCool cec2e4ed70 Retry rate-limited Robolectric downloads with a Maven Central mirror (#3620) 2026-12-03 07:26:11 -05:00
MaxsTechReview affb0da37f fix(fex): keep the guest stack clear of the host stack's growth reserve (#3623) 2026-12-03 07:13:39 -05:00
FryMcNugget 8cf1e60cc2 fix(runtime): thermal zone binds no longer leak into the stand-in for PCI devices (#3595) 2026-12-02 22:22:52 -05:00
LunaDL e3faee459f Fix frame generation controls in Library and Steam settings (#3597)
Restore the frame generation controls and make the Steam menu focus its first enabled option for controller and keyboard navigation.
2026-12-02 20:54:39 -05:00
Kurt Himebauch 20df8b1858 fix(nativeguest): reap the zombies session processes adopt as subreapers and never wait for (#3610) 2026-12-02 20:31:58 -05:00
Kurt Himebauch 4ab9635ceb fix(desktop): run Plasma, its helpers and the apps it opens outside Android's child-process count (#3599) 2026-12-02 18:45:22 -05:00
Kurt Himebauch 34fff40b56 ci: run Kotlin unit tests separately from APK builds (#3566)
Run Kotlin tests beside APK compilation while keeping merge and release checks intact. Pin the APK and test workflows to the same pull request base, retry Robolectric rate limits on both Maven Central hosts, and verify source parity when main advances.
2026-12-02 16:47:42 -05:00
Maksynum 5d05c36033 fix(audio): fall back to standard AAudio and bound startup restarts (#3514)
Fall back to standard audio mode after low-latency failures and cap consecutive startup restarts. On the Pocket Fit Elite, the exact locally signed PR build accepted playback in both DirectAudio modes. The Samsung-specific failure did not reproduce on that device.
2026-12-02 16:34:46 -05:00
MaxsTechReview ec281db0d1 fix(nativeguest): restore desktop startup after child handoff (#3594)
Keep handed-off children on the guest hook’s standard wait path. Verified the exact signed PR build on a Pocket Fit Elite: the desktop reached READY with KWin, Xwayland, and Plasma running.
2026-12-02 16:32:38 -05:00
JRAlmonte 1a7a116939 feat(ui): add frosted launcher wallpaper and cards (#3559)
Add opt-in frosted wallpaper and cards with separate transparency settings. Keep dialogs solid and fall back to the standard palette when blur or readable contrast is unavailable.
2026-12-02 15:48:36 -05:00
Hay Li bi c7cd7c18e6 fix(ea): the game's own Origin session gets the profile and GetSettings (#3578)
EA games open two LSX sessions: the activation layer's, which holds the launch,
and the game SDK's, which claims the same game but is never trusted. GetProfile
then sent it an empty UserId/PersonaId, which the SDK parses as integers, and
Lost in Random quit on the FormatException. Sessions that claimed the prepared
game now get the profile ids (tokens, codes, licences and entitlements stay with
the trusted session), and GetSettings is answered with the SDK's
GetSettingsResponse instead of ErrorSuccess.
2026-12-02 14:47:36 -05:00
Hay Li bi 80dbec57d7 fix(preload): Steam's overlay finds the robust list in Wine games without proot (#3577)
thread_robust_head() read the candidate list heads with process_vm_readv(getpid()).
In Wine games run without proot, and in any process whose first thread has exited,
that read fails with ESRCH, so the emulated get_robust_list answered ENOSYS and
Steam's arm64 gameoverlayrenderer.so aborted the game ("futex robust_list not
initialized by pthreads"). The read now goes through gettid().
2026-12-02 14:47:05 -05:00
LunaDL e04e38b44c Feat:Add a setting to hide the Smart Glasses shortcut (#3564)
* Add persistent Smart Glasses shortcut preference

* Add Smart Glasses shortcut visibility setting

* Respect Smart Glasses shortcut visibility preference

* Add Smart Glasses shortcut setting strings

* Observe shortcut preference in Smart Glasses settings

* Test Smart Glasses shortcut visibility preference

* Keep shortcut toggle in session settings only

* Expose shortcut preference in global Smart Glasses setup

* Label Smart Glasses shortcut setting

* Verify shortcut setting is available without connected glasses

* Mark new Smart Glasses shortcut labels as English-only

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Add Smart Glasses shortcut translations

* Keep Smart Glasses shortcut labels translatable
2026-12-02 14:44:24 -05:00
LunaDL 90c7dece92 feat(ui): Add dedicated Frame Generation tab and better engine selection ( left side menu ) (#3549)
* feat(ui): add dedicated frame generation drawer tab

* fix(ui): keep frame limit label in display settings

* fix(ui): focus display controls on a stable setting

* feat(ui): simplify frame generation engine and multiplier selection

* chore(ui): clean up frame generation selector imports

* fix(ui): restore controller support in frame generation menu

* refactor(ui): keep frame generation controls always visible

* refactor(ui): show frame generation controls inline

* chore(ui): remove obsolete frame generation focus import

* fix(ui): register frame generation engine focus

* fix(ui): remove obsolete frame generation menu host

* fix(ui): update frame generation menu call sites

* fix(ui): stack frame generation controls and restore focus

* fix(ui): gate legacy frame generation card menu

* fix(ui): gate legacy frame generation sheet menu

* Fix FrameGenMenu call signature

* Show frame generation controls only when opened

* ci: trigger checks

* feat(ui): add always-visible frame generation off option

* feat(ui): keep frame generation controls visible

* feat(ui): add custom frame generation vector icon

* feat(ui): use custom icon for frame generation tab

* fix(ui): restore adaptive LSFG target picker

* fix(ui): remove excess top spacing in frame generation menu

* Fix FrameGenMenu disabled-state handling

* Format FrameGenMenu multiplier row

* Add tighter Frame Generation control spacing

* Tighten Frame Generation drawer spacing

* Replace Frame Generation icon with new vector

* Keep legacy Frame Generation buttons available

* Use legacy Frame Generation buttons outside drawer

* chore: trigger CI
2026-12-02 14:32:24 -05:00
Kurt Himebauch 6d78142a67 fix(gamescope): SDR games keep their brightness while Steam's overlays are composited over them (#3590) 2026-12-02 14:28:03 -05:00
5cd6fe8864 feat(session): run the session outside Android's child-process count (#3338)
* docs: research Android's child-process limit without developer options

* docs: confirm the child-process gaps on the Thor

* feat(session): start long-lived daemons in uncounted worker processes

* feat(nativeguest): hand long-lived programs to uncounted worker processes

* test(session): run the session bus block with dd_spawn

* test(nativeguest): cover the exec handoff's wait and kill

* feat(session): run the session root, its jobs and the gamescope chain outside the child-process count

* feat(setup): the child-process limit no longer blocks Steam while the session runs in workers

* feat(audio): run PulseAudio outside the child-process count

* feat(nativeguest): hand off posix_spawn children and keep handed-off daemons alive

* fix(nativeguest): let Steam end a handed-off game and keep process-group signals

* perf(session): exec a worker as soon as its reply is in and keep two bound ahead; fix review findings

* fix(nativeguest): address review findings in handoff waits, signals and spawn errors

* fix(session): commit each worker launch explicitly and keep workers with the session that asked

* fix(session): let a worker wait for its launch commit on the main thread

* fix(session): confirm handoffs, honour wait selectors and stop spawns at teardown

* fix(session): one owner per handoff exit, worker launch answers and spawn edge cases

* fix(session): send a working directory outside the program's root by its real path

* fix(session): recheck a taken exit's child and commit a launch only on a whole go line

* fix(session): three-step launch, tagged exit reports and lock-free popen and system children

* test(native): popen test shell is static, as the other hook fixtures

* test(native): run the popen test program with a clean environment

* test(native): skip the popen test where a spawn child cannot exec aarch64

* fix(session): confirm the hook before the worker runs, prefer a late report and free a reused pid

* fix(session): tell a reused pid's old entry by start time, not the reaped flag

* fix(session): silent failed launches, bounded spawn requests and held check-gone writes

* test(native): check the unlisted child's status only where a child can exec aarch64

* fix(session): every exit-only waitid goes through the handoff wait

* fix(handoff): exact waitid events, safe exit timer, bounded request receipt

* feat(handoff): hand off shell children near Android's process limit

* fix(agent): tag handed-off game windows outside the reaper

* fix(handoff): a handed-off program's getppid() is its forking process

* fix(handoff): exact waitid selection, kept Steam and pipe readers, held reports

* fix(handoff): getppid() gives init for an exited or replaced parent

* fix(handoff): keep __WALL waitid calls on the handoff path

* test(handoff): require a zombie parent in the unreaped-parent case

* fix(handoff): honor __WNOTHREAD and check every argument for Steam

* fix(handoff): stop waiting on a held entry once its parent has exited

* fix(handoff): __WNOTHREAD on waits for a pid, flags on every shim reap

* fix(handoff): keep the forking thread of each child in the parent

* fix(handoff): a wait that finds no child rechecks live handoffs

* fix(handoff): keep a child's forking thread until its end is taken

* fix(handoff): the thread selector applies to claims in progress too

* fix(handoff): controlling-terminal check via /dev/tty, owned records only

* fix(handoff): a child whose forking thread ended is any thread's

* fix(handoff): a parent /proc cannot read is checked with kill(), then given up

* fix(handoff): one-word fork records, changed only by compare-and-swap

* fix(handoff): watch the forking parent through a pidfd opened at start

* fix(handoff): fork records by pid, a gone thread's children go to the main one

* fix(handoff): keep the parent pidfd through dup2 and check it before use

* fix(handoff): no handoff without fork records, unknown thread state keeps the owner

* fix(handoff): undo a pidfd move when dup fails, recheck it after the poll

* fix(handoff): fresh fork records in a forked child, heir is the first live thread

* fix(handoff): one lock over a pidfd move, its dup and the undo

* fix(handoff): liveness check under the pidfd lock, forget only a reaped pid's record

* fix(handoff): lock only dups onto the pidfd, with signals blocked

* fix(handoff): fork record generations, no pidfd restore after a failed move

* fix(handoff): every dup in a pidfd process locks, fork prep blocks signals

* test(semaphores): tell a child hung in qemu-user from a guest deadlock

* fix(handoff): fork records matched by the child's start time, never removed

* test(semaphores): count only reaped children, only futex waits as emulator stalls

* fix(handoff): a known-start bit in fork records

* fix(handoff): dup bookkeeping before the pidfd lock, newer fork records kept

* fix(handoff): a fork record stays only for the pid's current process

* fix(handoff): keep a pending child's fork record when an older fork records late

* fix(handoff): an unknown-start fork record never replaces a pending one

* fix(handoff): self-recorded forks, ELF and wait option checks, both nofile limits

* test(handoff): find the module in the namespace run under discover too

* fix(handoff): a spare parent pidfd made at start, so a dup2 onto it makes no fd

* test(handoff): require ENOEXEC for an ELF stub; skip the namespace run without binfmt

* fix(hook): change the kept fd list under a sequence lock; readers take a copy

* fix(handoff): one report per handed-off child; stops keep a claim; nested waits keep their selector

* fix(hook): a table made at runtime outlives closes begun before it; unknown-start fork records kept

* fix(handoff): waits look before they reap, so a handed-off fork's child is never reported

* fix(hook): settle waits out earlier epochs; unknown-start fork records kept for any handoff under way

* fix(handoff): generation-checked reap marks, stops taken as stops, close counts reset in a fork

* fix(handoff): one given-up table at most, whole stop codes and rusage, WNOWAIT exits rechecked

* fix(handoff): requests name their session; stops of handed-off programs reported; cancellable look

* fix(handoff): table setup not cancellable; test spawner never runs what it cannot end

* fix(handoff): job-control jobs stay counted; unnamed requests refused; cancel-safe setup

* docs(phantom): job-control jobs stay counted; listed programs report no stops

* fix(handoff): a listed program a shell runs as a job-control job stays counted

* refactor(hook): kept descriptors in their own part, a handoff matched by another program

The descriptors close(), close_range() and closefrom() leave open move from
privileged.c to hook/kept.c (unchanged), so the bionic runtime's exec shim can
build the handoff with them. ddh_try_as() matches DD_HANDOFF against one
program and sends another: the bionic shim sends "/system/bin/linker64 PROGRAM
ARGS" and lists it by PROGRAM. ddh_try() is ddh_try_as() with both the same.

* feat(bionic): hand the bionic runtime's Wine programs to the app's workers

The glibc session's hook never sees DroidDeck-Bionic's processes (Wine on
Android's libc), so a bionic game's Wine programs all stayed counted under the
worker running the tool's launch.sh. The handoff is now built into the
runtime's exec shim (tools/bionic-runtime/handoff.c, part of libexecshim.so):

- hook/handoff.c and hook/kept.c with what the native hook's other parts do
  around them: fork(), close(), close_range(), dup2(), dup3(), and exit() for
  the on_exit() bionic lacks
- bionic's execv(), execvp(), execl*() reach the execve system call inside
  libc, past execshim's execve(); Wine starts its preloader with execv(), so
  the shim defines them on top of its execve()
- a linker64 start is listed by its program
- the app starts a handed-off program from the glibc root's bash, which cannot
  load the runtime's LD_PRELOAD/LD_LIBRARY_PATH: they go as arguments of
  /system/bin/env, which puts them back for the program
- launch.sh keeps DD_SPAWN, DD_SPAWN_SESSION, DD_HANDOFF*, DDH_* and
  DDNATV_ROOT, and its /proc/N/environ reads no longer print "Permission
  denied" for idle workers (2>/dev/null before the redirect)

Pocket FIT, DroidDeck-Bionic 14.1-r67 with this shim and launcher, handoff on:
counted during Brawlhalla 25 -> 17, DiRT Showdown 24-27 -> 16, whole run
28 -> 19-20; with Android's limit on no DroidDeck process and no other app's
process was killed (before: Discord, BatteryLog helpers); DiRT 75 fps either
way. docs/phantom-processes.md: "The bionic runtime".

* fix(bionic): hand off only starts that would succeed here; bionic's execvp fallbacks

Review follow-ups on the bionic runtime's handoff (tools/bionic-runtime/handoff.c):

- A start is handed to a worker only when it would get past execve() in this process: the file is a
  regular executable outside the app's data (Android refuses execve() there), and for a linker64 start
  the program it loads is a readable regular file. A start that failed in the worker failed where the
  caller could not see it, so Wine never tried its next candidate. The hook's own check looked at
  /system/bin/env, not the program.
- A start whose argv[0] is not its file stays here: env starts FILE with FILE as argv[0]. linker64 and
  interpreter starts are unaffected (their argv[0] is the file). An empty argv stays here too.
- Nothing is built for the handoff without DD_SPAWN and DD_HANDOFF.
- execvp()/execvpe()/execlp() follow bionic's: an unset PATH is libc's default, an empty PATH or entry
  is the current directory, and a file the kernel cannot start (ENOEXEC) runs under /system/bin/sh.
- close_range() refuses first > last and unknown flags before it splits the range or unshares the table.
- The debug line reads the table's owner only once the table is seen published.

* fix(bionic): hand off app-data starts only where SELinux lets them run; bare names stay here

Follow-up to 7d95564f7 (review, and a Pocket FIT test of its pack):

- 7d95564f7 kept every start of a file in the app's data here. Wine's preloader is one (a static ELF,
  so execshim.c cannot make it a linker64 start), and where SELinux is permissive, as on AYANEO's
  firmware, it runs: Wine then never reached its loader, and its programs ran here, counted again
  (Pocket FIT: Brawlhalla 26-28 counted vs 16-17 before). Where SELinux enforces, Android refuses the
  exec, here and in a worker alike, and Wine falls back to its loader, which goes as a linker64 start.
  Such a start is now handed off when /sys/fs/selinux/enforce reads 0, and stays here otherwise
  (also when the setting cannot be read).
- The program a start would run is checked with the hook's own ddh_startable() (an ELF the kernel
  loads with its interpreter there, or a script with its interpreter): for a linker64 start, the
  program it loads.
- A file name without '/' stays here: env would look it up in PATH, the exec here in the caller's
  working directory.
- execvpe() skips a PATH entry whose candidate exceeds PATH_MAX (ENAMETOOLONG) instead of copying
  it onto the stack.

* fix(handoff): spawn blocks signals and cancellation across the fork; root flag stored under the stop lock

* fix(handoff): a thread that unshares its fd table keeps its own copy of the kept fds

* fix(handoff): register the kept list's fork handlers before a split takes its lock

* test(handoff): cover WNOHANG with a held forked child, early reaps, blocked waitid and pidfd parents; keep the counted-process exception in translations

* test(handoff): exited-entry precondition, atomic checkpoints, a pidfd-only zombie check; validate the shim hold fd

* test(handoff): WNOHANG with two handed-off children and for a group; a program's exit while its entry is held

* test(handoff): a held exit with no free fd, with and without the parent's pidfd

* test(handoff): held-exit tests require the program's own exit status

* test(handoff): time held exits from the run, and only once the program is at its exit

* perf(handoff): keep the asker's priority, quick tools local, workers bound ahead of a game (#3582)

Three fixes that bring handoff-on speed to within 1-2 % of handoff off
(AIO D3D11 same session: 3196 -> 3520 fps, 1 % low 444 -> 637) with the
same counted processes (benchmark mean 18.5, peak 23):

- A handed-off program keeps its asker's priority. Workers are bound
  from the top app with BIND_IMPORTANT, so Android boosts their main
  thread to THREAD_PRIORITY_TOP_APP_BOOST (-10); the program the worker
  execs inherited it. The asker's nice value is sent with the request and
  set before execve, and a watcher resets it if Android boosts it again.
- Quick script tools (awk, sed, grep, cat, ...) stay where they are when
  the count is near the limit. Sent to a worker, the forked child waits
  (counted) while a worker starts; run locally it is counted for a few ms.
- Workers are bound ahead when a Steam game is queued (16 for 20 s), so
  Wine's services do not wait on zygote forks at game start.

---------

Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com>
2026-12-02 14:02:55 -05:00
Kurt Himebauch 186bae8f3e feat(native): run the desktop, its apps and shells as an ordinary user instead of fake root (#3587)
* feat(native): run the desktop, its apps and shells as an ordinary user instead of fake root

* fix(native): a script's interpreter takes DDNATV_BECOME, so sudo runs scripts as root

* fix(desktop): keep the Plasma start line the pipewire tests slice the script at
2026-12-02 13:50:06 -05:00
Kurt Himebauch 3bb22dc92b fix(native): terminals use the ioctls Android allows on an app's pseudo-terminal (#3585)
* fix(native): terminals use the ioctls Android allows on an app's pseudo-terminal

* fix(native): leave a terminal request alone when its register is read before the high half
2026-12-02 13:47:59 -05:00
LunaDL f3f410059d Feat:Add separate orientation settings for Steam and desktop sessions (#3567)
* Add per-session orientation preferences

* Apply orientation preference for active session

* Use session-specific orientation for output following

* Test independent session orientation preferences

* Map run sessions to Steam orientation preference

* Add separate Steam and desktop orientation controls

* Cover session mode orientation mapping

* Persist in-session orientation by session mode

* Refresh inherited orientation settings after global change

* Resolve window and portrait orientation by session mode

* Use session orientation for output sizing and window behavior

* Test mode-specific window and portrait orientation

* Refresh session orientation choices on resume

* Refresh session orientation choices on resume

* Use Compose lifecycle owner import

* Trigger CI
2026-12-02 12:29:52 -05:00
MaxsTechReview 6e7908ed81 fix(display): copy the game and the window above it in one GPU submit (#3583)
* fix(display): copy the game and the window above it in one GPU submit

When a game's frames go on the layer-copy path and a window sits above
the game, each scene copied the game frame and then the window above it
with two separate submits and two CPU waits. Each wait queued behind
the game's own GPU work, so a GPU-bound game lost on-screen frames to
the second wait.

Record both copies in one command buffer, merge their release fences,
and wait once per scene. The zero-copy path and the single-layer copy
path are unchanged.

* Check overlay eligibility against the frame's own game geometry and keep both release waits when a fence merge fails
2026-12-02 12:12:08 -05:00
LunaDL 9ca6fa064e fix(bionic): the WSI layer uses its normal bypass check, and zero-copy fallbacks log their reason (#3487)
The Bionic launcher no longer forces the WSI layer's XWayland bypass; the layer runs its normal eligibility check, cached for 100 ms. The compositor logs, rate-limited, why a frame or layer candidate leaves the zero-copy path: no registered gralloc buffer, a failed direct present, or a rejected candidate draw.

Tested on a 60 Hz Adreno handheld with the forced bypass on and off and with two driver versions: every run stayed on the zero-copy path at about 60 fps.
2026-12-02 04:04:53 -05:00
MaxsTechReview aab15f3146 fix(display): copy zero-copy frames that carry no acquire fence (#3427)
When a frame's acquire fence cannot be exported from its dma-buf, the frame takes the layer-copy path instead of reaching the display unfenced. Fixes #3410.
2026-12-02 03:29:48 -05:00
Kurt Himebauch 11af78340a fix(gamescope): keep forwarded buffers alive while waiting for scanout, and composite at full rate (#3560)
* fix(gamescope): a pending scanout wait keeps its forwarded buffer alive

Patch 0147 waits for scanout on a forwarded client buffer with a raw
pointer to its CWaylandFb. If the buffer was shown again and the next host
release found scanout already over, that release dropped the last
reference while the earlier wait was still queued, and the wait then
called OnScanoutDone on a freed buffer. The wait now holds a reference
until it finishes.

* fix(gamescope): composite every frame when the host releases buffers before scanout

Holding a forwarded client buffer until scanout ends (0147) costs a three-buffer
client a third of the refresh rate: Steam's UI ran at 80 fps on a 120 Hz screen.
Once the backend sees a forwarded buffer released while it is still being
scanned out, it composites every frame into its own output images, which 0146
reuses at latch. The Steam UI runs at 120 fps again on the Pocket FIT.

* Pin the gamescope build with the scanout wait reference and full-rate compositing
2026-12-02 00:54:29 -05:00
MaxsTechReview 2c95ebd22d fix(input): the middle of a crossed on-screen D-pad presses the nearest arm (#3558)
* fix(input): the middle of a crossed on-screen D-pad presses the nearest arm

Four direction buttons laid out as a cross left an empty square in the
middle, so a touch there fell through to the mouse. A touch inside the
cross now picks the arm on that side, for the stock pad and any custom
layout with the same shape.

* fix(input): take the D-pad middle for hand-placed arms that are not exactly centred

* fix(input): limit the D-pad fallback to its middle and find the cross among duplicate arms

* fix(input): D-pad middle picks the nearest arm and needs overlapping opposite arms

* fix(input): D-pad middle measures the distance to each arm itself

* fix(input): D-pad middle weighs every matching arm set
2026-12-01 22:15:02 -05:00
MaxsTechReview 7ce53ccbed fix(tabs): keep More on the bar so tabs can always be edited (#3556)
Edit tabs only opens from the More page, and More left the bar once no
tab was shelved in it. Hiding or moving every shelved tab therefore
removed the only way back into the tab editor. More now always stays on
the bar; with nothing shelved it opens to the Edit tabs button.
2026-12-01 20:33:08 -05:00
Kurt Himebauch 1b4aaf8a3b feat(drawer): fold session menu groups into summarized sections and regroup pages (#3550)
* feat(drawer): fold session menu groups into summarized sections and regroup pages

* chore(drawer): drop unused strings

* fix(drawer): observe controller state, drop stale achievements, stable section keys
2026-12-01 20:26:14 -05:00
Kurt Himebauch 4793d1df62 fix(display): the Game Mode FPS override caps the frames the guest draws (#3388)
fix(display): the Game Mode FPS override caps the frames the guest draws, not only the ones shown
2026-12-01 20:10:34 -05:00
Kurt Himebauch 9dfbc05933 fix(droiddeckctl): gamepad and pen input on Android 13 and 14 QPR1 (#3530)
* fix(droiddeckctl): gamepad and pen input on Android 13 and 14 QPR1

* fix(droiddeckctl): read the pen's codes before its bus so Android 14 QPR1 retries numerically
2026-12-01 10:32:06 -05:00
MaxsTechReview 8ec6e646d9 fix(effects): CAS addresses the scene with its pushed input size (#3519)
CAS derives texel centres from the input size in its push constants instead of textureSize on the imported scene image, as the previous CAS shader did. Fixes the grid of black marks with CAS on 10-bit game images on Adreno 8xx.
2026-12-01 10:11:30 -05:00
Kurt Himebauch 41412450fd feat(bottom): Steam menu and Quick Access side by side on the bottom screen (#3501) 2026-12-01 09:52:13 -05:00
MaxsTechReview bf772b7c55 ci(desktop): build KWin 6.8.3 to match the Arch Linux ARM package (#3526) 2026-12-01 09:09:51 -05:00
MaxsTechReview 29b04b66eb fix(gamescope): hold forwarded client buffers until the display finished scanning them out (#3516)
* Return a forwarded client buffer to its client only after the display finished scanning it out

* Test that a forwarded client buffer waits for scanout and composite images do not

* Pin the gamescope build that holds forwarded client buffers until scanout ends
2026-12-01 06:02:16 -05:00
MaxsTechReview 044c8ee475 fix(gamescope): a composited cursor no longer forwards the default arrow to the host (#3510) 2026-12-01 03:55:33 -05:00
MaxsTechReview ca499115ac fix(zero-copy): merge a second release fence into the pending fence wait (#3509)
When the kernel cannot attach a display release fence to the buffer, the
compositor waits on the fence itself. A second release of the same buffer
before that fence signalled overwrote the pending wait, so the first wait
removed the second one and then fired again with no source to remove,
crashing the compositor and losing the session.

A second unsignalled fence is now merged into the pending wait, and a
signalled or attached one leaves the pending wait in charge of the
deferred release.
2026-12-01 02:55:37 -05:00
The412BannerandThe412Banner d7898360e3 fix(input): keep the glibc-only __chk_fail out of the bionic build (#3492)
DroidDeck-Bionic preloads libfakeinput.so into its Wine processes
(tools/bionic-runtime/build.sh builds fakeinput_steam.cpp for bionic). The
fortified read/poll/ppoll entry points (#2916) call glibc's __chk_fail, which
bionic does not export, so the bionic build of the library cannot be loaded:
"CANNOT LINK EXECUTABLE .../wine: cannot locate symbol "__chk_fail"" and no
Wine program starts. Every DroidDeck-Bionic pack built from main since #2916 is
affected (r67 predates it).

The bounds failures now go through fakeinput_chk_fail(): abort() on bionic,
__chk_fail() as before on glibc. tools/tests/test_fakeinput_bionic.py fails if
__chk_fail is named outside the non-bionic branch again.

Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
2026-11-30 19:48:33 -05:00
301 changed files with 32599 additions and 1673 deletions

No files matched your search

+7 -1
View File
@@ -7,7 +7,7 @@ on:
push:
branches: [main]
workflow_run:
workflows: [Build APK]
workflows: [Build APK, Unit tests]
types: [completed]
workflow_dispatch:
inputs:
@@ -21,6 +21,12 @@ permissions:
pull-requests: read
statuses: write
# Build APK and Unit tests each trigger a validation, and the last one to post sets the status. Queued runs for a
# commit wait, so the newest one reads both results and posts last.
concurrency:
group: build-validation-${{ github.event.pull_request.head.sha || github.event.workflow_run.head_sha || inputs.pr_number || github.sha }}
cancel-in-progress: false
jobs:
validate:
name: Validate source and build result
+10 -120
View File
@@ -1,5 +1,5 @@
name: Build APK
run-name: ${{ github.event_name == 'pull_request' && format('building pr {0} on {1}', github.event.pull_request.number, github.event.pull_request.head.sha) || format('building {0} on {1}', github.ref_name, github.sha) }}
run-name: ${{ github.event_name == 'pull_request' && format('building pr {0} on {1} against {2}', github.event.pull_request.number, github.event.pull_request.head.sha, github.event.pull_request.base.sha) || format('building {0} on {1}', github.ref_name, github.sha) }}
on:
push:
@@ -57,15 +57,18 @@ jobs:
- name: Pin and merge the APK source
id: merge
if: github.event_name == 'pull_request'
env:
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
set -euo pipefail
git fetch --no-tags origin main
echo "base-sha=$(git rev-parse origin/main)" >> "$GITHUB_OUTPUT"
# Unit tests uses the same event snapshot, including when either workflow is rerun.
git fetch --no-tags origin "$PR_BASE_SHA"
echo "base-sha=$PR_BASE_SHA" >> "$GITHUB_OUTPUT"
git config user.name "ci"
git config user.email "ci@users.noreply.github.com"
# Partial clone: a merged blob that only exists in a fork's history can't be lazily fetched (GitHub: "not our ref"); merge-tree writes it locally first.
git merge-tree --write-tree HEAD origin/main >/dev/null || true
git merge --no-ff --no-edit origin/main
git merge-tree --write-tree HEAD FETCH_HEAD >/dev/null || true
git merge --no-ff --no-edit FETCH_HEAD
- name: Resolve trusted manifest base
id: trusted
if: github.event_name != 'pull_request'
@@ -349,7 +352,7 @@ jobs:
build:
needs: [source, components, xbox, build-runner]
name: Compile APK and Android tests
name: Compile APK
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
runs-on: ${{ fromJSON(needs.build-runner.outputs.labels) }}
timeout-minutes: 45
@@ -507,23 +510,7 @@ jobs:
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
BUILD_REF: ${{ github.ref_name }}
BUILD_SHA: ${{ github.sha }}
run: |
if [[ -n "$(git status --porcelain)" ]]; then
tree_state=dirty
else
tree_state=clean
fi
echo "DROIDDECK_BUILD_TREE_STATE=$tree_state" >> "$GITHUB_ENV"
if [[ -n "$PR_NUMBER" ]]; then
label="pr${PR_NUMBER} at ${PR_HEAD_SHA:0:7}"
else
label="${BUILD_REF} at ${BUILD_SHA:0:7}"
fi
echo "label=$label" >> "$GITHUB_OUTPUT"
echo "DROIDDECK_SOURCE_COMMIT=${PR_HEAD_SHA:-$BUILD_SHA}" >> "$GITHUB_ENV"
echo "DROIDDECK_PR_NUMBER=${PR_NUMBER:-0}" >> "$GITHUB_ENV"
echo "DROIDDECK_PR_TITLE=${PR_TITLE//$'\n'/ }" >> "$GITHUB_ENV"
echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY"
run: bash tools/ci/build-label.sh
- name: Rust toolchain for the store engines (aarch64-linux-android)
id: rust
@@ -734,101 +721,6 @@ jobs:
if-no-files-found: ignore
overwrite: true
- name: Resolve the Robolectric version
id: robolectric
run: |
echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT"
# Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes.
# The cache path sits beside the workspace because runner homes are at different depths from it, and
# actions/cache stores paths relative to the workspace. It is passed as an absolute path: the save action rejects
# "..". Runners that keep their own ~/.m2 skip the cache.
- name: Place Robolectric's Android jars beside the workspace
id: robolectric-jars
run: |
set -euo pipefail
jars="$GITHUB_WORKSPACE/../robolectric-jars"
m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented"
if [ -d "$m2" ] && [ ! -L "$m2" ]; then
echo "cache=false" >> "$GITHUB_OUTPUT"
else
mkdir -p "$jars" "$(dirname "$m2")"
jars=$(cd "$jars" && pwd)
ln -sfn "$jars" "$m2"
echo "path=$jars" >> "$GITHUB_OUTPUT"
echo "cache=true" >> "$GITHUB_OUTPUT"
fi
- name: Restore Robolectric's Android jars
id: robolectric-cache
if: steps.robolectric-jars.outputs.cache == 'true'
uses: actions/cache/restore@v4
with:
path: ${{ steps.robolectric-jars.outputs.path }}
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-
- name: Count the restored Robolectric jars
if: steps.robolectric-jars.outputs.cache == 'true'
run: echo "ROBOLECTRIC_JARS_BEFORE=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)" >> "$GITHUB_ENV"
- name: Unit tests
id: unit-tests
env:
DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }}
SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }}
run: |
set -o pipefail
mkdir -p app/build
# A Maven 429 fails every test class that needs the missing jar. The jars an attempt did get stay for the next.
for wait in 60 180 0; do
status=0
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log || status=$?
if [ "$status" = 0 ] || [ "$wait" = 0 ] || ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://repo\.maven\.apache\.org/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://repo\.maven\.apache\.org/)' app/build/unit-tests.log; then
exit "$status"
fi
echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s"
sleep "$wait"
done
# actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache.
# Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first.
- name: Save Robolectric's Android jars
id: robolectric-jars-final
if: always() && steps.robolectric-jars.outputs.cache == 'true'
run: |
python3 - <<'PY'
import glob, os, zipfile
root = os.path.join(os.environ['GITHUB_WORKSPACE'], '..', 'robolectric-jars')
for f in glob.glob(os.path.join(root, '**', '*'), recursive=True):
if not os.path.isfile(f):
continue
try:
ok = f.endswith('.jar') and zipfile.ZipFile(f).testzip() is None
except Exception:
ok = False
if not ok:
os.remove(f)
PY
after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)
[ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true
- name: Store Robolectric's Android jars
if: always() && steps.robolectric-jars-final.outputs.save == 'true'
uses: actions/cache/save@v4
with:
path: ${{ steps.robolectric-jars.outputs.path }}
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
- name: Upload unit test diagnostics
id: unit-test-diagnostics
if: always() && steps.unit-tests.outcome != 'skipped'
uses: actions/upload-artifact@v4
with:
name: unit-test-results
path: |
app/build/unit-tests.log
app/build/test-results/testReleaseUnitTest/
app/build/reports/tests/testReleaseUnitTest/
if-no-files-found: ignore
retention-days: 14
overwrite: true
- name: Sign with the testkey (v1 + v2 + v3)
run: |
set -euo pipefail
@@ -884,8 +776,6 @@ jobs:
PR: ${{ github.event.pull_request.number }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
BUILD_OUTCOME: ${{ steps.build.outcome }}
UNIT_TEST_OUTCOME: ${{ steps.unit-tests.outcome }}
TEST_DIAGNOSTICS_URL: ${{ steps.unit-test-diagnostics.outputs.artifact-url }}
APK_OUTCOME: ${{ steps.apk-upload.outcome }}
run: bash tools/release/report-build.sh
+7
View File
@@ -47,6 +47,13 @@ jobs:
echo "::error::main ${GITHUB_SHA::7} has no successful Build APK run yet: wait for it, then release"
exit 1
fi
tests=$(gh run list -R "$GITHUB_REPOSITORY" --workflow unit-tests.yml --branch main --commit "$GITHUB_SHA" \
--json conclusion,event,headSha -L 20 |
jq -r --arg sha "$GITHUB_SHA" '[.[] | select(.headSha == $sha and (.event == "push" or .event == "workflow_dispatch"))][0].conclusion // empty')
if [ "$tests" != success ]; then
echo "::error::main ${GITHUB_SHA::7} has no passing Unit tests run (${tests:-none yet}): fix or wait for it, then release"
exit 1
fi
variants=$(awk '!/^#/ && NF { print $1 }' tools/release/variants.txt | jq -R . | jq -sc .)
echo "run_id=$id" >> "$GITHUB_OUTPUT"
echo "variants=$variants" >> "$GITHUB_OUTPUT"
+200
View File
@@ -0,0 +1,200 @@
name: Unit tests
run-name: ${{ github.event_name == 'pull_request' && format('unit tests for pr {0} on {1} against {2}', github.event.pull_request.number, github.event.pull_request.head.sha, github.event.pull_request.base.sha) || format('unit tests for {0} on {1}', github.ref_name, github.sha) }}
# Runs beside Build APK rather than inside it, so a test build is published as soon as the APK compiles.
# Build validation folds this workflow's result into the "Build APK" commit status, and Release APKs requires it.
on:
push:
branches: [ main ]
paths-ignore:
- '**/*.md'
- 'LICENSE'
- '.gitignore'
- 'docs/**'
- '.github/ISSUE_TEMPLATE/**'
pull_request:
branches: [ main ]
types: [ opened, synchronize, reopened, ready_for_review ]
paths-ignore:
- '**/*.md'
- 'LICENSE'
- '.gitignore'
- 'docs/**'
- '.github/ISSUE_TEMPLATE/**'
workflow_dispatch:
permissions:
contents: read
actions: read
concurrency:
group: unit-tests-${{ github.event.pull_request.number || (github.event_name == 'push' && 'main') || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' }}
jobs:
unit-tests:
name: Unit tests
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
fetch-depth: 0
sparse-checkout: |
/*
!/docs/releases/media/
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Merge the pinned APK base
if: github.event_name == 'pull_request'
env:
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
set -euo pipefail
git config user.name "ci"
git config user.email "ci@users.noreply.github.com"
git fetch --no-tags origin "$PR_BASE_SHA"
git merge-tree --write-tree HEAD FETCH_HEAD >/dev/null || true
git merge --no-ff --no-edit FETCH_HEAD || { echo "::error::the pull request conflicts with main; Build APK lists the files"; exit 1; }
- name: Check out MaliBridge
run: git submodule update --init external/MaliBridge
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '17'
- uses: gradle/actions/setup-gradle@v4
with:
cache-read-only: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }}
cache-cleanup: ${{ github.event_name == 'pull_request' && 'never' || 'on-success' }}
- name: Resolve the pinned Android NDK
run: bash tools/ci/resolve-ndk.sh
- name: Set the APK build label
id: build-label
env:
PR_NUMBER: ${{ github.event.pull_request.number }}
PR_TITLE: ${{ github.event.pull_request.title }}
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
BUILD_REF: ${{ github.ref_name }}
BUILD_SHA: ${{ github.sha }}
run: bash tools/ci/build-label.sh
- name: Resolve the Robolectric version
id: robolectric
run: |
echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT"
# Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes.
# The cache path sits beside the workspace because runner homes are at different depths from it, and
# actions/cache stores paths relative to the workspace. It is passed as an absolute path: the save action rejects
# "..". Runners that keep their own ~/.m2 skip the cache.
- name: Place Robolectric's Android jars beside the workspace
id: robolectric-jars
run: |
set -euo pipefail
jars="$GITHUB_WORKSPACE/../robolectric-jars"
m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented"
if [ -d "$m2" ] && [ ! -L "$m2" ]; then
echo "cache=false" >> "$GITHUB_OUTPUT"
else
mkdir -p "$jars" "$(dirname "$m2")"
jars=$(cd "$jars" && pwd)
ln -sfn "$jars" "$m2"
echo "path=$jars" >> "$GITHUB_OUTPUT"
echo "cache=true" >> "$GITHUB_OUTPUT"
fi
- name: Restore Robolectric's Android jars
id: robolectric-cache
if: steps.robolectric-jars.outputs.cache == 'true'
uses: actions/cache/restore@v4
with:
path: ${{ steps.robolectric-jars.outputs.path }}
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-
- name: Count the restored Robolectric jars
if: steps.robolectric-jars.outputs.cache == 'true'
run: echo "ROBOLECTRIC_JARS_BEFORE=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)" >> "$GITHUB_ENV"
- name: Unit tests
id: unit-tests
env:
DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }}
SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }}
run: |
set -o pipefail
mkdir -p app/build
log=app/build/unit-tests.log
attempt_log=app/build/unit-tests-attempt.log
: > "$log"
mirror=()
central='https://(repo1\.maven\.org|repo\.maven\.apache\.org)/maven2/org/robolectric/'
gradle_error='((Caused by: )?org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: |>[[:space:]]+)?'
java_error='((Caused by: )?java\.io\.IOException: )?'
# A Maven 429 fails every test class that needs the missing jar. The jars an attempt did get stay for the next.
for wait in 60 180 0; do
status=0
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PskipRust=true -PunitTestsOnly=true -PndkVersion="$NDK_VERSION" "${mirror[@]}" 2>&1 | tee "$attempt_log" || status=$?
cat "$attempt_log" >> "$log"
if [ "$status" = 0 ] || [ "$wait" = 0 ]; then
exit "$status"
fi
if [ "${#mirror[@]}" = 0 ] && grep -qE \
-e "^[[:space:]]*${gradle_error}Could not (GET|HEAD) '?${central}[^'[:space:]]+'?\. Received status code 429([[:space:]]|$)" \
-e "^[[:space:]]*${java_error}Server returned HTTP response code: 429 for URL: ${central}[^[:space:]]+" "$attempt_log"; then
mirror=(-ProbolectricMavenMirror=https://maven-central.storage-download.googleapis.com/maven2)
echo "::notice::Maven Central rate limited Robolectric. Retrying unit tests with the Google Cloud mirror." | tee -a "$log"
continue
fi
if ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://(repo\.maven\.apache\.org|repo1\.maven\.org)/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://(repo\.maven\.apache\.org|repo1\.maven\.org)/)' "$attempt_log"; then
exit "$status"
fi
echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s" | tee -a "$log"
sleep "$wait"
done
# actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache.
# Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first.
- name: Save Robolectric's Android jars
id: robolectric-jars-final
if: always() && steps.robolectric-jars.outputs.cache == 'true'
run: |
python3 - <<'PY'
import glob, os, zipfile
root = os.path.join(os.environ['GITHUB_WORKSPACE'], '..', 'robolectric-jars')
for f in glob.glob(os.path.join(root, '**', '*'), recursive=True):
if not os.path.isfile(f):
continue
try:
ok = f.endswith('.jar') and zipfile.ZipFile(f).testzip() is None
except Exception:
ok = False
if not ok:
os.remove(f)
PY
after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)
[ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true
- name: Store Robolectric's Android jars
if: always() && steps.robolectric-jars-final.outputs.save == 'true'
uses: actions/cache/save@v4
with:
path: ${{ steps.robolectric-jars.outputs.path }}
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
- name: Upload unit test diagnostics
id: unit-test-diagnostics
if: always() && steps.unit-tests.outcome != 'skipped'
uses: actions/upload-artifact@v4
with:
name: unit-test-results
path: |
app/build/unit-tests.log
app/build/test-results/testReleaseUnitTest/
app/build/reports/tests/testReleaseUnitTest/
if-no-files-found: ignore
retention-days: 14
overwrite: true
+2 -2
View File
@@ -7,7 +7,7 @@
- For an install-and-look iteration, use `tools/quick_deploy.sh` (build without lint, sign, install, about 30 s). Run `tools/build_local.sh` once to prepare the runtime and again only before a PR. It is not a per-change step.
- `tools/build_local.sh` reuses the components a main CI run prepared when every recipe identity matches the local tree (it prints `components: … reusing`). It builds them locally when no usable CI artifact matches (after you change their inputs, or when the lookup fails) or with `DROIDDECK_CI_COMPONENTS=0`.
- Helper scripts (`tools/linuxfs/overlay`, `tools/linuxfs/desktop`) are staged on every Gradle build, so editing them needs no `build_local.sh`. After preloads or other runtime components change, the fast loop warns and reuses the old binaries; run `tools/build_local.sh` when those matter. "Missing or changed runtime input" means the prepared files themselves changed: run `tools/build_local.sh` once. Do not revert scripts or copy `app/build` between checkouts; `tools/seed_worktree.sh` seeds a new worktree from the main checkout.
- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest`; when a test fails only in CI, run the release variant locally.
- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest` in the `Unit tests` workflow, beside Build APK; when a test fails only in CI, run the release variant locally.
- Run the tests that cover what you changed, including unchanged tests of code you edited: `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '<class>'` and `python3 -m unittest discover -s tools/tests -p 'test_<area>*.py'`. The full Python suite takes about 9 minutes, and some preload tests fail on any host without zram/ntsync. Leave full runs to CI.
- For UI screenshots without a device, run `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*PreviewRenderTest'` and read `app/build/preview-renders/{handheld,portrait}/`. Add cases per `docs/compose-previews.md`. Check portrait, not just landscape.
- After changing `SettingsIndex`, regenerate the doc: `UPDATE_SETTINGS_MAP=1 ./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*SettingsMapTest*'`.
@@ -31,7 +31,7 @@
- CI builds the PR merged onto `main`. Before pushing, merge or rebase onto `origin/main` and compile: most "works locally" Kotlin failures come from that merge.
- Before a PR that touches strings or resources, run `./gradlew :app:lintVitalRelease`. The fast loop skips lint, and lint catches `ExtraTranslation` and missing-locale errors.
- Commit messages and PR bodies must not carry `Co-Authored-By` or other bot trailers. `tools/release/check_authorship.py` fails the build on them.
- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs/<job-id>/logs`, or `gh run download <run> -n unit-test-results`. Don't call a failure a runner problem until you have read it.
- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs/<job-id>/logs`, or `gh run download <run> -n unit-test-results` from the `Unit tests` workflow run. Don't call a failure a runner problem until you have read it.
- Only these are known flakes worth a `gh run rerun <run> --failed`: `ProtonMenuAutoTest` "Proton work did not finish", Robolectric `HTTP response code: 429` from Maven, `Gradle Test Executor N finished with non-zero exit value 2`, apt mirror and GitHub API rate-limit errors. Treat any other failure as real.
- A workflow step that names a script your branch lacks means the branch predates a CI change. Rebase onto `main`.
+1
View File
@@ -68,6 +68,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
- Anti-cheat support under FEX is the work of [StonkGuy](https://github.com/StonkGuy): the x86-64 ptrace, seccomp and `/proc` emulation from his [FEX fork](https://github.com/StonkGuy/FEX) (`eac-2611` branch, MIT) is carried as build patch 0021 with his authorship, patches 0022 to 0029 build on it, and his `eac-tests` regression suite verifies them.
- x86-64 programs on Wayland reach the GPU through FEX's Wayland client, wayland-egl and EGL thunks. The guest `wl_list` and `wl_array` helpers follow [libwayland](https://gitlab.freedesktop.org/wayland/wayland)'s `src/wayland-util.c` (MIT). The EGL extension table comes from the [Khronos EGL registry](https://github.com/KhronosGroup/EGL-Registry) (Apache-2.0) and Mesa's `egl_other.xml` (MIT).
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence.
+8 -1
View File
@@ -82,6 +82,8 @@ def buildBranch = providers.environmentVariable('GITHUB_HEAD_REF').getOrNull()?.
?: gitValue(['branch', '--show-current']) ?: ''
def escapeJava = { String value -> value.replace('\\', '\\\\').replace('"', '\\"').replace('\n', ' ').replace('\r', ' ') }
def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true'
// The Unit tests workflow compiles no APK, so it has no add-on packs to pin.
def unitTestsOnly = project.findProperty('unitTestsOnly')?.toString()?.toBoolean() ?: false
def releaseSigner = rootProject.file('keystore/release-signer.sha256').text.trim()
def commitTime = (gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit]) ?: '0').with { it.isLong() ? it : '0' }
def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines()
@@ -96,10 +98,12 @@ def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines()
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic'].collectEntries { name ->
def pack = file("build/packs/${name}.tar.zst")
if (!pack.isFile()) {
if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
if (ciBuild && !unitTestsOnly) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
if (name == 'proot' && prootPackPin.PROOT_PACK_SHA256) {
return [(name): [sha256: prootPackPin.PROOT_PACK_SHA256, size: (prootPackPin.PROOT_PACK_SIZE ?: '0') as long]]
}
// A CI APK pins every pack, and CI_BUILD code assumes that, so the tests see a placeholder pin.
if (unitTestsOnly) return [(name): [sha256: '0' * 64, size: 0L]]
return [(name): [sha256: '', size: 0L]]
}
def digest = java.security.MessageDigest.getInstance('SHA-256')
@@ -238,6 +242,9 @@ android {
doFirst { jvmTemp.mkdirs() }
def logTarget = providers.systemProperty('robolectric.logging').orNull
if (logTarget != null) systemProperty 'robolectric.logging', logTarget
// Robolectric resolves Android SDK jars inside the test JVM independently of Gradle.
def robolectricMirror = providers.gradleProperty('robolectricMavenMirror').orNull
if (robolectricMirror) systemProperty 'robolectric.dependency.repo.url', robolectricMirror
}
}
@@ -1,13 +1,17 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.material.icons.filled.Settings
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.SecondScreenMode
@@ -26,6 +30,50 @@ private fun Launcher(tab: String, games: List<com.droiddeck.launcher.frontend.Li
@DroidDeckPreviews @Composable private fun SettingsPreview() = Launcher("setup")
@DroidDeckPreviews @Composable private fun RuntimeMissingPreview() = Launcher("setup", ready = false)
/** [content] over a stand-in wallpaper as the frost shows it, with see-through [cards] or solid ones. */
@Composable
private fun Frosted(transparency: Int = FROST_WALLPAPER_DEFAULT, cards: Boolean = false, cardTransparency: Int = FROST_DEFAULT, content: @Composable () -> Unit) =
DroidDeckTheme(frost = FrostChoice(transparency, cards, cardTransparency)) {
val wallpaper = Brush.linearGradient(listOf(Color(0xFFE2725B), Color(0xFF7A4BC2), Color(0xFF2A9D8F)))
Box(Modifier.fillMaxSize().background(wallpaper).background(LocalFrost.current ?: Color.Transparent)) { content() }
}
@Composable
private fun FrostedLauncher(tab: String, transparency: Int = FROST_WALLPAPER_DEFAULT, cards: Boolean = false, cardTransparency: Int = FROST_DEFAULT) =
Frosted(transparency, cards, cardTransparency) { FrontEndScreen(sampleState(navigate = tab), sampleActions) }
/** A settings step opened over frosted page text with see-through cards: the step is solid, so none of the text shows through it. */
@Composable
private fun FrostedStepOut() = Frosted(cards = true) {
val text: @Composable (Int) -> String = { androidx.compose.ui.res.stringResource(it) }
Column(Modifier.padding(24.dp)) {
val line = List(8) { text(R.string.stores_shelf_new) }.joinToString(" ")
repeat(14) { androidx.compose.material3.Text(line, fontSize = 24.sp, color = LocalPalette.current.onBackground, maxLines = 1, softWrap = false) }
}
androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize()) {
val pill = with(androidx.compose.ui.platform.LocalDensity.current) {
androidx.compose.ui.geometry.Rect(androidx.compose.ui.geometry.Offset((maxWidth - 68.dp).toPx(), 16.dp.toPx()), androidx.compose.ui.geometry.Size(44.dp.toPx(), 44.dp.toPx()))
}
val accent = LocalPalette.current.signal
StepOut(
open = true, pill = pill, preferredSide = StepSide.Left, accent = accent, onDismiss = {}, onClosed = {}, items = 2, maxWidth = 440.dp,
handle = { androidx.compose.material3.Icon(androidx.compose.material.icons.Icons.Filled.Settings, null, tint = accent, modifier = Modifier.size(20.dp)) },
) {
StepTitle(text(R.string.stores_settings_eyebrow))
Column(Modifier.stepItem(1)) {
SettingsRow(text(R.string.stores_show_mature), null) { ToggleSwitch(true, label = text(R.string.stores_show_mature)) {} }
SettingsRow(text(R.string.gog_achievements), text(R.string.gog_achievements_hint)) { ToggleSwitch(false, label = text(R.string.gog_achievements)) {} }
}
}
}
}
@DroidDeckPreviews @Composable private fun FrostedSteamTabPreview() = FrostedLauncher("steam")
@DroidDeckPreviews @Composable private fun FrostedLibraryPreview() = FrostedLauncher("games")
@DroidDeckPreviews @Composable private fun FrostedSettingsCardsPreview() = FrostedLauncher("setup", cards = true)
@DroidDeckPreviews @Composable private fun FrostedSettingsClearestPreview() = FrostedLauncher("setup", transparency = FROST_MAX, cards = true, cardTransparency = FROST_MAX)
@DroidDeckPreviews @Composable private fun FrostedStepOutPreview() = FrostedStepOut()
/** The in-game menu on one page, as a session shows it. */
@Composable
private fun SessionMenu(page: SessionDrawerPage, steam: Boolean = true, desktop: Boolean = false) = PreviewHost {
@@ -72,6 +120,11 @@ internal val previewCases: List<PreviewCase> = listOf(
PreviewCase("downloads") { Launcher("downloads") },
PreviewCase("settings") { Launcher("setup") },
PreviewCase("runtime-missing") { Launcher("setup", ready = false) },
PreviewCase("frosted-steam-tab") { FrostedLauncher("steam") },
PreviewCase("frosted-library", storesLoaded) { FrostedLauncher("games") },
PreviewCase("frosted-settings-cards") { FrostedLauncher("setup", cards = true) },
PreviewCase("frosted-settings-clearest") { FrostedLauncher("setup", transparency = FROST_MAX, cards = true, cardTransparency = FROST_MAX) },
PreviewCase("frosted-step-out") { FrostedStepOut() },
PreviewCase("session-menu-controller") { SessionMenu(SessionDrawerPage.CONTROLLER) },
PreviewCase("session-menu-display") { SessionMenu(SessionDrawerPage.DISPLAY) },
PreviewCase("session-menu-hud") { SessionMenu(SessionDrawerPage.HUD) },
+139
View File
@@ -277,6 +277,17 @@
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:theme="@style/AppTheme" />
<activity
android:name=".agent.AgentChatActivity"
android:exported="false"
android:launchMode="singleTask"
android:taskAffinity="${applicationId}.agentchat"
android:resizeableActivity="true"
android:theme="@style/AppTheme"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density">
<layout android:defaultWidth="720dp" android:defaultHeight="800dp" />
</activity>
<activity
android:name=".agent.AgentStartActivity"
android:exported="true"
@@ -417,5 +428,133 @@
android:name="backend:com.google.android.datatransport.cct.CctBackendFactory"
tools:node="remove" />
</service>
<service android:name=".runtime.GuestWorker0" android:exported="false" android:process=":g0" />
<service android:name=".runtime.GuestWorker1" android:exported="false" android:process=":g1" />
<service android:name=".runtime.GuestWorker2" android:exported="false" android:process=":g2" />
<service android:name=".runtime.GuestWorker3" android:exported="false" android:process=":g3" />
<service android:name=".runtime.GuestWorker4" android:exported="false" android:process=":g4" />
<service android:name=".runtime.GuestWorker5" android:exported="false" android:process=":g5" />
<service android:name=".runtime.GuestWorker6" android:exported="false" android:process=":g6" />
<service android:name=".runtime.GuestWorker7" android:exported="false" android:process=":g7" />
<service android:name=".runtime.GuestWorker8" android:exported="false" android:process=":g8" />
<service android:name=".runtime.GuestWorker9" android:exported="false" android:process=":g9" />
<service android:name=".runtime.GuestWorker10" android:exported="false" android:process=":g10" />
<service android:name=".runtime.GuestWorker11" android:exported="false" android:process=":g11" />
<service android:name=".runtime.GuestWorker12" android:exported="false" android:process=":g12" />
<service android:name=".runtime.GuestWorker13" android:exported="false" android:process=":g13" />
<service android:name=".runtime.GuestWorker14" android:exported="false" android:process=":g14" />
<service android:name=".runtime.GuestWorker15" android:exported="false" android:process=":g15" />
<service android:name=".runtime.GuestWorker16" android:exported="false" android:process=":g16" />
<service android:name=".runtime.GuestWorker17" android:exported="false" android:process=":g17" />
<service android:name=".runtime.GuestWorker18" android:exported="false" android:process=":g18" />
<service android:name=".runtime.GuestWorker19" android:exported="false" android:process=":g19" />
<service android:name=".runtime.GuestWorker20" android:exported="false" android:process=":g20" />
<service android:name=".runtime.GuestWorker21" android:exported="false" android:process=":g21" />
<service android:name=".runtime.GuestWorker22" android:exported="false" android:process=":g22" />
<service android:name=".runtime.GuestWorker23" android:exported="false" android:process=":g23" />
<service android:name=".runtime.GuestWorker24" android:exported="false" android:process=":g24" />
<service android:name=".runtime.GuestWorker25" android:exported="false" android:process=":g25" />
<service android:name=".runtime.GuestWorker26" android:exported="false" android:process=":g26" />
<service android:name=".runtime.GuestWorker27" android:exported="false" android:process=":g27" />
<service android:name=".runtime.GuestWorker28" android:exported="false" android:process=":g28" />
<service android:name=".runtime.GuestWorker29" android:exported="false" android:process=":g29" />
<service android:name=".runtime.GuestWorker30" android:exported="false" android:process=":g30" />
<service android:name=".runtime.GuestWorker31" android:exported="false" android:process=":g31" />
<service android:name=".runtime.GuestWorker32" android:exported="false" android:process=":g32" />
<service android:name=".runtime.GuestWorker33" android:exported="false" android:process=":g33" />
<service android:name=".runtime.GuestWorker34" android:exported="false" android:process=":g34" />
<service android:name=".runtime.GuestWorker35" android:exported="false" android:process=":g35" />
<service android:name=".runtime.GuestWorker36" android:exported="false" android:process=":g36" />
<service android:name=".runtime.GuestWorker37" android:exported="false" android:process=":g37" />
<service android:name=".runtime.GuestWorker38" android:exported="false" android:process=":g38" />
<service android:name=".runtime.GuestWorker39" android:exported="false" android:process=":g39" />
<service android:name=".runtime.GuestWorker40" android:exported="false" android:process=":g40" />
<service android:name=".runtime.GuestWorker41" android:exported="false" android:process=":g41" />
<service android:name=".runtime.GuestWorker42" android:exported="false" android:process=":g42" />
<service android:name=".runtime.GuestWorker43" android:exported="false" android:process=":g43" />
<service android:name=".runtime.GuestWorker44" android:exported="false" android:process=":g44" />
<service android:name=".runtime.GuestWorker45" android:exported="false" android:process=":g45" />
<service android:name=".runtime.GuestWorker46" android:exported="false" android:process=":g46" />
<service android:name=".runtime.GuestWorker47" android:exported="false" android:process=":g47" />
<service android:name=".runtime.GuestWorker48" android:exported="false" android:process=":g48" />
<service android:name=".runtime.GuestWorker49" android:exported="false" android:process=":g49" />
<service android:name=".runtime.GuestWorker50" android:exported="false" android:process=":g50" />
<service android:name=".runtime.GuestWorker51" android:exported="false" android:process=":g51" />
<service android:name=".runtime.GuestWorker52" android:exported="false" android:process=":g52" />
<service android:name=".runtime.GuestWorker53" android:exported="false" android:process=":g53" />
<service android:name=".runtime.GuestWorker54" android:exported="false" android:process=":g54" />
<service android:name=".runtime.GuestWorker55" android:exported="false" android:process=":g55" />
<service android:name=".runtime.GuestWorker56" android:exported="false" android:process=":g56" />
<service android:name=".runtime.GuestWorker57" android:exported="false" android:process=":g57" />
<service android:name=".runtime.GuestWorker58" android:exported="false" android:process=":g58" />
<service android:name=".runtime.GuestWorker59" android:exported="false" android:process=":g59" />
<service android:name=".runtime.GuestWorker60" android:exported="false" android:process=":g60" />
<service android:name=".runtime.GuestWorker61" android:exported="false" android:process=":g61" />
<service android:name=".runtime.GuestWorker62" android:exported="false" android:process=":g62" />
<service android:name=".runtime.GuestWorker63" android:exported="false" android:process=":g63" />
<service android:name=".runtime.GuestWorker64" android:exported="false" android:process=":g64" />
<service android:name=".runtime.GuestWorker65" android:exported="false" android:process=":g65" />
<service android:name=".runtime.GuestWorker66" android:exported="false" android:process=":g66" />
<service android:name=".runtime.GuestWorker67" android:exported="false" android:process=":g67" />
<service android:name=".runtime.GuestWorker68" android:exported="false" android:process=":g68" />
<service android:name=".runtime.GuestWorker69" android:exported="false" android:process=":g69" />
<service android:name=".runtime.GuestWorker70" android:exported="false" android:process=":g70" />
<service android:name=".runtime.GuestWorker71" android:exported="false" android:process=":g71" />
<service android:name=".runtime.GuestWorker72" android:exported="false" android:process=":g72" />
<service android:name=".runtime.GuestWorker73" android:exported="false" android:process=":g73" />
<service android:name=".runtime.GuestWorker74" android:exported="false" android:process=":g74" />
<service android:name=".runtime.GuestWorker75" android:exported="false" android:process=":g75" />
<service android:name=".runtime.GuestWorker76" android:exported="false" android:process=":g76" />
<service android:name=".runtime.GuestWorker77" android:exported="false" android:process=":g77" />
<service android:name=".runtime.GuestWorker78" android:exported="false" android:process=":g78" />
<service android:name=".runtime.GuestWorker79" android:exported="false" android:process=":g79" />
<service android:name=".runtime.GuestWorker80" android:exported="false" android:process=":g80" />
<service android:name=".runtime.GuestWorker81" android:exported="false" android:process=":g81" />
<service android:name=".runtime.GuestWorker82" android:exported="false" android:process=":g82" />
<service android:name=".runtime.GuestWorker83" android:exported="false" android:process=":g83" />
<service android:name=".runtime.GuestWorker84" android:exported="false" android:process=":g84" />
<service android:name=".runtime.GuestWorker85" android:exported="false" android:process=":g85" />
<service android:name=".runtime.GuestWorker86" android:exported="false" android:process=":g86" />
<service android:name=".runtime.GuestWorker87" android:exported="false" android:process=":g87" />
<service android:name=".runtime.GuestWorker88" android:exported="false" android:process=":g88" />
<service android:name=".runtime.GuestWorker89" android:exported="false" android:process=":g89" />
<service android:name=".runtime.GuestWorker90" android:exported="false" android:process=":g90" />
<service android:name=".runtime.GuestWorker91" android:exported="false" android:process=":g91" />
<service android:name=".runtime.GuestWorker92" android:exported="false" android:process=":g92" />
<service android:name=".runtime.GuestWorker93" android:exported="false" android:process=":g93" />
<service android:name=".runtime.GuestWorker94" android:exported="false" android:process=":g94" />
<service android:name=".runtime.GuestWorker95" android:exported="false" android:process=":g95" />
<service android:name=".runtime.GuestWorker96" android:exported="false" android:process=":g96" />
<service android:name=".runtime.GuestWorker97" android:exported="false" android:process=":g97" />
<service android:name=".runtime.GuestWorker98" android:exported="false" android:process=":g98" />
<service android:name=".runtime.GuestWorker99" android:exported="false" android:process=":g99" />
<service android:name=".runtime.GuestWorker100" android:exported="false" android:process=":g100" />
<service android:name=".runtime.GuestWorker101" android:exported="false" android:process=":g101" />
<service android:name=".runtime.GuestWorker102" android:exported="false" android:process=":g102" />
<service android:name=".runtime.GuestWorker103" android:exported="false" android:process=":g103" />
<service android:name=".runtime.GuestWorker104" android:exported="false" android:process=":g104" />
<service android:name=".runtime.GuestWorker105" android:exported="false" android:process=":g105" />
<service android:name=".runtime.GuestWorker106" android:exported="false" android:process=":g106" />
<service android:name=".runtime.GuestWorker107" android:exported="false" android:process=":g107" />
<service android:name=".runtime.GuestWorker108" android:exported="false" android:process=":g108" />
<service android:name=".runtime.GuestWorker109" android:exported="false" android:process=":g109" />
<service android:name=".runtime.GuestWorker110" android:exported="false" android:process=":g110" />
<service android:name=".runtime.GuestWorker111" android:exported="false" android:process=":g111" />
<service android:name=".runtime.GuestWorker112" android:exported="false" android:process=":g112" />
<service android:name=".runtime.GuestWorker113" android:exported="false" android:process=":g113" />
<service android:name=".runtime.GuestWorker114" android:exported="false" android:process=":g114" />
<service android:name=".runtime.GuestWorker115" android:exported="false" android:process=":g115" />
<service android:name=".runtime.GuestWorker116" android:exported="false" android:process=":g116" />
<service android:name=".runtime.GuestWorker117" android:exported="false" android:process=":g117" />
<service android:name=".runtime.GuestWorker118" android:exported="false" android:process=":g118" />
<service android:name=".runtime.GuestWorker119" android:exported="false" android:process=":g119" />
<service android:name=".runtime.GuestWorker120" android:exported="false" android:process=":g120" />
<service android:name=".runtime.GuestWorker121" android:exported="false" android:process=":g121" />
<service android:name=".runtime.GuestWorker122" android:exported="false" android:process=":g122" />
<service android:name=".runtime.GuestWorker123" android:exported="false" android:process=":g123" />
<service android:name=".runtime.GuestWorker124" android:exported="false" android:process=":g124" />
<service android:name=".runtime.GuestWorker125" android:exported="false" android:process=":g125" />
<service android:name=".runtime.GuestWorker126" android:exported="false" android:process=":g126" />
<service android:name=".runtime.GuestWorker127" android:exported="false" android:process=":g127" />
</application>
</manifest>
+34 -13
View File
@@ -329,16 +329,28 @@ static constexpr int kWatchedFds = 1 << 16;
static constexpr int kWatchedBits = sizeof(unsigned long) * 8;
static std::atomic<unsigned long> watched_fds[kWatchedFds / kWatchedBits];
static std::atomic<bool> watched_beyond{false};
static std::atomic<int> watched_count{0};
static void watch_fd(int fd) {
if (fd < 0) return;
if (fd >= kWatchedFds) watched_beyond.store(true, std::memory_order_release);
else watched_fds[fd / kWatchedBits].fetch_or(1UL << (fd % kWatchedBits), std::memory_order_release);
if (fd >= kWatchedFds) {
watched_beyond.store(true, std::memory_order_release);
return;
}
const unsigned long bit = 1UL << (fd % kWatchedBits);
if (!(watched_fds[fd / kWatchedBits].fetch_or(bit, std::memory_order_acq_rel) & bit))
watched_count.fetch_add(1, std::memory_order_acq_rel);
}
static void unwatch_fd(int fd) {
if (fd >= 0 && fd < kWatchedFds)
watched_fds[fd / kWatchedBits].fetch_and(~(1UL << (fd % kWatchedBits)), std::memory_order_release);
if (fd < 0 || fd >= kWatchedFds) return;
const unsigned long bit = 1UL << (fd % kWatchedBits);
if (watched_fds[fd / kWatchedBits].fetch_and(~bit, std::memory_order_acq_rel) & bit)
watched_count.fetch_sub(1, std::memory_order_acq_rel);
}
static bool any_watched() {
return watched_count.load(std::memory_order_acquire) > 0 || watched_beyond.load(std::memory_order_acquire);
}
static bool watched(int fd) {
@@ -4130,13 +4142,20 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) {
return read_input(fd, buf, count);
}
// glibc's fortify failure; bionic (DroidDeck-Bionic preloads this library into its Wine processes) has no
// __chk_fail, and a library naming it there cannot be loaded, which stops every Wine program from starting.
#if defined(__BIONIC__)
[[noreturn]] static void fakeinput_chk_fail(void) { abort(); }
#else
extern "C" [[noreturn]] void __chk_fail(void);
[[noreturn]] static void fakeinput_chk_fail(void) { __chk_fail(); }
#endif
/* Programs built with _FORTIFY_SOURCE (Flatpak runtimes among them) call these instead of read, poll
* and ppoll, and glibc's versions go straight to the kernel. */
EXPORT ssize_t __read_chk(int fd, void *buf, size_t count, size_t buflen) {
static auto next_read_chk = reinterpret_cast<ssize_t (*)(int, void *, size_t, size_t)>(dlsym(RTLD_NEXT, "__read_chk"));
if (count > buflen) __chk_fail();
if (count > buflen) fakeinput_chk_fail();
if (next_read_chk && !is_fake_input_fd(fd)) return next_read_chk(fd, buf, count, buflen);
return read_input(fd, buf, count);
}
@@ -4262,7 +4281,7 @@ static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout,
const auto my_poll = next_symbol<decltype(&::poll)>(Next::poll);
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
nfds_t first = 0;
nfds_t first = any_watched() ? 0 : nfds;
while (first < nfds && !watched(fds[first].fd)) first++;
bool has_fake_fds = false;
std::vector<struct pollfd> real_fds;
@@ -4365,12 +4384,12 @@ EXPORT int poll(struct pollfd *fds, nfds_t nfds, int timeout) {
EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
const struct timespec *timeout, const sigset_t *sigmask) {
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
errno = EINVAL;
return -1;
}
for (nfds_t i = 0; i < nfds; ++i) {
for (nfds_t i = 0; any_watched() && i < nfds; ++i) {
if (!is_fake_input_fd(fds[i].fd)) continue;
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
errno = EINVAL;
return -1;
}
if (!sigmask)
return poll_fake(fds, nfds, static_cast<int>(timespec_to_ms(timeout)), nullptr);
sigset_t all_signals, original_mask;
@@ -4390,19 +4409,21 @@ EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
}
EXPORT int __poll_chk(struct pollfd *fds, nfds_t nfds, int timeout, size_t fdslen) {
if (fdslen / sizeof(*fds) < nfds) __chk_fail();
if (fdslen / sizeof(*fds) < nfds) fakeinput_chk_fail();
return poll(fds, nfds, timeout);
}
EXPORT int __ppoll_chk(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout,
const sigset_t *sigmask, size_t fdslen) {
if (fdslen / sizeof(*fds) < nfds) __chk_fail();
if (fdslen / sizeof(*fds) < nfds) fakeinput_chk_fail();
return ppoll(fds, nfds, timeout, sigmask);
}
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout) {
const auto my_select = next_symbol<decltype(&::select)>(Next::select);
if (!any_watched())
return my_select ? my_select(nfds, readfds, writefds, exceptfds, timeout) : -1;
fd_set original_readfds;
fd_set original_writefds;
+1 -1
View File
@@ -8,6 +8,6 @@ target_compile_features(droiddeckxr PRIVATE cxx_std_17)
target_compile_definitions(droiddeckxr PRIVATE XR_USE_PLATFORM_ANDROID XR_USE_GRAPHICS_API_OPENGL_ES XR_USE_TIMESPEC)
target_compile_options(droiddeckxr PRIVATE -Wall -Wextra -Wno-missing-field-initializers -Werror=return-type)
target_link_options(droiddeckxr PRIVATE -Wl,-z,max-page-size=16384 -uANativeActivity_onCreate)
target_link_libraries(droiddeckxr PRIVATE droiddeckxr_glue OpenXR::openxr_loader EGL GLESv3 android log)
target_link_libraries(droiddeckxr PRIVATE droiddeckxr_glue OpenXR::openxr_loader EGL GLESv3 android jnigraphics log)
target_include_directories(droiddeckxr PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../tools/vr/src)
+325 -21
View File
@@ -1,6 +1,7 @@
#include <jni.h>
#include <EGL/egl.h>
#include <GLES3/gl3.h>
#include <android/bitmap.h>
#include <android/log.h>
#include <android_native_app_glue.h>
#include <time.h>
@@ -22,10 +23,14 @@
#include <cerrno>
#include <cstddef>
#include <ctime>
#include <pthread.h>
#include <algorithm>
#include "xr_tracking.h"
#include "xr_frame_channel.h"
#include "xr_frame_math.h"
#include "gpu_frames.h"
#include "xr_host.h"
#include "xr_overlay.h"
static void check(XrResult result, const char *operation) {
if (XR_FAILED(result)) throw std::runtime_error(std::string(operation) + ": " + std::to_string(result));
@@ -37,6 +42,15 @@ struct Eye {
std::vector<XrSwapchainImageOpenGLESKHR> images;
};
struct SurfaceLayer {
XrSwapchain swapchain = XR_NULL_HANDLE;
jobject surface = nullptr;
int width = 0, height = 0;
};
class QuestXR;
static QuestXR *g_runtime = nullptr;
class QuestXR {
public:
explicit QuestXR(android_app *app) : app_(app) {}
@@ -76,21 +90,74 @@ public:
"\"headPosition\":[%.6f,%.6f,%.6f],\"controllersActive\":[%s,%s],"
"\"periodNs\":%lld,\"surfaceSwapchain\":%s,\"source\":\"%s\",\"guestFrames\":%lld,\"steamvrState\":%d,"
"\"receivedFrames\":%llu,\"rejectedFrames\":%llu,\"uploadedFrames\":%llu,\"sourceFrameId\":%llu,"
"\"gpuReceivedFrames\":%llu,\"gpuDroppedFrames\":%llu,\"gpuVerifiedFrameId\":%llu,\"gpuChecksum\":%u,\"error\":\"%s\"}\n",
"\"gpuReceivedFrames\":%llu,\"gpuDroppedFrames\":%llu,\"gpuVerifiedFrameId\":%llu,\"gpuChecksum\":%u,"
"\"hostVersion\":%u,\"visibleLayers\":%d,\"overlay\":%s,\"error\":\"%s\"}\n",
(unsigned long long)frames_, (unsigned long long)rendered_, state_,
(unsigned long long)head_.locationFlags,
head_.pose.position.x, head_.pose.position.y, head_.pose.position.z,
handActive_[0] ? "true" : "false", handActive_[1] ? "true" : "false",
(long long)period_, "false", "frames",
(long long)period_, surfaceSupported_ ? "true" : "false", "frames",
0LL, steamvrState, (unsigned long long)(receiver_.Received() + gpuFrames_.Received()),
(unsigned long long)(receiver_.Rejected() + gpuFrames_.Rejected()),
(unsigned long long)uploadedFrames_, (unsigned long long)sourceHeader_.frame_id,
(unsigned long long)gpuFrames_.Received(), (unsigned long long)gpuFrames_.Dropped(),
(unsigned long long)verifiedFrame_, gpuChecksum_, error);
(unsigned long long)verifiedFrame_, gpuChecksum_,
hostBuffers_ ? DROIDDECK_XR_HOST_VERSION : 0u, visibleLayers_,
XrOverlay::active(hostControl_) ? "true" : "false", error);
std::fclose(file);
std::rename(temp.c_str(), path.c_str());
}
bool onXrThread() const { return pthread_equal(pthread_self(), xrThread_); }
int createLayer(JNIEnv *env, int width, int height) {
if (!onXrThread() || !createSurfaceSwapchain_ || session_ == XR_NULL_HANDLE || width <= 0 || height <= 0) return -1;
for (int index = 0; index < DROIDDECK_XR_HOST_LAYERS; index++) {
SurfaceLayer &layer = layers_[index];
if (layer.swapchain) continue;
XrSwapchainCreateInfo create{XR_TYPE_SWAPCHAIN_CREATE_INFO};
create.usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT;
create.width = width; create.height = height;
jobject surface = nullptr;
XrResult result = createSurfaceSwapchain_(session_, &create, &layer.swapchain, &surface);
if (XR_FAILED(result) || !surface) {
__android_log_print(ANDROID_LOG_ERROR, "DroidDeckXR", "surface layer %dx%d failed: %d", width, height, result);
if (layer.swapchain) xrDestroySwapchain(layer.swapchain);
layer = {};
return -1;
}
layer.surface = env->NewGlobalRef(surface);
layer.width = width; layer.height = height;
__android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "surface layer %d created %dx%d", index, width, height);
return index;
}
return -1;
}
jobject layerSurface(JNIEnv *env, int index) {
if (!onXrThread() || index < 0 || index >= DROIDDECK_XR_HOST_LAYERS || !layers_[index].surface) return nullptr;
return env->NewLocalRef(layers_[index].surface);
}
void setOrbImage(JNIEnv *env, jobject bitmap) {
if (!onXrThread() || !bitmap) return;
AndroidBitmapInfo info{};
void *pixels = nullptr;
if (AndroidBitmap_getInfo(env, bitmap, &info) != ANDROID_BITMAP_RESULT_SUCCESS
|| info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) return;
if (AndroidBitmap_lockPixels(env, bitmap, &pixels) != ANDROID_BITMAP_RESULT_SUCCESS) return;
overlay_.setLogo(pixels, (int)info.width, (int)info.height, (int)info.stride);
AndroidBitmap_unlockPixels(env, bitmap);
}
void destroyLayer(JNIEnv *env, int index) {
if (!onXrThread() || index < 0 || index >= DROIDDECK_XR_HOST_LAYERS) return;
SurfaceLayer &layer = layers_[index];
if (layer.swapchain) xrDestroySwapchain(layer.swapchain);
if (layer.surface) env->DeleteGlobalRef(layer.surface);
layer = {};
}
private:
android_app *app_;
JNIEnv *env_ = nullptr;
@@ -104,6 +171,20 @@ private:
XrAction primary_ = XR_NULL_HANDLE, secondary_ = XR_NULL_HANDLE, menu_ = XR_NULL_HANDLE;
XrAction triggerTouch_ = XR_NULL_HANDLE, stickTouch_ = XR_NULL_HANDLE, primaryTouch_ = XR_NULL_HANDLE;
XrAction secondaryTouch_ = XR_NULL_HANDLE, thumbrestTouch_ = XR_NULL_HANDLE;
PFN_xrCreateSwapchainAndroidSurfaceKHR createSurfaceSwapchain_ = nullptr;
bool surfaceSupported_ = false;
bool imageLayoutSupported_ = false;
pthread_t xrThread_{};
SurfaceLayer layers_[DROIDDECK_XR_HOST_LAYERS];
DroidDeckXrHostState hostState_{};
DroidDeckXrHostControl hostControl_{};
bool hostBuffers_ = false;
jmethodID hostFrameCallback_ = nullptr;
uint64_t hostPulse_[2]{};
int visibleLayers_ = 0;
XrOverlay overlay_;
Eye overlayEyes_[2];
GLuint overlayDepth_[2]{};
DroidDeckXrHand inputs_[2]{};
PFN_xrConvertTimeToTimespecTimeKHR convertTime_ = nullptr;
bool timespecSupported_ = false;
@@ -220,6 +301,8 @@ private:
void initialize() {
app_->userData = this;
xrThread_ = pthread_self();
g_runtime = this;
app_->onInputEvent = [](android_app *app, AInputEvent *event) -> int32_t {
if (AInputEvent_getType(event) != AINPUT_EVENT_TYPE_KEY || AKeyEvent_getKeyCode(event) != AKEYCODE_BACK
|| AKeyEvent_getAction(event) != AKEY_EVENT_ACTION_UP) return 0;
@@ -244,6 +327,10 @@ private:
frameCallback_ = env_->GetMethodID(activityClass, "onXrFrame", "(J)V");
statusCallback_ = env_->GetMethodID(activityClass, "onXrStatus", "()I");
if (env_->ExceptionCheck()) { env_->ExceptionClear(); throw std::runtime_error("XR activity bridge methods unavailable"); }
hostFrameCallback_ = env_->GetMethodID(activityClass, "onXrHostFrame", "()V");
jmethodID hostBuffersCallback = hostFrameCallback_ ?
env_->GetMethodID(activityClass, "onXrHostBuffers", "(Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)V") : nullptr;
if (env_->ExceptionCheck()) { env_->ExceptionClear(); hostFrameCallback_ = nullptr; hostBuffersCallback = nullptr; }
env_->DeleteLocalRef(intentClass); env_->DeleteLocalRef(intent); env_->DeleteLocalRef(activityClass);
PFN_xrInitializeLoaderKHR initializeLoader = nullptr;
check(xrGetInstanceProcAddr(XR_NULL_HANDLE, "xrInitializeLoaderKHR",
@@ -261,10 +348,21 @@ private:
timespecSupported_ = true;
if (!std::strcmp(extension.extensionName, XR_EXT_PERFORMANCE_SETTINGS_EXTENSION_NAME))
performanceSupported_ = true;
if (!std::strcmp(extension.extensionName, XR_KHR_ANDROID_SURFACE_SWAPCHAIN_EXTENSION_NAME))
surfaceSupported_ = true;
if (!std::strcmp(extension.extensionName, XR_FB_COMPOSITION_LAYER_IMAGE_LAYOUT_EXTENSION_NAME))
imageLayoutSupported_ = true;
}
__android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "surface swapchain available=%d image layout=%d",
surfaceSupported_, imageLayoutSupported_);
// A surface swapchain's image arrives upside down, and a quad's back face is not drawn, so
// panels need the layout flag to flip it.
surfaceSupported_ = surfaceSupported_ && imageLayoutSupported_;
std::vector<const char *> enabled{XR_KHR_ANDROID_CREATE_INSTANCE_EXTENSION_NAME, XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME};
if (timespecSupported_) enabled.push_back(XR_KHR_CONVERT_TIMESPEC_TIME_EXTENSION_NAME);
if (performanceSupported_) enabled.push_back(XR_EXT_PERFORMANCE_SETTINGS_EXTENSION_NAME);
if (surfaceSupported_) enabled.push_back(XR_KHR_ANDROID_SURFACE_SWAPCHAIN_EXTENSION_NAME);
if (surfaceSupported_) enabled.push_back(XR_FB_COMPOSITION_LAYER_IMAGE_LAYOUT_EXTENSION_NAME);
XrInstanceCreateInfoAndroidKHR androidInfo{XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR};
androidInfo.applicationVM = app_->activity->vm;
androidInfo.applicationActivity = app_->activity->clazz;
@@ -281,6 +379,11 @@ private:
reinterpret_cast<PFN_xrVoidFunction *>(&setPerformance_));
if (XR_FAILED(result)) setPerformance_ = nullptr;
}
if (surfaceSupported_ && XR_FAILED(xrGetInstanceProcAddr(instance_, "xrCreateSwapchainAndroidSurfaceKHR",
reinterpret_cast<PFN_xrVoidFunction *>(&createSurfaceSwapchain_)))) {
createSurfaceSwapchain_ = nullptr;
surfaceSupported_ = false;
}
if (timespecSupported_) check(xrGetInstanceProcAddr(instance_, "xrConvertTimeToTimespecTimeKHR",
reinterpret_cast<PFN_xrVoidFunction *>(&convertTime_)), "time conversion entrypoint");
XrSystemGetInfo systemInfo{XR_TYPE_SYSTEM_GET_INFO};
@@ -334,6 +437,16 @@ private:
bool gpu = !verifyPixels_ && gpuFrames_.Start(std::string(app_->activity->internalDataPath) + "/.wayland-rt/" DROIDDECK_XR_GPU_SOCKET, display_);
__android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "GPU frame channel available=%d", gpu);
}
overlay_.initialize();
hostState_.version = DROIDDECK_XR_HOST_VERSION;
if (hostBuffersCallback) {
jobject state = env_->NewDirectByteBuffer(&hostState_, sizeof(hostState_));
jobject control = env_->NewDirectByteBuffer(&hostControl_, sizeof(hostControl_));
env_->CallVoidMethod(app_->activity->clazz, hostBuffersCallback, state, control);
if (env_->ExceptionCheck()) { env_->ExceptionDescribe(); env_->ExceptionClear(); hostFrameCallback_ = nullptr; }
else hostBuffers_ = true;
env_->DeleteLocalRef(state); env_->DeleteLocalRef(control);
}
health();
}
@@ -422,6 +535,13 @@ private:
target.images.resize(count, {XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR});
check(xrEnumerateSwapchainImages(target.swapchain, count, &count,
reinterpret_cast<XrSwapchainImageBaseHeader *>(target.images.data())), "images");
Eye &overlay = overlayEyes_[eye];
overlay.width = target.width; overlay.height = target.height;
check(xrCreateSwapchain(session_, &create, &overlay.swapchain), "overlay swapchain");
check(xrEnumerateSwapchainImages(overlay.swapchain, 0, &count, nullptr), "overlay image count");
overlay.images.resize(count, {XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR});
check(xrEnumerateSwapchainImages(overlay.swapchain, count, &count,
reinterpret_cast<XrSwapchainImageBaseHeader *>(overlay.images.data())), "overlay images");
}
}
@@ -530,6 +650,12 @@ private:
void initializeGraphics() {
glGenFramebuffers(1, &framebuffer_);
glGenRenderbuffers(2, overlayDepth_);
for (int eye = 0; eye < 2; eye++) {
glBindRenderbuffer(GL_RENDERBUFFER, overlayDepth_[eye]);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, overlayEyes_[eye].width, overlayEyes_[eye].height);
}
glBindRenderbuffer(GL_RENDERBUFFER, 0);
glGenVertexArrays(1, &vertexArray_);
GLuint vertex = shader(GL_VERTEX_SHADER,
"#version 300 es\nout vec2 uv; uniform float eye; void main(){vec2 coordinate=vec2(float((gl_VertexID<<1)&2),float(gl_VertexID&2));uv=vec2(coordinate.x*0.5+eye*0.5,1.0-coordinate.y);gl_Position=vec4(coordinate*2.0-1.0,0.0,1.0);}");
@@ -584,24 +710,46 @@ private:
if (verifyPixels_ || uploadedFrames_ % 72 == 1) health();
}
void render(Eye &eye, uint32_t image) {
void render(Eye &eye, uint32_t image, bool source, const XrPosef &pose, const XrFovf &fov, float seconds) {
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, eye.images[image].image, 0);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
throw std::runtime_error("Incomplete eye framebuffer");
{
glViewport(0, 0, eye.width, eye.height); glDisable(GL_DEPTH_TEST);
glViewport(0, 0, eye.width, eye.height); glDisable(GL_DEPTH_TEST);
if (source) {
glUseProgram(sourceProgram_); glBindVertexArray(vertexArray_);
glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, sourceTexture_);
glUniform1i(glGetUniformLocation(sourceProgram_, "source"), 0);
glUniform1f(glGetUniformLocation(sourceProgram_, "eye"), &eye == &eyes_[1] ? 1.f : 0.f);
glDrawArrays(GL_TRIANGLES, 0, 3);
} else {
glClearColor(0.f, 0.f, 0.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT);
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
if (glGetError() != GL_NO_ERROR) throw std::runtime_error("OpenGL render error");
glFlush();
}
// Lasers and the orb go in their own layer above the panels, which only the panels' depth hides.
void renderOverlay(int index, uint32_t image, const XrPosef &pose, const XrFovf &fov, float seconds) {
Eye &eye = overlayEyes_[index];
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, eye.images[image].image, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, overlayDepth_[index]);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
throw std::runtime_error("Incomplete overlay framebuffer");
glViewport(0, 0, eye.width, eye.height);
glClearColor(0.f, 0.f, 0.f, 0.f); glClearDepthf(1.f);
glDepthMask(GL_TRUE);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
overlay_.draw(pose, fov, hostControl_, hostState_, seconds);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
if (glGetError() != GL_NO_ERROR) throw std::runtime_error("OpenGL overlay error");
glFlush();
}
void pollEvents() {
XrEventDataBuffer event{XR_TYPE_EVENT_DATA_BUFFER};
XrResult result;
@@ -685,6 +833,7 @@ private:
XrViewState viewState{XR_TYPE_VIEW_STATE}; uint32_t count = 0;
XrView views[2]{{XR_TYPE_VIEW}, {XR_TYPE_VIEW}};
check(xrLocateViews(session_, &locate, &viewState, 2, &count, views), "xrLocateViews");
hostFrame(frameState.predictedDisplayTime);
publishTracking(views, frameState.predictedDisplayTime);
if (guestAttached_) {
timespec now{}; clock_gettime(CLOCK_MONOTONIC, &now);
@@ -692,29 +841,34 @@ private:
if (env_->ExceptionCheck()) { env_->ExceptionClear(); throw std::runtime_error("Guest frame callback failed"); }
}
XrCompositionLayerProjectionView projection[2]{{XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}, {XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}};
bool valid = frameState.shouldRender && count == 2 &&
const bool viewsValid = frameState.shouldRender && count == 2 &&
(viewState.viewStateFlags & (XR_VIEW_STATE_ORIENTATION_VALID_BIT | XR_VIEW_STATE_POSITION_VALID_BIT))
== (XR_VIEW_STATE_ORIENTATION_VALID_BIT | XR_VIEW_STATE_POSITION_VALID_BIT);
{
valid = valid && sourceHeader_.frame_id && xr_frame_now() - sourceHeader_.captured_ns < 500000000LL;
if (valid) for (int eye = 0; eye < 2; eye++) {
auto source = xr_frame_view(sourceHeader_, eye);
views[eye].pose.orientation = {source.orientation[0], source.orientation[1], source.orientation[2], source.orientation[3]};
views[eye].pose.position = {source.position[0], source.position[1], source.position[2]};
views[eye].fov = {source.fov[0], source.fov[1], source.fov[2], source.fov[3]};
}
bool valid = viewsValid && sourceHeader_.frame_id && xr_frame_now() - sourceHeader_.captured_ns < 500000000LL;
if (valid) for (int eye = 0; eye < 2; eye++) {
auto source = xr_frame_view(sourceHeader_, eye);
views[eye].pose.orientation = {source.orientation[0], source.orientation[1], source.orientation[2], source.orientation[3]};
views[eye].pose.position = {source.position[0], source.position[1], source.position[2]};
views[eye].fov = {source.fov[0], source.fov[1], source.fov[2], source.fov[3]};
}
std::vector<XrCompositionLayerQuad> quads;
std::vector<XrCompositionLayerImageLayoutFB> layouts;
if (viewsValid) collectQuads(quads, layouts);
const bool uiOnly = !valid && viewsValid && !quads.empty();
const bool draw = valid || uiOnly;
const std::string capture = captureRequest();
bool captured = valid;
if (!capture.empty() && valid)
captured = captureTexture(sourceTexture_, sourceHeader_.width, sourceHeader_.height, "source");
if (valid) for (int eye = 0; eye < 2; eye++) {
timespec clock{}; clock_gettime(CLOCK_MONOTONIC, &clock);
const float seconds = (float)(clock.tv_sec % 3600) + clock.tv_nsec * 1e-9f;
if (draw) for (int eye = 0; eye < 2; eye++) {
uint32_t image = 0;
XrSwapchainImageAcquireInfo acquire{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO};
check(xrAcquireSwapchainImage(eyes_[eye].swapchain, &acquire, &image), "acquire image");
XrSwapchainImageWaitInfo imageWait{XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO}; imageWait.timeout = XR_INFINITE_DURATION;
check(xrWaitSwapchainImage(eyes_[eye].swapchain, &imageWait), "wait image");
render(eyes_[eye], image);
render(eyes_[eye], image, valid, views[eye].pose, views[eye].fov, seconds);
if (!capture.empty()) captured = captureTexture(eyes_[eye].images[image].image, eyes_[eye].width, eyes_[eye].height, eye ? "right" : "left") && captured;
XrSwapchainImageReleaseInfo release{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO};
check(xrReleaseSwapchainImage(eyes_[eye].swapchain, &release), "release image");
@@ -722,19 +876,143 @@ private:
projection[eye].subImage.swapchain = eyes_[eye].swapchain;
projection[eye].subImage.imageRect.extent = {eyes_[eye].width, eyes_[eye].height};
}
const bool overlay = viewsValid && hostBuffers_ && XrOverlay::active(hostControl_);
XrCompositionLayerProjectionView overlayViews[2]{{XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}, {XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}};
if (overlay) for (int eye = 0; eye < 2; eye++) {
uint32_t image = 0;
XrSwapchainImageAcquireInfo acquire{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO};
check(xrAcquireSwapchainImage(overlayEyes_[eye].swapchain, &acquire, &image), "acquire overlay image");
XrSwapchainImageWaitInfo imageWait{XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO}; imageWait.timeout = XR_INFINITE_DURATION;
check(xrWaitSwapchainImage(overlayEyes_[eye].swapchain, &imageWait), "wait overlay image");
renderOverlay(eye, image, views[eye].pose, views[eye].fov, seconds);
XrSwapchainImageReleaseInfo release{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO};
check(xrReleaseSwapchainImage(overlayEyes_[eye].swapchain, &release), "release overlay image");
overlayViews[eye].pose = views[eye].pose; overlayViews[eye].fov = views[eye].fov;
overlayViews[eye].subImage.swapchain = overlayEyes_[eye].swapchain;
overlayViews[eye].subImage.imageRect.extent = {overlayEyes_[eye].width, overlayEyes_[eye].height};
}
XrCompositionLayerProjection layer{XR_TYPE_COMPOSITION_LAYER_PROJECTION};
layer.space = world_; layer.viewCount = 2; layer.views = projection;
const XrCompositionLayerBaseHeader *layers[] = {reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer)};
XrCompositionLayerProjection overlayLayer{XR_TYPE_COMPOSITION_LAYER_PROJECTION};
overlayLayer.layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
overlayLayer.space = world_; overlayLayer.viewCount = 2; overlayLayer.views = overlayViews;
std::vector<const XrCompositionLayerBaseHeader *> layers;
if (draw) layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer));
for (auto &quad : quads) layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&quad));
if (overlay) layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&overlayLayer));
visibleLayers_ = (int)quads.size();
XrFrameEndInfo end{XR_TYPE_FRAME_END_INFO}; end.displayTime = frameState.predictedDisplayTime;
end.environmentBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; end.layerCount = valid ? 1 : 0; end.layers = layers;
end.environmentBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
end.layerCount = (uint32_t)layers.size(); end.layers = layers.data();
check(xrEndFrame(session_, &end), "xrEndFrame");
if (!capture.empty()) captureResult(capture, captured, valid, projection, frameState.predictedDisplayTime);
frames_++; if (valid) rendered_++;
if (frames_ % 72 == 0) {
health();
__android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "frames=%llu rendered=%llu head=%llu hands=%d,%d period=%lld",
__android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "frames=%llu rendered=%llu head=%llu hands=%d,%d period=%lld layers=%d",
(unsigned long long)frames_, (unsigned long long)rendered_, (unsigned long long)head_.locationFlags,
handActive_[0], handActive_[1], (long long)period_);
handActive_[0], handActive_[1], (long long)period_, visibleLayers_);
}
}
// Android surfaces are stored top row first, while OpenXR samples images bottom row first.
void collectQuads(std::vector<XrCompositionLayerQuad> &quads, std::vector<XrCompositionLayerImageLayoutFB> &layouts) {
if (!hostBuffers_) return;
quads.reserve(DROIDDECK_XR_HOST_LAYERS);
layouts.reserve(DROIDDECK_XR_HOST_LAYERS);
const DroidDeckXrHostLayer *ordered[DROIDDECK_XR_HOST_LAYERS];
int visible = 0;
for (const auto &layer : hostControl_.layers) {
if (!layer.visible || layer.id < 0 || layer.id >= DROIDDECK_XR_HOST_LAYERS || !layers_[layer.id].swapchain) continue;
if (!(layer.width > 0.f) || !(layer.height > 0.f)) continue;
ordered[visible++] = &layer;
}
std::sort(ordered, ordered + visible, [](const DroidDeckXrHostLayer *a, const DroidDeckXrHostLayer *b) { return a->order < b->order; });
for (int index = 0; index < visible; index++) {
const auto &layer = *ordered[index];
const SurfaceLayer &surface = layers_[layer.id];
XrCompositionLayerQuad quad{XR_TYPE_COMPOSITION_LAYER_QUAD};
quad.layerFlags = (layer.flags & DROIDDECK_XR_HOST_LAYER_ALPHA) ? XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT : 0;
quad.space = (layer.flags & DROIDDECK_XR_HOST_LAYER_HEAD_LOCKED) ? view_ : world_;
quad.eyeVisibility = XR_EYE_VISIBILITY_BOTH;
quad.subImage.swapchain = surface.swapchain;
quad.subImage.imageRect.extent = {surface.width, surface.height};
quad.pose.orientation = {layer.pose.orientation[0], layer.pose.orientation[1], layer.pose.orientation[2], layer.pose.orientation[3]};
quad.pose.position = {layer.pose.position[0], layer.pose.position[1], layer.pose.position[2]};
quad.size = {layer.width, layer.height};
layouts.push_back({XR_TYPE_COMPOSITION_LAYER_IMAGE_LAYOUT_FB, nullptr, XR_COMPOSITION_LAYER_IMAGE_LAYOUT_VERTICAL_FLIP_BIT_FB});
quad.next = &layouts.back();
quads.push_back(quad);
}
}
// SteamVR draws its laser from the "tip" of the Quest Touch render model the driver names
// (resources/rendermodels/oculus_quest_plus_controller_*), placed on the raw grip pose; panels
// use the same ray so there is one laser per controller.
static DroidDeckXrPose steamVrPointer(const XrSpaceLocation &grip, int hand) {
const float q[4] = {grip.pose.orientation.x, grip.pose.orientation.y, grip.pose.orientation.z, grip.pose.orientation.w};
const XrVec3 tip{hand == 0 ? 0.016694f : -0.016694f, -0.02522f, 0.024687f};
const XrVec3 at = XrVec3{grip.pose.position.x, grip.pose.position.y, grip.pose.position.z} + rotate(q, tip);
const float tx = -0.320613f, tw = 0.947210f;
DroidDeckXrPose pose{};
pose.orientation[0] = q[3] * tx + q[0] * tw;
pose.orientation[1] = q[1] * tw + q[2] * tx;
pose.orientation[2] = q[2] * tw - q[1] * tx;
pose.orientation[3] = q[3] * tw - q[0] * tx;
pose.position[0] = at.x; pose.position[1] = at.y; pose.position[2] = at.z;
pose.flags = (uint32_t)grip.locationFlags;
return pose;
}
void hostFrame(XrTime predicted) {
if (!hostBuffers_ || !hostFrameCallback_) return;
hostState_.version = DROIDDECK_XR_HOST_VERSION;
hostState_.session_state = state_;
hostState_.flags = (surfaceSupported_ ? DROIDDECK_XR_HOST_SURFACE_SWAPCHAIN : 0u) |
(state_ == XR_SESSION_STATE_FOCUSED ? DROIDDECK_XR_HOST_FOCUSED : 0u);
hostState_.frame = (int64_t)frames_;
hostState_.display_time_ns = 0;
if (convertTime_) {
timespec displayTime{};
if (XR_SUCCEEDED(convertTime_(instance_, predicted, &displayTime)))
hostState_.display_time_ns = (int64_t)displayTime.tv_sec * 1000000000LL + displayTime.tv_nsec;
}
hostState_.head = posePacket(head_.pose, head_.locationFlags);
const XrSpaceLocationFlags tracked = XR_SPACE_LOCATION_ORIENTATION_VALID_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT;
for (int hand = 0; hand < 2; hand++) {
auto &out = hostState_.hands[hand];
out.grip = posePacket(handLocations_[hand].pose, handLocations_[hand].locationFlags);
out.aim = steamVrPointer(handLocations_[hand], hand);
out.trigger = inputs_[hand].trigger; out.squeeze = inputs_[hand].squeeze;
out.stick[0] = inputs_[hand].stick[0]; out.stick[1] = inputs_[hand].stick[1];
out.buttons = inputs_[hand].buttons;
out.active = handActive_[hand] && (handLocations_[hand].locationFlags & tracked) == tracked;
}
env_->CallVoidMethod(app_->activity->clazz, hostFrameCallback_);
if (env_->ExceptionCheck()) {
env_->ExceptionDescribe(); env_->ExceptionClear();
hostControl_ = {};
return;
}
if (hostControl_.version != DROIDDECK_XR_HOST_VERSION) { hostControl_ = {}; return; }
for (int hand = 0; hand < 2; hand++) {
const auto &control = hostControl_.hands[hand];
if (control.mask & DROIDDECK_XR_HOST_MASK_INPUT) {
inputs_[hand].trigger = 0; inputs_[hand].squeeze = 0;
inputs_[hand].stick[0] = inputs_[hand].stick[1] = 0;
inputs_[hand].buttons = 0;
}
const auto &pulse = control.haptic;
if (pulse.id == hostPulse_[hand]) continue;
hostPulse_[hand] = pulse.id;
if (state_ != XR_SESSION_STATE_FOCUSED || !handActive_[hand]
|| pulse.duration_ns < 1000000 || pulse.duration_ns > 1000000000
|| !std::isfinite(pulse.amplitude) || pulse.amplitude < 0 || pulse.amplitude > 1
|| !std::isfinite(pulse.frequency) || pulse.frequency < 0) continue;
XrHapticActionInfo info{XR_TYPE_HAPTIC_ACTION_INFO}; info.action = vibration_; info.subactionPath = hands_[hand];
XrHapticVibration vibration{XR_TYPE_HAPTIC_VIBRATION};
vibration.duration = pulse.duration_ns; vibration.amplitude = pulse.amplitude; vibration.frequency = pulse.frequency;
check(xrApplyHapticFeedback(session_, &info, reinterpret_cast<XrHapticBaseHeader *>(&vibration)), "host haptics");
}
}
@@ -749,11 +1027,17 @@ private:
munmap(tracking_, sizeof(DroidDeckXrTracking));
}
if (haptics_) munmap(haptics_, sizeof(DroidDeckXrHaptics));
g_runtime = nullptr;
hostBuffers_ = false;
if (display_ != EGL_NO_DISPLAY && context_ != EGL_NO_CONTEXT) {
glDeleteFramebuffers(1, &framebuffer_); glDeleteVertexArrays(1, &vertexArray_);
glDeleteTextures(1, &cpuTexture_); glDeleteProgram(sourceProgram_);
glDeleteRenderbuffers(2, overlayDepth_);
overlay_.destroy();
}
if (env_) for (int index = 0; index < DROIDDECK_XR_HOST_LAYERS; index++) destroyLayer(env_, index);
for (auto &eye : eyes_) if (eye.swapchain) xrDestroySwapchain(eye.swapchain);
for (auto &eye : overlayEyes_) if (eye.swapchain) xrDestroySwapchain(eye.swapchain);
for (auto space : handSpaces_) if (space) xrDestroySpace(space);
if (view_) xrDestroySpace(view_); if (world_) xrDestroySpace(world_);
if (session_) xrDestroySession(session_);
@@ -769,6 +1053,26 @@ private:
}
};
extern "C" JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_QuestXrActivity_nativeCreateLayer(JNIEnv *env, jobject, jint width, jint height) {
return g_runtime ? g_runtime->createLayer(env, width, height) : -1;
}
extern "C" JNIEXPORT jobject JNICALL
Java_com_droiddeck_launcher_QuestXrActivity_nativeLayerSurface(JNIEnv *env, jobject, jint index) {
return g_runtime ? g_runtime->layerSurface(env, index) : nullptr;
}
extern "C" JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_QuestXrActivity_nativeDestroyLayer(JNIEnv *env, jobject, jint index) {
if (g_runtime) g_runtime->destroyLayer(env, index);
}
extern "C" JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_QuestXrActivity_nativeSetOrbImage(JNIEnv *env, jobject, jobject bitmap) {
if (g_runtime) g_runtime->setOrbImage(env, bitmap);
}
void android_main(android_app *app) {
QuestXR runtime(app);
try { runtime.run(); }
+91
View File
@@ -0,0 +1,91 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "xr_tracking.h"
// Shared with com.droiddeck.launcher.session.xr.XrHost, which reads and writes these through direct
// ByteBuffers by fixed offset: any layout change must bump the version and update both sides.
#define DROIDDECK_XR_HOST_VERSION 1u
#define DROIDDECK_XR_HOST_LAYERS 6
#define DROIDDECK_XR_HOST_SURFACE_SWAPCHAIN (1u << 0)
#define DROIDDECK_XR_HOST_FOCUSED (1u << 1)
#define DROIDDECK_XR_HOST_MASK_INPUT (1u << 0)
#define DROIDDECK_XR_HOST_LAYER_ALPHA (1u << 0)
#define DROIDDECK_XR_HOST_LAYER_HEAD_LOCKED (1u << 1)
struct DroidDeckXrHostHand {
DroidDeckXrPose grip;
DroidDeckXrPose aim;
float trigger, squeeze, stick[2];
uint32_t buttons, active;
uint32_t reserved[2];
};
struct DroidDeckXrHostState {
uint32_t version, session_state, flags, reserved0;
int64_t frame, display_time_ns;
DroidDeckXrPose head;
DroidDeckXrHostHand hands[2];
uint32_t reserved[8];
};
struct DroidDeckXrHostHaptic {
uint64_t id;
int64_t duration_ns;
float amplitude, frequency;
};
struct DroidDeckXrHostHandControl {
uint32_t mask;
float laser;
DroidDeckXrHostHaptic haptic;
uint32_t reserved[2];
};
struct DroidDeckXrHostOrb {
uint32_t visible;
float progress, burst, radius;
DroidDeckXrPose pose;
};
struct DroidDeckXrHostLayer {
int32_t id;
uint32_t visible, flags;
int32_t order;
DroidDeckXrPose pose;
float width, height;
uint32_t reserved[2];
};
struct DroidDeckXrHostControl {
uint32_t version, reserved0;
DroidDeckXrHostHandControl hands[2];
DroidDeckXrHostOrb orb;
DroidDeckXrHostLayer layers[DROIDDECK_XR_HOST_LAYERS];
uint32_t reserved[8];
};
static_assert(sizeof(DroidDeckXrHostHand) == 96, "XR host hand layout");
static_assert(offsetof(DroidDeckXrHostHand, aim) == 32 && offsetof(DroidDeckXrHostHand, trigger) == 64 &&
offsetof(DroidDeckXrHostHand, stick) == 72 && offsetof(DroidDeckXrHostHand, buttons) == 80 &&
offsetof(DroidDeckXrHostHand, active) == 84, "XR host hand layout");
static_assert(offsetof(DroidDeckXrHostState, flags) == 8 && offsetof(DroidDeckXrHostState, frame) == 16 &&
offsetof(DroidDeckXrHostState, head) == 32, "XR host state layout");
static_assert(offsetof(DroidDeckXrHostHandControl, laser) == 4 && offsetof(DroidDeckXrHostHandControl, haptic) == 8,
"XR host hand control layout");
static_assert(offsetof(DroidDeckXrHostHaptic, duration_ns) == 8 && offsetof(DroidDeckXrHostHaptic, amplitude) == 16,
"XR host haptic layout");
static_assert(offsetof(DroidDeckXrHostOrb, progress) == 4 && offsetof(DroidDeckXrHostOrb, pose) == 16, "XR host orb layout");
static_assert(offsetof(DroidDeckXrHostLayer, order) == 12 && offsetof(DroidDeckXrHostLayer, pose) == 16 &&
offsetof(DroidDeckXrHostLayer, width) == 48, "XR host layer layout");
static_assert(sizeof(DroidDeckXrHostState) == 288, "XR host state layout");
static_assert(offsetof(DroidDeckXrHostState, hands) == 64, "XR host state layout");
static_assert(sizeof(DroidDeckXrHostHandControl) == 40, "XR host hand control layout");
static_assert(sizeof(DroidDeckXrHostOrb) == 48, "XR host orb layout");
static_assert(sizeof(DroidDeckXrHostLayer) == 64, "XR host layer layout");
static_assert(offsetof(DroidDeckXrHostControl, orb) == 88, "XR host control layout");
static_assert(offsetof(DroidDeckXrHostControl, layers) == 136, "XR host control layout");
static_assert(sizeof(DroidDeckXrHostControl) == 552, "XR host control layout");
+229
View File
@@ -0,0 +1,229 @@
#pragma once
#include <GLES3/gl3.h>
#include <openxr/openxr.h>
#include <algorithm>
#include <cmath>
#include <stdexcept>
#include "xr_host.h"
struct XrVec3 { float x, y, z; };
static inline XrVec3 xrv(float x, float y, float z) { return {x, y, z}; }
static inline XrVec3 operator+(XrVec3 a, XrVec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
static inline XrVec3 operator-(XrVec3 a, XrVec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
static inline XrVec3 operator*(XrVec3 a, float s) { return {a.x * s, a.y * s, a.z * s}; }
static inline float dot(XrVec3 a, XrVec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
static inline XrVec3 cross(XrVec3 a, XrVec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
static inline XrVec3 normalized(XrVec3 a) {
float length = std::sqrt(dot(a, a));
return length > 1e-6f ? a * (1.f / length) : xrv(0, 0, 0);
}
static inline XrVec3 rotate(const float q[4], XrVec3 v) {
XrVec3 u{q[0], q[1], q[2]};
float s = q[3];
return u * (2.f * dot(u, v)) + v * (s * s - dot(u, u)) + cross(u, v) * (2.f * s);
}
class XrOverlay {
public:
void initialize() {
GLuint vertex = compile(GL_VERTEX_SHADER,
"#version 300 es\nlayout(location=0) in vec3 position; layout(location=1) in vec2 coordinate;"
"uniform mat4 viewProjection; out vec2 uv;"
"void main(){uv=coordinate;gl_Position=viewProjection*vec4(position,1.0);}");
GLuint fragment = compile(GL_FRAGMENT_SHADER,
"#version 300 es\nprecision highp float; in vec2 uv; uniform int mode; uniform float progress, burst, time;"
"uniform vec3 color; uniform sampler2D logo; uniform int hasLogo; out vec4 outputColor;"
"void main(){"
" if(mode==0){float across=1.0-abs(uv.y); float a=smoothstep(0.0,0.7,across)*mix(0.95,0.35,uv.x);"
" outputColor=vec4(color*a,a);return;}"
" if(mode==1){float r=length(uv); float a=1.0-smoothstep(0.55,1.0,r); outputColor=vec4(vec3(1.0)*a,a);return;}"
" float r=length(uv); vec3 c=vec3(0.0); float a=0.0;"
" float pulse=0.5+0.5*sin(time*6.0);"
" float glow=exp(-pow(max(r-0.45,0.0)*6.0,2.0))*(0.25+0.2*pulse)*step(0.5,r); c+=color*glow; a=max(a,glow*0.7);"
" if(hasLogo==1&&r<0.52){vec4 l=texture(logo,vec2(0.5+uv.x/1.04,0.5-uv.y/1.04)); c=c*(1.0-l.a)+l.rgb; a=a*(1.0-l.a)+l.a;}"
" else if(r<0.5){float core=1.0-smoothstep(0.46,0.5,r); c+=color*core; a=max(a,core);}"
" float angle=atan(uv.x,uv.y); float sweep=(angle<0.0?angle+6.2831853:angle)/6.2831853;"
" float band=1.0-smoothstep(0.0,0.03,abs(r-0.64));"
" float track=band*0.25; float fill=band*step(sweep,progress);"
" c+=vec3(1.0)*track+color*fill*1.4; a=max(a,max(track,fill));"
" if(burst>0.0){float ring=(1.0-smoothstep(0.0,0.06,abs(r-(0.64+burst*0.3))))*(1.0-burst); c+=color*ring*2.0; a=max(a,ring);}"
" a=clamp(a,0.0,1.0); outputColor=vec4(c*a,a);"
"}");
program_ = glCreateProgram();
glAttachShader(program_, vertex); glAttachShader(program_, fragment);
glLinkProgram(program_); glDeleteShader(vertex); glDeleteShader(fragment);
GLint linked = 0; glGetProgramiv(program_, GL_LINK_STATUS, &linked);
if (!linked) throw std::runtime_error("Overlay shader link failed");
viewProjection_ = glGetUniformLocation(program_, "viewProjection");
mode_ = glGetUniformLocation(program_, "mode");
progress_ = glGetUniformLocation(program_, "progress");
burst_ = glGetUniformLocation(program_, "burst");
time_ = glGetUniformLocation(program_, "time");
color_ = glGetUniformLocation(program_, "color");
logoSampler_ = glGetUniformLocation(program_, "logo");
hasLogo_ = glGetUniformLocation(program_, "hasLogo");
glGenVertexArrays(1, &vertexArray_);
glGenBuffers(1, &buffer_);
glBindVertexArray(vertexArray_);
glBindBuffer(GL_ARRAY_BUFFER, buffer_);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 5 * 6, nullptr, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 5, nullptr);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 5, reinterpret_cast<void *>(sizeof(float) * 3));
glBindVertexArray(0);
}
/** [pixels] are premultiplied RGBA rows, top row first, as an Android ARGB_8888 bitmap holds them. */
void setLogo(const void *pixels, int width, int height, int stride) {
if (!logo_) glGenTextures(1, &logo_);
glBindTexture(GL_TEXTURE_2D, logo_);
glPixelStorei(GL_UNPACK_ROW_LENGTH, stride / 4);
glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
void destroy() {
if (logo_) glDeleteTextures(1, &logo_);
logo_ = 0;
if (program_) glDeleteProgram(program_);
if (buffer_) glDeleteBuffers(1, &buffer_);
if (vertexArray_) glDeleteVertexArrays(1, &vertexArray_);
program_ = buffer_ = vertexArray_ = 0;
}
static bool active(const DroidDeckXrHostControl &control) {
return control.orb.visible || control.hands[0].laser > 0.f || control.hands[1].laser > 0.f;
}
void draw(const XrPosef &eye, const XrFovf &fov, const DroidDeckXrHostControl &control,
const DroidDeckXrHostState &state, float seconds) {
if (!active(control)) return;
float matrix[16];
viewProjectionOf(eye, fov, matrix);
const float eyeOrientation[4] = {eye.orientation.x, eye.orientation.y, eye.orientation.z, eye.orientation.w};
const XrVec3 eyePosition{eye.position.x, eye.position.y, eye.position.z};
glUseProgram(program_);
glUniformMatrix4fv(viewProjection_, 1, GL_FALSE, matrix);
glUniform3f(color_, 0.12f, 0.62f, 1.0f);
glUniform1f(time_, seconds);
glBindVertexArray(vertexArray_);
glBindBuffer(GL_ARRAY_BUFFER, buffer_);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glDepthMask(GL_TRUE);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glDisable(GL_BLEND);
glUniform1i(mode_, 0);
for (const auto &layer : control.layers) {
if (!layer.visible || !(layer.width > 0.f) || !(layer.height > 0.f)) continue;
if (layer.flags & DROIDDECK_XR_HOST_LAYER_HEAD_LOCKED) continue;
XrVec3 center{layer.pose.position[0], layer.pose.position[1], layer.pose.position[2]};
XrVec3 right = rotate(layer.pose.orientation, xrv(layer.width / 2.f, 0, 0));
XrVec3 up = rotate(layer.pose.orientation, xrv(0, layer.height / 2.f, 0));
quad(center - right - up, center + right - up, center - right + up, center + right + up, 0.f, 1.f);
}
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glDepthMask(GL_FALSE);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
for (int hand = 0; hand < 2; hand++) {
float length = control.hands[hand].laser;
if (!(length > 0.f) || !state.hands[hand].active) continue;
const auto &aim = state.hands[hand].aim;
XrVec3 start{aim.position[0], aim.position[1], aim.position[2]};
XrVec3 direction = normalized(rotate(aim.orientation, xrv(0, 0, -1)));
XrVec3 end = start + direction * std::max(length - 0.004f, 0.f);
XrVec3 side = normalized(cross(direction, eyePosition - start)) * 0.0022f;
glUniform1i(mode_, 0);
quad(start - side, start + side, end - side, end + side, 0.f, 1.f);
XrVec3 right = rotate(eyeOrientation, xrv(1, 0, 0)) * 0.007f;
XrVec3 up = rotate(eyeOrientation, xrv(0, 1, 0)) * 0.007f;
glUniform1i(mode_, 1);
billboard(end + normalized(eyePosition - end) * 0.008f, right, up);
}
if (control.orb.visible) {
const auto &pose = control.orb.pose;
XrVec3 center{pose.position[0], pose.position[1], pose.position[2]};
float size = control.orb.radius * 1.25f;
XrVec3 right = rotate(eyeOrientation, xrv(1, 0, 0)) * size;
XrVec3 up = rotate(eyeOrientation, xrv(0, 1, 0)) * size;
glUniform1i(mode_, 2);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, logo_);
glUniform1i(logoSampler_, 0);
glUniform1i(hasLogo_, logo_ ? 1 : 0);
glUniform1f(progress_, control.orb.progress);
glUniform1f(burst_, control.orb.burst);
billboard(center, right, up);
}
glBindVertexArray(0);
glDisable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
}
private:
GLuint program_ = 0, buffer_ = 0, vertexArray_ = 0, logo_ = 0;
GLint viewProjection_ = -1, mode_ = -1, progress_ = -1, burst_ = -1, time_ = -1, color_ = -1;
GLint logoSampler_ = -1, hasLogo_ = -1;
static GLuint compile(GLenum type, const char *text) {
GLuint handle = glCreateShader(type);
glShaderSource(handle, 1, &text, nullptr); glCompileShader(handle);
GLint success = 0; glGetShaderiv(handle, GL_COMPILE_STATUS, &success);
if (!success) { glDeleteShader(handle); throw std::runtime_error("Overlay shader compile failed"); }
return handle;
}
void billboard(XrVec3 center, XrVec3 right, XrVec3 up) {
quadUv(center - right - up, center + right - up, center - right + up, center + right + up);
}
void quad(XrVec3 a0, XrVec3 a1, XrVec3 b0, XrVec3 b1, float from, float to) {
const float vertices[] = {
a0.x, a0.y, a0.z, from, -1, a1.x, a1.y, a1.z, from, 1, b0.x, b0.y, b0.z, to, -1,
b0.x, b0.y, b0.z, to, -1, a1.x, a1.y, a1.z, from, 1, b1.x, b1.y, b1.z, to, 1};
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
glDrawArrays(GL_TRIANGLES, 0, 6);
}
void quadUv(XrVec3 bottomLeft, XrVec3 bottomRight, XrVec3 topLeft, XrVec3 topRight) {
const float vertices[] = {
bottomLeft.x, bottomLeft.y, bottomLeft.z, -1, -1, bottomRight.x, bottomRight.y, bottomRight.z, 1, -1,
topLeft.x, topLeft.y, topLeft.z, -1, 1, topLeft.x, topLeft.y, topLeft.z, -1, 1,
bottomRight.x, bottomRight.y, bottomRight.z, 1, -1, topRight.x, topRight.y, topRight.z, 1, 1};
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
glDrawArrays(GL_TRIANGLES, 0, 6);
}
static void viewProjectionOf(const XrPosef &pose, const XrFovf &fov, float out[16]) {
const float q[4] = {pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w};
XrVec3 xAxis = rotate(q, xrv(1, 0, 0)), yAxis = rotate(q, xrv(0, 1, 0)), zAxis = rotate(q, xrv(0, 0, 1));
XrVec3 position{pose.position.x, pose.position.y, pose.position.z};
float view[16] = {
xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0,
-dot(xAxis, position), -dot(yAxis, position), -dot(zAxis, position), 1};
const float nearZ = 0.05f, farZ = 100.f;
float left = std::tan(fov.angleLeft), right = std::tan(fov.angleRight);
float up = std::tan(fov.angleUp), down = std::tan(fov.angleDown);
float width = right - left, height = up - down;
float projection[16] = {
2.f / width, 0, 0, 0, 0, 2.f / height, 0, 0,
(right + left) / width, (up + down) / height, -(farZ + nearZ) / (farZ - nearZ), -1,
0, 0, -2.f * farZ * nearZ / (farZ - nearZ), 0};
for (int column = 0; column < 4; column++)
for (int row = 0; row < 4; row++) {
float sum = 0;
for (int k = 0; k < 4; k++) sum += projection[k * 4 + row] * view[column * 4 + k];
out[column * 4 + row] = sum;
}
}
};
+3 -3
View File
@@ -39,7 +39,7 @@
// - Same push constants as cas.frag: ndc, input size, sharpness [0..1].
// CasSetup's const1.x = -1 / lerp(8, 5, sharpness) is computed here.
// - The input is the effect chain's previous target at the same size, so the
// output pixel reads the input pixel 1:1 (texelFetch, edges clamped).
// output pixel reads the input pixel 1:1 (texel centres, edges clamped).
// =============================================================================
// DD_HALF is set for the *_half_frag.h build (gen_shaders.sh): colour and
@@ -64,8 +64,8 @@ layout(location = 0) in highp vec2 fragTexCoord;
layout(location = 0) out vec4 outColor;
vec3 CasLoad(ivec2 p) {
ivec2 sz = textureSize(InputTexture, 0);
return texelFetch(InputTexture, clamp(p, ivec2(0), sz - ivec2(1)), 0).rgb;
highp vec2 uv = (vec2(p) + 0.5) / pc.resolution;
return textureLod(InputTexture, uv, 0.0).rgb;
}
float AMin3F1(float x, float y, float z) { return min(x, min(y, z)); }
+210 -211
View File
@@ -1,214 +1,213 @@
// 1116.2.0
// 1115.1.0
#pragma once
const uint32_t cas_ffx_half_code[] = {
0x07230203,0x00010000,0x0008000b,0x000000d7,0x00000000,0x00020011,0x00000001,0x00020011,
0x00000032,0x0006000b,0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,
0x00000000,0x00000001,0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000043,
0x000000d1,0x00030010,0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,
0x00000004,0x6e69616d,0x00000000,0x00060005,0x0000000d,0x4c736143,0x2864616f,0x3b326976,
0x00000000,0x00030005,0x0000000c,0x00000070,0x00070005,0x00000014,0x6e694d41,0x28314633,
0x663b3166,0x31663b31,0x0000003b,0x00030005,0x00000011,0x00000078,0x00030005,0x00000012,
0x00000079,0x00030005,0x00000013,0x0000007a,0x00070005,0x00000019,0x78614d41,0x28314633,
0x663b3166,0x31663b31,0x0000003b,0x00030005,0x00000016,0x00000078,0x00030005,0x00000017,
0x00000079,0x00030005,0x00000018,0x0000007a,0x00030005,0x0000001b,0x00007a73,0x00060005,
0x0000001f,0x75706e49,0x78655474,0x65727574,0x00000000,0x00030005,0x00000040,0x00007073,
0x00060005,0x00000043,0x67617266,0x43786554,0x64726f6f,0x00000000,0x00030005,0x00000045,
0x00004350,0x00040006,0x00000045,0x00000000,0x0063646e,0x00060006,0x00000045,0x00000001,
0x6f736572,0x6974756c,0x00006e6f,0x00060006,0x00000045,0x00000002,0x72616873,0x73656e70,
0x00000073,0x00030005,0x00000047,0x00006370,0x00040005,0x0000004d,0x6b616570,0x00000000,
0x00030005,0x0000005b,0x00000062,0x00040005,0x00000060,0x61726170,0x0000006d,0x00030005,
0x00000062,0x00000064,0x00040005,0x00000066,0x61726170,0x0000006d,0x00030005,0x00000068,
0x00000065,0x00040005,0x00000069,0x61726170,0x0000006d,0x00030005,0x0000006c,0x00000066,
0x00040005,0x00000070,0x61726170,0x0000006d,0x00030005,0x00000072,0x00000068,0x00040005,
0x00000076,0x61726170,0x0000006d,0x00030005,0x00000078,0x00476e6d,0x00040005,0x00000079,
0x61726170,0x0000006d,0x00040005,0x0000007e,0x61726170,0x0000006d,0x00040005,0x00000081,
0x61726170,0x0000006d,0x00040005,0x00000085,0x61726170,0x0000006d,0x00040005,0x00000086,
0x61726170,0x0000006d,0x00040005,0x00000089,0x61726170,0x0000006d,0x00030005,0x0000008d,
0x0047786d,0x00040005,0x0000008e,0x61726170,0x0000006d,0x00040005,0x00000091,0x61726170,
0x0000006d,0x00040005,0x00000094,0x61726170,0x0000006d,0x00040005,0x00000098,0x61726170,
0x0000006d,0x00040005,0x00000099,0x61726170,0x0000006d,0x00040005,0x0000009c,0x61726170,
0x0000006d,0x00040005,0x000000a0,0x4d706372,0x00000047,0x00040005,0x000000a5,0x47706d61,
0x00000000,0x00030005,0x000000af,0x00004777,0x00050005,0x000000b3,0x57706372,0x68676965,
0x00000074,0x00030005,0x000000b9,0x00786970,0x00050005,0x000000d1,0x4374756f,0x726f6c6f,
0x00000000,0x00030047,0x0000000d,0x00000000,0x00030047,0x00000011,0x00000000,0x00030047,
0x00000012,0x00000000,0x00030047,0x00000013,0x00000000,0x00030047,0x00000014,0x00000000,
0x00030047,0x00000016,0x00000000,0x00030047,0x00000017,0x00000000,0x00030047,0x00000018,
0x00000000,0x00030047,0x00000019,0x00000000,0x00030047,0x0000001f,0x00000000,0x00040047,
0x0000001f,0x00000021,0x00000000,0x00040047,0x0000001f,0x00000022,0x00000000,0x00030047,
0x00000020,0x00000000,0x00030047,0x00000024,0x00000000,0x00030047,0x0000002e,0x00000000,
0x00030047,0x0000002f,0x00000000,0x00030047,0x00000032,0x00000000,0x00030047,0x00000033,
0x00000000,0x00030047,0x00000034,0x00000000,0x00030047,0x00000035,0x00000000,0x00030047,
0x00000036,0x00000000,0x00030047,0x00000039,0x00000000,0x00030047,0x0000003a,0x00000000,
0x00030047,0x0000003b,0x00000000,0x00030047,0x0000003c,0x00000000,0x00030047,0x0000003d,
0x00000000,0x00040047,0x00000043,0x0000001e,0x00000000,0x00030047,0x00000045,0x00000002,
0x00050048,0x00000045,0x00000000,0x00000023,0x00000000,0x00050048,0x00000045,0x00000001,
0x00000023,0x00000010,0x00040048,0x00000045,0x00000002,0x00000000,0x00050048,0x00000045,
0x00000002,0x00000023,0x00000018,0x00030047,0x0000004d,0x00000000,0x00030047,0x00000054,
0x00000000,0x00030047,0x00000057,0x00000000,0x00030047,0x00000058,0x00000000,0x00030047,
0x00000059,0x00000000,0x00030047,0x0000005b,0x00000000,0x00030047,0x00000061,0x00000000,
0x00030047,0x00000062,0x00000000,0x00030047,0x00000067,0x00000000,0x00030047,0x00000068,
0x00000000,0x00030047,0x0000006b,0x00000000,0x00030047,0x0000006c,0x00000000,0x00030047,
0x00000071,0x00000000,0x00030047,0x00000072,0x00000000,0x00030047,0x00000077,0x00000000,
0x00030047,0x00000078,0x00000000,0x00030047,0x00000079,0x00000000,0x00030047,0x0000007d,
0x00000000,0x00030047,0x0000007e,0x00000000,0x00030047,0x00000080,0x00000000,0x00030047,
0x00000081,0x00000000,0x00030047,0x00000083,0x00000000,0x00030047,0x00000084,0x00000000,
0x00030047,0x00000085,0x00000000,0x00030047,0x00000086,0x00000000,0x00030047,0x00000088,
0x00000000,0x00030047,0x00000089,0x00000000,0x00030047,0x0000008b,0x00000000,0x00030047,
0x0000008c,0x00000000,0x00030047,0x0000008d,0x00000000,0x00030047,0x0000008e,0x00000000,
0x00030047,0x00000090,0x00000000,0x00030047,0x00000091,0x00000000,0x00030047,0x00000093,
0x00000000,0x00030047,0x00000094,0x00000000,0x00030047,0x00000096,0x00000000,0x00030047,
0x00000097,0x00000000,0x00030047,0x00000098,0x00000000,0x00030047,0x00000099,0x00000000,
0x00030047,0x0000009b,0x00000000,0x00030047,0x0000009c,0x00000000,0x00030047,0x0000009e,
0x00000000,0x00030047,0x0000009f,0x00000000,0x00030047,0x000000a0,0x00000000,0x00030047,
0x000000a1,0x00000000,0x00030047,0x000000a3,0x00000000,0x00030047,0x000000a4,0x00000000,
0x00030047,0x000000a5,0x00000000,0x00030047,0x000000a6,0x00000000,0x00030047,0x000000a7,
0x00000000,0x00030047,0x000000a8,0x00000000,0x00030047,0x000000a9,0x00000000,0x00030047,
0x000000aa,0x00000000,0x00030047,0x000000ab,0x00000000,0x00030047,0x000000ac,0x00000000,
0x00030047,0x000000ad,0x00000000,0x00030047,0x000000ae,0x00000000,0x00030047,0x000000af,
0x00000000,0x00030047,0x000000b0,0x00000000,0x00030047,0x000000b1,0x00000000,0x00030047,
0x000000b2,0x00000000,0x00030047,0x000000b3,0x00000000,0x00030047,0x000000b5,0x00000000,
0x00030047,0x000000b6,0x00000000,0x00030047,0x000000b7,0x00000000,0x00030047,0x000000b8,
0x00000000,0x00030047,0x000000b9,0x00000000,0x00030047,0x000000ba,0x00000000,0x00030047,
0x000000bb,0x00000000,0x00030047,0x000000bc,0x00000000,0x00030047,0x000000bd,0x00000000,
0x00030047,0x000000be,0x00000000,0x00030047,0x000000bf,0x00000000,0x00030047,0x000000c0,
0x00000000,0x00030047,0x000000c1,0x00000000,0x00030047,0x000000c2,0x00000000,0x00030047,
0x000000c3,0x00000000,0x00030047,0x000000c4,0x00000000,0x00030047,0x000000c5,0x00000000,
0x00030047,0x000000c6,0x00000000,0x00030047,0x000000c7,0x00000000,0x00030047,0x000000c8,
0x00000000,0x00030047,0x000000c9,0x00000000,0x00030047,0x000000ca,0x00000000,0x00030047,
0x000000cb,0x00000000,0x00030047,0x000000cc,0x00000000,0x00030047,0x000000cd,0x00000000,
0x00030047,0x000000ce,0x00000000,0x00030047,0x000000cf,0x00000000,0x00030047,0x000000d1,
0x00000000,0x00040047,0x000000d1,0x0000001e,0x00000000,0x00030047,0x000000d2,0x00000000,
0x00030047,0x000000d3,0x00000000,0x00030047,0x000000d4,0x00000000,0x00030047,0x000000d5,
0x00000000,0x00030047,0x000000d6,0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,
0x00000002,0x00040015,0x00000006,0x00000020,0x00000001,0x00040017,0x00000007,0x00000006,
0x00000002,0x00040020,0x00000008,0x00000007,0x00000007,0x00030016,0x00000009,0x00000020,
0x00040017,0x0000000a,0x00000009,0x00000003,0x00040021,0x0000000b,0x0000000a,0x00000008,
0x00040020,0x0000000f,0x00000007,0x00000009,0x00060021,0x00000010,0x00000009,0x0000000f,
0x0000000f,0x0000000f,0x00090019,0x0000001c,0x00000009,0x00000001,0x00000000,0x00000000,
0x00000000,0x00000001,0x00000000,0x0003001b,0x0000001d,0x0000001c,0x00040020,0x0000001e,
0x00000000,0x0000001d,0x0004003b,0x0000001e,0x0000001f,0x00000000,0x0004002b,0x00000006,
0x00000021,0x00000000,0x0005002c,0x00000007,0x00000026,0x00000021,0x00000021,0x0004002b,
0x00000006,0x00000028,0x00000001,0x0005002c,0x00000007,0x00000029,0x00000028,0x00000028,
0x00040017,0x0000002d,0x00000009,0x00000004,0x00040017,0x00000041,0x00000009,0x00000002,
0x00040020,0x00000042,0x00000001,0x00000041,0x0004003b,0x00000042,0x00000043,0x00000001,
0x0005001e,0x00000045,0x0000002d,0x00000041,0x00000009,0x00040020,0x00000046,0x00000009,
0x00000045,0x0004003b,0x00000046,0x00000047,0x00000009,0x00040020,0x00000048,0x00000009,
0x00000041,0x0004002b,0x00000009,0x0000004e,0xbf800000,0x0004002b,0x00000009,0x0000004f,
0x41000000,0x0004002b,0x00000009,0x00000050,0x40a00000,0x0004002b,0x00000006,0x00000051,
0x00000002,0x00040020,0x00000052,0x00000009,0x00000009,0x0004002b,0x00000009,0x00000055,
0x00000000,0x0004002b,0x00000009,0x00000056,0x3f800000,0x00040020,0x0000005a,0x00000007,
0x0000000a,0x0004002b,0x00000006,0x0000005d,0xffffffff,0x0005002c,0x00000007,0x0000005e,
0x00000021,0x0000005d,0x0005002c,0x00000007,0x00000064,0x0000005d,0x00000021,0x0005002c,
0x00000007,0x0000006e,0x00000028,0x00000021,0x0005002c,0x00000007,0x00000074,0x00000021,
0x00000028,0x00040015,0x0000007a,0x00000020,0x00000000,0x0004002b,0x0000007a,0x0000007b,
0x00000001,0x0004002b,0x00000009,0x000000a2,0x3a800000,0x0004002b,0x00000009,0x000000b4,
0x40800000,0x00040020,0x000000d0,0x00000003,0x0000002d,0x0004003b,0x000000d0,0x000000d1,
0x00000003,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,
0x0004003b,0x00000008,0x00000040,0x00000007,0x0004003b,0x0000000f,0x0000004d,0x00000007,
0x0004003b,0x0000005a,0x0000005b,0x00000007,0x0004003b,0x00000008,0x00000060,0x00000007,
0x0004003b,0x0000005a,0x00000062,0x00000007,0x0004003b,0x00000008,0x00000066,0x00000007,
0x0004003b,0x0000005a,0x00000068,0x00000007,0x0004003b,0x00000008,0x00000069,0x00000007,
0x0004003b,0x0000005a,0x0000006c,0x00000007,0x0004003b,0x00000008,0x00000070,0x00000007,
0x0004003b,0x0000005a,0x00000072,0x00000007,0x0004003b,0x00000008,0x00000076,0x00000007,
0x0004003b,0x0000000f,0x00000078,0x00000007,0x0004003b,0x0000000f,0x00000079,0x00000007,
0x0004003b,0x0000000f,0x0000007e,0x00000007,0x0004003b,0x0000000f,0x00000081,0x00000007,
0x0004003b,0x0000000f,0x00000085,0x00000007,0x0004003b,0x0000000f,0x00000086,0x00000007,
0x0004003b,0x0000000f,0x00000089,0x00000007,0x0004003b,0x0000000f,0x0000008d,0x00000007,
0x0004003b,0x0000000f,0x0000008e,0x00000007,0x0004003b,0x0000000f,0x00000091,0x00000007,
0x0004003b,0x0000000f,0x00000094,0x00000007,0x0004003b,0x0000000f,0x00000098,0x00000007,
0x0004003b,0x0000000f,0x00000099,0x00000007,0x0004003b,0x0000000f,0x0000009c,0x00000007,
0x0004003b,0x0000000f,0x000000a0,0x00000007,0x0004003b,0x0000000f,0x000000a5,0x00000007,
0x0004003b,0x0000000f,0x000000af,0x00000007,0x0004003b,0x0000000f,0x000000b3,0x00000007,
0x0004003b,0x0000005a,0x000000b9,0x00000007,0x0004003d,0x00000041,0x00000044,0x00000043,
0x00050041,0x00000048,0x00000049,0x00000047,0x00000028,0x0004003d,0x00000041,0x0000004a,
0x00000049,0x00050085,0x00000041,0x0000004b,0x00000044,0x0000004a,0x0004006e,0x00000007,
0x0000004c,0x0000004b,0x0003003e,0x00000040,0x0000004c,0x00050041,0x00000052,0x00000053,
0x00000047,0x00000051,0x0004003d,0x00000009,0x00000054,0x00000053,0x0008000c,0x00000009,
0x00000057,0x00000001,0x0000002b,0x00000054,0x00000055,0x00000056,0x0008000c,0x00000009,
0x00000058,0x00000001,0x0000002e,0x0000004f,0x00000050,0x00000057,0x00050088,0x00000009,
0x00000059,0x0000004e,0x00000058,0x0003003e,0x0000004d,0x00000059,0x0004003d,0x00000007,
0x0000005c,0x00000040,0x00050080,0x00000007,0x0000005f,0x0000005c,0x0000005e,0x0003003e,
0x00000060,0x0000005f,0x00050039,0x0000000a,0x00000061,0x0000000d,0x00000060,0x0003003e,
0x0000005b,0x00000061,0x0004003d,0x00000007,0x00000063,0x00000040,0x00050080,0x00000007,
0x00000065,0x00000063,0x00000064,0x0003003e,0x00000066,0x00000065,0x00050039,0x0000000a,
0x00000067,0x0000000d,0x00000066,0x0003003e,0x00000062,0x00000067,0x0004003d,0x00000007,
0x0000006a,0x00000040,0x0003003e,0x00000069,0x0000006a,0x00050039,0x0000000a,0x0000006b,
0x0000000d,0x00000069,0x0003003e,0x00000068,0x0000006b,0x0004003d,0x00000007,0x0000006d,
0x00000040,0x00050080,0x00000007,0x0000006f,0x0000006d,0x0000006e,0x0003003e,0x00000070,
0x0000006f,0x00050039,0x0000000a,0x00000071,0x0000000d,0x00000070,0x0003003e,0x0000006c,
0x00000071,0x0004003d,0x00000007,0x00000073,0x00000040,0x00050080,0x00000007,0x00000075,
0x00000073,0x00000074,0x0003003e,0x00000076,0x00000075,0x00050039,0x0000000a,0x00000077,
0x0000000d,0x00000076,0x0003003e,0x00000072,0x00000077,0x00050041,0x0000000f,0x0000007c,
0x00000062,0x0000007b,0x0004003d,0x00000009,0x0000007d,0x0000007c,0x0003003e,0x00000079,
0x0000007d,0x00050041,0x0000000f,0x0000007f,0x00000068,0x0000007b,0x0004003d,0x00000009,
0x00000080,0x0000007f,0x0003003e,0x0000007e,0x00000080,0x00050041,0x0000000f,0x00000082,
0x0000006c,0x0000007b,0x0004003d,0x00000009,0x00000083,0x00000082,0x0003003e,0x00000081,
0x00000083,0x00070039,0x00000009,0x00000084,0x00000014,0x00000079,0x0000007e,0x00000081,
0x0003003e,0x00000085,0x00000084,0x00050041,0x0000000f,0x00000087,0x0000005b,0x0000007b,
0x0004003d,0x00000009,0x00000088,0x00000087,0x0003003e,0x00000086,0x00000088,0x00050041,
0x0000000f,0x0000008a,0x00000072,0x0000007b,0x0004003d,0x00000009,0x0000008b,0x0000008a,
0x0003003e,0x00000089,0x0000008b,0x00070039,0x00000009,0x0000008c,0x00000014,0x00000085,
0x00000086,0x00000089,0x0003003e,0x00000078,0x0000008c,0x00050041,0x0000000f,0x0000008f,
0x00000062,0x0000007b,0x0004003d,0x00000009,0x00000090,0x0000008f,0x0003003e,0x0000008e,
0x00000090,0x00050041,0x0000000f,0x00000092,0x00000068,0x0000007b,0x0004003d,0x00000009,
0x00000093,0x00000092,0x0003003e,0x00000091,0x00000093,0x00050041,0x0000000f,0x00000095,
0x0000006c,0x0000007b,0x0004003d,0x00000009,0x00000096,0x00000095,0x0003003e,0x00000094,
0x00000096,0x00070039,0x00000009,0x00000097,0x00000019,0x0000008e,0x00000091,0x00000094,
0x0003003e,0x00000098,0x00000097,0x00050041,0x0000000f,0x0000009a,0x0000005b,0x0000007b,
0x0004003d,0x00000009,0x0000009b,0x0000009a,0x0003003e,0x00000099,0x0000009b,0x00050041,
0x0000000f,0x0000009d,0x00000072,0x0000007b,0x0004003d,0x00000009,0x0000009e,0x0000009d,
0x0003003e,0x0000009c,0x0000009e,0x00070039,0x00000009,0x0000009f,0x00000019,0x00000098,
0x00000099,0x0000009c,0x0003003e,0x0000008d,0x0000009f,0x0004003d,0x00000009,0x000000a1,
0x0000008d,0x0007000c,0x00000009,0x000000a3,0x00000001,0x00000028,0x000000a1,0x000000a2,
0x00050088,0x00000009,0x000000a4,0x00000056,0x000000a3,0x0003003e,0x000000a0,0x000000a4,
0x0004003d,0x00000009,0x000000a6,0x00000078,0x0004003d,0x00000009,0x000000a7,0x0000008d,
0x00050083,0x00000009,0x000000a8,0x00000056,0x000000a7,0x0007000c,0x00000009,0x000000a9,
0x00000001,0x00000025,0x000000a6,0x000000a8,0x0004003d,0x00000009,0x000000aa,0x000000a0,
0x00050085,0x00000009,0x000000ab,0x000000a9,0x000000aa,0x0008000c,0x00000009,0x000000ac,
0x00000001,0x0000002b,0x000000ab,0x00000055,0x00000056,0x0003003e,0x000000a5,0x000000ac,
0x0004003d,0x00000009,0x000000ad,0x000000a5,0x0006000c,0x00000009,0x000000ae,0x00000001,
0x0000001f,0x000000ad,0x0003003e,0x000000a5,0x000000ae,0x0004003d,0x00000009,0x000000b0,
0x000000a5,0x0004003d,0x00000009,0x000000b1,0x0000004d,0x00050085,0x00000009,0x000000b2,
0x000000b0,0x000000b1,0x0003003e,0x000000af,0x000000b2,0x0004003d,0x00000009,0x000000b5,
0x000000af,0x00050085,0x00000009,0x000000b6,0x000000b4,0x000000b5,0x00050081,0x00000009,
0x000000b7,0x00000056,0x000000b6,0x00050088,0x00000009,0x000000b8,0x00000056,0x000000b7,
0x0003003e,0x000000b3,0x000000b8,0x0004003d,0x0000000a,0x000000ba,0x0000005b,0x0004003d,
0x00000009,0x000000bb,0x000000af,0x0005008e,0x0000000a,0x000000bc,0x000000ba,0x000000bb,
0x0004003d,0x0000000a,0x000000bd,0x00000062,0x0004003d,0x00000009,0x000000be,0x000000af,
0x0005008e,0x0000000a,0x000000bf,0x000000bd,0x000000be,0x00050081,0x0000000a,0x000000c0,
0x000000bc,0x000000bf,0x0004003d,0x0000000a,0x000000c1,0x0000006c,0x0004003d,0x00000009,
0x000000c2,0x000000af,0x0005008e,0x0000000a,0x000000c3,0x000000c1,0x000000c2,0x00050081,
0x0000000a,0x000000c4,0x000000c0,0x000000c3,0x0004003d,0x0000000a,0x000000c5,0x00000072,
0x0004003d,0x00000009,0x000000c6,0x000000af,0x0005008e,0x0000000a,0x000000c7,0x000000c5,
0x000000c6,0x00050081,0x0000000a,0x000000c8,0x000000c4,0x000000c7,0x0004003d,0x0000000a,
0x000000c9,0x00000068,0x00050081,0x0000000a,0x000000ca,0x000000c8,0x000000c9,0x0004003d,
0x00000009,0x000000cb,0x000000b3,0x0005008e,0x0000000a,0x000000cc,0x000000ca,0x000000cb,
0x00060050,0x0000000a,0x000000cd,0x00000055,0x00000055,0x00000055,0x00060050,0x0000000a,
0x000000ce,0x00000056,0x00000056,0x00000056,0x0008000c,0x0000000a,0x000000cf,0x00000001,
0x0000002b,0x000000cc,0x000000cd,0x000000ce,0x0003003e,0x000000b9,0x000000cf,0x0004003d,
0x0000000a,0x000000d2,0x000000b9,0x00050051,0x00000009,0x000000d3,0x000000d2,0x00000000,
0x00050051,0x00000009,0x000000d4,0x000000d2,0x00000001,0x00050051,0x00000009,0x000000d5,
0x000000d2,0x00000002,0x00070050,0x0000002d,0x000000d6,0x000000d3,0x000000d4,0x000000d5,
0x00000056,0x0003003e,0x000000d1,0x000000d6,0x000100fd,0x00010038,0x00050036,0x0000000a,
0x0000000d,0x00000000,0x0000000b,0x00030037,0x00000008,0x0000000c,0x000200f8,0x0000000e,
0x0004003b,0x00000008,0x0000001b,0x00000007,0x0004003d,0x0000001d,0x00000020,0x0000001f,
0x00040064,0x0000001c,0x00000022,0x00000020,0x00050067,0x00000007,0x00000023,0x00000022,
0x00000021,0x0003003e,0x0000001b,0x00000023,0x0004003d,0x0000001d,0x00000024,0x0000001f,
0x0004003d,0x00000007,0x00000025,0x0000000c,0x0004003d,0x00000007,0x00000027,0x0000001b,
0x00050082,0x00000007,0x0000002a,0x00000027,0x00000029,0x0008000c,0x00000007,0x0000002b,
0x00000001,0x0000002d,0x00000025,0x00000026,0x0000002a,0x00040064,0x0000001c,0x0000002c,
0x00000024,0x0007005f,0x0000002d,0x0000002e,0x0000002c,0x0000002b,0x00000002,0x00000021,
0x0008004f,0x0000000a,0x0000002f,0x0000002e,0x0000002e,0x00000000,0x00000001,0x00000002,
0x000200fe,0x0000002f,0x00010038,0x00050036,0x00000009,0x00000014,0x00000000,0x00000010,
0x00030037,0x0000000f,0x00000011,0x00030037,0x0000000f,0x00000012,0x00030037,0x0000000f,
0x00000013,0x000200f8,0x00000015,0x0004003d,0x00000009,0x00000032,0x00000011,0x0004003d,
0x00000009,0x00000033,0x00000012,0x0004003d,0x00000009,0x00000034,0x00000013,0x0007000c,
0x00000009,0x00000035,0x00000001,0x00000025,0x00000033,0x00000034,0x0007000c,0x00000009,
0x00000036,0x00000001,0x00000025,0x00000032,0x00000035,0x000200fe,0x00000036,0x00010038,
0x00050036,0x00000009,0x00000019,0x00000000,0x00000010,0x00030037,0x0000000f,0x00000016,
0x00030037,0x0000000f,0x00000017,0x00030037,0x0000000f,0x00000018,0x000200f8,0x0000001a,
0x0004003d,0x00000009,0x00000039,0x00000016,0x0004003d,0x00000009,0x0000003a,0x00000017,
0x0004003d,0x00000009,0x0000003b,0x00000018,0x0007000c,0x00000009,0x0000003c,0x00000001,
0x00000028,0x0000003a,0x0000003b,0x0007000c,0x00000009,0x0000003d,0x00000001,0x00000028,
0x00000039,0x0000003c,0x000200fe,0x0000003d,0x00010038
0x07230203,0x00010000,0x0008000b,0x000000d7,0x00000000,0x00020011,0x00000001,0x0006000b,
0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000047,0x000000d1,0x00030010,
0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
0x00000000,0x00060005,0x0000000d,0x4c736143,0x2864616f,0x3b326976,0x00000000,0x00030005,
0x0000000c,0x00000070,0x00070005,0x00000014,0x6e694d41,0x28314633,0x663b3166,0x31663b31,
0x0000003b,0x00030005,0x00000011,0x00000078,0x00030005,0x00000012,0x00000079,0x00030005,
0x00000013,0x0000007a,0x00070005,0x00000019,0x78614d41,0x28314633,0x663b3166,0x31663b31,
0x0000003b,0x00030005,0x00000016,0x00000078,0x00030005,0x00000017,0x00000079,0x00030005,
0x00000018,0x0000007a,0x00030005,0x0000001d,0x00007675,0x00030005,0x00000024,0x00004350,
0x00040006,0x00000024,0x00000000,0x0063646e,0x00060006,0x00000024,0x00000001,0x6f736572,
0x6974756c,0x00006e6f,0x00060006,0x00000024,0x00000002,0x72616873,0x73656e70,0x00000073,
0x00030005,0x00000026,0x00006370,0x00060005,0x0000002f,0x75706e49,0x78655474,0x65727574,
0x00000000,0x00030005,0x00000045,0x00007073,0x00060005,0x00000047,0x67617266,0x43786554,
0x64726f6f,0x00000000,0x00040005,0x0000004d,0x6b616570,0x00000000,0x00030005,0x0000005a,
0x00000062,0x00040005,0x00000060,0x61726170,0x0000006d,0x00030005,0x00000062,0x00000064,
0x00040005,0x00000066,0x61726170,0x0000006d,0x00030005,0x00000068,0x00000065,0x00040005,
0x00000069,0x61726170,0x0000006d,0x00030005,0x0000006c,0x00000066,0x00040005,0x00000070,
0x61726170,0x0000006d,0x00030005,0x00000072,0x00000068,0x00040005,0x00000076,0x61726170,
0x0000006d,0x00030005,0x00000078,0x00476e6d,0x00040005,0x00000079,0x61726170,0x0000006d,
0x00040005,0x0000007e,0x61726170,0x0000006d,0x00040005,0x00000081,0x61726170,0x0000006d,
0x00040005,0x00000085,0x61726170,0x0000006d,0x00040005,0x00000086,0x61726170,0x0000006d,
0x00040005,0x00000089,0x61726170,0x0000006d,0x00030005,0x0000008d,0x0047786d,0x00040005,
0x0000008e,0x61726170,0x0000006d,0x00040005,0x00000091,0x61726170,0x0000006d,0x00040005,
0x00000094,0x61726170,0x0000006d,0x00040005,0x00000098,0x61726170,0x0000006d,0x00040005,
0x00000099,0x61726170,0x0000006d,0x00040005,0x0000009c,0x61726170,0x0000006d,0x00040005,
0x000000a0,0x4d706372,0x00000047,0x00040005,0x000000a5,0x47706d61,0x00000000,0x00030005,
0x000000af,0x00004777,0x00050005,0x000000b3,0x57706372,0x68676965,0x00000074,0x00030005,
0x000000b9,0x00786970,0x00050005,0x000000d1,0x4374756f,0x726f6c6f,0x00000000,0x00030047,
0x0000000d,0x00000000,0x00030047,0x00000011,0x00000000,0x00030047,0x00000012,0x00000000,
0x00030047,0x00000013,0x00000000,0x00030047,0x00000014,0x00000000,0x00030047,0x00000016,
0x00000000,0x00030047,0x00000017,0x00000000,0x00030047,0x00000018,0x00000000,0x00030047,
0x00000019,0x00000000,0x00030047,0x00000024,0x00000002,0x00050048,0x00000024,0x00000000,
0x00000023,0x00000000,0x00050048,0x00000024,0x00000001,0x00000023,0x00000010,0x00040048,
0x00000024,0x00000002,0x00000000,0x00050048,0x00000024,0x00000002,0x00000023,0x00000018,
0x00030047,0x0000002f,0x00000000,0x00040047,0x0000002f,0x00000021,0x00000000,0x00040047,
0x0000002f,0x00000022,0x00000000,0x00030047,0x00000030,0x00000000,0x00030047,0x00000033,
0x00000000,0x00030047,0x00000034,0x00000000,0x00030047,0x00000037,0x00000000,0x00030047,
0x00000038,0x00000000,0x00030047,0x00000039,0x00000000,0x00030047,0x0000003a,0x00000000,
0x00030047,0x0000003b,0x00000000,0x00030047,0x0000003e,0x00000000,0x00030047,0x0000003f,
0x00000000,0x00030047,0x00000040,0x00000000,0x00030047,0x00000041,0x00000000,0x00030047,
0x00000042,0x00000000,0x00040047,0x00000047,0x0000001e,0x00000000,0x00030047,0x0000004d,
0x00000000,0x00030047,0x00000054,0x00000000,0x00030047,0x00000056,0x00000000,0x00030047,
0x00000057,0x00000000,0x00030047,0x00000058,0x00000000,0x00030047,0x0000005a,0x00000000,
0x00030047,0x00000061,0x00000000,0x00030047,0x00000062,0x00000000,0x00030047,0x00000067,
0x00000000,0x00030047,0x00000068,0x00000000,0x00030047,0x0000006b,0x00000000,0x00030047,
0x0000006c,0x00000000,0x00030047,0x00000071,0x00000000,0x00030047,0x00000072,0x00000000,
0x00030047,0x00000077,0x00000000,0x00030047,0x00000078,0x00000000,0x00030047,0x00000079,
0x00000000,0x00030047,0x0000007d,0x00000000,0x00030047,0x0000007e,0x00000000,0x00030047,
0x00000080,0x00000000,0x00030047,0x00000081,0x00000000,0x00030047,0x00000083,0x00000000,
0x00030047,0x00000084,0x00000000,0x00030047,0x00000085,0x00000000,0x00030047,0x00000086,
0x00000000,0x00030047,0x00000088,0x00000000,0x00030047,0x00000089,0x00000000,0x00030047,
0x0000008b,0x00000000,0x00030047,0x0000008c,0x00000000,0x00030047,0x0000008d,0x00000000,
0x00030047,0x0000008e,0x00000000,0x00030047,0x00000090,0x00000000,0x00030047,0x00000091,
0x00000000,0x00030047,0x00000093,0x00000000,0x00030047,0x00000094,0x00000000,0x00030047,
0x00000096,0x00000000,0x00030047,0x00000097,0x00000000,0x00030047,0x00000098,0x00000000,
0x00030047,0x00000099,0x00000000,0x00030047,0x0000009b,0x00000000,0x00030047,0x0000009c,
0x00000000,0x00030047,0x0000009e,0x00000000,0x00030047,0x0000009f,0x00000000,0x00030047,
0x000000a0,0x00000000,0x00030047,0x000000a1,0x00000000,0x00030047,0x000000a3,0x00000000,
0x00030047,0x000000a4,0x00000000,0x00030047,0x000000a5,0x00000000,0x00030047,0x000000a6,
0x00000000,0x00030047,0x000000a7,0x00000000,0x00030047,0x000000a8,0x00000000,0x00030047,
0x000000a9,0x00000000,0x00030047,0x000000aa,0x00000000,0x00030047,0x000000ab,0x00000000,
0x00030047,0x000000ac,0x00000000,0x00030047,0x000000ad,0x00000000,0x00030047,0x000000ae,
0x00000000,0x00030047,0x000000af,0x00000000,0x00030047,0x000000b0,0x00000000,0x00030047,
0x000000b1,0x00000000,0x00030047,0x000000b2,0x00000000,0x00030047,0x000000b3,0x00000000,
0x00030047,0x000000b5,0x00000000,0x00030047,0x000000b6,0x00000000,0x00030047,0x000000b7,
0x00000000,0x00030047,0x000000b8,0x00000000,0x00030047,0x000000b9,0x00000000,0x00030047,
0x000000ba,0x00000000,0x00030047,0x000000bb,0x00000000,0x00030047,0x000000bc,0x00000000,
0x00030047,0x000000bd,0x00000000,0x00030047,0x000000be,0x00000000,0x00030047,0x000000bf,
0x00000000,0x00030047,0x000000c0,0x00000000,0x00030047,0x000000c1,0x00000000,0x00030047,
0x000000c2,0x00000000,0x00030047,0x000000c3,0x00000000,0x00030047,0x000000c4,0x00000000,
0x00030047,0x000000c5,0x00000000,0x00030047,0x000000c6,0x00000000,0x00030047,0x000000c7,
0x00000000,0x00030047,0x000000c8,0x00000000,0x00030047,0x000000c9,0x00000000,0x00030047,
0x000000ca,0x00000000,0x00030047,0x000000cb,0x00000000,0x00030047,0x000000cc,0x00000000,
0x00030047,0x000000cd,0x00000000,0x00030047,0x000000ce,0x00000000,0x00030047,0x000000cf,
0x00000000,0x00030047,0x000000d1,0x00000000,0x00040047,0x000000d1,0x0000001e,0x00000000,
0x00030047,0x000000d2,0x00000000,0x00030047,0x000000d3,0x00000000,0x00030047,0x000000d4,
0x00000000,0x00030047,0x000000d5,0x00000000,0x00030047,0x000000d6,0x00000000,0x00020013,
0x00000002,0x00030021,0x00000003,0x00000002,0x00040015,0x00000006,0x00000020,0x00000001,
0x00040017,0x00000007,0x00000006,0x00000002,0x00040020,0x00000008,0x00000007,0x00000007,
0x00030016,0x00000009,0x00000020,0x00040017,0x0000000a,0x00000009,0x00000003,0x00040021,
0x0000000b,0x0000000a,0x00000008,0x00040020,0x0000000f,0x00000007,0x00000009,0x00060021,
0x00000010,0x00000009,0x0000000f,0x0000000f,0x0000000f,0x00040017,0x0000001b,0x00000009,
0x00000002,0x00040020,0x0000001c,0x00000007,0x0000001b,0x0004002b,0x00000009,0x00000020,
0x3f000000,0x00040017,0x00000023,0x00000009,0x00000004,0x0005001e,0x00000024,0x00000023,
0x0000001b,0x00000009,0x00040020,0x00000025,0x00000009,0x00000024,0x0004003b,0x00000025,
0x00000026,0x00000009,0x0004002b,0x00000006,0x00000027,0x00000001,0x00040020,0x00000028,
0x00000009,0x0000001b,0x00090019,0x0000002c,0x00000009,0x00000001,0x00000000,0x00000000,
0x00000000,0x00000001,0x00000000,0x0003001b,0x0000002d,0x0000002c,0x00040020,0x0000002e,
0x00000000,0x0000002d,0x0004003b,0x0000002e,0x0000002f,0x00000000,0x0004002b,0x00000009,
0x00000032,0x00000000,0x00040020,0x00000046,0x00000001,0x0000001b,0x0004003b,0x00000046,
0x00000047,0x00000001,0x0004002b,0x00000009,0x0000004e,0xbf800000,0x0004002b,0x00000009,
0x0000004f,0x41000000,0x0004002b,0x00000009,0x00000050,0x40a00000,0x0004002b,0x00000006,
0x00000051,0x00000002,0x00040020,0x00000052,0x00000009,0x00000009,0x0004002b,0x00000009,
0x00000055,0x3f800000,0x00040020,0x00000059,0x00000007,0x0000000a,0x0004002b,0x00000006,
0x0000005c,0x00000000,0x0004002b,0x00000006,0x0000005d,0xffffffff,0x0005002c,0x00000007,
0x0000005e,0x0000005c,0x0000005d,0x0005002c,0x00000007,0x00000064,0x0000005d,0x0000005c,
0x0005002c,0x00000007,0x0000006e,0x00000027,0x0000005c,0x0005002c,0x00000007,0x00000074,
0x0000005c,0x00000027,0x00040015,0x0000007a,0x00000020,0x00000000,0x0004002b,0x0000007a,
0x0000007b,0x00000001,0x0004002b,0x00000009,0x000000a2,0x3a800000,0x0004002b,0x00000009,
0x000000b4,0x40800000,0x00040020,0x000000d0,0x00000003,0x00000023,0x0004003b,0x000000d0,
0x000000d1,0x00000003,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,
0x00000005,0x0004003b,0x00000008,0x00000045,0x00000007,0x0004003b,0x0000000f,0x0000004d,
0x00000007,0x0004003b,0x00000059,0x0000005a,0x00000007,0x0004003b,0x00000008,0x00000060,
0x00000007,0x0004003b,0x00000059,0x00000062,0x00000007,0x0004003b,0x00000008,0x00000066,
0x00000007,0x0004003b,0x00000059,0x00000068,0x00000007,0x0004003b,0x00000008,0x00000069,
0x00000007,0x0004003b,0x00000059,0x0000006c,0x00000007,0x0004003b,0x00000008,0x00000070,
0x00000007,0x0004003b,0x00000059,0x00000072,0x00000007,0x0004003b,0x00000008,0x00000076,
0x00000007,0x0004003b,0x0000000f,0x00000078,0x00000007,0x0004003b,0x0000000f,0x00000079,
0x00000007,0x0004003b,0x0000000f,0x0000007e,0x00000007,0x0004003b,0x0000000f,0x00000081,
0x00000007,0x0004003b,0x0000000f,0x00000085,0x00000007,0x0004003b,0x0000000f,0x00000086,
0x00000007,0x0004003b,0x0000000f,0x00000089,0x00000007,0x0004003b,0x0000000f,0x0000008d,
0x00000007,0x0004003b,0x0000000f,0x0000008e,0x00000007,0x0004003b,0x0000000f,0x00000091,
0x00000007,0x0004003b,0x0000000f,0x00000094,0x00000007,0x0004003b,0x0000000f,0x00000098,
0x00000007,0x0004003b,0x0000000f,0x00000099,0x00000007,0x0004003b,0x0000000f,0x0000009c,
0x00000007,0x0004003b,0x0000000f,0x000000a0,0x00000007,0x0004003b,0x0000000f,0x000000a5,
0x00000007,0x0004003b,0x0000000f,0x000000af,0x00000007,0x0004003b,0x0000000f,0x000000b3,
0x00000007,0x0004003b,0x00000059,0x000000b9,0x00000007,0x0004003d,0x0000001b,0x00000048,
0x00000047,0x00050041,0x00000028,0x00000049,0x00000026,0x00000027,0x0004003d,0x0000001b,
0x0000004a,0x00000049,0x00050085,0x0000001b,0x0000004b,0x00000048,0x0000004a,0x0004006e,
0x00000007,0x0000004c,0x0000004b,0x0003003e,0x00000045,0x0000004c,0x00050041,0x00000052,
0x00000053,0x00000026,0x00000051,0x0004003d,0x00000009,0x00000054,0x00000053,0x0008000c,
0x00000009,0x00000056,0x00000001,0x0000002b,0x00000054,0x00000032,0x00000055,0x0008000c,
0x00000009,0x00000057,0x00000001,0x0000002e,0x0000004f,0x00000050,0x00000056,0x00050088,
0x00000009,0x00000058,0x0000004e,0x00000057,0x0003003e,0x0000004d,0x00000058,0x0004003d,
0x00000007,0x0000005b,0x00000045,0x00050080,0x00000007,0x0000005f,0x0000005b,0x0000005e,
0x0003003e,0x00000060,0x0000005f,0x00050039,0x0000000a,0x00000061,0x0000000d,0x00000060,
0x0003003e,0x0000005a,0x00000061,0x0004003d,0x00000007,0x00000063,0x00000045,0x00050080,
0x00000007,0x00000065,0x00000063,0x00000064,0x0003003e,0x00000066,0x00000065,0x00050039,
0x0000000a,0x00000067,0x0000000d,0x00000066,0x0003003e,0x00000062,0x00000067,0x0004003d,
0x00000007,0x0000006a,0x00000045,0x0003003e,0x00000069,0x0000006a,0x00050039,0x0000000a,
0x0000006b,0x0000000d,0x00000069,0x0003003e,0x00000068,0x0000006b,0x0004003d,0x00000007,
0x0000006d,0x00000045,0x00050080,0x00000007,0x0000006f,0x0000006d,0x0000006e,0x0003003e,
0x00000070,0x0000006f,0x00050039,0x0000000a,0x00000071,0x0000000d,0x00000070,0x0003003e,
0x0000006c,0x00000071,0x0004003d,0x00000007,0x00000073,0x00000045,0x00050080,0x00000007,
0x00000075,0x00000073,0x00000074,0x0003003e,0x00000076,0x00000075,0x00050039,0x0000000a,
0x00000077,0x0000000d,0x00000076,0x0003003e,0x00000072,0x00000077,0x00050041,0x0000000f,
0x0000007c,0x00000062,0x0000007b,0x0004003d,0x00000009,0x0000007d,0x0000007c,0x0003003e,
0x00000079,0x0000007d,0x00050041,0x0000000f,0x0000007f,0x00000068,0x0000007b,0x0004003d,
0x00000009,0x00000080,0x0000007f,0x0003003e,0x0000007e,0x00000080,0x00050041,0x0000000f,
0x00000082,0x0000006c,0x0000007b,0x0004003d,0x00000009,0x00000083,0x00000082,0x0003003e,
0x00000081,0x00000083,0x00070039,0x00000009,0x00000084,0x00000014,0x00000079,0x0000007e,
0x00000081,0x0003003e,0x00000085,0x00000084,0x00050041,0x0000000f,0x00000087,0x0000005a,
0x0000007b,0x0004003d,0x00000009,0x00000088,0x00000087,0x0003003e,0x00000086,0x00000088,
0x00050041,0x0000000f,0x0000008a,0x00000072,0x0000007b,0x0004003d,0x00000009,0x0000008b,
0x0000008a,0x0003003e,0x00000089,0x0000008b,0x00070039,0x00000009,0x0000008c,0x00000014,
0x00000085,0x00000086,0x00000089,0x0003003e,0x00000078,0x0000008c,0x00050041,0x0000000f,
0x0000008f,0x00000062,0x0000007b,0x0004003d,0x00000009,0x00000090,0x0000008f,0x0003003e,
0x0000008e,0x00000090,0x00050041,0x0000000f,0x00000092,0x00000068,0x0000007b,0x0004003d,
0x00000009,0x00000093,0x00000092,0x0003003e,0x00000091,0x00000093,0x00050041,0x0000000f,
0x00000095,0x0000006c,0x0000007b,0x0004003d,0x00000009,0x00000096,0x00000095,0x0003003e,
0x00000094,0x00000096,0x00070039,0x00000009,0x00000097,0x00000019,0x0000008e,0x00000091,
0x00000094,0x0003003e,0x00000098,0x00000097,0x00050041,0x0000000f,0x0000009a,0x0000005a,
0x0000007b,0x0004003d,0x00000009,0x0000009b,0x0000009a,0x0003003e,0x00000099,0x0000009b,
0x00050041,0x0000000f,0x0000009d,0x00000072,0x0000007b,0x0004003d,0x00000009,0x0000009e,
0x0000009d,0x0003003e,0x0000009c,0x0000009e,0x00070039,0x00000009,0x0000009f,0x00000019,
0x00000098,0x00000099,0x0000009c,0x0003003e,0x0000008d,0x0000009f,0x0004003d,0x00000009,
0x000000a1,0x0000008d,0x0007000c,0x00000009,0x000000a3,0x00000001,0x00000028,0x000000a1,
0x000000a2,0x00050088,0x00000009,0x000000a4,0x00000055,0x000000a3,0x0003003e,0x000000a0,
0x000000a4,0x0004003d,0x00000009,0x000000a6,0x00000078,0x0004003d,0x00000009,0x000000a7,
0x0000008d,0x00050083,0x00000009,0x000000a8,0x00000055,0x000000a7,0x0007000c,0x00000009,
0x000000a9,0x00000001,0x00000025,0x000000a6,0x000000a8,0x0004003d,0x00000009,0x000000aa,
0x000000a0,0x00050085,0x00000009,0x000000ab,0x000000a9,0x000000aa,0x0008000c,0x00000009,
0x000000ac,0x00000001,0x0000002b,0x000000ab,0x00000032,0x00000055,0x0003003e,0x000000a5,
0x000000ac,0x0004003d,0x00000009,0x000000ad,0x000000a5,0x0006000c,0x00000009,0x000000ae,
0x00000001,0x0000001f,0x000000ad,0x0003003e,0x000000a5,0x000000ae,0x0004003d,0x00000009,
0x000000b0,0x000000a5,0x0004003d,0x00000009,0x000000b1,0x0000004d,0x00050085,0x00000009,
0x000000b2,0x000000b0,0x000000b1,0x0003003e,0x000000af,0x000000b2,0x0004003d,0x00000009,
0x000000b5,0x000000af,0x00050085,0x00000009,0x000000b6,0x000000b4,0x000000b5,0x00050081,
0x00000009,0x000000b7,0x00000055,0x000000b6,0x00050088,0x00000009,0x000000b8,0x00000055,
0x000000b7,0x0003003e,0x000000b3,0x000000b8,0x0004003d,0x0000000a,0x000000ba,0x0000005a,
0x0004003d,0x00000009,0x000000bb,0x000000af,0x0005008e,0x0000000a,0x000000bc,0x000000ba,
0x000000bb,0x0004003d,0x0000000a,0x000000bd,0x00000062,0x0004003d,0x00000009,0x000000be,
0x000000af,0x0005008e,0x0000000a,0x000000bf,0x000000bd,0x000000be,0x00050081,0x0000000a,
0x000000c0,0x000000bc,0x000000bf,0x0004003d,0x0000000a,0x000000c1,0x0000006c,0x0004003d,
0x00000009,0x000000c2,0x000000af,0x0005008e,0x0000000a,0x000000c3,0x000000c1,0x000000c2,
0x00050081,0x0000000a,0x000000c4,0x000000c0,0x000000c3,0x0004003d,0x0000000a,0x000000c5,
0x00000072,0x0004003d,0x00000009,0x000000c6,0x000000af,0x0005008e,0x0000000a,0x000000c7,
0x000000c5,0x000000c6,0x00050081,0x0000000a,0x000000c8,0x000000c4,0x000000c7,0x0004003d,
0x0000000a,0x000000c9,0x00000068,0x00050081,0x0000000a,0x000000ca,0x000000c8,0x000000c9,
0x0004003d,0x00000009,0x000000cb,0x000000b3,0x0005008e,0x0000000a,0x000000cc,0x000000ca,
0x000000cb,0x00060050,0x0000000a,0x000000cd,0x00000032,0x00000032,0x00000032,0x00060050,
0x0000000a,0x000000ce,0x00000055,0x00000055,0x00000055,0x0008000c,0x0000000a,0x000000cf,
0x00000001,0x0000002b,0x000000cc,0x000000cd,0x000000ce,0x0003003e,0x000000b9,0x000000cf,
0x0004003d,0x0000000a,0x000000d2,0x000000b9,0x00050051,0x00000009,0x000000d3,0x000000d2,
0x00000000,0x00050051,0x00000009,0x000000d4,0x000000d2,0x00000001,0x00050051,0x00000009,
0x000000d5,0x000000d2,0x00000002,0x00070050,0x00000023,0x000000d6,0x000000d3,0x000000d4,
0x000000d5,0x00000055,0x0003003e,0x000000d1,0x000000d6,0x000100fd,0x00010038,0x00050036,
0x0000000a,0x0000000d,0x00000000,0x0000000b,0x00030037,0x00000008,0x0000000c,0x000200f8,
0x0000000e,0x0004003b,0x0000001c,0x0000001d,0x00000007,0x0004003d,0x00000007,0x0000001e,
0x0000000c,0x0004006f,0x0000001b,0x0000001f,0x0000001e,0x00050050,0x0000001b,0x00000021,
0x00000020,0x00000020,0x00050081,0x0000001b,0x00000022,0x0000001f,0x00000021,0x00050041,
0x00000028,0x00000029,0x00000026,0x00000027,0x0004003d,0x0000001b,0x0000002a,0x00000029,
0x00050088,0x0000001b,0x0000002b,0x00000022,0x0000002a,0x0003003e,0x0000001d,0x0000002b,
0x0004003d,0x0000002d,0x00000030,0x0000002f,0x0004003d,0x0000001b,0x00000031,0x0000001d,
0x00070058,0x00000023,0x00000033,0x00000030,0x00000031,0x00000002,0x00000032,0x0008004f,
0x0000000a,0x00000034,0x00000033,0x00000033,0x00000000,0x00000001,0x00000002,0x000200fe,
0x00000034,0x00010038,0x00050036,0x00000009,0x00000014,0x00000000,0x00000010,0x00030037,
0x0000000f,0x00000011,0x00030037,0x0000000f,0x00000012,0x00030037,0x0000000f,0x00000013,
0x000200f8,0x00000015,0x0004003d,0x00000009,0x00000037,0x00000011,0x0004003d,0x00000009,
0x00000038,0x00000012,0x0004003d,0x00000009,0x00000039,0x00000013,0x0007000c,0x00000009,
0x0000003a,0x00000001,0x00000025,0x00000038,0x00000039,0x0007000c,0x00000009,0x0000003b,
0x00000001,0x00000025,0x00000037,0x0000003a,0x000200fe,0x0000003b,0x00010038,0x00050036,
0x00000009,0x00000019,0x00000000,0x00000010,0x00030037,0x0000000f,0x00000016,0x00030037,
0x0000000f,0x00000017,0x00030037,0x0000000f,0x00000018,0x000200f8,0x0000001a,0x0004003d,
0x00000009,0x0000003e,0x00000016,0x0004003d,0x00000009,0x0000003f,0x00000017,0x0004003d,
0x00000009,0x00000040,0x00000018,0x0007000c,0x00000009,0x00000041,0x00000001,0x00000028,
0x0000003f,0x00000040,0x0007000c,0x00000009,0x00000042,0x00000001,0x00000028,0x0000003e,
0x00000041,0x000200fe,0x00000042,0x00010038
};
@@ -7,6 +7,7 @@
#include "droiddeck-ahb-v1-server-protocol.h"
#include <android/hardware_buffer.h>
#include <errno.h>
#include <linux/sync_file.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
@@ -145,6 +146,12 @@ static void handle_released(uint64_t id, int fd) {
if (poll(&p, 1, 0) > 0) {
close(fd);
} else {
if (ab->fence_src) {
struct sync_merge_data m = {.name = "droiddeck-release", .fd2 = fd};
if (ioctl(ab->fence_fd, SYNC_IOC_MERGE, &m) == 0) { close(fd); fd = m.fence; }
wl_event_source_remove(ab->fence_src);
close(ab->fence_fd);
}
ab->fence_fd = fd;
ab->fence_src = wl_event_loop_add_fd(g_loop, fd, WL_EVENT_READABLE, on_fence_readable, ab);
if (!ab->fence_src) { close(fd); ab->fence_fd = -1; }
@@ -152,6 +159,7 @@ static void handle_released(uint64_t id, int fd) {
}
}
}
if (ab->fence_src) return;
send_deferred_release(ab);
maybe_free(ab);
}
@@ -197,15 +205,19 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_
struct droiddeck_dma_buf_sync_file exp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = -1};
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) {
acquire = exp.fd;
} else if (dmabuf_fd >= 0) {
} else {
if (!g_export_failed_logged) {
g_export_failed_logged = 1;
droiddeck_log("layer", "zero-copy: DMA_BUF_IOCTL_EXPORT_SYNC_FILE failed (%s): waiting for each frame on the CPU instead",
strerror(errno));
droiddeck_log("layer", "zero-copy: no acquire fence from the game's dma-buf (%s): %s",
dmabuf_fd >= 0 ? strerror(errno) : "no dma-buf fd",
draw ? "its frames are copied instead" : "it cannot be copied, so each frame is waited for on the CPU");
}
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
if (dmabuf_fd >= 0) {
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
}
if (draw) return -1;
}
int r = sc_layer_present_ahb(ab->ahb, ab->w, ab->h, acquire, (void *)(uintptr_t)ab->id, scene_w, scene_h, draw,
s ? droiddeck_surface_color(s) : NULL, ab->format);
+253 -18
View File
@@ -12,6 +12,7 @@
#include <stdarg.h>
#include <errno.h>
#include <poll.h>
#include <sys/ioctl.h>
#include <sys/timerfd.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
@@ -2272,6 +2273,69 @@ static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t
struct draw_list { struct vkp_draw *d; int n, cap; };
#define ZERO_COPY_FALLBACK_SIGNATURES 32u
enum zero_copy_fallback_reason {
ZERO_COPY_NO_SURFACE_BUFFER = 1,
ZERO_COPY_NO_GRALLOC_AHB = 2,
ZERO_COPY_AHB_PRESENT_FAILED = 3
};
struct zero_copy_fallback_signature {
uint32_t reason, format, stride, offset;
int width, height;
uint64_t modifier;
};
static struct zero_copy_fallback_signature g_zero_copy_fallbacks[ZERO_COPY_FALLBACK_SIGNATURES];
static uint32_t g_zero_copy_fallback_count;
static int g_zero_copy_fallback_limit_logged;
static int zero_copy_fallback_should_log(const struct dmabuf_buffer *b, uint32_t reason) {
const struct zero_copy_fallback_signature key = {
.reason = reason, .format = b ? b->format : 0,
.stride = b && b->n_planes ? b->stride[0] : 0,
.offset = b && b->n_planes ? b->offset[0] : 0,
.width = b ? b->width : 0, .height = b ? b->height : 0,
.modifier = b ? b->modifier : 0};
for (uint32_t i = 0; i < g_zero_copy_fallback_count; i++) {
const struct zero_copy_fallback_signature *seen = &g_zero_copy_fallbacks[i];
if (seen->reason == key.reason && seen->format == key.format && seen->stride == key.stride &&
seen->offset == key.offset && seen->width == key.width && seen->height == key.height &&
seen->modifier == key.modifier)
return 0;
}
if (g_zero_copy_fallback_count >= ZERO_COPY_FALLBACK_SIGNATURES) {
if (!g_zero_copy_fallback_limit_logged) {
g_zero_copy_fallback_limit_logged = 1;
droiddeck_log("layer", "zero-copy: further fallback diagnostics suppressed after %u distinct buffer signatures",
ZERO_COPY_FALLBACK_SIGNATURES);
}
return 0;
}
g_zero_copy_fallbacks[g_zero_copy_fallback_count++] = key;
return 1;
}
static void note_zero_copy_fallback(struct surface *s, const struct dmabuf_buffer *b, uint32_t reason,
int scene_w, int scene_h, int present_result) {
if (!zero_copy_fallback_should_log(b, reason)) return;
char name[160] = "unknown surface";
if (s) describe(s, name, sizeof(name));
if (reason == ZERO_COPY_NO_SURFACE_BUFFER) {
droiddeck_log("layer", "zero-copy: layer candidate %s has no associated Wayland surface buffer; using the layer-copy path",
name);
} else {
droiddeck_log("layer", "zero-copy: %s buffer %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx %s; "
"scene %dx%d will use the layer-copy path (direct-present result %d)",
name, b->format & 0xff, (b->format >> 8) & 0xff, (b->format >> 16) & 0xff,
(b->format >> 24) & 0xff, b->width, b->height,
b->n_planes ? b->stride[0] : 0, b->n_planes ? b->offset[0] : 0,
(unsigned long long)b->modifier,
reason == ZERO_COPY_NO_GRALLOC_AHB
? "has no registered gralloc AHardwareBuffer"
: "has a registered gralloc AHardwareBuffer but direct presentation failed",
scene_w, scene_h, present_result);
}
}
static int add_cursor(struct draw_list *dl, int scene_w);
static struct vkp_image *surface_image(struct surface *s) {
@@ -2391,17 +2455,53 @@ static int black_fill_below(const struct draw_list *dl, int n) {
return 1;
}
#define LAYER_CANDIDATE_DIAGNOSTICS 32u
static unsigned g_layer_candidate_diag_count;
static int g_layer_candidate_diag_limit;
static void note_layer_candidate_skip(const struct vkp_draw *d, int index, int reason,
int scene_w, int scene_h) {
static int seen[LAYER_CANDIDATE_DIAGNOSTICS][8];
const int key[8] = {index, reason, scene_w, scene_h, d->dx, d->dy, d->dw, d->dh};
for (unsigned i = 0; i < g_layer_candidate_diag_count; i++)
if (!memcmp(seen[i], key, sizeof(key))) return;
if (g_layer_candidate_diag_count >= LAYER_CANDIDATE_DIAGNOSTICS) {
if (!g_layer_candidate_diag_limit++) droiddeck_log("layer", "zero-copy: further candidate-rejection details suppressed after %u signatures",
LAYER_CANDIDATE_DIAGNOSTICS);
return;
}
memcpy(seen[g_layer_candidate_diag_count++], key, sizeof(key));
const char *why = reason == 1 ? "translucent draw" :
reason == 2 ? "image is not DMA-BUF" :
reason == 3 ? "source rectangle is outside/invalid" :
reason == 4 ? "draw rectangle is outside scene or invalid" :
"not fullscreen and no black backing below";
droiddeck_log("layer", "zero-copy: candidate draw %d rejected: %s; scene %dx%d, dst %dx%d at %d,%d, src %.2f,%.2f %.2fx%.2f, image %dx%d",
index, why, scene_w, scene_h, d->dw, d->dh, d->dx, d->dy,
d->sx, d->sy, d->sw, d->sh, vkp_image_width(d->img), vkp_image_height(d->img));
}
static int layer_candidate(const struct draw_list *dl, int scene_w, int scene_h) {
for (int i = dl->n - 1; i >= 0 && i >= dl->n - 2; i--) {
const struct vkp_draw *d = &dl->d[i];
if (d->blend) continue;
if (!vkp_image_is_dmabuf(d->img)) continue;
if (d->blend) { note_layer_candidate_skip(d, i, 1, scene_w, scene_h); continue; }
if (!vkp_image_is_dmabuf(d->img)) { note_layer_candidate_skip(d, i, 2, scene_w, scene_h); continue; }
if (d->sx < 0 || d->sy < 0 || d->sw < 1.0f || d->sh < 1.0f ||
d->sx + d->sw >= vkp_image_width(d->img) + 1.0f ||
d->sy + d->sh >= vkp_image_height(d->img) + 1.0f) continue;
d->sy + d->sh >= vkp_image_height(d->img) + 1.0f) {
note_layer_candidate_skip(d, i, 3, scene_w, scene_h);
continue;
}
if (d->dx == 0 && d->dy == 0 && d->dw == scene_w && d->dh == scene_h) return i;
if (d->dx < 0 || d->dy < 0 || d->dw <= 0 || d->dh <= 0 || d->dx + d->dw > scene_w ||
d->dy + d->dh > scene_h || !black_fill_below(dl, i)) continue;
d->dy + d->dh > scene_h) {
note_layer_candidate_skip(d, i, 4, scene_w, scene_h);
continue;
}
if (!black_fill_below(dl, i)) {
note_layer_candidate_skip(d, i, 5, scene_w, scene_h);
continue;
}
return i;
}
return -1;
@@ -2422,6 +2522,56 @@ static void note_copy_scene(const struct draw_list *dl, int scene_w, int scene_h
vkp_image_is_dmabuf(t->img) ? "GPU" : "memory", t->blend ? ", translucent" : "");
}
static struct surface *surface_for_image(const struct vkp_image *img);
static void note_layer_candidate_rejected(const struct draw_list *dl, int scene_w, int scene_h) {
static int seen[32][14];
static unsigned seen_count;
static int limit_logged;
static time_t window_start;
struct timespec now_ts;
const struct vkp_draw *a = dl->n > 0 ? &dl->d[dl->n - 1] : NULL;
const struct vkp_draw *b = dl->n > 1 ? &dl->d[dl->n - 2] : NULL;
struct surface *sa = a ? surface_for_image(a->img) : NULL;
struct surface *sb = b ? surface_for_image(b->img) : NULL;
const int signature[14] = {
dl->n, scene_w, scene_h,
a ? a->dw : 0, a ? a->dh : 0,
a ? vkp_image_width(a->img) : 0, a ? vkp_image_height(a->img) : 0,
a ? vkp_image_is_dmabuf(a->img) : 0, a ? a->blend : 0, sa && sa->dmabuf_buf ? 1 : 0,
b ? b->dw : 0, b ? b->dh : 0, b ? vkp_image_is_dmabuf(b->img) : 0, sb && sb->dmabuf_buf ? 1 : 0
};
clock_gettime(CLOCK_MONOTONIC, &now_ts);
if (!window_start || now_ts.tv_sec - window_start >= 30) {
seen_count = 0;
limit_logged = 0;
window_start = now_ts.tv_sec;
}
for (unsigned i = 0; i < seen_count; i++)
if (!memcmp(signature, seen[i], sizeof(signature))) return;
if (seen_count >= 32) {
if (!limit_logged++) droiddeck_log("layer", "zero-copy: further fullscreen-candidate rejection details suppressed after 32 signatures in 30 seconds");
return;
}
memcpy(seen[seen_count++], signature, sizeof(signature));
char below[48];
if (b)
snprintf(below, sizeof(below), "%s %dx%d",
vkp_image_is_dmabuf(b->img) ? "DMA-BUF" : "non-DMA-BUF", b->dw, b->dh);
else
snprintf(below, sizeof(below), "none");
droiddeck_log("layer", "zero-copy: no eligible fullscreen DMA-BUF layer candidate: scene %dx%d, %d draws; "
"top draw %dx%d at %d,%d image %dx%d %s%s surface=%s dmabuf=%s; "
"draw below %s",
scene_w, scene_h, dl->n, a ? a->dw : 0, a ? a->dh : 0, a ? a->dx : 0, a ? a->dy : 0,
a ? vkp_image_width(a->img) : 0, a ? vkp_image_height(a->img) : 0,
a && vkp_image_is_dmabuf(a->img) ? "DMA-BUF" : "non-DMA-BUF",
a && a->blend ? " blended" : "",
sa ? "associated" : "unassociated",
sa && sa->dmabuf_buf ? "yes" : "no",
below);
}
static struct surface *surface_for_image(const struct vkp_image *img) {
struct surface *s;
wl_list_for_each(s, &g_surfaces, link)
@@ -2430,16 +2580,56 @@ static struct surface *surface_for_image(const struct vkp_image *img) {
}
static struct surface *ahb_layer_only_candidate(int scene_w, int scene_h) {
static struct {
const struct surface *surface;
int reason, scene_w, scene_h, w, h, buf_w, buf_h, x, y, src_set, dst_set, children;
} seen[32];
static unsigned seen_count;
static int limit_logged;
struct surface *s;
int w, h;
int w = 0, h = 0, reason = 0;
if (wl_list_empty(&g_toplevels)) return NULL;
s = wl_container_of(g_toplevels.prev, s, toplevel_link);
if (!s->dmabuf_buf || s->dmabuf_buf->img || !ahb_swapchain_has_ahb(s->dmabuf_buf)) return NULL;
if ((g_desktop && !s->placed) || s->x != 0 || s->y != 0 || s->src_set || s->dst_set) return NULL;
if (!wl_list_empty(&s->children)) return NULL;
if (g_hide_shell && !strcmp(client_name(wl_resource_get_client(s->resource)), "explorer.exe")) return NULL;
if (!s->dmabuf_buf) reason = 1;
else if (s->dmabuf_buf->img) reason = 2;
else if (!ahb_swapchain_has_ahb(s->dmabuf_buf)) reason = 3;
else if ((g_desktop && !s->placed) || s->x != 0 || s->y != 0 || s->src_set || s->dst_set) reason = 4;
else if (!wl_list_empty(&s->children)) reason = 5;
else if (g_hide_shell && !strcmp(client_name(wl_resource_get_client(s->resource)), "explorer.exe")) reason = 6;
surface_size(s, &w, &h);
if (w != scene_w || h != scene_h || s->buf_w != scene_w || s->buf_h != scene_h) return NULL;
if (!reason && (w != scene_w || h != scene_h || s->buf_w != scene_w || s->buf_h != scene_h)) reason = 7;
if (reason) {
int found = 0;
for (unsigned i = 0; i < seen_count; i++) {
if (seen[i].surface == s && seen[i].reason == reason && seen[i].scene_w == scene_w &&
seen[i].scene_h == scene_h && seen[i].w == w && seen[i].h == h &&
seen[i].buf_w == s->buf_w && seen[i].buf_h == s->buf_h && seen[i].x == s->x &&
seen[i].y == s->y && seen[i].src_set == s->src_set && seen[i].dst_set == s->dst_set &&
seen[i].children == !wl_list_empty(&s->children)) { found = 1; break; }
}
if (!found && seen_count < 32) {
seen[seen_count].surface = s; seen[seen_count].reason = reason;
seen[seen_count].scene_w = scene_w; seen[seen_count].scene_h = scene_h;
seen[seen_count].w = w; seen[seen_count].h = h; seen[seen_count].buf_w = s->buf_w; seen[seen_count].buf_h = s->buf_h;
seen[seen_count].x = s->x; seen[seen_count].y = s->y; seen[seen_count].src_set = s->src_set;
seen[seen_count].dst_set = s->dst_set; seen[seen_count].children = !wl_list_empty(&s->children);
seen_count++;
const char *why = reason == 1 ? "no DMA-BUF buffer" :
reason == 2 ? "buffer is already importable by Vulkan" :
reason == 3 ? "no registered gralloc AHardwareBuffer" :
reason == 4 ? "surface is positioned/cropped/scaled" :
reason == 5 ? "surface has child surfaces" :
reason == 6 ? "hidden shell surface" : "surface or buffer dimensions differ from scene";
char name[160]; describe(s, name, sizeof(name));
droiddeck_log("layer", "zero-copy: AHardwareBuffer-only candidate rejected: %s; %s, scene %dx%d, surface %dx%d at %d,%d, buffer %dx%d, crop=%d destination=%d children=%d",
why, name, scene_w, scene_h, w, h, s->x, s->y, s->buf_w, s->buf_h,
s->src_set, s->dst_set, !wl_list_empty(&s->children));
} else if (!found && !limit_logged) {
limit_logged = 1;
droiddeck_log("layer", "zero-copy: further AHardwareBuffer-only candidate diagnostics suppressed after 32 signatures");
}
return NULL;
}
return s;
}
@@ -2882,7 +3072,10 @@ static void render_scene(void) {
struct surface *ls = li >= 0 ? surface_for_image(dl.d[li].img) : NULL;
const struct vkp_draw *ld = li >= 0 ? &dl.d[li] : NULL;
if (li < 0) ls = layer_only;
if (g_zero_copy && li < 0 && !ls && !blocked && !cardboard) note_copy_scene(&dl, w, h, cursor_on);
if (g_zero_copy && li < 0 && !ls && !blocked && !cardboard) {
if (!cursor_on && !bfi) note_layer_candidate_rejected(&dl, w, h);
note_copy_scene(&dl, w, h, cursor_on);
}
if (cardboard) ls = NULL;
if (cursor_on) ls = NULL;
if (bfi) ls = NULL;
@@ -2910,15 +3103,30 @@ static void render_scene(void) {
r = generated >= 0 ? 0 : -1;
else if (generated >= 0 && !(fx_on && li >= 0) && ls && ls->dmabuf_buf && ahb_swapchain_has_ahb(ls->dmabuf_buf))
r = ahb_swapchain_present(ls->dmabuf_buf, ls, w, h, ld);
if (!fg_pass && generated >= 0 && !fx_on && !framegen && r != 0) {
if (!ls || !ls->dmabuf_buf)
note_zero_copy_fallback(ls, NULL, ZERO_COPY_NO_SURFACE_BUFFER, w, h, r);
else if (!ahb_swapchain_has_ahb(ls->dmabuf_buf))
note_zero_copy_fallback(ls, ls->dmabuf_buf, ZERO_COPY_NO_GRALLOC_AHB, w, h, r);
else
note_zero_copy_fallback(ls, ls->dmabuf_buf, ZERO_COPY_AHB_PRESENT_FAILED, w, h, r);
}
if (r == 0 && !fg_pass) g_zero_copy_shown = ls;
else settle_unwaited();
if (!fg_pass && generated >= 0 && r != 0 && li >= 0)
r = fx_on ? sc_layer_present_pass(&dl.d[li], 1, w, h)
: sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL);
int ov = 0, ov_done = 0;
if (!fg_pass && generated >= 0 && r != 0 && li >= 0) {
if (fx_on) {
r = sc_layer_present_pass(&dl.d[li], 1, w, h);
} else {
r = sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL,
over == 1 ? &dl.d[li + 1] : NULL, &ov);
ov_done = 1;
}
}
if (r == 0) {
if (ls) ls->drawn = 1;
int go[8], ov = 0;
if (over == 1 && li >= 0 && vkp_map_draw(&dl.d[li + 1], go))
int go[8];
if (!ov_done && over == 1 && li >= 0 && vkp_map_draw(&dl.d[li + 1], go))
ov = sc_layer_present_overlay(dl.d[li + 1].img, go, dl.d[li + 1].blend) == 0 ? 1 : -1;
if (ov <= 0) sc_layer_hide_overlay();
if (ov < 0) {
@@ -4375,11 +4583,15 @@ static void output_resized(void) {
wl_display_flush_clients(g_display);
}
static int on_input_readable(int fd, uint32_t mask, void *data) {
static void dispatch_input(int fd, int remaining) {
struct input_msg m;
int vsync = 0;
int64_t vsync_ns = 0;
while (read(fd, &m, sizeof(m)) == (ssize_t)sizeof(m)) {
while (remaining != 0) {
ssize_t n = read(fd, &m, sizeof(m));
if (n < 0 && errno == EINTR) continue;
if (n != (ssize_t)sizeof(m)) break;
if (remaining > 0) --remaining;
switch (m.type) {
case 1: deliver_key(&m); break;
case 2: pointer_event(m.p1, m.p2, 0, 0); break;
@@ -4421,9 +4633,27 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
wl_display_flush_clients(g_display);
}
if (vsync) on_vsync(vsync_ns);
}
static int on_input_readable(int fd, uint32_t mask, void *data) {
dispatch_input(fd, -1);
return 0;
}
void droiddeck_dispatch_pending_input(void) {
int fd = g_input_pipe[0];
if (fd < 0) return;
int bytes;
int result;
do {
result = ioctl(fd, FIONREAD, &bytes);
} while (result < 0 && errno == EINTR);
if (result == 0 && bytes >= (int)sizeof(struct input_msg)) {
dispatch_input(fd, bytes / (int)sizeof(struct input_msg));
}
}
void droiddeck_wayland_set_scale_mode(int mode, int alignment) {
if (g_input_pipe[1] < 0) {
vk_present_set_scale_mode(mode, alignment);
@@ -4560,6 +4790,11 @@ void droiddeck_surface_scene_origin(struct wl_resource *surface, int *x, int *y)
void droiddeck_inject_key(uint32_t evdev, int pressed) { key_event(evdev, pressed); }
int droiddeck_key_is_down(uint32_t evdev) {
return evdev < sizeof(g_keys_down) * 8 &&
(g_keys_down[evdev >> 3] & (1u << (evdev & 7))) != 0;
}
static struct wl_event_source *g_stats_timer;
volatile unsigned g_zero_copy_last;
@@ -62,8 +62,40 @@ struct entry {
static struct wl_list g_entries;
static struct wl_event_loop *g_loop;
static uint64_t g_next_id = 1;
static int g_refused_logged;
static int g_ubwc_promised;
#define DISPLAY_BUFFER_MISMATCH_SIGNATURES 64u
struct display_buffer_mismatch_signature {
uint32_t kind, format, stride, offset;
int width, height;
uint64_t modifier;
};
static struct display_buffer_mismatch_signature g_mismatch_signatures[DISPLAY_BUFFER_MISMATCH_SIGNATURES];
static uint32_t g_mismatch_signature_count;
static int g_mismatch_limit_logged;
static int mismatch_should_log(const struct dmabuf_buffer *b, uint32_t kind) {
const struct display_buffer_mismatch_signature key = {
.kind = kind, .format = b->format, .stride = b->stride[0], .offset = b->offset[0],
.width = b->width, .height = b->height, .modifier = b->modifier};
for (uint32_t i = 0; i < g_mismatch_signature_count; i++) {
const struct display_buffer_mismatch_signature *seen = &g_mismatch_signatures[i];
if (seen->kind == key.kind && seen->format == key.format && seen->stride == key.stride &&
seen->offset == key.offset && seen->width == key.width && seen->height == key.height &&
seen->modifier == key.modifier)
return 0;
}
if (g_mismatch_signature_count >= DISPLAY_BUFFER_MISMATCH_SIGNATURES) {
if (!g_mismatch_limit_logged) {
g_mismatch_limit_logged = 1;
droiddeck_log("layer", "display buffers: further mismatch diagnostics suppressed after %u distinct buffer signatures",
DISPLAY_BUFFER_MISMATCH_SIGNATURES);
}
return 0;
}
g_mismatch_signatures[g_mismatch_signature_count++] = key;
return 1;
}
static int g_ubwc_probed[2];
static uint32_t ahb_format_of(uint32_t drm, uint64_t modifier) {
@@ -238,16 +270,51 @@ static void handle_alloc(struct peer *p, const struct display_buffers_request *q
} else {
if (ahb) AHardwareBuffer_release(ahb);
fd = -1;
if (sized && wanted && (compressed || !g_refused_logged)) {
g_refused_logged = 1;
droiddeck_log(compressed ? "error" : "layer", "display buffers: no gralloc buffer matches pid %d's %ux%u "
"%c%c%c%c %s layout (stride %u bytes, pixels at %u, %llu bytes; gralloc's layout has pixels at "
"%llu, %llu bytes): %s", (int)p->pid, q->width, q->height,
q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff,
compressed ? "UBWC" : "linear", q->stride, q->offset, (unsigned long long)q->size,
(unsigned long long)(compressed ? ubwc_meta_size(q->width, q->height) : 0),
(unsigned long long)(compressed ? ubwc_size(q->width, q->height, q->stride) : q->size),
compressed ? "its compressed frames cannot be shown" : "its frames keep the copy path");
static struct {
pid_t pid;
uint32_t width, height, format, stride, offset, reason;
uint64_t size, modifier;
} refused[32];
static unsigned refused_count;
static int refused_limit_logged;
uint32_t reason = !sized ? 1u : !sane ? 2u : !wanted ? 3u :
!ahb_swapchain_advertised() ? 4u :
p->count >= DISPLAY_BUFFERS_MAX_PER_CLIENT ? 5u : 6u;
int seen = 0;
for (unsigned i = 0; i < refused_count; i++) {
if (refused[i].pid == p->pid && refused[i].width == q->width && refused[i].height == q->height &&
refused[i].format == q->format && refused[i].stride == q->stride && refused[i].offset == q->offset &&
refused[i].size == q->size && refused[i].modifier == q->modifier && refused[i].reason == reason) {
seen = 1;
break;
}
}
if (!seen && refused_count < 32) {
refused[refused_count].pid = p->pid;
refused[refused_count].width = q->width;
refused[refused_count].height = q->height;
refused[refused_count].format = q->format;
refused[refused_count].stride = q->stride;
refused[refused_count].offset = q->offset;
refused[refused_count].size = q->size;
refused[refused_count].modifier = q->modifier;
refused[refused_count].reason = reason;
refused_count++;
const char *why = reason == 1 ? "invalid dimensions, format, or stride" :
reason == 2 ? "size/offset/layout sanity check failed" :
reason == 3 ? "zero-copy or UBWC offering is disabled" :
reason == 4 ? "AHardwareBuffer swapchain is not advertised" :
reason == 5 ? "per-client allocation limit reached" :
"gralloc allocation/fd/size validation failed";
droiddeck_log(compressed ? "error" : "layer",
"display buffers: allocation refused for pid %d: %s; request %ux%u %c%c%c%c %s stride=%u offset=%u size=%llu modifier=0x%llx (client has %d allocations)",
(int)p->pid, why, q->width, q->height,
q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff,
compressed ? "UBWC" : "linear", q->stride, q->offset,
(unsigned long long)q->size, (unsigned long long)q->modifier, p->count);
} else if (!seen && !refused_limit_logged) {
refused_limit_logged = 1;
droiddeck_log("layer", "display buffers: further allocation-refusal diagnostics suppressed after 32 signatures");
}
}
if (reply(p, &r, fd) != 0 && e) entry_free(e);
@@ -299,9 +366,18 @@ static int on_listen(int fd, uint32_t mask, void *data) {
}
void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b) {
static int invalid_logged;
struct stat st;
struct entry *e;
if (!g_loop || wl_list_empty(&g_entries) || b->n_planes != 1 || b->offset[0] != 0 || fstat(b->fd[0], &st) != 0) return;
if (!g_loop || wl_list_empty(&g_entries)) return;
if (b->n_planes != 1 || b->offset[0] != 0 || fstat(b->fd[0], &st) != 0) {
if (!invalid_logged) {
invalid_logged = 1;
droiddeck_log("layer", "display buffers: cannot associate %s's DMA-BUF with gralloc (plane count %u; expected one plane at offset 0, or fstat failed)",
droiddeck_client_name(c), b->n_planes);
}
return;
}
wl_list_for_each(e, &g_entries, link) {
if (e->dev != st.st_dev || e->ino != st.st_ino) continue;
AHardwareBuffer_Desc d;
@@ -311,11 +387,27 @@ void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, stru
(uint32_t)b->height == e->height
: (b->modifier == MOD_LINEAR || b->modifier == MOD_INVALID) &&
e->stride == b->stride[0];
if (laid_out && e->format == ahb_format_of(b->format, e->modifier) && b->width > 0 && b->height > 0 &&
(uint32_t)b->width <= d.width && (uint32_t)b->height <= d.height)
const uint32_t expected_format = ahb_format_of(b->format, e->modifier);
const int dimensions = b->width > 0 && b->height > 0 &&
(uint32_t)b->width <= d.width && (uint32_t)b->height <= d.height;
if (laid_out && e->format == expected_format && dimensions) {
ahb_swapchain_adopt(c, buffer, b, e->ahb, e->modifier);
} else if (mismatch_should_log(b, 2)) {
droiddeck_log("layer", "display buffers: gralloc DMA-BUF identity matched but layout was rejected for %s: %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx; gralloc %ux%u stride %u format 0x%x, expected format 0x%x (layout %s, dimensions %s)",
droiddeck_client_name(c), b->format & 0xff, (b->format >> 8) & 0xff,
(b->format >> 16) & 0xff, (b->format >> 24) & 0xff, b->width, b->height,
b->stride[0], b->offset[0], (unsigned long long)b->modifier,
e->width, e->height, e->stride, e->format, expected_format,
laid_out ? "ok" : "mismatch", dimensions ? "ok" : "mismatch");
}
return;
}
if (mismatch_should_log(b, 1)) {
droiddeck_log("layer", "display buffers: no registered gralloc allocation matches %s's DMA-BUF identity: %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx; imported normally, copy path only",
droiddeck_client_name(c), b->format & 0xff, (b->format >> 8) & 0xff,
(b->format >> 16) & 0xff, (b->format >> 24) & 0xff, b->width, b->height,
b->stride[0], b->offset[0], (unsigned long long)b->modifier);
}
}
void display_buffers_init(struct wl_display *display) {
@@ -4,12 +4,14 @@
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <limits.h>
#include <linux/input-event-codes.h>
#include <android/log.h>
#include "droiddeck_ext.h"
#include "ahb_swapchain.h"
#include "droiddeck_color.h"
enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT };
enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD };
struct host_msg {
enum host_kind kind;
@@ -23,6 +25,32 @@ static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER;
static struct host_msg *g_head, *g_tail;
static int g_wake[2] = {-1, -1};
/* Compositor-thread-only fallback ordering state. */
static int g_pending_token, g_pending_submit;
static int g_fallback_failed;
static int g_next_token = 1;
static struct host_msg *g_deferred_head, *g_deferred_tail;
static size_t g_deferred_count, g_deferred_bytes;
static int g_deferred_overflow;
static int g_completed_token, g_completed_result;
#define DROIDDECK_EVDEV_KEY_MAX 768
#define DROIDDECK_TEXT_DEFERRED_LIMIT 256
#define DROIDDECK_TEXT_DEFERRED_BYTES (256 * 1024)
static unsigned char g_ordered_key_down[DROIDDECK_EVDEV_KEY_MAX];
void droiddeck_host_text_input_fallback_complete(int token, int result) {
pthread_mutex_lock(&g_mu);
g_completed_token = token;
g_completed_result = result;
pthread_mutex_unlock(&g_mu);
if (g_wake[1] >= 0) {
char c = 1;
ssize_t n = write(g_wake[1], &c, 1);
(void)n;
}
}
static void host_post(enum host_kind kind, const char *text, size_t len, int a, int b) {
struct host_msg *m = calloc(1, sizeof(*m));
if (!m) return;
@@ -51,6 +79,9 @@ void droiddeck_host_clipboard_text(const char *utf8, int len) {
void droiddeck_host_text_commit(const char *utf8, int len) {
host_post(HOST_TEXT_COMMIT, utf8, len > 0 ? (size_t)len : 0, 0, 0);
}
void droiddeck_host_text_commit_and_submit(const char *utf8, int len) {
if (len > 0) host_post(HOST_TEXT_COMMIT, utf8, (size_t)len, 1, 0);
}
void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end) {
host_post(HOST_TEXT_PREEDIT, utf8, len > 0 ? (size_t)len : 0, cursor_begin, cursor_end);
}
@@ -63,23 +94,173 @@ void droiddeck_host_zero_copy(int on, int live) {
void droiddeck_host_hdr_output(int on) {
host_post(HOST_HDR_OUTPUT, NULL, 0, on, 0);
}
void droiddeck_host_key(int evdev, int state) {
host_post(HOST_KEY, NULL, 0, evdev, state);
}
void droiddeck_host_select_game_field(int copy) {
host_post(HOST_SELECT_GAME_FIELD, NULL, 0, copy, 0);
}
static void tap_unheld_key(uint32_t key) {
if (droiddeck_key_is_down(key)) return;
droiddeck_inject_key(key, 1);
droiddeck_inject_key(key, 0);
}
static void select_game_field(int copy) {
/* Apply pending raw releases before using the compositor's held-key state. */
droiddeck_dispatch_pending_input();
int temporary_ctrl = !droiddeck_key_is_down(KEY_LEFTCTRL) && !droiddeck_key_is_down(KEY_RIGHTCTRL);
if (temporary_ctrl) droiddeck_inject_key(KEY_LEFTCTRL, 1);
tap_unheld_key(KEY_A);
if (copy) tap_unheld_key(KEY_C);
if (temporary_ctrl) droiddeck_inject_key(KEY_LEFTCTRL, 0);
}
static void restore_deferred_to_front(void) {
if (g_deferred_head) {
g_deferred_tail->next = g_head;
if (!g_head) g_tail = g_deferred_tail;
g_head = g_deferred_head;
g_deferred_head = g_deferred_tail = NULL;
g_deferred_count = g_deferred_bytes = 0;
}
}
/* Only suppress the queued submit for this commit, not a later commit or a held-key release. */
static void discard_queued_submit(void) {
struct host_msg *prev = NULL;
struct host_msg *m = g_head;
int enter_held = g_ordered_key_down[KEY_ENTER];
int key_pad_enter_held = g_ordered_key_down[KEY_KPENTER];
while (m) {
int soft_submit = 0;
if (m->kind == HOST_TEXT_COMMIT) {
if (m->a || m->len == 0) break;
soft_submit = 1;
size_t i = 0;
for (; i < m->len; i++) {
char c = m->text[i];
if (c != '\r' && c != '\n') soft_submit = 0;
if (c != '\r' && c != '\n' && c != '\b' && c != '\t' && c != 0x7f) break;
}
if (i != m->len) break;
}
struct host_msg *next = m->next;
int *held = m->a == KEY_ENTER ? &enter_held : m->a == KEY_KPENTER ? &key_pad_enter_held : NULL;
if (soft_submit || (m->kind == HOST_KEY && held && (m->b != 0 || !*held))) {
if (prev) prev->next = next; else g_head = next;
if (g_tail == m) g_tail = prev;
free(m->text);
free(m);
} else {
if (m->kind == HOST_KEY && held) *held = 0;
prev = m;
}
m = next;
}
}
static int release_held_key(const struct host_msg *m) {
int k = m->a;
if (m->kind != HOST_KEY || m->b != 0 || k < 0 || k >= DROIDDECK_EVDEV_KEY_MAX ||
!g_ordered_key_down[k]) return 0;
g_ordered_key_down[k] = 0;
droiddeck_inject_key((uint32_t)k, 0);
return 1;
}
static void discard_deferred_input(void) {
struct host_msg *m = g_deferred_head;
while (m) {
struct host_msg *next = m->next;
release_held_key(m);
free(m->text);
free(m);
m = next;
}
g_deferred_head = g_deferred_tail = NULL;
g_deferred_count = g_deferred_bytes = 0;
}
static int on_wake(int fd, uint32_t mask, void *data) {
char buf[64];
while (read(fd, buf, sizeof(buf)) > 0) {}
for (;;) {
int deferred = 0, submit = 0;
pthread_mutex_lock(&g_mu);
if (g_pending_token != 0 && g_completed_token == g_pending_token) {
int result = g_completed_result;
g_completed_token = 0;
restore_deferred_to_front();
if (result != DROIDDECK_TEXT_DELIVERED) discard_queued_submit();
if (result == DROIDDECK_TEXT_UNRESOLVED) {
g_fallback_failed = 1;
} else {
if (result == DROIDDECK_TEXT_DELIVERED) submit = g_pending_submit;
g_pending_submit = 0;
g_pending_token = 0;
g_fallback_failed = 0;
g_deferred_overflow = 0;
}
}
struct host_msg *m = g_head;
if (m) { g_head = m->next; if (!g_head) g_tail = NULL; }
if (m) { g_head = m->next; if (!g_head) g_tail = NULL; m->next = NULL; }
pthread_mutex_unlock(&g_mu);
if (submit) tap_unheld_key(KEY_ENTER);
if (!m) break;
if (g_pending_token != 0 &&
(m->kind == HOST_TEXT_COMMIT || m->kind == HOST_TEXT_PREEDIT ||
m->kind == HOST_TEXT_DELETE || m->kind == HOST_KEY ||
m->kind == HOST_SELECT_GAME_FIELD)) {
int released_during_recovery = g_fallback_failed && release_held_key(m);
if (released_during_recovery || g_deferred_overflow ||
g_deferred_count == DROIDDECK_TEXT_DEFERRED_LIMIT ||
m->len > DROIDDECK_TEXT_DEFERRED_BYTES - g_deferred_bytes) {
if (!released_during_recovery) {
/* An incomplete queue could replay a submit or lose a paired release. */
if (!g_deferred_overflow)
droiddeck_log("text-input", "deferred input exceeded the recovery queue limit");
discard_deferred_input();
release_held_key(m);
g_deferred_overflow = 1;
}
free(m->text);
free(m);
continue;
}
if (g_deferred_tail) g_deferred_tail->next = m; else g_deferred_head = m;
g_deferred_tail = m;
g_deferred_count++;
g_deferred_bytes += m->len;
deferred = 1;
}
if (deferred) continue;
switch (m->kind) {
case HOST_CLIPBOARD:
clipboard_host_text(m->text, m->len);
m->text = NULL;
break;
case HOST_TEXT_COMMIT:
text_input_host_commit(m->text ? m->text : "", m->len);
if (!text_input_host_commit(m->text ? m->text : "", m->len)) {
int token = 0;
if (g_next_token == INT_MAX) g_next_token = 1;
else g_next_token++;
token = g_next_token;
g_pending_token = 0;
if (droiddeck_on_text_input_fallback(m->text ? m->text : "", (int)m->len, token)) {
g_pending_token = token;
g_pending_submit = m->a;
} else {
droiddeck_log("text-input", "fallback had no accepting Android listener");
pthread_mutex_lock(&g_mu);
discard_queued_submit();
pthread_mutex_unlock(&g_mu);
}
} else if (m->a) {
tap_unheld_key(KEY_ENTER);
}
break;
case HOST_TEXT_PREEDIT:
text_input_host_preedit(m->text ? m->text : "", m->len, m->a, m->b);
@@ -93,6 +274,19 @@ static int on_wake(int fd, uint32_t mask, void *data) {
case HOST_HDR_OUTPUT:
droiddeck_color_set_output(m->a);
break;
case HOST_SELECT_GAME_FIELD:
select_game_field(m->a);
break;
case HOST_KEY:
if (m->b == 1) {
int k = m->a;
if (k >= 0 && k < DROIDDECK_EVDEV_KEY_MAX) g_ordered_key_down[k] = 1;
} else if (m->b == 0) {
int k = m->a;
if (k >= 0 && k < DROIDDECK_EVDEV_KEY_MAX) g_ordered_key_down[k] = 0;
}
droiddeck_inject_key((uint32_t)m->a, m->b);
break;
}
free(m->text);
free(m);
@@ -15,22 +15,34 @@ struct wl_display *droiddeck_get_display(void);
struct wl_resource *droiddeck_ime_target(void);
void droiddeck_surface_scene_origin(struct wl_resource *surface, int *x, int *y);
void droiddeck_inject_key(uint32_t evdev, int pressed);
int droiddeck_key_is_down(uint32_t evdev);
void droiddeck_dispatch_pending_input(void);
void droiddeck_on_clipboard_text(const char *utf8, int len);
int droiddeck_on_text_input_fallback(const char *utf8, int len, int token);
void droiddeck_on_text_input(int enabled, const char *program, int x, int y, int w, int h);
void droiddeck_host_clipboard_text(const char *utf8, int len);
void droiddeck_host_text_commit(const char *utf8, int len);
void droiddeck_host_text_commit_and_submit(const char *utf8, int len);
void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end);
void droiddeck_host_text_delete(int before, int after);
void droiddeck_host_zero_copy(int on, int live);
void droiddeck_host_hdr_output(int on);
void droiddeck_host_key(int evdev, int state);
void droiddeck_host_select_game_field(int copy);
enum droiddeck_text_input_result {
DROIDDECK_TEXT_NOT_DELIVERED = 0,
DROIDDECK_TEXT_DELIVERED = 1,
DROIDDECK_TEXT_UNRESOLVED = 2,
};
void droiddeck_host_text_input_fallback_complete(int token, int result);
void clipboard_init(struct wl_display *display);
void clipboard_host_text(char *utf8, size_t len);
void text_input_init(struct wl_display *display);
void text_input_host_commit(const char *utf8, size_t len);
int text_input_host_commit(const char *utf8, size_t len);
void text_input_host_preedit(const char *utf8, size_t len, int cursor_begin, int cursor_end);
void text_input_host_delete(int before, int after);
void toplevel_icon_init(struct wl_display *display);
+58 -14
View File
@@ -187,6 +187,8 @@ struct layer {
static struct layer g_layers[SC_LAYER_COUNT];
static void apply_frame_rate(ASurfaceTransaction *tx, struct layer *l);
static void coverage_text(const struct layer *l, char *out, size_t n);
static int overlay_slot(struct layer *l, struct vkp_image *src, int *idx, int *wait_fd);
static int overlay_shown(struct layer *l, int idx, const int geo[8], int translucent);
static int g_layers_ready;
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static int g_pending_cb;
@@ -721,9 +723,15 @@ static int layer_geometry(int w, int h, int scene_w, int scene_h, const struct v
static ARect g_game_src, g_game_dst;
static int g_game_geo_known;
static void note_game_geometry(const int r[8]) {
g_game_src = (ARect){r[0], r[1], r[2], r[3]};
g_game_dst = (ARect){r[4], r[5], r[6], r[7]};
g_game_geo_known = 1;
}
static void apply_geometry(ASurfaceTransaction *tx, struct layer *l, const int r[8]) {
ARect srcR = {r[0], r[1], r[2], r[3]}, dstR = {r[4], r[5], r[6], r[7]};
if (l == &g_layers[SC_LAYER_GAME]) { g_game_src = srcR; g_game_dst = dstR; g_game_geo_known = 1; }
if (l == &g_layers[SC_LAYER_GAME]) note_game_geometry(r);
if (!l->geo_valid || memcmp(&srcR, &l->geo_src, sizeof(srcR)) || memcmp(&dstR, &l->geo_dst, sizeof(dstR))) {
api.setGeometry(tx, l->sc, &srcR, &dstR, 0 );
l->geo_src = srcR; l->geo_dst = dstR; l->geo_valid = 1;
@@ -998,19 +1006,40 @@ unavailable:
}
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw,
const struct droiddeck_color *color) {
const struct droiddeck_color *color, const struct vkp_draw *over, int *over_shown) {
struct layer *l = layer_of(SC_LAYER_GAME);
*over_shown = 0;
if (!src || ensure_sc(l) != 0) return -1;
int sw = vkp_image_width(src), sh = vkp_image_height(src);
int r[8];
int g = layer_geometry(sw, sh, scene_w, scene_h, draw, r);
if (g < 0) return -1;
if (g == 0) { sc_layer_hide(); return 0; }
int og[8];
if (over && !vkp_map_draw(over, og)) over = NULL;
if (g == 0) {
sc_layer_hide();
if (over) *over_shown = sc_layer_present_overlay(over->img, og, over->blend) == 0 ? 1 : -1;
return 0;
}
int wait_fd;
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
struct vkp_blit blits[2] = {{.src = src, .wait_fd = -1}, {.src = over ? over->img : NULL, .wait_fd = -1}};
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &blits[0].wait_fd);
if (idx < 0) {
log_drop(l);
if (g_alloc_failed) return -1;
if (over) *over_shown = sc_layer_present_overlay(over->img, og, over->blend) == 0 ? 1 : -1;
return 0;
}
blits[0].dst = l->slots[idx].img;
struct layer *ol = layer_of(SC_LAYER_OVERLAY);
int over_idx = -1;
if (over) {
note_game_geometry(r);
const int taken = overlay_slot(ol, over->img, &over_idx, &blits[1].wait_fd);
*over_shown = taken < 0 ? -1 : 1;
if (taken > 0) blits[1].dst = ol->slots[over_idx].img;
}
if (vkp_blit_images(blits, over_idx >= 0 ? 2 : 1) != 0) return -1;
if (present_slot(l, idx, r, color, 0) != 0) return -1;
if (color && color->dataspace) droiddeck_color_frame_shown(color, DROIDDECK_HDR_LAYER_COPY, AHB_RGBA8);
if (!l->first_logged) {
@@ -1020,6 +1049,7 @@ int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const stru
pool_kind(l->pool_modifier), l->pool_n);
}
vkp_signal_first_frame();
if (over_idx >= 0 && overlay_shown(ol, over_idx, og, over->blend) != 0) *over_shown = -1;
return 0;
}
@@ -1209,17 +1239,19 @@ int sc_layer_overlay_affordable(void) {
return ok;
}
int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent) {
struct layer *l = layer_of(SC_LAYER_OVERLAY);
if (!src || !geo) return -1;
static int overlay_slot(struct layer *l, struct vkp_image *src, int *idx, int *wait_fd) {
*wait_fd = -1;
if (!src) return -1;
if (!sc_layer_overlay_affordable()) return -1;
if (ensure_sc(l) != 0) return -1;
int sw = vkp_image_width(src), sh = vkp_image_height(src);
if (sw <= 0 || sh <= 0) return -1;
int wait_fd;
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
*idx = take_free_slot(l, sw, sh, AHB_RGBA8, wait_fd);
if (*idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
return 1;
}
static int overlay_shown(struct layer *l, int idx, const int geo[8], int translucent) {
if (present_slot(l, idx, geo, NULL, translucent) != 0) return -1;
if (!l->first_logged) {
l->first_logged = 1;
@@ -1228,6 +1260,18 @@ int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int transl
return 0;
}
int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent) {
struct layer *l = layer_of(SC_LAYER_OVERLAY);
if (!geo) return -1;
int idx;
struct vkp_blit blit = {.src = src, .wait_fd = -1};
const int taken = overlay_slot(l, src, &idx, &blit.wait_fd);
if (taken <= 0) return taken;
blit.dst = l->slots[idx].img;
if (vkp_blit_images(&blit, 1) != 0) return -1;
return overlay_shown(l, idx, geo, translucent);
}
static int hide_layer(struct layer *l) {
if (!l->sc || !l->shown || api.state != 1) return 0;
ASurfaceTransaction *tx = api.txCreate();
+1 -1
View File
@@ -22,7 +22,7 @@ void sc_layer_hdr_symbols(char *out, size_t size);
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw,
const struct droiddeck_color *color);
const struct droiddeck_color *color, const struct vkp_draw *over, int *over_shown);
int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int scene_h);
int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const struct vkp_hdr_frame *hf,
+62 -27
View File
@@ -20,6 +20,8 @@
#include <unistd.h>
#include <errno.h>
#include <poll.h>
#include <linux/sync_file.h>
#include <sys/ioctl.h>
#include <time.h>
#include <pthread.h>
#include <stdarg.h>
@@ -3162,8 +3164,38 @@ static void blit_to_layer(VkCommandBuffer cmd, VkImage src, VkImageLayout src_la
0, 0, NULL, 0, NULL, 1, &release);
}
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
if (!src || src->blit_dst || !dst || !dst->blit_dst || dev_init() != 0) {
static int merge_wait_fds(int a, int b) {
if (a < 0) return b;
if (b < 0) return a;
struct sync_merge_data m = {.name = "droiddeck-layer-copy", .fd2 = b};
if (ioctl(a, SYNC_IOC_MERGE, &m) == 0) {
close(a);
close(b);
return m.fence;
}
struct pollfd p = {.fd = b, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
close(b);
if (r != 0) return a;
p.fd = a;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
close(a);
return -2;
}
int vkp_blit_images(const struct vkp_blit *blits, int n) {
int wait_fd = -1;
for (int i = 0; i < n; i++) {
if (wait_fd == -2) { if (blits[i].wait_fd >= 0) close(blits[i].wait_fd); continue; }
wait_fd = merge_wait_fds(wait_fd, blits[i].wait_fd);
}
int valid = n > 0 && wait_fd != -2;
for (int i = 0; valid && i < n; i++) {
const struct vkp_image *src = blits[i].src, *dst = blits[i].dst;
if (!src || src->blit_dst || !dst || !dst->blit_dst) valid = 0;
}
if (!valid || dev_init() != 0) {
if (wait_fd >= 0) close(wait_fd);
return -1;
}
@@ -3176,32 +3208,35 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(g_cmd, &bi);
stage_linear_dmabuf(g_cmd, src);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair);
VkImageMemoryBarrier acq = src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
if (!src_external) {
acq.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq.newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
src->in_general = 1;
for (int i = 0; i < n; i++) {
struct vkp_image *src = blits[i].src, *dst = blits[i].dst;
stage_linear_dmabuf(g_cmd, src);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair);
VkImageMemoryBarrier acq = src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
if (!src_external) {
acq.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq.newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
src->in_general = 1;
}
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &acq);
int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h;
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {bw, bh, 1}},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
blit_to_layer(g_cmd, src->image, src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst, &blit, VK_FILTER_NEAREST);
release_external_client_image(g_cmd, src);
}
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &acq);
int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h;
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {bw, bh, 1}},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
blit_to_layer(g_cmd, src->image, src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst, &blit, VK_FILTER_NEAREST);
release_external_client_image(g_cmd, src);
g_vk.EndCommandBuffer(g_cmd);
VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
@@ -105,7 +105,11 @@ int vkp_render_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n
int vkp_pass_begin_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
const struct vkp_hdr_frame *hf, int *rw, int *rh);
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd);
struct vkp_blit {
struct vkp_image *src, *dst;
int wait_fd;
};
int vkp_blit_images(const struct vkp_blit *blits, int n);
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px);
int vkp_update_map(int scene_w, int scene_h);
int vkp_map_draw(const struct vkp_draw *d, int out[8]);
@@ -68,6 +68,7 @@ static jmethodID g_on_compositor_frame;
static jmethodID g_on_game_program;
static jmethodID g_on_pointer_lock;
static jmethodID g_on_clipboard;
static jmethodID g_on_text_input_fallback;
static jmethodID g_on_text_input;
static jmethodID g_on_overlay_planes;
static jmethodID g_on_refresh_target;
@@ -92,6 +93,8 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); g_on_game_program = NULL; }
g_on_pointer_lock = (*env)->GetStaticMethodID(env, g_compositor_cls, "onPointerLock", "(ZII)V");
g_on_clipboard = (*env)->GetStaticMethodID(env, g_compositor_cls, "onClipboardText", "([B)V");
g_on_text_input_fallback = (*env)->GetStaticMethodID(env, g_compositor_cls, "onTextInputFallback",
"([BI)Z");
g_on_text_input = (*env)->GetStaticMethodID(env, g_compositor_cls, "onTextInput",
"(ZLjava/lang/String;IIII)V");
g_on_overlay_planes = (*env)->GetStaticMethodID(env, g_compositor_cls, "onOverlayPlanes", "(I)V");
@@ -203,6 +206,20 @@ void droiddeck_on_clipboard_text(const char *utf8, int len) {
(*env)->DeleteLocalRef(env, arr);
}
int droiddeck_on_text_input_fallback(const char *utf8, int len, int token) {
JNIEnv *env;
if (len <= 0 || token <= 0 || !utf8 || !g_compositor_cls || !g_on_text_input_fallback || !(env = thread_env()))
return 0;
jbyteArray arr = (*env)->NewByteArray(env, len);
if (!arr) { (*env)->ExceptionClear(env); return 0; }
(*env)->SetByteArrayRegion(env, arr, 0, len, (const jbyte *)utf8);
jboolean accepted = (*env)->CallStaticBooleanMethod(env, g_compositor_cls, g_on_text_input_fallback, arr,
(jint)token);
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); accepted = JNI_FALSE; }
(*env)->DeleteLocalRef(env, arr);
return accepted == JNI_TRUE ? 1 : 0;
}
void droiddeck_on_text_input(int enabled, const char *program, int x, int y, int w, int h) {
JNIEnv *env;
if (!g_compositor_cls || !g_on_text_input || !(env = thread_env())) return;
@@ -376,6 +393,18 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKey(
droiddeck_wayland_send_key(evdev, state);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKeyOrdered(
JNIEnv *env, jclass clazz, jint evdev, jint state) {
droiddeck_host_key(evdev, state);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSelectGameField(
JNIEnv *env, jclass clazz, jboolean copy) {
droiddeck_host_select_game_field(copy);
}
JNIEXPORT jboolean JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFocusTakesTouch(
JNIEnv *env, jclass clazz) {
@@ -807,6 +836,15 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputCommit(JNIE
free(buf);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputCommitAndSubmit(
JNIEnv *env, jclass clazz, jbyteArray utf8) {
int len;
char *buf = dup_bytes(env, utf8, &len);
if (buf && len) droiddeck_host_text_commit_and_submit(buf, len);
free(buf);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputPreedit(JNIEnv *env, jclass clazz, jbyteArray utf8,
jint cursorBegin, jint cursorEnd) {
@@ -821,6 +859,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputDelete(JNIE
droiddeck_host_text_delete(before, after);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCompleteTextInputFallback(
JNIEnv *env, jclass clazz, jint token, jint result) {
droiddeck_host_text_input_fallback_complete(token, result);
}
extern void adrenotools_set_turbo(bool turbo);
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTurbo(JNIEnv *env, jclass clazz, jboolean on) {
@@ -10,6 +10,12 @@
#ifndef KEY_DELETE
#define KEY_DELETE 111
#endif
#ifndef KEY_ENTER
#define KEY_ENTER 28
#endif
#ifndef KEY_TAB
#define KEY_TAB 15
#endif
static struct wl_display *g_disp;
@@ -203,16 +209,43 @@ static int32_t utf8_offset(const char *s, size_t len, int chars) {
return (int32_t)i;
}
void text_input_host_commit(const char *utf8, size_t len) {
static int control_evdev(unsigned char c) {
switch (c) {
case '\r': case '\n': return KEY_ENTER;
case '\b': return KEY_BACKSPACE;
case 0x7f: return KEY_DELETE;
case '\t': return KEY_TAB;
default: return -1;
}
}
static int all_controls(const char *utf8, size_t len) {
for (size_t i = 0; i < len; i++)
if (control_evdev((unsigned char)utf8[i]) < 0) return 0;
return 1;
}
int text_input_host_commit(const char *utf8, size_t len) {
struct text_input *ti = active_input();
if (!ti) {
droiddeck_log("text-input", "typed text (%zu chars) dropped: no program accepts text input", utf8_chars(utf8, len));
return;
droiddeck_log("text-input", "typed text (%zu chars): no program accepts Wayland text input", utf8_chars(utf8, len));
return 0;
}
if (len > 0 && all_controls(utf8, len)) {
/* Keep editing keys on the compositor queue so they cannot overtake text commits. */
for (size_t i = 0; i < len; i++) {
int code = control_evdev((unsigned char)utf8[i]);
droiddeck_inject_key(code, 1);
droiddeck_inject_key(code, 0);
}
droiddeck_log("text-input", "injected %zu soft control(s) to %s", len, ti_program(ti));
return 1;
}
if (ti->has_preedit) { zwp_text_input_v3_send_preedit_string(ti->res, "", 0, 0); ti->has_preedit = 0; }
zwp_text_input_v3_send_commit_string(ti->res, utf8);
zwp_text_input_v3_send_done(ti->res, ti->serial);
droiddeck_log("text-input", "committed %zu chars to %s", utf8_chars(utf8, len), ti_program(ti));
return 1;
}
void text_input_host_preedit(const char *utf8, size_t len, int cursor_begin, int cursor_end) {
@@ -20,6 +20,10 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
if (android.os.Build.VERSION.SDK_INT >= 28 &&
com.droiddeck.launcher.runtime.GuestWorker.isWorkerProcess(this, Application.getProcessName())) return
if (android.os.Build.VERSION.SDK_INT >= 28 && Application.getProcessName() == packageName)
com.droiddeck.launcher.runtime.GuestWorkers.attach(this)
com.droiddeck.launcher.runtime.NativeGuest.init(this)
com.droiddeck.launcher.session.Onboarding.attach(this)
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
@@ -25,6 +25,7 @@ import android.widget.EditText
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
@@ -192,6 +193,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
private var nativeUserland by mutableStateOf(true)
private var desktopAsUser by mutableStateOf(false)
private var cursorComposite by mutableStateOf(true)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
private var phantomWarning by mutableStateOf<String?>(null)
@@ -206,6 +208,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
private var homePage by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM)
private var launcherFullscreen by mutableStateOf(true)
private var launcherFrost by mutableStateOf(false)
private var frostWallpaper by mutableStateOf(true)
private var frostCards by mutableStateOf(true)
private var frostTransparency by mutableStateOf(com.droiddeck.launcher.ui.FROST_WALLPAPER_DEFAULT)
private var frostCardTransparency by mutableStateOf(com.droiddeck.launcher.ui.FROST_DEFAULT)
private val frost = com.droiddeck.launcher.ui.LauncherFrost(this)
private var controllerHaptics by mutableStateOf(true)
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
private var downloadMirror by mutableStateOf("")
@@ -1371,6 +1379,14 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
requestedOrientation = launcherOrientation
homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this)
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
launcherFrost = SessionPrefs.launcherFrost(this)
frostWallpaper = SessionPrefs.frostWallpaper(this)
frostCards = SessionPrefs.frostCards(this)
frostTransparency = SessionPrefs.frostTransparency(this)
frostCardTransparency = SessionPrefs.frostCardTransparency(this)
frost.start()
frost.prepare(launcherFrost && frostWallpaper)
frost.show(frostShown())
controllerHaptics = SessionPrefs.controllerHaptics(this)
downloadSource = DownloadSource.mode(this)
downloadMirror = DownloadSource.mirror(this)
@@ -1395,8 +1411,14 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
val appsTabShown = "android-apps" !in com.droiddeck.launcher.ui.NavTabs.hidden
androidx.compose.runtime.LaunchedEffect(appsTabShown) { if (appsTabShown && androidApps.isEmpty()) refreshAndroidApps() }
DroidDeckTheme(theme, appScale = appScale) {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().exposeTestTags()) {
val frostShown = frostShown()
androidx.compose.runtime.LaunchedEffect(frostShown) { frost.show(frostShown) }
val frostChoice = if (frostShown) com.droiddeck.launcher.ui.FrostChoice(frostTransparency, frostCards, frostCardTransparency) else null
DroidDeckTheme(theme, appScale = appScale, frost = frostChoice) {
val palette = com.droiddeck.launcher.ui.LocalPalette.current
val veil = com.droiddeck.launcher.ui.LocalFrost.current
val ground = if (frost.prepared) androidx.compose.ui.Modifier.background(veil ?: palette.background) else androidx.compose.ui.Modifier
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().then(ground).exposeTestTags()) {
if (decky.deckyPendingZip != null) com.droiddeck.launcher.ui.DeckyZipWarningDialog(
onConfirm = { decky.confirmPluginZip() }, onCancel = { decky.cancelPluginZip() },
)
@@ -1472,6 +1494,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
launcherOrientation = launcherOrientation,
homePage = homePage,
launcherFullscreen = launcherFullscreen,
launcherFrost = launcherFrost,
frostWallpaper = frostWallpaper,
frostCards = frostCards,
frostTransparency = frostTransparency,
frostCardTransparency = frostCardTransparency,
frostSupported = frost.supported,
controllerHaptics = controllerHaptics,
downloadSource = downloadSource,
downloadMirror = downloadMirror,
@@ -1807,6 +1835,28 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
launcherFullscreen = on
applyLauncherFullscreen()
},
onLauncherFrost = { on ->
SessionPrefs.setLauncherFrost(this, on)
launcherFrost = on
if (on && frostWallpaper && !frost.prepared) restartLauncher()
},
onFrostWallpaper = { on ->
SessionPrefs.setFrostWallpaper(this, on)
frostWallpaper = on
if (on && !frost.prepared) restartLauncher()
},
onFrostCards = { on ->
SessionPrefs.setFrostCards(this, on)
frostCards = on
},
onFrostTransparency = { percent ->
SessionPrefs.setFrostTransparency(this, percent)
frostTransparency = SessionPrefs.frostTransparency(this)
},
onFrostCardTransparency = { percent ->
SessionPrefs.setFrostCardTransparency(this, percent)
frostCardTransparency = SessionPrefs.frostCardTransparency(this)
},
onGameStoresSpeedTier = { tier -> SessionPrefs.setGameStoresSpeedTier(this, tier); gameStoresSpeedTier = tier },
onNavigated = { navRequest = null },
onStoresShowMature = { show -> SessionPrefs.setStoresShowMature(this, show); storesShowMature = show },
@@ -2113,6 +2163,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
private fun frostShown(): Boolean =
launcherFrost && frostWallpaper && frost.prepared && frost.available && theme != com.droiddeck.launcher.ui.Themes.TRUE_BLACK
private fun applyLauncherFullscreen() {
@Suppress("DEPRECATION")
window.decorView.systemUiVisibility = if (launcherFullscreen) {
@@ -2194,7 +2247,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
return true
}
return try {
super.dispatchKeyEvent(event)
super.dispatchKeyEvent(event) || com.droiddeck.launcher.ui.PageBumpers.handle(event)
} catch (e: IllegalStateException) {
if (e.message?.contains("active focus target") != true) throw e
android.util.Log.w("MainActivity", "key ${event.keyCode} dropped: ${e.message}")
@@ -2203,6 +2256,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
private val triggerKeys = com.droiddeck.launcher.input.TriggerKeys { dispatchKeyEvent(it) }
internal fun onMenuMotion(event: MotionEvent) = triggerKeys.onMotion(event)
private val rightStickLayouts = HashMap<Int, Boolean>()
private val rightStickScrollHandler = android.os.Handler(android.os.Looper.getMainLooper())
private var rightStickScrollDeviceId = -1
@@ -2460,6 +2516,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
launchCoordinator.cancelAll()
cancelCompatLaunch()
updates.unregister()
frost.stop()
runCatching { unregisterReceiver(shortcutsInstallStatus) }
super.onDestroy()
}
@@ -3049,7 +3106,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on },
@@ -3066,6 +3123,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
onDesktopAsUser = { on -> SessionPrefs.setDesktopAsUser(this, on); desktopAsUser = on },
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
onClientCore = { core, on ->
@@ -3384,6 +3442,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
nativeUserland = SessionPrefs.nativeUserland(this)
desktopAsUser = SessionPrefs.desktopAsUser(this)
cursorComposite = SessionPrefs.cursorComposite(this)
guestHostname = SessionPrefs.guestHostname(this)
refreshPhantomStatus()
@@ -4,25 +4,32 @@ import android.app.NativeActivity
import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import android.view.Surface
import android.widget.Toast
import com.droiddeck.launcher.gpu.SteamVr
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.xr.XrLayerSource
import com.droiddeck.launcher.session.xr.XrPanels
import com.droiddeck.launcher.wayland.CompositorHost
import com.droiddeck.launcher.wayland.WaylandCompositor
class QuestXrActivity : NativeActivity() {
class QuestXrActivity : NativeActivity(), XrLayerSource {
private var steamVrStarted = false
@Volatile private var closing = false
@Volatile private var steamVrStatus = SteamVr.Status.UNAVAILABLE
private var sessionId: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
// NativeActivity opens the library itself, but the layer host's JNI methods resolve only
// through a System.loadLibrary.
System.loadLibrary("droiddeckxr")
sessionId = SessionState.sessionId
SessionService.setXrActivityVisible(this, true)
super.onCreate(savedInstanceState)
}
fun onXrActive(active: Boolean) {
XrPanels.setDrawing(active)
if (active) {
check(CompositorHost.isStarted) { "DroidDeck compositor is not running" }
SessionService.resume(this)
@@ -100,8 +107,30 @@ class QuestXrActivity : NativeActivity() {
fun onXrStatus(): Int = steamVrStatus.ordinal
fun onXrHostBuffers(state: java.nio.ByteBuffer, control: java.nio.ByteBuffer) {
runOnUiThread { if (!closing) XrPanels.attach(this, state, control) }
}
fun onXrHostFrame() = XrPanels.frame()
override val context: android.content.Context get() = this
override fun createLayer(width: Int, height: Int) = nativeCreateLayer(width, height)
override fun layerSurface(id: Int) = nativeLayerSurface(id)
override fun destroyLayer(id: Int) = nativeDestroyLayer(id)
override fun setOrbImage(image: android.graphics.Bitmap) = nativeSetOrbImage(image)
override fun leave() {
closing = true
finish()
}
private external fun nativeCreateLayer(width: Int, height: Int): Int
private external fun nativeLayerSurface(id: Int): Surface?
private external fun nativeDestroyLayer(id: Int)
private external fun nativeSetOrbImage(image: android.graphics.Bitmap)
override fun onDestroy() {
closing = true
XrPanels.detach()
SessionService.setXrActivityVisible(this, false)
super.onDestroy()
}
@@ -76,6 +76,7 @@ import com.droiddeck.launcher.input.InputSpace
import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.SessionClipboard
import com.droiddeck.launcher.input.SessionTextInput
import com.droiddeck.launcher.input.OnScreenControls
import com.droiddeck.launcher.input.OnScreenLayout
import com.droiddeck.launcher.input.InputRouter
@@ -162,7 +163,8 @@ import kotlin.math.abs
private const val SCREEN_EFFECTS_TARGET_AUTO = "auto"
private const val SCREEN_EFFECTS_TARGET_GLOBAL = "global"
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost {
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost,
com.droiddeck.launcher.session.xr.XrMenuHost {
override fun attachBaseContext(newBase: android.content.Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
@@ -348,6 +350,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
window.decorView.hasWindowFocus() || secondScreenPresentation?.window?.decorView?.hasWindowFocus() == true
}
}
private val sessionTextInput by lazy {
SessionTextInput(this) {
window.decorView.hasWindowFocus() || secondScreenPresentation?.window?.decorView?.hasWindowFocus() == true
}
}
private var watching = true
private lateinit var touchpad: TouchpadGestures
private lateinit var directTouchHold: DirectTouchHold
@@ -546,6 +553,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var drawerOpenState by mutableStateOf(false)
private var typingReturnMode: SecondScreenMode? = null
private var drawerDocked by mutableStateOf(false)
/** The menu is open as a floating panel in the immersive Quest view instead of over this window. */
private var drawerXr by mutableStateOf(false)
private var drawerPinned by mutableStateOf(false)
private var drawerLayerOpen = false
private var drawerBackRequests by mutableIntStateOf(0)
@@ -563,9 +572,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
drawerPinned = false
if (value) {
releaseHeldKeys()
drawerDocked = dockDrawer() && openDockedMenu()
drawerXr = com.droiddeck.launcher.session.xr.XrPanels.showMenu()
drawerDocked = !drawerXr && dockDrawer() && openDockedMenu()
}
drawerOpenState = value
if (!value && drawerXr) {
drawerXr = false
com.droiddeck.launcher.session.xr.XrPanels.hideMenu()
}
if (!value && drawerDocked) closeDockedMenu()
}
private val dockedMenuIdle: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuIdleOnBottom(drawerOpen, drawerDocked, drawerPinned, dockedMenuController)
@@ -807,6 +821,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private var isHomeApp by mutableStateOf(false)
private var androidApps by mutableStateOf<List<HomeApp.LaunchableApp>>(emptyList())
private var padConnected by mutableStateOf(false)
private val deviceListener = object : InputManager.InputDeviceListener {
override fun onInputDeviceAdded(deviceId: Int) {
@@ -849,6 +864,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
com.droiddeck.launcher.session.xr.XrPanels.setMenuHost(this)
AgentGuest.readyListener = agentReadyListener
com.droiddeck.launcher.agent.AgentAttachments.gameFrame = gameFrame
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving() ||
@@ -987,7 +1003,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
root.addView(controls)
}
keyboard = KeyboardHost(this).also { host ->
keyboard = KeyboardHost(this, sendKeyEvent = ::dispatchImeKeyEvent, sendText = WaylandCompositor::textInputCommit).also { host ->
host.onImeChanged = ::onPrimaryImeChanged
root.addView(host)
}
@@ -1192,7 +1208,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val cursorHidden = cursorHiddenByUi()
androidx.compose.runtime.SideEffect {
com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity,
(drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && steamVrStatus != SteamVr.Status.RUNNING)
(drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && !drawerXr && steamVrStatus != SteamVr.Status.RUNNING)
}
androidx.compose.runtime.SideEffect { applyPlatformPointer(uiPointer) }
androidx.compose.runtime.DisposableEffect(Unit) {
@@ -1262,14 +1278,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
glasses.usesSpatialControllers(glassesSettings) && glassesSettings.joyConTracking)
joyConVr?.let { { it.recenter() } } else null,
) { headTracker?.recenter() }
if (!phonePanel && glasses.present && !drawerOpen && !pcKeyboardOpen && !loading.visible) com.droiddeck.launcher.ui.GlassesCornerButton(glassesSlot,
val showGlassesShortcut = com.droiddeck.launcher.ui.rememberShowGlassesShortcut()
if (!phonePanel && glasses.present && showGlassesShortcut && !drawerOpen && !pcKeyboardOpen && !loading.visible) com.droiddeck.launcher.ui.GlassesCornerButton(glassesSlot,
controllerSettings?.tint ?: android.graphics.Color.rgb(90, 160, 255), controllerSettings?.opacity ?: 100) {
drawerPage = com.droiddeck.launcher.ui.SessionDrawerPage.GLASSES
drawerPage = com.droiddeck.launcher.ui.SessionDrawerPage.VR
drawerOpen = true
}
if (!drawerOpen && !pcKeyboardOpen && !loading.visible) {
com.droiddeck.launcher.ui.DrawerEntryHint(SessionState.mode == SessionService.MODE_STEAM, backActionsInverted) { drawerOpen = true }
if (cornerTap) com.droiddeck.launcher.ui.DrawerCornerTap { drawerOpen = true }
if (com.droiddeck.launcher.session.QuestExperimental.isSupported())
com.droiddeck.launcher.ui.DrawerEdgeSwipe { onBackPressedDispatcher.onBackPressed() }
}
if (loading.visible) LoadingOverlay(
loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended,
@@ -1451,7 +1470,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
LaunchedEffect(drawerOpen, achievementsOpen, AgentGuest.focusRevision, StoreAchievements.revision) {
if (!drawerOpen && !achievementsOpen) return@LaunchedEffect
if (!drawerOpen && !achievementsOpen) {
achievementsInFront = null
return@LaunchedEffect
}
val found = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
runCatching { resolveAchievementsInFront() }
.onFailure { Log.w(TAG, "achievements in front: ${it.javaClass.simpleName}") }.getOrNull()
@@ -1470,11 +1492,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onAndroidKeyboard = { pcKeyboardOpen = false; togglePrimaryKeyboard() },
onClose = { pcKeyboardOpen = false },
)
if (!drawerDocked) SessionMenu(
if (!drawerDocked && !drawerXr) SessionMenu(
docked = false,
effectsEditorProfileId = effectsEditorProfileId,
effectsEditorTarget = effectsEditorTarget,
)
if (drawerOpen && !drawerDocked && !drawerXr && com.droiddeck.launcher.session.QuestExperimental.isSupported())
com.droiddeck.launcher.ui.DrawerEdgeSwipe { onBackPressedDispatcher.onBackPressed() }
LaunchedEffect(achievementsOpen) {
if (achievementsOpen) {
releasePads()
@@ -1523,6 +1547,74 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
@androidx.compose.runtime.Composable
override fun XrMenuContent() {
val activeEffectsProfileId = currentScreenEffectsProfileId()
val effectsEditorTarget = if (drawerOpen) screenEffectsTarget else null
val effectsEditorProfileId = activeEffectsProfileId.takeIf { effectsEditorTarget == SCREEN_EFFECTS_TARGET_AUTO }
androidx.compose.runtime.LaunchedEffect(effectsEditorTarget, effectsEditorProfileId) {
when (effectsEditorTarget) {
SCREEN_EFFECTS_TARGET_AUTO -> syncActiveScreenEffectsProfile()
null -> Unit
else -> syncScreenEffectsTarget(effectsEditorTarget)
}
}
SessionMenu(docked = true, effectsEditorProfileId = effectsEditorProfileId, effectsEditorTarget = effectsEditorTarget)
}
override fun xrSetMenuOpen(open: Boolean) {
if (open != drawerOpen) drawerOpen = open
}
/**
* In the immersive Quest view, Stop takes the user back to this window with the session still
* running, and Stop SteamVR leaves at once instead of after the stop is noticed.
*/
private fun leaveXrMenu() {
if (!drawerXr) return
drawerOpen = false
com.droiddeck.launcher.session.xr.XrPanels.leaveImmersive()
}
override fun xrMenuBack() {
if (drawerLayerOpen) drawerBackRequests++ else drawerOpen = false
}
override fun xrSendKey(code: Int, down: Boolean) {
if (CompositorHost.isStarted) sendGuestKey(code, down, 32)
}
override fun xrTypeText(text: String) = xrKeys.type(text)
override fun xrImmersiveChanged(active: Boolean) {
if (active) {
if (immersiveFlatSize == null) immersiveFlatSize = SessionState.outputSize
resizeOutputForWindow(surfaceW, surfaceH)
return
}
val flat = immersiveFlatSize
immersiveFlatSize = null
if (windowOutputSize(surfaceW, surfaceH) == null && flat != null) applyOutputSize(flat)
else resizeOutputForWindow(surfaceW, surfaceH)
}
/** The output's size when the immersive view opened; this window may have no surface while it is up. */
private var immersiveFlatSize: Pair<Int, Int>? = null
override fun xrTapKey(keyCode: Int) = xrKeys.tap(keyCode)
/** The VR keyboard's keys go straight to the game, past the menu and pad handling a real key passes through. */
private val xrKeys by lazy {
KeyboardHost(
this,
sendKeyEvent = { event ->
CompositorHost.isStarted && (event.action != KeyEvent.ACTION_DOWN || event.repeatCount == 0) &&
com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, 16) }
},
sendText = { text -> if (CompositorHost.isStarted) WaylandCompositor.textInputCommit(text) },
)
}
@androidx.compose.runtime.Composable
private fun SessionMenu(
docked: Boolean,
@@ -1787,7 +1879,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onBlackFrameInsertion = { on ->
SessionPrefs.setBlackFrameInsertion(this@SessionActivity, on)
blackFrameInsertion = on
CompositorHost.setBlackFrameInsertion(on, refreshHz(), outputFpsLimit())
CompositorHost.setBlackFrameInsertion(on, refreshHz(), compositorFpsLimit())
},
hdr = hdrWanted,
hdrAvailable = hdrAvailable,
@@ -1824,7 +1916,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onRumble = { on -> updateControllerPrefs { ControllerPrefs.setRumble(this@SessionActivity, on) } },
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
onAchievements = achievementsInFront?.let { { drawerOpen = false; achievementsOpen = true } },
controllerConnected = padConnected,
achievementsGame = achievementsInFront?.game,
achievementsTitle = achievementsInFront?.title,
achievementsProgress = achievementsInFront?.progress,
padType = if (SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad) padType else null,
onPadType = { id ->
@@ -1899,9 +1993,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionService.suspendPolicyChanged(this@SessionActivity)
},
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
onInputSettings = { releasePads(); drawerOpen = false; inputSettingsOpen = true },
onInputSettings = { leaveImmersiveForDialog(); releasePads(); drawerOpen = false; inputSettingsOpen = true },
onInputSelection = { releasePads(); refreshInputProfile() },
onGestureSettings = { drawerOpen = false; gestureSettingsOpen = true },
onGestureSettings = { leaveImmersiveForDialog(); drawerOpen = false; gestureSettingsOpen = true },
touchActive = drawerTouchMode(),
directHoldBehavior = directHoldBehavior,
onDirectHoldBehavior = { value ->
@@ -1945,7 +2039,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onResume = { SessionService.resume(this@SessionActivity) },
orientation = sessionOrientation,
onOrientation = { value ->
SessionPrefs.setOrientation(this@SessionActivity, value)
when (SessionState.mode) {
SessionService.MODE_STEAM, SessionService.MODE_RUN ->
SessionPrefs.setOrientation(this@SessionActivity, "steam", value)
SessionService.MODE_DESKTOP ->
SessionPrefs.setOrientation(this@SessionActivity, "desktop", value)
else -> SessionPrefs.setOrientation(this@SessionActivity, value)
}
sessionOrientation = value
applyFollowOrientation(resources.configuration)
},
@@ -1992,18 +2092,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController,
onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) },
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
onStop = {
if (drawerXr) leaveXrMenu() else {
drawerOpen = false
SessionService.stop(this@SessionActivity)
finish()
}
},
onStopFrom = { onScreen ->
drawerOpen = false
if (onScreen == null || com.droiddeck.launcher.ui.Motion.scale == 0f || quitFrom != null) {
if (quitFrom == null) { SessionService.stop(this@SessionActivity); finish() }
} else {
val at = IntArray(2).also { sessionOverlay.getLocationOnScreen(it) }
quitFrom = onScreen.translate(-at[0].toFloat(), -at[1].toFloat())
if (drawerXr) leaveXrMenu() else {
drawerOpen = false
if (onScreen == null || com.droiddeck.launcher.ui.Motion.scale == 0f || quitFrom != null) {
if (quitFrom == null) { SessionService.stop(this@SessionActivity); finish() }
} else {
val at = IntArray(2).also { sessionOverlay.getLocationOnScreen(it) }
quitFrom = onScreen.translate(-at[0].toFloat(), -at[1].toFloat())
}
}
},
onClose = { drawerOpen = false },
onDismissScreen = if (docked) ({ selectSecondScreenMode(SecondScreenMode.NONE) }) else null,
onDismissScreen = if (docked && !drawerXr) ({ selectSecondScreenMode(SecondScreenMode.NONE) }) else null,
components = drawerComponents,
onComponentsRefresh = {
refreshDrawerComponents()
@@ -2081,7 +2189,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}) else null,
onKeyboard = { togglePrimaryKeyboard() },
onSessionMenu = { drawerOpen = true },
onStopSteamVr = if (vr) ({ steamVrAction("stop") }) else null,
onStopSteamVr = if (vr) ({ leaveXrMenu(); steamVrAction("stop") }) else null,
brightness = glasses.brightness,
brightnessMax = glasses.brightnessMax,
onBrightness = if (glasses.canControl && glasses.hardwareControls) Glasses::setBrightness else null,
@@ -2120,6 +2228,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun togglePcKeyboard() {
drawerOpen = false
if (com.droiddeck.launcher.session.xr.XrPanels.toggleGameKeyboard(pc = true)) return
hidePrimaryKeyboard()
onScreenControls?.releaseAll()
bottomInputControls?.releaseAll()
@@ -2129,12 +2238,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun showPrimaryKeyboard() {
pendingFieldKeyboard = false
fieldKeyboardOnPrimary = false
if (com.droiddeck.launcher.session.xr.XrPanels.showGameKeyboard(pc = false)) return
keyboard?.show()
}
private fun togglePrimaryKeyboard() {
pendingFieldKeyboard = false
fieldKeyboardOnPrimary = false
if (com.droiddeck.launcher.session.xr.XrPanels.toggleGameKeyboard(pc = false)) return
keyboard?.toggle()
}
@@ -2724,7 +2835,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
oscTrackpads = SessionPrefs.oscTrackpads(this)
backHold = SessionPrefs.backHold(this)
dockedMenuController = SessionPrefs.dockedMenuController(this)
sessionOrientation = SessionPrefs.orientation(this)
sessionOrientation = SessionPrefs.orientation(this, SessionState.mode)
dualScreenSessionMode = SessionPrefs.dualScreenSessionMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
@@ -2990,7 +3101,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
CompositorHost.startOrAttach(
this, holder.surface, runtimeDir.path,
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), outputFpsLimit(),
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), compositorFpsLimit(),
)
onOutputAttached(holder)
if (SessionState.running && size != previous) {
@@ -3032,6 +3143,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun windowOutputSize(width: Int, height: Int): Pair<Int, Int>? {
if (com.droiddeck.launcher.session.xr.XrPanels.immersiveActive) {
val flat = immersiveFlatSize ?: SessionState.outputSize
return if (steamScreenShown()) vrOutputSize(flat) else flat
}
if (width <= 0 || height <= 0 || isInPictureInPictureMode) return null
if (bottomGame != null) return when {
SessionState.followScreen ->
@@ -3045,9 +3160,38 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
else if (glassesScreen == null) outputSize() else null
}
/** These editors draw in this window, which the immersive view hides, so they open after leaving it. */
private fun leaveImmersiveForDialog() {
if (com.droiddeck.launcher.session.xr.XrPanels.immersiveActive) com.droiddeck.launcher.session.xr.XrPanels.leaveImmersive()
}
/** Steam's own screen is up with no game holding a window; with no focus report, a game may be running. */
private fun steamScreenShown(): Boolean {
if (SessionState.mode != SessionService.MODE_STEAM) return false
val focus = com.droiddeck.launcher.agent.AgentGuest.focus(this) ?: return false
return com.droiddeck.launcher.session.xr.XrSteamScreen.shown(
focus.takeUnless { it.isNull("focusedApp") }?.optLong("focusedApp"),
focus.optJSONArray("focusableApps")?.let { list -> (0 until list.length()).map { list.optLong(it) } },
)
}
/**
* SteamVR shows Steam's own screen as its floating Steam window, so in the headset that screen is drawn
* tall enough for the window to stay sharp. A flat game keeps the flat size, so the output keeps it
* while one is running.
*/
private fun vrOutputSize(flat: Pair<Int, Int>): Pair<Int, Int> {
if (flat.second >= VR_OUTPUT_HEIGHT) return flat
val width = (flat.first.toLong() * VR_OUTPUT_HEIGHT / flat.second.coerceAtLeast(1)).toInt() and 1.inv()
return width to VR_OUTPUT_HEIGHT
}
private fun resizeOutputForWindow(width: Int, height: Int) {
applyOutputSize(windowOutputSize(width, height) ?: return)
}
private fun applyOutputSize(size: Pair<Int, Int>) {
if (!CompositorHost.isStarted) return
val size = windowOutputSize(width, height) ?: return
if (size == SessionState.outputSize) return
Log.i(TAG, "output resized: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}")
SessionState.outputSize = size
@@ -3056,7 +3200,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
WaylandCompositor.nativeResizeOutput(size.first, size.second)
}
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this)
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this, SessionState.mode)
private fun applyFollowChoice() {
val scale = SessionState.followScales.let { if (followPortrait()) it.second else it.first }
@@ -3065,7 +3209,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun applyFollowOrientation(config: android.content.res.Configuration) {
val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp)
val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp, SessionState.mode)
if (requestedOrientation != wanted) requestedOrientation = wanted
}
@@ -3128,13 +3272,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun displayMode(): String = SessionPrefs.displayMode(this,
intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, intent.getStringExtra(SessionService.EXTRA_PROGRAM))
private fun portraitOutput(): Boolean = SessionPrefs.portrait(this) && !controlsBelowWanted()
private fun portraitOutput(): Boolean = SessionPrefs.portrait(this, SessionState.mode) && !controlsBelowWanted()
private fun outputSize(): Pair<Int, Int> =
com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
resolutionChoice(), portraitOutput())
private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this)): String {
private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this, SessionState.mode)): String {
val mode = displayMode()
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
return if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
@@ -3181,6 +3325,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun outputFpsLimit(): Int = outputFpsLimit(pipUi)
// Android holds the window to the Game Mode override while the panel runs faster; the guest paces to the panel,
// so without this cap every frame past the override is drawn and dropped.
private fun hostFrameCap(): Int {
if (glassesScreen != null || bottomOutputActive) return 0
val display = (if (Build.VERSION.SDK_INT >= 30) display else @Suppress("DEPRECATION") windowManager.defaultDisplay) ?: return 0
return SessionPrefs.hostFrameCap(display.refreshRate, display.mode.refreshRate)
}
private fun compositorFpsLimit(): Int = SessionPrefs.compositorFpsLimit(
mirrorRefreshLimit(), if (noSteamSession()) SessionState.fpsLimit else 0, pipUi, hostFrameCap(),
)
private fun outputFpsLimit(pip: Boolean): Int =
SessionPrefs.compositorFpsLimit(mirrorRefreshLimit(), if (noSteamSession()) SessionState.fpsLimit else 0, pip)
@@ -3218,7 +3374,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
)
val hz = refreshHz()
val changed = kotlin.math.abs(SessionState.refreshHz - hz) > 0.1f
CompositorHost.updatePacing(hz, outputFpsLimit())
CompositorHost.updatePacing(hz, compositorFpsLimit())
pushCardboard(activeCardboard)
if (changed && ::surfaceView.isInitialized) applyFrameGen()
}
@@ -3655,16 +3811,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
internal fun dispatchImeKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event, orderedImeKey = true)
override fun dispatchKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event, orderedImeKey = false)
private fun dispatchKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean {
val normalized = com.droiddeck.launcher.input.GuestKeys.normalizeKeyboardEscape(event)
if (normalized === event) return dispatchSessionKeyEvent(event)
if (normalized === event) return dispatchSessionKeyEvent(event, orderedImeKey)
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
Log.i(TAG, "hardware Esc normalized from Back device=${event.deviceId} scan=${event.scanCode}")
}
return dispatchSessionKeyEvent(normalized)
return dispatchSessionKeyEvent(normalized, orderedImeKey)
}
private fun dispatchSessionKeyEvent(event: KeyEvent): Boolean {
private fun dispatchSessionKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean {
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
@@ -3747,7 +3907,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
return true
}
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
if (pad !== event) return dispatchKeyEvent(pad)
if (pad !== event) return dispatchKeyEvent(pad, orderedImeKey)
val fromController = PadBridge.isControllerKeyEvent(event)
if (fromController && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
padBridge?.setInputEnabled(false)
@@ -3789,7 +3949,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
// The bumpers walk the tabs on the strip; a page kept inside More counts as the More tab.
val pages = sessionDrawerPages(glasses.present)
val pages = sessionDrawerPages(achievementsInFront != null)
drawerPage = pages.strip().step(pages.tabFor(drawerPage), if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
releaseDrawerDirection()
}
@@ -3830,7 +3990,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val down = event.action == KeyEvent.ACTION_DOWN
if (down && event.repeatCount > 0) return true
val owner = if (event.deviceId <= 0) 16 else 8
if (com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, owner) }) return true
if (com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, owner, orderedImeKey) }) return true
}
return super.dispatchKeyEvent(event)
}
@@ -4945,6 +5105,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun refreshControls() {
padConnected = controllerConnected()
applyUnfoldedControls()
updateOnScreenControls()
}
@@ -5123,27 +5284,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else {
endGameField()
}
host.type(text)
host.tap(KeyEvent.KEYCODE_ENTER)
if (text.isEmpty()) host.tap(KeyEvent.KEYCODE_ENTER)
else WaylandCompositor.textInputCommitAndSubmit(text)
uiHandler.postDelayed({
if (AgentGuest.gameTextField && com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram)) endGameField()
}, FIELD_SETTLE_MS)
}
private fun endGameField() {
WaylandCompositor.nativeSendKey(KEY_END, 1)
WaylandCompositor.nativeSendKey(KEY_END, 0)
orderedImeKeySender(KEY_END, true)
orderedImeKeySender(KEY_END, false)
}
private fun selectGameField(vararg then: Int) {
heldKeys.set(256, KEY_LEFTCTRL, true)
try {
for (key in intArrayOf(KEY_A) + then) {
heldKeys.set(256, key, true)
heldKeys.set(256, key, false)
}
} finally { heldKeys.release(256) }
}
private fun selectGameField(copy: Boolean = false) { WaylandCompositor.nativeSelectGameField(copy) }
private fun readGameField(done: (String?) -> Unit) {
val opened = wowChat.request
@@ -5152,7 +5305,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (text != null && stillOpen()) endGameField()
done(text)
}
selectGameField(KEY_C)
selectGameField(copy = true)
}
private fun cancelWowChat() {
@@ -6055,11 +6208,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
releaseHeldKeys()
}
private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1) {
private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1, orderedImeKey: Boolean = false) {
if (down && pipUi) return
val code = if (key == KEY_RIGHTCTRL && SessionState.mode == SessionService.MODE_DESKTOP) KEY_LEFTCTRL else key
if (owner == 1) { if (down) guestKeysDown.add(code) else guestKeysDown.remove(code) }
heldKeys.set(owner, code, down)
val orderedSender = if (orderedImeKey) orderedImeKeySender else null
heldKeys.set(owner, code, down, orderedSender)
}
private val orderedImeKeySender: (Int, Boolean) -> Unit = { code, down ->
WaylandCompositor.nativeSendKeyOrdered(code, if (down) 1 else 0)
}
private fun capturePausedFrame(manual: Boolean = false, onDone: () -> Unit = {}) {
@@ -6127,7 +6285,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val back = {
if (restore.compareAndSet(false, true)) {
pauseCaptures--
if (!isDestroyed) WaylandCompositor.nativeSetZeroCopy(composedOutputFree())
if (!isDestroyed && zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy(composedOutputFree())
}
}
uiHandler.postDelayed({ capturePausedFrame(manual = true, onDone = back) }, ZERO_COPY_SETTLE_MS)
@@ -6242,6 +6400,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
heldButtons.clear()
hidePrimaryKeyboard()
sessionClipboard.stop()
sessionTextInput.stop()
padMotion?.stop()
cursorVisible = false
closeSecondScreen(reset = false)
@@ -6257,7 +6416,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else if (!isFinishing && !isDestroyed) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
updateOnScreenControls()
if (resumed) { sessionClipboard.start(); updatePadMotion() }
if (resumed) { sessionClipboard.start(); sessionTextInput.start(); updatePadMotion() }
if (started) {
settleDualScreenControls()
refreshSecondScreenDisplays()
@@ -6328,6 +6487,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener)
contentResolver.unregisterContentObserver(refreshSettingObserver)
if (!screenIsOff()) closeSecondScreen(reset = false)
sessionTextInput.stop()
startedScreens = (startedScreens - 1).coerceAtLeast(0)
updateGlassesScreen()
updateBottomGame()
@@ -6385,6 +6545,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
(getSystemService(INPUT_SERVICE) as? InputManager)
?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper()))
padConnected = controllerConnected()
padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this))
refreshSecondScreenDisplays()
if (SessionState.guestPid > 1) padBridge?.syncConnectedControllers()
@@ -6406,7 +6567,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onCancel = { padBridge?.cancelHomeGuide() },
)
updatePointerCapture()
if (!pipUi) sessionClipboard.start()
if (!pipUi) { sessionClipboard.start(); sessionTextInput.start() }
updatePadMotion()
ControllerPrefs.prefs(this).registerOnSharedPreferenceChangeListener(shortcutPrefListener)
SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(screenEffectsProfilePrefListener)
@@ -7123,6 +7284,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
override fun onDestroy() {
com.droiddeck.launcher.session.xr.XrPanels.clearMenuHost(this)
if (drawerXr) com.droiddeck.launcher.session.xr.XrPanels.hideMenu()
uiHandler.removeCallbacks(panelHeldCheck)
uiHandler.removeCallbacks(panelHeldRetry)
synchronized(frameGenGlobalLock) {
@@ -7135,6 +7298,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
gamescopeConvarRequests.shutdownNow()
backQamInput.cancel()
steamVrRecovery.close()
sessionTextInput.stop()
uiHandler.removeCallbacks(steamTouchRetry)
uiHandler.removeCallbacks(cursorResync)
uiHandler.removeCallbacks(usbMouseFallback)
@@ -7247,6 +7411,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
const val EXTRA_RETURN_HOME = "returnHome"
private const val BLUETOOTH_CONNECT = "android.permission.BLUETOOTH_CONNECT"
private const val REQUEST_BLUETOOTH = 31
private const val VR_OUTPUT_HEIGHT = 1080
const val EXTRA_LINK_TASK = "linkTask"
const val EXTRA_STEAMVR = "steamVr"
const val EXTRA_PLAYED_GAME = "com.droiddeck.launcher.PLAYED_GAME"
@@ -0,0 +1,48 @@
package com.droiddeck.launcher.agent
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.core.AppUiPrefs
import com.droiddeck.launcher.ui.AgentPage
import com.droiddeck.launcher.ui.DroidDeckTheme
/**
* The agent's chat in a window of its own, for Quest's flat mode: opened in its own task, it is a
* separate Horizon panel the user can move, resize and close like any other.
*/
class AgentChatActivity : ComponentActivity() {
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(newBase)
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DroidDeckTheme(appScale = AppUiPrefs.scale(this)) {
AgentPage(
Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).padding(horizontal = 12.dp, vertical = 6.dp),
visible = true, startTyping = AgentHost.entries.isEmpty(),
)
}
}
}
companion object {
fun open(context: Context) {
context.startActivity(
Intent(context, AgentChatActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT),
)
}
}
}
@@ -19,7 +19,7 @@ import java.util.UUID
object AgentGuest {
private val main by lazy { Handler(Looper.getMainLooper()) }
var focusRevision by mutableIntStateOf(0)
private set
@androidx.annotation.VisibleForTesting internal set
var steamKeyboard by mutableStateOf(false)
private set
var desktopTextField by mutableStateOf(false)
@@ -89,7 +89,7 @@ public class DirectAudioRelayComponent extends SessionPart {
}
}
final java.io.PrintWriter log = out;
pid = HostProcess.start(command.toString(), env.toArray(new String[0]),
pid = HostProcess.startUncounted(command.toString(), env.toArray(new String[0]),
app().getFilesDir(), null,
line -> {
Log.i(TAG, line);
@@ -12,6 +12,7 @@ import com.droiddeck.launcher.core.TarZst;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
@@ -36,9 +37,15 @@ public class PulseAudioComponent extends SessionPart {
private final HostLifecycle host = new HostLifecycle(Process::killProcess);
static final class HostLifecycle {
static final int MAX_STARTUP_CRASH_RESTARTS = 4;
private static final long[] STARTUP_RESTART_DELAYS_MS = {250L, 1000L, 2000L, 4000L};
volatile int pid = -1;
private long generation;
private long launches;
private boolean preferStandardPerformanceMode;
private boolean sinkReady;
private int startupCrashRestarts;
private final IntConsumer terminate;
final ReentrantReadWriteLock commands = new ReentrantReadWriteLock();
@@ -48,6 +55,9 @@ public class PulseAudioComponent extends SessionPart {
synchronized long begin() {
stop();
preferStandardPerformanceMode = false;
sinkReady = false;
startupCrashRestarts = 0;
return generation;
}
@@ -55,6 +65,7 @@ public class PulseAudioComponent extends SessionPart {
generation++;
if (pid > 1) terminate.accept(pid);
pid = -1;
sinkReady = false;
}
boolean launch(long expected, IntSupplier launch) {
@@ -63,6 +74,7 @@ public class PulseAudioComponent extends SessionPart {
synchronized (this) {
if (expected != generation) return false;
launches++;
sinkReady = false;
pid = launch.getAsInt();
return true;
}
@@ -93,11 +105,45 @@ public class PulseAudioComponent extends SessionPart {
return token == launches && pid > 1;
}
synchronized boolean preferStandardPerformanceMode() {
return preferStandardPerformanceMode;
}
synchronized void markLowLatencyFailed(long token) {
if (token == launches && pid > 1) preferStandardPerformanceMode = true;
}
synchronized void markSinkReady(long token) {
if (token == launches && pid > 1) {
sinkReady = true;
startupCrashRestarts = 0;
}
}
synchronized boolean exited(long expected) {
if (expected != generation || pid <= 1) return false;
pid = -1;
return true;
}
/**
* Decides whether a dead host should be restarted and after how many milliseconds.
* Returns 0 for immediate recovery of a host that had a working sink, a positive backoff
* while falling back to standard AAudio mode after a startup crash, or -1 to stop retrying.
*/
synchronized long nextRestartDelayMs(long expected) {
if (expected != generation) return -1L;
if (sinkReady) {
sinkReady = false;
startupCrashRestarts = 0;
return 0L;
}
preferStandardPerformanceMode = true;
if (startupCrashRestarts >= MAX_STARTUP_CRASH_RESTARTS) return -1L;
long delay = STARTUP_RESTART_DELAYS_MS[Math.min(startupCrashRestarts, STARTUP_RESTART_DELAYS_MS.length - 1)];
startupCrashRestarts++;
return delay;
}
}
public PulseAudioComponent(Context context) {
@@ -167,11 +213,14 @@ public class PulseAudioComponent extends SessionPart {
if (micFifoPath != null && !micFifoPath.isEmpty()) {
new File(micFifoPath).delete();
}
boolean standardMode = host.preferStandardPerformanceMode();
String initialPerformanceMode = standardMode ? "0" : "1";
ArrayList<String> config = new ArrayList<>();
config.add("load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0 socket=\""
+ socket().getAbsolutePath() + "\"");
config.add(".nofail");
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls);
config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode="
+ initialPerformanceMode + " adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls);
config.add("set-default-sink DirectAudio");
config.add(".fail");
if (micFifoPath != null && !micFifoPath.isEmpty()) {
@@ -186,15 +235,36 @@ public class PulseAudioComponent extends SessionPart {
env.add("LD_LIBRARY_PATH=/system/lib64:" + modules + ":" + workingDir.getAbsolutePath());
env.add("HOME=" + workingDir);
env.add("TMPDIR=" + workingDir);
// The daemon closes every fd at start but this one; in a worker process it is the binder
// fd whose closing Android takes for the process's death.
env.add("PULSE_PASSED_FD=" + com.droiddeck.launcher.runtime.GuestWorker.BINDER_FD_TOKEN);
String command = String.join(" ", HostProcess.dataExecutable(workingDir.getAbsolutePath() + "/libpulseaudio.so"))
+ " --system=false --disable-shm=true --fail=false"
+ " -n --file=default.pa --daemonize=false --use-pid-file=false --exit-idle-time=-1"
+ " --log-level=info";
final java.io.PrintWriter out = openLog();
if (!host.launch(generation, () -> HostProcess.start(command, env.toArray(new String[0]), workingDir, status -> {
if (!host.launch(generation, () -> HostProcess.startUncounted(command, env.toArray(new String[0]), workingDir, status -> {
if (host.exited(generation)) {
Log.w(TAG, "audio host exited with status " + status + "; restarting");
long delayMs = host.nextRestartDelayMs(generation);
if (delayMs < 0) {
String msg = "audio host exited with status " + status
+ " before a client sink came up too many times; not restarting again in this session";
Log.w(TAG, msg);
note(out, msg);
return;
}
Log.w(TAG, "audio host exited with status " + status + "; restarting"
+ (host.preferStandardPerformanceMode() ? " with standard AAudio mode" : "")
+ (delayMs > 0 ? " in " + delayMs + " ms" : ""));
if (delayMs > 0) {
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
start(generation);
}
},
@@ -208,6 +278,24 @@ public class PulseAudioComponent extends SessionPart {
guard.start();
}
private boolean loadDirectAudioSink(long token, String performanceMode) {
if ("0".equals(performanceMode)) pactlOk(token, "unload-module", "module-directaudio-native-sink");
String loaded = pactlFor(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio",
"performance_mode=" + performanceMode,
"adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls);
if (loaded == null) return false;
if (pactlOk(token, "set-default-sink", "DirectAudio")) return true;
String moduleId = loaded.trim();
pactlOk(token, "unload-module", moduleId.matches("\\d+") ? moduleId : "module-directaudio-native-sink");
return false;
}
private boolean loadPlainAAudioSink(long token, String performanceMode) {
return pactlOk(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink",
"performance_mode=" + performanceMode, "adaptive=1", "volume=1.0", "control_dir=" + deviceControls)
&& pactlOk(token, "set-default-sink", "AAudioSink");
}
private void ensureClientSink(java.io.PrintWriter out, long token) {
try {
// Nothing that may block (a sink whose AAudio open hangs: a Galaxy S24 FE (US) hung the
@@ -229,27 +317,42 @@ public class PulseAudioComponent extends SessionPart {
if (sinks == null) {
line = "== client sink: the daemon did not answer in 30 s; no fallback attempted";
} else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
line = "== client sink: DirectAudio (module-directaudio-native-sink)";
host.markSinkReady(token);
line = "== client sink: DirectAudio (module-directaudio-native-sink"
+ (host.preferStandardPerformanceMode() ? ", standard mode" : "") + ")";
} else {
// AAudio can refuse the first open with AAUDIO_ERROR_DISCONNECTED while Android is
// still switching the output route as the session starts (seen on a Galaxy S24 FE):
// try DirectAudio again, then the plain sink, a few times over ten seconds.
// still switching the output route (Galaxy S24 FE) or when low-latency MMAP output
// is rejected by the HAL (Samsung One UI). Retry low-latency once if it hasn't been
// disqualified yet, then fall back to performance_mode=0 (non-MMAP) on DirectAudio
// before trying the plain AAudio sink.
String loadedAs = null;
for (int attempt = 1; attempt <= 5 && loadedAs == null && host.live(token); attempt++) {
try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
if (pactlOk(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1",
"adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls)
&& pactlOk(token, "set-default-sink", "DirectAudio")) {
loadedAs = "DirectAudio on attempt " + attempt;
} else if (pactlOk(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink",
"performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls)
&& pactlOk(token, "set-default-sink", "AAudioSink")) {
loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt;
if (!host.live(token)) break;
if (attempt == 1 && !host.preferStandardPerformanceMode()) {
if (loadDirectAudioSink(token, "1")) {
loadedAs = "DirectAudio on attempt " + attempt;
break;
}
if (!host.live(token)) break;
host.markLowLatencyFailed(token);
}
if (loadDirectAudioSink(token, "0")) {
loadedAs = "DirectAudio (standard mode) on attempt " + attempt;
} else if (host.live(token) && loadPlainAAudioSink(token, "0")) {
loadedAs = "the plain AAudio sink (AAudioSink, standard mode) on attempt " + attempt;
}
}
line = loadedAs != null ? "== client sink: DirectAudio did not come up at start; retried and got " + loadedAs
: "== client sink: DirectAudio did not come up and the AAudio fallback failed too after 5 retries - no client sound."
+ " If audio.log shows AAUDIO_ERROR_DISCONNECTED, Android refused the audio output: rebooting the phone usually fixes this";
if (loadedAs != null) {
host.markSinkReady(token);
line = "== client sink: DirectAudio did not come up at start; retried and got " + loadedAs;
} else if (!host.live(token)) {
line = "== client sink: audio host exited during sink recovery";
} else {
line = "== client sink: DirectAudio did not come up and the AAudio fallback failed too after 5 retries - no client sound."
+ " If audio.log shows AAUDIO_ERROR_DISCONNECTED, Android refused the audio output: rebooting the phone usually fixes this";
}
Log.w(TAG, line);
}
Log.i(TAG, line);
@@ -404,11 +507,22 @@ public class PulseAudioComponent extends SessionPart {
continue;
}
File destination = new File(workingDir, lib);
File temp = null;
try (InputStream in = resource.openStream()) {
Files.copy(in, destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
FileUtils.chmod(destination, 0771);
temp = File.createTempFile(lib + ".", ".tmp", workingDir);
Files.copy(in, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
FileUtils.chmod(temp, 0771);
try {
Files.move(temp.toPath(), destination.toPath(),
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException e) {
Files.move(temp.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
temp = null;
} catch (Exception e) {
Log.w(TAG, "copy " + lib, e);
} finally {
if (temp != null) temp.delete();
}
}
}
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.core
import android.os.ParcelFileDescriptor
import android.util.Log
import java.io.File
import java.util.function.Consumer
@@ -7,6 +8,9 @@ import java.util.function.Consumer
object HostProcess {
private const val TAG = "HostProcess"
private const val LINKER = "/system/bin/linker64"
// sh -c WORKER_CD sh DIR NAME=VALUE... -- PROGRAM ARGS...
private const val WORKER_CD = "cd \"\$1\" || exit 126; shift; " +
"while [ \$# -gt 0 ] && [ \"\$1\" != -- ]; do export \"\$1\"; shift; done; shift; exec \"\$@\""
/** Android 10+ refuses to execute app data files for targetSdk 29+; its linker still loads them. */
@JvmStatic
@@ -65,6 +69,77 @@ object HostProcess {
}
}
/**
* As [start], but the program runs as the main process of one of the app's worker processes,
* which Android does not count against the app's child processes (docs/phantom-processes.md).
* Falls back to [start] when no worker is available. The exit status is the program's exit
* code, or 128 plus the signal that ended it, as Process.waitFor() reports it.
*/
@JvmStatic
@JvmOverloads
fun startUncounted(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?,
outputFile: File? = null, onOutputComplete: Runnable? = null): Int {
val context = com.droiddeck.launcher.runtime.GuestWorkers.context
val argv = split(command)
// A missing working directory fails the launch (start() returns -1 for it), not the program
if (context == null || argv.isEmpty() || !com.droiddeck.launcher.runtime.GuestWorkers.enabled(context) ||
(dir != null && !dir.isDirectory)) {
return start(command, env, dir, onExit, onLine, outputFile, onOutputComplete)
}
val environment = LinkedHashMap(System.getenv())
env?.forEach { line ->
val eq = line.indexOf('=')
if (eq > 0) environment[line.substring(0, eq)] = line.substring(eq + 1)
}
val assignments = environment.map { (k, v) -> "$k=$v" }
// A worker cannot chdir before its exec, so Android's shell does it. The shell starts with an
// environment of its own (the program's LD_PRELOAD of glibc libraries would stop it loading)
// and exports the program's before the exec.
val launch = if (dir != null) {
listOf("/system/bin/sh", "-c", WORKER_CD, "sh", dir.path) + assignments + listOf("--") + argv
} else argv
val workerEnv = if (dir != null) listOf("PATH=/system/bin") else assignments
var input: ParcelFileDescriptor? = null
var reader: ParcelFileDescriptor? = null
var output: ParcelFileDescriptor? = null
val pid = try {
input = ParcelFileDescriptor.open(File("/dev/null"), ParcelFileDescriptor.MODE_READ_ONLY)
output = when {
onLine != null -> ParcelFileDescriptor.createPipe().let { reader = it[0]; it[1] }
outputFile != null -> ParcelFileDescriptor.open(outputFile,
ParcelFileDescriptor.MODE_WRITE_ONLY or ParcelFileDescriptor.MODE_CREATE or ParcelFileDescriptor.MODE_APPEND)
else -> ParcelFileDescriptor.open(File("/dev/null"), ParcelFileDescriptor.MODE_WRITE_ONLY)
}
com.droiddeck.launcher.runtime.GuestWorkers.start(context, launch, workerEnv, listOf(input, output, output)) { status ->
onExit?.accept(if (status < 0) -1 else if (status and 0x7f == 0) (status shr 8) and 0xff else 128 + (status and 0x7f))
}
} catch (e: Exception) {
Log.w(TAG, "no worker for ${argv.first()}", e)
-1
} finally {
runCatching { input?.close() }
runCatching { output?.close() }
}
if (pid <= 0) {
reader?.close()
return start(command, env, dir, onExit, onLine, outputFile, onOutputComplete)
}
Log.i(TAG, "started pid $pid outside the child-process count: ${argv.first()} (${argv.size - 1} arguments)")
reader?.let { pipe ->
Thread({
try {
ParcelFileDescriptor.AutoCloseInputStream(pipe).bufferedReader().useLines { lines ->
lines.forEach { onLine?.accept(it) }
}
} catch (e: Exception) {
} finally {
onOutputComplete?.run()
}
}, "proc-out-$pid").apply { priority = Thread.NORM_PRIORITY - 1; isDaemon = true; start() }
}
return pid
}
@JvmStatic
fun pidOf(process: Process): Int = try {
val field = process.javaClass.getDeclaredField("pid")
@@ -7,6 +7,8 @@ import com.droiddeck.launcher.R
enum class PhantomProcessStatus {
NOT_APPLICABLE,
/** The limit is on, but the session keeps its programs out of Android's count (GuestWorkers). */
UNCOUNTED,
DISABLED,
ENABLED,
UNSET,
@@ -57,6 +59,12 @@ object PhantomProcessLimit {
fun read(context: Context, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus {
if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE
val status = readSetting(context, sdk)
return if (status != PhantomProcessStatus.DISABLED && com.droiddeck.launcher.runtime.GuestWorkers.limitHandled(context))
PhantomProcessStatus.UNCOUNTED else status
}
private fun readSetting(context: Context, sdk: Int): PhantomProcessStatus {
if (usesDeviceConfig(sdk)) {
val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false)
val global = try {
@@ -101,7 +109,8 @@ object PhantomProcessLimit {
fun hasDeveloperToggle(sdk: Int = Build.VERSION.SDK_INT): Boolean = sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
fun blocksSteam(status: PhantomProcessStatus): Boolean =
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED &&
status != PhantomProcessStatus.UNCOUNTED
fun title(context: Context, status: PhantomProcessStatus): String = context.getString(when (status) {
PhantomProcessStatus.ENABLED -> R.string.phantom_title_on
@@ -109,6 +118,7 @@ object PhantomProcessLimit {
PhantomProcessStatus.UNREADABLE -> R.string.phantom_title_unreadable
PhantomProcessStatus.DISABLED -> R.string.phantom_title_off
PhantomProcessStatus.NOT_APPLICABLE -> R.string.phantom_title_not_required
PhantomProcessStatus.UNCOUNTED -> R.string.phantom_title_uncounted
})
fun instructions(context: Context, status: PhantomProcessStatus): String = when (status) {
@@ -116,6 +126,7 @@ object PhantomProcessLimit {
context.getString(R.string.phantom_instructions_fix, fixSentence(context))
PhantomProcessStatus.DISABLED -> context.getString(R.string.phantom_instructions_off)
PhantomProcessStatus.NOT_APPLICABLE -> context.getString(R.string.phantom_instructions_not_applicable)
PhantomProcessStatus.UNCOUNTED -> context.getString(R.string.phantom_instructions_uncounted)
}
fun gateInstructions(context: Context, status: PhantomProcessStatus): String = when (status) {
@@ -132,5 +143,6 @@ object PhantomProcessLimit {
PhantomProcessStatus.UNSET -> "not set (ROM default applies; DroidDeck requires an explicit disabled value)"
PhantomProcessStatus.UNREADABLE -> "unreadable (DroidDeck could not verify the setting)"
PhantomProcessStatus.NOT_APPLICABLE -> "not applicable before Android 12"
PhantomProcessStatus.UNCOUNTED -> "on, not needed (most of the session's programs run in uncounted worker processes)"
}
}
@@ -28,17 +28,18 @@ object SessionLogCapture {
out.flush()
writer = out
this.target = target
pid = HostProcess.start(
pid = HostProcess.startUncounted(
command(Process.myPid(), sinceMillis),
null, target.parentFile, null,
) { line ->
synchronized(this) {
try {
writer?.apply { write(line); newLine(); flush() }
} catch (e: Exception) {
onLine = { line ->
synchronized(this) {
try {
writer?.apply { write(line); newLine(); flush() }
} catch (e: Exception) {
}
}
}
}
},
)
if (pid == -1) {
out.write("logcat could not be started; this ROM may not hand an app its own entries.\n")
out.flush()
@@ -2,14 +2,24 @@ package com.droiddeck.launcher.input
class HeldInput(private val emit: (Int, Boolean) -> Unit) {
private val owners = IntArray(768)
private val ordered = arrayOfNulls<(Int, Boolean) -> Unit>(768)
@Synchronized
fun set(source: Int, code: Int, down: Boolean) {
fun set(source: Int, code: Int, down: Boolean, orderedEmit: ((Int, Boolean) -> Unit)? = null) {
if (code !in owners.indices) return
val before = owners[code]
val after = if (down) before or source else before and source.inv()
owners[code] = after
if ((before == 0) != (after == 0)) emit(code, after != 0)
if ((before == 0) != (after == 0)) {
if (after != 0) {
ordered[code] = orderedEmit
orderedEmit?.invoke(code, true) ?: emit(code, true)
} else {
val fn = ordered[code]
ordered[code] = null
fn?.invoke(code, false) ?: emit(code, false)
}
}
}
@Synchronized
@@ -21,7 +31,9 @@ class HeldInput(private val emit: (Int, Boolean) -> Unit) {
fun clear() {
for (code in owners.indices) if (owners[code] != 0) {
owners[code] = 0
emit(code, false)
val fn = ordered[code]
ordered[code] = null
fn?.invoke(code, false) ?: emit(code, false)
}
}
}
@@ -4,7 +4,6 @@ import android.app.Activity
import android.content.Context
import android.os.Build
import android.text.InputType
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.View
import android.view.WindowInsets
@@ -12,15 +11,17 @@ import android.view.inputmethod.BaseInputConnection
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputMethodManager
import com.droiddeck.launcher.wayland.WaylandCompositor
class KeyboardHost(
context: Context,
private val sendKeyEvent: (KeyEvent) -> Boolean,
private val sendText: (String) -> Unit,
) : View(context) {
constructor(activity: Activity) : this(activity, { activity.dispatchKeyEvent(it) })
constructor(activity: Activity) :
this(activity, { activity.dispatchKeyEvent(it) }, { WaylandCompositor.textInputCommit(it) })
private val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
private val map: KeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)
var shown = false
private set
var imeShowing = false
@@ -40,8 +41,7 @@ class KeyboardHost(
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
if (!shown) return null
outAttrs.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
outAttrs.inputType = InputType.TYPE_CLASS_TEXT
outAttrs.imeOptions = EditorInfo.IME_ACTION_NONE or EditorInfo.IME_FLAG_NO_FULLSCREEN or
EditorInfo.IME_FLAG_NO_EXTRACT_UI
return KeyConnection()
@@ -93,45 +93,153 @@ class KeyboardHost(
fun type(text: CharSequence?) {
if (text.isNullOrEmpty()) return
val events = map.getEvents(text.toString().toCharArray())
if (events != null) {
for (event in events) sendKeyEvent(event)
} else {
for (ch in text) {
val t = System.currentTimeMillis()
val down = KeyEvent(t, t, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_UNKNOWN, 0, 0,
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, 0)
sendKeyEvent(CharKeyEvent(down, ch))
sendKeyEvent(CharKeyEvent(KeyEvent.changeAction(down, KeyEvent.ACTION_UP), ch))
}
}
// Text and soft editing actions share this queue to preserve IME ordering.
sendText(text.toString())
}
fun tap(keyCode: Int) {
val control = softControl(keyCode)
if (control != null) {
sendText(control.toString())
return
}
val t = System.currentTimeMillis()
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_DOWN, keyCode, 0))
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_UP, keyCode, 0))
}
private inner class KeyConnection : BaseInputConnection(this, false) {
// A press keeps the route chosen on its first down across repeats and the matching up.
private val controlRoutes = HashMap<Int, Boolean>()
private var composingText = ""
private var composingCursor = 0
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
composingText = ""
composingCursor = 0
type(text)
return true
}
override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean = true
override fun finishComposingText(): Boolean = true
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
repeat(beforeLength) { tap(KeyEvent.KEYCODE_DEL) }
repeat(afterLength) { tap(KeyEvent.KEYCODE_FORWARD_DEL) }
override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean {
composingText = text?.toString().orEmpty()
val rawCursor = if (newCursorPosition > 0) {
composingText.length.toLong() + newCursorPosition - 1L
} else {
newCursorPosition.toLong()
}
composingCursor = rawCursor.coerceIn(0L, composingText.length.toLong()).toInt()
return true
}
override fun sendKeyEvent(event: KeyEvent): Boolean = this@KeyboardHost.sendKeyEvent(event)
override fun finishComposingText(): Boolean {
val text = composingText
composingText = ""
composingCursor = 0
type(text)
return true
}
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
val before = beforeLength.coerceAtLeast(0)
val after = afterLength.coerceAtLeast(0)
if (before == 0 && after == 0) return true
val consumedBefore = minOf(before, composingCursor)
val consumedAfter = minOf(after, composingText.length - composingCursor)
val guestBefore = before - consumedBefore
val guestAfter = after - consumedAfter
if (guestBefore > 1 || guestAfter > 1) return false
return applyDeletion(
composingCursor - consumedBefore,
composingCursor + consumedAfter,
guestBefore,
guestAfter,
)
}
override fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int): Boolean {
val before = beforeLength.coerceAtLeast(0)
val after = afterLength.coerceAtLeast(0)
if (before == 0 && after == 0) return true
if (splitsPair(composingCursor)) return false
val text = composingText
val beforePoints = Character.codePointCount(text, 0, composingCursor)
val afterPoints = Character.codePointCount(text, composingCursor, text.length)
val consumedBefore = minOf(before, beforePoints)
val consumedAfter = minOf(after, afterPoints)
val start = Character.offsetByCodePoints(text, composingCursor, -consumedBefore)
val end = Character.offsetByCodePoints(text, composingCursor, consumedAfter)
if (hasUnpairedSurrogate(text, start, end)) return false
return applyDeletion(
start,
end,
before - consumedBefore,
after - consumedAfter,
)
}
private fun applyDeletion(start: Int, end: Int, guestBefore: Int, guestAfter: Int): Boolean {
if (guestBefore > 64 || guestAfter > 64) return false
if (splitsPair(start) || splitsPair(end)) return false
if (start < end) {
composingText = composingText.removeRange(start, end)
composingCursor = start
}
val controls = StringBuilder()
repeat(guestBefore) { controls.append(BACKSPACE) }
repeat(guestAfter) { controls.append(FORWARD_DELETE) }
if (controls.isNotEmpty()) sendText(controls.toString())
return true
}
private fun splitsPair(index: Int): Boolean =
index > 0 && index < composingText.length &&
composingText[index - 1].isHighSurrogate() && composingText[index].isLowSurrogate()
private fun hasUnpairedSurrogate(text: CharSequence, start: Int, end: Int): Boolean {
var i = start
while (i < end) {
val c = text[i]
if (c.isHighSurrogate()) {
if (i + 1 >= end || !text[i + 1].isLowSurrogate()) return true
i += 2
} else if (c.isLowSurrogate()) {
return true
} else {
i++
}
}
return false
}
override fun sendKeyEvent(event: KeyEvent): Boolean {
val control = softControl(event.keyCode)
if (control == null) return this@KeyboardHost.sendKeyEvent(event)
if (event.action == KeyEvent.ACTION_DOWN) {
val soft = if (event.repeatCount == 0) {
val route = !event.isModified()
controlRoutes[event.keyCode] = route
route
} else {
controlRoutes[event.keyCode] ?: !event.isModified()
}
if (!soft) return this@KeyboardHost.sendKeyEvent(event)
if (control == ENTER) finishComposingText()
sendText(control.toString())
return true
}
if (event.action == KeyEvent.ACTION_UP) {
val soft = controlRoutes.remove(event.keyCode) ?: !event.isModified()
if (soft) return true
return this@KeyboardHost.sendKeyEvent(event)
}
return this@KeyboardHost.sendKeyEvent(event)
}
override fun performEditorAction(actionCode: Int): Boolean {
tap(KeyEvent.KEYCODE_ENTER)
finishComposingText()
sendText(ENTER.toString())
return true
}
@@ -140,8 +248,22 @@ class KeyboardHost(
override fun getSelectedText(flags: Int): CharSequence? = null
}
private class CharKeyEvent(origin: KeyEvent, private val ch: Char) : KeyEvent(origin) {
override fun getUnicodeChar(): Int = ch.code
override fun getUnicodeChar(metaState: Int): Int = ch.code
private fun softControl(keyCode: Int): Char? = when (keyCode) {
KeyEvent.KEYCODE_DEL -> BACKSPACE
KeyEvent.KEYCODE_FORWARD_DEL -> FORWARD_DELETE
KeyEvent.KEYCODE_ENTER -> ENTER
KeyEvent.KEYCODE_TAB -> TAB
else -> null
}
private fun KeyEvent.isModified(): Boolean =
isCtrlPressed || isShiftPressed || isAltPressed || isMetaPressed
private companion object {
// Control characters represent editing keys on the guest text channel.
const val ENTER = '\r'
const val BACKSPACE = '\b'
const val FORWARD_DELETE = '\u007f'
const val TAB = '\t'
}
}
@@ -0,0 +1,327 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.net.LocalSocket
import android.net.LocalSocketAddress
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.io.IOException
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.TimeUnit
private enum class TextDelivery(val result: Int) {
NOT_DELIVERED(WaylandCompositor.TEXT_NOT_DELIVERED),
DELIVERED(WaylandCompositor.TEXT_DELIVERED),
UNRESOLVED(WaylandCompositor.TEXT_UNRESOLVED),
}
class SessionTextInput(context: Context, private val hasFocus: () -> Boolean) {
private val delivery = deliveryFor(context)
private val owner = Any()
fun start() = delivery.start(owner, hasFocus)
fun stop() = delivery.stop(owner)
private companion object {
private var instance: SessionTextDelivery? = null
@Synchronized private fun deliveryFor(context: Context): SessionTextDelivery =
instance ?: SessionTextDelivery(context.applicationContext).also { instance = it }
}
}
private class SessionTextDelivery(private val appContext: Context) {
private val handler = Handler(Looper.getMainLooper())
private val lock = Any()
private var generation = 0L
@Volatile private var active = false
private var owner: Any? = null
private var focusCheck: (() -> Boolean)? = null
private var executor: ScheduledThreadPoolExecutor? = null
private var socket: LocalSocket? = null
private var pendingToken = 0
private var runningToken = 0
private var failedToken = 0
private val guestListener = object : WaylandCompositor.TextInputFallbackListener {
override fun onTextInputFallback(text: String, token: Int): Boolean {
synchronized(lock) {
if (!active || pendingToken != 0 || failedToken != 0 || token <= 0) return false
val received = generation
pendingToken = token
val posted = try {
handler.post { enqueue(text, received, token) }
} catch (e: RuntimeException) {
false
}
if (!posted) pendingToken = 0
return posted
}
}
}
fun start(nextOwner: Any, hasFocus: () -> Boolean) {
val previous = synchronized(lock) {
if (owner === nextOwner) return
owner
}
if (previous != null) stop(previous)
val queue = ScheduledThreadPoolExecutor(1) { runnable ->
Thread(runnable, "session-text-input").apply { isDaemon = true }
}
queue.executeExistingDelayedTasksAfterShutdownPolicy = false
synchronized(lock) {
this.owner = nextOwner
focusCheck = hasFocus
active = true
executor = queue
if (failedToken != 0) scheduleRetryLocked(failedToken, INITIAL_DELAY_MS)
}
WaylandCompositor.setTextInputFallbackListener(guestListener)
}
fun stop(oldOwner: Any) {
val detached = synchronized(lock) {
if (owner !== oldOwner) return
owner = null
focusCheck = null
active = false
generation += 1
val queue = executor
val open = socket
val token = if (runningToken == 0 && failedToken == 0) pendingToken else 0
executor = null
socket = null
Triple(queue, open, token)
}
WaylandCompositor.clearTextInputFallbackListener(guestListener)
handler.removeCallbacksAndMessages(null)
detached.second?.let { requestCancel(it) }
detached.first?.shutdown()
if (detached.third != 0) complete(detached.third)
}
private fun enqueue(text: String, received: Long, token: Int) {
val currentFocus = synchronized(lock) { if (active && generation == received) focusCheck else null }
if (currentFocus == null || !currentFocus() || !WaylandCompositor.isTextInputFallbackListener(guestListener)) {
Log.d(TAG, "guest text fallback skipped outside the active focused session")
complete(token)
return
}
val bytes = text.toByteArray(Charsets.UTF_8)
if (bytes.isEmpty() || bytes.size > MAX_BYTES) {
complete(token)
return
}
val queue = synchronized(lock) {
if (active && generation == received) executor else null
}
if (queue == null) {
complete(token)
return
}
try {
queue.execute {
try {
val delivery = send(bytes, received, token)
if (delivery == TextDelivery.UNRESOLVED) recover(token)
else complete(token, delivery)
} finally {
releaseRunning(token)
}
}
} catch (e: RejectedExecutionException) {
complete(token)
}
}
private fun recover(token: Int) {
if (probe()) {
complete(token)
return
}
val marked = synchronized(lock) {
if (pendingToken == token && failedToken == 0) {
failedToken = token
WaylandCompositor.completeTextInputFallback(token, TextDelivery.UNRESOLVED.result)
scheduleRetryLocked(token, INITIAL_DELAY_MS)
true
} else {
false
}
}
if (marked) Log.w(TAG, "text injection could not be confirmed")
}
private fun scheduleRetryLocked(token: Int, delayMs: Long) {
if (!active || failedToken != token || pendingToken != token) return
val queue = executor ?: return
val current = generation
try {
queue.schedule({ retryProbe(current, token, delayMs) }, delayMs, TimeUnit.MILLISECONDS)
} catch (e: RejectedExecutionException) {
}
}
private fun retryProbe(received: Long, token: Int, delayMs: Long) {
val ready = synchronized(lock) {
active && generation == received && failedToken == token && pendingToken == token
}
if (!ready) return
val proven = probe()
val owned = synchronized(lock) {
if (proven) {
if (active && generation == received && failedToken == token && pendingToken == token) {
pendingToken = 0
runningToken = 0
failedToken = 0
true
} else {
false
}
} else {
if (active && generation == received && failedToken == token && pendingToken == token) {
val next = (delayMs * 2).coerceAtMost(MAX_DELAY_MS)
scheduleRetryLocked(token, next)
}
false
}
}
if (owned) WaylandCompositor.completeTextInputFallback(token, TextDelivery.NOT_DELIVERED.result)
}
private fun probe(): Boolean {
val live = LocalSocket()
return try {
live.connect(LocalSocketAddress(endpoint().path, LocalSocketAddress.Namespace.FILESYSTEM))
live.soTimeout = TIMEOUT_MS
val out = live.outputStream
out.write(lengthPrefix(0))
out.flush()
live.inputStream.read() == 0
} catch (e: IOException) {
Log.w(TAG, "could not probe guest text input state", e)
false
} finally {
close(live)
}
}
private fun complete(token: Int, delivery: TextDelivery = TextDelivery.NOT_DELIVERED) {
val owned = synchronized(lock) {
if (pendingToken == token) {
pendingToken = 0
runningToken = 0
failedToken = 0
true
} else {
false
}
}
if (owned) WaylandCompositor.completeTextInputFallback(token, delivery.result)
}
private fun releaseRunning(token: Int) {
synchronized(lock) {
if (runningToken == token) runningToken = 0
}
}
private fun send(bytes: ByteArray, received: Long, token: Int): TextDelivery {
val live = LocalSocket()
if (!claim(live, received, token)) {
close(live)
return TextDelivery.NOT_DELIVERED
}
var requested = false
try {
live.connect(LocalSocketAddress(endpoint().path, LocalSocketAddress.Namespace.FILESYSTEM))
live.soTimeout = TIMEOUT_MS
if (!isCurrent(received)) return TextDelivery.NOT_DELIVERED
val out = live.outputStream
out.write(lengthPrefix(bytes.size))
requested = true
out.write(bytes)
out.flush()
val input = live.inputStream
val ack = try {
input.read()
} catch (e: IOException) {
// Android may report a socket read timeout as a plain IOException.
requestCancel(live)
input.read()
}
if (ack == 0) Log.d(TAG, "guest did not complete text delivery")
if (ack != 0 && ack != 1 && isCurrent(received)) Log.w(TAG, "guest did not acknowledge text delivery")
return when (ack) {
1 -> TextDelivery.DELIVERED
0 -> TextDelivery.NOT_DELIVERED
else -> TextDelivery.UNRESOLVED
}
} catch (e: IOException) {
if (isCurrent(received)) Log.w(TAG, "could not hand text to the guest", e)
if (!requested) return TextDelivery.NOT_DELIVERED
return TextDelivery.UNRESOLVED
} finally {
release(live)
close(live)
}
}
private fun requestCancel(live: LocalSocket) {
try {
live.shutdownOutput()
} catch (e: IOException) {
Log.w(TAG, "could not request guest text input cancellation", e)
}
}
private fun isCurrent(received: Long) = synchronized(lock) { active && generation == received }
private fun claim(live: LocalSocket, received: Long, token: Int) = synchronized(lock) {
if (!active || generation != received || pendingToken != token || runningToken != 0 || failedToken != 0) {
false
} else {
runningToken = token
socket = live
true
}
}
private fun release(live: LocalSocket) {
synchronized(lock) {
if (socket === live) socket = null
}
}
private fun endpoint(): File = File(LinuxRuntime.sessionRoot(appContext), "text-input.sock")
private fun lengthPrefix(size: Int): ByteArray {
val flagged = if (size == 0) size else size or Int.MIN_VALUE
return byteArrayOf(
(flagged ushr 24).toByte(),
(flagged ushr 16).toByte(),
(flagged ushr 8).toByte(),
flagged.toByte(),
)
}
private fun close(sock: LocalSocket) {
try {
sock.close()
} catch (e: IOException) {
}
}
private companion object {
const val TAG = "SessionTextInput"
const val MAX_BYTES = 65536
const val TIMEOUT_MS = 3000
const val INITIAL_DELAY_MS = 500L
const val MAX_DELAY_MS = 5000L
}
}
@@ -38,6 +38,11 @@ object ElfSeccompPatch {
val end = minOf(data.size, buffer.getLong(at + 8).toInt() + buffer.getLong(at + 32).toInt()) and 3.inv()
var pos = start
while (pos + 4 <= end) {
if (patchTermiosRequest(buffer, pos, end)) {
patched++
pos += 4
continue
}
val replacement = when (buffer.getInt(pos)) {
MOV_X8_SET_ROBUST_LIST -> NOP
MOV_X8_CLONE3, MOV_X8_RSEQ -> MOV_X0_ENOSYS
@@ -65,6 +70,40 @@ object ElfSeccompPatch {
return patched
}
/**
* glibc 2.42 and later read and set a terminal with TCGETS2 and TCSETS2/W2/F2, which Android's
* SELinux policy refuses on an app's pseudo-terminal slaves (EACCES): isatty() was false in every
* Konsole, ssh and tmux session, so bash had no prompt or job control and stdout was not line
* buffered. TCGETS and TCSETS* carry the same struct without its two speed fields, which glibc
* then takes from c_cflag. A site is `movz xN, #lo` then `movk xN, #hi, lsl #16`; the movz gets
* the old request and the movk becomes a no-op.
*/
private fun patchTermiosRequest(buffer: ByteBuffer, pos: Int, end: Int): Boolean {
val movz = buffer.getInt(pos)
if ((movz and 0x7fe00000) != 0x52800000) return false
val low = (movz ushr 5) and 0xffff
if (low !in 0x542a..0x542d) return false
val register = movz and 0x1f
var next = pos + 4
while (next < minOf(end, pos + 4 + 4 * 4)) {
val movk = buffer.getInt(next)
if ((movk and 0x7fe00000) == 0x72a00000 && (movk and 0x1f) == register) {
val request = when ((movk ushr 5) and 0xffff) {
0x802c -> if (low == 0x542a) 0x5401 else return false
0x402c -> if (low != 0x542a) 0x5402 + (low - 0x542b) else return false
else -> return false
}
buffer.putInt(pos, (movz and 0x1f.inv() and (0xffff shl 5).inv()) or (request shl 5) or register)
buffer.putInt(next, NOP)
return true
}
// Anything between that might read or write the register would see the old low half
if (intArrayOf(0, 5, 10, 16).any { (movk ushr it) and 0x1f == register }) return false
next += 4
}
return false
}
/** Patches the file behind [path] (symlinks followed) if it still has unpatched call sites. */
fun patchFile(path: File): Int {
val target = path.canonicalFile
@@ -0,0 +1,980 @@
package com.droiddeck.launcher.runtime
import android.app.ActivityManager
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.net.LocalServerSocket
import android.net.LocalSocket
import android.os.Binder
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Parcel
import android.os.ParcelFileDescriptor
import android.os.Process
import android.system.ErrnoException
import android.system.Os
import android.system.OsConstants
import android.system.StructPollfd
import android.util.Log
import org.json.JSONObject
import java.io.DataInputStream
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* A guest program run as the main process of its own Android process.
*
* Android counts the processes in an app process's cgroup against its child-process limit, but not
* the app processes themselves. The worker execs the program in place; its binder fd stays open
* across the exec, so the system keeps the process as a live service process. The program's own
* children are still counted. See docs/phantom-processes.md.
*/
open class GuestWorker : Service() {
private val binder = object : Binder() {
override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {
if (code != RUN) return super.onTransact(code, data, reply, flags)
val argv = data.createStringArray() ?: return false
val env = data.createStringArray() ?: return false
val fds = List(data.readInt()) { data.readFileDescriptor() }
val targets = data.createIntArray() ?: IntArray(fds.size) { it }
val fillBinderFd = data.readInt() != 0
val go = data.readFileDescriptor()
val nice = data.readInt()
reply?.writeInt(Process.myPid())
Handler(Looper.getMainLooper()).post {
// The app writes a byte once it has the reply and has taken the launch on: an exec
// before then would end this process with the reply undelivered, and with none (the
// app gave up and starts the program another way) the program must not run here.
var why = ""
// poll() with a timeout counts as network I/O to StrictMode on the main thread
android.os.StrictMode.setThreadPolicy(android.os.StrictMode.ThreadPolicy.LAX)
val committed = runCatching {
fun byte(timeout: Int): Int {
val poll = StructPollfd().apply { fd = go.fileDescriptor; events = OsConstants.POLLIN.toShort() }
val ready = Os.poll(arrayOf(poll), timeout)
return (if (ready > 0) Os.read(go.fileDescriptor, ByteArray(1), 0, 1) else -1)
.also { why = "poll $ready revents ${poll.revents} read $it" }
}
// The commit, an answer, and the app's word that it has the answer: the app may
// have stopped waiting for it (and started the program another way) meanwhile.
// That last word comes, or the app closes its end (a byte or EOF): no timeout,
// which could drop a launch the app has already reported as started.
byte(GO_TIMEOUT_MS) == 1 && Os.write(go.fileDescriptor, byteArrayOf(1), 0, 1) == 1 && byte(-1) == 1
}.getOrElse { why = it.toString(); false }
go.close()
if (committed) exec(argv, env, fds, targets, fillBinderFd, nice)
else {
Log.w(TAG, "launch not committed ($why): not running ${argv.firstOrNull()}")
Process.killProcess(Process.myPid())
}
}
return true
}
}
override fun onBind(intent: Intent): IBinder = binder
private fun exec(argv: Array<String>, env: Array<String>, fds: List<ParcelFileDescriptor?>, targets: IntArray, fillBinderFd: Boolean,
nice: Int) {
try {
val top = targets.maxOrNull() ?: 2
val (binderTop, binderFd) = keepBinderOpen(maxOf(BINDER_FDS, top + 1))
// Out of the way first, so that placing one fd cannot overwrite another not yet placed.
val above = maxOf(MOVED_FDS, top + 1, binderTop + 1)
val moved = fds.map { pfd -> pfd?.let { Os.fcntlInt(it.fileDescriptor, OsConstants.F_DUPFD, above) } }
moved.forEachIndexed { i, fd ->
if (fd == null || i >= targets.size) return@forEachIndexed
val source = ParcelFileDescriptor.adoptFd(fd).also { kept.add(it) }.fileDescriptor
Os.dup2(source, targets[i])
Os.fcntlInt(source, OsConstants.F_SETFD, OsConstants.FD_CLOEXEC)
}
// A session of its own: in zygote's process group, a program signalling its group
// (kill(0, sig)) would reach every process of the app.
runCatching { Os.setsid() }
// The native hook closes the binder fds in every other process (hook/handoff.c). Only an
// app launch asks for the number (a whole argument or variable value), never a guest's.
val fill = { arg: String ->
if (!fillBinderFd) arg
else if (arg == BINDER_FD_TOKEN) binderFd.toString()
else if (arg.endsWith("=$BINDER_FD_TOKEN")) arg.removeSuffix(BINDER_FD_TOKEN) + binderFd
else arg
}
// This thread blocks SIGQUIT, SIGUSR1 and SIGPIPE (Android's runtime), and an exec keeps
// that: the program's hook sets DDH_SIGMASK instead (none blocked, unless the request says).
val mask = if (env.any { it.startsWith("DDH_SIGMASK=") }) emptyList() else listOf("DDH_SIGMASK=0")
// Android raised this thread to THREAD_PRIORITY_TOP_APP_BOOST (a service the top app binds with
// BIND_IMPORTANT is scheduled as the top app); the program and its threads would keep it and
// run ahead of the game. They get the asker's priority instead, as a forked child would.
runCatching { Process.setThreadPriority(nice) }
Os.execve(argv[0], argv.map(fill).toTypedArray(),
env.filterNot { it.startsWith("DDH_WORKER_PID=") }.map(fill).toTypedArray() + mask +
"DDH_WORKER_PID=${Process.myPid()}")
} catch (e: ErrnoException) {
Log.e(TAG, "could not exec ${argv.firstOrNull()}", e)
}
Process.killProcess(Process.myPid())
}
/**
* Binder fds stay open across the exec, at [from] or above, where no fd of the program goes.
* Returns the highest fd used and the one on /dev/binder, whose closing Android takes for
* the death of this process.
*/
private fun keepBinderOpen(from: Int): Pair<Int, Int> {
var highest = from - 1
var binder = -1
File("/proc/self/fd").listFiles()?.forEach { link ->
val target = runCatching { Os.readlink(link.path) }.getOrNull() ?: return@forEach
if (target !in BINDER_DEVICES && !target.startsWith("/dev/binderfs/")) return@forEach
// A copy, not adoptFd(): some of these fds are owned (fdsan) by a ParcelFileDescriptor.
val copy = runCatching { ParcelFileDescriptor.fromFd(link.name.toIntOrNull() ?: return@forEach) }.getOrNull()
?: return@forEach
val kept = Os.fcntlInt(copy.fileDescriptor, OsConstants.F_DUPFD, from)
highest = maxOf(highest, kept)
if (target.substringAfterLast('/') == "binder") binder = kept
copy.close()
}
return highest to binder
}
companion object {
const val RUN = IBinder.FIRST_CALL_TRANSACTION
/** An argument, or a variable's whole value, in an app launch: replaced by the number of its kept binder fd. */
const val BINDER_FD_TOKEN = "@DDH_WORKER_BINDER_FD@"
// Longer than the app may wait for the hook's "go" (GuestWorkers.ACK_TIMEOUT_MS) before it commits
private const val GO_TIMEOUT_MS = 15000
private val BINDER_DEVICES = setOf("/dev/binder", "/dev/hwbinder", "/dev/vndbinder")
private const val BINDER_FDS = 900
private const val MOVED_FDS = 1200
private const val TAG = "GuestWorker"
private val kept = ArrayList<ParcelFileDescriptor>()
fun isWorkerProcess(context: Context, process: String?): Boolean =
process != null && process.startsWith(context.packageName + ":g") &&
process.substring(context.packageName.length + 2).all { it.isDigit() }
}
}
class GuestWorker0 : GuestWorker()
class GuestWorker1 : GuestWorker()
class GuestWorker2 : GuestWorker()
class GuestWorker3 : GuestWorker()
class GuestWorker4 : GuestWorker()
class GuestWorker5 : GuestWorker()
class GuestWorker6 : GuestWorker()
class GuestWorker7 : GuestWorker()
class GuestWorker8 : GuestWorker()
class GuestWorker9 : GuestWorker()
class GuestWorker10 : GuestWorker()
class GuestWorker11 : GuestWorker()
class GuestWorker12 : GuestWorker()
class GuestWorker13 : GuestWorker()
class GuestWorker14 : GuestWorker()
class GuestWorker15 : GuestWorker()
class GuestWorker16 : GuestWorker()
class GuestWorker17 : GuestWorker()
class GuestWorker18 : GuestWorker()
class GuestWorker19 : GuestWorker()
class GuestWorker20 : GuestWorker()
class GuestWorker21 : GuestWorker()
class GuestWorker22 : GuestWorker()
class GuestWorker23 : GuestWorker()
class GuestWorker24 : GuestWorker()
class GuestWorker25 : GuestWorker()
class GuestWorker26 : GuestWorker()
class GuestWorker27 : GuestWorker()
class GuestWorker28 : GuestWorker()
class GuestWorker29 : GuestWorker()
class GuestWorker30 : GuestWorker()
class GuestWorker31 : GuestWorker()
class GuestWorker32 : GuestWorker()
class GuestWorker33 : GuestWorker()
class GuestWorker34 : GuestWorker()
class GuestWorker35 : GuestWorker()
class GuestWorker36 : GuestWorker()
class GuestWorker37 : GuestWorker()
class GuestWorker38 : GuestWorker()
class GuestWorker39 : GuestWorker()
class GuestWorker40 : GuestWorker()
class GuestWorker41 : GuestWorker()
class GuestWorker42 : GuestWorker()
class GuestWorker43 : GuestWorker()
class GuestWorker44 : GuestWorker()
class GuestWorker45 : GuestWorker()
class GuestWorker46 : GuestWorker()
class GuestWorker47 : GuestWorker()
class GuestWorker48 : GuestWorker()
class GuestWorker49 : GuestWorker()
class GuestWorker50 : GuestWorker()
class GuestWorker51 : GuestWorker()
class GuestWorker52 : GuestWorker()
class GuestWorker53 : GuestWorker()
class GuestWorker54 : GuestWorker()
class GuestWorker55 : GuestWorker()
class GuestWorker56 : GuestWorker()
class GuestWorker57 : GuestWorker()
class GuestWorker58 : GuestWorker()
class GuestWorker59 : GuestWorker()
class GuestWorker60 : GuestWorker()
class GuestWorker61 : GuestWorker()
class GuestWorker62 : GuestWorker()
class GuestWorker63 : GuestWorker()
class GuestWorker64 : GuestWorker()
class GuestWorker65 : GuestWorker()
class GuestWorker66 : GuestWorker()
class GuestWorker67 : GuestWorker()
class GuestWorker68 : GuestWorker()
class GuestWorker69 : GuestWorker()
class GuestWorker70 : GuestWorker()
class GuestWorker71 : GuestWorker()
class GuestWorker72 : GuestWorker()
class GuestWorker73 : GuestWorker()
class GuestWorker74 : GuestWorker()
class GuestWorker75 : GuestWorker()
class GuestWorker76 : GuestWorker()
class GuestWorker77 : GuestWorker()
class GuestWorker78 : GuestWorker()
class GuestWorker79 : GuestWorker()
class GuestWorker80 : GuestWorker()
class GuestWorker81 : GuestWorker()
class GuestWorker82 : GuestWorker()
class GuestWorker83 : GuestWorker()
class GuestWorker84 : GuestWorker()
class GuestWorker85 : GuestWorker()
class GuestWorker86 : GuestWorker()
class GuestWorker87 : GuestWorker()
class GuestWorker88 : GuestWorker()
class GuestWorker89 : GuestWorker()
class GuestWorker90 : GuestWorker()
class GuestWorker91 : GuestWorker()
class GuestWorker92 : GuestWorker()
class GuestWorker93 : GuestWorker()
class GuestWorker94 : GuestWorker()
class GuestWorker95 : GuestWorker()
class GuestWorker96 : GuestWorker()
class GuestWorker97 : GuestWorker()
class GuestWorker98 : GuestWorker()
class GuestWorker99 : GuestWorker()
class GuestWorker100 : GuestWorker()
class GuestWorker101 : GuestWorker()
class GuestWorker102 : GuestWorker()
class GuestWorker103 : GuestWorker()
class GuestWorker104 : GuestWorker()
class GuestWorker105 : GuestWorker()
class GuestWorker106 : GuestWorker()
class GuestWorker107 : GuestWorker()
class GuestWorker108 : GuestWorker()
class GuestWorker109 : GuestWorker()
class GuestWorker110 : GuestWorker()
class GuestWorker111 : GuestWorker()
class GuestWorker112 : GuestWorker()
class GuestWorker113 : GuestWorker()
class GuestWorker114 : GuestWorker()
class GuestWorker115 : GuestWorker()
class GuestWorker116 : GuestWorker()
class GuestWorker117 : GuestWorker()
class GuestWorker118 : GuestWorker()
class GuestWorker119 : GuestWorker()
class GuestWorker120 : GuestWorker()
class GuestWorker121 : GuestWorker()
class GuestWorker122 : GuestWorker()
class GuestWorker123 : GuestWorker()
class GuestWorker124 : GuestWorker()
class GuestWorker125 : GuestWorker()
class GuestWorker126 : GuestWorker()
class GuestWorker127 : GuestWorker()
/** The pool of [GuestWorker] processes, and the socket guests ask it through (`droiddeck-spawn`). */
object GuestWorkers {
private const val TAG = "GuestWorkers"
private val classes: List<Class<out GuestWorker>> = listOf(
GuestWorker0::class.java, GuestWorker1::class.java, GuestWorker2::class.java,
GuestWorker3::class.java, GuestWorker4::class.java, GuestWorker5::class.java,
GuestWorker6::class.java, GuestWorker7::class.java, GuestWorker8::class.java,
GuestWorker9::class.java, GuestWorker10::class.java, GuestWorker11::class.java,
GuestWorker12::class.java, GuestWorker13::class.java, GuestWorker14::class.java,
GuestWorker15::class.java, GuestWorker16::class.java, GuestWorker17::class.java,
GuestWorker18::class.java, GuestWorker19::class.java, GuestWorker20::class.java,
GuestWorker21::class.java, GuestWorker22::class.java, GuestWorker23::class.java,
GuestWorker24::class.java, GuestWorker25::class.java, GuestWorker26::class.java,
GuestWorker27::class.java, GuestWorker28::class.java, GuestWorker29::class.java,
GuestWorker30::class.java, GuestWorker31::class.java, GuestWorker32::class.java,
GuestWorker33::class.java, GuestWorker34::class.java, GuestWorker35::class.java,
GuestWorker36::class.java, GuestWorker37::class.java, GuestWorker38::class.java,
GuestWorker39::class.java, GuestWorker40::class.java, GuestWorker41::class.java,
GuestWorker42::class.java, GuestWorker43::class.java, GuestWorker44::class.java,
GuestWorker45::class.java, GuestWorker46::class.java, GuestWorker47::class.java,
GuestWorker48::class.java, GuestWorker49::class.java, GuestWorker50::class.java,
GuestWorker51::class.java, GuestWorker52::class.java, GuestWorker53::class.java,
GuestWorker54::class.java, GuestWorker55::class.java, GuestWorker56::class.java,
GuestWorker57::class.java, GuestWorker58::class.java, GuestWorker59::class.java,
GuestWorker60::class.java, GuestWorker61::class.java, GuestWorker62::class.java,
GuestWorker63::class.java, GuestWorker64::class.java, GuestWorker65::class.java,
GuestWorker66::class.java, GuestWorker67::class.java, GuestWorker68::class.java,
GuestWorker69::class.java, GuestWorker70::class.java, GuestWorker71::class.java,
GuestWorker72::class.java, GuestWorker73::class.java, GuestWorker74::class.java,
GuestWorker75::class.java, GuestWorker76::class.java, GuestWorker77::class.java,
GuestWorker78::class.java, GuestWorker79::class.java, GuestWorker80::class.java,
GuestWorker81::class.java, GuestWorker82::class.java, GuestWorker83::class.java,
GuestWorker84::class.java, GuestWorker85::class.java, GuestWorker86::class.java,
GuestWorker87::class.java, GuestWorker88::class.java, GuestWorker89::class.java,
GuestWorker90::class.java, GuestWorker91::class.java, GuestWorker92::class.java,
GuestWorker93::class.java, GuestWorker94::class.java, GuestWorker95::class.java,
GuestWorker96::class.java, GuestWorker97::class.java, GuestWorker98::class.java,
GuestWorker99::class.java, GuestWorker100::class.java, GuestWorker101::class.java,
GuestWorker102::class.java, GuestWorker103::class.java, GuestWorker104::class.java,
GuestWorker105::class.java, GuestWorker106::class.java, GuestWorker107::class.java,
GuestWorker108::class.java, GuestWorker109::class.java, GuestWorker110::class.java,
GuestWorker111::class.java, GuestWorker112::class.java, GuestWorker113::class.java,
GuestWorker114::class.java, GuestWorker115::class.java, GuestWorker116::class.java,
GuestWorker117::class.java, GuestWorker118::class.java, GuestWorker119::class.java,
GuestWorker120::class.java, GuestWorker121::class.java, GuestWorker122::class.java,
GuestWorker123::class.java, GuestWorker124::class.java, GuestWorker125::class.java,
GuestWorker126::class.java, GuestWorker127::class.java,
)
private class Slot(val index: Int) {
lateinit var connection: ServiceConnection
val connected = CountDownLatch(1)
@Volatile var service: IBinder? = null
@Volatile var pid = -1
@Volatile var guest = false
/** The session it runs a program for ([serve]'s number). */
@Volatile var session = 0
@Volatile var onExit: ((Int) -> Unit)? = null
/** The priority it runs its program at: the asker's (a guest, or the app thread that started it). */
@Volatile var nice = 0
/** Set once its program was handed over: only then does its end count as the program's. */
@Volatile var started = false
/** Between the pid and the last word of a launch (under the slots lock): its end is held back. */
var launching = false
/** It ended while launching: reported once the launch turns out to have run, never otherwise. */
var endedLaunching = false
}
private val slots = arrayOfNulls<Slot>(classes.size)
// Workers bound ahead of need while a session runs: a zygote fork and the bind take about
// 60-100 ms, which every program the session starts would otherwise wait for.
private val warm = ArrayDeque<Slot>()
@Volatile private var warmTarget = 0
// Numbers the sessions: an old session's teardown can still be running when the next one starts.
@Volatile private var session = 0
// The latest session whose teardown has begun
@Volatile private var stopped = 0
// Held for a launch's last word and for marking a session stopped
private val authorizing = Any()
private val warming = java.util.concurrent.atomic.AtomicBoolean(false)
private const val WARM_WORKERS = 2
// A game's start hands off a burst of programs (Wine's services, the agent's checks) within a few
// seconds: bound ahead while the client starts it, not forked while the game draws its first frames.
private const val LAUNCH_WORKERS = 16
private const val LAUNCH_MS = 20_000L
@Volatile private var launchUntil = 0L
private val launches = java.util.concurrent.atomic.AtomicInteger()
private const val ACK_TIMEOUT_MS = 5000
private const val ANSWER_TIMEOUT_MS = 5000
private const val RECEIVE_TIMEOUT_MS = 10000
// argv and the environment of one exec, with room: Linux caps them at a quarter of the stack
private const val MAX_REQUEST_BYTES = 8 shl 20
private const val MAX_RECEIVING = 32
private val receiving = java.util.concurrent.atomic.AtomicInteger()
private val connections = java.util.concurrent.Executors.newSingleThreadExecutor { Thread(it, "guest-worker-binder").apply { isDaemon = true } }
@Volatile private var server: Thread? = null
// Android sets a worker's main thread to THREAD_PRIORITY_TOP_APP_BOOST again each time the app returns to the top
private const val TOP_APP_BOOST = -10
private const val PRIORITY_CHECK_MS = 2000L
@Volatile private var keeper: Thread? = null
/** The app, once [attach] or [serve] ran in its main process; null before. */
@Volatile var context: Context? = null
private set
/** Whether the session runs its programs in workers: the native userland, and not turned off. */
fun enabled(context: Context): Boolean = handoffAllowed(context) && NativeGuest.enabled(context)
private fun handoffAllowed(context: Context): Boolean =
android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.session.SessionPrefs.childProcessHandoff(context)
/** How the running session's root was started: in a worker (true) or counted (false); null with none running. */
@Volatile var sessionRootUncounted: Boolean? = null
/**
* Whether Android's child-process limit is out of the session's way: as the running session
* started (a proot session, or one whose root fell back to a counted start, is not), else as
* the next one would start.
*/
fun limitHandled(context: Context): Boolean =
sessionRootUncounted ?: (NativeGuest.sessionMode != false && handoffAllowed(context) && NativeGuest.nextSession(context))
/** Whether pid is a program running in one of the workers. */
fun runsInWorker(pid: Int): Boolean = pid > 0 && synchronized(slots) { slots.any { it != null && it.started && it.pid == pid } }
fun socketName(context: Context): String = "droiddeck-spawn." + context.packageName + "." + Process.myUid()
/**
* Runs [argv] (a host command line) as the main process of a free worker with [env] and the
* fds in [stdio] as its 0, 1 and 2. Returns its pid, or -1. Blocks: not for the main thread.
* [onExit] runs once the process is gone.
*/
fun start(context: Context, argv: List<String>, env: List<String>, stdio: List<ParcelFileDescriptor>, onExit: (Int) -> Unit): Int =
start(context, argv, env, stdio, IntArray(stdio.size) { it }, onExit)
/** As [start], with the fds in [fds] placed at the numbers in [targets]. */
fun start(context: Context, argv: List<String>, env: List<String>, fds: List<ParcelFileDescriptor>, targets: IntArray,
onExit: (Int) -> Unit): Int = start(context, argv, env, fds, targets, false, onExit)
/**
* [guest]: one of the session's guest programs, which [guestPids] lists and [stopGuests] ends.
* [commit] runs with the pid before the worker may run the program; false, and it does not.
* [confirmed] runs once the worker has taken it on, just before it is told to run it; false, and it does not.
* [owner]: the session asking (the one a guest's request names), else the latest.
*/
private fun start(context: Context, argv: List<String>, env: List<String>, fds: List<ParcelFileDescriptor>, targets: IntArray,
guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true },
confirmed: () -> Boolean = { true }, owner: Int = session,
nice: Int = Process.getThreadPriority(Process.myTid())): Int {
val app = context.applicationContext
if (guest && owner <= stopped) {
Log.w(TAG, (if (owner == 0) "a request naming no session" else "session $owner is stopping") +
": not starting ${argv.firstOrNull()}")
return -1
}
val slot = takeWarm() ?: bind(app)?.takeIf { fresh ->
fresh.connected.await(10, TimeUnit.SECONDS).also { if (!it) release(app, fresh) }
} ?: run {
Log.w(TAG, "no worker started for ${argv.firstOrNull()}")
return -1
}
slot.guest = guest
slot.session = owner
slot.onExit = onExit
slot.nice = nice
// during a game's start the pool drains instead: its refill would fork while the game starts
if (android.os.SystemClock.elapsedRealtime() >= launchUntil) refill(app)
// The worker execs once a byte comes through this socket: after the reply has reached us, so
// that its exec does not cut the reply off, and after the slot is marked started. Closed
// without one, the worker ends without running the program (the caller starts it another way).
// It answers with a byte of its own: without that it gave up waiting, and nothing runs.
var go: Array<ParcelFileDescriptor>? = null
var data: Parcel? = Parcel.obtain()
val reply = Parcel.obtain()
try {
go = ParcelFileDescriptor.createSocketPair()
data!!.writeStringArray(argv.toTypedArray())
data.writeStringArray(env.toTypedArray())
data.writeInt(fds.size)
fds.forEach { data.writeFileDescriptor(it.fileDescriptor) }
data.writeIntArray(targets)
data.writeInt(if (guest) 0 else 1)
data.writeFileDescriptor(go[0].fileDescriptor)
data.writeInt(nice)
slot.service!!.transact(GuestWorker.RUN, data, reply, 0)
// The worker has its own copy: with ours closed (and the request's, which holds one too),
// a worker that gave up leaves no reader
data.recycle()
data = null
go[0].close()
val pid = reply.readInt()
// Once a session's teardown has begun (stopGuests), none of its programs may start: it
// would not find them.
val stopping = { guest && owner <= stopped }
if (stopping() || !commit(pid)) {
Log.w(TAG, "worker ${slot.index}: ${argv.firstOrNull()} was not taken on")
release(app, slot)
return -1
}
// launching, not started yet: an end before the last word is reported only if the launch ran
val live = synchronized(slots) {
(slots[slot.index] === slot && !stopping()).also { if (it) { slot.pid = pid; slot.launching = true } }
}
if (!live) {
Log.w(TAG, "worker ${slot.index} ended, or its session is stopping, before running ${argv.firstOrNull()}")
release(app, slot)
return -1
}
Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1)
val answer = StructPollfd().apply { fd = go[1].fileDescriptor; events = OsConstants.POLLIN.toShort() }
// then the word to run it: given only here, once its answer is in, so that a worker whose
// answer came too late never runs a program this call reports as not started. [confirmed]
// goes first: a caller that hears nothing runs the program itself, so it must have heard
// before the worker may run it (an app dying in between loses the program, not doubles it).
// The word and a teardown's start exclude each other: a launch is authorized before stopGuests()
// marks the session stopped, and is then stopped with the pids it takes (guestPids lists a
// launching slot), or never.
val answered = Os.poll(arrayOf(answer), ANSWER_TIMEOUT_MS) > 0 && Os.read(go[1].fileDescriptor, ByteArray(1), 0, 1) == 1
val accepted = answered && synchronized(authorizing) {
!stopping() && confirmed() && Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1
}
val endedRunning = synchronized(slots) {
slot.launching = false
if (accepted && !slot.endedLaunching) slot.started = true
accepted && slot.endedLaunching
}
if (!accepted) {
Log.w(TAG, "worker ${slot.index} did not take ${argv.firstOrNull()} on")
release(app, slot)
return -1
}
// it ran and was already gone by now: its end, once
if (endedRunning) reportEnd(app, slot)
} catch (e: Exception) {
Log.w(TAG, "worker ${slot.index} refused ${argv.firstOrNull()}", e)
synchronized(slots) { slot.launching = false }
release(app, slot)
return -1
} finally {
data?.recycle()
reply.recycle()
go?.forEach { runCatching { it.close() } }
}
Log.i(TAG, "worker ${slot.index} (pid ${slot.pid}) runs ${argv.lastOrNull { !it.startsWith("-") }}")
return slot.pid
}
/** Binds a free worker; its [Slot.connected] opens once it is up. Null when all are in use. */
private fun bind(app: Context): Slot? {
val slot = synchronized(slots) {
val index = slots.indexOfFirst { it == null }
if (index < 0) {
Log.w(TAG, "all ${slots.size} workers are busy")
return null
}
Slot(index).also { slots[index] = it }
}
slot.connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
slot.service = binder
slot.connected.countDown()
}
override fun onServiceDisconnected(name: ComponentName) = release(app, slot)
override fun onBindingDied(name: ComponentName) = release(app, slot)
}
// Callbacks off the main thread: start() waits for onServiceConnected, and a caller holding a
// lock the main thread is waiting for (PulseAudio's launch) would otherwise wait out the timeout.
val bound = runCatching {
app.bindService(Intent(app, classes[slot.index]), Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT,
connections, slot.connection)
}.onFailure { Log.w(TAG, "worker ${slot.index} could not be bound", it) }.getOrDefault(false)
if (!bound) {
release(app, slot)
return null
}
return slot
}
private fun takeWarm(): Slot? = synchronized(slots) {
while (warm.isNotEmpty()) {
val slot = warm.removeFirst()
if (slots[slot.index] === slot && slot.service?.isBinderAlive == true) return slot
}
null
}
/** Brings the warm workers back up to [warmTarget], one at a time, off the caller's thread. */
private fun refill(app: Context) {
if (warmTarget == 0 || !warming.compareAndSet(false, true)) return
Thread({
try {
while (true) {
val missing = warmTarget - synchronized(slots) { warm.size }
if (missing <= 0) break
// all at once: the zygote forks them in parallel
val fresh = (1..missing).mapNotNull { bind(app) }
if (fresh.isEmpty()) break
for (slot in fresh) {
if (!slot.connected.await(10, TimeUnit.SECONDS)) {
release(app, slot)
continue
}
// decided once, under the lock: kept warm, or released
val kept = synchronized(slots) {
(slots[slot.index] === slot && warmTarget > 0).also { if (it) warm.addLast(slot) }
}
if (!kept) release(app, slot)
}
}
} finally {
warming.set(false)
}
}, "guest-worker-warm").apply { isDaemon = true; start() }
}
/** A game is about to start: [LAUNCH_WORKERS] bound ahead, back to [WARM_WORKERS] once it is up. */
fun expectLaunch(context: Context) {
val app = context.applicationContext
val raised = synchronized(slots) { (warmTarget > 0).also { if (it) warmTarget = LAUNCH_WORKERS } }
if (!raised) return
launchUntil = android.os.SystemClock.elapsedRealtime() + LAUNCH_MS
val launch = launches.incrementAndGet()
refill(app)
Thread({
try {
Thread.sleep(LAUNCH_MS)
} catch (_: InterruptedException) {
return@Thread
}
if (launches.get() != launch) return@Thread
val extra = synchronized(slots) {
if (warmTarget != LAUNCH_WORKERS) emptyList()
else {
warmTarget = WARM_WORKERS
List((warm.size - WARM_WORKERS).coerceAtLeast(0)) { warm.removeLast() }
}
}
extra.forEach { release(app, it) }
refill(app)
}, "guest-worker-launch").apply { isDaemon = true; start() }
}
private fun release(app: Context, slot: Slot) {
var report = false
val removed = synchronized(slots) {
warm.remove(slot)
if (slot.launching) slot.endedLaunching = true else report = slot.started
(slots[slot.index] === slot).also { if (it) slots[slot.index] = null }
}
if (!removed) return
runCatching { app.unbindService(slot.connection) }
if (report) reportEnd(app, slot)
}
private fun reportEnd(app: Context, slot: Slot) {
val onExit = slot.onExit ?: return
Thread({ onExit(exitStatus(app, slot.pid)) }, "guest-worker-exit").start()
}
/** The worker's exit as a wait status (exit code << 8, or the signal), -1 when unknown. */
private fun exitStatus(app: Context, pid: Int): Int {
if (pid <= 0 || android.os.Build.VERSION.SDK_INT < 30) return -1
val am = app.getSystemService(ActivityManager::class.java)
var recorded = false
repeat(20) {
am.getHistoricalProcessExitReasons(app.packageName, pid, 1).firstOrNull()?.let {
recorded = true
// an exit code only when the process exited itself; a signal number otherwise (a native crash)
if (it.reason == android.app.ApplicationExitInfo.REASON_EXIT_SELF) return (it.status and 0xff) shl 8
if (it.status in 1..64) return it.status and 0x7f
// Android records the death first and the zygote's status later (as UNKNOWN, 0, then
// EXIT_SELF): a reason without a status may still be completed
if (it.reason != android.app.ApplicationExitInfo.REASON_UNKNOWN) return OsConstants.SIGKILL
}
Thread.sleep(50)
}
// killed by Android with no signal recorded, not a clean exit
return if (recorded) OsConstants.SIGKILL else -1
}
/** The pids of session [of]'s guest programs running in workers. */
fun guestPids(of: Int = session): List<Int> =
synchronized(slots) { slots.mapNotNull { s -> s?.takeIf { it.guest && it.session == of }?.pid?.takeIf { it > 0 } } }
/** Ends session [of]'s guest programs that are still running, and, for the latest session, the warm workers. */
fun stopGuests(of: Int = session) {
// the check and the reset together: a new session's serve() may be under way
val drained = synchronized(authorizing) {
synchronized(slots) {
stopped = maxOf(stopped, of)
if (of != session) emptyList() else { warmTarget = 0; warm.toList().also { warm.clear() } }
}
}
context?.let { app -> drained.forEach { release(app, it) } }
val pids = guestPids(of)
if (pids.isEmpty()) return
pids.forEach { Process.sendSignal(it, OsConstants.SIGTERM) }
Thread.sleep(500)
pids.forEach { Process.killProcess(it) }
}
/** Listens for `droiddeck-spawn` requests from the session's guests. */
fun attach(context: Context) {
this.context = context.applicationContext
}
/** Puts a running program's main thread back to its asker's priority after Android boosted it (once started, never stops). */
private fun keepPriorities() {
synchronized(this) {
if (keeper != null) return
keeper = Thread({
while (true) {
try {
Thread.sleep(PRIORITY_CHECK_MS)
} catch (_: InterruptedException) {
return@Thread
}
val running = synchronized(slots) {
slots.filterNotNull().filter { it.started && it.pid > 0 && it.nice != TOP_APP_BOOST }
}
for (s in running) runCatching {
if (Process.getThreadPriority(s.pid) == TOP_APP_BOOST) Process.setThreadPriority(s.pid, s.nice)
}
}
}, "guest-worker-priority").apply { isDaemon = true; start() }
}
}
/** Starts a session's use of the workers (and the spawn socket, once); returns its number. */
fun serve(context: Context): Int {
val app = context.applicationContext
this.context = app
val number = synchronized(slots) { warmTarget = WARM_WORKERS; ++session }
refill(app)
keepPriorities()
synchronized(this) {
if (server != null) return number
server = Thread({
val socket = try {
LocalServerSocket(socketName(app))
} catch (e: Exception) {
Log.e(TAG, "no spawn socket", e)
synchronized(this) { server = null }
return@Thread
}
while (true) {
val client = runCatching { socket.accept() }.getOrNull()
if (client == null) {
Thread.sleep(100) // out of fds, for one: do not spin
continue
}
// A bounded number of requests still coming in: a stalled sender holds a thread
if (receiving.incrementAndGet() > MAX_RECEIVING) {
receiving.decrementAndGet()
Log.w(TAG, "$MAX_RECEIVING spawn requests are still coming in: refusing another")
runCatching { client.close() }
continue
}
Thread({
try {
handle(app, client) { receiving.decrementAndGet() }
} catch (e: Throwable) {
Log.w(TAG, "spawn request failed", e)
}
}, "guest-spawn").start()
}
}, "guest-spawn-server").apply { isDaemon = true; start() }
}
return number
}
private fun handle(app: Context, client: LocalSocket, received: () -> Unit) {
var receiving = true
val done = { if (receiving) { receiving = false; received() } }
try {
handleRequest(app, client, done)
} finally {
done()
}
}
private fun handleRequest(app: Context, client: LocalSocket, received: () -> Unit) {
client.use {
if (client.peerCredentials.uid != Process.myUid()) return
// The whole request and its fds within this, however slowly they come (the wait for a
// program's exit is not): each read gets what is left of it
val deadline = android.os.SystemClock.elapsedRealtime() + RECEIVE_TIMEOUT_MS
fun left() {
val ms = deadline - android.os.SystemClock.elapsedRealtime()
if (ms <= 0) throw java.net.SocketTimeoutException("spawn request not received in time")
client.soTimeout = ms.toInt()
}
val input = DataInputStream(client.inputStream)
val fds = ArrayList<ParcelFileDescriptor>()
fun take() {
val received = client.ancillaryFileDescriptors.orEmpty()
try {
received.forEach { fds.add(ParcelFileDescriptor.dup(it)) }
} finally {
received.forEach { runCatching { Os.close(it) } }
}
}
// fds can come with any read, the request's own bytes too: each read's are taken at once
fun fill(bytes: ByteArray) {
var got = 0
while (got < bytes.size) {
left()
val n = input.read(bytes, got, bytes.size - got)
take()
if (n < 0) throw java.io.EOFException("spawn request ended at $got of ${bytes.size} bytes")
got += n
}
}
// Until start() has them: closed on every way out before that, from the first byte on
var handedOver = false
try {
val length = ByteArray(4).also { fill(it) }.let { java.nio.ByteBuffer.wrap(it).int }
if (length !in 1..MAX_REQUEST_BYTES) {
Log.w(TAG, "spawn request of $length bytes refused")
return
}
val payload = ByteArray(length).also { fill(it) }
val request = JSONObject(String(payload))
if (request.has("fdchunks")) {
// The hook sends its fds after the request, a chunk with each byte (hook/handoff.c)
val total = (request.optJSONArray("fds")?.length() ?: 0) + (if (request.has("table")) 1 else 0)
while (fds.size < total) {
left()
if (input.read() < 0) throw java.io.EOFException("fds ended at ${fds.size} of $total")
take()
}
} else {
take()
}
received()
val argv = request.getJSONArray("argv").let { a -> List(a.length()) { a.getString(it) } }
val env = LinkedHashMap<String, String>()
request.optJSONObject("env")?.let { o -> o.keys().forEach { env[it] = o.getString(it) } }
request.optJSONArray("envlist")?.let { a ->
for (i in 0 until a.length()) a.getString(i).split('=', limit = 2).let { if (it.size == 2) env[it[0]] = it[1] }
}
// What the hook told the program that asked (it may run in a worker itself) is not this one's
env.keys.removeAll { it.startsWith("DDH_") }
val cwd = request.optString("cwd", "/")
val wait = request.optBoolean("wait", false)
// A path without a slash names a file in the cwd, as execve() takes it, not one on PATH
val file = request.optString("file", "").let { if (it.isNotEmpty() && '/' !in it) "./$it" else it }
// The handoff table (the hook's) comes last among the fds; the rest go to these numbers.
val tableIndex = request.optInt("table", -1)
val numbers = request.optJSONArray("fds")?.let { a -> IntArray(a.length()) { a.getInt(it) } } ?: IntArray(3) { it }
val table = fds.getOrNull(tableIndex)?.takeIf { pfd ->
runCatching { Os.readlink("/proc/self/fd/${pfd.fd}") }.getOrNull()?.contains("ddnatv-handoff") == true
}
val slot = request.optInt("slot", -1)
val parent = request.optInt("parent", -1)
var programFds = fds.filterIndexed { i, _ -> i != tableIndex }
var targets = numbers
if (table != null && slot >= 0) {
// The program reports its own exit status into the table (hook/handoff.c)
val tableFd = (numbers.maxOrNull() ?: 2) + 1
programFds = programFds + table
targets = numbers + tableFd
env["DDH_TABLE"] = "$tableFd:$slot:$parent:${request.optInt("child", -1)}"
}
val root = env["DDNATV_ROOT"]?.let(::File)
val out = client.outputStream
if (root == null || argv.isEmpty()) {
out.write("error no guest root or program\n".toByteArray())
return
}
val shell = listOf("/usr/bin/bash", "/bin/bash").first { File(root, it.removePrefix("/")).isFile }
val args = if (file.isNotEmpty()) {
listOf("-c", "unset DDH_WRAPPER; cd -- \"\$1\" 2>/dev/null; a=\$2; f=\$3; shift 3; exec -a \"\$a\" \"\$f\" \"\$@\"",
"droiddeck-spawn", cwd, argv[0], file) + argv.drop(1)
} else {
listOf("-c", "unset DDH_WRAPPER; cd -- \"\$1\" 2>/dev/null; shift; exec \"\$@\"", "droiddeck-spawn", cwd) + argv
}
val command = NativeGuest.command(root, shell, args)
env["DDNATV_REAL_EXE"] = File(root, shell.removePrefix("/")).path
// The hook restores these in the program (tools/nativeguest/hook/handoff.c).
if (request.has("sigign")) env["DDH_SIGIGN"] = request.getLong("sigign").toString()
if (request.has("nofile")) {
env["DDH_NOFILE"] = request.getLong("nofile").toString() +
(if (request.has("nofilemax")) ":" + request.getLong("nofilemax") else "")
}
if (request.has("umask")) env["DDH_UMASK"] = request.getLong("umask").toString()
if (request.has("pgid")) env["DDH_PGID"] = request.getLong("pgid").toString()
if (request.has("anchor")) env["DDH_ANCHOR"] = request.getLong("anchor").toString()
if (request.has("pstart")) env["DDH_PSTART"] = request.getLong("pstart").toString()
if (request.has("astart")) env["DDH_ASTART"] = request.getLong("astart").toString()
env["DDH_SIGMASK"] = request.optLong("sigmask", 0L).toString()
// The shell above: the hook restores nothing there (bash changes its own signal mask),
// only in the program it execs, which no longer has this.
env["DDH_WRAPPER"] = "1"
val child = request.optInt("child", -1)
val exited = CountDownLatch(1)
var status = -1
var worker = -1
// The hook answers the pid with "go" (ack): without it (it died, or gave up and runs the
// program itself) the worker must not run it too.
val ack = request.optBoolean("ack", false)
var answered = false
// the hook's last word, sent once the worker has taken the program on and before it runs it
var confirmedToHook = false
// The session whose guest asks, not the latest: a new session can start (serve()) while an
// older one's guests are still sending, and that older one's teardown must find its programs.
// A request that names none is refused (start() runs nothing for session 0): the hook and
// droiddeck-spawn always name it, and which session's it is cannot be told otherwise.
val owner = request.optInt("session", 0).coerceAtLeast(0)
// The sender is the forked child (or droiddeck-spawn): its priority is the one the program would inherit
val nice = runCatching { Process.getThreadPriority(client.peerCredentials.pid) }.getOrDefault(Process.THREAD_PRIORITY_DEFAULT)
val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true, owner = owner, nice = nice, onExit = { code ->
status = code
if (table != null && slot >= 0) reportExit(table, slot, code, parent, child, worker)
exited.countDown()
}, confirmed = {
!ack || runCatching {
out.write("ok\n".toByteArray())
out.flush()
confirmedToHook = true
}.isSuccess
}, commit = { started ->
worker = started
if (!ack) return@start true
runCatching {
out.write("pid $started\n".toByteArray())
out.flush()
answered = true
client.soTimeout = ACK_TIMEOUT_MS
// the whole line: a hook whose write stopped short treats it as failed and runs the program itself
val line = StringBuilder()
var ended = false
while (!ended) {
val c = input.read()
if (c < 0) break
if (c == '\n'.code) ended = true else line.append(c.toChar())
}
ended && line.toString() == "go"
}.getOrDefault(false)
})
handedOver = true
programFds.filter { it !== table }.forEach { runCatching { it.close() } }
if (pid <= 0) table?.let { runCatching { it.close() } }
if (!answered) {
out.write(if (pid > 0) "pid $pid\n".toByteArray() else "error no worker\n".toByteArray())
out.flush()
} else if (!confirmedToHook) {
// nothing runs it in a worker: the hook runs it itself
runCatching { out.write("error not started\n".toByteArray()); out.flush() }
}
if (pid > 0 && wait) {
exited.await()
// droiddeck-spawn exits with this: an exit code, or 128 plus the signal
val code = if (status < 0) 1 else if (status and 0x7f == 0) (status shr 8) and 0xff else 128 + (status and 0x7f)
out.write("exit $code\n".toByteArray())
out.flush()
}
} finally {
if (!handedOver) fds.forEach { runCatching { it.close() } }
}
}
}
// Layout of the hook's table (tools/nativeguest/hook/handoff.c): a 64-byte header, then 64-byte
// entries of int32 child, real, parent, state, ..., and at 32 the app's report: int32 status, child.
// The report is one 8-byte write tagged with the child it is for; only the hook changes an
// entry's state, so a report that lands after the entry went to another child is ignored there.
private fun reportExit(table: ParcelFileDescriptor, slot: Int, status: Int, parent: Int, child: Int, worker: Int) {
runCatching {
val entry = 64L + slot * 64L
val head = java.nio.ByteBuffer.allocate(16).order(java.nio.ByteOrder.nativeOrder())
Os.pread(table.fileDescriptor, head, entry)
val real = head.getInt(4)
val state = head.getInt(12)
// Also while the hook holds the entry (TAKEN) or has already guessed its end (EXITED):
// the report is for this child only, and wins over the timeout's guess (ddh_status)
if (head.getInt(0) != child || head.getInt(8) != parent || (real != 0 && real != worker) || state !in 1..4)
return@runCatching
// An exit Android has no record of is reported as a failure, not as a signal.
val report = java.nio.ByteBuffer.allocate(8).order(java.nio.ByteOrder.nativeOrder())
.putInt(0, if (status < 0) 1 shl 8 else status).putInt(4, child)
Os.pwrite(table.fileDescriptor, report, entry + 32)
if (parent > 0) Process.sendSignal(parent, OsConstants.SIGCHLD)
}.onFailure { Log.w(TAG, "could not report an exit to the guest's parent", it) }
runCatching { table.close() }
}
}
@@ -35,9 +35,40 @@ object LegacyNames {
@Synchronized
fun migrateEtc(root: File) {
for ((old, new) in LINKED_DIRS) moveAndLink(File(root, old), File(root, new))
File(root, "etc/droiddeck/empty").mkdirs()
clearEmptyStandIn(root)
File(root, NO_THERMAL).mkdirs()
}
/**
* It stands in for /sys/bus/pci/devices, and libpci exits the whole process on an entry it cannot
* parse; older builds let thermal bind mount points leak into it. The guest can write here, so a
* link is never followed: one in place of the folder is removed, and one above it stops the cleanup.
*/
private fun clearEmptyStandIn(root: File) {
val linkedAbove = listOf("etc", "etc/droiddeck").firstOrNull { Files.isSymbolicLink(File(root, it).toPath()) }
if (linkedAbove != null) {
Log.w(TAG, "not clearing the empty stand-in: $linkedAbove is a link")
return
}
val empty = File(root, "etc/droiddeck/empty")
if (Files.isSymbolicLink(empty.toPath())) runCatching { Files.delete(empty.toPath()) }
.onFailure { Log.w(TAG, "could not remove the link at $empty", it); return }
empty.mkdirs()
empty.listFiles()?.forEach { entry ->
runCatching { deleteWithoutFollowing(entry.toPath()) }.onFailure { Log.w(TAG, "could not clear $entry", it) }
}
}
private fun deleteWithoutFollowing(path: java.nio.file.Path) {
if (Files.isDirectory(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)) {
Files.newDirectoryStream(path).use { entries -> entries.forEach(::deleteWithoutFollowing) }
}
Files.deleteIfExists(path)
}
/** Stands in for a /sys/class/thermal the kernel won't list; proot adds the bound zones' mount points to it. */
const val NO_THERMAL = "etc/droiddeck/no-thermal"
@Synchronized
fun migrateRootfs(root: File) {
migrateEtc(root)
@@ -248,7 +248,7 @@ public final class LinuxRuntime {
// A kernel that refuses to list /sys/class/thermal (Pixel 10, Android 17) made mangoapp abort
// at start ("filesystem_error ... Permission denied: '/sys/class/thermal/'") until its
// wrapper gave up: it lists the directory for CPU temperatures. Empty there instead.
if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/class/thermal");
if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, LegacyNames.NO_THERMAL).getPath() + ":/sys/class/thermal");
bind(cmd, context.getFilesDir().getPath());
bind(cmd, context.getCacheDir().getPath());
bind(cmd, liveDir(context).getPath());
@@ -24,6 +24,16 @@ object NativeGuest {
fun enabled(context: Context): Boolean =
SessionPrefs.nativeUserland(context) && available(LinuxRuntime.rootDir(context))
/**
* Whether the next session will start natively. The session stages the hook from the APK before
* it starts, so only the setting and the rootfs's loader decide, and a runtime still to be
* installed will have one.
*/
fun nextSession(context: Context): Boolean =
SessionPrefs.nativeUserland(context) && willRun(LinuxRuntime.rootDir(context), LinuxRuntime.isInstalled(context))
internal fun willRun(root: File, installed: Boolean): Boolean = !installed || loader(root) != null
/** The mode the running session started in; null between sessions. */
@Volatile var sessionMode: Boolean? = null
@@ -219,6 +219,19 @@ object BottomDesktop {
fun sendText(text: String) {
val target = service ?: return
if (text.isNotEmpty() && text.all { it == '\r' || it == '\n' || it == '\b' || it == '\u007f' || it == '\t' }) {
for (c in text) {
val evdev = when (c) {
'\r', '\n' -> 28
'\b' -> 14
'\u007f' -> 111
else -> 15
}
sendKey(evdev, true)
sendKey(evdev, false)
}
return
}
send(target, Message.obtain(null, Comp.MSG_TEXT).apply { data = Bundle().apply { putString(Comp.KEY_TEXT, text) } })
}
@@ -66,11 +66,14 @@ object ProtonExtras {
internal fun installedIn(dir: File, tool: Tool): List<String> =
dir.listFiles()
?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && usable(it) }
?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && !x86_64Build(it) && usable(it) }
?.map { it.name }
?.sortedWith { a, b -> compareVersions(a, b) }
?: emptyList()
internal fun x86_64Build(dir: File): Boolean =
File(dir, "files/lib/wine/x86_64-unix").isDirectory && !File(dir, "files/bin-arm64").isDirectory
private fun usable(dir: File): Boolean {
val manifest = runCatching { File(dir, "toolmanifest.vdf").readText() }.getOrNull() ?: return false
val command = Regex("\\\"commandline\\\"\\s+\\\"/?([^\\\" ]+)").find(manifest)?.groupValues?.getOrNull(1) ?: return false
@@ -11,6 +11,7 @@ import com.droiddeck.launcher.runtime.DesktopCatalog
import com.droiddeck.launcher.runtime.LegacyNames
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.ProotFastPath
import org.json.JSONObject
import java.io.File
object SessionFiles {
@@ -21,6 +22,8 @@ object SessionFiles {
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
private const val STAGED_LEDGER = "usr/local/.droiddeck-staged"
private const val IME_MANIFEST = "usr/local/share/droiddeck/ime-files.json"
private const val IME_DEFAULT_MODE = 420
val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread")
internal val DESKTOP_FILES = arrayOf(
@@ -130,7 +133,11 @@ object SessionFiles {
"usr/local/bin/droiddeck-agent" to "usr/local/bin/droiddeck-agent",
"usr/local/bin/steam-compatibility" to "usr/local/bin/steam-compatibility",
"usr/local/bin/droiddeck-clipboard" to "usr/local/bin/droiddeck-clipboard",
"usr/local/bin/droiddeck-spawn" to "usr/local/bin/droiddeck-spawn",
"usr/local/bin/droiddeck-log-writer" to "usr/local/bin/droiddeck-log-writer",
"usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard",
"usr/local/bin/droiddeck-text-input" to "usr/local/bin/droiddeck-text-input",
"usr/local/bin/droiddeck-steam-ime" to "usr/local/bin/droiddeck-steam-ime",
"usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window",
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
"usr/local/bin/droiddeck-steam-preapply" to "usr/local/bin/droiddeck-steam-preapply",
@@ -154,6 +161,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
"usr/local/bin/droiddeck-downloads" to "usr/local/bin/droiddeck-downloads",
"usr/local/bin/droiddeck-root" to "usr/local/bin/droiddeck-root",
"usr/local/bin/droiddeck-user" to "usr/local/bin/droiddeck-user",
"usr/local/bin/droiddeck-text" to "usr/local/bin/droiddeck-text",
"usr/local/bin/droiddeck-snapd" to "usr/local/bin/droiddeck-snapd",
"usr/local/bin/droiddeck-emulators" to "usr/local/bin/droiddeck-emulators",
@@ -332,6 +340,7 @@ object SessionFiles {
if (installed) ledger.staged(key, target) else Log.e(TAG, "DirectAudio $set/$relative NOT staged")
}
for (pack in SERVICE_PACKS.keys) stageStoreService(context, root, pack, ledger)
stageImeFiles(context, root, ledger)
ledger.save()
for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively()
val preload = StringBuilder("/usr/local/lib/libddsession.so\n")
@@ -358,6 +367,7 @@ object SessionFiles {
Log.e(TAG, "could not write steam-compatibility-label")
}
writeCjkFontConfig(root, etc)
writeSessionBusPolicy(etc)
writeDesktopStrings(context, File(etc, "droiddeck").apply { mkdirs() })
val droiddeckEtc = File(etc, "droiddeck").apply { mkdirs() }
val stagedSocket = File(droiddeckEtc, "bwrap-socket.staged")
@@ -417,6 +427,42 @@ object SessionFiles {
seen?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
}
private fun stageImeFiles(context: Context, root: File, ledger: StageLedger) {
val entries = LinkedHashMap<String, Int>()
try {
val text = context.assets.open("linuxfs/$IME_MANIFEST").bufferedReader().use { it.readText() }
val files = JSONObject(text).getJSONObject("files")
for (name in files.keys()) {
entries[name] = files.optJSONObject(name)?.optString("mode").orEmpty().toIntOrNull(8) ?: IME_DEFAULT_MODE
}
entries[IME_MANIFEST] = IME_DEFAULT_MODE
} catch (e: Exception) {
Log.w(TAG, "the Chinese input payload is not bundled; Steam sessions start without it", e)
return
}
for ((relative, mode) in entries) {
val target = File(root, relative)
if (ledger.current(relative, target)) continue
val staged = File(target.parentFile, target.name + ".staged")
var installed = false
try {
target.parentFile?.mkdirs()
context.assets.open("linuxfs/$relative").use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
}
installed = staged.setReadable(true, false) &&
staged.setWritable((mode and 0x80) != 0, true) &&
staged.setExecutable((mode and 0x49) != 0, false) &&
staged.renameTo(target)
} catch (e: Exception) {
Log.w(TAG, "could not stage $relative", e)
} finally {
if (!installed) staged.delete()
}
if (installed) ledger.staged(relative, target) else Log.e(TAG, "$relative NOT staged")
}
}
internal fun resetMissingStartupMovie(config: File, force: Boolean): Boolean {
synchronized(STEAM_CONFIG) {
if (!config.isFile) return true
@@ -880,6 +926,24 @@ object SessionFiles {
}
}
/**
* A session bus admits only its owner, and with droiddeck-user (the native hook's ordinary
* user) a root process and a user's share the bus while the kernel sees one Android uid.
*/
private fun writeSessionBusPolicy(etc: File) {
val xml = """<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<policy context="default">
<allow user="*"/>
</policy>
</busconfig>
"""
val conf = File(etc, "dbus-1/session.d/droiddeck-users.conf")
conf.parentFile?.mkdirs()
if (!FileUtils.writeString(conf, xml)) Log.e(TAG, "could not write the session bus policy")
}
private fun writeCjkFontConfig(root: File, etc: File) {
try {
val confDir = File(etc, "fonts/conf.d").apply { mkdirs() }
@@ -63,6 +63,24 @@ object SessionPrefs {
.takeIf { value -> orientationOptions.any { it.first == value } }
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
fun orientation(context: Context, mode: String?): Int {
val key = when (mode) {
"steam", SessionService.MODE_STEAM, SessionService.MODE_RUN -> "orientation.steam"
"desktop", SessionService.MODE_DESKTOP -> "orientation.desktop"
else -> null
} ?: return orientation(context)
val stored = prefs(context).getInt(key, Int.MIN_VALUE)
return if (stored == Int.MIN_VALUE) orientation(context)
else stored.takeIf { value -> orientationOptions.any { it.first == value } } ?: orientation(context)
}
fun setOrientation(context: Context, mode: String, orientation: Int) {
require(mode == "steam" || mode == "desktop")
require(orientationOptions.any { it.first == orientation })
val key = if (mode == "steam") "orientation.steam" else "orientation.desktop"
prefs(context).edit().putInt(key, orientation).apply()
}
/** The session menu's width in dp the user dragged it to; null keeps the default. */
fun drawerWidthDp(context: Context): Int? = prefs(context).getInt("drawerWidthDp", 0).takeIf { it > 0 }
@@ -75,11 +93,19 @@ object SessionPrefs {
prefs(context).edit().putInt("orientation", orientation).apply()
}
fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int): Int =
if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !prefs(context).contains("orientation"))
fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int, mode: String? = null): Int {
val modeKey = when (mode) {
"steam", SessionService.MODE_STEAM, SessionService.MODE_RUN -> "orientation.steam"
"desktop", SessionService.MODE_DESKTOP -> "orientation.desktop"
else -> null
}
val preferences = prefs(context)
if (modeKey != null && preferences.contains(modeKey)) return orientation(context, mode)
return if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !preferences.contains("orientation"))
ActivityInfo.SCREEN_ORIENTATION_USER else orientation(context)
}
fun portrait(context: Context): Boolean = when (orientation(context)) {
fun portrait(context: Context, mode: String? = null): Boolean = when (orientation(context, mode)) {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT -> true
ActivityInfo.SCREEN_ORIENTATION_USER ->
context.resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT
@@ -92,6 +118,39 @@ object SessionPrefs {
prefs(context).edit().putBoolean("launcherFullscreen", on).apply()
}
fun launcherFrost(context: Context): Boolean = prefs(context).getBoolean("launcherFrost", false)
fun setLauncherFrost(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("launcherFrost", on).apply()
}
fun frostWallpaper(context: Context): Boolean = prefs(context).getBoolean("frostWallpaper", true)
fun setFrostWallpaper(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("frostWallpaper", on).apply()
}
fun frostCards(context: Context): Boolean = prefs(context).getBoolean("frostCards", true)
fun setFrostCards(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("frostCards", on).apply()
}
fun frostTransparency(context: Context): Int = frostPercent(context, "frostTransparency", com.droiddeck.launcher.ui.FROST_WALLPAPER_DEFAULT)
fun setFrostTransparency(context: Context, percent: Int) = setFrostPercent(context, "frostTransparency", percent)
fun frostCardTransparency(context: Context): Int = frostPercent(context, "frostCardTransparency", com.droiddeck.launcher.ui.FROST_DEFAULT)
fun setFrostCardTransparency(context: Context, percent: Int) = setFrostPercent(context, "frostCardTransparency", percent)
private fun frostPercent(context: Context, key: String, default: Int): Int =
prefs(context).getInt(key, default).coerceIn(0, com.droiddeck.launcher.ui.FROST_MAX)
private fun setFrostPercent(context: Context, key: String, percent: Int) {
prefs(context).edit().putInt(key, percent.coerceIn(0, com.droiddeck.launcher.ui.FROST_MAX)).apply()
}
fun controllerHaptics(context: Context): Boolean = prefs(context).getBoolean("controllerHaptics", true)
fun setControllerHaptics(context: Context, on: Boolean) {
@@ -493,6 +552,17 @@ object SessionPrefs {
prefs(context).edit().putString("drawerPageHidden", keys.joinToString(",")).apply()
}
fun drawerSections(context: Context): Map<String, Boolean> =
idList(prefs(context).getString("drawerSections", null)).mapNotNull { entry ->
val at = entry.lastIndexOf('=').takeIf { it > 0 } ?: return@mapNotNull null
entry.substring(0, at) to (entry.substring(at + 1) == "1")
}.toMap()
fun setDrawerSections(context: Context, sections: Map<String, Boolean>) {
prefs(context).edit().putString("drawerSections", sections.entries.filter { ',' !in it.key }
.joinToString(",") { "${it.key}=${if (it.value) 1 else 0}" }).apply()
}
fun setNavTabHidden(context: Context, keys: Set<String>) {
prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply()
}
@@ -1100,10 +1170,20 @@ object SessionPrefs {
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true)
/** The session's long-lived programs run in worker processes Android does not count (GuestWorkers). */
fun childProcessHandoff(context: Context): Boolean = prefs(context).getBoolean("childProcessHandoff", true)
fun setNativeUserland(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("nativeUserland", on).apply()
}
/** Whether the Plasma desktop, and so its apps and shells, runs as an ordinary user instead of root (native userland only). */
fun desktopAsUser(context: Context): Boolean = prefs(context).getBoolean("desktopAsUser", false)
fun setDesktopAsUser(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("desktopAsUser", on).apply()
}
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
fun setProotFastPath(context: Context, on: Boolean) {
@@ -1794,10 +1874,10 @@ object SessionPrefs {
prefs(context).edit().putBoolean(hdrKey(mode), on).apply()
}
fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.$mode", true)
fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.${prefMode(mode)}", true)
fun setZeroCopy(context: Context, mode: String, on: Boolean) {
prefs(context).edit().putBoolean("zeroCopy.$mode", on).apply()
prefs(context).edit().putBoolean("zeroCopy.${prefMode(mode)}", on).apply()
}
const val FPS_UNPACED = -1
@@ -1807,16 +1887,15 @@ object SessionPrefs {
const val PIP_FPS = 30
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)
}
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0, pip: Boolean = false, hostCap: Int = 0): Int {
val limit = listOf(mirrorRefreshLimit, sessionLimit, hostCap).filter { it > 0 }.minOrNull() ?: FPS_UNPACED
return if (pip && mirrorRefreshLimit <= 0 && (limit <= 0 || limit > PIP_FPS)) PIP_FPS else limit
}
/** The per-app rate Android holds this window to (Game Mode's FPS override), or 0 when the panel's rate applies. */
fun hostFrameCap(overrideHz: Float, panelHz: Float): Int =
if (overrideHz > 1f && panelHz - overrideHz > 1f) Math.round(overrideHz) else 0
val upscalerChoices = listOf(
2 to "Nearest", 0 to "Linear", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
8 to "Snapdragon GSR (quality)", 7 to "NVIDIA NIS", 6 to "Sharpen only",
@@ -2117,6 +2196,12 @@ object SessionPrefs {
(resolutionChosen(context, SessionService.MODE_DESKTOP) || resolutionChosen(context, SessionService.MODE_DESKTOP, true))) SessionService.MODE_DESKTOP
else prefMode(mode)
fun showGlassesShortcut(context: Context): Boolean = prefs(context).getBoolean("showGlassesShortcut", true)
fun setShowGlassesShortcut(context: Context, show: Boolean) {
prefs(context).edit().putBoolean("showGlassesShortcut", show).apply()
}
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", true)
fun setPipAutoEnter(context: Context, enabled: Boolean) {
@@ -661,7 +661,7 @@ class SessionService : Service() {
Log.i(TAG, "game resolution: ${w}x$h on a ${size.first}x${size.second} output")
}
if (SessionState.followScreen || size.first < size.second ||
SessionPrefs.orientation(this) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
SessionPrefs.orientation(this, SessionState.mode) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
guest.add("DD_FOLLOW_OUTPUT=1")
if (SessionState.hdr) {
guest.add("DD_HDR=1")
@@ -705,10 +705,25 @@ class SessionService : Service() {
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1")
}
guest.add("DD_LAUNCH_DIR=" + sessionRoot.path)
// this session's worker number: the shared field may be a newer session's by the time it is used
var ownWorkers = 0
if (com.droiddeck.launcher.runtime.GuestWorkers.enabled(this)) {
// Under the lock a stop takes its number with: a stop either comes first (and this session
// starts no workers) or owns them
ownWorkers = synchronized(stopLock) {
if (gen != sessionGen || !SessionState.running) 0
else com.droiddeck.launcher.runtime.GuestWorkers.serve(this).also { guestWorkerSession = it }
}
if (ownWorkers > 0) {
guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this))
guest.add("DD_SPAWN_SESSION=$ownWorkers")
}
}
// Proton builds up to 11.12 report X11 text fields under this name.
guest.add("BL_LAUNCH_DIR=" + sessionRoot.path)
GameStorage.effective(this)?.let { guest.add("DD_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("DD_STEAM_UI=desktop")
if (SessionPrefs.desktopAsUser(this)) guest.add("DD_DESKTOP_USER=1")
// Detailed graphics logs: per-game logs and the guest's Vulkan summary (a GPU that is not
// an Adreno, or Setup's switch), and graphics-report.txt for every session.
if (GraphicsReport.detailed(this)) guest.add("DD_GAME_LOGS=1")
@@ -863,10 +878,10 @@ class SessionService : Service() {
watchLaunchRequests(sessionRoot)
watchSyncWanted(root)
EsyncPacks.fetchInBackground(this, root)
val pid = SessionEvents.step("guest-launch") { HostProcess.start(line, hostEnv.asArray(), root, { status ->
val pid = SessionEvents.step("guest-launch") { HostProcess.startUncounted(line, hostEnv.asArray(), root, { status ->
if (gen != sessionGen) {
Log.i(TAG, "an earlier session's process ended ($status); the current one carries on")
return@start
return@startUncounted
}
val program = programStatus(sessionRoot)
Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "")
@@ -882,10 +897,19 @@ class SessionService : Service() {
syncWatcher = null
}
abandonStart(gen, sessionDir, started)
if (pid > 1) Thread({ teardown(pid) }, "session-teardown").start()
val workers = ownWorkers
if (pid > 1) Thread({ teardown(pid, workerSession = workers) }, "session-teardown").start()
else com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
return
}
sessionPid = pid
// Under the lock Stop clears it with, and only while this session still runs: a Stop since the
// check above has cleared it already, and this would set it again for no running session.
val uncounted = com.droiddeck.launcher.runtime.GuestWorkers.runsInWorker(pid)
synchronized(stopLock) {
if (gen == sessionGen && SessionState.running)
com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = uncounted
}
if (pid > 1) {
raiseTracer(pid, gen)
SessionEvents.guestStarted(pid)
@@ -1535,10 +1559,15 @@ class SessionService : Service() {
return binds
}
private fun teardown(prootPid: Int, expectedStartTime: Long? = null) {
// The workers' session number of the session running now (GuestWorkers.serve)
@Volatile private var guestWorkerSession = 0
private fun teardown(prootPid: Int, expectedStartTime: Long? = null, workerSession: Int = guestWorkerSession) {
fun stillSameProcess(): Boolean = expectedStartTime == null || readStat(prootPid)?.second == expectedStartTime
if (!stillSameProcess()) return
val tree = descendants(prootPid)
// The session's programs that run in worker processes are not descendants of its root.
val workers = if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.guestPids(workerSession) else emptyList()
val tree = descendants(prootPid) + workers.flatMap { pid -> listOfNotNull(readStat(pid)?.let { Pair(pid, it.second) }) + descendants(pid) }
if (!stillSameProcess()) return
saveWineRegistries(tree)
android.os.Process.sendSignal(prootPid, 15)
@@ -1555,6 +1584,7 @@ class SessionService : Service() {
killed++
}
if (killed > 0) Log.i(TAG, "swept $killed process(es) proot left behind")
if (expectedStartTime == null) com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workerSession)
}
private fun clearCachedApps() {
@@ -1729,6 +1759,7 @@ class SessionService : Service() {
SessionEvents.record("steam.game_launch_requested", mapOf("gameId" to gameId, "generation" to gen))
watchGameExit(gameId, gen, exitWatchToken, pendingSteamPreviousGameId)
Log.i(TAG, "queued Steam game $gameId for the running client")
com.droiddeck.launcher.runtime.GuestWorkers.expectLaunch(this)
}
private fun watchGameExit(
@@ -2325,12 +2356,16 @@ class SessionService : Service() {
return
}
completeNativeSleep()
var workers = 0
val (ended, endedArch) = synchronized(stopLock) {
if (gen != null && gen != sessionGen) return
// as it is when running is cleared: startup registers its workers under this lock too
workers = guestWorkerSession
cancelQueuedSteamGame()
gameExitWatchToken++
// also when startup stopped before the guest ran
com.droiddeck.launcher.runtime.NativeGuest.sessionMode = null
com.droiddeck.launcher.runtime.GuestWorkers.sessionRootUncounted = null
if (!SessionState.running) return
if (relaunch) SessionState.confirmRelaunchStop()
SessionEvents.record("guest.exited", mapOf("status" to status))
@@ -2391,7 +2426,8 @@ class SessionService : Service() {
if (prootPid > 1 && steamClientMayRun) askSteamToExit(prootPid)
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
if (prootPid > 1) teardown(prootPid, workerSession = workers)
else com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
killGuestLeftovers(ended)
pruneSystemVulkanRuntime()
finishSessionStop(status, stoppedGen, collectEnded)
@@ -2400,6 +2436,7 @@ class SessionService : Service() {
} else {
Thread({ pruneSystemVulkanRuntime() }, "system-vulkan-prune").start()
Thread({
com.droiddeck.launcher.runtime.GuestWorkers.stopGuests(workers)
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
finishSessionStop(status, stoppedGen, collectEnded)
if (launcherEnded) importLauncherGames()
@@ -12,13 +12,13 @@ object SettingsReset {
private const val TAG = "SettingsReset"
internal val SESSION_KEYS = setOf(
"orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
"orientation", "launcherFullscreen", "launcherFrost", "frostWallpaper", "frostCards", "frostTransparency", "frostCardTransparency", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
"drawerWidthDp", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
"soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "drawerSections", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
@@ -10,9 +10,23 @@ import java.io.File
// browser view placed outside the Big Picture window, composition capped at "notification" so gamescope keeps the game
// focused, and gamepad focus on the main UI. The hold is a lease the app renews, so Steam recovers if the app goes away.
object SteamQam {
data class Target(val port: Int, val path: String)
/** [mainPath] is Steam's main menu page, shown beside the quick access menu in the split layout. */
data class Target(val port: Int, val path: String, val mainPath: String? = null)
const val MAIN_MENU = 1
const val QUICK_ACCESS = 2
/** Height in CSS pixels both menus are laid out at in the split layout, so they show at one scale. */
const val SPLIT_CSS_HEIGHT = 480
/** Steam's own width for the main menu; quick access takes the rest of the panel. */
const val MAIN_CSS_WIDTH = 240
/** Holds the parked main menu in place and spreads its item rows (not dividers) over the full height, at most 80 px each. */
private const val MAIN_PARKED_CSS =
".BasicUI > .Panel { transform: none !important; width: 100% !important; height: 100% !important; margin: 0 !important; } " +
".BasicUI > .Panel > :has(> .Focusable) { flex: 1 1 0 !important; height: auto !important; max-height: 80px; } " +
".BasicUI > .Panel > :has(> .Focusable) > .Panel { height: 100% !important; }"
const val LEASE_MS = 5_000
private const val TAG = "SteamQam"
private const val EVAL_MS = 6_000L
@@ -26,21 +40,54 @@ object SteamQam {
* Takes or renews the lease for [owner], or releases it. A live lease held by a newer panel is never taken back by an
* older one, so a late request from a panel being torn down cannot end its replacement's lease or change its layout.
*/
internal fun leaseScript(on: Boolean, owner: Long, aspect: Float = 0f): String =
internal fun leaseScript(on: Boolean, owner: Long, aspect: Float = 0f, split: Boolean = false): String =
if (on) "if (!(g.__ddQamUntil > Date.now()) || !(g.__ddQamOwner > $owner)) { g.__ddQamOwner = $owner; g.__ddQamUntil = Date.now() + $LEASE_MS;" +
(if (aspect > 0f) " g.__ddQamAspect = $aspect;" else "") + " }"
(if (aspect > 0f) " g.__ddQamAspect = $aspect;" else "") + " g.__ddQamSplit = $split; }"
else "if (g.__ddQamOwner === $owner) g.__ddQamUntil = 0;"
/** [aspect] is the panel's width over height: the menu is laid out at that shape so every tab shows at one scale. */
internal fun script(on: Boolean, aspect: Float = 0f, owner: Long = 0): String = """(() => {
const g = globalThis, QAM = 2;
/**
* [aspect] is the panel's width over height: the menu is laid out at that shape so every tab shows at one scale. With
* [split], Steam's main menu is kept rendered at its own width beside the quick access menu, which gets the rest.
*/
internal fun script(on: Boolean, aspect: Float = 0f, owner: Long = 0, split: Boolean = false): String = """(() => {
const g = globalThis, QAM = 2, MAIN = 1;
const W = SteamUIStore.WindowStore.SteamUIWindows[0];
const m = W.MenuStore, c = W.m_CompositionStateStore;
const nav = W.m_FocusNavContext;
const popup = g_PopupManager.GetExistingPopup("SP BPM_uid0");
const held = () => g.__ddQamUntil > Date.now();
const ours = () => held() && m.m_eOpenSideMenu === QAM && !g.__ddQamTop;
const split = () => held() && g.__ddQamSplit === true;
// Steam's views carry no names: the main menu's is the one Steam focuses while the main menu is open. Until Steam
// has shown it, the main menu is opened once with its view parked like the quick access menu's.
const probing = () => g.__ddMainProbe > Date.now();
const ours = () => held() && !g.__ddQamTop && (m.m_eOpenSideMenu === QAM || (probing() && m.m_eOpenSideMenu === MAIN));
const width = (h) => g.__ddQamAspect > 0 ? Math.round(h * g.__ddQamAspect) : 0;
const parkX = () => popup.m_popup.innerWidth + 64;
const mainSize = () => [$MAIN_CSS_WIDTH, $SPLIT_CSS_HEIGHT];
const qamSplitSize = () => [Math.max(Math.round($SPLIT_CSS_HEIGHT * (g.__ddQamAspect > 0 ? g.__ddQamAspect : 1)) - $MAIN_CSS_WIDTH, 320), $SPLIT_CSS_HEIGHT];
const size = (w, h) => split() ? qamSplitSize() : [width(h) || w, h];
const mainView = () => views().find(v => v.__ddMain);
// Only the quick access view is parked: the one Steam focuses while quick access is open. Before Steam has
// focused it, any view but the main menu's and the header's web page (Store and other pages) may be it.
const headerView = () => W.m_HeaderStore?.m_currentBrowserAndBackstack?.m_browserView;
const isQam = (v) => !v.__ddMain && v !== headerView() &&
(!!v.__ddQamView || !views().some(o => o.__ddQamView) || (probing() && m.m_eOpenSideMenu === MAIN));
const mainParked = () => split() && (m.m_eOpenSideMenu !== MAIN || probing());
const mainDoc = () => {
for (const s of SteamUIStore.m_GamepadNavigationManager?.m_rgGamepadInputSources || []) {
try { const d = s.m_targetWindow?.document; if (d?.title?.startsWith("MainMenu")) return d; } catch (e) {}
}
return null;
};
// Steam slides the main menu out whenever it is not the open side menu; parked, it stays in place and fills its view.
const mainStyle = (on) => {
const d = mainDoc();
let s = d?.getElementById("dd-main-split");
if (!on) { s?.remove(); return; }
if (!d?.head) return;
if (!s) { s = d.createElement("style"); s.id = "dd-main-split"; d.head.appendChild(s); }
if (s.textContent !== "$MAIN_PARKED_CSS") s.textContent = "$MAIN_PARKED_CSS";
};
if (!c.__ddQam) {
c.__ddQam = c.ComputeOverallMinimumRequestedComposition;
m.__ddQam = m.OnMenuDeactivated;
@@ -59,6 +106,18 @@ object SteamQam {
return without >= 2 ? v : 1;
};
}
// Steam frosts its Store page while a side menu is open; a parked menu is not over it.
const inst = m.m_Instance;
if (inst?.SetStoreBrowserGlass && !inst.__ddQamGlass) {
inst.__ddQamGlass = inst.SetStoreBrowserGlass;
inst.SetStoreBrowserGlass = function (e) { return inst.__ddQamGlass.call(this, ours() ? 0 : e); };
}
const glass = () => {
const on = !ours() && m.m_eOpenSideMenu !== 0;
if (g.__ddQamGlassOn === on) return;
g.__ddQamGlassOn = on;
inst?.SetStoreBrowserGlass?.(m.m_eOpenSideMenu);
};
const views = () => popup?.m_rgChildBrowserViews || [];
const backdrop = (hide) => {
const doc = popup?.m_popup?.document;
@@ -75,16 +134,61 @@ object SteamQam {
};
const keep = () => {
for (const v of views()) {
if (v.__ddQam) continue;
v.__ddQam = v.SetBounds;
if (!v.__ddQam) v.__ddQam = v.SetBounds;
if (v.__ddQamW === 4) continue;
v.__ddQamW = 4;
v.__ddQamVis = v.__ddQamVis || v.SetVisible;
v.__ddQamFocus = v.__ddQamFocus || v.SetFocus;
v.SetBounds = function (x, y, w, h, ...r) {
if (v.__ddMain && mainParked()) {
if (w > 0) v.__ddMainAsked = [x, y, w, h];
[w, h] = mainSize();
v.__ddMainOn = true; v.__ddMainW = w; v.__ddMainH = h;
return v.__ddQam.call(this, parkX(), 0, w, h, ...r);
}
if (v.__ddMain && w > 0) mainStyle(false);
v.__ddAsked = [x, y, w, h];
if (w > 0 && ours()) { x = popup.m_popup.innerWidth + 64; w = width(h) || w; }
if (w > 0 && ours() && isQam(v)) { x = parkX(); [w, h] = size(w, h); }
v.__ddAt = x;
v.__ddW = w;
v.__ddH = h;
return v.__ddQam.call(this, x, y, w, h, ...r);
};
v.SetVisible = function (on, ...r) {
return v.__ddQamVis.call(this, on || (!!v.__ddMain && mainParked()), ...r);
};
v.SetFocus = function (on, ...r) {
if (on && m.m_eOpenSideMenu === MAIN && v !== headerView()) {
for (const o of views()) if (o !== v) delete o.__ddMain;
v.__ddMain = true;
delete v.__ddQamView;
}
if (on && m.m_eOpenSideMenu === QAM && !v.__ddMain && v !== headerView()) {
for (const o of views()) if (o !== v) delete o.__ddQamView;
v.__ddQamView = true;
}
return v.__ddQamFocus.call(this, on, ...r);
};
}
if (g.__ddMainProbe && !probing()) { g.__ddMainProbe = 0; g.__ddMainProbed = true; }
if (probing() && mainView()) { g.__ddMainProbe = 0; g.__ddMainProbed = true; }
const mv = mainView();
if (mv && !probing()) {
if (mainParked()) {
const [w, h] = mainSize();
if (!mv.__ddMainOn || mv.__ddMainW !== w || mv.__ddMainH !== h) {
mv.__ddQam.call(mv, parkX(), 0, w, h);
mv.__ddQamVis.call(mv, true);
mv.__ddMainOn = true; mv.__ddMainW = w; mv.__ddMainH = h;
}
} else if (mv.__ddMainOn) {
mv.__ddMainOn = false;
if (m.m_eOpenSideMenu !== MAIN) { mv.__ddQamVis.call(mv, false); mv.__ddQam.call(mv, 0, 0, 0, 0); }
else if (mv.__ddMainAsked) mv.__ddQam.call(mv, ...mv.__ddMainAsked);
}
}
mainStyle(!!mv && mainParked() && !probing());
glass();
if (!held()) {
const parked = !g.__ddQamTop;
g.__ddQamTop = false;
@@ -124,6 +228,25 @@ object SteamQam {
}
g.__ddQamTop = false;
}
// Each Split activation gets a fresh probe budget, and a spent one refills after a backoff, so a Steam that was
// still loading does not leave the main menu undiscovered for good.
if (split() !== !!g.__ddQamSplitOn) { g.__ddQamSplitOn = split(); if (split()) g.__ddMainProbes = 0; }
if (split() && !mv) {
if (probing()) return;
if ((g.__ddMainProbes || 0) >= 3 && Date.now() - (g.__ddMainProbeLast || 0) > 30000) g.__ddMainProbes = 0;
if ((g.__ddMainProbes || 0) < 3 && m.m_eOpenSideMenu !== MAIN) {
g.__ddMainProbes = (g.__ddMainProbes || 0) + 1;
g.__ddMainProbeLast = Date.now();
g.__ddMainProbe = Date.now() + 1500;
m.OpenMainMenu();
c.EnsureCorrectComposition?.();
return;
}
}
if (g.__ddMainProbed) {
g.__ddMainProbed = false;
if (m.m_eOpenSideMenu === MAIN) m.OpenQuickAccessMenu(g.__ddQamTab ?? undefined);
}
const decky = !!g.DeckyPluginLoader?.tabsHook?.qamBrowserViewPatch;
// Decky hooks the menu after Steam starts; the menu has to unmount for its tab to appear, so reopen on the next tick.
if (m.m_eOpenSideMenu === QAM && decky && !g.__ddQamDecky) { g.__ddQamDecky = true; m.CloseSideMenus(); return; }
@@ -136,18 +259,26 @@ object SteamQam {
if (m.m_eQuickAccessTab != null) g.__ddQamTab = m.m_eQuickAccessTab;
if (!g.__ddQamOn) { g.__ddQamOn = true; c.EnsureCorrectComposition?.(); }
for (const v of views()) {
if (v.__ddMain) continue;
if (!isQam(v)) {
// A view parked before the quick access view was known goes back where Steam asked for it.
const a = v.__ddAsked;
if (a?.[2] > 0 && v.__ddAt >= popup.m_popup.innerWidth) { v.__ddQam.call(v, ...a); v.__ddAt = a[0]; v.__ddW = a[2]; v.__ddH = a[3]; }
continue;
}
if (!v.__ddAsked) {
const b = v.GetBounds?.();
if (b && b.width > 0) { v.__ddAsked = [b.x, b.y, b.width, b.height]; v.__ddAt = b.x; v.__ddW = b.width; }
if (b && b.width > 0) { v.__ddAsked = [b.x, b.y, b.width, b.height]; v.__ddAt = b.x; v.__ddW = b.width; v.__ddH = b.height; }
}
const a = v.__ddAsked;
if (a?.[2] > 0 && (v.__ddAt < popup.m_popup.innerWidth || (width(a[3]) && v.__ddW !== width(a[3])))) v.SetBounds(...a);
const [w, h] = a?.[2] > 0 ? size(a[2], a[3]) : [0, 0];
if (a?.[2] > 0 && (v.__ddAt < popup.m_popup.innerWidth || v.__ddW !== w || v.__ddH !== h)) v.SetBounds(...a);
}
const main = nav?.m_rgGamepadNavigationTrees?.find(t => t.m_ID === "GamepadUI_Full_Root");
if (main && nav.m_LastActiveNavTree?.m_ID?.startsWith("QuickAccess")) nav.SetActiveNavTree(main);
if (main && /^(QuickAccess|MainMenu)/.test(nav.m_LastActiveNavTree?.m_ID ?? "")) nav.SetActiveNavTree(main);
backdrop(true);
};
${leaseScript(on, owner, aspect)}
${leaseScript(on, owner, aspect, split)}
keep();
if (held() && !g.__ddQamTimer) {
g.__ddQamTimer = setInterval(() => {
@@ -161,7 +292,8 @@ object SteamQam {
/** [open] is Steam's open side menu; [top] is true while the menu is shown on the top screen. */
data class Hold(val open: Int, val top: Boolean)
fun hold(context: Context, aspect: Float, owner: Long): Hold? = eval(context, script(true, aspect, owner))?.let(::parseHold)
fun hold(context: Context, aspect: Float, owner: Long, split: Boolean = false): Hold? =
eval(context, script(true, aspect, owner, split))?.let(::parseHold)
internal fun parseHold(text: String): Hold? = runCatching {
val a = JSONArray(text)
@@ -181,7 +313,9 @@ object SteamQam {
fun target(context: Context): Target? = runCatching {
val devtools = File(AgentGuest.dir(context), "cdp-port").readText().trim().toInt()
val (relay, secret) = parseRelay(helper(context, "start", devtools.toString())) ?: return null
val found = runCatching { parseTarget(relay, get(relay, "/$secret/json"))?.let { it.copy(path = "/$secret${it.path}") } }
val found = runCatching {
parseTarget(relay, get(relay, "/$secret/json"))?.let { t -> t.copy(path = "/$secret${t.path}", mainPath = t.mainPath?.let { "/$secret$it" }) }
}
if (found.getOrNull() == null) helper(context, "stop", relay.toString())
found.getOrThrow()
}.onFailure { android.util.Log.e(TAG, "no quick access target: $it") }.getOrNull()
@@ -232,14 +366,16 @@ object SteamQam {
internal fun parseTarget(port: Int, json: String): Target? {
val list = JSONArray(json)
for (i in 0 until list.length()) {
val t = list.optJSONObject(i) ?: continue
if (!t.optString("title").startsWith("QuickAccess")) continue
val ws = t.optString("webSocketDebuggerUrl")
val path = Regex("^ws://[^/]+(/devtools/page/[A-Za-z0-9-]+)$").find(ws)?.groupValues?.get(1) ?: continue
return Target(port, path)
fun page(prefix: String): String? {
for (i in 0 until list.length()) {
val t = list.optJSONObject(i) ?: continue
if (!t.optString("title").startsWith(prefix)) continue
val ws = t.optString("webSocketDebuggerUrl")
Regex("^ws://[^/]+(/devtools/page/[A-Za-z0-9-]+)$").find(ws)?.groupValues?.get(1)?.let { return it }
}
return null
}
return null
return page("QuickAccess")?.let { Target(port, it, page("MainMenu")) }
}
private fun eval(context: Context, expression: String): String? = runCatching {
@@ -0,0 +1,68 @@
package com.droiddeck.launcher.session.xr
/**
* The menu gesture: both controllers held together. It arms when the two aim points come within
* [ARM_METRES], cancels once they part beyond [CANCEL_METRES], and fires after [HOLD_MS] held.
* It needs both controllers apart again before it can arm a second time.
*/
internal class XrGesture {
enum class Phase { IDLE, ARMING, FIRED }
var phase = Phase.IDLE
private set
var progress = 0f
private set
var midpoint = Vec3.ZERO
private set
private var startedMs = 0L
private var needsRelease = false
/** Returns true on the frame the gesture completes. */
fun update(left: XrHand, right: XrHand, nowMs: Long): Boolean {
if (!left.active || !right.active) {
reset(release = false)
return false
}
val a = left.aim.position
val b = right.aim.position
val distance = (a - b).length
midpoint = Vec3.lerp(a, b, 0.5f)
if (needsRelease) {
if (distance > CANCEL_METRES) needsRelease = false
phase = Phase.IDLE
progress = 0f
return false
}
when (phase) {
Phase.IDLE, Phase.FIRED -> if (distance < ARM_METRES) {
phase = Phase.ARMING
startedMs = nowMs
progress = 0f
}
Phase.ARMING -> if (distance > CANCEL_METRES) {
phase = Phase.IDLE
progress = 0f
} else {
progress = ((nowMs - startedMs).toFloat() / HOLD_MS).coerceIn(0f, 1f)
if (progress >= 1f) {
phase = Phase.FIRED
needsRelease = true
return true
}
}
}
return false
}
fun reset(release: Boolean) {
phase = Phase.IDLE
progress = 0f
if (release) needsRelease = true
}
companion object {
const val ARM_METRES = 0.09f
const val CANCEL_METRES = 0.14f
const val HOLD_MS = 1500L
}
}
@@ -0,0 +1,160 @@
package com.droiddeck.launcher.session.xr
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* Typed access to the two buffers quest_xr.cpp shares each frame (app/src/main/cpp/questxr/xr_host.h).
* The offsets here must match that header.
*/
internal object XrHostLayout {
const val VERSION = 1
const val LAYERS = 6
const val STATE_SIZE = 288
const val CONTROL_SIZE = 552
const val POSE_SIZE = 32
const val HAND_SIZE = 96
const val STATE_HEAD = 32
const val STATE_HANDS = 64
const val HAND_GRIP = 0
const val HAND_AIM = 32
const val HAND_TRIGGER = 64
const val HAND_SQUEEZE = 68
const val HAND_STICK = 72
const val HAND_BUTTONS = 80
const val HAND_ACTIVE = 84
const val CONTROL_HANDS = 8
const val HAND_CONTROL_SIZE = 40
const val HAND_CONTROL_MASK = 0
const val HAND_CONTROL_LASER = 4
const val HAND_CONTROL_HAPTIC = 8
const val CONTROL_ORB = 88
const val CONTROL_LAYERS = 136
const val LAYER_SIZE = 64
const val FLAG_SURFACE_SWAPCHAIN = 1
const val FLAG_FOCUSED = 2
const val MASK_INPUT = 1
const val LAYER_ALPHA = 1
const val LAYER_HEAD_LOCKED = 2
const val SECONDARY_CLICK = 1 shl 2
}
internal class XrHand(
val grip: Pose,
val aim: Pose,
val trigger: Float,
val squeeze: Float,
val stickX: Float,
val stickY: Float,
val buttons: Int,
val active: Boolean,
) {
val secondary: Boolean get() = buttons and XrHostLayout.SECONDARY_CLICK != 0
companion object {
val IDLE = XrHand(Pose(), Pose(), 0f, 0f, 0f, 0f, 0, false)
}
}
internal class XrFrame(val flags: Int, val frame: Long, val displayTimeNs: Long, val head: Pose, val hands: List<XrHand>) {
val focused: Boolean get() = flags and XrHostLayout.FLAG_FOCUSED != 0
val surfaces: Boolean get() = flags and XrHostLayout.FLAG_SURFACE_SWAPCHAIN != 0
}
internal class XrHaptic(val durationMs: Int, val amplitude: Float, val frequency: Float = 0f)
internal class XrLayerOut(
val id: Int,
val pose: Pose,
val width: Float,
val height: Float,
val order: Int,
val alpha: Boolean = true,
)
internal class XrControlOut {
val masks = BooleanArray(2)
val lasers = FloatArray(2)
val haptics = arrayOfNulls<XrHaptic>(2)
var orb: Orb? = null
val layers = mutableListOf<XrLayerOut>()
class Orb(val position: Vec3, val radius: Float, val progress: Float, val burst: Float)
}
internal class XrHost(state: ByteBuffer, control: ByteBuffer) {
private val state = state.order(ByteOrder.nativeOrder())
private val control = control.order(ByteOrder.nativeOrder())
private val hapticIds = LongArray(2)
init {
require(state.capacity() >= XrHostLayout.STATE_SIZE && control.capacity() >= XrHostLayout.CONTROL_SIZE) { "XR host buffers too small" }
}
fun read(): XrFrame = readFrame(state)
fun write(out: XrControlOut) = writeControl(control, out, hapticIds)
companion object {
fun readPose(b: ByteBuffer, at: Int) = Pose(
Quat(b.getFloat(at), b.getFloat(at + 4), b.getFloat(at + 8), b.getFloat(at + 12)),
Vec3(b.getFloat(at + 16), b.getFloat(at + 20), b.getFloat(at + 24)),
)
fun writePose(b: ByteBuffer, at: Int, pose: Pose) {
b.putFloat(at, pose.orientation.x); b.putFloat(at + 4, pose.orientation.y)
b.putFloat(at + 8, pose.orientation.z); b.putFloat(at + 12, pose.orientation.w)
b.putFloat(at + 16, pose.position.x); b.putFloat(at + 20, pose.position.y); b.putFloat(at + 24, pose.position.z)
b.putInt(at + 28, 0)
}
fun readFrame(b: ByteBuffer): XrFrame {
val hands = (0 until 2).map { hand ->
val at = XrHostLayout.STATE_HANDS + hand * XrHostLayout.HAND_SIZE
XrHand(
readPose(b, at + XrHostLayout.HAND_GRIP), readPose(b, at + XrHostLayout.HAND_AIM),
b.getFloat(at + XrHostLayout.HAND_TRIGGER), b.getFloat(at + XrHostLayout.HAND_SQUEEZE),
b.getFloat(at + XrHostLayout.HAND_STICK), b.getFloat(at + XrHostLayout.HAND_STICK + 4),
b.getInt(at + XrHostLayout.HAND_BUTTONS), b.getInt(at + XrHostLayout.HAND_ACTIVE) != 0,
)
}
return XrFrame(b.getInt(8), b.getLong(16), b.getLong(24), readPose(b, XrHostLayout.STATE_HEAD), hands)
}
fun writeControl(b: ByteBuffer, out: XrControlOut, hapticIds: LongArray) {
for (i in 0 until XrHostLayout.CONTROL_SIZE step 4) b.putInt(i, 0)
b.putInt(0, XrHostLayout.VERSION)
for (hand in 0 until 2) {
val at = XrHostLayout.CONTROL_HANDS + hand * XrHostLayout.HAND_CONTROL_SIZE
b.putInt(at + XrHostLayout.HAND_CONTROL_MASK, if (out.masks[hand]) XrHostLayout.MASK_INPUT else 0)
b.putFloat(at + XrHostLayout.HAND_CONTROL_LASER, out.lasers[hand])
out.haptics[hand]?.let { hapticIds[hand]++ }
val haptic = at + XrHostLayout.HAND_CONTROL_HAPTIC
b.putLong(haptic, hapticIds[hand])
out.haptics[hand]?.let {
b.putLong(haptic + 8, it.durationMs * 1_000_000L)
b.putFloat(haptic + 16, it.amplitude)
b.putFloat(haptic + 20, it.frequency)
}
}
out.orb?.let { orb ->
val at = XrHostLayout.CONTROL_ORB
b.putInt(at, 1)
b.putFloat(at + 4, orb.progress); b.putFloat(at + 8, orb.burst); b.putFloat(at + 12, orb.radius)
writePose(b, at + 16, Pose(position = orb.position))
}
out.layers.take(XrHostLayout.LAYERS).forEachIndexed { index, layer ->
val at = XrHostLayout.CONTROL_LAYERS + index * XrHostLayout.LAYER_SIZE
b.putInt(at, layer.id)
b.putInt(at + 4, 1)
b.putInt(at + 8, if (layer.alpha) XrHostLayout.LAYER_ALPHA else 0)
b.putInt(at + 12, layer.order)
writePose(b, at + 16, layer.pose)
b.putFloat(at + 48, layer.width); b.putFloat(at + 52, layer.height)
}
for (index in out.layers.size until XrHostLayout.LAYERS) b.putInt(XrHostLayout.CONTROL_LAYERS + index * XrHostLayout.LAYER_SIZE, -1)
}
}
}
@@ -0,0 +1,303 @@
package com.droiddeck.launcher.session.xr
import kotlin.math.PI
import kotlin.math.abs
/**
* [barButton]: the grab bar has a button at its left end; the menu has its own close button instead.
* [tilt]: how far the panel leans back from upright, in radians, as a keyboard lies on a desk.
*/
internal enum class XrPanelKind(
val key: String, val resizable: Boolean, val chrome: Boolean, val barButton: Boolean = false, val tilt: Float = 0f,
) {
MENU("menu", resizable = true, chrome = true),
PET_HEAD("pet_head", resizable = false, chrome = false),
PET_CHAT("pet_chat", resizable = true, chrome = true, barButton = true),
KEYBOARD("keyboard_desk", resizable = true, chrome = true, barButton = true, tilt = (PI / 4).toFloat());
/** Turned towards [head] about the vertical axis, then leant back by [tilt]. */
fun orient(position: Vec3, head: Vec3): Quat = facing(position, head) * Quat.pitch(-tilt)
}
/** Where a panel is and how big, in metres; [pixelWidth] and [pixelHeight] are its surface's size. */
internal class XrPanelState(val kind: XrPanelKind, var pose: Pose, var width: Float, var height: Float) {
var pixelWidth = XrUnits.pixels(width)
var pixelHeight = XrUnits.pixels(height)
/** 0 while it opens or closes from [animationFrom], 1 when it is in place and takes input. */
var scale = 1f
var animationFrom: Vec3? = null
val shownPose: Pose get() = animationFrom?.let { Pose(pose.orientation, Vec3.lerp(it, pose.position, scale)) } ?: pose
val interactive: Boolean get() = scale >= 1f
fun hit(ray: Pose): XrHit? = hitPlane(ray, bounded = true)
/** Where [ray] meets this panel's plane; [bounded] limits it to the panel itself. */
fun hitPlane(ray: Pose, bounded: Boolean, plane: Pose = pose, w: Float = width, h: Float = height): XrHit? {
val normal = plane.orientation.rotate(Vec3(0f, 0f, 1f))
val direction = ray.forward
val denominator = direction dot normal
if (denominator > -1e-4f) return null
val distance = ((plane.position - ray.position) dot normal) / denominator
if (distance <= 0f) return null
val local = plane.toLocal(ray.position + direction * distance)
if (bounded && (abs(local.x) > w / 2f || abs(local.y) > h / 2f)) return null
return XrHit(this, local.x, local.y, distance)
}
fun u(localX: Float) = (localX / width + 0.5f).coerceIn(0f, 1f)
fun v(localY: Float) = (0.5f - localY / height).coerceIn(0f, 1f)
fun pixelX(localX: Float) = u(localX) * pixelWidth
fun pixelY(localY: Float) = v(localY) * pixelHeight
/** The grab bar runs along the bottom, as under Quest's own windows, with its button at the left end. */
fun inBar(hit: XrHit) = kind.chrome && hit.y + 0.5f * height <= XrUnits.BAR_METRES
fun inBarButtons(hit: XrHit) = kind.barButton && inBar(hit) && hit.x + 0.5f * width <= XrUnits.BAR_BUTTONS_METRES
fun inResizeGrip(hit: XrHit) = kind.resizable &&
0.5f * width - hit.x <= XrUnits.GRIP_METRES && hit.y + 0.5f * height <= XrUnits.GRIP_METRES
}
internal class XrHit(val panel: XrPanelState, val x: Float, val y: Float, val distance: Float)
internal object XrUnits {
const val DP_PER_METRE = 900f
const val DENSITY = 2f
const val DPI = 320
const val BAR_METRES = 52f / DP_PER_METRE
const val BAR_BUTTONS_DP = 150f
const val BAR_BUTTONS_METRES = BAR_BUTTONS_DP / DP_PER_METRE
const val GRIP_METRES = 0.05f
const val MIN_METRES = 0.3f
const val MAX_METRES = 1.6f
const val MIN_DISTANCE = 0.4f
const val MAX_DISTANCE = 3f
fun pixels(metres: Float) = (metres * DP_PER_METRE * DENSITY).toInt().coerceAtLeast(16)
}
internal sealed class XrPointerEvent(val panel: XrPanelState) {
class Down(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel)
class Move(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel)
class Up(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel)
class Cancel(panel: XrPanelState, val hand: Int = 0) : XrPointerEvent(panel)
class Scroll(panel: XrPanelState, val x: Float, val y: Float, val amount: Float) : XrPointerEvent(panel)
class Back(panel: XrPanelState) : XrPointerEvent(panel)
class Click(panel: XrPanelState) : XrPointerEvent(panel)
class Resized(panel: XrPanelState) : XrPointerEvent(panel)
class Moved(panel: XrPanelState) : XrPointerEvent(panel)
}
internal class XrInteractionOut {
val events = mutableListOf<XrPointerEvent>()
val masks = BooleanArray(2)
val lasers = FloatArray(2)
val ticks = BooleanArray(2)
/** Where each controller points on each panel, in its pixels, left hand first; panels with no entry show none. */
val cursors = mutableMapOf<XrPanelState, MutableList<Pair<Float, Float>>>()
fun point(panel: XrPanelState, x: Float, y: Float) {
cursors.getOrPut(panel) { mutableListOf() } += x to y
}
}
/**
* What the two controllers do to the panels each frame. A controller acts on a panel only while it
* points at one, or while it holds one it picked up, pressed or is resizing; only then is its input
* taken from the game.
*/
internal class XrInteraction {
private sealed class Hold {
object None : Hold()
class Press(val panel: XrPanelState, var x: Float, var y: Float) : Hold()
class Move(val panel: XrPanelState, var offset: Vec3, val byGrip: Boolean) : Hold()
class Resize(val panel: XrPanelState, val plane: Pose, val width: Float, val height: Float, val startX: Float, val startY: Float) : Hold()
class HeadPress(val panel: XrPanelState, val startX: Float, val startY: Float, val offset: Vec3) : Hold()
}
private val holds = arrayOf<Hold>(Hold.None, Hold.None)
private val trigger = BooleanArray(2)
private val grip = BooleanArray(2)
private val secondary = BooleanArray(2)
fun holding(panel: XrPanelState) = holds.any { held(it) === panel }
private fun held(hold: Hold): XrPanelState? = when (hold) {
is Hold.Press -> hold.panel
is Hold.Move -> hold.panel
is Hold.Resize -> hold.panel
is Hold.HeadPress -> hold.panel
Hold.None -> null
}
/** Lets go of everything, as when the immersive view goes. A button still held counts only once let go and pressed again. */
fun reset() {
holds.fill(Hold.None)
trigger.fill(true)
grip.fill(true)
secondary.fill(true)
}
/** Cancels a press and ends a move or resize where it is, as when the headset loses focus; then [reset]. */
fun cancel(out: XrInteractionOut) {
for ((hand, hold) in holds.withIndex()) when (hold) {
is Hold.Press -> out.events += XrPointerEvent.Cancel(hold.panel, hand)
is Hold.Move -> out.events += XrPointerEvent.Moved(hold.panel)
is Hold.Resize -> out.events += XrPointerEvent.Resized(hold.panel)
else -> Unit
}
reset()
}
/** Lets go of [panel], as when it closes. */
fun release(panel: XrPanelState, out: XrInteractionOut) {
for (hand in 0..1) if (held(holds[hand]) === panel) {
if (holds[hand] is Hold.Press) out.events += XrPointerEvent.Cancel(panel, hand)
holds[hand] = Hold.None
}
}
fun update(head: Pose, hands: List<XrHand>, panels: List<XrPanelState>, dtSeconds: Float): XrInteractionOut {
val out = XrInteractionOut()
for (hand in 0..1) handFrame(hand, head, hands[hand], panels.filter { it.interactive }, dtSeconds, out)
return out
}
private fun handFrame(index: Int, head: Pose, hand: XrHand, panels: List<XrPanelState>, dt: Float, out: XrInteractionOut) {
val wasTrigger = trigger[index]
val wasGrip = grip[index]
val wasSecondary = secondary[index]
trigger[index] = if (wasTrigger) hand.trigger > 0.4f else hand.trigger > 0.6f
grip[index] = if (wasGrip) hand.squeeze > 0.5f else hand.squeeze > 0.7f
secondary[index] = hand.secondary
val triggerDown = trigger[index] && !wasTrigger
val triggerUp = !trigger[index] && wasTrigger
val gripDown = grip[index] && !wasGrip
val secondaryDown = secondary[index] && !wasSecondary
val hold = holds[index]
if (!hand.active) {
if (hold is Hold.Press) out.events += XrPointerEvent.Cancel(hold.panel, index)
if (hold is Hold.Move) out.events += XrPointerEvent.Moved(hold.panel)
if (hold is Hold.Resize) out.events += XrPointerEvent.Resized(hold.panel)
holds[index] = Hold.None
return
}
val ray = hand.aim
when (hold) {
is Hold.Move -> {
val panel = hold.panel
if (abs(hand.stickY) > 0.2f) {
val length = hold.offset.length
val wanted = (length * (1f + hand.stickY * 1.2f * dt)).coerceIn(XrUnits.MIN_DISTANCE, XrUnits.MAX_DISTANCE)
hold.offset = hold.offset.normalized() * wanted
}
val position = ray.toWorld(hold.offset)
panel.pose = Pose(panel.kind.orient(position, head.position), position)
out.masks[index] = true
out.lasers[index] = hold.offset.length
val released = if (hold.byGrip) !grip[index] else !trigger[index]
if (released) {
holds[index] = Hold.None
out.events += XrPointerEvent.Moved(panel)
}
return
}
is Hold.Resize -> {
val panel = hold.panel
out.masks[index] = true
hold.panel.hitPlane(ray, bounded = false, plane = hold.plane, w = hold.width, h = hold.height)?.let { hit ->
val left = -hold.width / 2f
val top = hold.height / 2f
val width = (hold.width + hit.x - hold.startX).coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES)
val height = (hold.height + hold.startY - hit.y).coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES)
panel.width = width
panel.height = height
panel.pose = Pose(hold.plane.orientation, hold.plane.toWorld(Vec3(left + width / 2f, top - height / 2f, 0f)))
out.lasers[index] = hit.distance
}
if (!trigger[index]) {
holds[index] = Hold.None
out.events += XrPointerEvent.Resized(panel)
}
return
}
is Hold.Press -> {
val panel = hold.panel
out.masks[index] = true
val hit = panel.hitPlane(ray, bounded = false)
if (hit != null) {
val x = panel.pixelX(hit.x)
val y = panel.pixelY(hit.y)
if (x != hold.x || y != hold.y) out.events += XrPointerEvent.Move(panel, x, y, index)
hold.x = x; hold.y = y
out.lasers[index] = hit.distance
out.point(panel, x, y)
}
if (secondaryDown) out.events += XrPointerEvent.Back(panel)
if (triggerUp || !trigger[index]) {
out.events += if (hit != null) XrPointerEvent.Up(panel, hold.x, hold.y, index) else XrPointerEvent.Cancel(panel, index)
holds[index] = Hold.None
}
return
}
is Hold.HeadPress -> {
val panel = hold.panel
out.masks[index] = true
val hit = panel.hitPlane(ray, bounded = false)
if (hit != null) {
out.lasers[index] = hit.distance
val moved = Vec3(hit.x - hold.startX, hit.y - hold.startY, 0f).length
if (moved > HEAD_DRAG_METRES) {
holds[index] = Hold.Move(panel, hold.offset, byGrip = false)
val position = ray.toWorld(hold.offset)
panel.pose = Pose(panel.kind.orient(position, head.position), position)
return
}
}
if (!trigger[index]) {
holds[index] = Hold.None
if (panel.hit(ray) != null) out.events += XrPointerEvent.Click(panel)
}
return
}
Hold.None -> Unit
}
val hit = panels.mapNotNull { it.hit(ray) }.minByOrNull { it.distance } ?: return
val panel = hit.panel
out.masks[index] = true
out.lasers[index] = hit.distance
val x = panel.pixelX(hit.x)
val y = panel.pixelY(hit.y)
out.point(panel, x, y)
val other = holds[1 - index]
val heldByOther = held(other) === panel && other !is Hold.Press
when {
heldByOther -> Unit
gripDown -> {
holds[index] = Hold.Move(panel, ray.toLocal(panel.pose.position), byGrip = true)
out.ticks[index] = true
}
triggerDown && panel.kind == XrPanelKind.PET_HEAD ->
holds[index] = Hold.HeadPress(panel, hit.x, hit.y, ray.toLocal(panel.pose.position))
triggerDown && panel.inResizeGrip(hit) -> {
holds[index] = Hold.Resize(panel, panel.pose, panel.width, panel.height, hit.x, hit.y)
out.ticks[index] = true
}
triggerDown && panel.inBar(hit) && !panel.inBarButtons(hit) -> {
holds[index] = Hold.Move(panel, ray.toLocal(panel.pose.position), byGrip = false)
out.ticks[index] = true
}
triggerDown -> {
holds[index] = Hold.Press(panel, x, y)
out.events += XrPointerEvent.Down(panel, x, y, index)
}
}
if (holds[index] === Hold.None) {
if (abs(hand.stickY) > 0.25f) out.events += XrPointerEvent.Scroll(panel, x, y, hand.stickY * SCROLL_PER_SECOND * dt)
if (secondaryDown) out.events += XrPointerEvent.Back(panel)
}
}
companion object {
const val HEAD_DRAG_METRES = 0.02f
const val SCROLL_PER_SECOND = 12f
}
}
@@ -0,0 +1,283 @@
package com.droiddeck.launcher.session.xr
import android.view.KeyEvent
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Backspace
import androidx.compose.material.icons.automirrored.outlined.KeyboardReturn
import androidx.compose.material.icons.outlined.KeyboardArrowUp
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.EditCommand
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.ImeOptions
import androidx.compose.ui.text.input.PlatformTextInputService
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.input.PC_KEY_ROWS
import kotlinx.coroutines.delay
import com.droiddeck.launcher.ui.TypingRequest
/** Sends text fields in the floating panels to [XrKeyboard], since the system keyboard cannot show in the immersive view. */
internal class XrTextInput : PlatformTextInputService {
private var request: TypingRequest? = null
override fun startInput(
value: TextFieldValue, imeOptions: ImeOptions,
onEditCommand: (List<EditCommand>) -> Unit, onImeActionPerformed: (ImeAction) -> Unit,
) {
val next = TypingRequest(value, imeOptions, { onEditCommand(TypingRequest.editsFor(it)) }, onImeActionPerformed)
request = next
XrPanels.startTyping(next)
}
override fun stopInput() {
request?.let { XrPanels.stopTyping(it) }
request = null
}
override fun showSoftwareKeyboard() {
request?.let { XrPanels.startTyping(it) }
}
override fun hideSoftwareKeyboard() {
request?.let { XrPanels.stopTyping(it) }
}
override fun updateState(oldValue: TextFieldValue?, newValue: TextFieldValue) {
request?.value = newValue
}
}
internal object XrKeys {
private val letters = listOf("qwertyuiop", "asdfghjkl", "zxcvbnm")
private val symbols = listOf("1234567890", "@#&*-+=()", "!?:;'\"/,")
fun rows(numbers: Boolean, shift: Boolean): List<String> =
(if (numbers) symbols else letters).map { if (shift && !numbers) it.uppercase() else it }
fun insert(value: TextFieldValue, text: String): TextFieldValue {
val start = minOf(value.selection.start, value.selection.end)
val end = maxOf(value.selection.start, value.selection.end)
val next = value.text.substring(0, start) + text + value.text.substring(end)
return TextFieldValue(next, TextRange(start + text.length))
}
fun backspace(value: TextFieldValue): TextFieldValue {
val start = minOf(value.selection.start, value.selection.end)
val end = maxOf(value.selection.start, value.selection.end)
if (start != end) return TextFieldValue(value.text.substring(0, start) + value.text.substring(end), TextRange(start))
if (start == 0) return value
val cut = value.text.offsetByCodePoints(start, -1)
return TextFieldValue(value.text.substring(0, cut) + value.text.substring(start), TextRange(cut))
}
const val REPEAT_DELAY_MS = 450L
const val REPEAT_MS = 50L
/** Return sends when the field asks for an action, and starts a new line otherwise. */
fun returnSends(options: ImeOptions) = options.imeAction != ImeAction.Default && options.imeAction != ImeAction.None &&
options.singleLine
}
/** Where the laser keyboard's keys go: a text field in a panel, or the game. */
internal interface XrKeyTarget {
fun type(text: String)
fun backspace()
fun enter()
}
internal class XrFieldTarget(private val request: TypingRequest) : XrKeyTarget {
override fun type(text: String) = request.send(XrKeys.insert(request.value, text))
override fun backspace() = request.send(XrKeys.backspace(request.value))
override fun enter() = if (XrKeys.returnSends(request.imeOptions)) request.action() else type("\n")
}
internal class XrGameTarget(private val host: XrMenuHost) : XrKeyTarget {
override fun type(text: String) = host.xrTypeText(text)
override fun backspace() = host.xrTapKey(KeyEvent.KEYCODE_DEL)
override fun enter() = host.xrTapKey(KeyEvent.KEYCODE_ENTER)
}
/**
* DroidDeck's PC keyboard typing into a panel's text field: the keys that make a character type it,
* Backspace, Enter and Space edit, and Shift and Caps Lock pick the case. The rest have nothing to do there.
*/
internal class XrPcText(private val target: XrKeyTarget, private val timer: XrTimer = XrTimer.Main) {
private val keys = PC_KEY_ROWS.flatten()
.filter { it.labelRes == 0 && it.label.length == 1 && it.code !in ARROWS }
.associateBy { it.code }
private val shifts = mutableSetOf<Int>()
private var caps = false
private var stopRepeat: (() -> Unit)? = null
fun key(code: Int, down: Boolean) {
if (code == LEFT_SHIFT || code == RIGHT_SHIFT) {
if (down) shifts += code else shifts -= code
return
}
if (!down && code != BACKSPACE) return
stopRepeat?.invoke()
stopRepeat = null
if (!down) return
val shifted = shifts.isNotEmpty()
when (code) {
BACKSPACE -> {
target.backspace()
stopRepeat = timer.after(XrKeys.REPEAT_DELAY_MS, ::repeatBackspace)
}
ENTER -> target.enter()
SPACE -> target.type(" ")
CAPS -> caps = !caps
else -> keys[code]?.let { key ->
target.type(when {
shifted && key.shifted != null -> key.shifted
key.label[0].isLetter() && (shifted xor caps) -> key.label.uppercase()
else -> key.label
})
}
}
}
private fun repeatBackspace() {
target.backspace()
stopRepeat = timer.after(XrKeys.REPEAT_MS, ::repeatBackspace)
}
private companion object {
const val LEFT_SHIFT = 42
const val RIGHT_SHIFT = 54
const val BACKSPACE = 14
const val ENTER = 28
const val SPACE = 57
const val CAPS = 58
val ARROWS = setOf(103, 105, 106, 108)
}
}
/** Runs an action later on the main thread; the function it returns cancels it. */
internal fun interface XrTimer {
fun after(ms: Long, action: () -> Unit): () -> Unit
companion object {
private val handler by lazy { android.os.Handler(android.os.Looper.getMainLooper()) }
val Main = XrTimer { ms, action ->
val runnable = Runnable(action)
handler.postDelayed(runnable, ms)
({ handler.removeCallbacks(runnable) })
}
}
}
/** The Android-style text keyboard. */
@Composable
internal fun XrKeyboard(target: XrKeyTarget) {
var shift by remember { mutableStateOf(false) }
var numbers by remember { mutableStateOf(false) }
fun type(text: String) {
target.type(text)
if (shift) shift = false
}
Column(Modifier.fillMaxSize().padding(8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
XrKeys.rows(numbers, shift).forEachIndexed { index, row ->
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
if (index == 2) KeyIcon(Icons.Outlined.KeyboardArrowUp, stringResource(R.string.pckb_key_shift), active = shift, weight = 1.5f) { shift = !shift }
row.forEach { key -> Key(key.toString()) { type(key.toString()) } }
if (index == 2) KeyIcon(Icons.AutoMirrored.Outlined.Backspace, stringResource(R.string.pckb_key_backspace), weight = 1.5f, repeats = true) { target.backspace() }
}
}
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Key(if (numbers) "abc" else "?123", weight = 1.5f) { numbers = !numbers }
Key(",") { type(",") }
Key(" ", weight = 5f) { type(" ") }
Key(".") { type(".") }
KeyIcon(Icons.AutoMirrored.Outlined.KeyboardReturn, stringResource(R.string.pckb_key_enter), weight = 1.5f) { target.enter() }
}
}
}
/** A key that lights while the laser is over it and dips while it is pressed; [repeats] keeps acting while held. */
@Composable
private fun RowScope.KeyBox(
weight: Float, active: Boolean, onClick: () -> Unit, repeats: Boolean = false, content: @Composable (Color) -> Unit,
) {
val colors = MaterialTheme.colorScheme
val source = remember { MutableInteractionSource() }
val (pointedAt, pointed) = rememberXrPointed()
val hovered = pointed.value
val pressed by source.collectIsPressedAsState()
val action by rememberUpdatedState(onClick)
var repeated by remember { mutableStateOf(false) }
if (repeats) LaunchedEffect(pressed) {
if (!pressed) return@LaunchedEffect
repeated = false
delay(XrKeys.REPEAT_DELAY_MS)
repeated = true
while (true) {
action()
delay(XrKeys.REPEAT_MS)
}
}
val fill by animateColorAsState(
when {
pressed -> colors.primary
active -> colors.primary.copy(alpha = 0.8f)
hovered -> colors.onSurface.copy(alpha = 0.22f).compositeOver(colors.surfaceVariant)
else -> colors.surfaceVariant
}, tween(if (pressed) 40 else 140), label = "keyFill",
)
val scale by animateFloatAsState(if (pressed) 0.9f else if (hovered) 1.05f else 1f, tween(if (pressed) 40 else 140), label = "keyScale")
Box(
Modifier.weight(weight).fillMaxHeight()
.then(pointedAt)
.graphicsLayer { scaleX = 1f + (scale - 1f) * size.height / size.width; scaleY = scale }
.clip(RoundedCornerShape(8.dp)).background(fill)
.border(if (hovered) 2.dp else 0.dp, if (hovered) colors.primary else Color.Transparent, RoundedCornerShape(8.dp))
.clickable(interactionSource = source, indication = null) { if (repeated) repeated = false else onClick() },
contentAlignment = Alignment.Center,
) { content(if (pressed || active) colors.onPrimary else colors.onSurface) }
}
@Composable
private fun RowScope.Key(label: String, weight: Float = 1f, onClick: () -> Unit) =
KeyBox(weight, active = false, onClick) { tint -> Text(label, color = tint, fontSize = 22.sp, maxLines = 1) }
@Composable
private fun RowScope.KeyIcon(icon: ImageVector, label: String, active: Boolean = false, weight: Float = 1f, repeats: Boolean = false, onClick: () -> Unit) =
KeyBox(weight, active, onClick, repeats) { tint -> Icon(icon, label, tint = tint) }
@@ -0,0 +1,61 @@
package com.droiddeck.launcher.session.xr
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
internal data class Vec3(val x: Float, val y: Float, val z: Float) {
operator fun plus(o: Vec3) = Vec3(x + o.x, y + o.y, z + o.z)
operator fun minus(o: Vec3) = Vec3(x - o.x, y - o.y, z - o.z)
operator fun times(s: Float) = Vec3(x * s, y * s, z * s)
infix fun dot(o: Vec3) = x * o.x + y * o.y + z * o.z
infix fun cross(o: Vec3) = Vec3(y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x)
val length: Float get() = sqrt(this dot this)
fun normalized(): Vec3 = length.let { if (it > 1e-6f) this * (1f / it) else ZERO }
companion object {
val ZERO = Vec3(0f, 0f, 0f)
val FORWARD = Vec3(0f, 0f, -1f)
val UP = Vec3(0f, 1f, 0f)
fun lerp(a: Vec3, b: Vec3, t: Float) = a + (b - a) * t
}
}
internal data class Quat(val x: Float, val y: Float, val z: Float, val w: Float) {
fun rotate(v: Vec3): Vec3 {
val u = Vec3(x, y, z)
return u * (2f * (u dot v)) + v * (w * w - (u dot u)) + (u cross v) * (2f * w)
}
fun conjugate() = Quat(-x, -y, -z, w)
operator fun times(o: Quat) = Quat(
w * o.x + x * o.w + y * o.z - z * o.y,
w * o.y - x * o.z + y * o.w + z * o.x,
w * o.z + x * o.y - y * o.x + z * o.w,
w * o.w - x * o.x - y * o.y - z * o.z,
)
companion object {
val IDENTITY = Quat(0f, 0f, 0f, 1f)
fun yaw(radians: Float) = Quat(0f, sin(radians / 2f), 0f, cos(radians / 2f))
fun pitch(radians: Float) = Quat(sin(radians / 2f), 0f, 0f, cos(radians / 2f))
}
}
internal data class Pose(val orientation: Quat = Quat.IDENTITY, val position: Vec3 = Vec3.ZERO) {
val forward: Vec3 get() = orientation.rotate(Vec3.FORWARD)
fun toLocal(world: Vec3): Vec3 = orientation.conjugate().rotate(world - position)
fun toWorld(local: Vec3): Vec3 = position + orientation.rotate(local)
}
/** Yaw of a direction in the horizontal plane, 0 along -Z, matching [Quat.yaw] applied to -Z. */
internal fun yawOf(direction: Vec3): Float = atan2(-direction.x, -direction.z)
/** An orientation that turns +Z, the side of a quad that shows, from [position] towards [target] about the vertical axis only. */
internal fun facing(position: Vec3, target: Vec3): Quat {
val d = target - position
if (d.x * d.x + d.z * d.z < 1e-8f) return Quat.IDENTITY
return Quat.yaw(atan2(d.x, d.z))
}
@@ -0,0 +1,126 @@
package com.droiddeck.launcher.session.xr
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Remove
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.boundsInWindow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/**
* The frame of a floating panel: the content, a bar under it to grab it by with up to two buttons at
* its left end, a corner grip to resize it, and the dot where a controller points. Its sizes match [XrUnits].
*/
@Composable
internal fun XrPanelChrome(
cursor: State<List<Pair<Float, Float>>>,
buttons: List<XrPanelButton>,
resizable: Boolean,
content: @Composable () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val shape = RoundedCornerShape(18.dp)
Box(Modifier.fillMaxSize().clip(shape).background(colors.background).border(1.dp, Color(0x33FFFFFF), shape)) {
Column(Modifier.fillMaxSize()) {
Box(Modifier.weight(1f).fillMaxWidth().padding(start = 10.dp, top = 10.dp, end = 10.dp)) {
CompositionLocalProvider(LocalXrPointers provides cursor) { content() }
}
Box(
Modifier.fillMaxWidth().height(52.dp).background(colors.surfaceVariant.copy(alpha = 0.6f)),
contentAlignment = Alignment.Center,
) {
Box(Modifier.width(72.dp).height(6.dp).clip(CircleShape).background(colors.onSurface.copy(alpha = 0.35f)))
if (buttons.isNotEmpty()) Row(
Modifier.align(Alignment.CenterStart).width(XrUnits.BAR_BUTTONS_DP.dp).padding(start = 8.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
buttons.take(2).forEach { button ->
if (button.icon != null) IconButton(onClick = button.onClick, modifier = Modifier.size(44.dp)) {
Icon(button.icon, button.label, tint = colors.onSurface)
} else TextButton(onClick = button.onClick, modifier = Modifier.height(40.dp), contentPadding = PaddingValues(horizontal = 10.dp)) {
Text(button.label, color = colors.onSurface, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1)
}
}
}
}
}
if (resizable) Canvas(Modifier.align(Alignment.BottomEnd).padding(6.dp).size(28.dp)) {
val stroke = Stroke(width = 3.dp.toPx())
for (step in 1..3) {
val inset = size.width * step / 4f
drawLine(Color(0x99FFFFFF), Offset(size.width, inset), Offset(inset, size.height), stroke.width)
}
}
val density = LocalDensity.current
Canvas(Modifier.fillMaxSize()) {
val radius = with(density) { 7.dp.toPx() }
for ((x, y) in cursor.value) {
drawCircle(Color(0xCC1E9EFF), radius, Offset(x, y))
drawCircle(Color.White, radius, Offset(x, y), style = Stroke(with(density) { 2.dp.toPx() }))
}
}
}
}
/** Where each laser meets the panel, in the panel's pixels; null off a floating panel. */
internal val LocalXrPointers = staticCompositionLocalOf<State<List<Pair<Float, Float>>>?> { null }
/**
* Whether a laser rests on the element the returned [Modifier] is put on, for both controllers at
* once, where a mouse hover has room for one. False off a floating panel.
*/
@Composable
internal fun rememberXrPointed(): Pair<Modifier, State<Boolean>> {
val pointers = LocalXrPointers.current
var bounds by remember { mutableStateOf(Rect.Zero) }
val pointed = remember(pointers) {
derivedStateOf { pointers != null && pointers.value.any { (x, y) -> bounds.contains(Offset(x, y)) } }
}
return Modifier.onGloballyPositioned { bounds = it.boundsInWindow() } to pointed
}
/** With no [icon] the button shows [label] itself, for a short word such as a keyboard mode. */
internal class XrPanelButton(val icon: ImageVector?, val label: String, val onClick: () -> Unit)
internal val XrCollapseIcon get() = Icons.Outlined.Remove
@@ -0,0 +1,271 @@
package com.droiddeck.launcher.session.xr
import android.app.Presentation
import android.content.Context
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.os.Bundle
import android.os.SystemClock
import android.view.InputDevice
import android.view.MotionEvent
import android.view.Surface
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inspector.WindowInspector
import android.widget.FrameLayout
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalTextInputService
import androidx.compose.ui.text.input.TextInputService
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.activity.OnBackPressedDispatcher
import androidx.activity.OnBackPressedDispatcherOwner
import androidx.activity.setViewTreeOnBackPressedDispatcherOwner
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.lifecycle.setViewTreeViewModelStoreOwner
import androidx.savedstate.SavedStateRegistry
import androidx.savedstate.SavedStateRegistryController
import androidx.savedstate.SavedStateRegistryOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.droiddeck.launcher.ui.LocalPresentationWindow
/** Keeps a panel's Compose content running while the activity that made it is stopped behind the XR view. */
private class PanelOwner : LifecycleOwner, SavedStateRegistryOwner, ViewModelStoreOwner, OnBackPressedDispatcherOwner {
private val registry = LifecycleRegistry(this)
private val saved = SavedStateRegistryController.create(this)
override val lifecycle: Lifecycle get() = registry
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
override val viewModelStore = ViewModelStore()
override val onBackPressedDispatcher = OnBackPressedDispatcher()
fun own(view: View) {
view.setViewTreeLifecycleOwner(this)
view.setViewTreeSavedStateRegistryOwner(this)
view.setViewTreeViewModelStoreOwner(this)
view.setViewTreeOnBackPressedDispatcherOwner(this)
}
init {
saved.performRestore(null)
registry.currentState = Lifecycle.State.RESUMED
}
fun destroy() {
registry.currentState = Lifecycle.State.DESTROYED
viewModelStore.clear()
}
}
/**
* One floating panel's Android side: a private virtual display drawing into the panel's OpenXR
* surface, and a presentation on it holding the Compose content. Main thread only.
*/
internal class XrPanelWindow(
private val context: Context,
private var surface: Surface,
width: Int,
height: Int,
startPaused: Boolean,
private val content: @Composable () -> Unit,
) {
private var paused = startPaused
private val owner = PanelOwner()
private val textInput = TextInputService(XrTextInput())
private val display: VirtualDisplay = context.getSystemService(DisplayManager::class.java).createVirtualDisplay(
"DroidDeck XR panel", width, height, XrUnits.DPI, surface.takeUnless { paused }, DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY,
)
private val presentation = PanelPresentation(context, display.display)
private var downTime = 0L
private var target: View? = null
/** The controllers pressing the panel, by hand, as fingers of one touch. */
private val touches = linkedMapOf<Int, Pair<Float, Float>>()
private var hovering: View? = null
private var hoverAt = 0f to 0f
private var cursor: Pair<Float, Float>? = null
init {
try {
presentation.show()
} catch (failure: RuntimeException) {
release()
throw failure
}
}
val displayId: Int get() = display.display.displayId
fun resize(surface: Surface, width: Int, height: Int) {
this.surface = surface
if (!paused) display.surface = surface
display.resize(width, height, XrUnits.DPI)
}
/** Stops drawing into the panel's layer, or starts again. */
fun pause(pause: Boolean) {
if (pause == paused) return
paused = pause
display.surface = if (pause) null else surface
}
fun release() {
runCatching { presentation.dismiss() }
owner.destroy()
display.release()
}
private inner class PanelPresentation(outer: Context, display: android.view.Display) : Presentation(outer, display) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window?.setBackgroundDrawableResource(android.R.color.transparent)
window?.addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED)
val compose = ComposeView(context).apply {
owner.own(this)
setContent {
CompositionLocalProvider(
LocalPresentationWindow provides true,
LocalTextInputService provides textInput,
) { content() }
}
}
val frame = FrameLayout(context).apply {
addView(compose, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
}
setContentView(frame)
window?.decorView?.let(owner::own)
}
}
/**
* The topmost window on this panel's display under the point, so popups and dialogs get the input.
* A focusable popup or dialog on top takes a press outside it too, as on a touchscreen, where it
* dismisses itself rather than letting the press act on what is behind it.
*/
private fun rootAt(x: Float, y: Float): View? {
val roots = WindowInspector.getGlobalWindowViews().filter { it.isAttachedToWindow && it.display?.displayId == displayId && it.isShown }
val location = IntArray(2)
fun contains(root: View): Boolean {
root.getLocationOnScreen(location)
return x >= location[0] && y >= location[1] && x < location[0] + root.width && y < location[1] + root.height
}
val top = roots.lastOrNull() ?: return null
val focusable = (top.layoutParams as? WindowManager.LayoutParams)
?.let { it.flags and WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE == 0 } ?: false
if (roots.size > 1 && focusable && !contains(top)) return top
return roots.lastOrNull(::contains) ?: top
}
/** Sends every finger in [touches] to [target]; [action] is already shifted by its pointer index where it needs one. */
private fun sendTouches(action: Int, time: Long) {
val view = target ?: return
val location = IntArray(2)
view.getLocationOnScreen(location)
val properties = touches.keys.map { hand ->
MotionEvent.PointerProperties().apply { id = hand; toolType = MotionEvent.TOOL_TYPE_FINGER }
}.toTypedArray()
val coords = touches.values.map { (x, y) ->
MotionEvent.PointerCoords().apply { this.x = x - location[0]; this.y = y - location[1]; pressure = 1f; size = 1f }
}.toTypedArray()
val event = MotionEvent.obtain(downTime, time, action, touches.size, properties, coords, 0, 0, 1f, 1f, 0, 0,
InputDevice.SOURCE_TOUCHSCREEN, 0)
try {
view.dispatchTouchEvent(event)
} finally {
event.recycle()
}
}
private fun indexed(action: Int, hand: Int) =
action or (touches.keys.indexOf(hand) shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
private fun send(view: View, action: Int, x: Float, y: Float, time: Long, generic: Boolean, scroll: Float = 0f): Boolean {
val location = IntArray(2)
view.getLocationOnScreen(location)
val properties = arrayOf(MotionEvent.PointerProperties().apply {
id = 0
toolType = if (generic) MotionEvent.TOOL_TYPE_MOUSE else MotionEvent.TOOL_TYPE_FINGER
})
val coords = arrayOf(MotionEvent.PointerCoords().apply {
this.x = x - location[0]
this.y = y - location[1]
pressure = 1f
size = 1f
if (scroll != 0f) setAxisValue(MotionEvent.AXIS_VSCROLL, scroll)
})
val source = if (generic) InputDevice.SOURCE_MOUSE else InputDevice.SOURCE_TOUCHSCREEN
val event = MotionEvent.obtain(if (generic) time else downTime, time, action, 1, properties, coords, 0, 0, 1f, 1f, 0, 0, source, 0)
return try {
if (generic) view.dispatchGenericMotionEvent(event) else view.dispatchTouchEvent(event)
} finally {
event.recycle()
}
}
/** The laser resting on the panel, as a mouse hovering, so keys and buttons light under it. Null: it left. */
fun hover(at: Pair<Float, Float>?) {
cursor = at
if (target != null) return
val now = SystemClock.uptimeMillis()
val root = at?.let { (x, y) -> rootAt(x, y) }
if (root !== hovering) endHover(now)
if (root == null || at == null) return
if (hovering == null) send(root, MotionEvent.ACTION_HOVER_ENTER, at.first, at.second, now, generic = true)
send(root, MotionEvent.ACTION_HOVER_MOVE, at.first, at.second, now, generic = true)
hovering = root
hoverAt = at
}
private fun endHover(now: Long) {
hovering?.let { send(it, MotionEvent.ACTION_HOVER_EXIT, hoverAt.first, hoverAt.second, now, generic = true) }
hovering = null
}
fun pointer(event: XrPointerEvent) {
val now = SystemClock.uptimeMillis()
when (event) {
is XrPointerEvent.Down -> {
if (event.hand in touches) return
touches[event.hand] = event.x to event.y
if (touches.size == 1) {
endHover(now)
downTime = now
target = rootAt(event.x, event.y)
sendTouches(MotionEvent.ACTION_DOWN, now)
} else sendTouches(indexed(MotionEvent.ACTION_POINTER_DOWN, event.hand), now)
}
is XrPointerEvent.Move -> {
if (event.hand !in touches) return
touches[event.hand] = event.x to event.y
sendTouches(MotionEvent.ACTION_MOVE, now)
}
is XrPointerEvent.Up -> {
if (event.hand !in touches) return
touches[event.hand] = event.x to event.y
if (touches.size > 1) {
sendTouches(indexed(MotionEvent.ACTION_POINTER_UP, event.hand), now)
touches -= event.hand
} else {
sendTouches(MotionEvent.ACTION_UP, now)
touches.clear()
target = null
hover(cursor)
}
}
is XrPointerEvent.Cancel -> {
if (event.hand !in touches) return
sendTouches(MotionEvent.ACTION_CANCEL, now)
touches.clear()
target = null
}
is XrPointerEvent.Scroll -> rootAt(event.x, event.y)?.let {
send(it, MotionEvent.ACTION_SCROLL, event.x, event.y, now, generic = true, scroll = event.amount)
}
else -> Unit
}
}
}
@@ -0,0 +1,611 @@
package com.droiddeck.launcher.session.xr
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import android.view.Surface
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.KeyboardHide
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentHost
import com.droiddeck.launcher.session.QuestExperimental
import com.droiddeck.launcher.ui.AgentPage
import com.droiddeck.launcher.ui.AgentPet
import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.ui.PcKeyboard
import com.droiddeck.launcher.ui.PetFigure
import com.droiddeck.launcher.ui.TypingRequest
import com.droiddeck.launcher.ui.petStateNow
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import java.lang.ref.WeakReference
import java.nio.ByteBuffer
import java.util.concurrent.ConcurrentLinkedQueue
import kotlin.math.PI
/** The 2D session window, which hands its menu to the immersive view while that is open. */
internal interface XrMenuHost {
@Composable
fun XrMenuContent()
fun xrSetMenuOpen(open: Boolean)
fun xrMenuBack()
/** A key of DroidDeck's PC keyboard, by Linux key code, to the game. */
fun xrSendKey(code: Int, down: Boolean)
/** Text from the laser keyboard to the game, as the Android keyboard sends it. */
fun xrTypeText(text: String)
fun xrTapKey(keyCode: Int)
/** The immersive view opened or closed; Steam's screen, which SteamVR mirrors as its Steam window, sizes for it. */
fun xrImmersiveChanged(active: Boolean)
}
/** What the immersive view's native loop offers: surface-backed layers it composites in front of the game. */
internal interface XrLayerSource {
val context: Context
fun createLayer(width: Int, height: Int): Int
fun layerSurface(id: Int): Surface?
fun destroyLayer(id: Int)
fun setOrbImage(image: android.graphics.Bitmap)
fun leave()
}
/**
* DroidDeck's own windows inside the immersive Quest view: the session menu, opened by holding the
* controllers together, and the agent pet with its chat. Quest only. [frame] runs on the XR thread
* each frame; the rest runs on the main thread.
*/
internal object XrPanels {
private const val TAG = "XrPanels"
private const val OPEN_MS = 350f
private const val CLOSE_MS = 250f
private const val BURST_MS = 400f
/** The immersive view is up, so the menu and pet belong in it. Always false off Quest. */
@Volatile
var immersiveActive = false
/** Counts attachments, so work posted from one immersive view is dropped once a later one, or none, is up. */
@Volatile
private var attachment = 0
private set
private val main = Handler(Looper.getMainLooper())
/** Whether the headset shows the session; panels draw into their layers only then. */
@Volatile
private var drawing = false
private val lock = Any()
private val ops = ConcurrentLinkedQueue<() -> Unit>()
private var source: XrLayerSource? = null
private var host: XrHost? = null
private var menuHost: WeakReference<XrMenuHost>? = null
private var scope: CoroutineScope? = null
private class Panel(val state: XrPanelState, val content: @Composable (State<List<Pair<Float, Float>>>) -> Unit) {
val cursorState = mutableStateOf<List<Pair<Float, Float>>>(emptyList())
var layerId = -1
var window: XrPanelWindow? = null
var openedMs = 0L
var closingMs = 0L
var resizing = false
var cursor: List<Pair<Float, Float>> = emptyList()
}
private val panels = mutableListOf<Panel>()
private val gesture = XrGesture()
private val interaction = XrInteraction()
private var lastFrameMs = 0L
private var orbImageSent = false
private var lastHead = Pose()
private var burstMs = 0L
private var burstAt = Vec3.ZERO
private var lastTick = 0
private var menuFrom: Vec3? = null
private val typing = mutableStateOf<TypingRequest?>(null)
/** The keyboard was opened for the game, from the session menu; a panel's text field takes it over while it types. */
private val gameKeyboard = mutableStateOf(false)
private val pcKeyboard = mutableStateOf(false)
fun gateOpen(model: String, device: String, manufacturer: String, immersive: Boolean) =
immersive && QuestExperimental.supported(model, device, manufacturer)
fun setMenuHost(menu: XrMenuHost?) {
menuHost = menu?.let { WeakReference(it) }
if (immersiveActive) menu?.xrImmersiveChanged(true)
}
fun clearMenuHost(menu: XrMenuHost) {
if (menuHost?.get() === menu) menuHost = null
}
/** Main thread: the immersive view handed over its buffers. */
fun attach(layers: XrLayerSource, state: ByteBuffer, control: ByteBuffer) {
if (!QuestExperimental.isSupported()) return
synchronized(lock) {
source = layers
host = XrHost(state, control)
orbImageSent = false
}
attachment++
immersiveActive = true
menuHost?.get()?.xrImmersiveChanged(true)
scope?.cancel()
scope = MainScope().also { scope ->
scope.launch {
snapshotFlow { com.droiddeck.launcher.agent.AgentGuest.focusRevision }.collect {
menuHost?.get()?.xrImmersiveChanged(true)
}
}
scope.launch {
snapshotFlow { AgentPet.enabled && AgentHost.installed }.collect { on ->
if (on) { if (!shown(XrPanelKind.PET_CHAT)) open(XrPanelKind.PET_HEAD) }
else { close(XrPanelKind.PET_HEAD); close(XrPanelKind.PET_CHAT) }
}
}
}
}
/**
* XR thread, as the session becomes visible or stops being so. OpenXR allows writing into a surface
* swapchain only while the session is visible or focused, and requires the writes to have stopped
* before xrEndSession, so this returns once the panels have stopped or started drawing.
*/
fun setDrawing(visible: Boolean) {
val done = java.util.concurrent.CountDownLatch(1)
val apply = Runnable {
try {
drawing = visible
synchronized(lock) { panels.mapNotNull { it.window } }.forEach { it.pause(!visible) }
} finally {
done.countDown()
}
}
if (Looper.myLooper() == Looper.getMainLooper()) apply.run()
else if (main.post(apply) && !done.await(1, java.util.concurrent.TimeUnit.SECONDS))
Log.w(TAG, "panels did not ${if (visible) "start" else "stop"} drawing within a second")
}
/** Main thread: the immersive view is going; every panel goes with it. */
fun detach() {
if (!immersiveActive) return
immersiveActive = false
scope?.cancel()
scope = null
val windows = synchronized(lock) {
source = null
host = null
ops.clear()
interaction.reset()
panels.mapNotNull { it.window }.also { panels.clear() }
}
windows.forEach { it.release() }
typing.value = null
gameKeyboard.value = false
gesture.reset(release = false)
menuHost?.get()?.xrSetMenuOpen(false)
menuHost?.get()?.xrImmersiveChanged(false)
}
/** Main thread, from the session window's menu state. */
fun showMenu(): Boolean {
if (!immersiveActive) return false
open(XrPanelKind.MENU, menuFrom)
menuFrom = null
return true
}
fun hideMenu() = close(XrPanelKind.MENU)
/** Main thread: closes the immersive view, as a stop chosen in its menu asks. */
fun leaveImmersive() {
synchronized(lock) { source }?.leave()
}
/** Main thread: a text field in a panel wants typing, so the laser keyboard opens. */
fun startTyping(request: TypingRequest) {
if (!immersiveActive) return
typing.value = request
open(XrPanelKind.KEYBOARD)
}
fun stopTyping(request: TypingRequest) {
if (typing.value !== request) return
typing.value = null
if (!gameKeyboard.value) close(XrPanelKind.KEYBOARD)
}
/**
* Main thread: the session menu's keyboards. [pc] picks DroidDeck's PC keyboard over the Android-style one;
* asking again for the one already open closes it. False off the immersive view, where the 2D keyboards stay.
*/
fun toggleGameKeyboard(pc: Boolean): Boolean {
if (!immersiveActive) return false
if (gameKeyboard.value && pcKeyboard.value == pc && shown(XrPanelKind.KEYBOARD)) hideKeyboard()
else showGameKeyboard(pc)
return true
}
fun showGameKeyboard(pc: Boolean): Boolean {
if (!immersiveActive) return false
gameKeyboard.value = true
pcKeyboard.value = pc
open(XrPanelKind.KEYBOARD)
return true
}
private fun hideKeyboard() {
typing.value = null
gameKeyboard.value = false
close(XrPanelKind.KEYBOARD)
}
private fun shown(kind: XrPanelKind) = synchronized(lock) { panels.any { it.state.kind == kind && it.closingMs == 0L } }
private fun open(kind: XrPanelKind, from: Vec3? = null) {
ops += { create(kind, from) }
}
private fun close(kind: XrPanelKind) {
ops += {
panels.filter { it.state.kind == kind && it.closingMs == 0L }.forEach { panel ->
panel.closingMs = SystemClock.uptimeMillis()
val out = XrInteractionOut()
interaction.release(panel.state, out)
dispatch(out)
}
}
}
/** XR thread. */
private fun create(kind: XrPanelKind, from: Vec3?) {
val layers = source ?: return
panels.firstOrNull { it.state.kind == kind }?.let { existing ->
if (existing.closingMs != 0L) {
existing.closingMs = 0L
val elapsed = 1f - Math.cbrt((1.0 - existing.state.scale).coerceIn(0.0, 1.0)).toFloat()
existing.openedMs = SystemClock.uptimeMillis() - (elapsed * OPEN_MS).toLong()
}
return
}
val placed = XrPlacement.load(layers.context, kind, lastHead)
val state = XrPanelState(kind, placed.pose, placed.width, placed.height)
state.scale = 0f
state.animationFrom = from ?: placed.pose.position
val id = layers.createLayer(state.pixelWidth, state.pixelHeight)
val surface = if (id >= 0) layers.layerSurface(id) else null
if (surface == null) {
Log.w(TAG, "no layer for the ${kind.key} panel")
if (id >= 0) layers.destroyLayer(id)
if (kind == XrPanelKind.MENU) main.post { menuHost?.get()?.xrSetMenuOpen(false) }
return
}
val panel = Panel(state, contentFor(kind))
panel.layerId = id
panel.openedMs = SystemClock.uptimeMillis()
panels += panel
val context = layers.context
main.post {
synchronized(lock) {
if (panel !in panels) return@post
panel.window = runCatching {
XrPanelWindow(context, surface, state.pixelWidth, state.pixelHeight, startPaused = !drawing) {
panel.content(panel.cursorState)
}
}.onFailure {
Log.w(TAG, "could not show the ${kind.key} panel", it)
panels -= panel
ops += { if (source === layers) layers.destroyLayer(id) }
if (kind == XrPanelKind.MENU) menuHost?.get()?.xrSetMenuOpen(false)
}.getOrNull()
}
}
}
private fun contentFor(kind: XrPanelKind): @Composable (State<List<Pair<Float, Float>>>) -> Unit = when (kind) {
XrPanelKind.MENU -> { cursor ->
DroidDeckTheme {
XrPanelChrome(cursor, buttons = emptyList(), resizable = true) {
menuHost?.get()?.XrMenuContent()
}
}
}
XrPanelKind.PET_HEAD -> { _ ->
DroidDeckTheme { Box(Modifier.fillMaxSize()) { PetFigure(petStateNow(), Modifier.fillMaxSize()) } }
}
XrPanelKind.KEYBOARD -> { cursor ->
DroidDeckTheme {
val buttons = listOf(
XrPanelButton(Icons.Outlined.KeyboardHide, stringResource(R.string.pckb_hide), ::hideKeyboard),
XrPanelButton(null, if (pcKeyboard.value) "Android" else "PC") { pcKeyboard.value = !pcKeyboard.value },
)
XrPanelChrome(cursor, buttons, resizable = true) { KeyboardContent() }
}
}
XrPanelKind.PET_CHAT -> { cursor ->
DroidDeckTheme {
XrPanelChrome(cursor, listOf(XrPanelButton(XrCollapseIcon, stringResource(R.string.bottom_chat_close), ::collapseChat)), resizable = true) {
AgentPage(Modifier.fillMaxSize().padding(horizontal = 12.dp), visible = true, startTyping = false, hidesPet = false)
}
}
}
}
/** A panel's text field takes the keyboard while it types; otherwise its keys go to the game. */
@Composable
private fun KeyboardContent() {
val request = typing.value
val host = menuHost?.get()?.takeIf { gameKeyboard.value }
val target = request?.let(::XrFieldTarget) ?: host?.let(::XrGameTarget) ?: return
if (pcKeyboard.value) {
val pcText = remember(request) { request?.let { XrPcText(XrFieldTarget(it)) } }
PcKeyboard(
sendKey = { code, down -> pcText?.key(code, down) ?: host?.xrSendKey(code, down) },
onAndroidKeyboard = { pcKeyboard.value = false },
onClose = ::hideKeyboard,
heightFraction = 1f,
showButtons = false,
hoverFeedback = true,
)
} else XrKeyboard(target)
}
private fun collapseChat() {
close(XrPanelKind.PET_CHAT)
open(XrPanelKind.PET_HEAD)
}
private fun expandChat(from: Vec3) {
close(XrPanelKind.PET_HEAD)
open(XrPanelKind.PET_CHAT, from)
}
/** XR thread, once per frame, from QuestXrActivity.onXrHostFrame. */
fun frame() = synchronized(lock) {
val host = host ?: return
val layers = source ?: return
val frame = host.read()
lastHead = frame.head
while (true) (ops.poll() ?: break).invoke()
if (!orbImageSent) {
orbImageSent = true
runCatching {
android.graphics.BitmapFactory.decodeResource(layers.context.resources, R.drawable.logo)
}.getOrNull()?.let { layers.setOrbImage(it); it.recycle() }
}
val now = SystemClock.uptimeMillis()
val dt = if (lastFrameMs == 0L) 0f else ((now - lastFrameMs) / 1000f).coerceIn(0f, 0.1f)
lastFrameMs = now
val control = XrControlOut()
animate(now, layers)
val active = panels.filter { it.closingMs == 0L && it.window != null }
if (frame.focused) {
if (gesture.update(frame.hands[0], frame.hands[1], now)) {
burstMs = now
burstAt = gesture.midpoint
lastTick = 0
for (hand in 0..1) control.haptics[hand] = XrHaptic(60, 0.9f)
val from = gesture.midpoint
val posted = attachment
main.post { if (immersiveActive && posted == attachment) toggleMenu(from) }
} else if (gesture.phase == XrGesture.Phase.ARMING) {
val step = (gesture.progress * 4).toInt()
if (step > lastTick) for (hand in 0..1) control.haptics[hand] = XrHaptic(18, 0.2f + 0.15f * step)
lastTick = step
} else lastTick = 0
val out = interaction.update(frame.head, frame.hands, active.map { it.state }, dt)
for (hand in 0..1) {
control.masks[hand] = out.masks[hand]
control.lasers[hand] = out.lasers[hand]
if (out.ticks[hand] && control.haptics[hand] == null) control.haptics[hand] = XrHaptic(12, 0.35f)
}
dispatch(out)
} else {
gesture.reset(release = false)
val out = XrInteractionOut()
interaction.cancel(out)
dispatch(out)
}
control.orb = orb(now)
panels.forEachIndexed { index, panel ->
if (panel.layerId < 0 || panel.window == null) return@forEachIndexed
val state = panel.state
control.layers += XrLayerOut(panel.layerId, state.shownPose, state.width * state.scale, state.height * state.scale,
order = if (state.kind == XrPanelKind.PET_HEAD) 100 else index)
}
host.write(control)
}
private fun orb(now: Long): XrControlOut.Orb? {
if (gesture.phase == XrGesture.Phase.ARMING)
return XrControlOut.Orb(gesture.midpoint, 0.02f + 0.01f * gesture.progress, gesture.progress, 0f)
val burst = (now - burstMs) / BURST_MS
if (burstMs != 0L && burst < 1f) return XrControlOut.Orb(burstAt, 0.03f, 1f, burst.coerceAtLeast(0.01f))
return null
}
private fun animate(now: Long, layers: XrLayerSource) {
val gone = mutableListOf<Panel>()
for (panel in panels) {
val state = panel.state
if (panel.closingMs != 0L) {
val t = ((now - panel.closingMs) / CLOSE_MS).coerceIn(0f, 1f)
state.scale = minOf(state.scale, 1f - easeOut(t))
if (state.animationFrom == null) state.animationFrom = state.pose.position
if (t >= 1f) gone += panel
} else if (state.scale < 1f) {
state.scale = easeOut(((now - panel.openedMs) / OPEN_MS).coerceIn(0f, 1f))
if (state.scale >= 1f) state.animationFrom = null
}
}
for (panel in gone) {
panels -= panel
if (panel.layerId >= 0) layers.destroyLayer(panel.layerId)
val window = panel.window
val context = layers.context
val state = panel.state
val head = lastHead
main.post {
window?.release()
XrPlacement.save(context, state.kind, head, state.pose, state.width, state.height)
}
}
}
private fun easeOut(t: Float) = 1f - (1f - t) * (1f - t) * (1f - t)
/** XR thread: hands each panel its input on the main thread and follows up on moves and resizes. */
private fun dispatch(out: XrInteractionOut) {
val layers = source ?: return
for (panel in panels) {
val cursor = out.cursors[panel.state]?.toList().orEmpty()
if (cursor != panel.cursor) {
panel.cursor = cursor
val target = panel.cursorState
val window = panel.window
main.post {
target.value = cursor
window?.hover(cursor.firstOrNull())
}
}
}
for (event in out.events) {
val panel = panels.firstOrNull { it.state === event.panel } ?: continue
when (event) {
is XrPointerEvent.Back -> main.post { back(panel.state.kind) }
is XrPointerEvent.Click -> {
val from = panel.state.pose.position
main.post { expandChat(from) }
}
is XrPointerEvent.Resized -> {
savePlacement(panel, layers)
resize(panel, layers)
}
is XrPointerEvent.Moved -> savePlacement(panel, layers)
else -> {
val window = panel.window
main.post { window?.pointer(event) }
}
}
}
}
/** XR thread: the place a move or resize ended at, read together now and saved on the main thread. */
private fun savePlacement(panel: Panel, layers: XrLayerSource) {
val state = panel.state
val kind = state.kind
val head = lastHead
val pose = state.pose
val width = state.width
val height = state.height
val context = layers.context
main.post { XrPlacement.save(context, kind, head, pose, width, height) }
}
/** XR thread: gives a resized panel a surface of its new size once its content has moved over to it. */
private fun resize(panel: Panel, layers: XrLayerSource) {
val state = panel.state
val width = XrUnits.pixels(state.width)
val height = XrUnits.pixels(state.height)
if (width == state.pixelWidth && height == state.pixelHeight) return
val id = layers.createLayer(width, height)
val surface = if (id >= 0) layers.layerSurface(id) else null
if (surface == null) {
if (id >= 0) layers.destroyLayer(id)
return
}
val window = panel.window
main.post {
window?.resize(surface, width, height)
ops += {
if (panel in panels) {
val old = panel.layerId
panel.layerId = id
state.pixelWidth = width
state.pixelHeight = height
if (old >= 0) layers.destroyLayer(old)
} else if (source === layers) layers.destroyLayer(id)
}
}
}
/** Main thread. */
private fun toggleMenu(from: Vec3) {
val menu = menuHost?.get() ?: return
if (shown(XrPanelKind.MENU)) menu.xrSetMenuOpen(false)
else {
menuFrom = from
menu.xrSetMenuOpen(true)
}
}
/** Main thread: B on a panel goes back a step, as Back does in the 2D window. */
private fun back(kind: XrPanelKind) {
when (kind) {
XrPanelKind.MENU -> menuHost?.get()?.xrMenuBack()
XrPanelKind.PET_CHAT -> collapseChat()
XrPanelKind.PET_HEAD -> Unit
XrPanelKind.KEYBOARD -> hideKeyboard()
}
}
}
/** Where each panel kind was left, relative to where the user faced, so it comes back there. */
internal object XrPlacement {
class Placed(val pose: Pose, val width: Float, val height: Float)
private class Default(val yaw: Float, val distance: Float, val dy: Float, val width: Float, val height: Float)
private val defaults = mapOf(
XrPanelKind.MENU to Default(0f, 0.95f, -0.12f, 0.9f, 0.6f),
XrPanelKind.PET_CHAT to Default(0.6f, 0.95f, -0.12f, 0.6f, 0.7f),
XrPanelKind.PET_HEAD to Default(0.7f, 0.75f, -0.45f, 0.12f, 0.12f),
XrPanelKind.KEYBOARD to Default(0f, 0.5f, -0.5f, 0.8f, 0.36f),
)
private fun prefs(context: Context) = context.getSharedPreferences("quest_xr_panels", Context.MODE_PRIVATE)
fun place(kind: XrPanelKind, head: Pose, yaw: Float, distance: Float, dy: Float): Pose {
val angle = yawOf(head.forward) + yaw
val direction = Quat.yaw(angle).rotate(Vec3.FORWARD)
val position = head.position + direction * distance + Vec3(0f, dy, 0f)
return Pose(kind.orient(position, head.position), position)
}
fun relative(head: Pose, position: Vec3): Triple<Float, Float, Float> {
val offset = position - head.position
val distance = Vec3(offset.x, 0f, offset.z).length
var yaw = yawOf(offset) - yawOf(head.forward)
while (yaw > PI) yaw -= (2 * PI).toFloat()
while (yaw < -PI) yaw += (2 * PI).toFloat()
return Triple(yaw, distance, offset.y)
}
fun load(context: Context, kind: XrPanelKind, head: Pose): Placed {
val fallback = defaults.getValue(kind)
val saved = prefs(context).getString(kind.key, null)?.split(',')?.mapNotNull { it.toFloatOrNull() }
val values = saved?.takeIf { it.size == 5 } ?: listOf(fallback.yaw, fallback.distance, fallback.dy, fallback.width, fallback.height)
val distance = values[1].coerceIn(XrUnits.MIN_DISTANCE, XrUnits.MAX_DISTANCE)
val width = if (kind.resizable) values[3].coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) else fallback.width
val height = if (kind.resizable) values[4].coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) else fallback.height
return Placed(place(kind, head, values[0], distance, values[2].coerceIn(-1.5f, 1.5f)), width, height)
}
fun save(context: Context, kind: XrPanelKind, head: Pose, pose: Pose, width: Float, height: Float) {
val (yaw, distance, dy) = relative(head, pose.position)
prefs(context).edit().putString(kind.key, listOf(yaw, distance, dy, width, height).joinToString(",")).apply()
}
}
@@ -0,0 +1,16 @@
package com.droiddeck.launcher.session.xr
/** Whether the guest's focus report shows Steam's own screen, with no game holding a window. */
internal object XrSteamScreen {
/** Steam's own UI and SteamVR, which have windows of their own but are not games. */
private val STEAM_APPS = setOf(769L, 250820L)
/**
* Gamescope lists Steam itself while its screen is up, so a report naming no app at all, as the guest
* writes when it could not collect focus or gamescope has not published it, says nothing.
*/
fun shown(focusedApp: Long?, focusableApps: List<Long>?): Boolean {
val apps = (listOfNotNull(focusedApp) + focusableApps.orEmpty()).filter { it > 0 }
return apps.isNotEmpty() && apps.all { it in STEAM_APPS }
}
}
@@ -67,7 +67,7 @@ object EaLsx {
}
@Volatile var game: Game? = null
@Volatile private var account: Account? = null
@Volatile internal var account: Account? = null
/** The one session of the current launch that may act for the account. */
/** Bumped whenever the launch changes; a connection accepted under an older one is not admitted. */
@Volatile internal var generation = 0
@@ -333,10 +333,11 @@ object EaLsx {
private fun now() = LocalDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"))
private fun answer(session: Session, m: Message): String? {
internal fun answer(session: Session, m: Message): String? {
val g = game
val who = account
val person = who?.takeIf { session.trusted }
val profile = who?.takeIf { session.trusted || session.claimed }
val locale = g?.locale ?: "en_US"
return when (m.name) {
"ChallengeResponse" -> {
@@ -355,15 +356,16 @@ object EaLsx {
"GetConfig" -> tag("GetConfigResponse", body = SERVICES.joinToString("") { tag("Service", "Name" to it.first, "Facility" to it.second) })
"GetProfile" -> tag(
"GetProfileResponse",
"Persona" to person?.persona.orEmpty(), "SubscriberLevel" to 0, "CommerceCurrency" to "USD", "IsTrialSubscriber" to false,
"Country" to "US", "UserId" to person?.userId.orEmpty(), "GeoCountry" to "US", "AvatarId" to "", "IsSubscriber" to false,
"IsSteamSubscriber" to false, "PersonaId" to person?.personaId.orEmpty(), "IsUnderAge" to false, "UserIndex" to 0,
"Persona" to profile?.persona.orEmpty(), "SubscriberLevel" to 0, "CommerceCurrency" to "USD", "IsTrialSubscriber" to false,
"Country" to "US", "UserId" to profile?.userId.orEmpty(), "GeoCountry" to "US", "AvatarId" to "", "IsSubscriber" to false,
"IsSteamSubscriber" to false, "PersonaId" to profile?.personaId.orEmpty(), "IsUnderAge" to false, "UserIndex" to 0,
)
"GetSetting" -> tag("GetSettingResponse", "Setting" to when (m.attrs["SettingId"]) {
"ENVIRONMENT" -> "production"
"LANGUAGE" -> locale
else -> "false"
})
"GetSettings" -> tag("GetSettingsResponse", "IsIGOAvailable" to false, "IsIGOEnabled" to false, "IsTelemetryEnabled" to false, "IsManualOffline" to false)
"GetGameInfo" -> tag("GetGameInfoResponse", "GameInfo" to when (m.attrs["GameInfoId"]) {
"FREETRIAL" -> "false"
"LANGUAGES" -> LANGUAGES
@@ -403,7 +405,7 @@ object EaLsx {
)
})
}
"GetPresence" -> tag("GetPresenceResponse", "UserId" to person?.userId.orEmpty(), "Presence" to "INGAME")
"GetPresence" -> tag("GetPresenceResponse", "UserId" to profile?.userId.orEmpty(), "Presence" to "INGAME")
"QueryPresence" -> tag("QueryPresenceResponse", body = "")
"QueryFriends" -> tag("QueryFriendsResponse", body = "")
"GetBlockList" -> tag("GetBlockListResponse", "Return" to "Success", body = "")
@@ -88,7 +88,14 @@ internal object AgentPet {
private set
/** The floating windows could not be made, so the pet stays in DroidDeck's own windows instead. */
private var floatFailed by mutableStateOf(false)
val floating get() = enabled && allowed && !floatFailed
val floating get() = enabled && allowed && !floatFailed && usesOverlayWindows(onQuest)
/** Quest's shell turns overlay windows into system panels that take input from the VR view. */
private val onQuest = com.droiddeck.launcher.session.QuestExperimental.isSupported()
internal fun usesOverlayWindows(quest: Boolean) = !quest
/** On Quest the chat opens as its own panel window, which Horizon moves, resizes and closes. */
internal fun chatInOwnWindow(quest: Boolean = onQuest) = quest
/** How to close the chat open inside each DroidDeck window that has one. */
private val closeInWindow = java.util.WeakHashMap<AgentPetHost, () -> Unit>()
@@ -118,7 +125,7 @@ internal object AgentPet {
AgentHost.prefs(context).edit().putBoolean(KEY, on).apply()
if (on) {
allowed = PetWindows.allowed(context)
if (!allowed) requestFloating(context)
if (!allowed && usesOverlayWindows(onQuest)) requestFloating(context)
}
}
@@ -251,9 +258,12 @@ private fun PetLayer(host: AgentPetHost) {
val density = LocalDensity.current
val openLabel = androidx.compose.ui.res.stringResource(com.droiddeck.launcher.R.string.agent_pet_open)
val openChat = {
motion.dock()
chatShown = true
chatOpen = true
if (AgentPet.chatInOwnWindow()) com.droiddeck.launcher.agent.AgentChatActivity.open(context)
else {
motion.dock()
chatShown = true
chatOpen = true
}
}
val closeChat = {
chatOpen = false
@@ -46,7 +46,11 @@ class BottomDesktopPanel(
private val status = ComposeView(context).apply {
setContent { DroidDeckTheme { BottomDesktopStatus(state.value, ::startAgain) } }
}
private val keyboardHost = KeyboardHost(context) { event -> sendKey(event) }
private val keyboardHost = KeyboardHost(
context,
sendKeyEvent = { event -> sendKey(event) },
sendText = BottomDesktop::sendText,
)
private var directTouch = SessionPrefs.bottomDesktopDirectTouch(context)
private val touchMode = mutableStateOf(directTouch)
private val trackpad = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(), TrackpadInput()).apply {
@@ -8,11 +8,14 @@ import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.AlignHorizontalCenter
import androidx.compose.material.icons.outlined.AlignHorizontalLeft
import androidx.compose.material.icons.outlined.AlignHorizontalRight
import androidx.compose.material.icons.outlined.VerticalSplit
import androidx.compose.material.icons.outlined.WidthFull
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
@@ -72,7 +75,8 @@ internal enum class QamFit(val id: String, @StringRes val label: Int, val icon:
FULL("full", R.string.bottom_qam_layout_full, Icons.Outlined.WidthFull, 0),
LEFT("left", R.string.bottom_qam_layout_left, Icons.Outlined.AlignHorizontalLeft, -1),
CENTER("center", R.string.bottom_qam_layout_center, Icons.Outlined.AlignHorizontalCenter, 0),
RIGHT("right", R.string.bottom_qam_layout_right, Icons.Outlined.AlignHorizontalRight, 1);
RIGHT("right", R.string.bottom_qam_layout_right, Icons.Outlined.AlignHorizontalRight, 1),
SPLIT("split", R.string.bottom_qam_layout_split, Icons.Outlined.VerticalSplit, 0);
val next: QamFit get() = entries[(ordinal + 1) % entries.size]
@@ -92,6 +96,7 @@ internal enum class QamFit(val id: String, @StringRes val label: Int, val icon:
internal object QamLayout {
private const val WIDE_CSS = "div.BasicUI { width: 100% !important; } div[class*=\\\"tab_\\\"] { max-width: none !important; }"
private const val PARKED_CSS = " #Footer { display: none !important; }"
/** Scale and left edge of the menu in a box; [align] -1, 0 or 1 places a narrower menu left, centred or right. */
fun fit(boxWidth: Float, boxHeight: Float, contentRight: Float, cssHeight: Float, align: Int = 0): Pair<Float, Float> {
@@ -102,10 +107,13 @@ internal object QamLayout {
fun toCss(x: Float, y: Float, scale: Float, left: Float): Pair<Float, Float> = (x - left) / scale to y / scale
/** Makes the menu follow the panel-shaped view (Steam sizes it once, on open) and lifts each tab's 300 px cap, then measures where the content ends. */
/** [wide] is false while the menu is shown on the top screen, where it keeps Steam's own layout. */
fun contentScript(wide: Boolean): String = "(() => { let s = document.getElementById('dd-qam-wide'); " +
/**
* [wide] is false while the menu is shown on the top screen, where it keeps Steam's own layout. [parked] hides the
* button-hint footer Steam draws in a game, which stays an empty black strip while the controller is not on the menu.
*/
fun contentScript(wide: Boolean, parked: Boolean = wide): String = "(() => { let s = document.getElementById('dd-qam-wide'); " +
"if (!s) { s = document.createElement('style'); s.id = 'dd-qam-wide'; document.head.appendChild(s); } " +
"const css = '${if (wide) WIDE_CSS else ""}'; " +
"const css = '${(if (wide) WIDE_CSS else "") + (if (parked) PARKED_CSS else "")}'; " +
"if (s.textContent !== css) s.textContent = css; if (document.scrollingElement.scrollLeft) document.scrollingElement.scrollLeft = 0; " +
"const w = innerWidth; let right = 0; for (const e of document.body.querySelectorAll('*')) { " +
"const r = e.getBoundingClientRect(); const tab = /(^| )tab_/.test(String(e.className)); " +
@@ -117,17 +125,90 @@ private const val TICK_MS = 1_000L
private const val FAST_TICK_MS = 150L
private const val MAX_RETRY_MS = 4_000L
/** The last frame shown, so returning to the panel shows the menu at once while the live stream reconnects. */
/** One of Steam's menu pages streamed to the panel; the last frame is kept so returning to the panel shows it at once. */
internal class MenuStream {
@Volatile var page: CdpPage? = null
val live = java.util.concurrent.atomic.AtomicBoolean(false)
val image = mutableStateOf<ImageBitmap?>(null)
val shape = mutableStateOf<FloatArray?>(null)
fun show(frame: ImageBitmap) {
image.value = frame
live.set(true)
}
/** Connects to [path] and starts its screencast; false when the page cannot be reached. */
fun connect(port: Int, path: String): Boolean {
page?.close()
page = null
live.set(false)
val p = runCatching {
CdpPage(port, path) { method, params ->
if (method == "Page.screencastFrame") {
page?.send("Page.screencastFrameAck", JSONObject().put("sessionId", params.optInt("sessionId")))
decodeFrame(params.optString("data"))?.let(::show)
}
}
}.onFailure { android.util.Log.w("SteamQam", "devtools connect: $it") }.getOrNull() ?: return false
page = p
p.send("Page.enable")
val started = p.call("Page.startScreencast", JSONObject().put("format", "jpeg").put("quality", 85)
.put("maxWidth", 1920).put("maxHeight", 1440))
if (started == null || started.has("error") || !started.has("result")) {
p.close()
page = null
return false
}
return true
}
/** Runs [script], which returns the page's [width, height, pixel ratio, content right], and refreshes a still page. */
fun refresh(script: String) {
val p = page ?: return
// The screencast sends frames only when the menu repaints, so a still menu needs one screenshot.
if (!live.get()) {
p.call("Page.captureScreenshot", JSONObject().put("format", "jpeg").put("quality", 85))
?.optJSONObject("result")?.optString("data")?.let(::decodeFrame)?.let(::show)
}
(p.evaluate(script) as? String)?.let { text ->
runCatching {
val a = JSONArray(text)
val layout = FloatArray(4) { a.getDouble(it).toFloat() }
if (!layout.contentEquals(shape.value)) shape.value = layout
}
}
}
/** Stops the stream and runs [restore] on the page, which outlives this connection. */
fun stop(restore: String) {
val p = page ?: return
page = null
runCatching { p.send("Page.stopScreencast") }
runCatching { p.evaluate(restore) }
p.close()
}
fun frame(): QamFrame? {
val img = image.value
val l = shape.value
return if (img != null && l != null && l[0] > 0f) QamFrame(img, l[0], l[1], l[3].coerceIn(l[0] * 0.25f, l[0])) else null
}
}
/** Steam's main menu beside the quick access menu; Steam's side of the hold keeps it in place and filling its view. */
internal object MainMenuLayout {
const val CONTENT_SCRIPT = "JSON.stringify([innerWidth, innerHeight, devicePixelRatio, innerWidth])"
}
/** Panel streams kept across visits to the panel. */
private object QamCache {
@Volatile var image: ImageBitmap? = null
@Volatile var shape: FloatArray? = null
val qam = MenuStream()
val main = MenuStream()
}
@Composable
internal fun SteamQamPanel() {
val context = LocalContext.current.applicationContext
var image by remember { mutableStateOf(QamCache.image) }
var shape by remember { mutableStateOf(QamCache.shape) }
var failed by remember { mutableStateOf(false) }
var slow by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
@@ -135,78 +216,67 @@ internal fun SteamQamPanel() {
slow = true
}
val fit = QamFit.current(context)
val holder = remember { arrayOfNulls<CdpPage>(1) }
val qam = QamCache.qam
val mainMenu = QamCache.main
val owner = remember { SteamQam.newOwner() }
val relay = remember { intArrayOf(0) }
val live = remember { java.util.concurrent.atomic.AtomicBoolean(false) }
val mainPath = remember { arrayOfNulls<String>(1) }
val aspect = remember { floatArrayOf(0f) }
val measure = Modifier.fillMaxSize().onSizeChanged { if (it.height > 0) aspect[0] = it.width.toFloat() / it.height }
val show = { frame: ImageBitmap -> image = frame; QamCache.image = frame; live.set(true) }
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
var misses = 0
// The main menu page backs off on its own, so Quick Access stays available while its neighbour cannot connect.
var mainMisses = 0
var mainRetryAt = 0L
fun split() = QamFit.current(context) == QamFit.SPLIT
// The lease is renewed on its own, so slow discovery or a retry backoff never lets the held menu lapse.
val renew = launch {
while (isActive) {
if (SessionState.phase == SessionPhase.READY && aspect[0] > 0f) SteamQam.hold(context, aspect[0], owner)
if (SessionState.phase == SessionPhase.READY && aspect[0] > 0f) SteamQam.hold(context, aspect[0], owner, split())
delay(TICK_MS)
}
}
try {
while (isActive) {
// Holding the menu before Steam's first frame keeps gamescope from presenting it.
if (SessionState.phase != SessionPhase.READY) {
if (SessionState.phase != SessionPhase.READY || aspect[0] == 0f) {
delay(FAST_TICK_MS)
continue
}
if (aspect[0] == 0f) {
delay(FAST_TICK_MS)
continue
}
val held = SteamQam.hold(context, aspect[0], owner)
val split = split()
val held = SteamQam.hold(context, aspect[0], owner, split)
ensureActive()
var reached = held != null
if (held?.open == SteamQam.QUICK_ACCESS) {
var page = holder[0]
if (page == null || page.closed) {
page?.close()
live.set(false)
page = SteamQam.target(context)?.let { t ->
if (qam.page?.closed != false) {
val t = SteamQam.target(context)
if (t != null) {
if (relay[0] != 0 && relay[0] != t.port) SteamQam.stopRelay(context, relay[0])
relay[0] = t.port
runCatching {
CdpPage(t.port, t.path) { method, params ->
if (method == "Page.screencastFrame") {
holder[0]?.send("Page.screencastFrameAck", JSONObject().put("sessionId", params.optInt("sessionId")))
decodeFrame(params.optString("data"))?.let(show)
}
}
}.onFailure { android.util.Log.w("SteamQam", "devtools connect: $it") }.getOrNull()
mainPath[0] = t.mainPath
qam.connect(t.port, t.path)
mainMenu.stop(MainMenuLayout.CONTENT_SCRIPT)
}
holder[0] = page
ensureActive()
page?.send("Page.enable")
val started = page?.call("Page.startScreencast", JSONObject().put("format", "jpeg").put("quality", 85)
.put("maxWidth", 1920).put("maxHeight", 1440))
if (page != null && (started == null || started.has("error") || !started.has("result"))) {
page.close()
page = null
holder[0] = null
}
}
// The screencast sends frames only when the menu repaints, so a still menu needs one screenshot.
if (!live.get()) {
page?.call("Page.captureScreenshot", JSONObject().put("format", "jpeg").put("quality", 85))
?.optJSONObject("result")?.optString("data")?.let(::decodeFrame)?.let(show)
}
reached = page != null
val wide = !held.top && QamFit.current(context) == QamFit.FULL
(page?.evaluate(QamLayout.contentScript(wide)) as? String)?.let { text ->
runCatching {
val a = JSONArray(text)
val layout = floatArrayOf(a.getDouble(0).toFloat(), a.getDouble(1).toFloat(), a.getDouble(2).toFloat(), a.getDouble(3).toFloat())
if (!layout.contentEquals(shape)) { shape = layout; QamCache.shape = layout }
reached = qam.page?.closed == false
val wide = !held.top && (QamFit.current(context) == QamFit.FULL || split)
qam.refresh(QamLayout.contentScript(wide, parked = !held.top))
val path = mainPath[0]
if (split && path != null) {
val now = android.os.SystemClock.elapsedRealtime()
if (mainMenu.page?.closed != false && now >= mainRetryAt) {
if (mainMenu.connect(relay[0], path)) {
mainMisses = 0
} else {
mainMisses++
mainRetryAt = now + minOf(TICK_MS shl minOf(mainMisses - 1, 2), MAX_RETRY_MS)
}
}
mainMenu.refresh(MainMenuLayout.CONTENT_SCRIPT)
} else if (!split) {
mainMenu.stop(MainMenuLayout.CONTENT_SCRIPT)
}
}
failed = !reached
@@ -214,7 +284,7 @@ internal fun SteamQamPanel() {
misses = if (reached) 0 else misses + 1
val wait = when {
!reached -> minOf(TICK_MS shl minOf(misses - 1, 2), MAX_RETRY_MS)
live.get() -> TICK_MS
qam.live.get() && (!split || mainMenu.live.get() || mainMenu.page?.closed != false) -> TICK_MS
else -> FAST_TICK_MS
}
val used = QamFit.current(context)
@@ -225,35 +295,46 @@ internal fun SteamQamPanel() {
} finally {
withContext(NonCancellable) {
renew.cancelAndJoin()
val page = holder[0]
holder[0] = null
runCatching { page?.send("Page.stopScreencast") }
// The page outlives this connection, so the widened layout would otherwise stay on the top screen.
runCatching { page?.evaluate(QamLayout.contentScript(wide = false)) }
page?.close()
// The pages outlive these connections, so the widened layouts would otherwise stay on the top screen.
qam.stop(QamLayout.contentScript(wide = false))
mainMenu.stop(MainMenuLayout.CONTENT_SCRIPT)
SteamQam.release(context, relay[0], owner)
}
}
}
}
val img = image
val l = shape
val f = remember(img, l) {
if (img != null && l != null && l[0] > 0f) QamFrame(img, l[0], l[1], l[3].coerceIn(l[0] * 0.25f, l[0])) else null
}
if (f == null) {
val qamFrame = qam.frame()
if (qamFrame == null) {
Box(measure) {
if (slow) PanelNote(stringResource(if (failed) R.string.bottom_qam_unavailable else R.string.achievements_reading))
}
return
}
BoxWithConstraints(measure.background(f.fill)) {
if (fit != QamFit.SPLIT) {
MenuCanvas(qamFrame, fit.align, measure) { qam.page }
return
}
// Each side is as wide as its menu at the shared scale, so neither is shrunk nor padded with empty space.
val mainFrame = mainMenu.frame()
val mainWidth = mainFrame?.cssWidth ?: SteamQam.MAIN_CSS_WIDTH.toFloat()
Row(measure) {
val left = Modifier.weight(mainWidth).fillMaxHeight()
if (mainFrame != null) MenuCanvas(mainFrame, -1, left) { mainMenu.page }
else Box(left.background(qamFrame.fill))
MenuCanvas(qamFrame, -1, Modifier.weight(qamFrame.cssWidth).fillMaxHeight()) { qam.page }
}
}
/** Draws [f] scaled into the box, placed by [align], and forwards touches on it to [page]. */
@Composable
private fun MenuCanvas(f: QamFrame, align: Int, modifier: Modifier, page: () -> CdpPage?) {
BoxWithConstraints(modifier.background(f.fill)) {
val density = LocalDensity.current
val boxW = with(density) { maxWidth.toPx() }
val boxH = with(density) { maxHeight.toPx() }
val (scale, left) = QamLayout.fit(boxW, boxH, f.contentRight, f.cssHeight, fit.align)
val (scale, left) = QamLayout.fit(boxW, boxH, f.contentRight, f.cssHeight, align)
Canvas(
Modifier.fillMaxSize().pointerInput(f.cssWidth, f.contentRight, boxW, boxH, fit) {
Modifier.fillMaxSize().pointerInput(f.cssWidth, f.contentRight, boxW, boxH, align) {
var touching = false
var target: CdpPage? = null
try {
@@ -268,7 +349,7 @@ internal fun SteamQamPanel() {
PointerEventType.Release -> "touchEnd"
else -> null
}?.takeIf { it == "touchStart" || touching } ?: continue
if (type == "touchStart") target = holder[0]
if (type == "touchStart") target = page()
touching = type != "touchEnd"
val points = if (type == "touchEnd") JSONArray()
else JSONArray().put(JSONObject().put("x", x.toDouble()).put("y", y.toDouble()))
@@ -7,13 +7,16 @@ import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.displayCutout
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
@@ -35,6 +38,7 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
@@ -90,6 +94,29 @@ internal fun DrawerEntryHint(steam: Boolean, inverted: Boolean, onOpen: () -> Un
}
}
/** A Quest has no system Back gesture, so a laser drag in from the right edge stands in for it. */
@Composable
internal fun DrawerEdgeSwipe(onBack: () -> Unit) {
val density = LocalDensity.current
val threshold = with(density) { 48.dp.toPx() }
val strip = with(density) { 12.toDp() }
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) {
Box(
Modifier.fillMaxHeight().width(strip).testTag("drawer-edge")
.pointerInput(Unit) {
var travelled = 0f
detectHorizontalDragGestures(
onDragStart = { travelled = 0f },
onDragEnd = { if (travelled <= -threshold) onBack() },
) { change, amount ->
change.consume()
travelled += amount
}
},
)
}
}
@Composable
internal fun DrawerCornerTap(onOpen: () -> Unit) {
Box(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.displayCutout), contentAlignment = Alignment.TopEnd) {
@@ -0,0 +1,142 @@
package com.droiddeck.launcher.ui
import android.content.Context
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
/**
* Inside the session menu every top-level settings group folds to its header and a summary of its values.
* Groups start folded; a group the player opens or folds stays that way across sessions.
*/
internal object DrawerSectionState {
private val chosen = mutableStateMapOf<String, Boolean>()
fun load(context: Context) {
if (DevPreview.drawer != null) return
chosen.clear()
chosen.putAll(SessionPrefs.drawerSections(context))
}
fun isOpen(key: String) = chosen[key] ?: false
fun toggle(context: Context, key: String) {
chosen[key] = !isOpen(key)
if (DevPreview.drawer == null) SessionPrefs.setDrawerSections(context, chosen.toMap())
}
}
internal class DrawerSections(val context: Context, val track: (String) -> Modifier)
internal val LocalDrawerSections = compositionLocalOf<DrawerSections?> { null }
@Composable
internal fun DrawerSection(
sections: DrawerSections, key: String, title: String, summary: String?, tag: String?,
content: @Composable ColumnScope.() -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val open = DrawerSectionState.isOpen(key)
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val rotation by animateFloatAsState(if (open) 180f else 0f, Motion.tw(180), label = "sectionArrow")
val state = stringResource(if (open) R.string.widgets_expanded else R.string.widgets_collapsed)
val toggle = { DrawerSectionState.toggle(sections.context, key) }
val shape = RoundedCornerShape(14.dp)
Column(
Modifier.fillMaxWidth().padding(top = 6.dp).clip(shape)
.background(colors.surface).border(1.dp, if (open) pal.line2 else pal.line, shape),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)
.then(sections.track("section-$key"))
.testTag("drawer-section-$key")
.background(if (hot) pal.signal.copy(alpha = 0.12f) else androidx.compose.ui.graphics.Color.Transparent)
.glideBorder(hot, shape, pal.signal)
.hoverable(source)
.clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = toggle)
.controllerConfirm(onClick = toggle)
.semantics { contentDescription = title; stateDescription = state }
.padding(start = 12.dp, end = 8.dp, top = 6.dp, bottom = 6.dp),
) {
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Text(title.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp,
color = if (open) colors.onBackground else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = false))
if (tag != null) Text(
tag, fontSize = 10.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1,
modifier = Modifier.clip(RoundedCornerShape(6.dp)).background(pal.signal.copy(alpha = 0.14f))
.padding(horizontal = 6.dp, vertical = 2.dp),
)
}
if (!open && !summary.isNullOrEmpty()) Text(
summary, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 2.dp),
)
}
Icon(Icons.Outlined.ExpandMore, contentDescription = null, tint = colors.onSurfaceVariant,
modifier = Modifier.size(22.dp).rotate(rotation))
}
AnimatedVisibility(open, enter = expandVertically(Motion.tw(200)) + fadeIn(Motion.tw(160)),
exit = shrinkVertically(Motion.tw(160)) + fadeOut(Motion.tw(120))) {
Column(Modifier.fillMaxWidth()) {
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
// Only top-level groups fold; groups and dialogs opened from inside one draw normally.
CompositionLocalProvider(LocalDrawerSections provides null) { content() }
}
}
}
}
@@ -26,7 +26,8 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
fun on(key: String) = cfg[key] == "1"
fun int(key: String, fallback: Int) = cfg[key]?.toIntOrNull() ?: fallback
SettingsGroup(stringResource(R.string.drawer_hud)) {
SettingsGroup(stringResource(R.string.drawer_hud), key = "performance-hud",
detail = stringResource(if (a.hudOn) R.string.widgets_on else R.string.widgets_off)) {
ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, chipModifier = track("hud"), onChange = a.onHud)
if (a.hudOn) ToggleRow(
host, "hud-only-during-game", stringResource(R.string.hud_only_during_game),
@@ -62,7 +63,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
if (a.dashboardAvailable && a.secondScreenDisplays.isNotEmpty()) BottomStripSettings(host, track)
if (!a.hudOn) return
SettingsGroup(stringResource(R.string.hud_group_look)) {
SettingsGroup(stringResource(R.string.hud_group_look), key = "performance-hud-look") {
SliderRow(stringResource(R.string.hud_scale), null, int("hudScale", 100), 50..150, step = 5, format = { "$it%" },
modifier = track("hud-scale")) { a.onHudSetting("hudScale", it.toString()) }
SliderRow(stringResource(R.string.drawer_hud_opacity), null, int("hudOpacity", 80), 0..100, step = 5, format = { "$it%" },
@@ -85,7 +86,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
}
var editing by remember { mutableStateOf(false) }
SettingsGroup(stringResource(R.string.hud_group_metrics)) {
SettingsGroup(stringResource(R.string.hud_group_metrics), key = "performance-hud-metrics") {
ActionRow(stringResource(R.string.hud_group_metrics), null, stringResource(R.string.common_edit),
onClick = { editing = true }, modifier = track("hud-readings"))
val rows = DroidDeckHudSize.rowsFor(DroidDeckHudSize.from(cfg["hudSize"]), cfg)
@@ -103,7 +104,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
)
}
if (on("showTemp") || on("showGpuTemp") || on("showBatteryTemp")) SettingsGroup(stringResource(R.string.hud_group_temps)) {
if (on("showTemp") || on("showGpuTemp") || on("showBatteryTemp")) SettingsGroup(stringResource(R.string.hud_group_temps), key = "performance-hud-temps") {
ChoiceRow(host, "hud-temp-unit", stringResource(R.string.hud_temp_unit), null,
listOf("c" to "°C", "f" to "°F"), if (cfg["tempUnit"].equals("f", true)) "f" else "c",
chipModifier = track("hud-temp-unit")) { a.onHudSetting("tempUnit", it) }
@@ -129,7 +130,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
}
}
SettingsGroup(stringResource(R.string.hud_group_more)) {
SettingsGroup(stringResource(R.string.hud_group_more), key = "performance-hud-more") {
ActionRow(stringResource(R.string.hud_export), stringResource(R.string.hud_export_hint),
stringResource(R.string.hud_export_button), onClick = a.onHudExport, modifier = track("hud-export"))
ActionRow(stringResource(R.string.hud_reset), null, stringResource(R.string.hud_reset_button),
@@ -145,7 +146,7 @@ private fun BottomStripSettings(host: MenuHost, track: (String) -> Modifier) {
var hudOn by remember { mutableStateOf(SessionPrefs.bottomHud(context)) }
var onTabs by remember { mutableStateOf(SessionPrefs.bottomStripOnTabs(context)) }
var shown by remember { mutableStateOf(SessionPrefs.bottomStripMetrics(context)) }
SettingsGroup(stringResource(R.string.bottom_hud_group)) {
SettingsGroup(stringResource(R.string.bottom_hud_group), key = "performance-bottom-hud") {
ToggleRow(host, "bottom-hud", stringResource(R.string.bottom_hud_group), null, hudOn,
chipModifier = track("bottom-hud")) { on ->
hudOn = on
@@ -1,52 +1,236 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.Lossless
@Composable
internal fun FrameGenMenu(
host: MenuHost, mode: FrameGen.Mode, lossless: Lossless.State,
mode: FrameGen.Mode,
lossless: Lossless.State,
onPick: (FrameGen.Mode) -> Unit,
onImportLossless: () -> Unit,
gameProfileId: String? = null,
hasGameOverride: Boolean = false,
onResetGame: () -> Unit = {},
focusModifier: Modifier = Modifier,
legacyButtons: Boolean = false,
) {
val context = LocalContext.current
AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = stringResource(R.string.frame_gen_title)) { firstItemFocus ->
val need = when {
lossless.ready -> null
lossless.owned -> stringResource(R.string.lsfg_needs_install)
else -> stringResource(R.string.lsfg_needs_steam)
val need = when {
lossless.ready -> null
lossless.owned -> stringResource(R.string.lsfg_needs_install)
else -> stringResource(R.string.lsfg_needs_steam)
}
val selectedEngine = mode.engine.takeIf { it != FrameGen.ENGINE_OFF }
val offLabel = FrameGen.label(LocalContext.current, FrameGen.Mode.OFF)
val colors = MaterialTheme.colorScheme
val engines = listOf(FrameGen.ENGINE_LSFG to "LSFG", FrameGen.ENGINE_DDFG to "DDFG")
if (legacyButtons) {
val context = LocalContext.current
val options = buildList {
add(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier))
(2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_DDFG, it)) }
(2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, it)) }
FrameGen.ADAPTIVE_TARGETS.forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it)) }
}
@Composable
fun item(m: FrameGen.Mode, enabled: Boolean = true, detail: String? = null, focus: FocusRequester? = null) =
MenuItem(FrameGen.label(context, m), checked = mode == m, enabled = enabled, detail = detail, focusRequester = focus) {
onPick(m); host.open = null
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, bottom = 8.dp)) {
options.forEachIndexed { index, option ->
val selected = mode == option ||
(option.engine == FrameGen.ENGINE_OFF && selectedEngine == null)
val enabled = option.engine != FrameGen.ENGINE_LSFG || lossless.ready || selected
val pick = { onPick(option) }
OutlinedButton(
onClick = pick,
enabled = enabled,
modifier = (if (index == 0) focusModifier else Modifier).fillMaxWidth()
.padding(top = if (index == 0) 0.dp else 6.dp)
.controllerConfirm(enabled = enabled, onClick = pick),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selected) colors.primary else colors.onSurface,
),
) { Text(FrameGen.label(context, option)) }
}
item(FrameGen.Mode.OFF, focus = firstItemFocus)
if (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) {
Text(
need.orEmpty(),
color = colors.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 6.dp),
)
}
if (gameProfileId != null) {
val resetGame = onResetGame
OutlinedButton(
onClick = resetGame,
modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
.controllerConfirm(onClick = resetGame),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
) {
Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓")
}
}
if (lossless.owned) {
val using = when (lossless.source) {
Lossless.Source.STEAM -> stringResource(R.string.lsfg_using_steam)
Lossless.Source.IMPORT -> stringResource(R.string.lsfg_using_import)
Lossless.Source.NONE -> null
}
OutlinedButton(
onClick = onImportLossless,
modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
.controllerConfirm(onClick = onImportLossless),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
) {
Text(stringResource(R.string.lsfg_import) + (using?.let { " · $it" } ?: ""))
}
}
}
return
}
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 0.dp, bottom = 8.dp)) {
OutlinedButton(
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
modifier = Modifier.fillMaxWidth().controllerConfirm(
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selectedEngine == null) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selectedEngine == null) colors.primary else colors.onSurface,
),
) { Text(offLabel) }
Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
val focusIndex = engines.indexOfFirst { (engine, _) ->
selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready
}
engines.forEachIndexed { index, (engine, label) ->
val selected = selectedEngine == engine
val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready
val pick = {
onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4)))
}
OutlinedButton(
onClick = pick,
enabled = enabled,
modifier = (if (index == focusIndex) focusModifier else Modifier)
.weight(1f).controllerConfirm(enabled = enabled, onClick = pick),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
contentColor = if (selected) colors.primary else colors.onSurface,
),
) { Text(label) }
}
}
if (selectedEngine != null) {
val multiplierEnabled = mode.engine != FrameGen.ENGINE_LSFG || lossless.ready
Row(
Modifier.fillMaxWidth().padding(top = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
(2..4).forEach { multiplier ->
val selected = mode.multiplier == multiplier && mode.target == 0
val pickMultiplier = {
onPick(mode.copy(multiplier = multiplier, target = 0))
}
OutlinedButton(
onClick = pickMultiplier,
enabled = multiplierEnabled,
modifier = Modifier.weight(1f).controllerConfirm(
enabled = multiplierEnabled,
onClick = pickMultiplier,
),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface,
contentColor = if (selected) colors.secondary else colors.onSurface,
),
) { Text("${multiplier}×") }
}
}
}
if (selectedEngine == FrameGen.ENGINE_LSFG) {
Row(
Modifier.fillMaxWidth().padding(top = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
FrameGen.ADAPTIVE_TARGETS.forEach { target ->
val adaptiveMode = FrameGen.Mode(FrameGen.ENGINE_LSFG, target = target)
val selected = mode.target == target
val pickTarget = { onPick(adaptiveMode) }
OutlinedButton(
onClick = pickTarget,
enabled = lossless.ready,
modifier = Modifier.weight(1f).controllerConfirm(
enabled = lossless.ready,
onClick = pickTarget,
),
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface,
contentColor = if (selected) colors.secondary else colors.onSurface,
),
) {
Text(FrameGen.label(LocalContext.current, adaptiveMode))
}
}
}
}
if (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) {
Text(need.orEmpty(), color = colors.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 6.dp))
}
if (gameProfileId != null) {
MenuItem(stringResource(R.string.comp_game_use_general), checked = !hasGameOverride) {
onResetGame()
host.open = null
val resetGame = onResetGame
OutlinedButton(
onClick = resetGame,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
.controllerConfirm(onClick = resetGame),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
) {
Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓")
}
}
for (m in 2..4) item(FrameGen.Mode(FrameGen.ENGINE_DDFG, m))
val lsfg = (2..4).map { FrameGen.Mode(FrameGen.ENGINE_LSFG, it) } +
FrameGen.ADAPTIVE_TARGETS.map { FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it) }
lsfg.forEachIndexed { i, m -> item(m, enabled = lossless.ready, detail = need.takeIf { i == 0 }) }
if (lossless.owned) {
val using = when (lossless.source) {
Lossless.Source.STEAM -> stringResource(R.string.lsfg_using_steam)
Lossless.Source.IMPORT -> stringResource(R.string.lsfg_using_import)
Lossless.Source.NONE -> null
}
MenuItem(stringResource(R.string.lsfg_import), checked = false, detail = using) { host.open = null; onImportLossless() }
OutlinedButton(
onClick = onImportLossless,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
.controllerConfirm(onClick = onImportLossless),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
) {
Text(stringResource(R.string.lsfg_import) + (using?.let { " · $it" } ?: ""))
}
}
}
}
@@ -177,6 +177,12 @@ class FrontEndState(
val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER,
val homePage: String = com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM,
val launcherFullscreen: Boolean = true,
val launcherFrost: Boolean = false,
val frostWallpaper: Boolean = true,
val frostCards: Boolean = true,
val frostTransparency: Int = FROST_WALLPAPER_DEFAULT,
val frostCardTransparency: Int = FROST_DEFAULT,
val frostSupported: Boolean = false,
val controllerHaptics: Boolean = true,
val downloadSource: String = DownloadSource.MODE_AUTO,
val downloadMirror: String = "",
@@ -284,6 +290,11 @@ class FrontEndActions(
val onLauncherOrientation: (Int) -> Unit = {},
val onHomePage: (String) -> Unit = {},
val onLauncherFullscreen: (Boolean) -> Unit = {},
val onLauncherFrost: (Boolean) -> Unit = {},
val onFrostWallpaper: (Boolean) -> Unit = {},
val onFrostCards: (Boolean) -> Unit = {},
val onFrostTransparency: (Int) -> Unit = {},
val onFrostCardTransparency: (Int) -> Unit = {},
val onControllerHaptics: (Boolean) -> Unit = {},
val onAnimationsEnabled: (Boolean) -> Unit = {},
val onLowStorageWarning: (Boolean) -> Unit = {},
@@ -446,6 +457,15 @@ internal suspend fun focusWithinFrames(done: () -> Boolean, target: () -> FocusR
}
}
internal suspend fun holdFocus(held: () -> Boolean, target: () -> FocusRequester?) {
val since = MainTabSteps.otherKeys
repeat(RAIL_HOLD_FRAMES) { frame ->
androidx.compose.runtime.withFrameNanos { }
if (MainTabSteps.otherKeys != since) return
if (frame == 0 || !held()) runCatching { target()?.requestFocus() }
}
}
internal suspend fun focusSoon(target: () -> FocusRequester) {
repeat(30) {
androidx.compose.runtime.withFrameNanos { }
@@ -693,7 +713,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}
}
androidx.compose.foundation.layout.BoxWithConstraints(
modifier = Modifier.fillMaxSize().background(colors.background)
modifier = Modifier.fillMaxSize().background(if (LocalFrost.current != null) Color.Transparent else colors.background)
.windowInsetsPadding(if (s.launcherFullscreen) WindowInsets.displayCutout else WindowInsets.systemBars)
.onFocusChanged { anyFocused = it.hasFocus },
) {
@@ -775,10 +795,13 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
val stepScope = androidx.compose.runtime.rememberCoroutineScope()
val pageKeyNow = androidx.compose.runtime.rememberUpdatedState(s.pageKey)
var railHold by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
val stepView = androidx.compose.ui.platform.LocalView.current
val tabStep = androidx.compose.runtime.rememberUpdatedState { step: Int ->
if (!processSettingsPageVisible) {
val keys = navigationKeys(s)
keys.getOrNull(keys.indexOf(railSelectionNow.value) + step)?.let { key ->
releaseFocusedTextField(stepView)
OpenMenus.leaveAll(withPage = true)
PageSwipe.direction = step
if (s.dualScreen) { onRailSelect(key); return@let }
showRailPage(key, false)
@@ -1,6 +1,9 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.FocusRequester
import android.os.Build
@@ -50,6 +53,7 @@ import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
@@ -152,6 +156,20 @@ internal fun SetupPanel(
) {
val host = rememberMenuHost()
val ctx = LocalContext.current
val frostRow = s.frostSupported && s.theme != Themes.TRUE_BLACK
var steamOrientation by remember { mutableStateOf(SessionPrefs.orientation(ctx, "steam")) }
var desktopOrientation by remember { mutableStateOf(SessionPrefs.orientation(ctx, "desktop")) }
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner, ctx) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
steamOrientation = SessionPrefs.orientation(ctx, "steam")
desktopOrientation = SessionPrefs.orientation(ctx, "desktop")
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
var hideHomeFromRecents by remember { mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.hideHomeFromRecents(ctx)) }
var processLimitBusy by remember { mutableStateOf(false) }
var processLimitMessage by remember { mutableStateOf<String?>(null) }
@@ -251,7 +269,7 @@ internal fun SetupPanel(
val listing = searching && query.isNotBlank()
val fixed = tab == CONTROLLER_TAB && !listing
Column(modifier = Modifier.weight(1f).fillMaxWidth().then(if (fixed) Modifier else Modifier.verticalScroll(rememberScrollState())).padding(bottom = if (fixed) 0.dp else 24.dp)) {
if (listing) SettingsSearchResults(query) { section -> pick(section.ordinal) }
if (listing) SettingsSearchResults(query, frostRow) { section -> pick(section.ordinal) }
else when (tab) {
OVERVIEW_TAB -> {
OnboardingCard(limitBlocks, a.onShowPhantomGate)
@@ -398,7 +416,8 @@ internal fun SetupPanel(
listOfNotNull(
gpu.displayName(ctx),
s.installed?.let { stringResource(R.string.setup_ready_runtime, it) },
stringResource(R.string.setup_ready_limit_off).takeIf { !limitBlocks },
stringResource(R.string.setup_ready_limit_off)
.takeIf { !limitBlocks && s.phantomProcessStatus != PhantomProcessStatus.UNCOUNTED },
s.offlineAccount?.takeIf { it.isNotEmpty() }?.let { stringResource(R.string.setup_ready_signed_in, it) },
).joinToString(" · "),
open = showChecks, onDetails = { showChecks = !showChecks },
@@ -447,6 +466,35 @@ internal fun SetupPanel(
if (s.theme == Themes.GRADIENT) GradientColorRows()
if (s.theme == Themes.CUSTOM) CustomColorRows()
if (s.theme == Themes.TRUE_BLACK) HighlightColorRow()
if (frostRow) {
ToggleRow(
host, "launcher-frost", stringResource(R.string.setup_frosted_background),
stringResource(R.string.setup_frosted_background_hint), s.launcherFrost, onChange = a.onLauncherFrost,
)
if (s.launcherFrost) {
val ctx = androidx.compose.ui.platform.LocalContext.current
val percent: (Int) -> String = { ctx.getString(R.string.ctrl_percent, it) }
ToggleRow(
host, "launcher-frost-wallpaper", stringResource(R.string.setup_frosted_wallpaper), null,
s.frostWallpaper, onChange = a.onFrostWallpaper,
)
SliderRow(
stringResource(R.string.setup_frost_transparency), stringResource(R.string.setup_frost_transparency_hint),
s.frostTransparency, 0..FROST_MAX, step = FROST_STEP, enabled = s.frostWallpaper, format = percent,
onChange = a.onFrostTransparency,
)
ToggleRow(
host, "launcher-frost-cards", stringResource(R.string.setup_frosted_cards),
stringResource(if (s.frostWallpaper) R.string.setup_frosted_cards_hint else R.string.setup_frosted_cards_needs_wallpaper),
s.frostCards, enabled = s.frostWallpaper, onChange = a.onFrostCards,
)
SliderRow(
stringResource(R.string.setup_frost_card_transparency), stringResource(R.string.setup_frost_card_transparency_hint),
s.frostCardTransparency, 0..FROST_MAX, step = FROST_STEP, enabled = s.frostWallpaper && s.frostCards, format = percent,
onChange = a.onFrostCardTransparency,
)
}
}
ChoiceRow(
host, "app-scale", stringResource(R.string.setup_app_scale), stringResource(R.string.setup_app_scale_hint),
com.droiddeck.launcher.core.AppUiPrefs.scales.map { percent ->
@@ -516,7 +564,27 @@ internal fun SetupPanel(
ChoiceRow(
host, "orientation", stringResource(R.string.setup_session_orientation), stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
s.orientation, onPick = a.onOrientation,
s.orientation, onPick = { value ->
a.onOrientation(value)
steamOrientation = SessionPrefs.orientation(ctx, "steam")
desktopOrientation = SessionPrefs.orientation(ctx, "desktop")
},
)
ChoiceRow(
host, "orientation-steam", stringResource(R.string.setup_session_orientation) + " (Steam)", stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
steamOrientation, onPick = { value ->
steamOrientation = value
SessionPrefs.setOrientation(ctx, "steam", value)
},
)
ChoiceRow(
host, "orientation-desktop", stringResource(R.string.setup_session_orientation) + " (Desktop)", stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
desktopOrientation, onPick = { value ->
desktopOrientation = value
SessionPrefs.setOrientation(ctx, "desktop", value)
},
)
ToggleRow(
host, "launcher-fullscreen", stringResource(R.string.setup_fullscreen),
@@ -643,7 +711,7 @@ internal fun SetupPanel(
ToggleRow(host, "agent-pet", stringResource(R.string.setup_agent_pet), stringResource(R.string.setup_agent_pet_hint), AgentPet.enabled) {
AgentPet.set(agentContext, it)
}
if (AgentPet.enabled && !AgentPet.allowed) ActionRow(
if (AgentPet.enabled && !AgentPet.allowed && AgentPet.usesOverlayWindows(com.droiddeck.launcher.session.QuestExperimental.isSupported())) ActionRow(
stringResource(R.string.setup_agent_pet_float), stringResource(R.string.setup_agent_pet_float_hint),
stringResource(R.string.setup_agent_pet_allow), onClick = { AgentPet.requestFloating(agentContext) },
)
@@ -792,7 +860,7 @@ internal fun ReadinessCard(
@Composable
private fun FrameGenMenu(s: FrontEndState, a: FrontEndActions, host: MenuHost) {
FrameGenMenu(host, s.frameGen, s.lossless, a.onFrameGenPick, a.onImportLossless)
FrameGenMenu(s.frameGen, s.lossless, a.onFrameGenPick, a.onImportLossless, legacyButtons = true)
}
@Composable
@@ -819,6 +887,34 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
val steamCard: (@Composable (Modifier) -> Unit)? = if (game != null && steamScope != null) { m ->
Box(m) { GameSettingsCard(host, game, steamScope) }
} else null
val frameGenMenuContent: @Composable () -> Unit = {
FrameGenMenu(
mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen,
lossless = s.lossless,
onPick = { mode ->
val key = frameGenProfileKey
if (key == null) {
a.onFrameGenPick(mode)
} else {
com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode)
gameFrameGenMode = mode
gameFrameGenOverride = true
}
},
onImportLossless = a.onImportLossless,
legacyButtons = true,
gameProfileId = frameGenProfileKey,
hasGameOverride = gameFrameGenOverride,
onResetGame = {
val key = frameGenProfileKey
if (key != null) {
com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key)
gameFrameGenMode = com.droiddeck.launcher.gpu.FrameGen.mode(context)
gameFrameGenOverride = false
}
},
)
}
val cards = if (game?.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER) listOfNotNull(steamCard) else buildList<@Composable (Modifier) -> Unit> {
add { m ->
val back = stringResource(R.string.hop_from_games)
@@ -840,33 +936,7 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
) {
host.open = if (host.open == "fg") null else "fg"
}
FrameGenMenu(
host = host,
mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen,
lossless = s.lossless,
onPick = { mode ->
val key = frameGenProfileKey
if (key == null) {
a.onFrameGenPick(mode)
} else {
com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode)
gameFrameGenMode = mode
gameFrameGenOverride = true
}
},
onImportLossless = a.onImportLossless,
gameProfileId = frameGenProfileKey,
hasGameOverride = gameFrameGenOverride,
onResetGame = {
val key = frameGenProfileKey
if (key != null) {
com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key)
gameFrameGenMode =
com.droiddeck.launcher.gpu.FrameGen.mode(context)
gameFrameGenOverride = false
}
}
)
}
}
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
@@ -898,6 +968,11 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
}
}
if (host.open == "fg") {
Box(Modifier.fillMaxWidth().padding(top = 4.dp)) {
frameGenMenuContent()
}
}
}
}
@@ -235,7 +235,7 @@ internal fun GameDetail(
steppedTo = null
return@LaunchedEffect
}
focusSoon { tabFocus.getValue(t) }
holdFocus({ onStrip }) { tabFocus.getValue(t) }
steppedTo = null
}
fun cycle(step: Int) {
@@ -243,7 +243,7 @@ internal fun GameDetail(
val at = tabs.indexOf(tab).coerceAtLeast(0)
val next = tabs[(at + step + tabs.size) % tabs.size]
picked = next
if (inPage) steppedTo = next
steppedTo = next
}
val art: Any? = game?.hero ?: item?.imageUrl ?: installed?.sidecar?.hero ?: installed?.sidecar?.cover
val artModel: Any? = if (art is String) cardArtRequest(art, item?.tallImageUrl) else art
@@ -23,6 +23,9 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.draw.clip
@@ -31,6 +34,7 @@ import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.sp
import androidx.compose.runtime.getValue
import com.droiddeck.launcher.session.SessionPrefs
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
@@ -67,6 +71,21 @@ internal val GlassesIcon: ImageVector by lazy {
}.build()
}
@Composable
internal fun rememberShowGlassesShortcut(): Boolean {
val context = LocalContext.current
var show by remember(context) { mutableStateOf(SessionPrefs.showGlassesShortcut(context)) }
DisposableEffect(context) {
val preferences = context.getSharedPreferences("session", android.content.Context.MODE_PRIVATE)
val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
if (key == "showGlassesShortcut") show = SessionPrefs.showGlassesShortcut(context)
}
preferences.registerOnSharedPreferenceChangeListener(listener)
onDispose { preferences.unregisterOnSharedPreferenceChangeListener(listener) }
}
return show
}
@Composable
internal fun rememberGlasses(): Pair<GlassesState, GlassesSettings> {
val g by Glasses.state.collectAsState()
@@ -88,7 +107,7 @@ internal fun VrControllerGroups(host: MenuHost, track: (String) -> Modifier = {
androidx.compose.runtime.LaunchedEffect(Unit) { com.droiddeck.launcher.input.VrControllers.load(context) }
val c by com.droiddeck.launcher.input.VrControllers.settings.collectAsState()
val emulate = com.droiddeck.launcher.input.VrControllers.Emulate.entries
SettingsGroup(stringResource(R.string.vr_controllers_group)) {
SettingsGroup(stringResource(R.string.vr_controllers_group), key = "vr-controllers") {
ChoiceRow(host, "vr-emulate", stringResource(R.string.vr_controllers_emulate), stringResource(R.string.vr_controllers_emulate_hint),
emulate.map { it to stringResource(when (it) {
com.droiddeck.launcher.input.VrControllers.Emulate.OFF -> R.string.vr_controllers_off
@@ -133,6 +152,7 @@ internal fun GlassesGroups(
) {
val display = tab == null || tab == GlassesTab.DISPLAY
val vr = tab == null || tab == GlassesTab.VR
val showShortcut = rememberShowGlassesShortcut()
val picture = GlassesRendering.picture(s, g.sbs, steamVrRunning)
val usesGlasses = GlassesRendering.usesGlasses(g, outputActive, steamVrRunning)
val spatialTracking = g.spatialConnected && s.positionalTracking
@@ -142,13 +162,13 @@ internal fun GlassesGroups(
val directView = usesGlasses && picture == GlassesRendering.Picture.STEREO
val menuScreen = !inSession && g.usable && s.gameOnGlasses && s.screen3dof
if (g.canControl && onRecenter != null && s.headTracking && (virtualScreen || menuScreen || (directView && steamVrRunning))) {
SettingsGroup(stringResource(R.string.glasses_quick_actions), compact = true) {
SettingsGroup(stringResource(R.string.glasses_quick_actions), compact = true, key = "vr-glasses-quick") {
ActionRow(stringResource(R.string.glasses_recenter),
if (virtualScreen || menuScreen) stringResource(R.string.glasses_recenter_screen_hint) else null,
stringResource(R.string.cardboard_recenter_button), onRecenter)
}
}
if (display) SettingsGroup(g.model) {
if (display) SettingsGroup(g.model, key = "vr-glasses") {
if (g.experimental) SettingsRow(stringResource(R.string.glasses_control), stringResource(
if (g.supportsDisplayModeControl) R.string.glasses_xreal_experimental else R.string.glasses_pro2_experimental)) {}
val status = if (g.hasDisplay) stringResource(R.string.glasses_status, g.width, g.height, kotlin.math.round(g.hz).toInt(),
@@ -168,9 +188,15 @@ internal fun GlassesGroups(
}
ToggleRow(host, "glasses-game", stringResource(R.string.glasses_game_on), stringResource(R.string.glasses_game_on_hint),
s.gameOnGlasses, chipModifier = track("glasses-game")) { Glasses.setGameOnGlasses(it) }
if (inSession) {
val context = androidx.compose.ui.platform.LocalContext.current
ToggleRow(host, "glasses-shortcut", stringResource(R.string.glasses_show_shortcut),
stringResource(R.string.glasses_show_shortcut_hint), showShortcut,
chipModifier = track("glasses-shortcut")) { SessionPrefs.setShowGlassesShortcut(context, it) }
}
}
if (display && g.canControl && g.supportsDisplayModeControl && (inSession || g.sbs || g.sbsSupport == GlassesState.SBS_FAILS)) {
SettingsGroup(stringResource(R.string.glasses_display_mode)) {
SettingsGroup(stringResource(R.string.glasses_display_mode), key = "vr-glasses-mode") {
if (g.sbsSupport == GlassesState.SBS_FAILS && !g.sbs) {
ActionRow(stringResource(R.string.glasses_3d), stringResource(R.string.glasses_3d_failed),
stringResource(R.string.stores_dl_retry), { Glasses.set3d(true) })
@@ -182,12 +208,12 @@ internal fun GlassesGroups(
val profiles = if (inSession) listOf(GlassesDisplayModes.profile(g.sbs, false))
else listOf(GlassesDisplayProfile.TWO_D, GlassesDisplayProfile.THREE_D)
for (profile in profiles) SettingsGroup(stringResource(if (profile == GlassesDisplayProfile.TWO_D)
R.string.glasses_output_2d else R.string.glasses_output_3d)) {
R.string.glasses_output_2d else R.string.glasses_output_3d), key = "vr-glasses-output-${profile.name.lowercase()}") {
GlassesResolutionRow(host, g, s, profile, track)
if ((profile == GlassesDisplayProfile.THREE_D) == g.sbs) GlassesRefreshRow(host, g, s, track)
}
}
if (display && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.glasses_picture_group)) {
if (display && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.glasses_picture_group), key = "vr-glasses-picture") {
ChoiceRow(host, "glasses-picture", stringResource(R.string.glasses_picture), stringResource(R.string.glasses_picture_hint),
listOf(
GlassesSettings.PICTURE_AUTO to stringResource(R.string.glasses_picture_auto),
@@ -213,7 +239,7 @@ internal fun GlassesGroups(
format = { SpatialMeasurements.distance(it / 10f) }, modifier = track("glasses-distance")) { Glasses.setScreenDistanceDm(it) }
}
}
if (vr && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.cardboard_steamvr)) {
if (vr && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.cardboard_steamvr), key = "vr-glasses-steamvr") {
steamVr()
if (g.supportsDisplayModeControl) ToggleRow(host, "glasses-auto3d", stringResource(R.string.glasses_auto3d),
stringResource(R.string.glasses_auto3d_hint), s.auto3d, chipModifier = track("glasses-auto3d")) { Glasses.setAuto3d(it) }
@@ -226,7 +252,7 @@ internal fun GlassesGroups(
format = { "$it°" }, modifier = track("glasses-vr-fov")) { Glasses.setVrFovDeg(it) }
}
if ((tab == null || tab == GlassesTab.TRACKING) && g.canControl) {
SettingsGroup(stringResource(R.string.glasses_head_tracking)) {
SettingsGroup(stringResource(R.string.glasses_head_tracking), key = "vr-glasses-tracking") {
val trackingHint = when {
inSession && !usesGlasses -> R.string.glasses_screen_no_output
spatialVr -> R.string.glasses_head_tracking_spatial_vr_hint
@@ -240,13 +266,13 @@ internal fun GlassesGroups(
chipModifier = track("glasses-tracking")) { Glasses.setHeadTracking(it) }
}
val calibration by Glasses.calibration.collectAsState()
if (calibration.supported) SettingsGroup(stringResource(R.string.glasses_calibration)) {
if (calibration.supported) SettingsGroup(stringResource(R.string.glasses_calibration), key = "vr-glasses-calibration") {
GlassesCalibrationControls(calibration,
onStart = Glasses::startCalibration, onCancel = Glasses::cancelCalibration,
onReset = Glasses::resetCalibration, onDone = { onRecenter?.invoke() })
}
}
if ((tab == null || tab == GlassesTab.HARDWARE) && g.canControl && g.hardwareControls) SettingsGroup(stringResource(R.string.glasses_hardware)) {
if ((tab == null || tab == GlassesTab.HARDWARE) && g.canControl && g.hardwareControls) SettingsGroup(stringResource(R.string.glasses_hardware), key = "vr-glasses-hardware") {
if (g.brightnessMax > 0) SliderRow(stringResource(R.string.glasses_brightness), null, g.brightness.coerceAtLeast(0), 0..g.brightnessMax, step = 1,
modifier = track("glasses-brightness")) { Glasses.setBrightness(it) }
if (g.volumeMax > 0) SliderRow(stringResource(R.string.glasses_volume), null, g.volume.coerceAtLeast(0), 0..g.volumeMax, step = 1,
@@ -259,7 +285,7 @@ internal fun GlassesGroups(
androidx.compose.runtime.LaunchedEffect(Unit) { HandTracking.load(context) }
if ((tab == null || tab == GlassesTab.TRACKING) && g.canControl) {
if (g.spatialConnected) {
SettingsGroup(stringResource(R.string.glasses_experimental)) {
SettingsGroup(stringResource(R.string.glasses_experimental), key = "vr-glasses-experimental") {
val spatial by SpatialTracking.status.collectAsState()
ToggleRow(host, "glasses-position", stringResource(R.string.glasses_position), stringResource(R.string.glasses_position_hint),
s.positionalTracking, chipModifier = track("glasses-position")) { Glasses.setPositionalTracking(it) }
@@ -282,7 +308,7 @@ internal fun GlassesGroups(
s.joyConTracking, enabled = s.positionalTracking, chipModifier = track("glasses-joycons")) { Glasses.setJoyConTracking(it) }
}
}
if (hands.usable) SettingsGroup(stringResource(R.string.phone_camera_tracking_group)) {
if (hands.usable) SettingsGroup(stringResource(R.string.phone_camera_tracking_group), key = "vr-hand-camera") {
HandCameraRows(host, track, inSession)
}
}
@@ -21,12 +21,20 @@ internal fun GlassesSetupPanel() {
val (glasses, settings) = rememberGlasses()
val host = rememberMenuHost()
val tabs = glassesTabs(glasses)
val context = androidx.compose.ui.platform.LocalContext.current
val showShortcut = rememberShowGlassesShortcut()
var selectedTab by rememberSaveable { mutableStateOf(GlassesTab.DISPLAY) }
val tab = selectedTab.takeIf { selected -> tabs.any { it.first == selected } } ?: GlassesTab.DISPLAY
LaunchedEffect(tab, glasses.present, glasses.canControl, glasses.model) { host.open = null }
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Note(stringResource(R.string.setup_glasses_scope))
SettingsGroup(stringResource(R.string.glasses_shortcut_group), key = "glasses-shortcut") {
ToggleRow(host, "glasses-shortcut", stringResource(R.string.glasses_show_shortcut),
stringResource(R.string.glasses_show_shortcut_hint), showShortcut) {
com.droiddeck.launcher.session.SessionPrefs.setShowGlassesShortcut(context, it)
}
}
if (!glasses.present && !glasses.hasDisplay && !glasses.canControl) {
Note(stringResource(R.string.setup_glasses_connect))
} else {
@@ -76,7 +76,7 @@ internal fun WindowDialog(
content: @Composable () -> Unit,
) {
if (!LocalPresentationWindow.current) {
Dialog(onDismissRequest, properties, content)
Dialog(onDismissRequest, properties) { SolidSurfaces(content) }
return
}
Popup(
@@ -87,7 +87,7 @@ internal fun WindowDialog(
Modifier.fillMaxSize().background(androidx.compose.ui.graphics.Color.Black.copy(alpha = 0.6f))
.tapOutside { if (properties.dismissOnClickOutside) onDismissRequest() },
contentAlignment = Alignment.Center,
) { content() }
) { SolidSurfaces(content) }
}
}
@@ -150,7 +150,7 @@ internal fun GlidePopup(
) {
Popup(popupPositionProvider, onDismissRequest, properties) {
if (properties.focusable) TrackKeyWindow()
FocusGlideHost(content = content)
SolidSurfaces { FocusGlideHost(content = content) }
}
}
@@ -44,6 +44,7 @@ import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.hypot
import kotlin.math.max
import kotlin.math.min
@SuppressLint("ViewConstructor")
@@ -63,6 +64,7 @@ class InputSurfaceView(
private val art by lazy(LazyThreadSafetyMode.NONE) { PadArt(context) }
private var artworkDpad = emptyList<HoldButton>()
private val artworkDpadBounds = RectF()
private var crossDpads = emptyList<Pair<List<HoldButton>, RectF>>()
private var requestedLayout = customLayout
init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) }
@@ -185,6 +187,7 @@ class InputSurfaceView(
private fun renderCustom(pad: PadBridge?) {
artworkDpad = emptyList()
crossDpads = emptyList()
val canvas = object : ViewGroup(context) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val layout = customLayout
@@ -203,6 +206,7 @@ class InputSurfaceView(
child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight)
}
updateArtworkDpad(this)
updateCrossDpad(this)
}
override fun dispatchDraw(canvas: Canvas) {
@@ -244,11 +248,39 @@ class InputSurfaceView(
canvas.getChildAt(index) as? HoldButton
}
val previous = artworkDpad
artworkDpad = if (crossed(buttons)) buttons else emptyList()
artworkDpad = if (crossed(buttons, artworkDpadBounds)) buttons else emptyList()
if (artworkDpad != previous) (previous + artworkDpad).forEach { it.invalidate() }
}
private fun crossed(buttons: List<HoldButton>): Boolean {
private fun updateCrossDpad(canvas: ViewGroup) {
val buttons = (0 until canvas.childCount).map(canvas::getChildAt).filterIsInstance<HoldButton>()
val (ups, rights, downs, lefts) = DIRECTIONS.map { direction -> buttons.filter { (it.tag as? InputSurfaceElement)?.control == direction } }
crossDpads = ups.flatMap { up -> rights.flatMap { right -> downs.flatMap { down ->
lefts.mapNotNull { left -> listOf(up, right, down, left).let { arms -> hole(arms)?.let { arms to it } } } } } }
}
private fun hole(buttons: List<HoldButton>): RectF? {
val (up, right, down, left) = buttons
val hole = RectF(left.right.toFloat(), up.bottom.toFloat(), right.left.toFloat(), down.top.toFloat())
val across = max(up.left, down.left) to min(up.right, down.right)
val along = max(left.top, right.top) to min(left.bottom, right.bottom)
return hole.takeIf {
!it.isEmpty && across.first < across.second && along.first < along.second &&
across.first < it.right && across.second > it.left && along.first < it.bottom && along.second > it.top
}
}
private fun crossTarget(x: Float, y: Float): HoldButton? {
val first = crossDpads.firstOrNull()?.first?.first() ?: return null
val hx = x - (originX(first) - first.left)
val hy = y - (originY(first) - first.top)
return crossDpads.filter { (arms, hole) -> arms.all { it.visibility == VISIBLE } && hole.contains(hx, hy) }
.flatMap { it.first }.distinct().minByOrNull { arm ->
hypot(max(max(arm.left - hx, hx - arm.right), 0f), max(max(arm.top - hy, hy - arm.bottom), 0f))
}
}
private fun crossed(buttons: List<HoldButton>, bounds: RectF): Boolean {
if (buttons.size != DIRECTIONS.size) return false
val (up, right, down, left) = buttons
val centerX = (left.left + right.right) / 2f
@@ -258,7 +290,7 @@ class InputSurfaceView(
kotlin.math.abs((left.top + left.bottom) / 2f - centerY) > 2f ||
kotlin.math.abs((right.top + right.bottom) / 2f - centerY) > 2f ||
up.bottom >= down.top || left.right >= right.left) return false
artworkDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat())
bounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat())
return true
}
@@ -284,6 +316,7 @@ class InputSurfaceView(
val views = (canvas.childCount - 1 downTo 0).map(canvas::getChildAt).filter { it.visibility == VISIBLE }
views.firstOrNull { !(it is StickView && it.adaptive) && hits(it, x, y, 0f) }?.let { return it }
views.filter { it is HoldButton && hits(it, x, y, slack(it)) }.minByOrNull { distance(it, x, y) }?.let { return it }
crossTarget(x, y)?.let { return it }
if (views.any { it is HoldButton && hits(it, x, y, slack(it) + ADAPTIVE_CLEARANCE_PX) }) return null
return views.filter { it is StickView && it.adaptive && it !in owners.values && (hits(it, x, y, 0f) || it.captures(x - originX(it), y - originY(it))) }
.minByOrNull { distance(it, x, y) }
@@ -0,0 +1,130 @@
package com.droiddeck.launcher.ui
import android.app.Activity
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.PowerManager
import android.view.WindowManager
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.graphics.luminance
import java.util.function.Consumer
internal val LocalFrost = staticCompositionLocalOf<Color?> { null }
internal const val FROST_MAX = 100
internal const val FROST_STEP = 10
internal const val FROST_DEFAULT = 50
internal const val FROST_WALLPAPER_DEFAULT = 80
private const val FROST_TEXT_LIFT = 0.5f
private const val FROST_LIFT_STEPS = 5
private const val FROST_TINT_MAX = 0.9f
private const val FROST_SEARCH_STEPS = 12
private const val FROST_BLUR_DP = 28
private class FrostScale(val solid: Float, val default: Float, val clear: Float) {
fun at(percent: Int): Float {
val t = percent.coerceIn(0, FROST_MAX) / FROST_DEFAULT.toFloat()
return if (t <= 1f) solid + (default - solid) * t else default + (clear - default) * (t - 1f)
}
}
private val TINT_DARK = FrostScale(0.9f, 0.58f, 0.32f)
private val TINT_LIGHT = FrostScale(0.94f, 0.7f, 0.48f)
private val CARD_DARK = FrostScale(1f, 0.6f, 0.3f)
private val CARD_LIGHT = FrostScale(1f, 0.74f, 0.45f)
private val TEXT_LIFT_MAX = FrostScale(FROST_TEXT_LIFT, FROST_TEXT_LIFT, 1f)
class FrostChoice(
val transparency: Int = FROST_WALLPAPER_DEFAULT,
val cards: Boolean = false,
val cardTransparency: Int = FROST_DEFAULT,
)
internal class FrostLook(val veil: Color, val lift: Float, val cardAlpha: Float)
internal fun frostLook(palette: Palette, choice: FrostChoice): FrostLook {
val light = palette.background.luminance() > 0.5f
val cardAlpha = if (!choice.cards) 1f else (if (light) CARD_LIGHT else CARD_DARK).at(choice.cardTransparency)
val maxLift = maxOf(TEXT_LIFT_MAX.at(choice.transparency), if (choice.cards) TEXT_LIFT_MAX.at(choice.cardTransparency) else 0f)
// Android reports only the wallpaper's main colours, and any part of it can sit behind text.
fun readable(alpha: Float, lift: Float): Boolean = listOf(Color.Black, Color.White).all { behind ->
val page = palette.background.copy(alpha = alpha).compositeOver(behind)
val card = palette.surface.copy(alpha = cardAlpha).compositeOver(page)
val hint = lerp(palette.onSurfaceVariant, palette.onBackground, lift)
minOf(ThemeColors.contrast(hint, page), ThemeColors.contrast(hint, card)) >= ThemeColors.MIN_CONTRAST
}
var low = 0f
var high = FROST_TINT_MAX
if (readable(low, maxLift)) high = low
else if (!readable(high, maxLift)) high = 1f
else repeat(FROST_SEARCH_STEPS) {
val mid = (low + high) / 2
if (readable(mid, maxLift)) high = mid else low = mid
}
val lifts = (0..FROST_LIFT_STEPS).map { FROST_TEXT_LIFT + (maxLift - FROST_TEXT_LIFT) * it / FROST_LIFT_STEPS }
val tint = maxOf((if (light) TINT_LIGHT else TINT_DARK).at(choice.transparency), kotlin.math.ceil(high * 255f) / 255f)
val alpha = if (lifts.any { readable(tint, it) }) tint else 1f
val lift = lifts.firstOrNull { readable(alpha, it) } ?: maxLift
return FrostLook(palette.background.copy(alpha = alpha), lift, cardAlpha)
}
internal fun Palette.frosted(look: FrostLook): Palette = Palette(
id, label, detail,
background = background,
surface = if (look.cardAlpha < 1f) surface.copy(alpha = look.cardAlpha) else surface,
surfaceVariant = if (look.cardAlpha < 1f) surfaceVariant.copy(alpha = look.cardAlpha) else surfaceVariant,
line = line, line2 = line2,
onBackground = onBackground, onSurfaceVariant = lerp(onSurfaceVariant, onBackground, look.lift),
primary = primary, primary2 = primary2, onPrimary = onPrimary, signal = signal,
good = good, error = error, warning = warning,
)
internal class LauncherFrost(private val activity: Activity) {
var available by mutableStateOf(false)
private set
var prepared = false
private set
private var stopListening: (() -> Unit)? = null
val supported: Boolean
get() = Build.VERSION.SDK_INT >= 31 &&
(available || activity.getSystemService(PowerManager::class.java)?.isPowerSaveMode == true)
fun start() {
if (Build.VERSION.SDK_INT < 31 || stopListening != null) return
val windows = activity.windowManager
val blur = Consumer<Boolean> { available = it }
available = windows.isCrossWindowBlurEnabled
windows.addCrossWindowBlurEnabledListener(blur)
stopListening = { windows.removeCrossWindowBlurEnabledListener(blur) }
}
fun stop() {
stopListening?.invoke()
stopListening = null
}
// A window made see-through after its first frame keeps drawing over its old frames, so this runs before setContent.
fun prepare(on: Boolean) {
prepared = on && Build.VERSION.SDK_INT >= 31
if (prepared) activity.window.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT))
}
fun show(on: Boolean) {
if (!prepared || Build.VERSION.SDK_INT < 31) return
val window = activity.window
val flags = WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER or WindowManager.LayoutParams.FLAG_BLUR_BEHIND
if (on) window.addFlags(flags) else window.clearFlags(flags)
window.attributes = window.attributes.apply {
blurBehindRadius = if (on) (FROST_BLUR_DP * activity.resources.displayMetrics.density).toInt() else 0
}
}
}
@@ -531,13 +531,11 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
val grid = remember { LazyGridState() }
val detailScroll = rememberScrollState()
var cycled by remember { mutableIntStateOf(0) }
var gridFocused by remember { mutableStateOf(false) }
LaunchedEffect(source, sort) { grid.scrollToItem(0) }
LaunchedEffect(cycled) {
if (cycled == 0 || ff == null || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect
focusWithinFrames({ gridFocused }) {
if (ff.firstTileAttached > 0) ff.firstTile else ff.items["libchip:$source"] ?: FocusRequester.Default
}
val chip = "libchip:$source"
holdFocus({ ff.last == chip }) { ff.items[chip] }
}
CardDetailHost(
open, detailScroll,
@@ -563,7 +561,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
else { focusManager.clearFocus(force = true); onSelect(it) }
},
searchCleared = open != null,
onFocus = { gridFocused = it },
onFocus = {},
soundMode = soundMode,
wallArt = { wallTiles(all.filterNot(concealed).mapNotNull { entryArt(it, tall = true) }) },
emptyText = when {
@@ -753,20 +751,23 @@ private fun LibraryGrid(
}
}
}
val manage = !soundMode && !s.shortcutPicker
LazyVerticalGrid(
columns = if (listMode) GridCells.Fixed(1) else remember(baseWidth, level) { LevelCells(baseWidth, level) }, state = grid,
modifier = Modifier.fillMaxSize().onFocusChanged { onFocus(it.hasFocus) }.focusGroup().bumpers(onPrevious = { onCycle(-1) }, onNext = { onCycle(1) }).onSizeChanged {
val gap = with(density) { 10.dp.roundToPx() }
columns = if (listMode) 1 else libraryColumns(it.width, with(density) { baseWidth.roundToPx() }, gap, level)
gridH = it.height
},
modifier = Modifier.fillMaxSize().onFocusChanged { onFocus(it.hasFocus) }.focusGroup()
.then(if (sourceChipsShown(sources, manage)) Modifier.bumpers(onPrevious = { onCycle(-1) }, onNext = { onCycle(1) }) else Modifier)
.onSizeChanged {
val gap = with(density) { 10.dp.roundToPx() }
columns = if (listMode) 1 else libraryColumns(it.width, with(density) { baseWidth.roundToPx() }, gap, level)
gridH = it.height
},
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
) {
val header: @Composable () -> Unit = {
LibraryHeader(s, a, if (soundMode) total else visible.size + hiddenUninstalled, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }, soundMode = soundMode, onAddSoundtrack = onAddSoundtrack, onCollections = onCollections, source = source)
}
val filters: @Composable () -> Unit = { LibraryFilters(sources, source, onSource, manage = !soundMode && !s.shortcutPicker) }
val filters: @Composable () -> Unit = { LibraryFilters(sources, source, onSource, manage) }
item(key = if (soundMode) "header" else "filters", span = { GridItemSpan(maxLineSpan) }) {
Box(Modifier.onSizeChanged { chipsH = it.height }) { Rise(0) { if (soundMode) header() else filters() } }
}
@@ -908,10 +909,13 @@ private fun LibraryHeader(
if (s.steamGamesX64 && narrow) Box(Modifier.padding(top = 4.dp)) { ClientTag() }
}
private fun sourceChipsShown(sources: List<String>, manage: Boolean): Boolean =
(manage && sources.isNotEmpty()) || sources.size >= 2 || sources.singleOrNull() == LIBRARY_HIDDEN
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
private fun LibraryFilters(sources: List<String>, source: String, onSource: (String) -> Unit, manage: Boolean) {
val chips = (manage && sources.isNotEmpty()) || sources.size >= 2 || sources.singleOrNull() == LIBRARY_HIDDEN
val chips = sourceChipsShown(sources, manage)
if (!chips && !manage) return
val pal = LocalPalette.current
val keys = if (chips) listOf(LIBRARY_ALL) + sources else emptyList()
@@ -116,10 +116,7 @@ internal object NavTabs {
fun more(s: FrontEndState) = listed(s).filter { place(s, it) == TabPlace.MORE }
fun bar(s: FrontEndState): List<String> {
val shown = listed(s).filter { place(s, it) == TabPlace.BAR }
return if (more(s).isEmpty()) shown else shown + MORE
}
fun bar(s: FrontEndState): List<String> = listed(s).filter { place(s, it) == TabPlace.BAR } + MORE
fun setHidden(context: Context, key: String, hide: Boolean) {
hidden = if (hide && hideable(key)) hidden + key else hidden - key
@@ -8,6 +8,9 @@ import com.droiddeck.launcher.input.PcKey
import androidx.compose.ui.res.stringResource
import android.view.KeyEvent
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
@@ -69,6 +72,9 @@ fun PcKeyboard(
sendKey: (Int, Boolean) -> Unit,
onAndroidKeyboard: () -> Unit,
onClose: () -> Unit,
heightFraction: Float? = null,
showButtons: Boolean = true,
hoverFeedback: Boolean = false,
) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
@@ -76,31 +82,40 @@ fun PcKeyboard(
var capsOn by remember { mutableStateOf(false) }
val firstKey = remember { FocusRequester() }
val shifted = (mods[42] ?: MOD_OFF) != MOD_OFF || (mods[54] ?: MOD_OFF) != MOD_OFF
// Keys go to wherever sendKey points now, but a held key is let go where it went down.
val currentSend by androidx.compose.runtime.rememberUpdatedState(sendKey)
val heldAt = remember { mutableMapOf<Int, (Int, Boolean) -> Unit>() }
fun down(code: Int) {
val send = currentSend
heldAt[code] = send
send(code, true)
}
fun up(code: Int) = (heldAt.remove(code) ?: currentSend)(code, false)
fun releaseOnceModifiers() {
for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { sendKey(code, false); mods[code] = MOD_OFF }
for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { up(code); mods[code] = MOD_OFF }
}
fun press(key: PcKey) {
if (key.code in PC_MODIFIERS) {
when (mods[key.code] ?: MOD_OFF) {
MOD_OFF -> { sendKey(key.code, true); mods[key.code] = MOD_ONCE }
MOD_OFF -> { down(key.code); mods[key.code] = MOD_ONCE }
MOD_ONCE -> mods[key.code] = MOD_LOCKED
else -> { sendKey(key.code, false); mods[key.code] = MOD_OFF }
else -> { up(key.code); mods[key.code] = MOD_OFF }
}
return
}
sendKey(key.code, true)
down(key.code)
}
fun release(key: PcKey) {
if (key.code in PC_MODIFIERS) return
sendKey(key.code, false)
up(key.code)
if (key.code == 58) capsOn = !capsOn
releaseOnceModifiers()
}
androidx.compose.runtime.DisposableEffect(Unit) {
onDispose { for ((code, state) in mods.toMap()) if (state != MOD_OFF) sendKey(code, false) }
onDispose { for (code in heldAt.keys.toList()) up(code) }
}
LaunchedEffect(Unit) { runCatching { firstKey.requestFocus() } }
LaunchedEffect(Unit) { if (!hoverFeedback) runCatching { firstKey.requestFocus() } }
val prefsContext = LocalContext.current
remember { PcKeyboardPrefs.load(prefsContext) }
@@ -108,7 +123,7 @@ fun PcKeyboard(
val rows = PC_KEY_ROWS.map { row -> row.filter { it.code !in hiddenCodes } }.filter { it.isNotEmpty() }
BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) {
val rowHeight = ((maxHeight * (PcKeyboardPrefs.size / 100f) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size)
val rowHeight = ((maxHeight * (heightFraction ?: (PcKeyboardPrefs.size / 100f)) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size)
.coerceIn(20.dp, 56.dp)
Box(
Modifier.fillMaxWidth()
@@ -122,9 +137,11 @@ fun PcKeyboard(
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(24.dp)) {
Text(stringResource(R.string.drawer_pc_keyboard), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant)
Spacer(Modifier.weight(1f))
HeaderButton(stringResource(R.string.pckb_android), onAndroidKeyboard)
Spacer(Modifier.width(8.dp))
HeaderButton(stringResource(R.string.pckb_hide), onClose)
if (showButtons) {
HeaderButton(stringResource(R.string.pckb_android), onAndroidKeyboard)
Spacer(Modifier.width(8.dp))
HeaderButton(stringResource(R.string.pckb_hide), onClose)
}
}
rows.forEachIndexed { r, row ->
Row(horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.fillMaxWidth().height(rowHeight)) {
@@ -139,7 +156,7 @@ fun PcKeyboard(
}
key(key.code) {
KeyCap(
label, key.weight, lit, locked = state == MOD_LOCKED,
label, key.weight, lit, locked = state == MOD_LOCKED, hoverFeedback = hoverFeedback,
modifier = if (r == 0 && i == 0) Modifier.focusRequester(firstKey) else Modifier,
onDown = { press(key) }, onUp = { release(key) },
)
@@ -154,25 +171,35 @@ fun PcKeyboard(
@Composable
private fun RowScope.KeyCap(
label: String, weight: Float, lit: Boolean, locked: Boolean,
label: String, weight: Float, lit: Boolean, locked: Boolean, hoverFeedback: Boolean,
modifier: Modifier, onDown: () -> Unit, onUp: () -> Unit,
) {
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val focused by src.collectIsFocusedAsState()
val hovered by src.collectIsHoveredAsState()
val (pointedAt, laser) = com.droiddeck.launcher.session.xr.rememberXrPointed()
val pointed = hoverFeedback && (hovered || laser.value)
var down by remember { mutableStateOf(false) }
val fill by animateColorAsState(
when {
down -> pal.signal.copy(alpha = 0.55f)
lit -> pal.signal.copy(alpha = if (locked) 0.45f else 0.28f)
pointed -> Color.White.copy(alpha = 0.2f)
else -> Color.White.copy(alpha = 0.07f)
}, Motion.tw(160), label = "keyFill",
}, Motion.tw(if (down) 40 else 160), label = "keyFill",
)
val scale by animateFloatAsState(
if (!hoverFeedback) 1f else if (down) 0.9f else if (pointed) 1.06f else 1f, Motion.tw(if (down) 40 else 140), label = "keyScale",
)
Box(
contentAlignment = Alignment.Center,
modifier = modifier.weight(weight).fillMaxHeight()
.then(pointedAt)
.graphicsLayer { scaleX = 1f + (scale - 1f) * size.height / size.width; scaleY = scale }
.background(fill, RoundedCornerShape(7.dp))
.glideBorder(focused, RoundedCornerShape(7.dp), pal.signal, if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f))
.glideBorder(if (hoverFeedback) pointed || down else focused, RoundedCornerShape(7.dp), pal.signal, if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f))
.then(if (hoverFeedback) Modifier.hoverable(src) else Modifier)
.pointerInput(Unit) {
awaitEachGesture {
awaitFirstDown().consume()
@@ -11,7 +11,7 @@ internal fun PenSettingsGroup(
host: MenuHost, pen: SessionPrefs.Pen, track: (String) -> Modifier = { Modifier },
onPick: (key: String, value: String) -> Unit,
) {
SettingsGroup(stringResource(R.string.mode_pen)) {
SettingsGroup(stringResource(R.string.mode_pen), key = "controller-pen") {
ChoiceRow(host, "pen", stringResource(R.string.mode_pen), null,
listOf(SessionPrefs.PEN_MOUSE to stringResource(R.string.mode_pen_mouse),
SessionPrefs.PEN_TOUCH to stringResource(R.string.mode_pen_touch)),
@@ -49,6 +49,7 @@ fun PerformancePage(
prootNoSeccomp: Boolean,
prootFastPath: Boolean,
nativeUserland: Boolean,
desktopAsUser: Boolean,
cursorComposite: Boolean,
guestHostname: String,
phantomWarning: String?,
@@ -67,6 +68,7 @@ fun PerformancePage(
onProotNoSeccomp: (Boolean) -> Unit,
onProotFastPath: (Boolean) -> Unit,
onNativeUserland: (Boolean) -> Unit,
onDesktopAsUser: (Boolean) -> Unit,
onCursorComposite: (Boolean) -> Unit,
onGuestHostname: (String) -> Unit,
onClientCore: (Int, Boolean) -> Unit,
@@ -194,6 +196,12 @@ fun PerformancePage(
modifier = Modifier.width(220.dp).focusGlide(),
)
}
ToggleRow(
host, "desktopasuser", stringResource(R.string.perf_desktop_as_user),
stringResource(if (nativeUserland) R.string.perf_desktop_as_user_hint else R.string.perf_desktop_as_user_needs_native),
desktopAsUser && nativeUserland, enabled = nativeUserland,
onChange = onDesktopAsUser,
)
}
if (phantomWarning != null) {
Spacer(Modifier.height(16.dp))
@@ -218,7 +226,7 @@ fun PerformancePage(
@Composable
internal fun GpuClockGroup(host: MenuHost, on: Boolean, chipModifier: Modifier = Modifier, onChange: (Boolean) -> Unit) {
SettingsGroup(stringResource(R.string.perf_gpu)) {
SettingsGroup(stringResource(R.string.perf_gpu), key = "performance-gpu") {
ToggleRow(
host, "gpuclock", stringResource(R.string.perf_gpuclock),
null,
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.compose.foundation.gestures.awaitEachGesture
@@ -48,10 +49,18 @@ internal fun releaseTextField(field: EditText, origin: IntArray, x: Float, y: Fl
val insideX = x >= origin[0] - margin && x <= origin[0] + field.width + margin
val insideY = y >= origin[1] - margin && y <= origin[1] + field.height + margin
if (insideX && insideY) return
releaseTextField(field)
}
internal fun releaseTextField(field: EditText) {
field.clearFocus()
(field.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(field.windowToken, 0)
}
internal fun releaseFocusedTextField(view: View) {
(view.rootView.findFocus() as? EditText)?.let(::releaseTextField)
}
/** A dialog's touches never reach the activity, so a dialog holding a search field counts its taps and releases the field itself. */
internal fun Modifier.releaseTextFieldOnTap(): Modifier = composed {
val view = LocalView.current
@@ -25,6 +25,7 @@ import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.droiddeck.launcher.input.DeckPanel
import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.wayland.WaylandCompositor
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.BottomDesktop
@@ -490,12 +491,19 @@ class SecondScreenPresentation(
}
private fun attachKeyboard() {
val host = KeyboardHost(context) { event ->
val handled = sessionActivity.dispatchKeyEvent(event)
if (fieldKeyboard && event.action == KeyEvent.ACTION_UP &&
(event.keyCode == KeyEvent.KEYCODE_ENTER || event.keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) root.post { closeFieldKeyboard() }
handled
}
val host = KeyboardHost(
context,
sendKeyEvent = { event ->
val handled = sessionActivity.dispatchImeKeyEvent(event)
if (fieldKeyboard && event.action == KeyEvent.ACTION_UP &&
(event.keyCode == KeyEvent.KEYCODE_ENTER || event.keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) root.post { closeFieldKeyboard() }
handled
},
sendText = { text ->
WaylandCompositor.textInputCommit(text)
if (fieldKeyboard && text == "\r") root.post { closeFieldKeyboard() }
},
)
host.onImeChanged = { visible -> if (!visible && keyboardShown.value) keyboardClosed() }
keyboardHost = host
root.addView(host, ViewGroup.LayoutParams(1, 1))
@@ -6,17 +6,19 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.SessionPrefs
/** HUD holds the Performance page and GAMES the Game page; the names stay because saved page orders use them. */
internal enum class SessionDrawerPage(val firstControl: String) {
CONTROLLER("input-profile"),
GLASSES("glasses-game"),
DISPLAY("fg"),
HUD("hud"),
EFFECTS("look"),
GAMES("anisotropy"),
AGENT("agent-input"),
SESSION("suspend"),
CONTROLLER("section-controller-input"),
HUD("section-performance-pacing"),
FRAMEGEN("fg"),
DISPLAY("section-display"),
EFFECTS("section-effects-look"),
GAMES("section-game-profile"),
VR("section-vr-steamvr"),
SESSION("pause"),
MORE("more-edit"),
VR("steamvr"),
ACHIEVEMENTS("achievements"),
AGENT("agent-input"),
}
internal object DrawerPages {
@@ -71,16 +73,16 @@ internal object DrawerPages {
}
internal fun offeredDrawerPages(
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
hasAchievements: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> =
DrawerPages.order.filter {
(hasGlasses || it != SessionDrawerPage.GLASSES) &&
(hasAchievements || it != SessionDrawerPage.ACHIEVEMENTS) &&
(hasAgent || it != SessionDrawerPage.AGENT)
}
internal fun sessionDrawerPages(
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> = offeredDrawerPages(hasGlasses, hasAgent).filter { it !in DrawerPages.hidden }
hasAchievements: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> = offeredDrawerPages(hasAchievements, hasAgent).filter { it !in DrawerPages.hidden }
/** The pages shown as tabs: everything up to and including the More tab. */
internal fun List<SessionDrawerPage>.strip(): List<SessionDrawerPage> {
File diff suppressed because it is too large. Load diff
@@ -39,6 +39,7 @@ internal class SettingsEntry(
val words: List<String> = emptyList(),
val developer: Boolean = false,
val tab: String? = null,
val frost: Boolean = false,
) {
val within: Int? get() = section?.title ?: tab?.let { railLabelIcon(it).first } ?: group
@@ -89,6 +90,7 @@ internal object SettingsIndex {
s(SettingsSection.PERFORMANCE, R.string.perf_native_userland, "proot"),
s(SettingsSection.PERFORMANCE, R.string.perf_cursor_composite, "mouse", "cursor"),
s(SettingsSection.PERFORMANCE, R.string.perf_hostname, "name"),
s(SettingsSection.PERFORMANCE, R.string.perf_desktop_as_user, "root", "user", "sudo", "fakeroot"),
s(SettingsSection.CONTROLLER, R.string.setup_tab_controller, "gamepad", "buttons", "mapping", "profile", "remap"),
SettingsEntry(SettingsPlace.TAB, R.string.rail_storage, tab = "storage", words = listOf("sd card", "space", "uninstall", "disk")),
@@ -99,6 +101,10 @@ internal object SettingsIndex {
s(SettingsSection.GLASSES, R.string.setup_tab_glasses, "xreal", "viture", "vr", "ar"),
s(SettingsSection.LAUNCHER, R.string.setup_theme, "color", "dark"),
SettingsEntry(
SettingsPlace.SETTINGS, R.string.setup_frosted_background, section = SettingsSection.LAUNCHER, frost = true,
words = listOf("blur", "wallpaper", "background", "cards", "transparent", "transparency", "opacity", "glass"),
),
s(SettingsSection.LAUNCHER, R.string.setup_app_scale, "size", "zoom"),
s(SettingsSection.LAUNCHER, R.string.setup_launcher_icon),
s(SettingsSection.LAUNCHER, R.string.setup_animations),
@@ -150,6 +156,6 @@ internal object SettingsIndex {
sh(R.string.stores_tab_library, R.string.stores_tab_library, "second library", "sd card", "steam library"),
)
fun search(context: Context, query: String): List<SettingsEntry> =
entries.filter { (!it.developer || DeveloperTools.on) && it.matches(context, query) }
fun search(context: Context, query: String, frost: Boolean = false): List<SettingsEntry> =
entries.filter { (!it.developer || DeveloperTools.on) && (!it.frost || frost) && it.matches(context, query) }
}
@@ -96,9 +96,9 @@ internal fun SettingsPillSearch(
}
@Composable
internal fun SettingsSearchResults(query: String, onOpen: (SettingsSection) -> Unit) {
internal fun SettingsSearchResults(query: String, frost: Boolean, onOpen: (SettingsSection) -> Unit) {
val ctx = LocalContext.current
val found = remember(query) { SettingsIndex.search(ctx, query) }
val found = remember(query, frost) { SettingsIndex.search(ctx, query, frost) }
if (found.isEmpty()) {
Note(stringResource(R.string.settings_search_none, query.trim()))
return
@@ -87,6 +87,7 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.node.currentValueOf
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
@@ -152,14 +153,43 @@ internal fun Modifier.blockTouches(): Modifier = pointerInput(Unit) { detectTapG
internal fun Modifier.tapOutside(onTap: () -> Unit): Modifier =
pointerInput(onTap) { detectTapGestures(onTap = { onTap() }) }
internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modifier = onPreviewKeyEvent { event ->
val keyEvent = event.nativeKeyEvent
val previous = keyEvent.keyCode == KeyEvent.KEYCODE_BUTTON_L1
if (!previous && keyEvent.keyCode != KeyEvent.KEYCODE_BUTTON_R1) {
false
} else {
if (keyEvent.action == KeyEvent.ACTION_DOWN && keyEvent.repeatCount == 0) { if (previous) onPrevious() else onNext() }
true
internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modifier = this then BumpersElement(onPrevious, onNext)
private data class BumpersElement(val onPrevious: () -> Unit, val onNext: () -> Unit) :
androidx.compose.ui.node.ModifierNodeElement<BumpersNode>() {
override fun create() = BumpersNode(onPrevious, onNext)
override fun update(node: BumpersNode) {
node.onPrevious = onPrevious
node.onNext = onNext
}
}
internal class BumpersNode(var onPrevious: () -> Unit, var onNext: () -> Unit) :
Modifier.Node(), androidx.compose.ui.input.key.KeyInputModifierNode, androidx.compose.ui.node.CompositionLocalConsumerModifierNode {
override fun onAttach() { PageBumpers.attached += this }
override fun onDetach() { PageBumpers.attached -= this }
override fun onPreKeyEvent(event: androidx.compose.ui.input.key.KeyEvent): Boolean = PageBumpers.handle(event.nativeKeyEvent, this)
override fun onKeyEvent(event: androidx.compose.ui.input.key.KeyEvent): Boolean = false
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
fun step(previous: Boolean) {
releaseFocusedTextField(currentValueOf(androidx.compose.ui.platform.LocalView))
OpenMenus.leaveAll(withPage = false)
if (previous) onPrevious() else onNext()
// Android keeps touch mode through gamepad buttons, and the pages move the focus only outside it.
val input = currentValueOf(LocalInputModeManager)
if (input.inputMode != InputMode.Keyboard) input.requestInputMode(InputMode.Keyboard)
}
}
internal object PageBumpers {
val attached = ArrayList<BumpersNode>()
fun handle(event: KeyEvent, node: BumpersNode? = attached.lastOrNull()): Boolean {
val previous = event.keyCode == KeyEvent.KEYCODE_BUTTON_L1
if (node == null || (!previous && event.keyCode != KeyEvent.KEYCODE_BUTTON_R1)) return false
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) node.step(previous)
return true
}
}
@@ -267,6 +297,25 @@ private class BelowEndProvider(private val gap: Int) : PopupPositionProvider {
}
}
private val StepKeys = setOf(KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.KEYCODE_BUTTON_R1, KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2)
private fun launcherOf(view: android.view.View) = view.context.findActivity() as? com.droiddeck.launcher.FrontEndActivity
// A popup is a window of its own, so controller input sent to it never reaches the launcher's.
private fun Modifier.passSteps(host: android.view.View): Modifier = onPreviewKeyEvent { event ->
event.nativeKeyEvent.keyCode in StepKeys && launcherOf(host) != null && host.rootView.dispatchKeyEvent(event.nativeKeyEvent)
}
@Composable
private fun PassTriggerMotion(host: android.view.View) {
val popup = androidx.compose.ui.platform.LocalView.current
androidx.compose.runtime.DisposableEffect(popup, host) {
val launcher = launcherOf(host)?.takeIf { it.window.decorView === host.rootView }
if (launcher != null) popup.setOnGenericMotionListener { _, event -> launcher.onMenuMotion(event); false }
onDispose { popup.setOnGenericMotionListener(null) }
}
}
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
@Composable
fun AnchoredMenu(
@@ -277,6 +326,13 @@ fun AnchoredMenu(
val state = remember { MutableTransitionState(false) }
state.targetState = open
if (!state.currentState && !state.targetState && state.isIdle) return
val dismissNow = rememberUpdatedState(onDismiss)
if (open) androidx.compose.runtime.DisposableEffect(Unit) {
val leave = { _: Boolean -> dismissNow.value() }
OpenMenus.leave += leave
onDispose { OpenMenus.leave -= leave }
}
val hostView = androidx.compose.ui.platform.LocalView.current
val firstItemFocus = remember { FocusRequester() }
val inputMode = LocalInputModeManager.current.inputMode
LaunchedEffect(open, inputMode) {
@@ -294,6 +350,7 @@ fun AnchoredMenu(
val pal = LocalPalette.current
Popup(popupPositionProvider = provider, onDismissRequest = onDismiss, properties = PopupProperties(focusable = true)) {
TrackKeyWindow()
PassTriggerMotion(hostView)
val popupInput = LocalInputModeManager.current
LaunchedEffect(open, inputMode) {
if (!open || inputMode != InputMode.Keyboard) return@LaunchedEffect
@@ -307,7 +364,7 @@ fun AnchoredMenu(
runCatching { firstItemFocus.requestFocus() }
}
}
CompositionLocalProvider(LocalDensity provides density, LocalConfiguration provides configuration) {
SolidSurfaces { CompositionLocalProvider(LocalDensity provides density, LocalConfiguration provides configuration) {
AnimatedVisibility(
visibleState = state,
enter = fadeIn(Motion.tw(180)) + scaleIn(Motion.sp(0.7f), initialScale = 0.94f, transformOrigin = TransformOrigin(if (compact) 0f else 1f, 0f)),
@@ -323,6 +380,7 @@ fun AnchoredMenu(
.clip(RowShape)
.background(pal.surfaceVariant.copy(alpha = 0.95f))
.border(1.dp, pal.signal.copy(alpha = 0.22f), RowShape)
.passSteps(hostView)
.controllerBack(onDismiss)
.padding(6.dp),
) {
@@ -363,7 +421,7 @@ fun AnchoredMenu(
}
}
}
}
} }
}
}
@@ -443,7 +501,11 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
}
@Composable
fun SettingsGroup(title: String, compact: Boolean = false, detail: String? = null, content: @Composable ColumnScope.() -> Unit) {
fun SettingsGroup(title: String, compact: Boolean = false, detail: String? = null, key: String? = null, tag: String? = null, content: @Composable ColumnScope.() -> Unit) {
LocalDrawerSections.current?.let { sections ->
DrawerSection(sections, key ?: title, title, detail, tag, content)
return
}
val tight = compact || LocalCompactSettings.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -462,7 +524,7 @@ fun SettingsGroup(title: String, compact: Boolean = false, detail: String? = nul
}
@Composable
fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hintLines: Int? = null, stacked: Boolean = false, control: @Composable () -> Unit) {
fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hintLines: Int? = null, stacked: Boolean = false, tightControlSpacing: Boolean = false, control: @Composable () -> Unit) {
val compact = LocalCompactSettings.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -484,13 +546,13 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint
} else if (stacked || LocalNarrowPane.current) Column(
modifier = Modifier.fillMaxWidth().background(bg).padding(
horizontal = if (compact) 10.dp else 14.dp,
vertical = if (compact) 6.dp else 12.dp),
vertical = if (tightControlSpacing) 2.dp else if (compact) 6.dp else 12.dp),
) {
Text(label, fontSize = if (compact) 13.sp else 15.sp,
lineHeight = if (compact) 16.sp else androidx.compose.ui.unit.TextUnit.Unspecified,
fontWeight = FontWeight.SemiBold, color = colors.onBackground)
if (hint != null || hintLines != null) hintText(if (compact) 11.sp else 13.sp)
Box(Modifier.padding(top = if (compact) 6.dp else 8.dp)) { control() }
Box(Modifier.padding(top = if (tightControlSpacing) 2.dp else if (compact) 6.dp else 8.dp)) { control() }
} else Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().background(bg).padding(horizontal = 14.dp, vertical = 11.dp),
@@ -2,7 +2,10 @@ package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
@@ -12,8 +15,30 @@ internal fun FrameGenGroup(s: FrontEndState, a: FrontEndActions) {
SettingsGroup(stringResource(R.string.frame_gen_title)) {
SettingsRow(stringResource(R.string.frame_gen_title), stringResource(R.string.frame_gen_hint), highlighted = host.open == "fg") {
Box {
ValueChip(s.frameGenLabel, host.open == "fg") { host.open = if (host.open == "fg") null else "fg" }
FrameGenMenu(host, s.frameGen, s.lossless, a.onFrameGenPick, a.onImportLossless)
val open = host.open == "fg"
ValueChip(s.frameGenLabel, open) { host.open = if (open) null else "fg" }
AnchoredMenu(
open = open,
onDismiss = { if (host.open == "fg") host.open = null },
title = stringResource(R.string.frame_gen_title),
compact = true,
minWidth = 220.dp,
) { firstItemFocus ->
FrameGenMenu(
mode = s.frameGen,
lossless = s.lossless,
onPick = { mode ->
a.onFrameGenPick(mode)
host.open = null
},
onImportLossless = {
a.onImportLossless()
host.open = null
},
focusModifier = Modifier.focusRequester(firstItemFocus),
legacyButtons = true,
)
}
}
}
}
@@ -145,11 +145,16 @@ internal class StepOutScope(private val items: List<Animatable<Float, AnimationV
}
}
internal object OpenMenus {
val leave = ArrayList<(Boolean) -> Unit>()
fun leaveAll(withPage: Boolean) = leave.toList().forEach { it(withPage) }
}
private val OutPull = 6.dp
private val OutBoxCorner = 16.dp
private val OutFillet = 10.dp
@OptIn(ExperimentalComposeUiApi::class)
@Composable
internal fun StepOut(
open: Boolean,
@@ -163,6 +168,22 @@ internal fun StepOut(
items: Int = 4,
handle: @Composable () -> Unit,
content: @Composable StepOutScope.() -> Unit,
) = SolidSurfaces { StepOutPanel(open, pill, preferredSide, accent, onDismiss, onClosed, pillCorner, maxWidth, items, handle, content) }
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun StepOutPanel(
open: Boolean,
pill: Rect,
preferredSide: StepSide,
accent: Color,
onDismiss: () -> Unit,
onClosed: () -> Unit,
pillCorner: Dp?,
maxWidth: Dp,
items: Int,
handle: @Composable () -> Unit,
content: @Composable StepOutScope.() -> Unit,
) {
val colors = MaterialTheme.colorScheme
val density = LocalDensity.current
@@ -179,13 +200,25 @@ internal fun StepOut(
val glide = LocalFocusGlide.current
val opener = remember { arrayOfNulls<GlideSource>(1) }
val openNow = androidx.compose.runtime.rememberUpdatedState(open)
val dismissNow = androidx.compose.runtime.rememberUpdatedState(onDismiss)
val leavesWithPage = remember { booleanArrayOf(false) }
val presence = remember { Animatable(1f) }
if (open) androidx.compose.runtime.DisposableEffect(Unit) {
val leave = { withPage: Boolean ->
opener[0] = null
leavesWithPage[0] = withPage
dismissNow.value()
}
OpenMenus.leave += leave
onDispose { OpenMenus.leave -= leave }
}
var moving by remember { mutableStateOf(false) }
val placed = remember { arrayOfNulls<Any>(3) }
if (moving) VeilRing()
val pull = with(density) { OutPull.toPx() }
val corner = pillCorner?.let { with(density) { it.toPx() } } ?: minOf(pill.height, pill.width) / 2f
BoxWithConstraints(Modifier.fillMaxSize()) {
BoxWithConstraints(Modifier.fillMaxSize().graphicsLayer { alpha = presence.value }) {
val hostWidth = constraints.maxWidth.toFloat()
val hostHeight = constraints.maxHeight.toFloat()
val availableHeight = with(density) {
@@ -206,9 +239,11 @@ internal fun StepOut(
if (grown && flipped) edge.snapTo(if (open) out else rest)
val boxBottom = pill.bottom + pull + c.height
if (open) {
leavesWithPage[0] = false
presence.snapTo(1f)
if (!grown) {
opener[0] = glide?.current
edge.snapTo(rest); bottom.snapTo(pill.bottom); tint.snapTo(0f)
edge.snapTo(rest); bottom.snapTo(pill.bottom); tint.snapTo(0f); dim.snapTo(0f)
pieces.forEach { it.snapTo(0f) }
grown = true
}
@@ -226,7 +261,10 @@ internal fun StepOut(
} else {
opener[0]?.let { o -> if (inputMode.inputMode == InputMode.Keyboard) runCatching { o.requester.requestFocus() } }
opener[0] = null
coroutineScope {
if (leavesWithPage[0]) {
moving = true
presence.animateTo(0f, Motion.tw(160))
} else coroutineScope {
pieces.forEach { launch { it.animateTo(0f, Motion.tw(90)) } }
launch { delay(Motion.ms(60).toLong()); dim.animateTo(0f, Motion.tw(300)) }
moving = true
@@ -56,6 +56,7 @@ import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
@@ -358,6 +359,67 @@ internal fun SessionAchievementsPanel(label: String, state: AchievementsState, t
}
}
/** The Achievements page of the session menu: the same list as the full panel, inside the menu's own scroll. */
@Composable
internal fun DrawerAchievementsPage(game: StoreAchievements.Game, title: String?, track: (String) -> Modifier) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val label = StoreAchievements.forSource(game.source)?.label.orEmpty()
val state = rememberAchievements(game) ?: AchievementsState.READING
val kinds = remember(state.list) {
val list = state.list.orEmpty()
val split = groups(list)
if (split.size < 2) emptyList() else listOf(R.string.stores_tab_all to list) + split
}
var pick by remember { mutableIntStateOf(0) }
if (pick >= kinds.size) pick = 0
var noteHadFocus by remember { mutableStateOf(false) }
val firstRow = remember { FocusRequester() }
val loaded = !state.list.isNullOrEmpty()
LaunchedEffect(loaded) {
if (loaded && noteHadFocus) {
noteHadFocus = false
withFrameNanos { }
runCatching { firstRow.requestFocus() }
}
}
Column(Modifier.fillMaxWidth().padding(top = 8.dp, start = 4.dp, end = 4.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
Text(title.orEmpty(), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
state.list?.takeIf { it.isNotEmpty() }?.let { list ->
if (state.all) Trophy(18.dp, Modifier.padding(end = 6.dp))
Text(stringResource(R.string.achievements_count_short, state.done, list.size), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = pal.signal)
}
}
val list = state.list
if (list.isNullOrEmpty()) {
Text(achievementsNote(state, label).orEmpty(), fontSize = 13.sp, color = colors.onSurfaceVariant,
modifier = Modifier.padding(top = 12.dp).then(track("achievements"))
.onFocusChanged { if (it.isFocused) noteHadFocus = true }.focusable())
return@Column
}
LinearProgressIndicator(
progress = { state.done / list.size.toFloat() }, color = pal.signal, trackColor = pal.line,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().height(4.dp).clip(RoundedCornerShape(2.dp)),
)
if (kinds.isNotEmpty()) TabStrip(
kinds.map { (name, group) -> if (name == R.string.stores_tab_all) stringResource(name) + " · " + group.size else stringResource(name, group.size) },
pick, { pick = it }, Modifier.padding(top = 10.dp), bumpers = false, compact = true,
)
val shown = kinds.getOrNull(pick)?.second ?: list
val sections = if (pick == 0) groups(shown).filter { it.second.isNotEmpty() } else listOf(null to shown)
val first = sections.firstOrNull()?.second?.firstOrNull()?.id
Column(Modifier.padding(top = 6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
for ((group, items) in sections) {
if (group != null) AchievementGroupLabel(stringResource(group, items.size))
for (a in items) androidx.compose.runtime.key(a.id) {
AchievementRow(a, compact = true, if (a.id == first) track("achievements").focusRequester(firstRow) else Modifier)
}
}
}
}
}
@Composable
internal fun DrawerAchievementsRow(progress: Pair<Int, Int>?, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -230,35 +230,51 @@ val LocalPalette = staticCompositionLocalOf { Themes.byId(Themes.GRAPHITE) }
val Palette.onSignal: Color get() = if (signal.luminance() > 0.18f) Color(0xFF03111F) else Color.White
internal val LocalSolidPalette = staticCompositionLocalOf<Palette?> { null }
@Composable
fun DroidDeckTheme(theme: String? = null, appScale: Int = AppUiPrefs.DEFAULT_SCALE, content: @Composable () -> Unit) {
fun DroidDeckTheme(theme: String? = null, appScale: Int = AppUiPrefs.DEFAULT_SCALE, frost: FrostChoice? = null, content: @Composable () -> Unit) {
val context = LocalContext.current
remember(context) { Themes.loadGradient(context) }
val id = theme ?: SessionPrefs.theme(context)
if (id == Themes.INNER_GAMER) InnerGamerHue(Themes.rgbSpeed)
val p = Themes.byId(id)
val scheme = darkColorScheme(
primary = p.primary, onPrimary = p.onPrimary, secondary = p.onSurfaceVariant,
background = p.background, onBackground = p.onBackground,
surface = p.surface, onSurface = p.onBackground,
surfaceVariant = p.surfaceVariant, onSurfaceVariant = p.onSurfaceVariant,
error = p.error,
)
val solid = Themes.byId(id)
val look = frost?.let { frostLook(solid, it) }
val p = if (look == null) solid else solid.frosted(look)
val baseDensity = LocalDensity.current
val baseConfiguration = LocalConfiguration.current
val density = remember(baseDensity, appScale) { scaledAppDensity(baseDensity, appScale) }
val configuration = remember(baseConfiguration, appScale) { scaledAppConfiguration(baseConfiguration, appScale) }
CompositionLocalProvider(
LocalPalette provides p,
LocalSolidPalette provides solid.takeIf { look != null },
LocalFrost provides look?.veil,
LocalDensity provides density,
LocalConfiguration provides configuration,
) {
MaterialTheme(colorScheme = scheme, typography = ContentDirected) {
MaterialTheme(colorScheme = p.scheme(), typography = ContentDirected) {
FocusGlideHost { ProvideTextStyle(TextStyle(textDirection = TextDirection.Content), content) }
}
}
}
private fun Palette.scheme() = darkColorScheme(
primary = primary, onPrimary = onPrimary, secondary = onSurfaceVariant,
background = background, onBackground = onBackground,
surface = surface, onSurface = onBackground,
surfaceVariant = surfaceVariant, onSurfaceVariant = onSurfaceVariant,
error = error,
)
@Composable
internal fun SolidSurfaces(content: @Composable () -> Unit) {
val solid = LocalSolidPalette.current
if (solid == null) content()
else CompositionLocalProvider(LocalPalette provides solid, LocalSolidPalette provides null, LocalFrost provides null) {
MaterialTheme(colorScheme = solid.scheme(), typography = MaterialTheme.typography, content = content)
}
}
private val ContentDirected = Typography().run {
fun TextStyle.byContent() = copy(textDirection = TextDirection.Content)
Typography(
@@ -69,7 +69,7 @@ internal object ThemeColors {
private val DARK_INK = Color(0xFF03111F)
private fun contrast(a: Color, b: Color): Float {
internal fun contrast(a: Color, b: Color): Float {
val x = a.luminance()
val y = b.luminance()
return (max(x, y) + 0.05f) / (min(x, y) + 0.05f)
@@ -80,7 +80,7 @@ internal object ThemeColors {
return if (worst(DARK_INK) >= worst(Color.White)) DARK_INK else Color.White
}
private const val MIN_CONTRAST = 4.5f
internal const val MIN_CONTRAST = 4.5f
private fun fitTo(ink: Color, argb: Int): Int {
fun short(color: Int) = contrast(ink, Color(color)) < MIN_CONTRAST
@@ -31,7 +31,7 @@ class BottomDesktopCompositorService : Service() {
MSG_RESIZE -> resize(msg.arg1, msg.arg2)
MSG_TOUCH -> WaylandCompositor.nativeSendTouch(msg.arg1 and 0xff, msg.arg1 shr 8,
msg.arg2 ushr 16, msg.arg2 and 0xffff)
MSG_KEY -> WaylandCompositor.nativeSendKey(msg.arg1, msg.arg2)
MSG_KEY -> WaylandCompositor.nativeSendKeyOrdered(msg.arg1, msg.arg2)
MSG_POINTER -> WaylandCompositor.nativeSendPointer(1, msg.arg1, msg.arg2)
MSG_SCENE -> WaylandCompositor.nativeSendSceneInput(msg.arg1, msg.arg2, msg.peekData()?.getInt(KEY_B) ?: 0)
MSG_CURSOR -> if (CompositorHost.isStarted) WaylandCompositor.nativeSetCursorComposite(msg.arg1 != 0)
@@ -202,6 +202,27 @@ public final class WaylandCompositor {
if (l != null) l.onTextInput(enabled, program, x, y, w, h);
}
public interface TextInputFallbackListener {
boolean onTextInputFallback(String text, int token);
}
private static volatile TextInputFallbackListener textInputFallbackListener;
public static void setTextInputFallbackListener(TextInputFallbackListener l) { textInputFallbackListener = l; }
public static boolean isTextInputFallbackListener(TextInputFallbackListener l) { return textInputFallbackListener == l; }
public static void clearTextInputFallbackListener(TextInputFallbackListener l) {
if (textInputFallbackListener == l) textInputFallbackListener = null;
}
@SuppressWarnings("unused")
static boolean onTextInputFallback(byte[] utf8, int token) {
TextInputFallbackListener l = textInputFallbackListener;
if (l == null || utf8 == null) return false;
return l.onTextInputFallback(new String(utf8, java.nio.charset.StandardCharsets.UTF_8), token);
}
private static byte[] utf8(String s) {
return s == null ? new byte[0] : s.getBytes(java.nio.charset.StandardCharsets.UTF_8);
}
@@ -210,14 +231,28 @@ public final class WaylandCompositor {
public static void textInputCommit(String text) { if (text != null && !text.isEmpty()) nativeTextInputCommit(utf8(text)); }
public static void textInputCommitAndSubmit(String text) {
if (text != null && !text.isEmpty()) nativeTextInputCommitAndSubmit(utf8(text));
}
public static void textInputPreedit(String text, int cursor) { nativeTextInputPreedit(utf8(text), cursor, cursor); }
public static void textInputDelete(int before, int after) { nativeTextInputDelete(before, after); }
public static final int TEXT_NOT_DELIVERED = 0;
public static final int TEXT_DELIVERED = 1;
public static final int TEXT_UNRESOLVED = 2;
public static void completeTextInputFallback(int token, int result) {
nativeCompleteTextInputFallback(token, result);
}
private static native void nativeSetClipboardText(byte[] utf8);
private static native void nativeTextInputCommit(byte[] utf8);
private static native void nativeTextInputCommitAndSubmit(byte[] utf8);
private static native void nativeTextInputPreedit(byte[] utf8, int cursorBegin, int cursorEnd);
private static native void nativeTextInputDelete(int before, int after);
private static native void nativeCompleteTextInputFallback(int token, int result);
public static native void nativeStart(String xdgRuntimeDir);
@@ -248,6 +283,10 @@ public final class WaylandCompositor {
public static native void nativeSendKey(int evdev, int state);
// Ordered delivery: key events share the host queue with text commits so keys cannot overtake pending text.
public static native void nativeSendKeyOrdered(int evdev, int state);
public static native void nativeSelectGameField(boolean copy);
public static native boolean nativeFocusTakesTouch();
public static native boolean nativeCursorInputPos(int[] out);
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="512"
android:viewportHeight="512">
<path android:fillColor="#FFFFFFFF" android:fillType="evenOdd" android:pathData="M 142 335 L 148 343 L 148 345 L 155 352 L 165 365 L 166 368 L 169 370 L 171 374 L 176 379 L 177 382 L 179 383 L 181 387 L 187 393 L 187 395 L 193 401 L 196 400 L 200 392 L 206 386 L 259 419 L 262 418 L 266 411 L 264 406 L 250 398 L 249 396 L 242 391 L 237 389 L 236 387 L 231 385 L 227 381 L 215 374 L 215 371 L 222 361 L 222 356 L 220 353 Z M 472 198 L 463 195 L 446 195 L 436 198 L 431 198 L 426 200 L 418 201 L 415 203 L 382 209 L 375 212 L 361 214 L 353 217 L 349 224 L 349 226 L 346 229 L 339 245 L 336 248 L 281 354 L 274 365 L 275 370 L 279 376 L 279 379 L 311 450 L 311 453 L 317 465 L 325 473 L 327 474 L 339 474 L 348 470 L 353 465 L 360 454 L 369 436 L 369 434 L 372 430 L 374 424 L 385 404 L 388 396 L 399 376 L 463 246 L 466 243 L 470 232 L 480 214 L 479 205 Z M 444 224 L 445 226 L 337 439 L 334 435 L 332 428 L 316 393 L 315 388 L 312 384 L 312 381 L 305 367 L 305 364 L 307 362 L 348 282 L 369 244 L 369 242 L 372 239 L 381 238 L 386 236 L 390 236 L 395 234 L 409 232 L 423 228 L 432 227 L 440 224 Z M 211 187 L 201 192 L 201 194 L 203 196 L 203 198 L 228 249 L 225 251 L 166 265 L 165 266 L 169 280 L 234 264 L 242 278 L 242 280 L 265 327 L 278 321 L 278 319 L 250 261 L 252 259 L 313 244 L 310 229 L 244 246 L 235 230 L 235 228 L 226 211 L 226 209 L 224 207 L 215 186 Z M 233 127 L 233 129 L 235 131 L 240 133 L 243 136 L 248 138 L 287 162 L 287 165 L 279 178 L 281 181 L 288 183 L 290 182 L 304 186 L 310 186 L 313 188 L 316 187 L 320 189 L 343 192 L 350 195 L 352 194 L 357 196 L 362 196 L 354 186 L 351 184 L 350 181 L 347 179 L 339 168 L 335 165 L 335 163 L 324 152 L 323 149 L 320 147 L 311 135 L 307 134 L 302 136 L 302 138 L 297 144 L 297 146 L 295 148 L 292 148 L 282 141 L 276 139 L 266 132 L 264 132 L 253 125 L 247 123 L 242 119 L 237 120 Z M 221 73 L 212 70 L 195 70 L 175 75 L 170 75 L 154 80 L 140 82 L 135 84 L 130 84 L 123 87 L 103 91 L 95 103 L 88 119 L 86 121 L 79 136 L 75 141 L 73 147 L 66 158 L 59 174 L 56 177 L 23 240 L 24 245 L 34 266 L 34 269 L 44 289 L 44 292 L 60 326 L 63 335 L 67 342 L 72 347 L 76 349 L 91 348 L 95 346 L 106 334 L 118 310 L 118 308 L 120 306 L 229 88 L 228 80 Z M 193 99 L 194 100 L 190 107 L 190 109 L 183 121 L 183 123 L 181 125 L 176 137 L 174 139 L 132 224 L 130 226 L 123 242 L 112 261 L 89 307 L 88 311 L 85 314 L 58 250 L 53 241 L 62 223 L 74 202 L 118 117 L 121 114 L 129 113 L 134 111 L 139 111 L 162 105 L 167 105 L 188 99 Z" />
</vector>
+19
View File
@@ -654,6 +654,9 @@
<string name="perf_hostname">اسم المضيف</string>
<string name="perf_hostname_hint">الاسم الذي يراه Steam لهذا الجهاز. اتركه خاليًا للاستعادة إلى %1$s.</string>
<string name="perf_hostname_invalid">أحرف وأرقام وشرطات داخلية فقط، حتى 63 حرفًا.</string>
<string name="perf_desktop_as_user">تشغيل سطح المكتب كمستخدم</string>
<string name="perf_desktop_as_user_hint">يعمل سطح المكتب وتطبيقاته وطرفياته كمستخدم عادي باسم deck بدلًا من root، للتطبيقات التي ترفض root. يظل sudo يعمل. يسري على سطح المكتب التالي.</string>
<string name="perf_desktop_as_user_needs_native">يتطلب التشغيل دون proot.</string>
<string name="perf_phantom_warning">Android مهيَّأ لإنهاء هذه الجلسة</string>
<string name="driver_installed">مثبّت</string>
<string name="driver_available">متاح للتنزيل</string>
@@ -1347,6 +1350,16 @@
<string name="ctrl_joycon_vr">أجهزة Joy-Con كوحدات تحكم VR</string>
<string name="ctrl_joycon_vr_hint">أثناء تشغيل SteamVR، يصبح كل Joy-Con يدًا. وجّهه إلى الأمام واضغط مطولًا على Home أو Capture لإعادة توسيطه.</string>
<string name="setup_animations">الرسوم المتحركة</string>
<string name="setup_frosted_background">مصنفر</string>
<string name="setup_frosted_background_hint">يعرض خلفية الشاشة مموّهة خلف المشغّل. يستهلك طاقة بطارية أكثر.</string>
<string name="setup_frosted_wallpaper">خلفية مصنفرة</string>
<string name="setup_frosted_cards">بطاقات مصنفرة</string>
<string name="setup_frosted_cards_hint">تُظهر البطاقات والمجموعات قليلًا من الخلفية. تبقى القوائم والحوارات معتمة.</string>
<string name="setup_frosted_cards_needs_wallpaper">يتطلب الخلفية المصنفرة.</string>
<string name="setup_frost_transparency">شفافية الخلفية</string>
<string name="setup_frost_transparency_hint">مقدار ما يظهر من الخلفية.</string>
<string name="setup_frost_card_transparency">شفافية البطاقات</string>
<string name="setup_frost_card_transparency_hint">مقدار ما يظهر من الخلفية عبر البطاقات.</string>
<string name="setup_low_storage_warning">التحذير عند انخفاض مساحة التخزين</string>
<string name="setup_low_storage_warning_hint">اسأل قبل تشغيل Steam عندما تكون المساحة الحرة أقل من 10 جيجابايت.</string>
<string name="ctrl_layout">التخطيط</string>
@@ -2236,6 +2249,7 @@
<string name="bottom_qam_layout_left">يسار</string>
<string name="bottom_qam_layout_center">وسط</string>
<string name="bottom_qam_layout_right">يمين</string>
<string name="bottom_qam_layout_split">مقسّم</string>
<string name="bottom_qam_unavailable">قائمة الوصول السريع في Steam غير متاحة بعد.</string>
<string name="bottom_page_telemetry">إحصاءات داخل اللعبة</string>
<string name="bottom_hud_group">مؤشرات الشاشة السفلية</string>
@@ -2550,6 +2564,8 @@
<string name="phantom_instructions_fix">%1$s إذا لم يكن ذلك ممكنًا، وصِّل هذا الجهاز بكمبيوتر يستخدم ADB ونفِّذ الأمر أدناه. عُد إلى هنا وتحقَّق مرة أخرى.</string>
<string name="phantom_instructions_off">يمكن بدء جلسات Steam.</string>
<string name="phantom_instructions_not_applicable">لا يستخدم إصدار Android هذا هذا الحدّ.</string>
<string name="phantom_title_uncounted">يتولى DroidDeck حد العمليات الفرعية</string>
<string name="phantom_instructions_uncounted">يشغّل DroidDeck معظم برامج الجلسة في عمليات لا يحتسبها Android، ما يبقي الجلسة دون الحد بكثير، لذا يمكن إبقاء خيارات المطوّرين متوقفة. ما زال Steam وبعض أدواته المساعدة محتسبة.</string>
<string name="phantom_fix_toggle">فعِّل «إيقاف القيود المفروضة على العمليات الثانوية» في خيارات المطوّرين، واترك خيارات المطوّرين مفعَّلة بعد ذلك.</string>
<string name="phantom_fix_no_toggle">لا يحتوي إصدار Android هذا على مفتاح لذلك. استخدِم تصحيح الأخطاء اللاسلكي لتغييره من هذا الجهاز.</string>
<string name="upd_block_no_apk">لا يتوفّر تنزيل لهذا الإصدار الخاص بهذه النسخة من DroidDeck.</string>
@@ -4315,4 +4331,7 @@
<string name="steam_store_linux_build">تثبّت هذه اللعبة إصدار Linux الخاص بها. ثبّتها من Steam.</string>
<string name="game_zoom_title">تكبير اللعبة</string>
<string name="game_zoom_hint">اضبط تكبير اللعبة من 100% إلى 300%</string>
<string name="glasses_shortcut_group">اختصار داخل اللعبة</string>
<string name="glasses_show_shortcut">إظهار اختصار النظارات الذكية</string>
<string name="glasses_show_shortcut_hint">إظهار زر النظارات الذكية العائم فوق اللعبة.</string>
</resources>
@@ -648,6 +648,9 @@
<string name="perf_hostname">Nombre del host</string>
<string name="perf_hostname_hint">El nombre que Steam ve para este dispositivo. En blanco restaura %1$s.</string>
<string name="perf_hostname_invalid">Solo letras, dígitos y guiones internos, hasta 63 caracteres.</string>
<string name="perf_desktop_as_user">El escritorio se ejecuta como usuario</string>
<string name="perf_desktop_as_user_hint">El escritorio, sus apps y sus terminales se ejecutan como el usuario común deck en lugar de root, para las apps que rechazan root. sudo sigue funcionando. Se aplica al próximo escritorio.</string>
<string name="perf_desktop_as_user_needs_native">Requiere Ejecutar sin proot.</string>
<string name="perf_phantom_warning">Android está configurado para cerrar esta sesión</string>
<string name="driver_installed">Instalado</string>
<string name="driver_available">Disponible para descargar</string>
@@ -1396,6 +1399,16 @@
<string name="glasses_xreal_experimental">Compatibilidad experimental con XREAL 1S, One, One Pro, One Pro+ y Aura. Usa el modo Follow y desactiva la estabilización en el menú de las gafas; en Aura, desactiva también Spatial Anchor. El seguimiento de cabeza y el cambio entre 2D/3D se han probado en Aura y One Pro+.</string>
<string name="glasses_pro2_experimental">Seguimiento de cabeza experimental para Pro 2. Los ajustes de brillo y volumen y el cambio de modo de pantalla aún no son compatibles.</string>
<string name="setup_animations">Animaciones</string>
<string name="setup_frosted_background">Esmerilado</string>
<string name="setup_frosted_background_hint">Muestra tu fondo de pantalla difuminado detrás del launcher. Consume más batería.</string>
<string name="setup_frosted_wallpaper">Fondo de pantalla esmerilado</string>
<string name="setup_frosted_cards">Tarjetas esmeriladas</string>
<string name="setup_frosted_cards_hint">Las tarjetas y los grupos dejan ver un poco del fondo de pantalla. Los menús y diálogos siguen sólidos.</string>
<string name="setup_frosted_cards_needs_wallpaper">Necesita el fondo de pantalla esmerilado.</string>
<string name="setup_frost_transparency">Transparencia del fondo de pantalla</string>
<string name="setup_frost_transparency_hint">Cuánto se ve el fondo de pantalla.</string>
<string name="setup_frost_card_transparency">Transparencia de las tarjetas</string>
<string name="setup_frost_card_transparency_hint">Cuánto se ve el fondo de pantalla a través de las tarjetas.</string>
<string name="setup_low_storage_warning">Avisar cuando queda poco almacenamiento</string>
<string name="setup_low_storage_warning_hint">Preguntar antes de iniciar Steam cuando el espacio libre es menor a 10 GB.</string>
<string name="ctrl_layout">Disposición</string>
@@ -2231,6 +2244,7 @@
<string name="bottom_qam_layout_left">Izquierda</string>
<string name="bottom_qam_layout_center">Centro</string>
<string name="bottom_qam_layout_right">Derecha</string>
<string name="bottom_qam_layout_split">Dividido</string>
<string name="bottom_qam_unavailable">El menú de acceso rápido de Steam aún no está disponible.</string>
<string name="bottom_page_telemetry">Estadísticas del juego</string>
<string name="bottom_hud_group">HUD de la pantalla inferior</string>
@@ -2542,6 +2556,8 @@
<string name="phantom_instructions_fix">%1$s Si no es posible, conecta este dispositivo a una computadora con ADB y ejecuta el comando de abajo. Después vuelve aquí y comprueba de nuevo.</string>
<string name="phantom_instructions_off">Ya se pueden iniciar sesiones de Steam.</string>
<string name="phantom_instructions_not_applicable">Esta versión de Android no usa este límite.</string>
<string name="phantom_title_uncounted">DroidDeck gestiona el límite de procesos secundarios</string>
<string name="phantom_instructions_uncounted">DroidDeck ejecuta la mayoría de los programas de la sesión en procesos que Android no cuenta, lo que mantiene la sesión muy por debajo del límite, así que las Opciones de desarrollador pueden quedar desactivadas. Steam y algunos de sus procesos auxiliares todavía cuentan.</string>
<string name="phantom_fix_toggle">Activa “Inhabilitar restricciones de procesos secundarios” en Opciones de desarrollador y deja activadas las Opciones de desarrollador después.</string>
<string name="phantom_fix_no_toggle">Esta versión de Android no tiene un interruptor para ello. Usa la Depuración inalámbrica para cambiarlo desde este dispositivo.</string>
<string name="upd_block_no_apk">Esta versión no tiene descarga para esta copia de DroidDeck.</string>
@@ -4193,4 +4209,7 @@
<string name="steam_store_close_steam">Cierra Steam primero</string>
<string name="steam_store_session_wait">Pausa primero la descarga de Steam</string>
<string name="steam_store_linux_build">Este juego instala su versión para Linux. Instálalo desde Steam.</string>
<string name="glasses_shortcut_group">Acceso directo en el juego</string>
<string name="glasses_show_shortcut">Mostrar acceso directo de Smart Glasses</string>
<string name="glasses_show_shortcut_hint">Mostrar el botón flotante de Smart Glasses sobre el juego.</string>
</resources>
Loaded 100 of 301 files, more files were not shown because too many files have changed in this diff. Show more