Compare commits

...
Author SHA1 Message Date
The412Banner 49381484dd fix(bionic): put the game's logs where Share logs finds them
Shared session logs never held DroidDeck-Bionic's own log or its
graphics logs. launch.sh wrote them into the game's prefix, which Share
logs does not read, and dropped the log locations Detailed graphics logs
sets along with the rest of the guest environment.

- proton: names a game launch's folder in the session folder (the
  game's log folder when Detailed graphics logs made one, else
  games/<date>-bionic-<appid>) and passes the graphics log locations as
  Android paths.
- launch.sh: writes the game's log into that folder; the prefix's
  droiddeck-bionic.log points to it, since Share logs takes only files
  with one name. Keeps DXVK_LOG_PATH, VKD3D_LOG_FILE and MESA_LOG_FILE.
- EnhancedSessionLogShare: keeps the name droiddeck-bionic.log and
  files it with the games.
2026-11-23 01:32:33 +00:00
The412Banner f17d3ddaad fix(bionic): name guest files by their Android paths in store launches
DroidDeck-Bionic's Wine has Android's root on Z:, but DroidDeck's store
launch files and helpers name guest files by guest Z: paths. A Ubisoft
game then skipped its service and started directly (Watch_Dogs exited at
launch); the Epic parent stand-in, GOG/Rockstar registry values, reg.exe
imports and the EA probe pointed at the wrong tree in the same way.
Reported by 2-Shar on PR #3037.

- proton: map guest Z: paths in every run argument (also NAME=Z:..., as
  in an installer's /DIR=) and export DROIDDECK_GUEST_ROOT, the guest's
  root as this Wine names it; launch.sh keeps it.
- StoreLaunch: the Ubisoft service and the Epic parent stand-in start
  from %DD_R% (DROIDDECK_GUEST_ROOT, else Z:). An installed Ubisoft
  game's older launch file is rewritten at the next library scan.
- droiddeck-store-launch: windows_path() asks DroidDeck-Bionic's
  getcompatpath when that tool runs the game.
- droiddeck-gog-maintenance: name the tool for the registry step.
2026-11-23 00:44:48 +00:00
The412Banner 2aae4b2284 fix(bionic): address review findings
Launcher (tools/bionic-runtime/tool/launch.sh)
- The FEX code cache is also cleared when another FEX build wrote to it since this tool last ran the prefix:
  the stamp now holds the FEX ID and a fingerprint of the caches, saved after each run (also after
  runinprefix and when Steam stops the game).
- A game started by a launcher that then exits keeps the tool waiting: the wait goes on while any program
  of the prefix runs, apart from Wine's own services. The game is looked up in this prefix only, by its
  name as fixed text.
- The tool exits with Wine's status instead of 0.

Install scripts (droiddeck-game-env)
- A "run process" entry counts as done only when its hasrunkey value is a DWORD of at least its
  MinimumHasRunValue (1 by default), as Steam's evaluator decides; a 0 or a value of another type no longer
  lets the evaluator be skipped.

Helpers
- execshim: non-regular files (a FIFO) go to libc without a blocking open; libc functions are bound at load
  through atomic slots; relative posix_spawn paths with file actions are left to libc; the argument vector
  has room for its terminator when argv is empty.
- gstag: replies and errors are matched to their request's sequence number per connection; one bounded
  packet reader; destroyed windows leave the candidate and tagged lists; the focus override needs a live
  tagged window and a successful focus read; only gone candidates are pruned.
- steamshm: a new shared object is created and sized under a private name and then put in place in one
  step; both code redirects go in or neither, and unused trampolines are released.
- check-needed.py fails when readelf fails and ignores dangling links.
- The bionic runtime workflow also runs for tools/gpuload changes.

App and tool wrapper
- FEX twin downloads run once per name; a twin that a game's FEX choice still needs on an installed tool
  cannot be deleted.
- With proot on and no DroidDeck-Proton installed, a launch sent to DroidDeck-Bionic stops with a message
  instead of starting the bionic tool.
2026-11-22 17:56:19 -05:00
The412Banner dca443e3aa feat(bionic): DroidDeck-Bionic compatibility tool (Wine on Android's libc, no proot)
DroidDeck-Bionic is a Steam compatibility tool that runs the game itself with
Android's own libc (bionic) instead of glibc inside proot. Steam, the stores and
the session stay on DroidDeck's Linux side unchanged; only the game process
leaves proot. It is listed in the Proton list only when "Run without proot" is
on, and it is shipped as a pre-release runtime pack (DroidDeck-Bionic-12.8-rNN
on Droid-Deck/DroidDeck-Proton), never as the default for other users.

Runtime pack (tools/bionic-runtime, .github/workflows/build-bionic-runtime.yml)
- CI builds an aarch64 bionic pack: the Wine layer from The412Banner/proton-wine
  (bionic build), an exec shim, launcher (tool/launch.sh + proton verbs run,
  runinprefix, waitforexitandrun), gamescope's WSI layer (patches 0117 + 0119),
  DroidDeck's GPU-load layer, fake input (fakeinput_steam.cpp), GStreamer
  plugins, Zink/Fast OpenGL Mesa, DXVK, VKD3D-Proton, D7VK and FEX (ARM64EC).
- Games run on gamescope's X server; Steam store games reach DroidDeck's Steam
  (lsteamclient), Steam Input works (shared /dev/shm via libsteamshm), and
  Steam Cloud maps Windows save folders (tool name contains "Proton").
- DroidDeck's game settings, game-environment fixes, in-game layers and DXVK /
  VKD3D / FEX choices reach bionic games the same way they reach
  DroidDeck-Proton games (DD_* setting names).
- Prefixes stay compatible both ways with DroidDeck-Proton: dead links are
  removed, the tool's .NET stubs and comctl32 v6 survive Wine updates, a stale
  FEX code cache from another FEX build is cleared, drive Z: is the whole device.
- Store launches: Xbox (Windows exe path + Xbox runtime environment), GOG and
  Epic (.bat launchers, games that rename their process).

App changes (all additive)
- ProtonExtras / ProtonMenu / ExperimentalProtons / droiddeck-proton-extra:
  DroidDeck-Bionic pre-releases are checked and listed only with Run without
  proot on, in their own row (not under Experimental); updates replace the
  older build and carry the default tool and per-game picks over; deleting a
  tool removes links inside it, never what they point to.
- ProtonDefault: a default or game pick left on an older bionic build moves to
  the installed one; bionic picks start on DroidDeck-Proton when Run without
  proot is off.
- ComponentsManager / ComponentUpdates / ComponentUpdater / ComponentsPage /
  SessionOverlay: FEX components for DroidDeck-Bionic (bionic-stable on
  DroidDeck-Components); each tool is offered only FEX builds that fit it.
- SessionService: DROIDDECK_DISPLAY_DRIVER tells bionic games which Turnip the
  display uses when the chosen runtime driver has no Android build.
- steam-compatibility: with proot on, a launch sent to a DroidDeck-Bionic tool
  goes to the newest DroidDeck-Proton (picks stay as set); glibc FEX rows are
  never applied to a DroidDeck-Bionic tool.
- droiddeck-game-env: Steam's install-script evaluator is skipped when its
  scripts only run processes already marked as done.

Tests
- New: ComponentsBionicFexTest; extended ComponentsRepublishTest,
  ExperimentalProtonsTest, ProtonDefaultTest, ProtonExtrasTest,
  test_game_environment.py, test_proton_extra.py.

Device testing (Pocket FIT, Adreno 750; Pocket FIT Elite, Adreno 830)
- Steam (Brawlhalla online, Left 4 Dead 2 controller, Black Ops II, Steam
  Cloud), Xbox, GOG, Epic and Amazon games run; saves carry both ways between
  DroidDeck-Bionic and DroidDeck-Proton on Xbox, GOG, Epic and Amazon.
- Not tested: EA, Ubisoft, Battle.net (no owned game / not signed in).
2026-11-22 17:12:43 -05:00
DeathKhan 6ef8e2274e fix(ui): focused cards keep their solid ground under the highlight tint (#2909) 2026-11-22 17:11:29 -05:00
Kurt Himebauch 00525cde15 fix(session): picking a bottom-screen mode clears the menu restore left by a teardown (#3007) 2026-11-22 17:07:23 -05:00
MaxsTechReview 210c127446 feat(addons): add a CurseForge source to the addon browser (#3028)
* feat(addons): add a CurseForge source to the addon browser

Search and install CurseForge addons from the Download addons window by
driving the installed CurseForge app in the background: it starts minimized
on the session's X display with its inspector bound to 127.0.0.1, and the
window's own renderer services handle game detection, search, install and
shutdown. Sign-in stays inside the CurseForge app.

The Install buttons in the addon list now size to their label, so the label
is centered and the button matches the other compact buttons.

* fix(curseforge): secret inspector URL, hold mode and serialised starts

- Start CurseForge with its Node inspector on 127.0.0.1:0 and publish only
  the UUID websocket URL, kept in the 0700 state directory, so no fixed
  unauthenticated debug port is exposed.
- The agent evaluates through that URL instead of a fixed port.
- Add a hold mode that runs as a session program and stops the app on
  exit, and a lock so hold and start never launch twice.

* feat(addons): run CurseForge in a hidden session when none is running

- Opening the CurseForge source with no session starts one headlessly
  (offscreen compositor output, shared start path with SessionActivity via
  CompositorHost) running the CurseForge hold helper; leaving the dialog
  stops the app and that session. A session the user already had is
  reused and left running.
- Drop the "start a session" notice from every locale.
- Addon browser link: cleanup shares the link's lock off the UI thread,
  stops the app at once on close, refuses work after close and stops a
  launch that finishes after close.
- CurseForgeApp.start stops the app before every failed return.
- instanceFor returns no instance when the populated list has no match.

* Harden headless CurseForge session and helper lifecycle

Scope the hidden session to its id, roll back partial starts, release the
offscreen reader once the session ends, re-acquire the inspector when its
endpoint goes away, bound DevTools calls by one deadline, key the installed
snapshot by target, track the helper launch by pid start time and directory,
fail on lock errors, and update the HDR gate test to its new location.

* Map DevTools send failures and recheck the hidden session id

* fix(addons): bind the hidden session to the id it claims at launch

* Keep the CurseForge helper quiet when no launch is recorded
2026-11-22 17:02:35 -05:00
Tushar Gandhe 234e40157e feat(launcher): LT and RT step between the main tabs from anywhere in the launcher (#3035)
* feat(launcher): LT and RT step between the main tabs from anywhere in the launcher

LT and RT move to the previous and next main tab on every layout. The activity handles them before any page sees the key, so a focused control, an embedded Android view such as the terminal, or nothing being focused no longer swallows them; dialogs and popups keep their own keys. Pads that report the triggers only as axes, like the Xbox Wireless Controller, get an L2/R2 press when a trigger passes 60% of its travel; pads that send their own trigger keys are left alone.

* fix(launcher): trigger tab steps tick, drop a pending press on focus loss, and move once per pull

Controller haptics now ticks for L2 and R2. A synthetic trigger press waiting its 40 ms is cancelled when the launcher loses window focus or is destroyed, so a dialog that opens in between keeps the page behind it. Each pull is tracked: when a synthetic press has gone out, the pad's own trigger key for the same pull is swallowed instead of stepping a second tab.
2026-11-22 16:59:01 -05:00
Tushar Gandhe c3809c0a75 fix(ui): keep the Agent composer above the keyboard and release search fields on tap (#2852)
* fix(agent): keep the composer above the keyboard outside fullscreen

* fix(ui): release a search field when another control is tapped

* fix(ui): release the add-on search field in its dialog, and let a reopened search take focus

* fix(ui): a drag that returns to where it began does not release the search field
2026-11-22 16:58:57 -05:00
Tushar Gandhe 71b7b6efad fix(library): put the store accounts button on the right of the source chips, as on other pages (#2929) 2026-11-22 16:58:53 -05:00
Tushar Gandhe a0e7c1715a fix(ui): smaller game page link pills with a gap between rows (#2973) 2026-11-22 16:58:49 -05:00
MaxsTechReview 2c2d55058e fix(preload): open synthesized socket tables when the fd reopen is denied (#3034) 2026-11-22 16:20:34 -05:00
MaxsTechReview 7f61e514e6 chore: pin gamescope to the release with the opacity focus fix (#3031) 2026-11-22 14:27:08 -05:00
MaxsTechReview b891019b87 fix(steam-x64): keep the session's GL thunk for the x86 web helper (#3027)
* fix(steam-x64): keep the session's GL thunk for the x86 web helper

FEX's global AppConfig for steamwebhelper turns the GL thunk off and is
read after FEX_THUNKCONFIG, so the x86 helper used the rootfs's x86 Mesa.
Steam's browser compositor creates its window through SDL3 and GLX in
the helper's browser process, x86 Mesa faulted in driCreateNewScreen3
(SIGSEGV) about 11 s after each start, and the client restarted the
helper every 12 s.

For every global FEX AppConfig that turns off a thunk the session uses,
the launcher writes a local AppConfig with the session's thunk set. It
leaves local files with other content alone and removes its own files
when the client runs in software.

* fix(steam-x64): write FEX AppConfig overrides atomically

* fix(steam-x64): stage AppConfig overrides in a unique temporary file

* fix(steam-x64): publish AppConfig overrides without replacing a newer file
2026-11-22 14:16:34 -05:00
MaxsTechReview 1a29c65d4f fix(gamescope): choose focus again when a window's opacity crosses zero (#3030)
A window is a focus candidate only while _NET_WM_WINDOW_OPACITY is above
zero, but a change of that property never re-ran focus selection. A
layered window that maps fully transparent and fades in was skipped at
map time and stayed skipped once opaque, so a nested desktop session
hid its gamescope window and the game ran with nothing on screen.
2026-11-22 13:47:22 -05:00
MaxsTechReview ff5e4c7ac7 fix(preload): accept NETLINK_ROUTE multicast subscriptions (#3015)
* fix(preload): accept NETLINK_ROUTE multicast subscriptions

Programs that watch for network changes bind their route socket with
multicast groups or join them with NETLINK_ADD_MEMBERSHIP. The emulated
socket refused both with EACCES, and .NET's NetworkChange treats that as
fatal: CurseForge's Mods Agent failed to initialise with "Permission
denied" from NetworkChange.CreateSocket(), so the app never loaded its
library.

Real Linux lets unprivileged sockets join rtnetlink groups. Accept the
groups at bind and through ADD/DROP_MEMBERSHIP, report them from
getsockname(), and keep queries on the same socket working. No change
events are generated yet; queries still return the current snapshot.

* fix(preload): keep netlink group membership in the shared socket state

Memberships now live in the peer metadata the kernel holds for the socket, next to the port and cap ack, so they survive exec and a change made by one process after fork is seen by every process holding the socket.

* fix(session): answer denied /proc/net socket tables

Android's SELinux policy denies app processes every file under /proc/net.
.NET lists TCP listeners from /proc/net/tcp and tcp6 before it binds a
server port, so the CurseForge Mods Agent failed on every port with
"An error was encountered while querying information from the operating
system" on stock firmware. Denied tcp, tcp6, udp and udp6 reads now get a
header-only table, through open and openat as well as fopen, the same way
the route and interface tables already are.

* fix(session): keep synthesized socket tables read-only and file-only

Reopen the populated table read-only instead of duplicating its writable
descriptor, and leave O_DIRECTORY opens with their original failure.
2026-11-22 13:37:44 -05:00
MaxsTechReview 2d38f11b36 Build FEX's latest release, point releases included (#3026)
The FEX build pinned FEX-2610 and its tag checks only accepted four
digits, so FEX-2611.1 was never picked up. The build now takes the
latest release tag, and Fixed-upstream compares the four-digit release.
CMake 4.5 rejects DEPENDS in install(CODE), which stopped host thunk
builds; patch 0007 drops it.
2026-11-22 13:03:43 -05:00
MaxsTechReview fd2e1652ad fix(fex): invalidate translated code written through a later writable alias (#3020)
* fix(fex): invalidate translated code written through a later writable alias

x86-64 CoreCLR maps its W^X memfd writable after the executable view was
translated. Under SMCChecks=mtrack the new alias was never write-protected,
so writes through it did not invalidate stale translations. Protect the
overlapping part of an executable alias on mmap and mprotect.

* fix(fex): protect every writable alias in one mprotect range and build fmt without modules

* fix(fex): build without C++ module scanning or import std
2026-11-22 12:22:11 -05:00
Tushar Gandhe c6b6e7362e fix(ui): game page main action above its box, and tabs that scroll and slide (#2994) 2026-11-22 11:31:46 -05:00
MaxsTechReview cb7edbefd2 fix(input): show the main screen layout editor first, like the second screen (#3019)
The Screen visibility group sat above the Layout group on the Main screen page, so in landscape its description pushed Edit on screen below the fold and the page looked like it had no editor. The Layout group now comes first on both screens.
2026-11-22 10:56:03 -05:00
Kurt Himebauch a9b5994a91 fix(library): drop the card's bottom gradient when it has no text to show (#3017) 2026-11-22 10:52:25 -05:00
MaxsTechReview 42f25c2a6c fix(input): controls edited in portrait keep their places in the panel below the game (#3013)
* fix(input): controls edited in portrait keep their places in the panel below the game

The panel below the game in portrait always regenerated the stock
layout, so positions saved from the Controls editor were dropped and
only the button styling carried over. The panel now orients to the
portrait frame and fits the edited controls into the panel at their
saved proportions; untouched stock layouts keep the generated panel.

* Keep the Deck panel's trackpads and fitted sizes for edited portrait controls
2026-11-22 09:51:32 -05:00
MaxsTechReview 501debc7f6 fix(game-env): Dragon's Dogma 2 starts with its Wine detection off (#3011)
Dragon's Dogma 2 checks for Wine and takes a path that does not start.
Launches of Steam app 2054970 now append the game's own
/WineDetectionEnabled:False switch at launch time. Steam's stored Launch
Options are untouched, and a /WineDetectionEnabled: value the user already
passes keeps priority and is not repeated.
2026-11-22 09:31:40 -05:00
Tushar Gandhe 1f70d43fe2 feat(ui): a Launcher setting turns page swipes off, and edge swipes in landscape leave the page alone (#2924) 2026-11-22 07:26:39 -05:00
Tamim Kabir a8d03d687f fix(input): SDL 3 games no longer crash on the virtual pads' udev devices (#2915) 2026-11-22 02:43:32 -05:00
Kurt Himebauch 9cfab884d5 feat(session): the DroidDeck menu is a bottom-screen mode, and the controller stays with the game (#3001) 2026-11-22 00:16:49 -05:00
FX1922 aefa5a3c0d feat(session): split the display resolution into landscape and portrait (#2990)
## Summary

Splits the session resolution setting into two: **Landscape resolution**
and **Portrait resolution**. Each has the same options as the old
Resolution row, plus a Follow option so one orientation can mirror the
other.

## Why

A single resolution has to serve both orientations. Presets and Match
screen flip automatically in portrait, but a custom size is used exactly
as typed, so a landscape size in a portrait session is wrong. Users who
play in both orientations couldn't pick a good size for each.

## Behavior

- The Display tab shows **Landscape resolution** and, underneath it,
**Portrait resolution**. Both offer the full existing list: presets,
Match screen, Follow screen, scaled follow options and Custom.
- Each row has an extra option at the top. **Follow portrait** (on the
landscape row) and **Follow landscape** (on the portrait row) use the
other orientation's choice, so someone can set one resolution and let
the other mirror it. The label shows the size it resolves to.
- A session picks the landscape or portrait choice from its orientation.
This uses the same orientation check as the output size, so the
unfolded-controls layout still counts as landscape.
- Custom WxH sizes are flipped to match the target orientation when
followed, e.g. portrait following 1280x720 uses 720x1280.
- If both rows would follow each other, the other row is set to the
concrete size it currently resolves to, so there is never a loop and
nothing visibly changes.
- The glasses output keeps using the landscape resolution.
- Applies to the Steam and Desktop Display tabs, which share the same
row.

## Compatibility

- The existing saved choice (`displayResolution.<mode>`) is now the
landscape resolution, so existing users keep their setting.
- The portrait choice is stored as `displayResolution.portrait.<mode>`
and defaults to Follow landscape, so portrait sessions behave as before
until it is changed. The settings reset covers it through the existing
`displayResolution.` prefix.
- One visible difference: a typed landscape custom size, used as typed
in portrait before, now flips to portrait while portrait follows
landscape.

## Known limitation

"Follow screen" is still decided once when the session starts, not on
every rotation. Re-evaluating it on rotation could make the window
orientation flip repeatedly when no orientation is pinned.

## Changes

- `SessionDisplay`: `LINK_LANDSCAPE` / `LINK_PORTRAIT`, `isLink`,
`orientCustom`, `effectiveChoice`
- `SessionPrefs`: `resolutionStored` (raw value per orientation),
`resolutionChoice(..., portrait)`, `setResolutionChoice(..., portrait)`
with the loop guard, `resolutionChosen(..., portrait)`
- `SessionActivity`: `portraitOutput()` drives the output size,
follow-screen choice and follow scale; the Match-screen default for
programs that draw at the panel size checks the matching orientation
- `ResolutionRow`, `ModeSettingsDialog`, `FrontEndActivity`: two rows,
the Follow option, state and actions
- `DeviceReport`: logs landscape and portrait separately
- Strings: `display_resolution_landscape`,
`display_resolution_portrait`, `display_follow_landscape`,
`display_follow_portrait` in all 33 locales; the unused
`display_resolution` is removed
- Tests: `PortraitResolutionTest`

## Testing

- Unit tests added for the preference logic, follow resolution, loop
guard and reset.
2026-11-22 08:03:03 +03:00
MaxsTechReview 6de3c59d7c fix(venus): lower the guest's SPIR-V to 1.3 for the phone's shader compiler (#2587)
* fix(venus): lower the guest's SPIR-V to 1.3 for the phone's shader compiler

* fix(venus): lower SPIR-V to 1.3 for Mali drivers

* fix(venus): keep the SPIR-V cap valid and scoped to active layers

Cap inline compute pipeline code too, leave the shader hooks off when
the layer is turned off, strip clip and cull distances only where they
are emulated, and leave modules alone whose capabilities, decorations or
OpSelect results need a newer version or an undeclared extension.

* fix(venus): keep application pipeline chains read-only and check non-semantic imports

Inline stage code is handed to the driver through a copy of the stage's
pNext chain instead of being written into the application's create info,
pipeline hooks return VK_ERROR_OUT_OF_HOST_MEMORY when their allocations
fail, and a NonSemantic import is only lowered to SPIR-V 1.3 when the
module declares SPV_KHR_non_semantic_info.

* fix(venus): preserve valid pipeline and shader behavior

* fix(venus): lower compatible read-only shader parameters

* fix(venus): install SPIR-V 1.3 lowering hooks on Vulkan 1.2+ devices or emulated gaps
2026-11-21 23:52:56 -05:00
MaxsTechReview bc11653c15 fix(steam): start the web helper when Android refuses CPU pinning on every GPU (#2819) 2026-11-21 23:52:53 -05:00
MaxsTechReview d6496b2f96 feat(addons): install the CurseForge app and update addons per game (#2986)
* feat(addons): install the CurseForge app and update addons per game

The Addons tab installs the official CurseForge Linux app from its own
update feed, checks it against the feed's SHA-512, shows its version,
offers updates and removes it with the components delete button.

Installed addons show their .toc version and are checked against
WoWInterface by X-WoWI-ID or the recorded source of addons installed
from the Download window; Update replaces them in place.

The CurseForge web search chip is replaced by the app.

* fix(addons): address review on update ordering, flavor filter, origins lock and failed checks

* fix(addons): compact scrollable addon browser with list rows

* fix(addons): compare release times as instants and replace the sources file atomically

* fix(addons): open the addon browser at the top of the list

* Keep the addon browser's search focus and installed version in sync

* Track the search field's own focus in the addon browser

* Key the installed addon version by install target

* Install rar and 7z addon archives
2026-11-21 23:47:58 -05:00
MaxsTechReview 3577073ab9 fix(input): move and resize the on-screen D-pad as one control, per-control button size and sizes above 100% (#2996)
* fix(input): move and resize the D-pad as one control, per-control button size and sizes above 100%

* fix(input): controller art for copied layouts, keep the minimum size when shrinking the D-pad

Copies and per-game versions of the on-screen gamepad now draw the same controller art and placement as the original, and resizing the D-pad from a corner or the per-control slider keeps every arrow at a usable size.

* Keep other controls' moves when undoing a repeated resize
2026-11-21 23:47:35 -05:00
Kurt Himebauch a2587f4f20 fix(display): preserve padded layer buffer layouts (#2985)
* fix(display): preserve padded layer buffer layouts

* fix(display): fall back when layer allocation fails

* fix(display): write linear targets at their row pitch
2026-11-21 23:40:11 -05:00
Kurt Himebauch b2687701c1 build: run the local macOS build natively, with no emulation (#2999)
build: make the local macOS build run natively, with no emulation

On an arm64 Mac the x86/i386 session preloads were built in a linux/amd64
container under emulation, and the Rockstar launcher failed to link against
Homebrew's SJLJ i686 mingw. Both now build on the host's own architecture.

- build_local.sh: on arm64 build the x86 preloads in a native arm64 Debian
  bullseye container with the x86_64/i686 cross toolchains (glibc 2.31, as
  before); x86 hosts keep the native gcc-multilib path.
- build-x86-preloads.sh: X86_CROSS=1 selects the cross toolchains.
- rockstar-launcher/build-container.sh: build the launcher in a native
  Ubuntu container with a DWARF2 mingw, used on macOS only.
- vr/build.sh: stop aborting silently when ANDROID_NDK_HOME names an NDK
  that is not installed.
- build_local.sh: expand the empty stores_check array safely on bash 3.2 so
  the script reaches its signing step.
2026-11-21 22:51:27 -05:00
MaxsTechReviewandKurt Himebauch 378175c6ac feat(input): controller-specific on-screen controls with editor, rotation and tablet fixes (#2988)
* feat(input): restore controller-specific overlay designs

* fix(input): restore portrait controller layouts

* fix(input): fix duplicates, rotation and tablet placement in the controller overlays

- Hide the below-game controls while the layout editor is open, and give the
  editor the same cutout insets and optional Steam controls as the game view,
  so the editor never shows a second copy of a control.
- Keep a separate portrait frame for layouts edited in portrait. A layout
  edited in one orientation keeps the stock kit positions in the other instead
  of being stretched across.
- Anchor the overlay to the bottom of the screen and cap the portrait panel's
  physical size, so tablets keep the controls in the lower half.
- Put L2/L1 and R1/R2 side by side in every kit.
- List deleted stock controls in the editor's Add dialog so they can be
  restored, and keep removed rear buttons and trackpads removed.

* fix(input): scale edited overlay layouts around the controller artwork positions

* fix(input): keep stock landscape controls, color setting, keyboard action and displayed frame edits consistent

* fix(input): draw the layout editor with the kit artwork at the size it will be saved

The editor placed its controls in onSizeChanged, which runs during layout, so
the preview canvas was rebuilt or remeasured too late: new controls were laid
out at 0x0 and existing ones kept stale sizes, losing the kit D-pad artwork.
Placement now happens in onMeasure, before the canvas measures its children.

The editor preview used the saved button size instead of the slider value, so
the slider showed a different layout from the one Done saved.

D-pad pieces that joined or left the kit cross were never redrawn, so moving
one piece hid all four.

* fix(input): keep portrait rear buttons and trackpads where they were saved

A portrait save stores the rear buttons and trackpads only in the rotated
frame, but loading that frame only moved controls that already existed in the
main frame, so they were regenerated at the screen edges.

* fix(input): adopt the displayed portrait frame for layouts edited only in landscape

Button size and reset positions now switch to the frame on screen whenever the edited layout's
orientation differs from the editor, not only when a rotated frame exists, so a portrait change
is saved as the portrait frame instead of overwriting the landscape edits. The tools panel stays
open while that happens.

* fix(input): keep a separate button size for the rotated frame

* fix(input): take the shown frame's button size whenever editing switches orientation

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-21 20:11:21 -05:00
MaxsTechReview 183cbd9351 fix(preload): start apps that check for a single thread and stop the first-call allocation hang (#2995)
* fix(preload): look up the native glibc symbol version first so wrapped calls never allocate

On x86 the first dlvsym lookup asked for GLIBC_2.17, which only exists on arm64. The failed lookup makes glibc allocate, which deadlocks when the first wrapped call happens inside a program's own allocator setup. Each architecture now asks for its base version first.

* fix(zram): start the page-out worker per request instead of keeping a thread in every process

Every process that loaded the session preload carried a resident zr-worker thread from its constructor on. Programs that check they are single-threaded before forking or before unshare(CLONE_NEWUSER) failed, for example Chromium's zygote, which could not start its GPU process.

The signal handler now starts the worker with a raw clone on a stack the preload maps itself. The worker makes only raw system calls and exits when no request is left, so starting it from the handler is safe and idle processes stay single-threaded. When the worker cannot be started, the process trims inline in small steps as before.

* fix(preload): start the page-out worker with the same clone flags as a thread

Programs that filter clone to the flag set threads use, as browser
sandboxes do, now accept the worker. The kernel clears the stack-busy
word and wakes waiters when the worker exits.

* fix(preload): page out inline in single-threaded and self-sandboxed processes

A process with one thread may be about to check that it is single-threaded
before fork or unshare, and a process that added a seccomp filter after it
started may trap system calls into its own handler. Neither gets a worker
thread now; both trim inline in small steps as before.

* fix(preload): check the signalled thread's own seccomp filters before starting the worker

Read Seccomp_filters from /proc/thread-self/status so a thread that installed its own filter
without TSYNC trims inline instead of calling clone under that filter, and fall back to the
inline path when the signal mask cannot be changed.

* test(preload): start parked threads with SIGURG already blocked

* test(preload): count only page-out workers when checking for leftover threads
2026-11-21 20:11:18 -05:00
Kurt Himebauch 6af598b25e feat(launcher): tick haptics for controller navigation (#2993)
* feat(launcher): tick haptics for controller navigation, off for touch

* docs: regenerate settings map for controller haptics

* fix(launcher): tick for hat and stick navigation, which arrive as joystick-source keys

* fix(launcher): tick before the Components tab consumes L1/R1
2026-11-21 16:31:58 -05:00
FX192 86226910c3 Correct the tall-aspect game height expectation in the test 2026-11-22 00:09:51 +03:00
FX192 0399c3e510 Use the portrait resolution in the controls-below layout and size the game area to the output aspect 2026-11-21 23:50:19 +03:00
MaxsTechReview 088c8ff1cf fix(battlenet): follow the selected FEX instead of pinning an old build (#2987)
* fix(battlenet): follow the selected FEX instead of pinning a d2rfix build

The Battle.net prefix forced the newest FEXCore d2rfix package from the Nightlies listing, which stopped updating. Its fixes are in the bundled and nightly FEX, so the prefix now uses whatever FEX is selected. Existing d2rfix selections for the Battle.net profile are cleared once; any other choice is kept. The DXVK memory cap and Start without Steam defaults are now applied when a session starts.

* fix(battlenet): import the legacy plugin state before unpinning the Battle.net FEX
2026-11-21 15:31:18 -05:00
Kurt Himebauch 31dd8f9987 feat(session): arrange and hide in-session menu pages, round pinned end-session button (#2989)
* feat(session): arrange and hide the in-session menu pages

* fix(session): the end-session button is a true circle pinned to the right of the menu header

* fix(session): arrange-pages drag reads the current list; reset reloads the page layout even if the activity was recreated

* fix(session): Back leaves Arrange pages first; UI zoo previews don't save page layout

* fix(session): Back on a grabbed page row restores its order before anything else
2026-11-21 15:25:45 -05:00
FX192 567181d05f fix(session): let the portrait custom resolution dialog accept tall sizes 2026-11-21 22:56:29 +03:00
FX192 a9054aac3f fix(session): address review on the landscape and portrait resolution split
Accept generated portrait sizes on reload, use the right orientation and output target when deciding follow screen, show the real size behind each Follow option, treat a saved portrait Desktop resolution as chosen, and update the orientation hint in every locale.
2026-11-21 22:46:45 +03:00
FX192 50dace9958 feat(session): split the display resolution into landscape and portrait
Landscape and Portrait resolution rows with the same options, each with a Follow option so one can mirror the other. Existing choices stay as the landscape resolution and portrait follows landscape by default, so nothing changes until portrait is set.
2026-11-21 22:21:08 +03:00
223 changed files with 11897 additions and 1799 deletions

No files matched your search

@@ -0,0 +1,35 @@
name: Build bionic runtime pack and DroidDeck-Bionic tool
on:
push:
paths:
- 'tools/bionic-runtime/**'
- 'tools/gamescope/patches/0117-wsi-cache-present-bypass-check.patch'
- 'tools/gamescope/patches/0119-wsi-default-images-under-limiter.patch'
- 'app/src/main/cpp/fakeinput_steam.cpp'
- 'tools/gpuload/**'
- '.github/workflows/build-bionic-runtime.yml'
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- name: Host tools
run: |
set -euo pipefail
sudo apt-get update -qq
sudo apt-get install -y -qq --no-install-recommends libwayland-bin libwayland-dev libx11-dev libx11-xcb-dev \
libxcb1-dev libxcb-composite0-dev libglm-dev zstd
- name: Build
run: |
set -euo pipefail
export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
export BUILD_NUMBER=${{ github.run_number }}
tools/bionic-runtime/build.sh "$RUNNER_TEMP/bionic-runtime" "$PWD/out"
- uses: actions/upload-artifact@v4
with:
name: droiddeck-bionic-runtime-${{ github.sha }}
path: out/*
+4 -1
View File
@@ -29,11 +29,14 @@ jobs:
persist-credentials: false
- name: Build in Arch Linux ARM
env:
GH_TOKEN: ${{ github.token }}
FEX_EXTRA_CXXFLAGS: ${{ inputs.cxxflags }}
FEX_THUNKS: ${{ inputs.thunks == 'true' && '1' || '0' }}
run: |
set -euo pipefail
docker run --rm -e FEX_EXTRA_CXXFLAGS="$FEX_EXTRA_CXXFLAGS" -e FEX_THUNKS="$FEX_THUNKS" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh
FEX_VERSION=$(gh api repos/FEX-Emu/FEX/releases/latest --jq .tag_name)
echo "Building $FEX_VERSION, FEX's latest release"
docker run --rm -e FEX_VERSION="$FEX_VERSION" -e FEX_EXTRA_CXXFLAGS="$FEX_EXTRA_CXXFLAGS" -e FEX_THUNKS="$FEX_THUNKS" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh
sudo chown -R "$(id -u):$(id -g)" .
- uses: actions/upload-artifact@v4
with:
+1 -1
View File
@@ -99,7 +99,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader.
- The Rockstar launcher service looks for launcher pipe names in the executables beside the game, since [CitizenFX](https://github.com/citizenfx/fivem)'s `ros-patches-five` shows GTA V opening `GTAVLauncher_Pipe` and [@pingod](https://github.com/pingod)'s [rdr2-linux-launcher](https://github.com/pingod/rdr2-linux-launcher) notes that Rockstar's protected executables resolve such strings only at run time. Read without taking code.
- World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used.
- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. [CurseForge](https://www.curseforge.com/wow) opens in the user's browser, with no API and no key.
- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. Installed addons show their `.toc` version and `X-WoWI-ID`, and are checked against that list for updates, as [WowUp](https://github.com/WowUp/WowUp) does. The Addons tab installs the official [CurseForge](https://www.curseforge.com/download/app) Linux app from CurseForge's own update feed (downloaded at install time and checked against its SHA-512, not included), which keeps its own sign-in.
- The Xbox store runs [@domsvoboda](https://github.com/domsvoboda)'s [nexus-backend](https://github.com/domsvoboda/nexus-backend) 0.2.15 (GPL-3.0, a fork of [Xodus](https://github.com/xodus-gaming/xodus)), and Xbox games load the Windows modules of his [nexus-runtime](https://github.com/domsvoboda/nexus-runtime) (LGPL-2.1-or-later), including the C++ [nexus-xgameruntime](https://github.com/domsvoboda/nexus-xgameruntime) and `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, as nexus-backend's Store license path (commit `27c335e`) does. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
- The Xbox Cloud Gaming player uses the WebRTC client of [@unknownskl](https://github.com/unknownskl)'s [Greenlight](https://github.com/unknownskl/greenlight) (MIT), and its offer tweaks and sharpening follow [@redphx](https://github.com/redphx)'s [Better xCloud](https://github.com/redphx/better-xcloud) (MIT). See `tools/xcloud-player/NOTICE.md`.
- The itch.io butler pack ships butler's `7z.so`, itch.io's build of [7-Zip](https://www.7-zip.org) by Igor Pavlov (LGPL-2.1, unRAR restriction on RAR code), unmodified. Other archives use Apache Commons Compress and the runtime's bsdtar (libarchive).
+32 -1
View File
@@ -205,6 +205,11 @@ static void controller_fork_prepare();
static void controller_fork_parent();
static void controller_fork_child();
// bionic: libc's own start-up calls hooked functions (access) before environ is set. Settings read
// then would be empty and cached for good, so until environ exists hooks see defaults, uncached.
extern "C" char **environ;
static bool env_ready() { return environ != nullptr; }
struct FakeConfig {
const char *hook_dir;
const char *udev_data_dir;
@@ -218,6 +223,10 @@ struct FakeConfig {
// would throw a recursive-init error there, so the fields are filled without allocating, and a
// reentry on the initializing thread gets them while other threads wait for the fork handlers.
static FakeConfig &config() {
if (!env_ready()) {
static FakeConfig early = {"/data/data/com.termux/files/home/fake-input", nullptr, false, false, false};
return early;
}
static FakeConfig cfg;
static std::atomic<int> state{0};
static __thread bool initializing __attribute__((tls_model("initial-exec")));
@@ -587,7 +596,7 @@ get_fake_input_rdev(const char *event) {
__attribute__((visibility("hidden"))) static void load_ring_paths() {
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
if (ring_paths_loaded)
if (ring_paths_loaded || !env_ready())
return;
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
@@ -807,12 +816,25 @@ __attribute__((visibility("hidden"))) static bool is_steam_client() {
__attribute__((visibility("hidden"))) static bool presents_steam_virtual() {
static int known;
if (known == 0) {
if (!env_ready()) return false;
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -1;
}
return known == 1;
}
// The bionic Proton layer's winebus has no udev bus, and its SDL bus skips 28de:11ff (Proton reads Steam's virtual
// pad through udev/evdev), so with FAKE_EVDEV_STEAM_PAD_AS_X360=1 other processes see that pad as a plain Xbox 360 pad.
__attribute__((visibility("hidden"))) static bool steam_pad_as_x360() {
static int known;
if (known == 0) {
if (!env_ready()) return false;
const char *v = getenv("FAKE_EVDEV_STEAM_PAD_AS_X360");
known = v && atoi(v) && !is_steam_client() ? 1 : -1;
}
return known == 1;
}
__attribute__((visibility("hidden"))) static bool
presents_xbox_triggers(const FakeController &fake) {
return fake.uinput || !is_steam_client();
@@ -1391,6 +1413,7 @@ static std::unordered_map<int, std::shared_ptr<DeckHidraw>> &deck_map() {
static bool fake_deck_enabled() {
static int enabled = -1;
if (enabled < 0 && !env_ready()) return false;
if (enabled < 0) enabled = getenv("FAKE_EVDEV_DECK") && atoi(getenv("FAKE_EVDEV_DECK")) ? 1 : 0;
return enabled == 1;
}
@@ -1398,6 +1421,7 @@ static bool fake_deck_enabled() {
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
static int type = -1;
if (type < 0) {
if (!env_ready()) return PAD_TYPE_DECK;
const char *env = getenv("FAKE_EVDEV_PAD_TYPE");
type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM
: env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX
@@ -1470,6 +1494,7 @@ __attribute__((visibility("hidden"))) static uint64_t monotonic_us() {
static bool fake_triton_enabled() {
static int enabled = -1;
if (enabled < 0 && !env_ready()) return false;
if (enabled < 0)
enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0;
return enabled == 1;
@@ -2091,6 +2116,7 @@ static_assert(sizeof(TouchRingFile) <= TOUCH_RING_SIZE, "TouchRingFile layout");
__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
static TouchRingFile *ring = nullptr;
if (!env_ready()) return nullptr;
static std::once_flag once;
std::call_once(once, [] {
const char *path = getenv("FAKE_TOUCHCTL_RING");
@@ -2434,6 +2460,7 @@ __attribute__((constructor)) static void start_touch_controller() {
static constexpr long SYSFS_FS_MAGIC = 0x62656572;
__attribute__((visibility("hidden"))) static const char *deck_listing_dir() {
if (!env_ready()) return nullptr;
static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING");
return dir && *dir ? dir : nullptr;
}
@@ -3689,6 +3716,10 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
id.bustype = 0x03;
if (made) {
id = made->id;
if (steam_pad_as_x360() && id.vendor == STEAM_VIRTUAL_VENDOR_ID && id.product == STEAM_VIRTUAL_PRODUCT_ID) {
id.vendor = X360_VENDOR_ID;
id.product = X360_PRODUCT_ID;
}
} else if (presents_steam_virtual()) {
id.vendor = STEAM_VIRTUAL_VENDOR_ID;
id.product = STEAM_VIRTUAL_PRODUCT_ID;
+6 -2
View File
@@ -518,6 +518,10 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
img = vkp_image_import_dmabuf(nh->data[0], fmt == AHB_RGB10A2 ? DRM_ABGR2101010 : DRM_ABGR8888, mod, w, h,
got.stride * 4, 0, 1);
path = "dma-buf (QTI handle)";
if (!img && mod == MOD_LINEAR && vkp_can_import_ahb()) {
img = vkp_image_import_ahb(ahb, info, sizeof(info));
if (img) { mod = SC_MOD_GRALLOC; path = "AHardwareBuffer"; }
}
} else {
if (tier == TIER_UBWC) {
char hd[256];
@@ -941,7 +945,7 @@ int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const stru
int wait_fd;
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
if (idx < 0) { log_drop(l); return 0; }
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;
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);
@@ -1150,7 +1154,7 @@ int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int transl
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 0; }
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;
if (present_slot(l, idx, geo, NULL, translucent) != 0) return -1;
if (!l->first_logged) {
@@ -24,6 +24,12 @@ static inline uint32_t vkp_linear_dmabuf_texel_bytes(VkFormat fmt) {
return fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? 8u : 4u;
}
static inline int vkp_padded_linear_target_needs_layout(int drm_modifiers, uint64_t modifier, VkFormat fmt,
int w, uint32_t stride, uint32_t offset) {
return !drm_modifiers && modifier == 0 &&
(offset != 0 || (uint64_t)stride != (uint64_t)w * vkp_linear_dmabuf_texel_bytes(fmt));
}
static inline VkDeviceSize vkp_linear_dmabuf_copy(VkFormat fmt, int w, int h, uint32_t stride, uint32_t offset,
VkBufferImageCopy *copy) {
const uint32_t texel = vkp_linear_dmabuf_texel_bytes(fmt);
@@ -39,11 +45,11 @@ static inline VkDeviceSize vkp_linear_dmabuf_copy(VkFormat fmt, int w, int h, ui
}
static inline VkBufferMemoryBarrier vkp_linear_dmabuf_ownership(VkBuffer buffer, uint32_t queue_family,
int acquire) {
VkAccessFlags access, int acquire) {
return (VkBufferMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
.srcAccessMask = acquire ? 0 : VK_ACCESS_TRANSFER_READ_BIT,
.dstAccessMask = acquire ? VK_ACCESS_TRANSFER_READ_BIT : 0,
.srcAccessMask = acquire ? 0 : access,
.dstAccessMask = acquire ? access : 0,
.srcQueueFamilyIndex = acquire ? VK_QUEUE_FAMILY_FOREIGN_EXT : queue_family,
.dstQueueFamilyIndex = acquire ? queue_family : VK_QUEUE_FAMILY_FOREIGN_EXT,
.buffer = buffer,
+1 -1
View File
@@ -22,7 +22,7 @@
X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \
X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \
X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) X(GetAndroidHardwareBufferPropertiesANDROID) \
X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) \
X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) X(CmdCopyImageToBuffer) \
X(CreateBuffer) X(DestroyBuffer) X(GetBufferMemoryRequirements) X(BindBufferMemory) \
X(CmdCopyBufferToImage) \
\
+72 -49
View File
@@ -1123,7 +1123,7 @@ static void release_external_client_draws(VkCommandBuffer cmd, const struct vkp_
static void stage_linear_dmabuf(VkCommandBuffer cmd, const struct vkp_image *img) {
if (!img || !img->linear_buf) return;
const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkBufferMemoryBarrier acquire = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, 1);
VkBufferMemoryBarrier acquire = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, VK_ACCESS_TRANSFER_READ_BIT, 1);
VkImageMemoryBarrier write = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
@@ -1132,7 +1132,7 @@ static void stage_linear_dmabuf(VkCommandBuffer cmd, const struct vkp_image *img
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
0, NULL, 1, &acquire, 1, &write);
g_vk.CmdCopyBufferToImage(cmd, img->linear_buf, img->image, VK_IMAGE_LAYOUT_GENERAL, 1, &img->linear_copy);
VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, 0);
VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(img->linear_buf, g_qfam, VK_ACCESS_TRANSFER_READ_BIT, 0);
VkImageMemoryBarrier read = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
@@ -1259,7 +1259,8 @@ static int import_linear_dmabuf(struct vkp_image *img, int fd, const VkBufferIma
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO,
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT};
VkBufferCreateInfo bci = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .pNext = &ext, .size = size,
.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE};
.usage = img->blit_dst ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE};
VkResult r = g_vk.CreateBuffer(g_dev, &bci, NULL, &img->linear_buf);
if (r != VK_SUCCESS) goto fail;
uint32_t allowed = 0xffffffff;
@@ -1312,8 +1313,8 @@ static int import_linear_dmabuf(struct vkp_image *img, int fd, const VkBufferIma
img->in_general = 1;
return 0;
fail:
LOGE("dmabuf: reading the linear %dx%d buffer at its row pitch failed (%s); importing it as an image",
img->w, img->h, vk_result_name(r));
LOGE("dmabuf: %s the linear %dx%d buffer at its row pitch failed (%s)",
img->blit_dst ? "writing" : "reading", img->w, img->h, vk_result_name(r));
if (dupfd >= 0) close(dupfd);
destroy_image_objects(img);
return -1;
@@ -1324,15 +1325,20 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
if (modifier == MOD_INVALID || w <= 0 || h <= 0) return NULL;
if (dev_init() != 0) return NULL;
const VkFormat format = drm_to_vk(drm_format);
const int padded_target = as_blit_dst &&
vkp_padded_linear_target_needs_layout(g_drm_modifiers, modifier, format, w, stride, offset);
if (padded_target && !g_vk.CmdCopyImageToBuffer) return NULL;
struct vkp_image *img = calloc(1, sizeof(*img));
if (!img) return NULL;
img->w = w; img->h = h; img->dmabuf = 1; img->blit_dst = as_blit_dst ? 1 : 0;
img->fmt = drm_to_vk(drm_format);
const int through_buffer = vkp_linear_dmabuf_through_buffer(g_drm_modifiers, modifier, as_blit_dst);
img->fmt = format;
const int through_buffer = padded_target || vkp_linear_dmabuf_through_buffer(g_drm_modifiers, modifier, as_blit_dst);
const VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
const int modifier_sampled = !as_blit_dst && g_drm_modifiers && g_vk.GetPhysicalDeviceImageFormatProperties2 &&
modifier_importable(img->fmt, modifier, sampled_usage);
img->sampled = through_buffer ? optimal_sampled(img->fmt) : modifier_sampled;
img->sampled = !as_blit_dst && (through_buffer ? optimal_sampled(img->fmt) : modifier_sampled);
/* Each new format/modifier/size a client hands over, once, for the graphics report: a colour
* or swizzle mismatch on a non-Adreno driver shows up as the pair it arrived as. */
{
@@ -1358,7 +1364,12 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
if (through_buffer) {
VkBufferImageCopy linear_copy;
const VkDeviceSize linear_size = vkp_linear_dmabuf_copy(img->fmt, w, h, stride, offset, &linear_copy);
if (linear_size && import_linear_dmabuf(img, fd, &linear_copy, linear_size) == 0) return img;
if (linear_size && import_linear_dmabuf(img, fd, &linear_copy, linear_size) == 0) {
if (padded_target) droiddeck_log("gpu", "linear layer target %dx%d writes at pitch %u via DMA-BUF",
w, h, stride);
return img;
}
if (padded_target) { free(img); return NULL; }
img->sampled = modifier_sampled;
}
VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride};
@@ -2522,6 +2533,48 @@ int vkp_map_draw(const struct vkp_draw *d, int out[8]) {
return 1;
}
static void blit_to_layer(VkCommandBuffer cmd, VkImage src, VkImageLayout src_layout, struct vkp_image *dst,
const VkImageBlit *blit, VkFilter filter) {
const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
const VkImageMemoryBarrier acquire = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = dst->staged ? VK_QUEUE_FAMILY_IGNORED : VK_QUEUE_FAMILY_FOREIGN_EXT,
.dstQueueFamilyIndex = dst->staged ? VK_QUEUE_FAMILY_IGNORED : g_qfam,
.image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 0, NULL, 1, &acquire);
g_vk.CmdBlitImage(cmd, src, src_layout, dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter);
if (dst->staged) {
const VkImageMemoryBarrier read = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = dst->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 0, NULL, 1, &read);
const VkBufferMemoryBarrier write = vkp_linear_dmabuf_ownership(dst->linear_buf, g_qfam, VK_ACCESS_TRANSFER_WRITE_BIT, 1);
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 1, &write, 0, NULL);
VkBufferImageCopy copy = dst->linear_copy;
copy.imageExtent.width = (uint32_t)blit->dstOffsets[1].x;
copy.imageExtent.height = (uint32_t)blit->dstOffsets[1].y;
g_vk.CmdCopyImageToBuffer(cmd, dst->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst->linear_buf, 1, &copy);
const VkBufferMemoryBarrier release = vkp_linear_dmabuf_ownership(dst->linear_buf, g_qfam, VK_ACCESS_TRANSFER_WRITE_BIT, 0);
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 1, &release, 0, NULL);
return;
}
const VkImageMemoryBarrier release = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
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 || g_dev_state == -2 || dev_init() != 0) {
if (wait_fd >= 0) close(wait_fd);
@@ -2540,41 +2593,28 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
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[2] = {
src_external ? src_pair.acquire : (VkImageMemoryBarrier){
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},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}};
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
if (!src_external) {
acq[0].oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq[0].newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
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, 2, acq);
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}}};
g_vk.CmdBlitImage(g_cmd, src->image,
src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
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);
VkImageMemoryBarrier rel = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 0, NULL, 1, &rel);
g_vk.EndCommandBuffer(g_cmd);
VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
@@ -2890,31 +2930,14 @@ static int pass_finish(const VkImage *srcs, VkImageLayout src_layout, struct vkp
}
const int gpu_wait = take_wait_fd(wait_fd);
if (gpu_wait < 0) { g_vk.EndCommandBuffer(cmd); return -1; }
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
for (int i = 0; i < n; i++) {
struct vkp_image *dst = dsts[i];
VkImageMemoryBarrier acq = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
.dstQueueFamilyIndex = g_qfam, .image = dst->image, .subresourceRange = range,
.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 0, NULL, 0, NULL, 1, &acq);
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}};
g_vk.CmdBlitImage(cmd, srcs[i], src_layout, dst->image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit,
(g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR);
VkImageMemoryBarrier rel = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .image = dst->image, .subresourceRange = range,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 0, NULL, 1, &rel);
blit_to_layer(cmd, srcs[i], src_layout, dst, &blit,
(g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR);
}
g_vk.EndCommandBuffer(cmd);
@@ -46,6 +46,7 @@ class App : Application() {
com.droiddeck.launcher.input.ShortcutsRelay.Holder.install(this)
com.droiddeck.launcher.agent.AgentHost.refresh(this)
com.droiddeck.launcher.ui.NavTabs.load(this)
com.droiddeck.launcher.ui.DrawerPages.load(this)
com.droiddeck.launcher.ui.DeveloperTools.load(this)
com.droiddeck.launcher.ui.AgentPet.install(this)
if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent"
@@ -17,8 +17,11 @@ import android.os.Looper
import android.util.Log
import android.view.Display
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowManager
import android.widget.EditText
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
@@ -199,6 +202,7 @@ 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 controllerHaptics by mutableStateOf(true)
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
private var downloadMirror by mutableStateOf("")
private var downloadPrefix by mutableStateOf("")
@@ -529,7 +533,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
saveAction(getString(R.string.main_addons_importing, name)) {
if (SessionState.running) return@saveAction getString(R.string.main_addons_close_session)
val imported = try {
com.droiddeck.launcher.runtime.WowAddons.import(zip, target)
com.droiddeck.launcher.runtime.WowAddons.import(zip, target, context = this@FrontEndActivity)
} catch (_: com.droiddeck.launcher.runtime.WowAddons.TooLarge) {
return@saveAction getString(R.string.main_addons_too_large, zip.name)
}
@@ -538,7 +542,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
val downloads = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).path
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), getString(R.string.main_addons_pick_zip, name), downloads))
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip", "rar", "7z"), getString(R.string.main_addons_pick_zip, name), downloads))
}
private fun exportSaves(name: String, layout: GameSaves.Layout, game: () -> GameSaves.Game) {
@@ -585,6 +589,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
private var settingsMode by mutableStateOf<String?>(null)
private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION)
private var resolutionPortrait by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE)
private var fexPreset by mutableStateOf("")
private var forceSsbs by mutableStateOf(false)
private var steamClientArch by mutableStateOf("arm64")
@@ -1264,6 +1269,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
requestedOrientation = launcherOrientation
homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this)
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
controllerHaptics = SessionPrefs.controllerHaptics(this)
downloadSource = DownloadSource.mode(this)
downloadMirror = DownloadSource.mirror(this)
downloadPrefix = DownloadSource.custom(this)
@@ -1363,6 +1369,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
launcherOrientation = launcherOrientation,
homePage = homePage,
launcherFullscreen = launcherFullscreen,
controllerHaptics = controllerHaptics,
downloadSource = downloadSource,
downloadMirror = downloadMirror,
downloadPrefix = downloadPrefix,
@@ -1679,6 +1686,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
com.droiddeck.launcher.core.AppUiPrefs.setHomePage(this, value)
homePage = value
},
onControllerHaptics = { on -> SessionPrefs.setControllerHaptics(this, on); controllerHaptics = on },
onLauncherFullscreen = { on ->
SessionPrefs.setLauncherFullscreen(this, on)
launcherFullscreen = on
@@ -2008,6 +2016,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (!hasFocus) triggerKeys.cancel()
if (hasFocus) {
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
applyLauncherFullscreen()
@@ -2037,6 +2046,36 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
private var touchDownX = 0f
private var touchDownY = 0f
private var touchDragged = false
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
com.droiddeck.launcher.ui.ScreenTaps.count++
touchDownX = event.rawX
touchDownY = event.rawY
touchDragged = false
}
// A drag that wanders back to where it began is still a drag, not a tap.
MotionEvent.ACTION_MOVE -> if (!touchDragged &&
kotlin.math.hypot(event.rawX - touchDownX, event.rawY - touchDownY) > ViewConfiguration.get(this).scaledTouchSlop
) touchDragged = true
MotionEvent.ACTION_CANCEL -> touchDragged = true
}
val handled = super.dispatchTouchEvent(event)
if (event.actionMasked == MotionEvent.ACTION_UP) leaveTextFieldOnOutsideTap(event)
return handled
}
private fun leaveTextFieldOnOutsideTap(event: MotionEvent) {
val field = currentFocus as? EditText ?: return
val slop = ViewConfiguration.get(this).scaledTouchSlop
if (touchDragged || kotlin.math.hypot(event.rawX - touchDownX, event.rawY - touchDownY) > slop) return
com.droiddeck.launcher.ui.releaseTextField(field, IntArray(2).also(field::getLocationOnScreen), event.rawX, event.rawY)
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
if (compatLaunch != null) {
@@ -2047,6 +2086,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (!compatLaunch!!.loading.ended && event.keyCode !in listOf(
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) return true
}
if (!triggerKeys.synthesizing && triggerKeys.nativeKey(event)) return true
val tabStep = com.droiddeck.launcher.ui.dualPageStep(event)
val tabs = com.droiddeck.launcher.ui.MainTabSteps.handler
if (tabStep != null && tabs != null) {
if (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event)
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) tabs(tabStep)
return true
}
if (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event)
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
@@ -2063,9 +2111,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
private val triggerKeys = com.droiddeck.launcher.input.TriggerKeys { dispatchKeyEvent(it) }
override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean {
if (compatLaunch != null && !compatLaunch!!.loading.ended &&
com.droiddeck.launcher.input.PadBridge.isControllerMotionEvent(event)) return true
triggerKeys.onMotion(event)
return super.dispatchGenericMotionEvent(event)
}
@@ -2195,6 +2246,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
override fun onDestroy() {
triggerKeys.cancel()
gameLaunchRequest.incrementAndGet()
cancelCompatLaunch()
updates.unregister()
@@ -2588,7 +2640,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (settingsMode != mode) return
com.droiddeck.launcher.ui.ModeSheetRows(
ModeSettings(
mode = mode, resolution = resolution,
mode = mode, resolution = resolution, resolutionPortrait = resolutionPortrait,
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
hdr = hdrOn, hdrReason = hdrReason, hdrDisplay = hdrDisplay, zeroCopy = zeroCopyOn,
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
@@ -2643,7 +2695,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onIntegration = ::configureIntegration,
onIntegrationAppInfo = ::openAppInfo,
onIntegrationLocation = ::openWifiDiscoverySettings,
onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value },
onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); loadResolutions(mode) },
onResolutionPortrait = { value -> SessionPrefs.setResolutionChoice(this, mode, value, portrait = true); loadResolutions(mode) },
onHdr = { on -> com.droiddeck.launcher.session.SessionHdr.set(this, mode, on); hdrOn = on },
onZeroCopy = { on ->
SessionPrefs.setZeroCopy(this, mode, on); zeroCopyOn = on
@@ -2976,11 +3029,17 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}, "shader-precache").start()
}
private fun loadResolutions(mode: String) {
val panel = com.droiddeck.launcher.session.SessionDisplay.panelSize(this)
resolution = SessionPrefs.resolutionStored(this, mode, panel, false)
resolutionPortrait = SessionPrefs.resolutionStored(this, mode, panel, true)
}
private fun loadModeSettings(mode: String) {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
unfoldedControls = SessionPrefs.unfoldedControls(this)
unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this)
resolution = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
loadResolutions(mode)
fexPreset = SessionPrefs.fexPreset(this)
forceSsbs = SessionPrefs.forceSsbs(this)
fastSync = SessionPrefs.fastSync(this)
@@ -3343,6 +3402,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
Thread({
val ok = com.droiddeck.launcher.session.SettingsReset.resetAll(this, gameProfiles, scopes)
ui.post {
com.droiddeck.launcher.ui.DrawerPages.load(applicationContext)
if (isDestroyed) return@post
com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM)
if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show()
@@ -149,7 +149,7 @@ internal class ProtonMenu(
fun refreshProtons() {
refreshExperimental()
protonRows = ProtonExtras.tools.map {
protonRows = ProtonExtras.offered(activity).map {
val all = ProtonExtras.installedAll(activity, it)
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
}
@@ -244,9 +244,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun key(code: Int, down: Boolean) { heldKeys.set(4, code, down) }
override fun button(code: Int, down: Boolean) { heldButtons.set(4, code, down) }
override fun pointer(dx: Float, dy: Float) {
if (Looper.myLooper() == Looper.getMainLooper()) moveInputPointer(dx, dy)
else uiHandler.post {
if (resumed && !SessionState.suspended && !pipUi && !drawerOpen && !inputSettingsOpen)
if (Looper.myLooper() == Looper.getMainLooper()) {
if (!menuOwnsController) moveInputPointer(dx, dy)
} else uiHandler.post {
if (resumed && !SessionState.suspended && !pipUi && !menuOwnsController && !inputSettingsOpen)
moveInputPointer(dx, dy)
}
}
@@ -545,6 +546,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
drawerOpenState = value
if (!value && drawerDocked) closeDockedMenu()
}
private val dockedMenuIdle: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuIdleOnBottom(drawerOpen, drawerDocked, drawerPinned, dockedMenuController)
private val dockedTouchOnly: Boolean get() = drawerOpen && drawerDocked && !dockedMenuController
private val menuOwnsController: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuOwnsController(drawerOpen, drawerDocked, dockedMenuController)
private var quitFrom by mutableStateOf<androidx.compose.ui.geometry.Rect?>(null)
private var quitFlooded = false
private var leaving by mutableStateOf(false)
@@ -588,6 +592,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
private var drawerControllerActive by mutableStateOf(false)
private var backHold by mutableStateOf(true)
private var dockedMenuController by mutableStateOf(false)
private var sessionOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
private var backActionsInverted by mutableStateOf(false)
private var backDoubleTapMs by mutableStateOf(500)
private var lowLatency by mutableStateOf(true)
@@ -838,6 +844,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
SessionEvents.begin(this, mode, SessionPaths.label(mode, intent.getStringExtra(SessionService.EXTRA_PROGRAM)))
SessionState.secondScreenAutoOpened = false
SessionState.bottomMenu = false
SessionState.secondScreenProvisional = false
SessionState.secondScreenAutomatic = false
SessionState.gameOnBottom = false
@@ -1109,6 +1116,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
when {
::loading.isInitialized && loading.ended -> finish()
inputSettingsOpen -> inputSettingsOpen = false
dockedTouchOnly -> routeBackAction()
drawerOpen -> drawerOpen = false
achievementsOpen -> closeAchievements()
pcKeyboardOpen -> pcKeyboardOpen = false
@@ -1137,6 +1145,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
val uiPointer = appUiOwnsPointer()
val cursorHidden = cursorHiddenByUi()
androidx.compose.runtime.SideEffect {
com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity,
(drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && steamVrStatus != SteamVr.Status.RUNNING)
@@ -1187,7 +1196,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
} else {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
CursorOverlay({ cursorPos }, cursorVisible && (!uiPointer || onlyPcKeyboardOpen()) && !bottomOutputActive,
CursorOverlay({ cursorPos }, cursorVisible && (!cursorHidden || onlyPcKeyboardOpen()) && !bottomOutputActive,
resources.displayMetrics.density,
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
if (memoryHud.text.isNotEmpty()) HudText(memoryHud.text, hudColor, hudOpacity)
@@ -1304,9 +1313,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
runCatching { com.droiddeck.launcher.session.TelemetryOutput.applyAutomatic(this@SessionActivity, nextGame) }
}
}
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) {
LaunchedEffect(drawerOpen, menuOwnsController, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) {
updateOnScreenControls()
padBridge?.setInputEnabled(resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended)
padBridge?.setInputEnabled(resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended)
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || inputSettingsOpen || pipUi || appTextFocus || SessionState.suspended) {
backQamInput.cancel()
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this@SessionActivity)
@@ -1358,13 +1367,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onDismiss = { gestureSettingsOpen = false },
onSaved = { gestureSettingsOpen = false; refreshGestureConfig() },
)
androidx.compose.runtime.LaunchedEffect(drawerOpen) {
androidx.compose.runtime.LaunchedEffect(drawerOpen, menuOwnsController) {
if (drawerOpen) {
syncLossless()
releasePads()
androidx.compose.runtime.withFrameNanos { }
val requested = focusDrawer()
Log.i(TAG, "drawer root focus requested=$requested docked=$drawerDocked")
if (menuOwnsController) {
releasePads()
androidx.compose.runtime.withFrameNanos { }
val requested = focusDrawer()
Log.i(TAG, "drawer root focus requested=$requested docked=$drawerDocked")
} else {
releaseDrawerDirection()
}
} else {
releaseDrawerDirection()
}
@@ -1423,7 +1436,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (!SessionState.manualPause && !SessionState.suspended) pauseAnimated = false
}
SessionPausedOverlay(
suspended = SessionState.suspended && (!autoResume || SessionState.resumeFailed || SessionState.manualPause),
suspended = (SessionState.suspended || SessionState.manualPause) && (!autoResume || SessionState.resumeFailed || SessionState.manualPause),
engaged = SessionState.resumeRequested || SessionState.resuming,
failures = SessionState.resumeFailures,
frame = pausedFrame,
@@ -1752,6 +1765,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
com.droiddeck.launcher.session.InputSysfsComponent.padTypeChanged(SessionPrefs.padType(id))
padType = id
onScreenControls?.reload()
applyUnfoldedControls()
unfoldedPanel?.reload()
bottomInputControls?.reload()
},
backHold = backHold,
@@ -1759,6 +1774,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionPrefs.setBackHold(this@SessionActivity, on)
backHold = on
},
dockedMenuController = dockedMenuController,
onDockedMenuController = { on ->
SessionPrefs.setDockedMenuController(this@SessionActivity, on)
dockedMenuController = on
if (!on && drawerDocked) drawerControllerActive = false
},
backActionsInverted = backActionsInverted,
backDoubleTapMs = backDoubleTapMs,
onBackDoubleTapMs = { ms ->
@@ -1827,6 +1848,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
setRelativeMouse(mode)
},
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
onSelectMenuMode = ::pickMenuMode,
onSecondScreenMode = { mode ->
if (docked) drawerOpen = false
pickSecondScreenMode(mode)
@@ -1850,6 +1872,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
pipAutoEnter = pipAutoEnter,
onPip = { pip.enter() },
onPause = ::pauseNow,
paused = SessionState.suspended || SessionState.manualPause,
onResume = { SessionService.resume(this@SessionActivity) },
orientation = sessionOrientation,
onOrientation = { value ->
SessionPrefs.setOrientation(this@SessionActivity, value)
sessionOrientation = value
applyFollowOrientation(resources.configuration)
},
onPipAutoEnter = { on ->
SessionPrefs.setPipAutoEnter(this@SessionActivity, on)
pipAutoEnter = on
@@ -1947,7 +1977,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun sendSteamGuide() {
drawerOpen = false
if (!dockedTouchOnly) drawerOpen = false
padBridge?.triggerSteamMenu()
}
@@ -1994,7 +2024,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun triggerSteamQam() {
drawerOpen = false
if (!dockedTouchOnly) drawerOpen = false
padBridge?.triggerQam()
}
@@ -2083,7 +2113,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun performBackAction(double: Boolean) {
val isSteam = SessionState.mode == SessionService.MODE_STEAM
val opensQam = isSteam && (double xor backActionsInverted)
if (opensQam) triggerSteamQam() else drawerOpen = !drawerOpen
if (opensQam) triggerSteamQam() else if (!dockedTouchOnly) drawerOpen = !drawerOpen
}
private fun handleHomeGuideIntent(incoming: Intent?) {
@@ -2627,6 +2657,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
oscRearButtons = SessionPrefs.oscRearButtons(this)
oscTrackpads = SessionPrefs.oscTrackpads(this)
backHold = SessionPrefs.backHold(this)
dockedMenuController = SessionPrefs.dockedMenuController(this)
sessionOrientation = SessionPrefs.orientation(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
@@ -2814,17 +2846,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (!SessionState.running) {
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
}
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() }
FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb"))
com.droiddeck.launcher.input.VrControllers.publish(this)
val turnip = TurnipDriver(this)
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "surface.driver-setup")
if (!CompositorHost.isStarted) {
CompositorHost.displayChoice = SessionPrefs.androidDriver(this)
com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(this, SessionPrefs.androidDriver(this))
}
val driverId = if (CompositorHost.isStarted) null else turnip.install()
val output = CompositorHost.prepare(this)
val previous = SessionState.outputSize
val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
@@ -2851,15 +2873,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
pushCardboard(activeCardboard)
WaylandCompositor.nativeSetCardboardPoseFile(File(filesDir, ".wayland-rt/droiddeck-headpose").path)
com.droiddeck.launcher.glasses.SpatialTracking.attachPublisher(File(filesDir, ".wayland-rt/droiddeck-spatialpose").path)
if (!SessionState.running) {
val waylandLog = File(SessionPaths.beginOrCurrent(this), "wayland.log")
WaylandCompositor.setSessionLogFile(waylandLog)
try {
android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true)
} catch (e: Exception) {
Log.w(TAG, "could not point the compositor's log at $waylandLog", e)
}
}
if (!SessionState.running) CompositorHost.logToSession(this)
val mode = hdrPrefMode()
if (probe != null) {
WaylandCompositor.nativeSetHdrDisplay(
@@ -2879,19 +2893,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
)
Log.i(TAG, "hdr: " + (if (tonemap) "tone-mapped (${probe.reason})" else if (capable) "available" else "unavailable") + " · display ${probe.formats.ifEmpty { "SDR" }}")
}
if (!SessionState.running) {
val on = SessionState.hdrCapable && SessionPrefs.hdr(this, mode)
SessionState.hdr = on
WaylandCompositor.nativeSetHdrOutput(on)
WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode))
Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session")
}
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId")
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(),
)
if (!SessionState.running) CompositorHost.applyHdr(this, mode)
CompositorHost.start(this, output, holder.surface, size, refreshHz(holder), outputFpsLimit())
onOutputAttached(holder)
if (SessionState.running && size != previous) {
Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
@@ -2956,16 +2959,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
WaylandCompositor.nativeResizeOutput(size.first, size.second)
}
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this)
private fun followScale(): Float {
val mode = displayMode()
val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait())
return com.droiddeck.launcher.session.SessionDisplay.followScale(choice) ?: 1f
}
private fun followChoice(): Boolean {
val mode = displayMode()
return com.droiddeck.launcher.session.SessionDisplay.isFollow(
SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)))
SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait()))
}
private fun applyFollowOrientation(config: android.content.res.Configuration) {
@@ -3031,17 +3036,19 @@ 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 outputSize(): Pair<Int, Int> =
com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
resolutionChoice(), SessionPrefs.portrait(this) && !controlsBelowWanted())
resolutionChoice(), portraitOutput())
private fun resolutionChoice(): String {
private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this)): String {
val mode = displayMode()
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
return if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode))
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode, portrait))
com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN
else SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
else SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), portrait)
}
private fun refreshHz(): Float = refreshHz(null)
@@ -3517,7 +3524,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val steamVolume =
SessionState.mode == SessionService.MODE_STEAM && SessionState.running &&
SessionState.firstFrameSeen && !SessionState.suspended && !ended &&
!pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
!pipUi && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen &&
!gestureSettingsOpen && !inputSettingsOpen && !appTextFocus && window.decorView.hasWindowFocus()
if (steamVolume) {
val audio = getSystemService(android.media.AudioManager::class.java)
@@ -3531,13 +3538,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (penStream.holdsKey(event) || (penSettings.mode != SessionPrefs.PEN_TOUCH && PenStream.isPenKey(event))) return penStream.onKey(event)
if (appTextFocus) return super.dispatchKeyEvent(event)
if (!pipUi) {
if (physicalInputBindings?.onKey(event, resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
if (physicalInputBindings?.onKey(event, resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen &&
!inputSettingsOpen && !gestureSettingsOpen && !SessionState.suspended && !loading.visible) == true) return true
if (physicalShortcuts.onKey(
event,
enabled = resumed && SessionState.running && !SessionState.suspended &&
!(drawerOpen && event.keyCode == KeyEvent.KEYCODE_BUTTON_A) &&
!(drawerOpen && PhysicalShortcuts.isDrawerNavigationKey(event)) &&
!(menuOwnsController && event.keyCode == KeyEvent.KEYCODE_BUTTON_A) &&
!(menuOwnsController && PhysicalShortcuts.isDrawerNavigationKey(event)) &&
(event.deviceId to event.keyCode) !in resumeKeysDown &&
!(::loading.isInitialized && (loading.visible || loading.ended)) &&
!pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen,
@@ -3545,12 +3552,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
) { action ->
pendingBackAction?.let(uiHandler::removeCallbacks)
pendingBackAction = null
drawerControllerActive = true
if (!dockedMenuIdle) drawerControllerActive = true
Log.i(TAG, "physical shortcut ${action.name} device=${event.deviceId} key=${event.keyCode} scan=${event.scanCode}")
when (action) {
PhysicalShortcuts.Action.STEAM -> sendSteamGuide()
PhysicalShortcuts.Action.QAM -> triggerSteamQam()
PhysicalShortcuts.Action.DROIDDECK -> drawerOpen = !drawerOpen
PhysicalShortcuts.Action.DROIDDECK -> if (!dockedTouchOnly) drawerOpen = !drawerOpen
}
}) return true
}
@@ -3576,7 +3583,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
if (mouseBackHandled) return true
val backToQam = !pipUi && !appTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
val backToQam = !pipUi && !appTextFocus && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen &&
!inputSettingsOpen && !gestureSettingsOpen &&
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
!SessionState.suspended && padBridge?.canHoldQam() == true
@@ -3589,12 +3596,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
if (pad !== event) return dispatchKeyEvent(pad)
val fromController = PadBridge.isControllerKeyEvent(event)
if (fromController && (drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
if (fromController && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
padBridge?.setInputEnabled(false)
padBridge?.onKeyEvent(event)
}
if (fromController && event.action == KeyEvent.ACTION_DOWN) {
if (drawerOpen && !drawerControllerActive) focusDrawer()
if (fromController && event.action == KeyEvent.ACTION_DOWN && !dockedMenuIdle) {
if (menuOwnsController && !drawerControllerActive) focusDrawer()
drawerControllerActive = true
}
if (fromController && event.keyCode == KeyEvent.KEYCODE_BUTTON_B && ::loading.isInitialized && loading.visible && !loading.ended && !drawerOpen) {
@@ -3613,7 +3620,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
val drawerShortcutKey = event.deviceId to event.keyCode
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_SELECT || event.keyCode == KeyEvent.KEYCODE_BUTTON_START) &&
((drawerOpen && SessionState.mode == SessionService.MODE_STEAM) || drawerShortcutKey in drawerShortcutKeysDown)) {
((menuOwnsController && SessionState.mode == SessionService.MODE_STEAM) || drawerShortcutKey in drawerShortcutKeysDown)) {
if (event.action == KeyEvent.ACTION_DOWN) {
drawerShortcutKeysDown.add(drawerShortcutKey)
if (event.repeatCount == 0) {
@@ -3625,7 +3632,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
return true
}
if (drawerOpen) {
if (drawerOpen && (menuOwnsController || (!fromController && !(dockedTouchOnly && event.keyCode == KeyEvent.KEYCODE_BACK)))) {
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
drawerPage = sessionDrawerPages(glasses.present)
@@ -3695,11 +3702,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
if (pipUi) return true
notePress(event)
if (PadBridge.isControllerMotionEvent(event) && (drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
if (PadBridge.isControllerMotionEvent(event) && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
padBridge?.setInputEnabled(false)
padBridge?.onMotionEvent(event)
}
if (drawerOpen && PadBridge.isControllerMotionEvent(event)) {
if (menuOwnsController && PadBridge.isControllerMotionEvent(event)) {
if (!drawerControllerActive) focusDrawer()
drawerControllerActive = true
if (event.actionMasked == MotionEvent.ACTION_MOVE &&
@@ -3876,6 +3883,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun closeDockedMenu() {
SessionState.bottomMenu = false
drawerDocked = false
val presentation = secondScreenPresentation ?: return
presentation.showMenu(false)
@@ -4301,7 +4309,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
?: if (SessionState.gameOnBottom) bottomGameDisplay()?.displayId else null
SessionState.secondScreenAutoOpened = true
if (gameDisplay != null && gameDisplay != target.displayId && secondScreenDisplays.any { it.id == gameDisplay }) {
panelMode(openingPanel())
panelMode(openingSurface())
} else {
val selectionChanged = selectedSecondScreenDisplay != target.displayId
selectedSecondScreenDisplay = target.displayId
@@ -4320,14 +4328,43 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun openingPanel() = SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this, desktopSession), SessionState.deckPad,
bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available(), desktopSession)
bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available())
private fun openingSurface() = openingPanel().takeIf { it != SecondScreenMode.MENU } ?: SecondScreenMode.KEYBOARD_TRACKPAD
private fun menuShownOnBottom() = drawerDocked && (drawerOpen || drawerPinned)
private fun pinDockedMenu() {
if (!dockDrawer()) return
drawerLayerOpen = false
if (!openDockedMenu()) return
drawerDocked = true
drawerOpenState = false
drawerPinned = true
updateKeyboardRoute()
}
private fun showMenuMode() {
dualControlsProvisional = false
selectSecondScreenMode(secondScreenMode.takeIf { it != SecondScreenMode.NONE } ?: SecondScreenMode.KEYBOARD_TRACKPAD)
if (secondScreenMode != SecondScreenMode.NONE) pinDockedMenu()
}
private fun pickMenuMode() {
typingReturnMode = null
automaticPanel = false
SessionPrefs.setSecondScreenPanel(this, desktopSession, SecondScreenMode.MENU.id)
drawerOpen = true
}
private fun settleDualScreenControls() {
if (!dualControlsProvisional || pipUi || !started || (::loading.isInitialized && loading.visible)) return
dualControlsProvisional = false
if (secondScreenMode == SecondScreenMode.NONE) return
val wanted = openingPanel()
if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
if (wanted == SecondScreenMode.MENU) {
if (!menuShownOnBottom()) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
} else if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
}
private fun selectSecondScreenDisplay(displayId: Int) {
@@ -4348,6 +4385,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
closeSecondScreen(reset = true)
return
}
if (mode == SecondScreenMode.MENU) {
showMenuMode()
return
}
if (secondScreenDisplays.isEmpty()) {
panelMode(SecondScreenMode.NONE)
return
@@ -4364,7 +4405,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun showSecondScreen(requested: SecondScreenMode) {
if (pipUi || !started) return
val mode = if (requested == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad) openingPanel() else requested
val mode = when {
requested == SecondScreenMode.MENU ->
secondScreenMode.takeIf { it != SecondScreenMode.NONE && it != SecondScreenMode.MENU } ?: SecondScreenMode.KEYBOARD_TRACKPAD
requested == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad -> openingSurface()
else -> requested
}
val target = displayManager.getDisplay(selectedSecondScreenDisplay)
if (target == null || !target.isValid || (target.flags and Display.FLAG_PRESENTATION) == 0) {
closeSecondScreen(reset = false)
@@ -4401,6 +4447,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun pickSecondScreenMode(mode: SecondScreenMode) {
typingReturnMode = null
automaticPanel = false
SessionState.bottomMenu = false
if (mode != SecondScreenMode.NONE) SessionPrefs.setSecondScreenPanel(this, desktopSession, mode.id)
selectSecondScreenMode(mode)
}
@@ -4408,7 +4455,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun bottomScreenPicker(mode: SecondScreenMode) = com.droiddeck.launcher.ui.ScreenPicker(
com.droiddeck.launcher.ui.secondScreenModes(false, SessionState.deckPad, bottomPages().isNotEmpty(),
com.droiddeck.launcher.session.BottomDesktop.available()),
mode, ::pickSecondScreenMode, onMenu = { drawerOpen = true },
mode, ::pickSecondScreenMode, onMenu = ::pickMenuMode,
)
private fun secondScreenPresentation(target: Display) = SecondScreenPresentation(
@@ -4620,7 +4667,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val tabRow = unfoldedColumn?.getChildAt(0)?.height?.let {
it - (com.droiddeck.launcher.ui.BAR_HEIGHT.value * resources.displayMetrics.density + 0.5f).toInt()
} ?: 0
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow)
val outputAspect = if (!wanted || SessionState.followScreen) 0f
else outputSize().let { it.first.toFloat() / it.second.coerceAtLeast(1) }
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow, outputAspect)
else FrameLayout.LayoutParams.MATCH_PARENT
val params = surfaceView.layoutParams as FrameLayout.LayoutParams
if (params.height != gameHeight) {
@@ -4629,7 +4678,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
else "unfolded controls: game full screen")
}
val portrait = !com.droiddeck.launcher.session.SessionDisplay.foldable(this)
val dock = if (SessionState.deckPad) com.droiddeck.launcher.input.OnScreenLayout.Dock.deck(portrait, deckPanelLayouts[com.droiddeck.launcher.input.DeckPanel.GAMEPAD])
val kit = com.droiddeck.launcher.input.PadKit.forOverlay(this, primaryInputLayout)
val dock = if (SessionState.deckPad && kit?.steam != false)
com.droiddeck.launcher.input.OnScreenLayout.Dock.deck(portrait, deckPanelLayouts[com.droiddeck.launcher.input.DeckPanel.GAMEPAD])
else com.droiddeck.launcher.input.OnScreenLayout.Dock(portrait, false)
var panel = unfoldedPanel
if (panel != null && (!wanted || panel.dock != dock)) {
@@ -4830,6 +4881,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun dropDockedDrawer() {
if (drawerDocked && (drawerOpenState || drawerPinned)) SessionState.bottomMenu = true
drawerPinned = false
if (!drawerDocked) return
drawerDocked = false
@@ -4848,6 +4900,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (reset) {
panelMode(SecondScreenMode.NONE)
automaticPanel = false
SessionState.bottomMenu = false
}
}
@@ -5400,8 +5453,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun onlyPcKeyboardOpen(): Boolean =
pcKeyboardOpen && !drawerOpen && !achievementsOpen && !inputSettingsOpen && !pipUi && !glassesOutputActive && !touchEditorOpen && !wowChatOnTop
private fun appUiOwnsPointer(): Boolean =
drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || pipUi || glassesOutputActive || bottomOutputActive || touchEditorOpen || wowChatOnTop
private fun otherUiOwnsPointer(): Boolean =
pcKeyboardOpen || achievementsOpen || inputSettingsOpen || pipUi || glassesOutputActive || bottomOutputActive || touchEditorOpen || wowChatOnTop
private fun appUiOwnsPointer(): Boolean = drawerOpen || otherUiOwnsPointer()
/** A touch-only docked menu leaves the game cursor alone, so controller pointer moves stay visible. */
private fun cursorHiddenByUi(): Boolean = menuOwnsController || otherUiOwnsPointer()
private fun applyPlatformPointer(shown: Boolean) {
if (!::sessionRoot.isInitialized || !::surfaceView.isInitialized) return
@@ -5510,6 +5568,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
.takeIf { it.isFile }
?.let { FileUtils.readString(it)?.trim()?.lowercase() }
?: SessionPrefs.oscMode(this, SessionState.mode == SessionService.MODE_STEAM)
unfoldedColumn?.let { column ->
val shown = if (inputSettingsOpen) View.INVISIBLE else View.VISIBLE
if (column.visibility != shown) { unfoldedPanel?.releaseAll(); unfoldedDeckSurface?.releaseInputs(); column.visibility = shown }
}
val controls = onScreenControls ?: return
fun showPinned() {
controls.setPinnedOnly(true)
@@ -5675,31 +5737,44 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
heldKeys.set(owner, code, down)
}
private fun capturePausedFrame(manual: Boolean = false) {
if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive || bottomOutputActive) return
private fun capturePausedFrame(manual: Boolean = false, onDone: () -> Unit = {}) {
fun skipped(reason: String) {
if (manual) SessionEvents.record("pause.frame_skipped", mapOf("reason" to reason))
onDone()
}
if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive || bottomOutputActive) {
return skipped("state running=${SessionState.running} pip=$pipUi glasses=$glassesOutputActive bottom=$bottomOutputActive")
}
if (SessionState.suspended && pausedFrame != null) return
if ((suspendPolicy == SessionPrefs.SUSPEND_NEVER && !manual && !SessionState.manualPause) || !::surfaceView.isInitialized) return
if (surfaceView.holder.surface?.isValid != true) return
if ((suspendPolicy == SessionPrefs.SUSPEND_NEVER && !manual && !SessionState.manualPause) || !::surfaceView.isInitialized) return skipped("policy")
if (surfaceView.holder.surface?.isValid != true) return skipped("surface invalid")
val width = surfaceView.width
val height = surfaceView.height
if (width <= 0 || height <= 0) return
if (width <= 0 || height <= 0) return skipped("size ${width}x$height")
val scale = minOf(1f, PAUSED_FRAME_MAX_EDGE / maxOf(width, height).toFloat())
val bitmap = try {
android.graphics.Bitmap.createBitmap(
maxOf(1, (width * scale).toInt()), maxOf(1, (height * scale).toInt()), android.graphics.Bitmap.Config.ARGB_8888,
)
} catch (_: OutOfMemoryError) {
return
return skipped("oom")
}
val surfaceAt = IntArray(2).also { surfaceView.getLocationInWindow(it) }
val overlayAt = IntArray(2).also { sessionOverlay.getLocationInWindow(it) }
val left = surfaceAt[0] - overlayAt[0]
val top = surfaceAt[1] - overlayAt[1]
val bounds = android.graphics.Rect(left, top, left + width, top + height)
val requestedAt = SystemClock.elapsedRealtime()
withPictureFrame { done ->
try {
android.view.PixelCopy.request(surfaceView, bitmap, { result ->
done()
onDone()
if (manual) SessionEvents.record("pause.frame_copy", mapOf(
"result" to result, "ms" to SystemClock.elapsedRealtime() - requestedAt,
"zeroCopy" to SessionPrefs.zeroCopy(this, SessionState.mode), "size" to "${width}x$height",
"lit" to (result == android.view.PixelCopy.SUCCESS && bitmapHasPicture(bitmap)),
))
if (result == android.view.PixelCopy.SUCCESS && !isDestroyed) {
pausedFrame = com.droiddeck.launcher.ui.PausedFrame(bitmap.asImageBitmap(), bounds)
pausedFrameWanted = false
@@ -5710,6 +5785,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} catch (_: IllegalArgumentException) {
done()
bitmap.recycle()
skipped("copy rejected")
}
}
}
@@ -5717,12 +5793,35 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun pauseNow() {
if (!SessionState.running || SessionState.suspended) return
pauseAnimated = true
drawerOpen = false
if (!dockedTouchOnly) drawerOpen = false
pausedFrame = null
capturePausedFrame(manual = true)
if (zeroCopyActive()) {
WaylandCompositor.nativeSetZeroCopy(false)
val restore = java.util.concurrent.atomic.AtomicBoolean(false)
val back = { if (restore.compareAndSet(false, true)) WaylandCompositor.nativeSetZeroCopy(true) }
uiHandler.postDelayed({ capturePausedFrame(manual = true, onDone = back) }, ZERO_COPY_SETTLE_MS)
uiHandler.postDelayed({ back() }, ZERO_COPY_RESTORE_MS)
} else {
capturePausedFrame(manual = true)
}
SessionService.pause(this)
}
private fun zeroCopyActive(): Boolean =
CompositorHost.isStarted && !SessionState.hdr && SessionPrefs.zeroCopy(this, SessionState.mode)
private fun bitmapHasPicture(bitmap: android.graphics.Bitmap): Boolean {
val w = bitmap.width
val h = bitmap.height
if (w <= 0 || h <= 0) return false
var lit = 0
for (i in 0 until 64) {
val c = bitmap.getPixel((w * (i % 8 + 1)) / 9, (h * (i / 8 + 1)) / 9)
if (android.graphics.Color.red(c) + android.graphics.Color.green(c) + android.graphics.Color.blue(c) > 24) lit++
}
return lit >= 3
}
private fun requestPausedFrame() {
if (pausedFrame != null) return
pausedFrameWanted = true
@@ -5826,8 +5925,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
reconcileDock(shownOnDisplayId)
settleDualScreenControls()
refreshSecondScreenDisplays()
if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
else openDualScreenControls()
if (secondScreenMode != SecondScreenMode.NONE) {
if (secondScreenPresentation == null) showSecondScreen(secondScreenMode)
if (com.droiddeck.launcher.input.DualScreen.menuReturnsOnStart(openingPanel(), SessionState.bottomMenu, menuShownOnBottom())) pinDockedMenu()
SessionState.bottomMenu = false
} else openDualScreenControls()
startedScreens++
SessionService.setActivityVisible(this, true, sessionActivityDisplayId)
Glasses.rescan()
@@ -5978,7 +6080,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
heldKeys.clear()
heldButtons.clear()
if (!screenOff) {
val menuUp = menuShownOnBottom()
drawerOpen = false
if (menuUp) SessionState.bottomMenu = true
pcKeyboardOpen = false
achievementsOpen = false
}
@@ -6750,6 +6854,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private const val LEAVE_TIMEOUT_MS = 1_500L
private const val TEXT_FIELD_TAP_MS = 1_000L
private const val PAUSED_FRAME_MAX_EDGE = 1920f
private const val ZERO_COPY_SETTLE_MS = 150L
private const val ZERO_COPY_RESTORE_MS = 1200L
private const val BFI_PICTURE_SETTLE_MS = 50L
private const val PAUSED_FRAME_REDRAW_MS = 150L
private const val BOTTOM_RECOVERY_MS = 1_000L
@@ -53,6 +53,13 @@ object AppUiPrefs {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("hide-home-from-recents", hidden).apply()
}
fun pageSwipe(context: Context): Boolean =
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).getBoolean("page-swipe", true)
fun setPageSwipe(context: Context, on: Boolean) {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putBoolean("page-swipe", on).apply()
}
internal fun normalizeScale(percent: Int): Int = percent.takeIf { it in scales } ?: DEFAULT_SCALE
fun scale(context: Context): Int = normalizeScale(
@@ -207,9 +207,11 @@ object DeviceReport {
k("refresh_rate_mode", runCatching { Settings.Secure.getString(context.contentResolver, "refresh_rate_mode") }.getOrNull() ?: "not set")
val panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(context)
for ((label, mode) in listOf("Resolution (Steam)" to SessionService.MODE_STEAM, "Resolution (Desktop)" to SessionService.MODE_DESKTOP)) {
val choice = SessionPrefs.resolutionChoice(context, mode, panelSize)
val size = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panelSize, choice)
k(label, "$choice (${size.first}x${size.second})")
for ((suffix, portrait) in listOf("landscape" to false, "portrait" to true)) {
val choice = SessionPrefs.resolutionChoice(context, mode, panelSize, portrait)
val size = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panelSize, choice, portrait)
k("$label $suffix", "$choice (${size.first}x${size.second})")
}
}
k("Foldable", context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle"))
@@ -0,0 +1,182 @@
package com.droiddeck.launcher.input
import android.graphics.Rect
import android.util.DisplayMetrics
import kotlin.math.max
import kotlin.math.min
internal class ControllerOverlayGeometry(
width: Int, height: Int, private val safe: Rect, metrics: DisplayMetrics, scale: Float,
) {
private val w = width.toFloat()
private val h = height.toFloat()
private val density = metrics.density
private val dpi = metrics.ydpi.takeIf { it in metrics.densityDpi * .6f..metrics.densityDpi * 1.6f }
?: metrics.densityDpi.toFloat()
private val fit = minOf(
min(w / 1600f, h / 900f) * min(1f, 80f / max(h / dpi * 25.4f, 1f)),
(w - safe.left - safe.right).coerceAtLeast(1f) / 1200f,
(h - safe.top - safe.bottom).coerceAtLeast(1f) / 900f,
)
private val unit = fit * min(scale, 1f)
private val size = fit * scale
private fun anchor(value: Float, reference: Float, extent: Float, start: Int, end: Int): Float {
val low = start + value * unit
val high = extent - end - (reference - value) * unit
return when {
value < reference / 3f -> low
value > reference * 2f / 3f -> high
else -> (extent / 2f + (value - reference / 2f) * unit).coerceIn(low, max(low, high))
}
}
private fun x(ref: Float) = anchor(ref, 1600f, w, safe.left, safe.right)
private fun y(ref: Float) = max(safe.top + ref * unit, h - safe.bottom - (900f - ref) * unit)
fun place(elements: List<InputSurfaceElement>, kit: PadKit, rearButtons: Boolean, trackpads: Boolean): List<InputSurfaceElement> {
if (!kit.steam) return placeStandardPad(elements, kit)
val leftEdge = safe.left + 52f * density
val middle = (w + safe.left - safe.right) / 2f
val keyboard = Box(max(x(136f), leftEdge + 46f * size), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } }
val row = fitRow(listOfNotNull(keyboard,
Box(max(x(370f), leftEdge + 66f * size), y(852f), 66f, 30f),
Box(middle - 140f * unit, y(850f), 46f, 26f),
Box(middle + 140f * unit, y(850f), 46f, 26f),
Box(x(1230f), y(852f), 66f, 30f)), leftEdge)
val (guide, select, start, qam) = row.takeLast(4)
val positions = shoulders() + face(1375f, 345f, 96f) + mapOf(
InputControl.UP to Box(x(220f), y(345f) - 102.5f * size, 55.5f, 47.5f),
InputControl.RIGHT to Box(x(220f) + 102.5f * size, y(345f), 47.5f, 55.5f),
InputControl.DOWN to Box(x(220f), y(345f) + 102.5f * size, 55.5f, 47.5f),
InputControl.LEFT to Box(x(220f) - 102.5f * size, y(345f), 47.5f, 55.5f),
InputControl.LS to Box(x(290f), y(640f), 96f),
InputControl.RS to Box(x(1310f), y(640f), 96f),
InputControl.SELECT to select,
InputControl.START to start,
InputControl.GUIDE to guide,
InputControl.QAM to qam,
)
val rear = mapOf(
InputControl.L4 to Box(x(30f), y(470f), 30f, 58f),
InputControl.L5 to Box(x(30f), y(590f), 30f, 58f),
InputControl.R4 to Box(x(1570f), y(470f), 30f, 58f),
InputControl.R5 to Box(x(1570f), y(590f), 30f, 58f),
)
val pads = mapOf(
InputControl.LEFT_PAD to Box(x(470f), y(360f), 88f),
InputControl.RIGHT_PAD to Box(x(1130f), y(360f), 88f),
)
val optional = rear.filterKeys { rearButtons } + pads.filterKeys { trackpads }
val placed = elements.mapNotNull { element ->
when {
element.id == KEYBOARD -> row.first().place(element)
element.id != "legacy:${element.control.id}" -> element
element.control in rear || element.control in pads -> optional[element.control]?.place(element)
else -> positions[element.control]?.place(element) ?: element
}
}
val chosen = placed.filter { it.id == "legacy:${it.control.id}" }.map { it.control }
return placed + optional.mapNotNull { (control, box) ->
if (chosen.any { if (control in rear) it in rear else it in pads }) null else box.place(InputSurfaceElement(control,
0f, 0f, 0f, 0f, floating = false, buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad))
}
}
private fun placeStandardPad(elements: List<InputSurfaceElement>, kit: PadKit): List<InputSurfaceElement> {
val leftEdge = safe.left + 52f * density
val middle = (w + safe.left - safe.right) / 2f
val keyboard = Box(max(x(136f), leftEdge + 46f * size), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } }
val controls = if (kit.playStation) listOf(
InputControl.QAM to Box(x(220f), y(848f), 46f),
InputControl.SELECT to Box(middle - 160f * unit, y(850f), 50f, 30f),
InputControl.GUIDE to Box(middle, y(850f), 46f),
InputControl.START to Box(middle + 160f * unit, y(850f), 50f, 30f),
) else listOf(
InputControl.QAM to Box(x(220f), y(848f), 46f),
InputControl.SELECT to Box(middle - 110f * unit, y(850f), 38f),
InputControl.GUIDE to Box(middle, y(850f), 46f),
InputControl.START to Box(middle + 110f * unit, y(850f), 38f),
)
val row = fitRow(listOfNotNull(keyboard) + controls.map { it.second }, leftEdge)
val positions = controls.map { it.first }.zip(row.takeLast(controls.size)).toMap() + shoulders() +
if (kit.playStation) {
face(1350f, 395f, 96f) + dpad(250f, 395f, 125f, kit.dpad) + mapOf(
InputControl.LS to Box(x(565f), y(690f), 100f),
InputControl.RS to Box(x(1035f), y(690f), 100f),
InputControl.L3 to Box(x(565f) - 135f * size, y(690f) - 100f * size, 42f),
InputControl.R3 to Box(x(1035f) + 135f * size, y(690f) - 100f * size, 42f),
)
} else {
face(1375f, 400f, 94f) + dpad(470f, 675f, 118f, kit.dpad) + mapOf(
InputControl.LS to Box(x(235f), y(400f), 104f),
InputControl.RS to Box(x(1130f), y(690f), 104f),
InputControl.L3 to Box(x(235f) + 150f * size, y(400f) - 110f * size, 42f),
InputControl.R3 to Box(x(1130f) + 160f * size, y(690f) + 100f * size, 42f),
)
}
return elements.map { element ->
when (element.id) {
KEYBOARD -> row.first().place(element)
"legacy:${element.control.id}" -> positions[element.control]?.place(element) ?: element
else -> element
}
}
}
private fun shoulders() = mapOf(
InputControl.LT to Box(x(120f), y(96f), 80f, 34f),
InputControl.LB to Box(x(310f), y(96f), 80f, 34f),
InputControl.RB to Box(x(1290f), y(96f), 80f, 34f),
InputControl.RT to Box(x(1480f), y(96f), 80f, 34f),
)
private fun face(cx: Float, cy: Float, offset: Float) = mapOf(
InputControl.Y to Box(x(cx), y(cy) - offset * size, 58f),
InputControl.X to Box(x(cx) - offset * size, y(cy), 58f),
InputControl.B to Box(x(cx) + offset * size, y(cy), 58f),
InputControl.A to Box(x(cx), y(cy) + offset * size, 58f),
)
private fun dpad(cx: Float, cy: Float, radius: Float, style: DpadStyle): Map<InputControl, Box> {
val inner = radius * if (style == DpadStyle.DISC) .25f else .14f
val depth = (radius - inner) / 2f
val offset = (radius - depth) * size
val side = radius * .25f
return mapOf(
InputControl.UP to Box(x(cx), y(cy) - offset, side, depth),
InputControl.RIGHT to Box(x(cx) + offset, y(cy), depth, side),
InputControl.DOWN to Box(x(cx), y(cy) + offset, side, depth),
InputControl.LEFT to Box(x(cx) - offset, y(cy), depth, side),
)
}
private fun fitRow(row: List<Box>, start: Float): List<Box> {
val end = w - safe.right
val gap = ((end - start - row.fold(0f) { sum, box -> sum + box.width }) / (row.size - 1)).coerceIn(0f, 8f * density)
var edge = start - gap
val pushed = row.map { box -> box.at(max(box.cx, edge + gap + box.width / 2f)).also { edge = it.cx + it.width / 2f } }
edge = end + gap
return pushed.asReversed().map { box -> box.at(min(box.cx, edge - gap - box.width / 2f)).also { edge = it.cx - it.width / 2f } }.asReversed()
}
private inner class Box(val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw) {
val width get() = max(hw * 2f * size, w * .03f)
fun at(cx: Float) = Box(cx, cy, hw, hh)
fun place(element: InputSurfaceElement): InputSurfaceElement {
val height = max(hh * 2f * size, h * .03f)
return element.copy(
x = (cx - width / 2f).coerceIn(safe.left.toFloat(), max(safe.left.toFloat(), w - safe.right - width)) / w,
y = (cy - height / 2f).coerceIn(safe.top.toFloat(), max(safe.top.toFloat(), h - safe.bottom - height)) / h,
width = width / w, height = height / h,
).bounded()
}
}
private companion object {
const val KEYBOARD = "builtin:keyboard"
}
}
@@ -0,0 +1,127 @@
package com.droiddeck.launcher.input
import android.graphics.Rect
import com.droiddeck.launcher.input.GamepadGeometry.Box
import kotlin.math.min
internal class ControllerPortraitGeometry(
private val width: Float,
private val height: Float,
private val safe: Rect,
private val density: Float,
) {
fun place(
elements: List<InputSurfaceElement>, kit: PadKit, docked: Boolean, scale: Float,
rearButtons: Boolean, trackpads: Boolean,
): List<InputSurfaceElement> {
val w = width - safe.left - safe.right
val h = height - safe.top - safe.bottom
if (w <= 0 || h <= 0) return elements
val presented = elements.toMutableList()
val buttons = mutableMapOf<String, Box>()
val rear = presented.filter { it.control in REAR && isStock(it) }
val pads = presented.filter { it.control.isTrackpad && isStock(it) }
if (!docked && kit.steam) {
if (!rearButtons) presented.removeAll(rear) else if (rear.isEmpty()) REAR.forEach { addOptional(presented, it) }
if (!trackpads) presented.removeAll(pads) else if (pads.isEmpty()) {
addOptional(presented, InputControl.LEFT_PAD)
addOptional(presented, InputControl.RIGHT_PAD)
}
}
fun put(control: InputControl, box: Box) { buttons["legacy:${control.id}"] = box }
val reserve = if (docked) 0f else min(60f * density, h * .15f)
val panel = if (docked) h else min(minOf(h * .60f, w * 1.15f, PANEL_DP * density) * scale, h - reserve)
val top = height - safe.bottom - reserve - panel
val unit = min(density, min(w / 275f, panel / 300f))
val pad = 8f * unit
val gap = 8f * unit
val buttonHeight = 44f * unit
val shoulders = if (docked) listOf(InputControl.LT, InputControl.LB, InputControl.SELECT, InputControl.START, InputControl.RB, InputControl.RT)
else listOf(InputControl.LT, InputControl.LB, InputControl.RB, InputControl.RT)
fun row(controls: List<InputControl>, y: Float, rowHeight: Float, spacing: Float) {
val cell = (w - 2f * pad - (controls.size - 1) * spacing) / controls.size
controls.forEachIndexed { index, control ->
put(control, Box(safe.left + pad + cell / 2f + index * (cell + spacing), y, cell, rowHeight))
}
}
row(shoulders, top + pad + buttonHeight / 2f, buttonHeight, 4f * unit)
var bodyTop = top + pad + buttonHeight + gap
if (presented.any { it.control in REAR && isStock(it) }) {
val rearHeight = min(56f * unit, (panel - bodyTop + top) * .12f).coerceAtLeast(buttonHeight)
row(REAR, bodyTop + rearHeight / 2f, rearHeight, gap)
bodyTop += rearHeight + gap
}
val floor = height - safe.bottom - reserve - pad
val bodyHeight = floor - bodyTop - gap
if (bodyHeight <= 0f) return elements
val hasLeftPad = presented.any { it.control == InputControl.LEFT_PAD && isStock(it) }
val hasRightPad = presented.any { it.control == InputControl.RIGHT_PAD && isStock(it) }
val hasLeftStick = presented.any { it.control == InputControl.LS && isStock(it) }
val hasRightStick = presented.any { it.control == InputControl.RS && isStock(it) }
val four = hasLeftPad && hasLeftStick || hasRightPad && hasRightStick
val main = min(w * .46f, bodyHeight * .53f)
val second = min(w * .42f, bodyHeight - main)
val mainY = floor - main / 2f
val secondY = bodyTop + second / 2f
val left = safe.left + w * .25f
val right = safe.left + w * .75f
if (four) {
val col = (w - 2f * pad - 3f * gap) / 4f
val stick = min(col, main)
put(InputControl.LEFT_PAD, Box(safe.left + pad + col * .5f, mainY, col, main))
put(InputControl.LS, Box(safe.left + pad + col * 1.5f + gap, mainY, stick, stick))
put(InputControl.RS, Box(safe.left + w - pad - col * 1.5f - gap, mainY, stick, stick))
put(InputControl.RIGHT_PAD, Box(safe.left + w - pad - col * .5f, mainY, col, main))
} else {
put(if (hasLeftPad) InputControl.LEFT_PAD else InputControl.LS, Box(left, mainY, main, main))
put(if (hasRightPad) InputControl.RIGHT_PAD else InputControl.RS, Box(right, mainY, main, main))
}
val radius = second / 2f
val armWidth = radius * if (kit.dpad == DpadStyle.CROSS) .37f else .25f
val inner = if (kit.dpad == DpadStyle.ARROWS) radius * .14f else armWidth
val depth = radius - inner
val distance = (radius + inner) / 2f
put(InputControl.UP, Box(left, secondY - distance, armWidth * 2f, depth))
put(InputControl.RIGHT, Box(left + distance, secondY, depth, armWidth * 2f))
put(InputControl.DOWN, Box(left, secondY + distance, armWidth * 2f, depth))
put(InputControl.LEFT, Box(left - distance, secondY, depth, armWidth * 2f))
val face = second * .34f
val spread = second * .30f
put(InputControl.Y, Box(right, secondY - spread, face, face))
put(InputControl.X, Box(right - spread, secondY, face, face))
put(InputControl.B, Box(right + spread, secondY, face, face))
put(InputControl.A, Box(right, secondY + spread, face, face))
if (!docked) {
val ids = listOf(KEYBOARD, "legacy:guide", "legacy:select", "legacy:start", "legacy:qam")
.filter { id -> presented.any { it.id == id } }
val inset = min(52f * density, w * .17f)
val rowWidth = (w - inset - pad - gap * (ids.size - 1)) / ids.size.coerceAtLeast(1)
val rowHeight = min(reserve * .8f, 44f * unit)
ids.forEachIndexed { i, id ->
val center = safe.left + inset + rowWidth / 2f + i * (rowWidth + gap)
buttons[id] = Box(center, height - safe.bottom - reserve / 2f, rowWidth, rowHeight)
}
}
return presented.map { element ->
val box = buttons[element.id]
if (box == null) element else element.copy(
x = box.left / width, y = box.top / height, width = box.width / width, height = box.height / height,
).bounded()
}
}
private fun isStock(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}"
private fun addOptional(elements: MutableList<InputSurfaceElement>, control: InputControl) {
if (elements.none { it.control == control && isStock(it) }) {
elements += InputSurfaceElement(control, 0f, 0f, 0f, 0f, floating = false,
buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad)
}
}
private companion object {
const val KEYBOARD = "builtin:keyboard"
const val PANEL_DP = 504f
val REAR = listOf(InputControl.L4, InputControl.L5, InputControl.R5, InputControl.R4)
}
}
@@ -23,6 +23,14 @@ object DualScreen {
@Volatile private var takenDisplays: Set<Int> = emptySet()
private val main by lazy { android.os.Handler(android.os.Looper.getMainLooper()) }
fun menuOwnsController(open: Boolean, docked: Boolean, optIn: Boolean): Boolean = open && (!docked || optIn)
fun menuReturnsOnStart(selected: SecondScreenMode, menuWasShown: Boolean, menuUp: Boolean): Boolean =
!menuUp && (selected == SecondScreenMode.MENU || menuWasShown)
fun menuIdleOnBottom(open: Boolean, docked: Boolean, pinned: Boolean, optIn: Boolean): Boolean =
docked && (open || pinned) && !menuOwnsController(open, docked, optIn)
fun yieldsBottom(model: String): Boolean = model.trim().lowercase().let { m -> knownModels.any(m::startsWith) }
fun taken(displayId: Int): Boolean = displayId in takenDisplays
@@ -27,8 +27,9 @@ internal class FloatingSteamOverlay(width: Int, height: Int, safe: Rect, density
val lowered = if (lowerShortcuts) lower(visible) else visible
if (rearButtons != true && trackpads != true) return lowered
val placed = lowered.toMutableList()
val chosen = lowered.filter(::isStock).map { it.control }
fun add(control: InputControl, x: Float, y: List<Float>, widthDp: Int, heightDp: Int, shape: InputButtonShape) {
if (placed.any { it.id == "legacy:${control.id}" }) return
if (chosen.any { if (control in rear) it in rear else it.isTrackpad }) return
val element = InputSurfaceElement(control, 0f, 0f, (widthDp * dp / w).coerceAtLeast(.03f),
(heightDp * dp / h).coerceAtLeast(.03f), floating = false, buttonShape = shape, showLabel = !control.isTrackpad)
findSpace(element, x, y, placed)?.let(placed::add)
@@ -324,15 +324,27 @@ object InputLibraries {
layout.copy(screen = screen)
})
private fun encodeElements(list: List<InputSurfaceElement>) = JSONArray().also { elements ->
for (e in list) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
.put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
}
private fun decodeElements(array: JSONArray) = array.objects(64).map { e ->
InputSurfaceElement(requireNotNull(InputControl.fromId(e.getString("control"))), e.getDouble("x").toFloat(),
e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(),
e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"),
e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""),
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false))
}
internal fun encode(library: InputLibrary): String {
val layouts = JSONArray()
for (layout in library.layouts) {
val elements = JSONArray()
for (e in layout.elements) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
.put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements)
val encoded = JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", encodeElements(layout.elements))
if (layout.rotated.isNotEmpty()) encoded.put("rotated", encodeElements(layout.rotated)).put("rotatedAspect", layout.rotatedAspect.toDouble()).put("rotatedScale", layout.rotatedScale.toDouble())
layouts.put(encoded
.put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble())
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL))
}
@@ -371,13 +383,7 @@ object InputLibraries {
require(version in 2..VERSION || restore)
val generated = mutableSetOf<String>()
val layouts = doc.getJSONArray("layouts").objects(256).map { layout ->
val stored = layout.getJSONArray("elements").objects(64).map { e ->
InputSurfaceElement(requireNotNull(InputControl.fromId(e.getString("control"))), e.getDouble("x").toFloat(),
e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(),
e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"),
e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""),
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false))
}
val stored = decodeElements(layout.getJSONArray("elements"))
val id = layout.getString("id")
val origin = layout.optionalString("origin")
val followsGamepad = restore && !layout.optBoolean("kitless") &&
@@ -388,7 +394,8 @@ object InputLibraries {
InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100),
layout.optJSONArray("hidden")?.let { hidden -> (0 until hidden.length()).map { InputCommand.valueOf(hidden.getString(it)) }.toSet() }.orEmpty()),
InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), origin,
layout.optDouble("scale", 1.0).toFloat())
layout.optDouble("scale", 1.0).toFloat(), layout.optJSONArray("rotated")?.let(::decodeElements).orEmpty(),
layout.optDouble("rotatedAspect", 0.0).toFloat(), layout.optDouble("rotatedScale", layout.optDouble("scale", 1.0)).toFloat())
}
val bindings = doc.getJSONArray("bindings").objects(512).map { b ->
val controls = b.getJSONObject("controls").actions(28).mapKeys { requireNotNull(InputControl.fromId(it.key)) }
@@ -22,8 +22,12 @@ data class SavedInputLayout(
val aspect: Float = 0f,
val origin: String? = null,
val scale: Float = 1f,
val rotated: List<InputSurfaceElement> = emptyList(),
val rotatedAspect: Float = 0f,
val rotatedScale: Float = 1f,
) {
val editable get() = template == InputLayoutTemplate.CUSTOM
val overlay get() = (origin ?: id).let { it == InputLibraries.OVERLAY || it.startsWith("migrated.layout.") }
val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } }
fun withQuickButton(button: InputCommand, shown: Boolean) =
copy(style = style.copy(hidden = if (shown) style.hidden - button else style.hidden + button))
@@ -249,6 +253,8 @@ data class InputLibrary(
for (layout in layouts) {
require(layout.style.opacity in 1..100 && layout.style.hidden.all { it in QUICK_BUTTONS })
require(layout.aspect == 0f || layout.aspect.isFinite() && layout.aspect in .05f..20f)
require(layout.rotated.isEmpty() || layout.rotatedAspect.isFinite() && layout.rotatedAspect in .05f..20f && layout.rotatedScale.isFinite() && layout.rotatedScale in .5f..2f)
require(layout.rotated.size <= 64 && layout.rotated.all { r -> listOf(r.x, r.y, r.width, r.height).all { it.isFinite() } })
require(layout.scale.isFinite() && layout.scale in .5f..2f)
inputName(layout.name); require(layout.elements.size <= 64); unique(layout.elements.map { it.id })
for (e in layout.elements) {
@@ -3,6 +3,8 @@ package com.droiddeck.launcher.input
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
import kotlin.math.max
import kotlin.math.min
enum class InputElementKind(val control: InputControl) {
BUTTON(InputControl.A), STICK(InputControl.LS), TRACKPAD(InputControl.LEFT_PAD),
@@ -63,6 +65,27 @@ internal fun List<InputSurfaceElement>.scaled(factor: Float): List<InputSurfaceE
width = w, height = h).bounded()
}
internal val DPAD = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
internal val InputSurfaceElement.dpadPiece get() = id == "legacy:${control.id}" && control in DPAD
internal fun List<InputSurfaceElement>.groupOf(e: InputSurfaceElement) = if (e.dpadPiece) filter { it.dpadPiece } else listOf(e)
internal fun List<InputSurfaceElement>.frame(): InputSurfaceElement {
val left = minOf { it.x }; val top = minOf { it.y }
return first().copy(x = left, y = top, width = maxOf { it.x + it.width } - left, height = maxOf { it.y + it.height } - top)
}
internal fun List<InputSurfaceElement>.resizedAroundCentre(factor: Float): List<InputSurfaceElement> {
if (isEmpty()) return this
val f = frame()
val k = factor.coerceIn(.03f / minOf { min(it.width, it.height) }, 1f / max(f.width, f.height))
val w = f.width * k; val h = f.height * k
val left = (f.x + f.width / 2 - w / 2).coerceIn(0f, 1f - w)
val top = (f.y + f.height / 2 - h / 2).coerceIn(0f, 1f - h)
return map { it.copy(x = left + (it.x - f.x) * k, y = top + (it.y - f.y) * k, width = it.width * k, height = it.height * k).bounded() }
}
internal fun List<InputSurfaceElement>.withPositionsOf(defaults: List<InputSurfaceElement>): List<InputSurfaceElement> {
val byId = defaults.associateBy { it.id }
return map { e -> byId[e.id]?.let { d -> e.copy(x = d.x, y = d.y, width = d.width, height = d.height).bounded() } ?: e }
@@ -197,19 +197,8 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
fun regenerate(stored: List<InputSurfaceElement>): List<InputSurfaceElement> = withGeometry(stored, elements())
fun rescale(stored: List<InputSurfaceElement>, from: LegacyGamepadLayout): List<InputSurfaceElement> {
val before = from.elements().associateBy { it.id }
val after = elements().associateBy { it.id }
return stored.map { e ->
val b = before[e.id] ?: return@map e
val a = after[e.id] ?: return@map e
val w = (a.width * e.width / b.width).coerceIn(.03f, 1f)
val h = (a.height * e.height / b.height).coerceIn(.03f, 1f)
val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2)
val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2)
e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded()
}
}
fun rescale(stored: List<InputSurfaceElement>, from: LegacyGamepadLayout): List<InputSurfaceElement> =
rescaleBetween(stored, from.elements(), elements())
fun buttonsOnly(stored: List<InputSurfaceElement>): List<InputSurfaceElement> {
val inset = dp(BUTTONS_ONLY_INSET_DP)
@@ -345,7 +334,6 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
const val STICK_REACH = 1.25f
const val LEGACY_DPAD_RADIUS_DP = 26f
const val LEGACY_DPAD_OFFSET_DP = 52f
val DPAD = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
const val KEYBOARD_ID = "builtin:keyboard"
const val KEYBOARD_RADIUS_DP = 18f
const val KEYBOARD_X_DP = 90f
@@ -360,3 +348,22 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4)
}
}
internal fun rescaleBetween(stored: List<InputSurfaceElement>, from: List<InputSurfaceElement>, to: List<InputSurfaceElement>,
sizeFrom: List<InputSurfaceElement> = from, sizeTo: List<InputSurfaceElement> = to): List<InputSurfaceElement> {
val before = from.associateBy { it.id }
val after = to.associateBy { it.id }
val smaller = sizeFrom.associateBy { it.id }
val larger = sizeTo.associateBy { it.id }
return stored.map { e ->
val b = before[e.id] ?: return@map e
val a = after[e.id] ?: return@map e
val sb = smaller[e.id] ?: b
val sa = larger[e.id] ?: a
val w = (sa.width * e.width / sb.width).coerceIn(.03f, 1f)
val h = (sa.height * e.height / sb.height).coerceIn(.03f, 1f)
val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2)
val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2)
e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded()
}
}
@@ -14,9 +14,6 @@ import android.view.View
import android.view.WindowInsets
import android.widget.FrameLayout
import com.droiddeck.launcher.ui.InputSurfaceView
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) {
private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null)
@@ -75,15 +72,15 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
render()
}
private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean)
private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean,
val kit: PadKit?, val optional: Pair<Boolean?, Boolean?>)
private fun placed(): List<InputSurfaceElement> {
val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly)
val optional = OnScreenLayout.optionalControls(context)
val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly, PadKit.forOverlay(context, layout), optional)
return placements.getOrPut(key) {
val steam = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad
OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock,
rearButtons = SessionPrefs.oscRearButtons(context).takeIf { steam },
trackpads = SessionPrefs.oscTrackpads(context).takeIf { steam })
rearButtons = optional.first, trackpads = optional.second)
}
}
@@ -100,9 +97,9 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
private fun refreshAppearance() {
val style = layout?.style ?: InputSurfaceStyle()
val deck = dock == null && OnScreenLayout.usesSteamDeckButtons(context, layout)
surface.updateStyle(style, steamDeckButtons = deck)
quickToggle.tint = style.tint.takeUnless { deck }
val artwork = PadKit.forOverlay(context, layout)
surface.updateStyle(style, artwork)
quickToggle.tint = style.tint.takeUnless { artwork != null }
quickToggle.alpha = style.opacity / 100f
quickToggle.invalidate()
}
@@ -136,7 +133,7 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
params.bottomMargin = bottom
quickToggle.layoutParams = params
}
val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
val fresh = OnScreenLayout.safeInsets(insets, dock != null)
if (fresh != safe) {
safe.set(fresh)
render()
@@ -3,17 +3,16 @@ package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
object OnScreenLayout {
internal fun usesSteamDeckButtons(context: Context, layout: SavedInputLayout?) =
layout?.id == InputLibraries.OVERLAY && SessionPrefs.steamController(context) == SessionPrefs.CONTROLLER_DECK
internal fun supportsFloatingSteamControls(controller: String, layout: SavedInputLayout?) =
layout?.id == InputLibraries.OVERLAY &&
layout?.overlay == true &&
(controller == SessionPrefs.CONTROLLER_DECK || controller == SessionPrefs.CONTROLLER_STEAM)
data class Dock(val portrait: Boolean, val grips: Boolean, val left: InputControl = InputControl.LS, val right: InputControl = InputControl.RS) {
@@ -31,41 +30,96 @@ object OnScreenLayout {
private const val TOLERANCE = .01f
private const val KEYBOARD_ID = "builtin:keyboard"
private val REAR = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5)
private val BAR = setOf(InputControl.GUIDE, InputControl.QAM)
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect,
fun elements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect,
buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null,
trackpads: Boolean? = null): List<InputSurfaceElement> {
val stored = layout?.elements ?: return emptyList()
if (width <= 0 || height <= 0) return stored
if (saved == null) return emptyList()
if (width <= 0 || height <= 0) return saved.elements
val layout = oriented(saved, dock?.portrait ?: (height > width))
val stored = layout.elements
val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale)
val (reference, generated) = reference(context, layout, width, height)
val (reference, matched) = reference(context, layout, width, height)
if (buttonsOnly && dock == null) return generator.buttonsOnly(stored) + fit(stored.filter { it.alwaysShown }, reference.first, reference.second, width, height, safe)
if (dock?.portrait == true && !dock.grips && !matched && layout.aspect > 0f && layout.aspect < 1f && stored.any(::isGamepad))
return cluster(stored.filterNot { it.alwaysShown || isGamepad(it) && (it.id == KEYBOARD_ID || it.control in BAR) }, layout.aspect, width, height, safe)
val generated = matched || PadKit.forOverlay(context, layout) != null && stored.any(::isGamepad) &&
(dock != null || height > width && layout.aspect >= 1f || height <= width && layout.aspect > 0f && layout.aspect < 1f)
val gamepad = if (generated) stored.filter(::isGamepad) else emptyList()
val others = fit(stored.filterNot { generated && isGamepad(it) || dock != null && it.alwaysShown }, reference.first, reference.second, width, height, safe)
val placed = when {
val regenerated = when {
gamepad.isEmpty() -> emptyList()
dock != null -> generator.dock(gamepad, dock.portrait, dock.grips, dock.left, dock.right)
else -> generator.regenerate(gamepad)
}
val placed = regenerated + gamepad.filter { g -> dock == null && optional(g) && regenerated.none { it.id == g.id } }
val byId = (placed + others).associateBy { it.id }
val ordered = stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } }
if (dock != null || !supportsFloatingSteamControls(SessionPrefs.steamController(context), layout)) return ordered
if (generated && width >= height && usesSteamDeckButtons(context, layout) &&
val kit = PadKit.forOverlay(context, layout) ?: return ordered
if (generated &&
ControllerPrefs.layout(context, reference.first.toInt(), reference.second.toInt()).isEmpty() &&
ControllerPrefs.layout(context, width, height).isEmpty()) {
return SteamDeckOverlayGeometry(width, height, safe, context.resources.displayMetrics, layout.scale)
.place(ordered, rearButtons == true, trackpads == true)
if (dock != null || height > width) {
return ControllerPortraitGeometry(width.toFloat(), height.toFloat(), safe, context.resources.displayMetrics.density)
.place(ordered, kit, dock != null, layout.scale, rearButtons == true, trackpads == true)
}
return ControllerOverlayGeometry(width, height, safe, context.resources.displayMetrics, layout.scale)
.place(ordered, kit, rearButtons == true, trackpads == true)
}
if (dock != null || !kit.steam) return ordered
return FloatingSteamOverlay(width, height, safe, context.resources.displayMetrics.density)
.place(ordered, lowerShortcuts = generated, rearButtons = rearButtons, trackpads = trackpads)
}
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List<InputSurfaceElement> =
elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, Rect())
fun oriented(layout: SavedInputLayout, width: Int, height: Int): SavedInputLayout = oriented(layout, height > width)
private fun oriented(layout: SavedInputLayout, portrait: Boolean): SavedInputLayout {
if (layout.rotated.isEmpty() || layout.aspect <= 0f || (layout.aspect < 1f) == portrait || (layout.rotatedAspect < 1f) != portrait) return layout
val rotated = layout.rotated.associateBy { it.id }
return layout.copy(elements = layout.elements.map { e -> rotated[e.id]?.let { e.copy(x = it.x, y = it.y, width = it.width, height = it.height) } ?: e } +
layout.rotated.filter { r -> optional(r) && layout.elements.none { it.id == r.id } },
aspect = layout.rotatedAspect, scale = layout.rotatedScale, rotated = emptyList(), rotatedAspect = 0f, rotatedScale = 1f)
}
fun withFrame(context: Context, saved: SavedInputLayout, elements: List<InputSurfaceElement>, aspect: Float, scale: Float = saved.scale): SavedInputLayout {
val (_, metrics) = InputLibraries.primaryDisplay(context)
val generated = generatedSize(context, saved, metrics.widthPixels, metrics.heightPixels) != null
val portraitMain = saved.aspect > 0f && saved.aspect < 1f
if (aspect <= 0f || aspect >= 1f || portraitMain && !generated) {
val rotated = if (aspect >= 1f && portraitMain && !generated) Triple(saved.elements, saved.aspect, saved.scale) else Triple(saved.rotated, saved.rotatedAspect, saved.rotatedScale)
return saved.copy(elements = elements, aspect = aspect, scale = scale, rotated = rotated.first,
rotatedAspect = if (rotated.first.isEmpty()) 0f else rotated.second, rotatedScale = if (rotated.first.isEmpty()) 1f else rotated.third)
}
val main = if (portraitMain) 1f / saved.aspect else saved.aspect.takeIf { it > 0f } ?: (1f / aspect)
val ids = elements.associateBy { it.id }
val kept = saved.elements.mapNotNull { e -> ids[e.id]?.copy(x = e.x, y = e.y, width = e.width, height = e.height) }
val added = fit(elements.filter { d -> !optional(d) && saved.elements.none { it.id == d.id } }, aspect, 1f, (main * 1000).roundToInt().coerceAtLeast(1), 1000, Rect())
return saved.copy(elements = kept + added, aspect = main, rotated = elements, rotatedAspect = aspect, rotatedScale = scale)
}
fun optionalControls(context: Context): Pair<Boolean?, Boolean?> {
val steam = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad
return SessionPrefs.oscRearButtons(context).takeIf { steam } to SessionPrefs.oscTrackpads(context).takeIf { steam }
}
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false, safe: Rect = Rect()): List<InputSurfaceElement> {
val (rear, pads) = optionalControls(context)
return elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, safe,
rearButtons = rear, trackpads = pads)
}
fun editorFrame(layout: SavedInputLayout, displayed: List<InputSurfaceElement>): List<InputSurfaceElement> {
val byId = displayed.associateBy { it.id }
return layout.elements.map { byId[it.id] ?: it }
return layout.elements.map { byId[it.id] ?: it } + displayed.filter { d ->
optional(d) && layout.elements.none { it.id == d.id }
}
}
fun safeInsets(insets: android.view.WindowInsets?, docked: Boolean): Rect {
val cutout = if (android.os.Build.VERSION.SDK_INT >= 28) insets?.displayCutout else null
return Rect(cutout?.safeInsetLeft ?: 0, if (docked) 0 else cutout?.safeInsetTop ?: 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
}
fun fit(elements: List<InputSurfaceElement>, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
@@ -81,6 +135,23 @@ object OnScreenLayout {
}
}
private fun cluster(elements: List<InputSurfaceElement>, aspect: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
if (elements.isEmpty()) return elements
val left = elements.minOf { it.x } * aspect
val top = elements.minOf { it.y }
val spanX = (elements.maxOf { it.x + it.width } * aspect - left).coerceAtLeast(.0001f)
val spanY = (elements.maxOf { it.y + it.height } - top).coerceAtLeast(.0001f)
val w = (width - safe.left - safe.right).toFloat().coerceAtLeast(1f)
val h = (height - safe.top - safe.bottom).toFloat().coerceAtLeast(1f)
val scale = minOf(w / aspect, w / spanX, h / spanY)
val originX = safe.left + (w - spanX * scale) / 2f - left * scale
val originY = safe.top + (h - spanY * scale) / 2f - top * scale
return elements.map { e ->
e.copy(x = (originX + e.x * aspect * scale) / width, y = (originY + e.y * scale) / height,
width = e.width * aspect * scale / width, height = e.height * scale / height)
}
}
private fun anchor(start: Float, size: Float, reference: Float, actual: Float, scale: Float): Float {
val centre = start + size / 2f
val scaled = size * reference * scale
@@ -91,6 +162,8 @@ object OnScreenLayout {
}
}
private fun optional(e: InputSurfaceElement) = e.id == "legacy:${e.control.id}" && (e.control.isTrackpad || e.control in REAR)
private fun isGamepad(e: InputSurfaceElement) = e.id.startsWith("legacy:") || e.id == KEYBOARD_ID
fun generatedSize(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair<Int, Int>? =
@@ -104,7 +177,7 @@ object OnScreenLayout {
if (gamepad.any { it.id.startsWith("legacy:") }) {
val named = layout.id.removePrefix("migrated.layout.").takeIf { it != layout.id }?.split('x')?.mapNotNull { it.toIntOrNull() }
?.takeIf { it.size == 2 && it.all { size -> size > 0 } }?.let { it[0] to it[1] }
val aspectSize = layout.aspect.takeIf { layout.id == InputLibraries.OVERLAY && it > 0f }
val aspectSize = layout.aspect.takeIf { layout.overlay && it > 0f }
?.let { (it * height).roundToInt().coerceAtLeast(1) to height }
for ((w, h) in listOfNotNull(named, width to height, aspectSize, long to short, short to long).distinct()) {
val generator = LegacyGamepadLayout(display, w, h, scale = layout.scale)
@@ -0,0 +1,54 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
internal enum class FaceGlyphs { MONO_LETTERS, COLOR_LETTERS, COLOR_SYMBOLS, MONO_SYMBOLS }
internal enum class DpadStyle { CROSS, DISC, ARROWS }
internal enum class StickCap { RINGED, DISHED, KNURLED }
internal enum class PadKit(val face: FaceGlyphs, val dpad: DpadStyle, val stick: StickCap, private val xbox: Boolean = false) {
STEAM_DECK(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
STEAM_CONTROLLER(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
XBOX(FaceGlyphs.COLOR_LETTERS, DpadStyle.DISC, StickCap.DISHED, xbox = true),
DUALSHOCK(FaceGlyphs.COLOR_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED),
DUALSENSE(FaceGlyphs.MONO_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED);
val steam get() = this == STEAM_DECK || this == STEAM_CONTROLLER
val playStation get() = this == DUALSHOCK || this == DUALSENSE
fun label(control: InputControl): String = when (control) {
InputControl.LB -> if (xbox) "LB" else "L1"
InputControl.RB -> if (xbox) "RB" else "R1"
InputControl.LT -> if (xbox) "LT" else "L2"
InputControl.RT -> if (xbox) "RT" else "R2"
else -> control.label
}
/** What the player calls [control] on this controller. */
fun name(control: InputControl): String = if (!playStation) label(control) else when (control) {
InputControl.A -> "Cross"
InputControl.B -> "Circle"
InputControl.X -> "Square"
InputControl.Y -> "Triangle"
else -> label(control)
}
fun native(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}" && element.icon == 0 &&
(element.name == element.control.label || element.name == name(element.control))
fun artwork(element: InputSurfaceElement) = element.image.isEmpty() && element.showLabel &&
(native(element) || element.id == "builtin:keyboard" && element.icon == InputButtonIcons.KEYBOARD)
companion object {
fun forOverlay(context: Context, layout: SavedInputLayout?): PadKit? =
if (layout?.overlay != true) null else when (SessionPrefs.steamController(context)) {
SessionPrefs.CONTROLLER_DECK -> STEAM_DECK
SessionPrefs.CONTROLLER_STEAM -> STEAM_CONTROLLER
SessionPrefs.CONTROLLER_XBOX360 -> XBOX
SessionPrefs.CONTROLLER_DS4 -> DUALSHOCK
SessionPrefs.CONTROLLER_DUALSENSE -> DUALSENSE
else -> null
}
}
}
@@ -9,6 +9,7 @@ import com.droiddeck.launcher.session.SessionPrefs
enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindings: String? = null) {
NONE("none", R.string.second_mode_none),
MENU("menu", R.string.touch_droiddeck_menu),
KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad, InputStockLayouts.TRACKPAD),
TERMINAL("terminal", R.string.second_mode_terminal),
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls, InputStockLayouts.DECK),
@@ -21,19 +22,12 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindi
fun panel(context: Context): String? = if (this == DECK_CONTROLS) SessionPrefs.deckPanel(context).bindings else bindings
companion object {
fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false, bottomDesktop: Boolean = false, desktopSession: Boolean = false): SecondScreenMode {
/** The mode the bottom screen opens in: the one picked last if it is still available, else the DroidDeck menu. */
fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false, bottomDesktop: Boolean = false): SecondScreenMode =
entries.firstOrNull {
it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD || dashboard) &&
(it != DESKTOP || bottomDesktop)
}?.let { return it }
val picked = entries.any { it != NONE && it.id == remembered }
return when {
desktopSession -> KEYBOARD_TRACKPAD
deckPad -> DECK_CONTROLS
dashboard && !picked -> DASHBOARD
else -> KEYBOARD_TRACKPAD
}
}
} ?: MENU
}
}
@@ -1,116 +0,0 @@
package com.droiddeck.launcher.input
import android.graphics.Rect
import android.util.DisplayMetrics
import kotlin.math.max
import kotlin.math.min
internal class SteamDeckOverlayGeometry(
width: Int, height: Int, private val safe: Rect, metrics: DisplayMetrics, scale: Float,
) {
private val w = width.toFloat()
private val h = height.toFloat()
private val density = metrics.density
private val dpi = metrics.ydpi.takeIf { it in metrics.densityDpi * .6f..metrics.densityDpi * 1.6f }
?: metrics.densityDpi.toFloat()
private val unit = minOf(
min(w / 1600f, h / 900f) * min(1f, 80f / max(h / dpi * 25.4f, 1f)) * scale,
(w - safe.left - safe.right).coerceAtLeast(1f) / 1200f,
(h - safe.top - safe.bottom).coerceAtLeast(1f) / 900f,
)
private fun anchor(value: Float, reference: Float, extent: Float, start: Int, end: Int): Float {
val low = start + value * unit
val high = extent - end - (reference - value) * unit
return when {
value < reference / 3f -> low
value > reference * 2f / 3f -> high
else -> (extent / 2f + (value - reference / 2f) * unit).coerceIn(low, max(low, high))
}
}
fun place(elements: List<InputSurfaceElement>, rearButtons: Boolean, trackpads: Boolean): List<InputSurfaceElement> {
val x = { ref: Float -> anchor(ref, 1600f, w, safe.left, safe.right) }
val y = { ref: Float -> anchor(ref, 900f, h, safe.top, safe.bottom) }
val leftEdge = safe.left + 52f * density
val middle = (w + safe.left - safe.right) / 2f
val keyboard = Box(max(x(136f), leftEdge + 46f * unit), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } }
val row = fitRow(listOfNotNull(keyboard,
Box(max(x(370f), leftEdge + 66f * unit), y(852f), 66f, 30f),
Box(middle - 140f * unit, y(850f), 46f, 26f),
Box(middle + 140f * unit, y(850f), 46f, 26f),
Box(x(1230f), y(852f), 66f, 30f)), leftEdge)
val (guide, select, start, qam) = row.takeLast(4)
val positions = mapOf(
InputControl.LT to Box(x(140f), y(66f), 88f, 34f),
InputControl.LB to Box(x(140f), y(148f), 88f, 30f),
InputControl.RT to Box(x(1460f), y(66f), 88f, 34f),
InputControl.RB to Box(x(1460f), y(148f), 88f, 30f),
InputControl.Y to Box(x(1375f), y(345f) - 96f * unit, 58f),
InputControl.X to Box(x(1375f) - 96f * unit, y(345f), 58f),
InputControl.B to Box(x(1375f) + 96f * unit, y(345f), 58f),
InputControl.A to Box(x(1375f), y(345f) + 96f * unit, 58f),
InputControl.UP to Box(x(220f), y(345f) - 102.5f * unit, 55.5f, 47.5f),
InputControl.RIGHT to Box(x(220f) + 102.5f * unit, y(345f), 47.5f, 55.5f),
InputControl.DOWN to Box(x(220f), y(345f) + 102.5f * unit, 55.5f, 47.5f),
InputControl.LEFT to Box(x(220f) - 102.5f * unit, y(345f), 47.5f, 55.5f),
InputControl.LS to Box(x(290f), y(640f), 96f),
InputControl.RS to Box(x(1310f), y(640f), 96f),
InputControl.SELECT to select,
InputControl.START to start,
InputControl.GUIDE to guide,
InputControl.QAM to qam,
)
val rear = mapOf(
InputControl.L4 to Box(x(30f), y(470f), 30f, 58f),
InputControl.L5 to Box(x(30f), y(590f), 30f, 58f),
InputControl.R4 to Box(x(1570f), y(470f), 30f, 58f),
InputControl.R5 to Box(x(1570f), y(590f), 30f, 58f),
)
val pads = mapOf(
InputControl.LEFT_PAD to Box(x(470f), y(360f), 88f),
InputControl.RIGHT_PAD to Box(x(1130f), y(360f), 88f),
)
val optional = rear.filterKeys { rearButtons } + pads.filterKeys { trackpads }
val placed = elements.mapNotNull { element ->
when {
element.id == KEYBOARD -> row.first().place(element)
element.id != "legacy:${element.control.id}" -> element
element.control in rear || element.control in pads -> optional[element.control]?.place(element)
else -> positions[element.control]?.place(element) ?: element
}
}
return placed + optional.mapNotNull { (control, box) ->
if (placed.any { it.id == "legacy:${control.id}" }) null else box.place(InputSurfaceElement(control,
0f, 0f, 0f, 0f, floating = false, buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad))
}
}
private fun fitRow(row: List<Box>, start: Float): List<Box> {
val end = w - safe.right
val gap = ((end - start - row.fold(0f) { sum, box -> sum + box.width }) / (row.size - 1)).coerceIn(0f, 8f * density)
var edge = start - gap
val pushed = row.map { box -> box.at(max(box.cx, edge + gap + box.width / 2f)).also { edge = it.cx + it.width / 2f } }
edge = end + gap
return pushed.asReversed().map { box -> box.at(min(box.cx, edge - gap - box.width / 2f)).also { edge = it.cx - it.width / 2f } }.asReversed()
}
private inner class Box(val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw) {
val width get() = max(hw * 2f * unit, w * .03f)
fun at(cx: Float) = Box(cx, cy, hw, hh)
fun place(element: InputSurfaceElement): InputSurfaceElement {
val height = max(hh * 2f * unit, h * .03f)
return element.copy(
x = (cx - width / 2f).coerceIn(safe.left.toFloat(), max(safe.left.toFloat(), w - safe.right - width)) / w,
y = (cy - height / 2f).coerceIn(safe.top.toFloat(), max(safe.top.toFloat(), h - safe.bottom - height)) / h,
width = width / w, height = height / h,
).bounded()
}
}
private companion object {
const val KEYBOARD = "builtin:keyboard"
}
}
@@ -0,0 +1,81 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
internal class TriggerKeys(private val dispatch: (KeyEvent) -> Unit) {
private class Pull {
val held = BooleanArray(2)
val sent = BooleanArray(2)
}
private val handler = Handler(Looper.getMainLooper())
private val keyed = HashSet<Int>()
private val pulls = HashMap<Int, Pull>()
var synthesizing = false
private set
/** True when this real trigger key belongs to a pull that already went out as a synthetic press. */
fun nativeKey(event: KeyEvent): Boolean {
val i = index(event.keyCode) ?: return false
keyed += event.deviceId
val pull = pulls[event.deviceId] ?: return false
if (!pull.sent[i]) return false
if (event.action == KeyEvent.ACTION_UP) pull.sent[i] = false
return true
}
fun onMotion(event: MotionEvent) {
if (event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK || event.action != MotionEvent.ACTION_MOVE) return
val device = event.deviceId
if (device in keyed) return
val pull = pulls.getOrPut(device) { Pull() }
update(pull, 0, maxOf(event.getAxisValue(MotionEvent.AXIS_LTRIGGER), event.getAxisValue(MotionEvent.AXIS_BRAKE)), event)
update(pull, 1, maxOf(event.getAxisValue(MotionEvent.AXIS_RTRIGGER), event.getAxisValue(MotionEvent.AXIS_GAS)), event)
}
fun cancel() {
handler.removeCallbacksAndMessages(null)
pulls.clear()
}
private fun update(pull: Pull, i: Int, value: Float, event: MotionEvent) {
if (!pull.held[i] && value >= PRESS) {
pull.held[i] = true
pull.sent[i] = false
val device = event.deviceId
val source = event.source
// A pad that also sends trigger keys delivers them close to the axis; waiting lets that key win.
handler.postDelayed({
if (device !in keyed && pulls[device] === pull) {
pull.sent[i] = true
press(CODES[i], device, source)
}
}, KEY_WAIT_MS)
} else if (pull.held[i] && value <= RELEASE) pull.held[i] = false
}
private fun press(code: Int, device: Int, source: Int) {
val now = SystemClock.uptimeMillis()
synthesizing = true
try {
dispatch(KeyEvent(now, now, KeyEvent.ACTION_DOWN, code, 0, 0, device, 0, 0, source))
dispatch(KeyEvent(now, now, KeyEvent.ACTION_UP, code, 0, 0, device, 0, 0, source))
} finally {
synthesizing = false
}
}
private fun index(code: Int): Int? = CODES.indexOf(code).takeIf { it >= 0 }
private companion object {
val CODES = intArrayOf(KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2)
const val PRESS = 0.6f
const val RELEASE = 0.3f
const val KEY_WAIT_MS = 40L
}
}
@@ -12,9 +12,6 @@ object BattleNet {
const val APP_ID = 2596113170L
const val FEX_REQUEST = "battlenet-fex.request"
const val FEX_RESULT = "battlenet-fex.result"
const val PROGRAM = "/usr/local/bin/droiddeck-battlenet"
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null, val product: String? = null, val flavor: String? = null)
@@ -162,8 +159,6 @@ object BattleNet {
source = com.droiddeck.launcher.stores.Store.BATTLENET.id,
)
fun fexInUse(context: Context): String? = ComponentsManager.gameComponents(context, APP_ID.toString())["fex"]
internal fun title(uid: String): Title? {
val id = uid.lowercase()
TITLES.firstOrNull { it.uid == id }?.let { return it }
@@ -391,54 +386,6 @@ object BattleNet {
Log.i(TAG, "removed")
}
private val D2RFIX = Regex("""(?i)FEXCore-(\d+(?:\.\d+)*)-d2rfix(\d+)-linux\.wcp""")
private const val LISTING_MAX_AGE = 6 * 3600L
private val NEWEST = Comparator<Pair<List<Long>, Long>> { a, b ->
for (i in 0 until minOf(a.first.size, b.first.size)) if (a.first[i] != b.first[i]) return@Comparator a.first[i].compareTo(b.first[i])
if (a.first.size != b.first.size) a.first.size.compareTo(b.first.size) else a.second.compareTo(b.second)
}
internal fun d2rfix(file: String): Pair<List<Long>, Long>? {
val m = D2RFIX.matchEntire(file) ?: return null
val version = m.groupValues[1].split('.').map { it.toLongOrNull() ?: return null }
return version to (m.groupValues[2].toLongOrNull() ?: return null)
}
internal fun newestD2rFix(items: List<ComponentsManager.CatalogItem>): ComponentsManager.CatalogItem? =
items.filter { it.comp == "fex" }.mapNotNull { item -> d2rfix(item.file)?.let { item to it } }
.maxWithOrNull { a, b -> NEWEST.compare(a.second, b.second) }?.first
fun ensureFex(context: Context): String = ensureFex(context) { ComponentsManager.catalog(it, true).items }
@Synchronized
internal fun ensureFex(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): String {
val item = newestD2rFix(listing(context, refresh)) ?: error("no d2rfix FEXCore build in the Nightlies listing")
val file = ComponentsManager.safeName(item.file)
if (ComponentsManager.packages(context).none { it.file == file }) {
Log.i(TAG, "downloading ${item.file}")
ComponentsManager.download(context, item) {}
}
val scope = APP_ID.toString()
if (ComponentsManager.gameComponents(context, scope)["fex"] != file) {
ComponentsManager.setGameComponent(context, scope, "fex", file)
Log.i(TAG, "FEX for the Battle.net prefix: $file")
} else if (ComponentsManager.republish(context)) {
Log.i(TAG, "FEX for the Battle.net prefix: $file, now in every installed Proton")
}
return file
}
private fun listing(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): List<ComponentsManager.CatalogItem> {
val cached = ComponentsManager.catalog(context, false)
val age = System.currentTimeMillis() / 1000 - cached.fetchedAt
if (age in 0 until LISTING_MAX_AGE && newestD2rFix(cached.items) != null) return cached.items
val fetched = runCatching { refresh(context) }
.onFailure { Log.w(TAG, "Nightlies listing: ${it.message}") }.getOrNull().orEmpty()
return if (newestD2rFix(fetched) != null) fetched else cached.items
}
internal fun videoMemory(totalMb: Long): Int = (totalMb / 5 / 512 * 512).coerceIn(1536, 3584).toInt()
internal fun videoMemoryOptions(megabytes: Int): String =
@@ -464,21 +411,9 @@ object BattleNet {
return true
}
fun answerFexRequest(context: Context, dir: File) {
val app = context.applicationContext
Thread({
runCatching { ensureVideoMemory(app) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) }
runCatching { ensureNoSteam(app) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) }
val answer = try {
"ok " + ensureFex(app)
} catch (e: Exception) {
Log.w(TAG, "FEX for the Battle.net prefix", e)
"error " + (e.message ?: e.javaClass.simpleName)
}
Log.i(TAG, "FEX request: $answer")
val result = File(dir, FEX_RESULT)
val partial = File(dir, "$FEX_RESULT.tmp")
runCatching { partial.writeText(answer.replace('\n', ' ') + "\n"); partial.renameTo(result) }
}, "battlenet-fex").start()
fun ensureDefaults(context: Context, program: String?) {
if (program != PROGRAM && !installed(context)) return
runCatching { ensureVideoMemory(context) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) }
runCatching { ensureNoSteam(context) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) }
}
}
@@ -0,0 +1,216 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.agent.AgentException
import com.droiddeck.launcher.agent.AgentGuest
import org.json.JSONArray
import org.json.JSONObject
import java.time.Instant
object CurseForgeApp {
const val NAME = "CurseForge"
const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml"
internal const val WOW = 1
const val HELPER = "/usr/local/bin/droiddeck-curseforge"
private const val READY_MS = 120_000L
private const val INSTALL_MS = 300_000L
enum class Start { READY, BUSY, NO_DISPLAY, FAILED }
class Started(val state: Start, val inspector: String? = null)
private val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
class Failure(message: String, val code: String? = null) : Exception(message) {
val gone get() = code == "DEVTOOLS_UNREACHABLE"
}
fun find(apps: List<UserApps.App>): UserApps.App? = apps.firstOrNull { it.feed == FEED }
fun request(): UserApps.Request = UserApps.Request(UserApps.Source.Feed(FEED), NAME, null)
internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") }
fun holdArgs(app: UserApps.App): List<String>? = dir(app)?.let { listOf("hold", it) }
internal fun inspectorUrl(stdout: String): String? = stdout.lineSequence().map { it.trim() }.lastOrNull { INSPECTOR.matches(it) }
internal fun startState(exitCode: Int): Start = when (exitCode) {
0 -> Start.READY
3 -> Start.BUSY
4 -> Start.NO_DISPLAY
else -> Start.FAILED
}
internal fun sortOf(sort: WowAddonCatalog.Sort): Pair<Int, Int> = when (sort) {
WowAddonCatalog.Sort.POPULAR -> 8 to 2
WowAddonCatalog.Sort.UPDATED -> 16 to 2
WowAddonCatalog.Sort.NAME -> 1 to 1
WowAddonCatalog.Sort.DOWNLOADS -> 7 to 2
}
internal fun searchRequest(guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): JSONObject {
val (column, order) = sortOf(sort)
return JSONObject().put("gameId", WOW).put("searchText", text.trim()).put("page", page + 1)
.put("sortColumn", column).put("sortOrder", order).put("gameInstanceGuid", guid)
}
internal fun installRequest(guid: String, projectId: String): JSONObject =
JSONObject().put("instanceId", guid).put("projectId", projectId.toLong()).put("categoryClassId", 1)
.put("installLatestFile", true).put("installSource", 4)
private const val SERVICES = """(() => {
const seen = new Set(), out = {};
const walk = (o, d) => {
if (!o || typeof o !== 'object' || seen.has(o) || d > 4) return;
seen.add(o);
if (typeof o._nameOfService === 'string') { out[o._nameOfService] = o; return; }
let keys; try { keys = Object.keys(o); } catch (e) { return; }
for (const k of keys.slice(0, 4000)) {
let v; try { v = o[k]; } catch (e) { continue; }
if (v instanceof Map) { for (const x of v.values()) walk(x, d + 1); } else walk(v, d + 1);
}
};
walk(window, 0);
return out;
})()"""
internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r"): String {
val name = JSONObject.quote(method)
val run = if (args == null) "true" else "($pick)(await s[$name](...$args))"
val inner = "(async () => { const s = $SERVICES[${JSONObject.quote(service)}]; " +
"if (!s || typeof s[$name] !== 'function') return { missing: true }; " +
"return { value: $run }; })()"
return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" +
".find(w => !w.isDestroyed() && w.webContents.getURL().includes('desktop.html')); " +
"if (!w) return JSON.stringify({ missing: true }); " +
"return w.webContents.executeJavaScript(${JSONObject.quote(inner)}).then(v => JSON.stringify(v)); })()"
}
internal fun unwrap(answer: JSONObject): Any? {
if (!answer.optBoolean("ok")) {
val error = answer.optJSONObject("error")
throw Failure(error?.optString("message")?.takeIf { it.isNotBlank() } ?: answer.toString(), error?.optString("code")?.takeIf { it.isNotBlank() })
}
val text = answer.opt("value") as? String ?: throw Failure("CurseForge gave no answer")
val reply = JSONObject(text)
if (reply.optBoolean("missing")) throw Failure("CurseForge is not ready")
return reply.opt("value")
}
internal fun parseSearch(value: Any?): WowAddonCatalog.Page {
val reply = value as? JSONObject ?: throw Failure("CurseForge search failed")
if (reply.has("success") && !reply.optBoolean("success")) throw Failure("CurseForge search failed")
val mods = reply.optJSONArray("mods") ?: JSONArray()
val items = (0 until mods.length()).mapNotNull { mods.optJSONObject(it) }.mapNotNull { mod ->
val id = mod.optLong("id", 0L).takeIf { it > 0 } ?: return@mapNotNull null
val name = mod.optString("name").takeIf { it.isNotBlank() } ?: return@mapNotNull null
val author = mod.optJSONObject("primaryAuthor")?.optString("name")?.takeIf { it.isNotBlank() }
?: mod.optJSONArray("authors")?.optJSONObject(0)?.optString("name").orEmpty()
val date = mod.optJSONObject("updateVersion")?.optString("fileDate")?.takeIf { it.isNotBlank() }
?: mod.optString("projectLatestReleaseDate")
WowAddonCatalog.Addon(
id.toString(), name, author, "", mod.optLong("downloads", 0L).coerceAtLeast(0L),
runCatching { Instant.parse(date).toEpochMilli() }.getOrDefault(0L),
mod.optString("thumbnailUrl").takeIf { WowAddonCatalog.isHttps(it) },
)
}
val page = reply.optJSONObject("pagination")
val more = page != null && page.optInt("index") + page.optInt("resultCount") < page.optInt("totalCount")
return WowAddonCatalog.Page(items, more)
}
internal fun samePath(a: String, b: String) = a.trimEnd('/') == b.trimEnd('/')
internal fun instanceFor(instances: Any?, flavorDir: String, detected: String?): String? {
val list = instances as? JSONArray
val match = list?.let { all ->
(0 until all.length()).mapNotNull { all.optJSONObject(it) }
.firstOrNull { samePath(it.optString("installPath"), flavorDir) }?.optString("guid")
}
if (list != null && list.length() > 0) return match?.takeIf { it.isNotBlank() }
return detected?.takeIf { it.isNotBlank() }
}
internal fun projectIds(value: Any?): Set<String> {
val list = value as? JSONArray ?: return emptySet()
return (0 until list.length()).mapNotNull { list.opt(it)?.toString()?.takeIf { id -> id.isNotBlank() && id != "null" } }.toSet()
}
private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? {
val request = JSONObject().put("kind", "cdp").put("inspector", inspector).put("commandLineApi", true)
.put("expression", expression(service, method, args, pick)).put("timeout", timeoutMs / 1000.0)
return unwrap(AgentGuest.call(context, request, timeoutMs + 3_000, trusted = true))
}
private fun helper(context: Context, command: String, dir: String, timeoutMs: Long): JSONObject? {
val request = JSONObject().put("kind", "exec").put("argv", JSONArray(listOf(HELPER, command, dir))).put("timeout", timeoutMs / 1000.0)
return runCatching { AgentGuest.call(context, request, timeoutMs + 5_000, trusted = true) }.getOrNull()
}
fun start(context: Context, app: UserApps.App): Started {
val dir = dir(app) ?: return Started(Start.FAILED)
val answer = helper(context, "start", dir, 90_000)
if (answer == null || !answer.optBoolean("ok") || answer.optBoolean("timedOut")) {
stop(context, app, null)
return Started(Start.FAILED)
}
val state = startState(answer.optInt("exitCode", -1))
if (state == Start.BUSY || state == Start.NO_DISPLAY) return Started(state)
val inspector = inspectorUrl(answer.optJSONObject("stdout")?.optString("text").orEmpty())
if (state != Start.READY || inspector == null) {
stop(context, app, null)
return Started(Start.FAILED)
}
val deadline = System.currentTimeMillis() + READY_MS
while (System.currentTimeMillis() < deadline) {
val ready = runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) }
if (ready.isSuccess) return Started(Start.READY, inspector)
val error = ready.exceptionOrNull()
if (error is AgentException && error.code == "NO_ACTIVE_SESSION") break
Thread.sleep(1_000)
}
stop(context, app, inspector)
return Started(Start.FAILED)
}
fun stop(context: Context, app: UserApps.App, inspector: String?) {
val dir = dir(app) ?: return
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
helper(context, "stop", dir, 30_000)
}
private fun connect(context: Context, inspector: String) {
call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true")
}
fun instance(context: Context, inspector: String, root: String, flavorDir: String): String {
connect(context, inspector)
val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject
val instances = call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
return instanceFor(instances, flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
}
fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page =
parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000))
fun installed(context: Context, inspector: String, guid: String): Set<String> {
connect(context, inspector)
return projectIds(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, "r => (r || []).map(p => String(p.id))"))
}
fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean {
connect(context, inspector)
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return false
val deadline = System.currentTimeMillis() + INSTALL_MS
while (System.currentTimeMillis() < deadline) {
val listed = runCatching { installed(context, inspector, guid) }
val error = listed.exceptionOrNull()
if (error is Failure && error.gone || error is AgentException && error.code == "NO_ACTIVE_SESSION") throw error
if (projectId in listed.getOrDefault(emptySet())) return true
Thread.sleep(1_000)
}
return false
}
}
@@ -36,6 +36,7 @@ object UserApps {
private const val GITHUB_TAG = "github-tag"
private const val GITHUB_PUBLISHED = "github-published"
private const val GITHUB_ASSET = "github-asset"
private const val FEED = "update-feed"
enum class Kind { SCRIPT, APPIMAGE, FLATPAK }
@@ -43,10 +44,15 @@ object UserApps {
val key: String, val kind: Kind, val name: String, val icon: Any?, val detail: String?,
val program: String, val args: List<String>, val copied: Boolean = false,
val repo: String? = null, val version: String? = null,
val fex: String = LinuxFex.AUTO, val arch: String? = null,
)
val fex: String = LinuxFex.AUTO, val arch: String? = null, val feed: String? = null,
) {
val updatable get() = repo != null || feed != null
}
class Release(val tag: String, val published: String, val asset: String, val url: String, val sha256: String? = null)
class Release(
val tag: String, val published: String, val asset: String, val url: String,
val sha256: String? = null, val sha512: String? = null,
)
sealed class UpdateCheck {
class Current(val tag: String) : UpdateCheck()
@@ -58,6 +64,7 @@ object UserApps {
class Script(val file: File) : Source()
class AppImage(val file: File) : Source()
class GitHub(val repo: String, val asset: String? = null) : Source()
class Feed(val url: String) : Source()
class Flatpak(val id: String) : Source()
class FlatpakBundle(val file: File) : Source()
}
@@ -91,6 +98,7 @@ object UserApps {
"appimage:${item.id}", Kind.APPIMAGE, item.name, item.icon, item.comment, AppImageManager.LAUNCHER, listOf(item.guestDir),
repo = FileUtils.readString(File(dir, GITHUB_REPO))?.trim(), version = FileUtils.readString(File(dir, GITHUB_TAG))?.trim(),
fex = LinuxFex.mode(dir), arch = FileUtils.readString(File(dir, "arch"))?.trim()?.takeIf { it.isNotEmpty() },
feed = FileUtils.readString(File(dir, FEED))?.trim()?.takeIf { it.isNotEmpty() },
)
}
val flatpaks = FlatpakManager.installedApps(context).map { app ->
@@ -115,6 +123,7 @@ object UserApps {
is Source.Script -> addScript(context, s.file, name, icon, request.meta, onProgress)
is Source.AppImage -> AppImageManager.import(context, s.file, name, icon, request.meta) { onProgress(it, -1) }
is Source.GitHub -> addFromGitHub(context, s.repo, s.asset, name, icon, onProgress)
is Source.Feed -> addFromFeed(context, s.url, name, icon, onProgress)
is Source.Flatpak -> addFlatpak(context, s.id, name, icon, onProgress)
is Source.FlatpakBundle -> addFlatpakBundle(context, s.file, name, icon, onProgress)
}
@@ -346,11 +355,15 @@ object UserApps {
}
private fun withDownload(context: Context, release: Release, onProgress: (String, Int) -> Unit, use: (File) -> String?): String? {
val download = File(context.cacheDir, "github-${release.asset}")
val download = File(File(context.cacheDir, "user-apps").apply { mkdirs() }, release.asset)
try {
val label = context.getString(R.string.user_apps_downloading, release.asset)
val ok = Downloader.downloadFile(release.url, download, false, release.sha256) { f -> onProgress(label, if (f < 0) -1 else Math.round(f * 100f)) }
return if (ok) use(download) else context.getString(R.string.user_apps_download_failed)
if (!ok) return context.getString(R.string.user_apps_download_failed)
if (release.sha512 != null && !Hashes.sha512(download).equals(release.sha512, ignoreCase = true)) {
return context.getString(R.string.selfinst_checksum_mismatch)
}
return use(download)
} finally {
download.delete()
}
@@ -392,20 +405,57 @@ object UserApps {
return urls + listOfNotNull(avatar)
}
internal fun parseFeed(feed: String, body: String): Release? {
val top = body.lineSequence().filter { it.isNotEmpty() && !it[0].isWhitespace() && ':' in it }
.associate { it.substringBefore(':').trim() to it.substringAfter(':').trim().trim('\'', '"') }
val version = top["version"]?.takeIf { it.isNotEmpty() } ?: return null
val path = top["path"]?.takeIf { it.endsWith(".AppImage", ignoreCase = true) && '/' !in it && ".." !in it } ?: return null
val sha512 = top["sha512"]?.let { runCatching { java.util.Base64.getDecoder().decode(it) }.getOrNull() }
?.takeIf { it.size == 64 }?.joinToString("") { "%02x".format(it) } ?: return null
val base = feed.substringBeforeLast('/', "").takeIf { it.startsWith("https://") } ?: return null
return Release(version, top["releaseDate"].orEmpty(), path, "$base/$path", sha512 = sha512)
}
private fun feedRelease(context: Context, feed: String): Release? =
Downloader.downloadString(feed)?.let { parseFeed(feed, it) }
private fun feedMeta(feed: String, release: Release) =
mapOf(FEED to feed, GITHUB_TAG to release.tag, GITHUB_PUBLISHED to release.published, GITHUB_ASSET to release.asset)
private fun addFromFeed(context: Context, feed: String, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
onProgress(context.getString(R.string.user_apps_github_checking, name ?: feed), -1)
val release = feedRelease(context, feed) ?: return context.getString(R.string.user_apps_update_failed)
return withDownload(context, release, onProgress) { file ->
AppImageManager.import(context, file, name ?: release.asset.substringBefore('-'), icon, feedMeta(feed, release)) { onProgress(it, -1) }
}
}
internal fun isNewer(release: Release, published: String, installed: String?): Boolean =
if (published.isNotEmpty() && release.published.isNotEmpty()) {
val feed = runCatching { java.time.Instant.parse(release.published) }.getOrNull()
val have = runCatching { java.time.Instant.parse(published) }.getOrNull()
if (feed != null && have != null) feed > have else release.published > published
} else release.tag != installed
fun checkUpdate(context: Context, app: App): UpdateCheck {
app.feed?.let { feed ->
val release = feedRelease(context, feed) ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed))
val published = FileUtils.readString(File(AppImageManager.dir(context, app.key.substringAfter(':')), GITHUB_PUBLISHED))?.trim().orEmpty()
return if (isNewer(release, published, app.version)) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
}
val repo = app.repo ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed))
val dir = AppImageManager.dir(context, app.key.substringAfter(':'))
val (release, problem) = latestRelease(context, repo, FileUtils.readString(File(dir, GITHUB_ASSET))?.trim()?.takeIf { it.isNotEmpty() })
if (release == null) return UpdateCheck.Failed(problem ?: context.getString(R.string.user_apps_update_failed))
val published = FileUtils.readString(File(dir, GITHUB_PUBLISHED))?.trim().orEmpty()
val newer = if (published.isNotEmpty() && release.published.isNotEmpty()) release.published > published else release.tag != app.version
return if (newer) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
return if (isNewer(release, published, app.version)) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
}
fun update(context: Context, app: App, release: Release, onProgress: (String, Int) -> Unit): String? {
val repo = app.repo ?: return context.getString(R.string.user_apps_update_failed)
val meta = app.feed?.let { feedMeta(it, release) }
?: app.repo?.let { githubMeta(it, release) } ?: return context.getString(R.string.user_apps_update_failed)
return withDownload(context, release, onProgress) { file ->
AppImageManager.replace(context, app.key.substringAfter(':'), file, githubMeta(repo, release)) { onProgress(it, -1) }
AppImageManager.replace(context, app.key.substringAfter(':'), file, meta) { onProgress(it, -1) }
}
}
@@ -38,7 +38,6 @@ object WowAddonCatalog {
internal class Cat(val id: String, val name: String, val parents: List<String>)
private const val WOWI = "https://api.mmoui.com/v3/game/WOW/"
private const val CURSEFORGE = "https://www.curseforge.com/wow/search?class=addons"
private const val WOWI_FILES = "wowi-filelist.json"
internal const val FRESH_MS = 6L * 60 * 60 * 1000
@@ -94,8 +93,7 @@ object WowAddonCatalog {
Client(folder, version?.let(::flavorOf) ?: folderFamily(folder))
fun client(target: WowAddons.Target): Client {
val dir = target.addOns.parentFile?.parentFile
return client(target.flavor, dir?.let(::clientVersion))
return client(target.flavor, WowAddons.flavorDir(target)?.let(::clientVersion))
}
internal fun flavorMatches(flavors: Set<String>?, family: String?): Boolean =
@@ -209,10 +207,12 @@ object WowAddonCatalog {
fun categories(context: Context): List<Category> = wowiCategories(context).map { Category(it.id, it.name) }
internal fun parseWowiDetails(json: String): Pair<String, String?>? {
internal class Details(val url: String, val md5: String?, val version: String?)
internal fun parseWowiDetails(json: String): Details? {
val o = JSONArray(json).optJSONObject(0) ?: return null
val url = o.optString("UIDownload").ifEmpty { return null }
return url to o.optString("UIMD5").ifEmpty { null }
return Details(url, o.optString("UIMD5").ifEmpty { null }, o.optString("UIVersion").trim().ifEmpty { null })
}
internal fun isHttps(url: String) = url.startsWith("https://", ignoreCase = true)
@@ -220,10 +220,11 @@ object WowAddonCatalog {
internal fun md5Matches(file: File, expected: String?): Boolean =
expected.isNullOrBlank() || Hashes.md5(file).equals(expected.trim(), ignoreCase = true)
fun download(context: Context, addon: Addon, dest: File, progress: (Int) -> Unit): File {
fun download(context: Context, addon: Addon, dest: File, progress: (Int) -> Unit): String? {
val body = StoreNet.get(WOWI + "filedetails/${URLEncoder.encode(addon.id, "UTF-8")}.json", timeoutMs = 30_000)
?: throw unreachable(context)
val (url, md5) = parseWowiDetails(body) ?: throw IOException(context.getString(R.string.addons_no_file))
val details = parseWowiDetails(body) ?: throw IOException(context.getString(R.string.addons_no_file))
val url = details.url
if (!isHttps(url)) throw IOException(context.getString(R.string.addons_no_file))
dest.parentFile?.mkdirs()
dest.delete()
@@ -232,14 +233,33 @@ object WowAddonCatalog {
dest.delete()
throw unreachable(context)
}
if (!md5Matches(dest, md5)) {
if (!md5Matches(dest, details.md5)) {
dest.delete()
throw IOException(context.getString(R.string.selfinst_checksum_mismatch))
}
progress(100)
return dest
return details.version
}
internal fun curseForgeUrl(text: String): String =
text.trim().let { if (it.isEmpty()) CURSEFORGE else CURSEFORGE + "&search=" + URLEncoder.encode(it, "UTF-8") }
internal fun sameVersion(a: String, b: String): Boolean {
fun norm(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase()
return norm(a) == norm(b)
}
internal fun findUpdates(entries: List<Entry>, installed: List<WowAddons.Installed>): Map<String, Addon> {
val byId = entries.associateBy { it.addon.id }
val seen = HashSet<String>()
return installed.mapNotNull { item ->
val id = item.wowiId ?: return@mapNotNull null
val version = item.version ?: return@mapNotNull null
val latest = byId[id]?.addon?.takeIf { it.summary.isNotBlank() } ?: return@mapNotNull null
if (sameVersion(version, latest.summary) || !seen.add(id)) null else item.name to latest
}.toMap()
}
fun updates(context: Context, installed: List<WowAddons.Installed>, target: WowAddons.Target): Map<String, Addon> {
if (installed.none { it.wowiId != null }) return emptyMap()
val family = client(target).family
return runCatching { findUpdates(wowiEntries(context).filter { flavorMatches(it.flavors, family) }, installed) }.getOrDefault(emptyMap())
}
}
@@ -2,15 +2,25 @@ package com.droiddeck.launcher.runtime
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import android.content.Context
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreArchiveUnpacker
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.itch.ItchArchives
import org.apache.commons.compress.archivers.zip.ZipFile
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
import java.util.concurrent.atomic.AtomicBoolean
object WowAddons {
var imports by mutableIntStateOf(0)
@@ -18,10 +28,24 @@ object WowAddons {
class TooLarge : IOException()
fun changed() {
imports++
}
fun flavorDir(target: Target): File? = target.addOns.parentFile?.parentFile
fun root(target: Target): File? = flavorDir(target)?.parentFile
class Target(val flavor: String, val addOns: File)
class Addon(val name: String, val root: String)
class Installed(val name: String, val version: String?, val wowiId: String?)
class Origin(val id: String, val version: String)
private const val ORIGINS = ".droiddeck-sources"
internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024
private val SUFFIX = Regex("[-_](standard|mainline|classic|vanilla|tbc|bcc|wrath|wotlkc|cata|mists|forever)$", RegexOption.IGNORE_CASE)
@@ -45,53 +69,149 @@ object WowAddons {
target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
.map { it.name }.sortedBy { it.lowercase() }
fun details(target: Target): List<Installed> {
val origins = origins(target)
return installed(target).map { name ->
val toc = toc(File(target.addOns, name))
val origin = origins[name]
Installed(name, origin?.version ?: toc["Version"], origin?.id ?: toc["X-WoWI-ID"])
}
}
internal fun tocFields(text: String): Map<String, String> {
val out = LinkedHashMap<String, String>()
for (raw in text.lineSequence()) {
val line = raw.trim().removePrefix("\uFEFF")
if (!line.startsWith("##") || ':' !in line) continue
val key = line.removePrefix("##").substringBefore(':').trim()
val value = line.substringAfter(':').trim()
if (key.isNotEmpty() && value.isNotEmpty() && '@' !in value) out.putIfAbsent(key, value)
}
return out
}
private fun toc(folder: File): Map<String, String> {
val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }
val main = tocs.firstOrNull { it.name.dropLast(4).equals(folder.name, ignoreCase = true) }
?: tocs.firstOrNull { it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) }
?: tocs.minByOrNull { it.name.length } ?: return emptyMap()
return runCatching { tocFields(main.readText()) }.getOrDefault(emptyMap())
}
internal fun parseOrigins(text: String): Map<String, Origin> = text.lineSequence().mapNotNull { line ->
val parts = line.split('\t')
if (parts.size != 3 || parts.any { it.isBlank() }) null else parts[0] to Origin(parts[1], parts[2])
}.toMap()
internal fun formatOrigins(origins: Map<String, Origin>): String =
origins.entries.sortedBy { it.key.lowercase() }.joinToString("") { (name, o) -> "$name\t${o.id}\t${o.version.replace(Regex("\\s+"), " ")}\n" }
private fun originsFile(target: Target) = File(target.addOns, ORIGINS)
private fun origins(target: Target): Map<String, Origin> =
runCatching { parseOrigins(originsFile(target).readText()) }.getOrDefault(emptyMap())
private val originsLock = Any()
private fun keepOrigins(target: Target, names: List<String>, origin: Origin?) = synchronized(originsLock) {
val current = origins(target)
val next = current - names.toSet() + (origin?.let { o -> names.associateWith { o } } ?: emptyMap())
if (next != current) {
val file = originsFile(target)
if (next.isEmpty()) file.delete() else {
val temp = File(target.addOns, "$ORIGINS.tmp")
temp.writeText(formatOrigins(next))
if (!temp.renameTo(file)) {
temp.delete()
throw IOException("Cannot save $ORIGINS")
}
}
}
}
fun delete(target: Target, name: String) {
val folder = target.addOns.listFiles()?.firstOrNull { it.name == name && !it.name.startsWith(".") }
?: throw IOException("Cannot find $name")
StoreInstalls.deleteTree(folder)
if (Files.exists(folder.toPath(), LinkOption.NOFOLLOW_LINKS)) throw IOException("Cannot delete $name")
runCatching { keepOrigins(target, listOf(name), null) }
imports++
}
fun import(zipFile: File, target: Target): List<String> {
fun import(archive: File, target: Target, origin: Origin? = null, context: Context? = null): List<String> {
if (context == null || ItchArchives.kind(archive, archive.name) == "zip") return importZip(archive, target, origin)
val work = File(File(context.cacheDir, "wowaddons"), "unpack-${System.nanoTime()}")
try {
if (!work.mkdirs()) throw IOException("Cannot create ${work.path}")
val unpacker = StoreArchiveUnpacker(context, AtomicBoolean(), "Addons", R.string.stores_itch_archive, R.string.stores_itch_extract_failed, "addon-unpack")
unpacker.work = work
unpacker.limit = MAX_EXPANDED_BYTES
try {
unpacker.unpack(archive, archive.name, { _, _ -> }, {})
} catch (_: StoreArchiveUnpacker.TooLarge) {
throw TooLarge()
}
return importFolder(work, target, origin)
} finally {
StoreInstalls.deleteTree(work)
}
}
private class Entry(val path: String, val open: () -> InputStream)
private fun importZip(zipFile: File, target: Target, origin: Origin?): List<String> =
ZipFile.builder().setFile(zipFile).get().use { zip ->
val all = zip.entries.toList()
if (all.any { it.isUnixSymlink }) return emptyList()
val entries = all.filter { clean(it.name) != null }
val addons = addons(entries.filter { !it.isDirectory }.mapNotNull { clean(it.name) })
if (addons.isEmpty()) return emptyList()
val addOns = target.addOns
if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}")
val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}")
try {
val fresh = File(stage, "new")
val buffer = ByteArray(64 * 1024)
var written = 0L
for (entry in entries) {
if (entry.isDirectory) continue
val path = clean(entry.name) ?: continue
val addon = addons.firstOrNull { path.startsWith(it.root) } ?: continue
val out = inside(fresh, addon.name + "/" + path.removePrefix(addon.root)) ?: continue
out.parentFile?.mkdirs()
zip.getInputStream(entry).use { input ->
out.outputStream().use { output ->
while (true) {
val read = input.read(buffer)
if (read < 0) break
written += read
if (written > MAX_EXPANDED_BYTES) throw TooLarge()
output.write(buffer, 0, read)
}
importEntries(all.filter { !it.isDirectory }.mapNotNull { entry -> clean(entry.name)?.let { Entry(it) { zip.getInputStream(entry) } } }, target, origin)
}
internal fun importFolder(folder: File, target: Target, origin: Origin?): List<String> {
val entries = ArrayList<Entry>()
var links = false
Files.walkFileTree(folder.toPath(), object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
if (!attrs.isRegularFile) links = true
else clean(folder.toPath().relativize(file).joinToString("/"))?.let { entries.add(Entry(it) { Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS) }) }
return if (links) FileVisitResult.TERMINATE else FileVisitResult.CONTINUE
}
})
return if (links) emptyList() else importEntries(entries, target, origin)
}
private fun importEntries(entries: List<Entry>, target: Target, origin: Origin?): List<String> {
val addons = addons(entries.map { it.path })
if (addons.isEmpty()) return emptyList()
val addOns = target.addOns
if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}")
val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}")
try {
val fresh = File(stage, "new")
val buffer = ByteArray(64 * 1024)
var written = 0L
for (entry in entries) {
val addon = addons.firstOrNull { entry.path.startsWith(it.root) } ?: continue
val out = inside(fresh, addon.name + "/" + entry.path.removePrefix(addon.root)) ?: continue
out.parentFile?.mkdirs()
entry.open().use { input ->
out.outputStream().use { output ->
while (true) {
val read = input.read(buffer)
if (read < 0) break
written += read
if (written > MAX_EXPANDED_BYTES) throw TooLarge()
output.write(buffer, 0, read)
}
}
}
swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() })
} finally {
StoreInstalls.deleteTree(stage)
}
imports++
return addons.map { it.name }
swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() })
} finally {
StoreInstalls.deleteTree(stage)
}
runCatching { keepOrigins(target, addons.map { it.name }, origin) }
imports++
return addons.map { it.name }
}
internal fun addons(files: List<String>): List<Addon> {
@@ -0,0 +1,119 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.graphics.PixelFormat
import android.media.ImageReader
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.storage.StorageState
import com.droiddeck.launcher.wayland.CompositorHost
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
object BackgroundSession {
private const val TAG = "BackgroundSession"
private const val WIDTH = 1280
private const val HEIGHT = 720
private const val REFRESH_HZ = 60f
private const val BEGIN_MS = 30_000L
private const val AGENT_MS = 120_000L
private const val STOP_MS = 30_000L
private val ended = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
private val main by lazy { Handler(Looper.getMainLooper()) }
private var reader: ImageReader? = null
fun start(context: Context, program: String, args: List<String>): String? {
val app = context.applicationContext
val claim = AtomicBoolean(false)
val began = CountDownLatch(1)
var own: String? = null
main.post {
if (claim.compareAndSet(false, true)) {
own = runCatching { begin(app, program, args) }
.onFailure { Log.w(TAG, "could not start a hidden session for $program", it) }
.getOrNull()
}
began.countDown()
}
if (!began.await(BEGIN_MS, TimeUnit.MILLISECONDS) && claim.compareAndSet(false, true)) return null
began.await()
val session = own ?: return null
val deadline = System.currentTimeMillis() + AGENT_MS
val settle = System.currentTimeMillis() + 5_000
while (System.currentTimeMillis() < deadline) {
if (SessionState.sessionId != session) return null
if (SessionState.running && AgentGuest.hello(app) != null && SessionState.sessionId == session) return session
if (SessionState.phase == SessionPhase.FAILED) break
if (!SessionState.running && SessionState.phase in ended && System.currentTimeMillis() > settle) break
Thread.sleep(250)
}
stop(app, session)
return null
}
fun stop(context: Context, session: String) {
val app = context.applicationContext
if (SessionState.sessionId != session) return
main.post { if (SessionState.sessionId == session) SessionService.stop(app) }
val deadline = System.currentTimeMillis() + STOP_MS
while (live(session) && System.currentTimeMillis() < deadline) Thread.sleep(250)
if (!live(session)) {
main.post { release() }
return
}
Thread {
while (live(session)) Thread.sleep(1_000)
main.post { release() }
}.start()
}
private fun live(session: String) =
SessionState.sessionId == session && (SessionState.running || SessionState.phase !in ended)
private fun begin(context: Context, program: String, args: List<String>): String? {
if (SessionState.running || SessionState.phase !in ended || LinuxRuntimeInstaller.isBusy() ||
SessionState.installing != null || StorageState.cleaning) return null
release()
SessionEvents.begin(context, SessionService.MODE_RUN, SessionPaths.label(SessionService.MODE_RUN, program))
val session = SessionState.sessionId ?: return null
SessionState.stopRequested = false
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
var requested = false
try {
val output = CompositorHost.prepare(context)
val size = WIDTH to HEIGHT
SessionState.outputSize = size
SessionState.refreshHz = REFRESH_HZ
CompositorHost.logToSession(context)
CompositorHost.applyHdr(context, SessionPrefs.prefMode(SessionService.MODE_RUN))
val offscreen = ImageReader.newInstance(WIDTH, HEIGHT, PixelFormat.RGBA_8888, 2)
reader = offscreen
offscreen.setOnImageAvailableListener({ it.acquireLatestImage()?.close() }, main)
CompositorHost.start(context, output, offscreen.surface, size, REFRESH_HZ, 0)
CompositorHost.detach(offscreen.surface)
SessionEvents.record("compositor.started")
SessionEvents.transition(SessionPhase.STARTING_GUEST, "guest.starting")
requested = true
SessionService.start(context, SessionService.MODE_RUN, program, programArgs = args.toTypedArray())
return session
} catch (e: Exception) {
if (requested) SessionService.stop(context)
if (!SessionState.running) {
reader?.close()
reader = null
SessionEvents.transition(SessionPhase.FAILED, "hidden.failed", mapOf("error" to e.toString()))
}
throw e
}
}
private fun release() {
if (SessionState.running) return
reader?.close()
reader = null
}
}
@@ -88,8 +88,8 @@ object ComponentUpdater {
logLines(context).mapNotNull { STAMP.find(it)?.groupValues?.get(1) }.maxOrNull() ?: "0"
private fun lineOf(context: Context, state: JSONObject, p: ComponentsManager.Proton, comp: String): ComponentUpdates.Line? {
if (!ComponentUpdates.follows(p) || !ComponentsManager.supports(p, comp)) return null
if (comp == "fex") return ComponentUpdates.line("fex", false)
if (!ComponentUpdates.autoFollows(p, comp) || !ComponentsManager.supports(p, comp)) return null
if (comp == "fex") return ComponentUpdates.fexLine(p)
val key = "${p.id}|${p.version}"
val flavors = state.obj("flavors").obj(key)
val arm64ec = if (flavors.has(comp)) flavors.optBoolean(comp) else ComponentsManager.arm64ec(context, p, comp)?.also { flavors.put(comp, it) }
@@ -13,7 +13,7 @@ object ComponentUpdates {
const val BOOTED_SECONDS = 60L
const val FAILED_BOOTS_BEFORE_ROLLBACK = 2
data class Line(val key: String, val comp: String, val prefix: String)
data class Line(val key: String, val comp: String, val prefix: String, val release: String = ComponentsManager.DD_NIGHTLY)
val LINES = listOf(
Line("dxvk", "dxvk", "DD-dxvk-"),
@@ -21,12 +21,19 @@ object ComponentUpdates {
Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"),
Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"),
Line("fex", "fex", "DD-FEXCore-"),
Line("fex-bionic", "fex", "FEXCore-", ComponentsManager.DD_BIONIC),
)
private val OWN_PREFIX = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }.prefix
fun follows(p: ComponentsManager.Proton): Boolean = !p.valve && p.dir.name.startsWith(OWN_PREFIX)
fun autoFollows(p: ComponentsManager.Proton, comp: String): Boolean =
follows(p) || (comp == "fex" && !p.valve && ComponentsManager.bionicTool(p.dir.name))
fun fexLine(p: ComponentsManager.Proton): Line =
if (ComponentsManager.bionicTool(p.dir.name)) LINES.first { it.release == ComponentsManager.DD_BIONIC } else line("fex", false)
fun ownId(protonId: String): Boolean = protonId.startsWith(ComponentsManager.safeName(OWN_PREFIX))
fun strays(
@@ -34,8 +41,8 @@ object ComponentUpdates {
choices: Map<String, Map<String, ComponentsManager.Choice>>,
placed: Set<String>,
): List<Pair<ComponentsManager.Proton, String>> =
protons.filterNot(::follows).flatMap { p ->
choices[p.id].orEmpty().filter { (_, c) -> !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
protons.flatMap { p ->
choices[p.id].orEmpty().filter { (comp, c) -> !autoFollows(p, comp) && !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
}
fun unseen(
@@ -53,13 +60,14 @@ object ComponentUpdates {
fun pick(items: List<ComponentsManager.CatalogItem>, line: Line, bad: Set<String>): ComponentsManager.CatalogItem? {
val newestBad = bad.filter { belongs(it, line) }.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a, b) }
return items.filter { it.release == ComponentsManager.DD_NIGHTLY && it.comp == line.comp && belongs(it.file, line) }
return items.filter { it.release == line.release && it.comp == line.comp && belongs(it.file, line) }
.filter { newestBad == null || ProtonExtras.compareVersions(it.file, newestBad) > 0 }
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }
}
fun belongs(file: String, line: Line): Boolean =
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true &&
(line.comp != "fex" || ComponentsManager.bionicFex(file) == (line.release == ComponentsManager.DD_BIONIC))
fun arm64ec(pe: ByteArray): Boolean? = runCatching {
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
@@ -161,7 +169,7 @@ object ComponentUpdates {
fun stale(line: Line?, owned: Set<String>, stored: List<String>, keep: Set<String>, current: String, bad: Set<String> = emptySet()): List<String> {
val ranked = line?.takeIf { belongs(current, it) }
fun newer(file: String) = ranked != null && belongs(file, ranked) && ProtonExtras.compareVersions(file, current) > 0
return (owned + stored.filter { ranked != null && belongs(it, ranked) })
return (owned + stored.filter { ranked != null && ranked.release == ComponentsManager.DD_NIGHTLY && belongs(it, ranked) })
.filter { it !in keep && ((it in bad && it in owned) || !newer(it)) }.distinct()
}
}
@@ -29,6 +29,7 @@ object ComponentsManager {
private const val NIGHTLIES = "The412Banner/Nightlies"
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
internal const val DD_NIGHTLY = "linux-nightly"
internal const val DD_BIONIC = "bionic-stable"
private val RELEASES = linkedMapOf(
"FexCore-Linux" to "fex",
"Dxvk-Linux" to "dxvk",
@@ -37,9 +38,9 @@ object ComponentsManager {
"Vkd3d-proton-Linux" to "vkd3d",
)
private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex")
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY)
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC)
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
private val TYPES = mapOf("FEXCore-Linux" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
private val TYPES = mapOf("FEXCore-Linux" to "fex", "FEXCore-Bionic" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
@@ -201,8 +202,34 @@ object ComponentsManager {
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
}
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) =
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) {
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
if (comp == "fex" && file != null) fetchFexTwin(context, safeName(file))
}
// Twin downloads in flight: one worker per name, so two profile changes cannot share one partial download.
private val twinDownloads = HashSet<String>()
private fun fetchFexTwin(context: Context, file: String) {
val twin = fexTwin(file) ?: return
if (protons(context).all { fexFits(it.dir.name, file) }) return
synchronized(lock) { if (isStored(context, twin) || !twinDownloads.add(twin)) return }
val app = context.applicationContext
Thread({
try {
runCatching {
val item = catalogItem(app, twin, if (bionicFex(twin)) DD_BIONIC else "FexCore-Linux")
if (item == null) Log.i(TAG, "$twin is not listed")
else {
download(app, item) {}
republish(app)
}
}.onFailure { Log.w(TAG, "download $twin", it) }
} finally {
synchronized(lock) { twinDownloads.remove(twin) }
}
}, "fex-twin").start()
}
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
@@ -238,6 +265,20 @@ object ComponentsManager {
saveState(context, state)
}
private val UNPINNED_FEX = Regex("""(?i)FEXCore-\d+(?:\.\d+)*-d2rfix\d+-linux\.wcp""")
fun migrateBattleNetFex(context: Context) = synchronized(lock) {
val marker = File(dataDir(context), ".battlenet-fex-unpinned")
if (marker.isFile) return@synchronized
migratePlugin(context)
val scope = com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString()
if (gameComponents(context, scope)["fex"]?.let(UNPINNED_FEX::matches) == true) {
setGameComponent(context, scope, "fex", null)
Log.i(TAG, "Battle.net follows the selected FEX again")
}
marker.writeText("1\n")
}
private fun migratePlugin(context: Context) {
val marker = File(dataDir(context), ".plugin-imported")
if (marker.isFile) return
@@ -399,7 +440,7 @@ object ComponentsManager {
}
}
require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" }
if (comp == "fex") FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
if (comp == "fex" && !bionicTool(dir.name)) FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
COMP_DIR[comp]?.let { compDir ->
for (arch in PE_ARCHES) {
val target = File(dir, "$compDir/$arch")
@@ -487,6 +528,7 @@ object ComponentsManager {
fun snapshotAll(context: Context) = synchronized(lock) {
migratePlugin(context)
runCatching { migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) }
val state = loadState(context)
for (p in protons(context)) for (comp in COMPONENTS) {
runCatching { ensureOriginal(context, p, comp, state) }.onFailure { Log.w(TAG, "original $comp of ${p.name}", it) }
@@ -497,6 +539,7 @@ object ComponentsManager {
fun snapshot(context: Context): Snapshot = synchronized(lock) {
migratePlugin(context)
runCatching { migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) }
val state = loadState(context)
val reapplied = HashMap<String, Long>()
runCatching {
@@ -587,7 +630,9 @@ object ComponentsManager {
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
.filter { owned(comp, it) }.associateWith { File(base, it) }
}
for (rel in managed(comp) - files.keys) {
// A bionic tool never loses a FEX file: its launch.sh would put the whole bundled FEX back.
val removed = if (comp == "fex" && bionicTool(p.dir.name)) emptySet() else managed(comp) - files.keys
for (rel in removed) {
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
.append('\t').append(rel).append("\t-\t-\n")
}
@@ -604,7 +649,8 @@ object ComponentsManager {
val version = safeName(file.removePrefix("original "))
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
} else {
safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
val fit = (if (comp == "fex") launchFex(p.dir.name, file) { File(packagesDir(context), it).isFile } else file) ?: return null
safeName(fit.removeSuffix(".wcp")) to File(packagesDir(context), fit)
}.takeIf { it.second.isFile }
}
@@ -635,12 +681,14 @@ object ComponentsManager {
for (scope in profiles.keys()) {
val profile = profiles.optJSONObject(scope) ?: continue
for (comp in COMPONENTS) {
val file = profile.optString(comp)
if (file.isEmpty()) continue
val wcp = File(packagesDir(context), file)
if (!wcp.isFile) continue
val key = safeName(file.removeSuffix(".wcp"))
for (p in all) append(scope, p, comp, key, wcp)
val chosen = profile.optString(comp)
if (chosen.isEmpty()) continue
for (p in all) {
val file = (if (comp == "fex") launchFex(p.dir.name, chosen) { File(packagesDir(context), it).isFile } else chosen) ?: continue
val wcp = File(packagesDir(context), file)
if (!wcp.isFile) continue
append(scope, p, comp, safeName(file.removeSuffix(".wcp")), wcp)
}
}
}
return PreparedLaunchState(lines.toString(), keep)
@@ -661,6 +709,7 @@ object ComponentsManager {
val wcp = File(packagesDir(context), safeName(file))
val info = packageInfo(context, wcp)
requireSelectable(context, info.comp)
requireFits(p, info)
val state = loadState(context)
if (inUse(context, p)) {
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
@@ -674,7 +723,11 @@ object ComponentsManager {
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
}
private fun requireFits(p: Proton, info: Package) =
check(info.comp != "fex" || fexFits(p.dir.name, info.file)) { "${info.file} is not a FEX build for ${p.name}" }
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject, auto: Boolean = false) {
requireFits(p, info)
ensureOriginal(context, p, info.comp, state)
val hashes = installFiles(context, p.dir, info.comp, wcp)
state.sub("active").sub(p.id).put(info.comp, JSONObject()
@@ -787,6 +840,18 @@ object ComponentsManager {
internal fun liveOnAny(key: String, entry: JSONObject, installs: List<Proton>?): Boolean =
installs?.any { liveSelection(key, entry, it) } == true
// An installed tool that launches with `name` as the stored twin of a game's FEX choice (a Linux choice on
// DroidDeck-Bionic, a -bionic one on another Proton): deleting the twin would drop that choice for that tool.
internal fun twinUser(state: JSONObject, installed: List<Proton>, name: String): Proton? {
val profiles = state.optJSONObject("profiles") ?: return null
for (scope in profiles.keys()) {
val chosen = profiles.optJSONObject(scope)?.optString("fex")?.takeIf { it.isNotEmpty() } ?: continue
if (fexTwin(chosen) != name) continue
installed.firstOrNull { !fexFits(it.dir.name, chosen) }?.let { return it }
}
return null
}
internal fun packagesInUse(state: JSONObject, installed: List<Proton>): Set<String> {
val byId = installed.groupBy { it.id }
val names = HashSet<String>()
@@ -803,7 +868,11 @@ object ComponentsManager {
val profiles = state.optJSONObject("profiles")
for (scope in profiles?.keys() ?: emptyList<String>().iterator()) {
val profile = profiles?.optJSONObject(scope) ?: continue
COMPONENTS.forEach { comp -> profile.optString(comp).takeIf { it.isNotEmpty() }?.let(names::add) }
COMPONENTS.forEach { comp ->
val file = profile.optString(comp).takeIf { it.isNotEmpty() } ?: return@forEach
names.add(file)
if (comp == "fex" && installed.any { !fexFits(it.dir.name, file) }) fexTwin(file)?.let(names::add)
}
}
return names
}
@@ -874,6 +943,7 @@ object ComponentsManager {
val queued = state.sub("queued").sub(target.id)
var changed = false
wanted.forEach { (comp, entry) ->
if (comp == "fex" && !fexFits(target.dir.name, entry.optString("file"))) return@forEach
if (active?.has(comp) != true && !queued.has(comp)) {
queued.put(comp, entry)
changed = true
@@ -954,6 +1024,8 @@ object ComponentsManager {
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
val name = safeName(file)
val state = loadState(context)
val twinTool = twinUser(state, protons(context), name)
check(twinTool == null) { context.getString(R.string.cmgr_package_in_use, name, twinTool?.name ?: "") }
val installed = protons(context).groupBy { it.id }
var changed = false
for (key in listOf("queued", "active")) {
@@ -1050,8 +1122,11 @@ object ComponentsManager {
return Catalog(items, o.optLong("fetchedAt"))
}
internal fun assetComp(release: String, name: String): String? =
RELEASES[release] ?: if (release == DD_NIGHTLY) NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value else null
internal fun assetComp(release: String, name: String): String? = RELEASES[release] ?: when (release) {
DD_NIGHTLY -> NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value
DD_BIONIC -> "fex"
else -> null
}
internal val CATALOG_ORDER: Comparator<CatalogItem> =
compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
@@ -1139,6 +1214,25 @@ object ComponentsManager {
return runCatching { readWcpEntry(original, rel) }.getOrNull()
}
// DroidDeck-Bionic loads only Android builds of FEX's unix libraries; other Protons only glibc builds.
internal fun bionicTool(dirName: String?): Boolean = dirName?.startsWith("DroidDeck-Bionic") == true
internal fun bionicFex(file: String): Boolean = file.endsWith("-bionic.wcp", ignoreCase = true)
internal fun fexFits(toolDir: String?, file: String): Boolean = bionicTool(toolDir) == bionicFex(file)
internal fun fexTwin(file: String): String? = when {
file.endsWith("-linux.wcp", ignoreCase = true) -> file.dropLast("-linux.wcp".length) + "-bionic.wcp"
file.endsWith("-bionic.wcp", ignoreCase = true) -> file.dropLast("-bionic.wcp".length) + "-linux.wcp"
else -> null
}
internal fun launchFex(toolDir: String, file: String, stored: (String) -> Boolean): String? =
if (fexFits(toolDir, file)) file else fexTwin(file)?.takeIf(stored)
internal fun <T> forTool(comp: String, toolDir: String?, items: List<T>, selected: String? = null, file: (T) -> String): List<T> =
if (comp != "fex") items else items.filter { file(it) == selected || fexFits(toolDir, file(it)) }
fun supports(p: Proton, comp: String): Boolean =
if (comp == "fex") File(p.dir, FEX_FILES.first()).isFile else File(p.dir, "${COMP_DIR.getValue(comp)}/aarch64-windows").isDirectory
@@ -937,7 +937,7 @@ internal object EnhancedSessionLogShare {
val value = entry.lowercase(Locale.US)
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") ||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").any(value::contains)) return Category.GAMES
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug", "bionic").any(value::contains)) return Category.GAMES
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
return Category.SESSION
}
@@ -948,7 +948,7 @@ internal object EnhancedSessionLogShare {
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt",
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt", "droiddeck-bionic.log",
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
)
private val KNOWN_COMPONENT_PATTERNS = listOf(
@@ -74,10 +74,16 @@ object ExperimentalProtons {
return PREFIX + base + (tag?.let { "-$it" } ?: "")
}
/** DroidDeck-Bionic test builds are prereleases of the same repository and have their own row in the Proton list. */
internal fun listed(assets: List<ProtonExtras.Asset>): List<ProtonExtras.Asset> {
val bionic = ProtonExtras.tools.first { it.id == ProtonExtras.BIONIC }
return assets.filterNot { bionic.assetPattern.containsMatchIn(it.name) }
}
fun refresh(context: Context): List<Release>? {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null
val assets = ProtonExtras.assets(tool, fetched.releases, prerelease = true)
val assets = listed(ProtonExtras.assets(tool, fetched.releases, prerelease = true))
val rows = assets.map { Release(it.tag, it.name, it.url, it.sha512, it.size, it.releaseName) }.distinctBy { it.tag }
if (!SessionState.running) {
reconcile(context, fetched)
@@ -14,7 +14,8 @@ object ProtonDefault {
data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean)
data class Request(val seq: Long, val valve: Boolean, val dir: String)
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>)
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>,
val source: String? = null)
data class GameChoice(val valve: Boolean, val dir: String)
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
@@ -34,6 +35,7 @@ object ProtonDefault {
Tool(t.optString("name"), t.optString("display"), t.optString("dir"), t.optBoolean("valve"))
}?.takeIf { it.name.isNotEmpty() }
},
source = o.optString("source").ifEmpty { null },
)
}
@@ -99,7 +101,13 @@ object ProtonDefault {
if (!runnable(state, proton)) return Outcome.NOT_RUNNABLE
val d = dir(context)
val seq = nextSeq(System.currentTimeMillis(), state, parseRequest(read(File(d, "request.json"))))
val body = JSONObject().put("seq", seq).put("valve", proton.valve).put("dir", proton.dir.name).toString(1) + "\n"
writeRequest(d, Request(seq, proton.valve, proton.dir.name))
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
}
private fun writeRequest(d: File, request: Request) {
val body = JSONObject().put("seq", request.seq).put("valve", request.valve).put("dir", request.dir).toString(1) + "\n"
val staged = File(d, "request.json.staged")
try {
d.mkdirs()
@@ -110,8 +118,45 @@ object ProtonDefault {
Log.w(TAG, "could not write the Proton request", e)
throw e
}
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
}
// The default that names a tool an update replaces moves to the new one, as the per-game picks do: otherwise the guest
// no longer finds it and falls back to DroidDeck-Proton.
internal fun movedDefault(state: State, request: Request?, from: Set<String>, to: String, now: Long): Request? {
val (valve, dir) = chosen(state, request) ?: return null
if (valve || dir !in from) return null
return Request(nextSeq(now, state, request), false, to)
}
@Synchronized
fun moveDefault(context: Context, from: Set<String>, to: String) {
val d = dir(context)
val moved = movedDefault(state(context), parseRequest(read(File(d, "request.json"))), from, to, System.currentTimeMillis()) ?: return
writeRequest(d, moved)
}
// DroidDeck-Bionic keeps one build. A default naming another one moves to the installed build: an app from before
// updates carried the default over left it, or the guest fell back to its own tool when that build was gone (the
// request the app last wrote still names it).
internal fun bionicDefault(state: State, request: Request?, prefix: String, newest: String, now: Long): Request? {
val current = chosen(state, request)
val stale = when {
current != null && !current.first && current.second.startsWith(prefix) -> current.second
state.source == "fallback" && request != null && !request.valve && request.dir.startsWith(prefix) -> request.dir
else -> return null
}
return if (stale == newest) null else Request(nextSeq(now, state, request), false, newest)
}
/** The default and the per-game picks that name a DroidDeck-Bionic build other than [newest] move to it. */
@Synchronized
fun keepBionicCurrent(context: Context, prefix: String, newest: String) {
val d = dir(context)
bionicDefault(state(context), parseRequest(read(File(d, "request.json"))), prefix, newest, System.currentTimeMillis())
?.let { writeRequest(d, it) }
val games = parseGames(read(File(d, GAMES)))
val stale = games.values.filterNotNull().filter { !it.valve && it.dir.startsWith(prefix) && it.dir != newest }.map { it.dir }.toSet()
if (stale.isNotEmpty()) movedGames(games, stale, newest)?.let { writeGames(d, it) }
}
internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? {
@@ -8,6 +8,7 @@ import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.NativeGuest
import java.io.File
import java.util.Locale
import org.json.JSONArray
@@ -27,20 +28,27 @@ object ProtonExtras {
@Volatile
private var replacing = false
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex,
val prereleases: Boolean = false)
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
val sha256: String? = null, val releaseName: String = tag)
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
const val OWN = "droiddeck"
const val BIONIC = "bionic"
val tools = listOf(
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("aarch64\\.tar\\.(gz|xz)$")),
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Proton-.*aarch64\\.tar\\.(gz|xz)$")),
// Bionic (Android libc) Proton started outside the Linux userland; test builds are prereleases. No-proot only.
Tool(BIONIC, "DroidDeck-Bionic", "DroidDeck-Bionic", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Bionic-.*aarch64\\.tar\\.(gz|xz)$"), prereleases = true),
)
/** The sources offered on this device: DroidDeck-Bionic only with Run without proot on. */
fun offered(context: Context): List<Tool> = tools.filter { it.id != BIONIC || NativeGuest.enabled(context) }
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
private fun requests(context: Context) = File(home(context), ".dd-proton-extra")
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
@@ -115,10 +123,11 @@ object ProtonExtras {
private var lastAttempt = 0L
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
keepBionicCurrent(context)
synchronized(checkLock) {
val file = latestFile(context)
val cache = readJson(file)
val due = tools.filter { tool ->
val due = offered(context).filter { tool ->
val at = cache.optJSONObject(tool.id)?.optLong("at", 0L) ?: 0L
force || (now - at) !in 0 until CHECK_EVERY_MS
}
@@ -168,15 +177,32 @@ object ProtonExtras {
fun remove(context: Context, tool: Tool, dir: String? = null) {
val name = if (dir != null) dir.takeIf { it in installedAll(context, tool) } ?: return else installed(context, tool) ?: return
if (File(toolsDir(context), name).deleteRecursively()) ComponentsManager.forgetProton(context, name)
if (deleteTool(context, name)) ComponentsManager.forgetProton(context, name)
}
// A tool folder can hold links that point out of it (a prefix template's dosdevices/z: -> /), and
// File.deleteRecursively() follows links into directories: remove each link itself, never what it points to.
private fun deleteTool(context: Context, name: String): Boolean {
val dir = File(toolsDir(context), name)
FileUtils.delete(dir)
return !dir.exists() && !java.nio.file.Files.isSymbolicLink(dir.toPath())
}
fun removeOlder(context: Context, tool: Tool) {
installedAll(context, tool).dropLast(1).forEach {
if (File(toolsDir(context), it).deleteRecursively()) ComponentsManager.forgetProton(context, it)
if (deleteTool(context, it)) ComponentsManager.forgetProton(context, it)
}
}
// DroidDeck-Bionic: the default and the game picks name the installed build, also when they were left on one an
// older app deleted without moving them.
private fun keepBionicCurrent(context: Context) {
if (SessionState.running) return
val tool = tools.firstOrNull { it.id == BIONIC } ?: return
val newest = installedAll(context, tool).lastOrNull() ?: return
runCatching { ProtonDefault.keepBionicCurrent(context, tool.prefix, newest) }.onFailure { Log.w(TAG, "bionic default and picks", it) }
}
private fun replaceOlder(context: Context, tool: Tool) {
val all = installedAll(context, tool)
val newest = all.lastOrNull() ?: return
@@ -189,7 +215,9 @@ object ProtonExtras {
if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue
if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue
if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue
if (File(toolsDir(context), old).deleteRecursively()) ComponentsManager.forgetProton(context, old)
// DroidDeck-Bionic only: the guest finds no default for a deleted Bionic build and falls back to DroidDeck-Proton
if (tool.id == BIONIC && runCatching { ProtonDefault.moveDefault(context, setOf(old), newest) }.onFailure { Log.w(TAG, "default pick of $old", it) }.isFailure) continue
if (deleteTool(context, old)) ComponentsManager.forgetProton(context, old)
else Log.w(TAG, "could not remove $old")
}
} finally {
@@ -308,7 +336,7 @@ object ProtonExtras {
archive.delete()
unqueue(context, tool)
record(context, tool, placed, asset.tag)
if (tool.id == OWN) replaceOlder(context, tool)
if (tool.id == OWN || tool.id == BIONIC) replaceOlder(context, tool)
if (EsyncPacks.enabled(context)) {
onProgress(context.getString(R.string.esync_fetching), -1)
try {
@@ -393,7 +421,7 @@ object ProtonExtras {
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
val candidates = (0 until array.length()).asSequence()
.mapNotNull { array.optJSONObject(it) }
.filter { !it.optBoolean("draft", false) && !it.optBoolean("prerelease", false) }
.filter { !it.optBoolean("draft", false) && (tool.prereleases || !it.optBoolean("prerelease", false)) }
return candidates.firstNotNullOfOrNull { assetOf(tool, it) }
}
@@ -12,6 +12,9 @@ object SessionDisplay {
const val FOLLOW_SCALE_MAX = 8f
private const val FOLLOW_SCALED_PREFIX = "follow/"
const val LINK_LANDSCAPE = "link/landscape"
const val LINK_PORTRAIT = "link/portrait"
const val DEFAULT_RESOLUTION = "720p"
private val PRESET_HEIGHTS = listOf(720, 900, 1080)
@@ -35,6 +38,23 @@ object SessionDisplay {
else -> null
}
fun isLink(choice: String): Boolean = choice == LINK_LANDSCAPE || choice == LINK_PORTRAIT
fun orientCustom(choice: String, portrait: Boolean): String {
val parts = choice.split('x').map { it.toIntOrNull() }
if (parts.size != 2 || parts.any { it == null || it <= 0 }) return choice
val width = parts[0]!!
val height = parts[1]!!
return if ((portrait && width > height) || (!portrait && height > width)) "${height}x$width" else choice
}
fun effectiveChoice(landscape: String, portrait: String, forPortrait: Boolean): String {
val own = if (forPortrait) portrait else landscape
if (!isLink(own)) return own
val other = if (forPortrait) landscape else portrait
return if (isLink(other)) DEFAULT_RESOLUTION else orientCustom(other, forPortrait)
}
fun screenSize(panel: Pair<Int, Int>): Pair<Int, Int> =
(maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv())
@@ -69,8 +89,12 @@ object SessionDisplay {
const val UNFOLDED_MIN_DP = 600
fun unfoldedGameHeight(width: Int, height: Int, tabRow: Int = 0): Int =
(minOf(width * 9 / 16, (height * UNFOLDED_MAX_GAME_SHARE).toInt()) - tabRow.coerceAtLeast(0)).coerceAtLeast(0) and 1.inv()
fun unfoldedGameHeight(width: Int, height: Int, tabRow: Int = 0, aspect: Float = 0f): Int {
val row = tabRow.coerceAtLeast(0)
val cap = (height * UNFOLDED_MAX_GAME_SHARE).toInt()
if (aspect > 0f && aspect < 16f / 9f) return minOf((width / aspect).toInt(), cap - row).coerceAtLeast(0) and 1.inv()
return (minOf(width * 9 / 16, cap) - row).coerceAtLeast(0) and 1.inv()
}
fun unfoldedControlsWanted(
enabled: Boolean,
@@ -180,6 +180,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-flatpak-run" to "usr/local/bin/droiddeck-flatpak-run",
"usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run",
"usr/local/bin/droiddeck-appimage-exec" to "usr/local/bin/droiddeck-appimage-exec",
"usr/local/bin/droiddeck-curseforge" to "usr/local/bin/droiddeck-curseforge",
"usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run",
"usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open",
"usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run",
@@ -287,6 +288,7 @@ object SessionFiles {
File(root, "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json").delete()
LegacyNames.migrateRootfs(root)
ComponentsManager.migrateLaunchDir(context)
runCatching { ComponentsManager.migrateBattleNetFex(context) }.onFailure { Log.w(TAG, "Battle.net FEX selection", it) }
EsyncPacks.stageBundled(context, root)
val directAudio = arrayOf(
"aarch64-unix/winedirectaudio.so",
@@ -85,6 +85,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("launcherFullscreen", on).apply()
}
fun controllerHaptics(context: Context): Boolean = prefs(context).getBoolean("controllerHaptics", true)
fun setControllerHaptics(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("controllerHaptics", on).apply()
}
fun blackFrameInsertion(context: Context): Boolean = prefs(context).getBoolean("blackFrameInsertion", false)
fun setBlackFrameInsertion(context: Context, on: Boolean) {
@@ -419,6 +425,18 @@ object SessionPrefs {
e.remove("gameStoresEnabled").remove("soundtracksEnabled").remove("agentTab").putInt("navTabLayout", version).apply()
}
fun drawerPageOrder(context: Context): List<String> = idList(prefs(context).getString("drawerPageOrder", null))
fun setDrawerPageOrder(context: Context, order: List<String>) {
prefs(context).edit().putString("drawerPageOrder", order.joinToString(",")).apply()
}
fun drawerPageHidden(context: Context): Set<String> = idList(prefs(context).getString("drawerPageHidden", null)).toSet()
fun setDrawerPageHidden(context: Context, keys: Set<String>) {
prefs(context).edit().putString("drawerPageHidden", keys.joinToString(",")).apply()
}
fun setNavTabHidden(context: Context, keys: Set<String>) {
prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply()
}
@@ -596,6 +614,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("backHold", on).apply()
}
fun dockedMenuController(context: Context): Boolean = prefs(context).getBoolean("dockedMenuController", false)
fun setDockedMenuController(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("dockedMenuController", on).apply()
}
fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false)
fun setBackActionsInverted(context: Context, inverted: Boolean) {
@@ -1296,14 +1320,31 @@ object SessionPrefs {
private fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", 720)
fun resolutionChosen(context: Context, mode: String): Boolean =
fun resolutionChosen(context: Context, mode: String, portrait: Boolean = false): Boolean =
prefs(context).contains("displayResolution.$mode") ||
prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null
prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null ||
(portrait && prefs(context).contains("displayResolution.portrait.$mode"))
fun resolutionChoice(context: Context, mode: String, panel: Pair<Int, Int>): String {
fun resolutionChoice(context: Context, mode: String, panel: Pair<Int, Int>, portrait: Boolean = false): String =
SessionDisplay.effectiveChoice(
resolutionStored(context, mode, panel, false), resolutionStored(context, mode, panel, true), portrait)
fun resolutionStored(context: Context, mode: String, panel: Pair<Int, Int>, portrait: Boolean): String {
if (!portrait) return landscapeResolutionStored(context, mode, panel)
val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE
if (value == SessionDisplay.LINK_LANDSCAPE || value == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(value) ||
SessionDisplay.presetHeight(value) != null) return value
return parseOrientedResolution(value)?.let { "${it.first}x${it.second}" } ?: SessionDisplay.LINK_LANDSCAPE
}
fun parseOrientedResolution(text: String): Pair<Int, Int>? =
parseResolution(text) ?: text.trim().split('x', 'X', '×', '*').takeIf { it.size == 2 }
?.let { parseResolution("${it[1]}x${it[0]}") }?.let { it.second to it.first }
private fun landscapeResolutionStored(context: Context, mode: String, panel: Pair<Int, Int>): String {
val saved = prefs(context)
saved.getString("displayResolution.$mode", null)?.let { value ->
if (value == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(value) ||
if (value == SessionDisplay.MATCH_SCREEN || value == SessionDisplay.LINK_PORTRAIT || SessionDisplay.isFollow(value) ||
SessionDisplay.presetHeight(value) != null) return value
parseResolution(value)?.let { return "${it.first}x${it.second}" }
}
@@ -1315,13 +1356,22 @@ object SessionPrefs {
else "${legacy.first}x${legacy.second}"
}
fun setResolutionChoice(context: Context, mode: String, choice: String) {
val value = if (choice == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(choice) ||
fun setResolutionChoice(context: Context, mode: String, choice: String, portrait: Boolean = false) {
val link = if (portrait) SessionDisplay.LINK_LANDSCAPE else SessionDisplay.LINK_PORTRAIT
val value = if (choice == link || choice == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(choice) ||
SessionDisplay.presetHeight(choice) != null) choice else {
val size = requireNotNull(parseResolution(choice)) { "Invalid resolution" }
val size = requireNotNull(if (portrait) parseOrientedResolution(choice) else parseResolution(choice)) { "Invalid resolution" }
"${size.first}x${size.second}"
}
prefs(context).edit().putString("displayResolution.$mode", value).apply()
val panel = SessionDisplay.panelSize(context)
val landscapeStored = resolutionStored(context, mode, panel, false)
val portraitStored = resolutionStored(context, mode, panel, true)
val edit = prefs(context).edit()
if (value == link && SessionDisplay.isLink(if (portrait) landscapeStored else portraitStored)) {
val concrete = SessionDisplay.effectiveChoice(landscapeStored, portraitStored, !portrait)
edit.putString(if (portrait) "displayResolution.$mode" else "displayResolution.portrait.$mode", concrete)
}
edit.putString(if (portrait) "displayResolution.portrait.$mode" else "displayResolution.$mode", value).apply()
}
fun fexPreset(context: Context): String = prefs(context).getString("fexPreset", DEFAULT_FEX_PRESET) ?: DEFAULT_FEX_PRESET
@@ -1960,7 +2010,7 @@ object SessionPrefs {
fun displayMode(context: Context, mode: String, program: String?): String =
if (mode == SessionService.MODE_RUN && com.droiddeck.launcher.runtime.UserApps.launches(program) &&
resolutionChosen(context, SessionService.MODE_DESKTOP)) SessionService.MODE_DESKTOP
(resolutionChosen(context, SessionService.MODE_DESKTOP) || resolutionChosen(context, SessionService.MODE_DESKTOP, true))) SessionService.MODE_DESKTOP
else prefMode(mode)
fun pipAutoEnter(context: Context): Boolean = prefs(context).getBoolean("pipAutoEnter", true)
@@ -589,7 +589,10 @@ class SessionService : Service() {
val sessionDir = openSessionFolder()
try {
SessionEvents.step("game-environment") { GameEnvironmentStore.publish(this) }
SessionEvents.step("game-environment") {
com.droiddeck.launcher.runtime.BattleNet.ensureDefaults(this, SessionState.program)
GameEnvironmentStore.publish(this)
}
} catch (e: Exception) {
Log.e(TAG, "could not publish the game environment", e)
failSession(gen, "GAME_ENVIRONMENT_FAILED", getString(R.string.session_game_environment_failed), -1)
@@ -1030,6 +1033,9 @@ class SessionService : Service() {
)
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
// DroidDeck-Bionic games load an Android driver build; this is the one the display uses, for a runtime driver
// that has none.
guest.add("DROIDDECK_DISPLAY_DRIVER=" + com.droiddeck.launcher.gpu.TurnipDriver(this).effectiveId())
if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) {
guest.add("XWAYLAND_NO_GLAMOR=1")
Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)")
@@ -1951,11 +1957,6 @@ class SessionService : Service() {
}
return
}
if (path == com.droiddeck.launcher.runtime.BattleNet.FEX_REQUEST) {
File(dir, path).delete()
com.droiddeck.launcher.runtime.BattleNet.answerFexRequest(this@SessionService, dir)
return
}
if (path != null && path.startsWith("desktop-import-") && path.endsWith(".request")) {
val request = File(dir, path)
val text = runCatching { request.readText() }.getOrNull() ?: return
@@ -133,6 +133,7 @@ object SessionState {
@Volatile var padBridge: com.droiddeck.launcher.input.PadBridge? = null
@Volatile var secondScreenMode = com.droiddeck.launcher.input.SecondScreenMode.NONE
@Volatile var bottomMenu = false
@Volatile var secondScreenDisplay = -1
@Volatile var secondScreenAutoOpened = false
@Volatile var secondScreenProvisional = false
@@ -12,13 +12,13 @@ object SettingsReset {
private const val TAG = "SettingsReset"
internal val SESSION_KEYS = setOf(
"orientation", "launcherFullscreen", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
"orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
"dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
"soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
"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", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
@@ -28,20 +28,26 @@ internal class StoreArchiveUnpacker(
private val logName: String,
) {
var work: File = File("")
var limit = Long.MAX_VALUE
fun unpack(archive: File, filename: String, handle: DownloadQueue.JobHandle) {
class TooLarge : java.io.IOException()
fun unpack(archive: File, filename: String, handle: DownloadQueue.JobHandle) =
unpack(archive, filename, { done, total -> handle.stageProgress(done, total) }, handle::log)
fun unpack(archive: File, filename: String, progress: (Long, Long) -> Unit, log: (String) -> Unit) {
when (val kind = ItchArchives.kind(archive, filename)) {
"zip" -> unzip(archive, handle)
"zip" -> unzip(archive, progress, log)
"7z" -> try {
sevenZip(archive, handle)
sevenZip(archive, progress, log)
} catch (e: MemoryLimitException) {
handle.log("$label: ${archive.name} needs more memory than the app has, unpacking it in the runtime")
unrar(archive, handle, kind)
log("$label: ${archive.name} needs more memory than the app has, unpacking it in the runtime")
unrar(archive, progress, log, kind)
}
"rar" -> unrar(archive, handle, kind)
"rar" -> unrar(archive, progress, log, kind)
"exe" -> copy(archive, File(work, filename.ifBlank { "game.exe" }))
"tar" -> untar(archive, null, handle)
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
"tar" -> untar(archive, null, progress, log)
"gz", "bz2", "xz" -> untar(archive, kind, progress, log) ?: single(archive, kind, progress, log)
else -> copy(archive, File(work, filename.ifBlank { "game" }))
}
}
@@ -53,7 +59,7 @@ internal class StoreArchiveUnpacker(
return if (path == root || path.startsWith(root + File.separator)) file else null
}
private fun unrar(archive: File, handle: DownloadQueue.JobHandle, kind: String) {
private fun unrar(archive: File, progress: (Long, Long) -> Unit, log: (String) -> Unit, kind: String) {
if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(unsupported, kind))
val binds = if (listOf(app.filesDir, app.cacheDir).any { work.absolutePath.startsWith(it.absolutePath + "/") }) null
else listOf(work.absolutePath)
@@ -62,23 +68,28 @@ internal class StoreArchiveUnpacker(
if (!line.startsWith("proot ")) onLine(line)
}
var entries = 0L
bsdtar(listOf("-tf", archive.absolutePath)) { entries++ }
var size = 0L
bsdtar(listOf("-tvf", archive.absolutePath)) { line ->
entries++
size += LISTED_SIZE.find(line)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
}
if (size > limit) throw TooLarge()
var done = 0L
val tail = ArrayDeque<String>()
val code = bsdtar(listOf("-xvf", archive.absolutePath, "-C", work.absolutePath)) { line ->
if (line.startsWith("x ")) handle.stageProgress(++done, entries) else {
if (line.startsWith("x ")) progress(++done, entries) else {
if (tail.size == 5) tail.removeFirst()
tail.addLast(line)
}
}
if (cancelled.get()) return
if (code != 0) {
handle.log("$label: bsdtar exited $code: ${tail.joinToString(" | ")}")
log("$label: bsdtar exited $code: ${tail.joinToString(" | ")}")
throw IllegalStateException(app.getString(extractFailed, code))
}
}
private fun sevenZip(archive: File, handle: DownloadQueue.JobHandle) {
private fun sevenZip(archive: File, progress: (Long, Long) -> Unit, log: (String) -> Unit) {
val total = archive.length()
var written = 0L
val buffer = ByteArray(64 * 1024)
@@ -90,7 +101,7 @@ internal class StoreArchiveUnpacker(
val entry = seven.nextEntry ?: break
val file = target(entry.name)
if (file == null) {
handle.log("$label: skipped an entry outside the game folder")
log("$label: skipped an entry outside the game folder")
continue
}
if (entry.isDirectory) {
@@ -105,7 +116,8 @@ internal class StoreArchiveUnpacker(
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
if (written > limit) throw TooLarge()
progress(written, total)
}
}
}
@@ -113,7 +125,7 @@ internal class StoreArchiveUnpacker(
}
}
private fun untar(archive: File, codec: String?, handle: DownloadQueue.JobHandle): Unit? {
private fun untar(archive: File, codec: String?, progress: (Long, Long) -> Unit, log: (String) -> Unit): Unit? {
val total = archive.length()
var written = 0L
var entries = 0
@@ -134,7 +146,7 @@ internal class StoreArchiveUnpacker(
entries++
val file = target(entry.name)
if (file == null) {
handle.log("$label: skipped an entry outside the game folder")
log("$label: skipped an entry outside the game folder")
continue
}
if (entry.isDirectory) {
@@ -149,7 +161,8 @@ internal class StoreArchiveUnpacker(
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
if (written > limit) throw TooLarge()
progress(written, total)
}
}
}
@@ -163,7 +176,7 @@ internal class StoreArchiveUnpacker(
return null
}
private fun single(archive: File, codec: String, handle: DownloadQueue.JobHandle) {
private fun single(archive: File, codec: String, progress: (Long, Long) -> Unit, log: (String) -> Unit) {
val name = archive.name.substringBeforeLast('.')
val file = target(name.ifBlank { "game" }) ?: throw IllegalStateException("archive")
file.parentFile?.mkdirs()
@@ -184,7 +197,8 @@ internal class StoreArchiveUnpacker(
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
if (written > limit) throw TooLarge()
progress(written, total)
}
}
}
@@ -196,7 +210,7 @@ internal class StoreArchiveUnpacker(
FileInputStream(source).use { input -> FileOutputStream(target).use { out -> input.copyTo(out, 128 * 1024) } }
}
private fun unzip(archive: File, handle: DownloadQueue.JobHandle) {
private fun unzip(archive: File, progress: (Long, Long) -> Unit, log: (String) -> Unit) {
val total = archive.length()
var written = 0L
val buffer = ByteArray(64 * 1024)
@@ -205,7 +219,7 @@ internal class StoreArchiveUnpacker(
if (cancelled.get()) return
val target = target(entry.name)
if (target == null) {
handle.log("$label: skipped an entry outside the game folder")
log("$label: skipped an entry outside the game folder")
continue
}
if (entry.isDirectory) {
@@ -221,11 +235,16 @@ internal class StoreArchiveUnpacker(
if (read < 0) break
out.write(buffer, 0, read)
written += read
handle.stageProgress(written, total)
if (written > limit) throw TooLarge()
progress(written, total)
}
}
}
}
}
}
private companion object {
val LISTED_SIZE = Regex("""^\S+\s+\d+\s+\S+\s+\S+\s+(\d+)\s""")
}
}
@@ -12,8 +12,11 @@ object StoreLaunch {
const val EPIC_CODE = ".droiddeck-epic-code"
const val EPIC_ARGS = ".droiddeck-epic-args"
const val UBISOFT_LAUNCH = ".droiddeck-ubisoft.json"
private const val UBISOFT_SERVICE = "Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
const val EPIC_PARENT = "Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe"
/** DroidDeck-Bionic's Wine has Android's root on Z:; that tool sets this to the guest's root as its Wine names it. */
const val GUEST_ROOT = "DROIDDECK_GUEST_ROOT"
private const val ROOT_VAR = "DD_R"
private const val UBISOFT_SERVICE = "%$ROOT_VAR%\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
const val EPIC_PARENT = "%$ROOT_VAR%\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe"
/** Per-game environment switch: 1 starts any Epic game under [EPIC_PARENT], 0 never does. */
const val EPIC_PARENT_SWITCH = "DD_EPIC_PARENT"
/** Epic app names whose launchers treat the game as unowned unless a process named EpicGamesLauncher.exe started it. */
@@ -47,6 +50,10 @@ object StoreLaunch {
for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\""
val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) }
val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "")
if (sidecar.store == Store.EPIC || sidecar.store == Store.UBISOFT) {
lines += "set \"$ROOT_VAR=Z:\""
lines += "if defined $GUEST_ROOT set \"$ROOT_VAR=%$GUEST_ROOT%\""
}
if (sidecar.store == Store.EPIC) {
lines += "set \"$PARENT_VAR=${if (sidecar.id in EPIC_PARENT_TITLES) "1" else ""}\""
lines += "if \"%$EPIC_PARENT_SWITCH%\"==\"1\" set \"$PARENT_VAR=1\""
@@ -137,7 +144,6 @@ object StoreLaunch {
if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null)
val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true)
if (sidecar.store == Store.UBISOFT && sidecar.launcher == LAUNCHER && !wrongExe) return sidecar
val metadataExe = if (sidecar.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarMetadata.find(folder)?.exe
?.takeIf { File(folder, it).isFile && File(folder, it).canonicalPath.startsWith(folder.canonicalPath + File.separator) } else null
val exe = metadataExe ?: if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe
@@ -311,6 +311,7 @@ internal fun AppDialog(
width: Dp? = null, fitContent: Boolean = false,
back: (() -> Unit)? = null,
scrollable: Boolean = true,
fillHeight: Boolean = false,
scrollState: androidx.compose.foundation.ScrollState = rememberScrollState(),
side: (@Composable () -> Unit)? = null,
sideRoom: Dp = 0.dp,
@@ -348,6 +349,7 @@ internal fun AppDialog(
},
)
.heightIn(max = (LocalConfiguration.current.screenHeightDp - 24).dp)
.then(if (fillHeight) Modifier.fillMaxHeight() else Modifier)
.shadow(24.dp, Shape16, ambientColor = Color.Black, spotColor = Color.Black)
.clip(Shape16)
.background(pal.surfaceVariant.copy(alpha = 0.97f))
@@ -358,7 +360,7 @@ internal fun AppDialog(
.then(if (scrollable) Modifier.verticalScroll(scrollState) else Modifier)
.padding(horizontal = 18.dp, vertical = 16.dp),
) {
content()
androidx.compose.runtime.CompositionLocalProvider(LocalRevealChecked provides true) { content() }
if (side != null && !beside) side()
}
}
@@ -1,29 +1,33 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.widget.Toast
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
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.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Icon
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
@@ -34,19 +38,37 @@ import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.CurseForgeApp
import com.droiddeck.launcher.runtime.UserApps
import com.droiddeck.launcher.runtime.WowAddonCatalog
import com.droiddeck.launcher.runtime.WowAddons
import com.droiddeck.launcher.session.BackgroundSession
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
@@ -62,8 +84,103 @@ private class AddonResults {
var more by mutableStateOf(false)
}
private enum class AddonStatus { INSTALL, UPDATE, INSTALLED }
private enum class AddonSource { WOWI, CURSE }
private class CurseState(val notice: Int? = null) : Exception()
private class CurseLink(val app: UserApps.App) {
class Linked(val inspector: String, val guid: String)
private val lock = Object()
@Volatile private var closed = false
private var held = false
private var ownSession: String? = null
private var started = false
@Volatile private var launching = false
@Volatile private var inspector: String? = null
private val guids = HashMap<String, String>()
fun <T> call(context: Context, target: WowAddons.Target, block: (Linked) -> T): T {
val linked = synchronized(lock) { link(context, target) }
try {
return block(linked)
} catch (e: CurseForgeApp.Failure) {
if (e.gone) synchronized(lock) {
if (inspector == linked.inspector) {
inspector = null
guids.clear()
}
}
throw e
}
}
private fun link(context: Context, target: WowAddons.Target): Linked {
if (closed) throw CurseState()
if (!SessionState.running) {
started = false
launching = false
held = false
ownSession = null
inspector = null
guids.clear()
val args = CurseForgeApp.holdArgs(app) ?: throw CurseState()
ownSession = BackgroundSession.start(context, CurseForgeApp.HELPER, args) ?: throw CurseState()
}
if (closed) throw CurseState()
if (!held) {
held = true
SessionService.holdForSignIn(context, true)
}
val awake = System.currentTimeMillis() + 30_000
while ((SessionState.suspended || SessionState.suspending) && System.currentTimeMillis() < awake) Thread.sleep(250)
val url = inspector ?: run {
launching = true
val done = CurseForgeApp.start(context, app)
when (done.state) {
CurseForgeApp.Start.READY -> {
started = true
inspector = done.inspector
done.inspector ?: throw CurseState()
}
CurseForgeApp.Start.BUSY -> throw CurseState(R.string.addons_curse_busy)
else -> throw CurseState()
}
}
if (closed) throw CurseState()
guids[target.addOns.path]?.let { return Linked(url, it) }
val root = WowAddons.root(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState()
val flavor = WowAddons.flavorDir(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState()
val guid = CurseForgeApp.instance(context, url, root, flavor)
guids[target.addOns.path] = guid
return Linked(url, guid)
}
fun close(context: Context) {
closed = true
Thread {
if (launching) CurseForgeApp.stop(context, app, inspector)
synchronized(lock) {
if (started) CurseForgeApp.stop(context, app, inspector)
val owned = ownSession
if (owned != null) BackgroundSession.stop(context, owned)
else if (held) SessionService.holdForSignIn(context, false)
started = false
launching = false
ownSession = null
held = false
inspector = null
}
}.start()
}
}
private const val PAGES_AHEAD = 8
@Composable
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, onDismiss: () -> Unit) {
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, curseForge: UserApps.App?, onDismiss: () -> Unit) {
val context = LocalContext.current.applicationContext
val scope = rememberCoroutineScope()
val shown = rememberShown(onDismiss)
@@ -72,12 +189,36 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
var text by remember { mutableStateOf("") }
var category by remember { mutableStateOf<WowAddonCatalog.Category?>(null) }
var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) }
val results = remember(text, category, sort, target) { AddonResults() }
var source by remember { mutableStateOf(AddonSource.WOWI) }
val curse = if (source == AddonSource.CURSE) curseForge else null
val link = remember(curseForge?.key) { curseForge?.let(::CurseLink) }
DisposableEffect(link) {
onDispose { link?.close(context) }
}
var notice by remember { mutableStateOf<Int?>(null) }
var curseInstalls by remember { mutableIntStateOf(0) }
val results = remember(text, category, sort, target, curse) { AddonResults() }
val installing = remember { mutableStateMapOf<String, Int>() }
val installed = remember { mutableStateMapOf<String, Boolean>() }
val installed = remember { mutableStateMapOf<String, Pair<String, String>>() }
val categories by produceState(emptyList<WowAddonCatalog.Category>()) {
value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) }
}
val presentKey = curse to target.addOns
val snapshot by produceState(presentKey to emptyMap<String, String?>(), target.addOns, WowAddons.imports, curse, curseInstalls, results.items.isEmpty()) {
val into = target
val key = curse to into.addOns
value = key to withContext(Dispatchers.IO) {
if (curse != null && link != null) runCatching { link.call(context, into) { CurseForgeApp.installed(context, it.inspector, it.guid) }.associateWith { null } }.getOrDefault(emptyMap())
else WowAddons.details(into).mapNotNull { item -> item.wowiId?.let { it to item.version } }.toMap()
}
}
val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: emptyMap()
fun status(addon: WowAddonCatalog.Addon): AddonStatus {
if (addon.id !in present) return AddonStatus.INSTALL
val have = present[addon.id]
val latest = installed[installKey(addon, target)]?.takeIf { it.first == addon.summary }?.second ?: addon.summary
return if (have == null || latest.isBlank() || WowAddonCatalog.sameVersion(have, latest)) AddonStatus.INSTALLED else AddonStatus.UPDATE
}
fun load(page: Int) {
if (results.loading) return
results.loading = true
@@ -86,10 +227,16 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
val words = text
val cat = category?.id
val order = sort
val via = link?.takeIf { curse != null }
notice = null
scope.launch {
val got = withContext(Dispatchers.IO) {
runCatching { WowAddonCatalog.search(context, WowAddonCatalog.Query(words, cat, WowAddonCatalog.client(into), order), page) }
runCatching {
if (via != null) via.call(context, into) { CurseForgeApp.search(context, it.inspector, it.guid, words, order, page) }
else WowAddonCatalog.search(context, WowAddonCatalog.Query(words, cat, WowAddonCatalog.client(into), order), page)
}
}
if (results.items.isEmpty()) notice = (got.exceptionOrNull() as? CurseState)?.notice
got.onSuccess {
if (page == 0) results.items.clear()
results.items.addAll(it.items.filter { addon -> results.items.none { seen -> seen.id == addon.id } })
@@ -106,6 +253,27 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
fun install(addon: WowAddonCatalog.Addon) {
val key = installKey(addon, target)
if (key in installing) return
val via = link?.takeIf { curse != null }
if (via != null) {
val into = target
installing[key] = 0
scope.launch {
val done = withContext(Dispatchers.IO) { runCatching { via.call(context, into) { CurseForgeApp.install(context, it.inspector, it.guid, addon.id) } } }
installing.remove(key)
val ok = done.getOrNull() == true
if (ok) {
WowAddons.changed()
curseInstalls++
}
val message = when {
ok -> context.resources.getQuantityString(R.plurals.main_addons_imported, 1, 1, into.flavor)
else -> (done.exceptionOrNull() as? CurseState)?.notice?.let(context::getString)
?: context.getString(R.string.stores_dl_failed_reason, done.exceptionOrNull()?.message ?: addon.name)
}
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
}
return
}
if (SessionState.running) {
Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show()
return
@@ -115,48 +283,105 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
scope.launch {
val message = withContext(Dispatchers.IO) { installAddon(context, addon, into) { pct -> scope.launch { if (key in installing) installing[key] = pct } } }
installing.remove(key)
if (message.second) installed[key] = true
message.second?.let { installed[key] = addon.summary to it }
Toast.makeText(context, message.first, Toast.LENGTH_LONG).show()
}
}
val sourceName = stringResource(R.string.addons_source_wowi)
AppDialog(shown, close, "addonBrowser", wide = true, scrollable = false) {
DialogTitleRow(stringResource(R.string.addons_download), close)
ModeHeader(sourceName, text, { text = it }, stringResource(R.string.stores_search_catalog, sourceName)) {
BrowseChip(stringResource(R.string.addons_source_curse), false) {
runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(WowAddonCatalog.curseForgeUrl(text))).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
}
val sourceName = stringResource(if (curse != null) R.string.addons_source_curse else R.string.addons_source_wowi)
val grid = rememberLazyGridState()
LaunchedEffect(results, grid) {
snapshotFlow { grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index to grid.layoutInfo.totalItemsCount }.collect { (last, total) ->
if (last != null && results.more && results.failed == null && last >= total - PAGES_AHEAD) load(results.page + 1)
}
ChipRow {
}
val firstAction = remember(results) { FocusRequester() }
val inputMode = LocalInputModeManager.current
var searching by remember { mutableStateOf(false) }
LaunchedEffect(results, results.items.isNotEmpty()) {
if (results.items.isNotEmpty() && !searching && inputMode.inputMode == InputMode.Keyboard) focusSoon { firstAction }
}
AppDialog(shown, close, "addonBrowser", wide = true, maxWidth = 980.dp, scrollable = false, fillHeight = true, modifier = Modifier.releaseTextFieldOnTap()) {
val sortChip: @Composable () -> Unit = {
BrowseDropdown(sortLabel(sort)) { first, done ->
WowAddonCatalog.Sort.entries.forEachIndexed { index, option ->
MenuItem(sortLabel(option), sort == option, focusRequester = if (index == 0) first else null) { sort = option; done() }
}
}
if (categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done ->
}
val sourceChip: @Composable () -> Unit = {
if (curseForge != null) BrowseDropdown(sourceName) { first, done ->
MenuItem(stringResource(R.string.addons_source_wowi), source == AddonSource.WOWI, focusRequester = first) { source = AddonSource.WOWI; done() }
MenuItem(stringResource(R.string.addons_source_curse), source == AddonSource.CURSE) { source = AddonSource.CURSE; done() }
}
}
val categoryChip: @Composable () -> Unit = {
if (curse == null && categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done ->
MenuItem(stringResource(R.string.addons_category_all), category == null, focusRequester = first) { category = null; done() }
categories.forEach { option -> MenuItem(option.name, category?.id == option.id) { category = option; done() } }
}
}
val flavorChip: @Composable () -> Unit = {
if (targets.size > 1) BrowseDropdown(target.flavor) { first, done ->
targets.forEachIndexed { index, option ->
MenuItem(option.flavor, option.addOns == target.addOns, focusRequester = if (index == 0) first else null) { target = option; done() }
}
}
}
val height = (LocalConfiguration.current.screenHeightDp * 0.62f).dp
val search: @Composable (Modifier) -> Unit = { modifier ->
AdbTextField(
value = text, onValueChange = { text = it }, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search,
placeholder = stringResource(R.string.stores_search_catalog, sourceName), compact = true, showLabel = false, modifier = modifier, onFocusChange = { searching = it },
)
}
val closeButton: @Composable () -> Unit = {
SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.error, onClick = close)
}
BoxWithConstraints(Modifier.fillMaxWidth()) {
if (maxWidth >= 640.dp) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
search(Modifier.weight(1f))
sourceChip()
sortChip()
categoryChip()
flavorChip()
closeButton()
} else Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
search(Modifier.weight(1f))
closeButton()
}
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.horizontalScroll(rememberScrollState()),
) {
sourceChip()
sortChip()
categoryChip()
flavorChip()
}
}
}
val thumb = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
LazyVerticalGrid(
GridCells.Adaptive(libraryTileWidth() + 40.dp), Modifier.fillMaxWidth().height(height),
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
GridCells.Adaptive(400.dp), Modifier.fillMaxWidth().weight(1f).scrollThumb(grid, thumb), state = grid,
contentPadding = PaddingValues(end = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(6.dp),
) {
items(results.items, key = { it.id }) { addon ->
AddonCard(addon, installing[installKey(addon, target)], installed[installKey(addon, target)] == true) { install(addon) }
val key = installKey(addon, target)
AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier) { install(addon) }
}
item(key = "tail", span = { GridItemSpan(maxLineSpan) }) {
Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {
item(span = { GridItemSpan(maxLineSpan) }) {
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
when {
results.loading -> LinearProgressIndicator(Modifier.fillMaxWidth())
results.failed != null -> BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(if (results.items.isEmpty()) 0 else results.page + 1) }
results.more -> BrowseChip(stringResource(R.string.stores_itch_load_more), false) { load(results.page + 1) }
results.failed != null && notice != null -> {
Text(stringResource(notice!!), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(0) }
}
results.failed != null -> {
Text(stringResource(R.string.addons_unreachable, sourceName), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(if (results.items.isEmpty()) 0 else results.page + 1) }
}
results.items.isEmpty() -> Text(stringResource(R.string.addons_none_found), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
@@ -166,29 +391,45 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
}
@Composable
private fun AddonCard(addon: WowAddonCatalog.Addon, progress: Int?, done: Boolean, onInstall: () -> Unit) {
private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onInstall: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
val hot = rememberHot(src)
val shape = androidx.compose.foundation.shape.RoundedCornerShape(10.dp)
Column(
Modifier.fillMaxWidth().clip(shape).glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onInstall)
.controllerConfirm(onClick = onInstall),
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().clip(Shape12).background(colors.surface.copy(alpha = 0.6f)).border(1.dp, pal.line, Shape12)
.padding(start = 8.dp, end = 8.dp, top = 6.dp, bottom = 6.dp),
) {
ArtCard(addon.name, addon.thumb, null, null, hot, capsule = false, chip = progress?.let { "$it%" }) {
if (done) Icon(Icons.Filled.Check, stringResource(R.string.stores_installed_chip), tint = pal.good, modifier = Modifier.height(11.dp))
else Text(stringResource(if (progress != null) R.string.store_installing else R.string.store_install), fontSize = 10.sp, color = pal.signal, maxLines = 1)
Box(Modifier.size(44.dp).clip(Shape12).background(artBrush(hueOf(addon.name)))) {
if (addon.thumb != null) AsyncImage(model = addon.thumb, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
}
Column(Modifier.weight(1f)) {
Text(addon.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
listOf(addon.author, addon.summary, formatCount(addon.downloads)).filter { it.isNotEmpty() }.joinToString(" · "),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
val size = action
when {
progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = size, progress = progress / 100f, onClick = onInstall)
status == AddonStatus.INSTALLED -> SecondaryButton(stringResource(R.string.stores_installed_chip), enabled = false, compact = true, modifier = size) {}
else -> PrimaryButton(stringResource(if (status == AddonStatus.UPDATE) R.string.common_update else R.string.store_install), compact = true, modifier = size, onClick = onInstall)
}
Text(
listOf(addon.author, formatCount(addon.downloads)).filter { it.isNotEmpty() }.joinToString(" · "),
fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
)
}
}
private fun Modifier.scrollThumb(state: LazyGridState, color: Color): Modifier = drawWithContent {
drawContent()
val info = state.layoutInfo
val visible = info.visibleItemsInfo
if (visible.isEmpty() || visible.size >= info.totalItemsCount) return@drawWithContent
val total = info.totalItemsCount.toFloat()
val length = (size.height * visible.size / total).coerceAtLeast(24.dp.toPx())
val top = (size.height - length) * (visible.first().index / (total - visible.size).coerceAtLeast(1f)).coerceIn(0f, 1f)
val width = 3.dp.toPx()
drawRoundRect(color, Offset(size.width - width, top), Size(width, length), CornerRadius(width / 2))
}
@Composable
private fun sortLabel(sort: WowAddonCatalog.Sort): String = stringResource(
when (sort) {
@@ -206,18 +447,18 @@ private fun formatCount(count: Long): String = when {
else -> count.toString()
}
private fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target: WowAddons.Target, progress: (Int) -> Unit): Pair<String, Boolean> {
internal fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target: WowAddons.Target, progress: (Int) -> Unit): Pair<String, String?> {
val zip = File(File(context.cacheDir, "wowaddons"), "download-wowi-${addon.id.filter(Char::isLetterOrDigit)}-${java.util.UUID.randomUUID()}.zip")
return try {
WowAddonCatalog.download(context, addon, zip, progress)
if (SessionState.running) return context.getString(R.string.main_addons_close_session) to false
val names = WowAddons.import(zip, target)
if (names.isEmpty()) context.getString(R.string.main_addons_none, addon.name) to false
else context.resources.getQuantityString(R.plurals.main_addons_imported, names.size, names.size, target.flavor) to true
val version = WowAddonCatalog.download(context, addon, zip, progress) ?: addon.summary
if (SessionState.running) return context.getString(R.string.main_addons_close_session) to null
val names = WowAddons.import(zip, target, WowAddons.Origin(addon.id, version).takeIf { version.isNotBlank() }, context)
if (names.isEmpty()) context.getString(R.string.main_addons_none, addon.name) to null
else context.resources.getQuantityString(R.plurals.main_addons_imported, names.size, names.size, target.flavor) to version
} catch (_: WowAddons.TooLarge) {
context.getString(R.string.main_addons_too_large, addon.name) to false
context.getString(R.string.main_addons_too_large, addon.name) to null
} catch (e: Exception) {
context.getString(R.string.stores_dl_failed_reason, e.message ?: e.javaClass.simpleName) to false
context.getString(R.string.stores_dl_failed_reason, e.message ?: e.javaClass.simpleName) to null
} finally {
zip.delete()
}
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.ui
import android.app.Activity
import android.content.ContextWrapper
import android.os.Build
import android.view.KeyEvent
import android.view.WindowManager
import androidx.activity.compose.LocalActivityResultRegistryOwner
@@ -184,7 +185,11 @@ private fun AgentPageContent(
?: generateSequence(view.context) { (it as? ContextWrapper)?.baseContext }
.filterIsInstance<Activity>().firstOrNull()?.window
val previousMode = window?.attributes?.softInputMode
// A window fitted to the system bars with ADJUST_NOTHING reports no keyboard height to Compose.
// It stays unfitted after the page leaves: fitting it again insets the other pages twice.
val edgeToEdge = visible && hidesPet && !drawer && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
if (visible) window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
if (edgeToEdge) window?.setDecorFitsSystemWindows(false)
onDispose {
if (visible && previousMode != null) window?.setSoftInputMode(previousMode)
}
@@ -230,6 +230,7 @@ internal fun BarButton(
internal val SecondScreenMode.icon: ImageVector get() = when (this) {
SecondScreenMode.NONE -> Icons.Outlined.DesktopAccessDisabled
SecondScreenMode.MENU -> Icons.Outlined.MoreHoriz
SecondScreenMode.KEYBOARD_TRACKPAD -> Icons.Outlined.Keyboard
SecondScreenMode.TERMINAL -> Icons.Outlined.Terminal
SecondScreenMode.DECK_CONTROLS -> Icons.Outlined.SportsEsports
@@ -290,17 +291,11 @@ private fun ScreenPickerMenu(picker: ScreenPicker, open: Boolean, dismiss: () ->
leading = { Icon(painterResource(R.drawable.ic_stat_session), contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(18.dp)) },
focusRequester = first.takeIf { target == null }, modifier = Modifier.testTag("screen-picker-menu"),
) { dismiss(); menu() }
Box(Modifier.fillMaxWidth().padding(vertical = 4.dp).height(1.dp).background(pal.line))
Text(
stringResource(R.string.drawer_second_screen).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp,
color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 10.dp, top = 6.dp, bottom = 4.dp),
)
}
picker.modes.forEach { mode ->
val current = mode == picker.current
MenuItem(
stringResource(mode.label), checked = current && !picker.menuShown,
detail = if (current && picker.menuShown) stringResource(R.string.screen_picker_last_used) else null,
leading = { Icon(mode.icon, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(18.dp)) },
focusRequester = first.takeIf { mode == target }, modifier = Modifier.testTag("screen-picker:${mode.id}"),
) { dismiss(); picker.onPick(mode) }
@@ -526,11 +526,11 @@ fun ComponentsPage(
val availableTitle: @Composable (String) -> String = { l ->
when (l) {
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count(ProtonRow::available))
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot).size)
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot, view?.proton?.dir?.name).size)
}
}
val followed = view?.proton?.let(ComponentUpdates::follows) == true
val moded: (String) -> Boolean = { followed && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
val followed: (String) -> Boolean = { l -> view?.proton?.let { ComponentUpdates.autoFollows(it, l) } == true }
val moded: (String) -> Boolean = { followed(it) && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
val automatic: (String) -> Boolean = { moded(it) && compModes[it] == ComponentUpdates.AUTO }
val installedRows: @Composable ColumnScope.(String, Boolean) -> Unit = { l, right ->
when (l) {
@@ -614,7 +614,7 @@ fun ComponentsPage(
}
}
else -> {
val available = availableRows(l, catalog, snapshot)
val available = availableRows(l, catalog, snapshot, view?.proton?.dir?.name)
if (available.isEmpty()) EmptyLine(if (catalogAt == 0L) stringResource(R.string.comp_refresh_to_list) else stringResource(R.string.comp_nothing_new))
for ((stable, nightly) in available) {
val d = if (nightly != null && nightlyPicked[stable.file] == true) nightly else stable
@@ -974,18 +974,18 @@ private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapsho
o.label.substringAfterLast(" · ", "").ifEmpty { o.label }.let { if (isCurrent) stringResource(R.string.comp_this_build, it) else stringResource(R.string.comp_earlier_build, it) },
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
)
} + (snapshot?.packages ?: emptyList()).filter { it.comp == l }.map { s ->
} + ComponentsManager.forTool(l, view.proton.dir.name, (snapshot?.packages ?: emptyList()).filter { it.comp == l }, st.activeFile) { it.file }.map { s ->
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", !runtimeManaged && s.file == st.activeFile, true, s.file, null)
}
}
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<CatalogItem> {
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<CatalogItem> {
val stored = (snapshot?.packages ?: emptyList()).map { it.file }.toSet()
return catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }
return ComponentsManager.forTool(l, toolDir, catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }) { it.file }
}
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<Pair<CatalogItem, CatalogItem?>> {
val available = availableFor(l, catalog, snapshot)
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<Pair<CatalogItem, CatalogItem?>> {
val available = availableFor(l, catalog, snapshot, toolDir)
val pairs = ComponentsManager.nightlyPairs(available)
val paired = pairs.values.toSet()
return available.filter { it !in paired }.map { it to pairs[it] }
@@ -1201,7 +1201,7 @@ private fun GameComponentOverrides(
}
GamePackageRow(
comp = "fex",
packages = packages,
packages = ComponentsManager.forTool("fex", protonChoice?.dir ?: generalProton?.dir?.name, packages, componentChoices["fex"]) { it.file },
selectedFile = componentChoices["fex"],
open = componentMenu == "fex",
busy = busy,
@@ -1495,22 +1495,26 @@ private fun ChoiceLine(
if (progress != null) ProgressBit(progress)
}
if (!removable) Spacer(Modifier.padding(end = 6.dp).size(44.dp))
else {
val delSrc = remember { MutableInteractionSource() }
val delHot = rememberHot(delSrc)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(end = 6.dp).size(44.dp).clip(ROW_SHAPE)
.background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(delHot, ROW_SHAPE, colors.error)
.hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, onClick = onDelete)
.controllerConfirm(onClick = onDelete),
) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) }
}
else DeleteButton(name, onDelete = onDelete)
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
@Composable
internal fun DeleteButton(name: String, modifier: Modifier = Modifier, enabled: Boolean = true, onDelete: () -> Unit) {
val colors = MaterialTheme.colorScheme
val delSrc = remember { MutableInteractionSource() }
val delHot = rememberHot(delSrc) && enabled
Box(
contentAlignment = Alignment.Center,
modifier = modifier.padding(end = 6.dp).size(44.dp).clip(ROW_SHAPE)
.background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(delHot, ROW_SHAPE, colors.error)
.hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, enabled = enabled, onClick = onDelete)
.controllerConfirm(enabled = enabled, onClick = onDelete),
) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) }
}
@Composable
private fun GetLine(
name: String, detail: String, progress: Int?, enabled: Boolean,
@@ -1625,7 +1629,7 @@ private fun DeviceChip(s: GpuDriversState) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.onGloballyPositioned { at = it.boundsInRoot() }.heightIn(min = 44.dp).paneItem("gpu-device").clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.14f)) else Modifier)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = open)
.controllerConfirm(onClick = open)
@@ -0,0 +1,42 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import android.view.InputDevice
import android.view.KeyEvent
object ControllerHaptics {
private val navKeys = setOf(
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT,
KeyEvent.KEYCODE_BUTTON_A, KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.KEYCODE_BUTTON_R1,
KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2,
)
fun onKey(context: Context, event: KeyEvent) {
if (event.action != KeyEvent.ACTION_DOWN || event.keyCode !in navKeys) return
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A && event.repeatCount > 0) return
val fromController = event.isFromSource(InputDevice.SOURCE_GAMEPAD) ||
event.isFromSource(InputDevice.SOURCE_DPAD) || event.isFromSource(InputDevice.SOURCE_JOYSTICK)
if (!fromController) return
tick(context)
}
fun tick(context: Context) {
val vibrator = if (Build.VERSION.SDK_INT >= 31) {
context.getSystemService(VibratorManager::class.java)?.defaultVibrator
} else {
@Suppress("DEPRECATION") context.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator
} ?: return
if (!vibrator.hasVibrator()) return
if (Build.VERSION.SDK_INT >= 29) {
vibrator.vibrate(VibrationEffect.createPredefined(VibrationEffect.EFFECT_TICK))
} else if (Build.VERSION.SDK_INT >= 26) {
vibrator.vibrate(VibrationEffect.createOneShot(10, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
@Suppress("DEPRECATION") vibrator.vibrate(10)
}
}
}
@@ -309,7 +309,7 @@ private fun DesktopCard(
Column(
Modifier.width(width).paneItem("tile:desktop:$key").then(if (first) Modifier.firstTile() else Modifier)
.graphicsLayer { scaleX = scale; scaleY = scale }
.clip(shape).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.clip(shape).background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button) { onClick(artAt) }
.controllerConfirm { onClick(artAt) }
@@ -477,7 +477,7 @@ private fun UserAppIcon(app: UserApps.App, size: Int) {
}
@Composable
private fun UserAppsProgress() {
internal fun UserAppsProgress() {
val colors = MaterialTheme.colorScheme
val working = UserAppsState.working
Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
@@ -514,7 +514,9 @@ private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions,
Column {
Text(app.name, fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
Text(
(app.repo?.let { stringResource(R.string.user_apps_github_version, it, app.version.orEmpty()) } ?: stringResource(app.kind.label())) +
(app.repo?.let { stringResource(R.string.user_apps_github_version, it, app.version.orEmpty()) }
?: app.version?.takeIf { app.feed != null }?.let { stringResource(R.string.user_apps_github_version, stringResource(app.kind.label()), it) }
?: stringResource(app.kind.label())) +
(if (app.arch == "x86_64" || app.arch == "i386") " · " + stringResource(R.string.app_fex_x86, app.arch) else ""),
fontSize = 14.sp, color = colors.onSurfaceVariant,
)
@@ -526,7 +528,7 @@ private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions,
PrimaryButton(stringResource(R.string.user_apps_open, app.name), enabled = !s.busy, main = true) { a.onUserApp(app) }
BusyChip(s)
SecondaryButton(stringResource(R.string.user_apps_edit), enabled = UserAppsState.working == null) { editing = true }
if (app.repo != null) UpdateButton(app, s)
if (app.updatable) UpdateButton(app, s)
RemoveAppButton(app, enabled = !s.busy && !s.sessionRunning && UserAppsState.working == null) {
UserAppsState.remove(ctx, app); onSelect("desktop")
}
@@ -174,6 +174,7 @@ 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 controllerHaptics: Boolean = true,
val downloadSource: String = DownloadSource.MODE_AUTO,
val downloadMirror: String = "",
val downloadPrefix: String = "",
@@ -279,6 +280,7 @@ class FrontEndActions(
val onLauncherOrientation: (Int) -> Unit = {},
val onHomePage: (String) -> Unit = {},
val onLauncherFullscreen: (Boolean) -> Unit = {},
val onControllerHaptics: (Boolean) -> Unit = {},
val onAnimationsEnabled: (Boolean) -> Unit = {},
val onLowStorageWarning: (Boolean) -> Unit = {},
val onDualScreenMode: (String) -> Unit = {},
@@ -759,24 +761,28 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
focusManager.clearFocus(force = true)
onRailSelect(key)
}, a)
val tabStep = androidx.compose.runtime.rememberUpdatedState { step: Int ->
if (!processSettingsPageVisible) {
val keys = navigationKeys(s)
keys.getOrNull(keys.indexOf(railSelectionNow.value) + step)?.let { key ->
PageSwipe.direction = step
onRailSelect(key)
}
}
}
DisposableEffect(Unit) {
val handler: (Int) -> Unit = { tabStep.value(it) }
MainTabSteps.handler = handler
onDispose { if (MainTabSteps.handler === handler) MainTabSteps.handler = null }
}
CompositionLocalProvider(LocalShowSection provides { key -> selected = key }) {
val swipeContext = androidx.compose.ui.platform.LocalContext.current
remember { com.droiddeck.launcher.core.AppUiPrefs.pageSwipe(swipeContext).also { PageSwipe.on = it } }
val agentKeyboardOpen = openTab == "agent" && WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current) > 0
LauncherLayout(
bottomNavigation && !s.dualScreen, pal.line,
Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() }
.then(if (openTab == "agent") Modifier.imePadding() else Modifier)
.then(if (s.dualScreen) Modifier.onKeyEvent { event ->
val step = dualPageStep(event.nativeKeyEvent) ?: return@onKeyEvent false
if (event.type == KeyEventType.KeyDown && !processSettingsPageVisible) {
val keys = navigationKeys(s)
val at = keys.indexOf(railSelectionNow.value)
keys.getOrNull(at + step)?.let { key ->
PageSwipe.direction = step
onRailSelect(key)
}
}
true
} else Modifier),
.then(if (openTab == "agent") Modifier.imePadding() else Modifier),
navigation = {
if (s.dualScreen || (bottomNavigation && agentKeyboardOpen)) Unit
else if (bottomNavigation) BottomBar(s, railSelection, onRailSelect, onRailFocus, a, railFocus)
@@ -785,7 +791,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
) {
Pane(
s, selected, a, page,
Modifier.fillMaxSize().then(paneFocus).pageSwipe({ !processSettingsPageVisible && appToChooseDisplay == null }) { dir ->
Modifier.fillMaxSize().then(paneFocus).pageSwipe({ !processSettingsPageVisible && appToChooseDisplay == null }, edgeGuard = { !bottomNavigation }) { dir ->
val keys = navigationKeys(s)
val at = keys.indexOf(railSelectionNow.value)
if (at >= 0) keys.getOrNull(at + dir)?.let { key ->
@@ -898,3 +904,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}
}
}
internal object MainTabSteps {
@Volatile var handler: ((Int) -> Unit)? = null
}
@@ -516,6 +516,18 @@ internal fun SetupPanel(
if (s.launcherFullscreen) stringResource(R.string.setup_fullscreen_on) else stringResource(R.string.setup_fullscreen_off),
s.launcherFullscreen,
) { a.onLauncherFullscreen(it) }
ToggleRow(
host, "page-swipe", stringResource(R.string.setup_page_swipe),
stringResource(R.string.setup_page_swipe_hint), PageSwipe.on,
) { on ->
PageSwipe.on = on
com.droiddeck.launcher.core.AppUiPrefs.setPageSwipe(ctx, on)
}
ToggleRow(
host, "controller-haptics", stringResource(R.string.setup_controller_haptics),
stringResource(R.string.setup_controller_haptics_hint),
s.controllerHaptics,
) { a.onControllerHaptics(it) }
if (s.dualScreenDevice) {
val dualModes = listOf(
com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto),
@@ -1154,7 +1166,7 @@ private fun SettingCard(label: String, value: String, id: String, modifier: Modi
verticalArrangement = Arrangement.spacedBy(3.dp),
modifier = modifier.paneItem(id)
.graphicsLayer { scaleX = scale; scaleY = scale }
.then(if (LocalGlass.current != null) Modifier.glass(Shape14, if (hot) 0.04f else 0f) else Modifier.clip(Shape14).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface))
.then(if (LocalGlass.current != null) Modifier.glass(Shape14, if (hot) 0.04f else 0f) else Modifier.clip(Shape14).background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier))
.glideBorder(hot, Shape14, pal.signal, if (LocalGlass.current != null) Color.Transparent else pal.line2)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
@@ -211,6 +211,7 @@ internal fun PrimaryButton(
val pal = LocalPalette.current
val pillMode = LocalPillButtons.current
val btnShape = if (pillMode) CircleShape else Shape12
val outlined = LocalGradientOutline.current && enabled
val frontFocus = if (main) LocalFrontFocus.current else null
if (frontFocus != null) DisposableEffect(Unit) {
frontFocus.primaryAttached++
@@ -234,6 +235,7 @@ internal fun PrimaryButton(
.clip(btnShape)
.background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant)))
.then(if (enabled) Modifier else Modifier.border(1.dp, pal.line2, btnShape))
.then(if (outlined) Modifier.border(2.dp, Brush.linearGradient(listOf(pal.primary2, colors.primary)), btnShape) else Modifier)
.glideBorder(hot, btnShape, pal.signal, hotFillAlpha = 0f)
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = null, enabled = enabled) {
placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) }
@@ -42,6 +42,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.outlined.Download
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Edit
import androidx.compose.material.icons.outlined.VideogameAsset
@@ -54,6 +55,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
@@ -73,6 +75,7 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInParent
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalDensity
@@ -94,7 +97,11 @@ import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.GameRemoval
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.runtime.CurseForgeApp
import com.droiddeck.launcher.runtime.UserApps
import com.droiddeck.launcher.runtime.WowAddonCatalog
import com.droiddeck.launcher.runtime.WowAddons
import com.droiddeck.launcher.store.UserAppsState
import com.droiddeck.launcher.session.GameSaves
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.CatalogItem
@@ -125,6 +132,9 @@ import kotlinx.coroutines.withContext
import java.io.File
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.layout.offset
internal class GameRef(val appId: Int?, val store: Store?, val storeId: String?) {
fun game(games: List<Library.SteamGame>): Library.SteamGame? = when {
@@ -248,12 +258,18 @@ internal fun GameDetail(
color = MaterialTheme.colorScheme.error, maxLines = 3, overflow = TextOverflow.Ellipsis,
)
Spacer(Modifier.height(2.dp))
GameCapsule(scores) { GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead), compactMenu = stacked, inStore = inStore) }
Column {
CompositionLocalProvider(LocalPillButtons provides true, LocalGradientOutline provides true) {
GameActions(store, id, game, item, installed, s, a, Modifier.focusRequester(lead), compactMenu = stacked, inStore = inStore, part = ActionPart.LEAD)
}
Spacer(Modifier.height(LeadGap - ActionGap))
GameCapsule(scores) { GameActions(store, id, game, item, installed, s, a, Modifier, compactMenu = stacked, inStore = inStore, part = ActionPart.REST) }
}
}
}
if (StoresMotion.heroLands) header() else Rise(1) { header() }
if (tab != null) Rise(2) {
Column(Modifier.fillMaxWidth().padding(top = 14.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Column(Modifier.fillMaxWidth().padding(top = ActionGap), verticalArrangement = Arrangement.spacedBy(ActionGap)) {
val labels = tabs.map { t ->
when (t) {
GameTab.ABOUT -> stringResource(R.string.game_tab_about)
@@ -271,15 +287,17 @@ internal fun GameDetail(
focusRequesters = tabs.map { tabFocus.getValue(it) }, bumpers = tabs.size > 1, compact = stacked,
)
Box(Modifier.fillMaxWidth().onFocusChanged { if (inPanel && !it.hasFocus) dropped++; inPanel = it.hasFocus }.testTag("game-tab-${tab.name.lowercase()}")) {
when (tab) {
GameTab.ABOUT -> AboutTab(developer, publisher, releaseDate, description, scores, stacked) {
if (!s.shortcutPicker) GameResourcesRow(title.takeUnless { it == id }.orEmpty(), game)
CompositionLocalProvider(LocalRevealChecked provides false) {
when (tab) {
GameTab.ABOUT -> AboutTab(developer, publisher, releaseDate, description, scores, stacked) {
if (!s.shortcutPicker) GameResourcesRow(title.takeUnless { it == id }.orEmpty(), game)
}
GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) }
GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail)
GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a)
GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, a)
GameTab.INSTALL -> InstallTab(game, installed, item, store)
}
GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) }
GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail)
GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a)
GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, a)
GameTab.INSTALL -> InstallTab(game, installed, item, store)
}
}
}
@@ -342,14 +360,22 @@ private fun StatusChip(text: String, icon: androidx.compose.ui.graphics.vector.I
}
}
private val ActionGap = 12.dp
private val LeadGap = 20.dp
@Composable
private fun GameCapsule(scores: GameScores?, actions: @Composable () -> Unit) {
var noActions by remember { mutableStateOf(false) }
val shown = scores?.takeIf { it.metacritic != Lookup.None || it.hltb != Lookup.None }
val empty = noActions && shown == null
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().glass(RoundedCornerShape(30.dp)).padding(6.dp),
modifier = Modifier.fillMaxWidth().then(if (empty) Modifier else Modifier.padding(top = ActionGap).glass(RoundedCornerShape(30.dp)).padding(6.dp)),
) {
CompositionLocalProvider(LocalPillButtons provides true) { Box(Modifier.weight(1f)) { actions() } }
if (scores != null) CapsuleScores(scores, Modifier.padding(start = 8.dp, end = 10.dp))
CompositionLocalProvider(LocalPillButtons provides true) {
Box(Modifier.weight(1f).onSizeChanged { noActions = it.height == 0 }) { actions() }
}
shown?.let { CapsuleScores(it, Modifier.padding(start = 8.dp, end = 10.dp)) }
}
}
@@ -361,41 +387,95 @@ private fun GameTabBar(
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val scroll = rememberScrollState()
val spans = remember(tabs.size) { androidx.compose.runtime.mutableStateListOf<IntRange?>(*arrayOfNulls<IntRange>(tabs.size)) }
var tabHeight by remember { mutableStateOf(0) }
var viewport by remember { mutableStateOf(0) }
LaunchedEffect(selected, viewport) {
val span = spans.getOrNull(selected) ?: return@LaunchedEffect
if (viewport > 0) scroll.animateScrollTo((span.first + span.last) / 2 - viewport / 2)
}
Row(modifier.fillMaxWidth().glass(CircleShape).padding(4.dp), verticalAlignment = Alignment.CenterVertically) {
if (bumpers) TabBarBumper("LB", stringResource(R.string.widgets_prev_tab), leading = true) { onSelect((selected + tabs.size - 1) % tabs.size) }
tabs.forEachIndexed { i, label ->
val on = i == selected
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val pick = { onSelect(i) }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.weight(1f)
.testTag("tab-$i")
.then(focusRequesters?.getOrNull(i)?.let { Modifier.focusRequester(it) } ?: Modifier)
.clip(CircleShape)
.background(if (on) pal.signal.copy(alpha = 0.3f) else if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(hot, CircleShape, pal.signal, if (on) pal.signal.copy(alpha = 0.5f) else Color.Transparent)
.hoverable(src).selectable(selected = on, interactionSource = src, indication = null, role = Role.Tab, onClick = pick)
.controllerConfirm(onClick = pick)
.padding(horizontal = 6.dp, vertical = if (compact) 8.dp else 10.dp),
) {
Text(
label, fontSize = if (compact) 13.sp else 14.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = if (on || hot) colors.onBackground else colors.onSurfaceVariant,
)
androidx.compose.foundation.layout.BoxWithConstraints(Modifier.weight(1f).clip(if (bumpers) RoundedCornerShape(BumperFlat) else CircleShape).onSizeChanged { viewport = it.width }) {
val share = maxWidth / tabs.size.coerceAtLeast(1)
Box(Modifier.horizontalScroll(scroll)) {
spans.getOrNull(selected)?.takeIf { tabHeight > 0 }?.let { span ->
TabHighlight(span, tabHeight, flatStart = bumpers && selected == 0, flatEnd = bumpers && selected == tabs.lastIndex)
}
Row(verticalAlignment = Alignment.CenterVertically) {
tabs.forEachIndexed { i, label ->
val on = i == selected
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val pick = { onSelect(i) }
val shape = tabShape(flatStart = bumpers && i == 0, flatEnd = bumpers && i == tabs.lastIndex)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.widthIn(min = share)
.onGloballyPositioned { c -> val x = c.positionInParent().x.toInt(); val r = x..(x + c.size.width); if (spans[i] != r) spans[i] = r; tabHeight = c.size.height }
.testTag("tab-$i")
.then(focusRequesters?.getOrNull(i)?.let { Modifier.focusRequester(it) } ?: Modifier)
.clip(shape)
.background(if (hot && !on) pal.signal.copy(alpha = 0.14f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal)
.hoverable(src).selectable(selected = on, interactionSource = src, indication = null, role = Role.Tab, onClick = pick)
.controllerConfirm(onClick = pick)
.padding(horizontal = 12.dp, vertical = if (compact) 8.dp else 10.dp),
) {
Text(
label, fontSize = if (compact) 13.sp else 14.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = if (on || hot) colors.onBackground else colors.onSurfaceVariant,
)
}
}
}
}
}
if (bumpers) TabBarBumper("RB", stringResource(R.string.widgets_next_tab), leading = false) { onSelect((selected + 1) % tabs.size) }
}
}
private val BumperFlat = 7.dp
@Composable
private fun TabHighlight(span: IntRange, height: Int, flatStart: Boolean, flatEnd: Boolean) {
val pal = LocalPalette.current
val density = LocalDensity.current
val spring = Motion.sp<Float>(0.8f, Spring.StiffnessMediumLow)
val x by animateFloatAsState(span.first.toFloat(), spring, label = "tabX")
val width by animateFloatAsState((span.last - span.first).toFloat(), spring, label = "tabWidth")
val start by animateFloatAsState(if (flatStart) 1f else 0f, spring, label = "tabFlatStart")
val end by animateFloatAsState(if (flatEnd) 1f else 0f, spring, label = "tabFlatEnd")
with(density) {
val round = (height / 2f).toDp()
val shape = RoundedCornerShape(
topStart = androidx.compose.ui.unit.lerp(round, BumperFlat, start), topEnd = androidx.compose.ui.unit.lerp(round, BumperFlat, end),
bottomEnd = androidx.compose.ui.unit.lerp(round, BumperFlat, end), bottomStart = androidx.compose.ui.unit.lerp(round, BumperFlat, start),
)
Box(
Modifier.offset { androidx.compose.ui.unit.IntOffset(x.toInt(), 0) }
.size(width.toDp(), height.toDp())
.clip(shape).background(pal.signal.copy(alpha = 0.3f)).border(1.dp, pal.signal.copy(alpha = 0.5f), shape),
)
}
}
private fun tabShape(flatStart: Boolean, flatEnd: Boolean): androidx.compose.ui.graphics.Shape {
if (!flatStart && !flatEnd) return CircleShape
val flat = androidx.compose.foundation.shape.CornerSize(BumperFlat)
val round = androidx.compose.foundation.shape.CornerSize(50)
val start = if (flatStart) flat else round
val end = if (flatEnd) flat else round
return RoundedCornerShape(topStart = start, topEnd = end, bottomEnd = end, bottomStart = start)
}
@Composable
private fun TabBarBumper(label: String, description: String, leading: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val round = 22.dp
val flat = 7.dp
val flat = BumperFlat
val cap = if (leading) RoundedCornerShape(round, flat, flat, round) else RoundedCornerShape(flat, round, round, flat)
Box(
contentAlignment = Alignment.Center,
@@ -427,12 +507,17 @@ private fun GameTitle(title: String, logo: Any?, titleSize: TextUnit) {
)
}
internal enum class ActionPart { ALL, LEAD, REST }
@Composable
internal fun GameActions(
store: Store?, id: String?, game: Library.SteamGame?, item: CatalogItem?, installed: InstalledStoreGame?,
s: FrontEndState, a: FrontEndActions, leadOn: Modifier, compactMenu: Boolean = false, inStore: Boolean = false,
part: ActionPart = ActionPart.ALL,
) {
val ctx = LocalContext.current
val lead = part != ActionPart.REST
val rest = part != ActionPart.LEAD
val storeKey = if (store != null && id != null) "${store.id}:$id" else null
val rawDownload = storeKey?.let { StoresState.download(it) }
val download = rawDownload?.takeIf { it.isActive }
@@ -442,127 +527,133 @@ internal fun GameActions(
Actions {
when {
s.shortcutPicker && game != null -> {
PrimaryButton(stringResource(R.string.game_shortcut_choose), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) { a.onSteamGame(game) }
FileButtons(game, a)
if (lead) PrimaryButton(stringResource(R.string.game_shortcut_choose), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn) { a.onSteamGame(game) }
if (rest) FileButtons(game, a)
}
!cloud && (game != null || installed != null) -> {
val gone = storeKey?.let { StoresState.uninstalling[it] }
val xboxBusy = store == Store.XBOX && id != null && XboxContent.busy(id)
val preparing = (game?.launchKey ?: storeKey)?.let { it in s.preparingGames } == true
PrimaryButton(
if (lead) PrimaryButton(
stringResource(if (preparing) R.string.store_starting else R.string.stores_play),
enabled = !s.busy && !preparing && gone == null && download == null && !xboxBusy && (store != Store.GOG || installed?.sidecar?.isInstalled != false),
main = true, icon = Icons.Filled.PlayArrow, modifier = leadOn,
) {
if (game != null) a.onSteamGame(game) else if (store != null && id != null) launchStoreGame(store, id, s, a)
}
if (game != null) {
if (compactMenu) GameMoreMenu(game, a) else {
FileButtons(game, a)
GameShortcutMenu(game, a)
}
}
if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GAMEJOLT && installed != null) GameJoltUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GAMEJOLT && installed != null) GameJoltVersionButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (inStore && store == Store.GAMEJOLT && installed != null) {
SecondaryButton(stringResource(R.string.stores_view_on, Store.GAMEJOLT.shortLabel)) {
openUrl(ctx, item?.storeUrl.orEmpty().ifBlank { GameJoltApi.pageUrl("game", installed.sidecar.id) })
}
}
if (store == Store.EA && installed != null) EaUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GOG && installed != null) GogMaintenanceActions(installed)
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
if (store == Store.XBOX && installed != null && id != null) {
SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) {
runCatching { XboxBackend.update(ctx, installed) }
.onFailure { StoresState.problems[Store.XBOX] = it.message ?: ctx.getString(R.string.stores_xbox_close_first) }
}
SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) }
}
if (store == Store.BATTLENET) {
if (installed != null && id != null) {
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
if (download != null) {
SteadyDownloadChip(download)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
} else if (BattleNetInstall.updates[id] == true) {
SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) }
if (rest) {
if (game != null) {
if (compactMenu) GameMoreMenu(game, a) else {
FileButtons(game, a)
GameShortcutMenu(game, a)
}
}
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
}
if (game != null && !compactMenu) {
HideButton(hideKey(game), game)
EditArtButton(game)
if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GAMEJOLT && installed != null) GameJoltUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GAMEJOLT && installed != null) GameJoltVersionButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (inStore && store == Store.GAMEJOLT && installed != null) {
SecondaryButton(stringResource(R.string.stores_view_on, Store.GAMEJOLT.shortLabel)) {
openUrl(ctx, item?.storeUrl.orEmpty().ifBlank { GameJoltApi.pageUrl("game", installed.sidecar.id) })
}
}
if (store == Store.EA && installed != null) EaUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.GOG && installed != null) GogMaintenanceActions(installed)
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
if (store == Store.XBOX && installed != null && id != null) {
SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) {
runCatching { XboxBackend.update(ctx, installed) }
.onFailure { StoresState.problems[Store.XBOX] = it.message ?: ctx.getString(R.string.stores_xbox_close_first) }
}
SecondaryButton(stringResource(R.string.stores_xbox_manage), enabled = download == null) { XboxContent.manage(ctx, installed) }
}
if (store == Store.BATTLENET) {
if (installed != null && id != null) {
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
if (download != null) {
SteadyDownloadChip(download)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
} else if (BattleNetInstall.updates[id] == true) {
SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) }
}
}
SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() }
}
if (game != null && !compactMenu) {
HideButton(hideKey(game), game)
EditArtButton(game)
}
}
}
download != null -> {
SteadyDownloadChip(download)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { DownloadQueue.pause(download.key) }
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { DownloadQueue.resume(ctx, download.key) }
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { DownloadQueue.cancel(ctx, download.key) }
if (rest) SteadyDownloadChip(download)
if (lead) {
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { DownloadQueue.pause(download.key) }
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { DownloadQueue.resume(ctx, download.key) }
}
if (rest) ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { DownloadQueue.cancel(ctx, download.key) }
}
failed != null -> {
ActionChip(stringResource(R.string.stores_dl_failed), ok = false)
PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) {
if (rest) ActionChip(stringResource(R.string.stores_dl_failed), ok = false)
if (lead) PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) {
if (item != null) StoresState.requestInstall(ctx, item) else DownloadQueue.retry(ctx, failed.key)
}
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(ctx, failed.key) }
if (rest) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { DownloadQueue.clear(ctx, failed.key) }
}
cloud -> {
val cloudId = game.storeId.orEmpty()
XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn)
if (item?.installable == true && item.xboxPc) {
if (lead) XboxStreamButton(cloudId, game.name, main = true, modifier = leadOn)
if (rest && item?.installable == true && item.xboxPc) {
SecondaryButton(
if (StoresState.isUnfinished(item)) stringResource(R.string.stores_resume_install)
else if (downloadBytes > 0) stringResource(R.string.stores_install_size, formatBytes(downloadBytes))
else stringResource(R.string.stores_install),
) { StoresState.requestInstall(ctx, item) }
}
if (item != null && StoresState.isUnfinished(item)) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
XboxLibraryButton(cloudId, item)
if (rest && item != null && StoresState.isUnfinished(item)) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
if (rest) XboxLibraryButton(cloudId, item)
}
store == Store.BATTLENET && item != null -> InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
store == Store.BATTLENET && item != null -> if (lead) InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
store == Store.XBOX && item != null && !item.xboxPc && item.xboxCloud -> {
XboxStreamButton(item.id, item.title, main = true, modifier = leadOn)
XboxLibraryButton(item.id, item)
if (lead) XboxStreamButton(item.id, item.title, main = true, modifier = leadOn)
if (rest) XboxLibraryButton(item.id, item)
}
item?.installable == true && StoresState.isUnfinished(item) -> {
InstallButton(stringResource(R.string.stores_resume_install), leadOn) { StoresState.requestInstall(ctx, item) }
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
if (lead) InstallButton(stringResource(R.string.stores_resume_install), leadOn) { StoresState.requestInstall(ctx, item) }
if (rest) ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
}
item?.installable == true -> {
InstallButton(
if (lead) InstallButton(
if (downloadBytes > 0) stringResource(R.string.stores_install_size, formatBytes(downloadBytes)) else stringResource(R.string.stores_install),
leadOn,
) { StoresState.requestInstall(ctx, item) }
if (store == Store.XBOX && item.xboxCloud) {
if (rest && store == Store.XBOX && item.xboxCloud) {
XboxStreamButton(item.id, item.title)
XboxLibraryButton(item.id, item)
}
if (!item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) }
if (rest && !item.accessible) SecondaryButton(buyLabel(item)) { openStoreUrl(ctx, item) }
}
item != null && (item.store == Store.ITCH || item.store == Store.GAMEJOLT) && item.isFree -> {
InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) }
if (lead) InstallButton(stringResource(R.string.stores_install), leadOn) { StoresState.requestInstall(ctx, item) }
if (rest) SecondaryButton(stringResource(R.string.stores_view_on, item.store.shortLabel)) { openStoreUrl(ctx, item) }
}
item != null && item.isFree -> {
item != null && item.isFree -> if (lead) {
val adding = StoresState.claiming[item.key] == true
PrimaryButton(stringResource(if (adding) R.string.stores_claiming else R.string.stores_get_free), enabled = !adding, main = true, modifier = leadOn) {
if (StoresState.canClaim(item)) StoresState.claim(ctx, item) { openStoreUrl(ctx, item) } else openStoreUrl(ctx, item)
}
}
item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
item != null -> if (lead) PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) }
}
val entryKey = game?.let(::hideKey) ?: storeKey
if (!s.shortcutPicker && entryKey != null && (game == null || cloud)) HideButton(entryKey, game)
if (cloud && (download != null || failed != null)) {
XboxStreamButton(game.storeId.orEmpty(), game.name)
XboxLibraryButton(game.storeId.orEmpty(), item)
if (rest) {
val entryKey = game?.let(::hideKey) ?: storeKey
if (!s.shortcutPicker && entryKey != null && (game == null || cloud)) HideButton(entryKey, game)
if (cloud && (download != null || failed != null)) {
XboxStreamButton(game.storeId.orEmpty(), game.name)
XboxLibraryButton(game.storeId.orEmpty(), item)
}
BusyChip(s)
}
BusyChip(s)
}
}
@@ -958,11 +1049,16 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
@Composable
private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a: FrontEndActions) {
var browsing by remember(g.gameId) { mutableStateOf<WowAddons.Target?>(null) }
browsing?.let { AddonBrowserDialog(targets, it) { browsing = null } }
browsing?.let { AddonBrowserDialog(targets, it, CurseForgeApp.find(UserAppsState.items)) { browsing = null } }
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
CurseForgeEntry(a)
targets.forEach { target ->
val names by produceState(emptyList<String>(), target.addOns, WowAddons.imports) {
value = withContext(Dispatchers.IO) { WowAddons.installed(target) }
val names by produceState(emptyList<WowAddons.Installed>(), target.addOns, WowAddons.imports) {
value = withContext(Dispatchers.IO) { WowAddons.details(target) }
}
val context = LocalContext.current
val updates by produceState(emptyMap<String, WowAddonCatalog.Addon>(), names) {
value = withContext(Dispatchers.IO) { WowAddonCatalog.updates(context, names, target) }
}
if (targets.size > 1) SectionLabel(target.flavor)
MenuItem(stringResource(R.string.addons_download), checked = false) { browsing = target }
@@ -974,17 +1070,85 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a:
target.addOns.mkdirs()
a.onBrowseFiles(target.addOns)
}
names.forEach { name -> AddonRow(name, target, a) }
names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a) } }
}
}
}
@Composable
private fun AddonRow(name: String, target: WowAddons.Target, a: FrontEndActions) {
private fun CurseForgeEntry(a: FrontEndActions) {
val ctx = LocalContext.current
val name = stringResource(R.string.addons_source_curse)
LaunchedEffect(Unit) { UserAppsState.refresh(ctx) }
val app = CurseForgeApp.find(UserAppsState.items)
val idle = UserAppsState.working == null
if (app == null) {
MenuItem(stringResource(R.string.content_install_named, name), checked = false, enabled = idle && !SessionState.running) {
UserAppsState.add(ctx, CurseForgeApp.request(), name)
}
} else {
var asking by remember(app.key) { mutableStateOf(false) }
var checked by remember { mutableStateOf<String?>(null) }
val checkKey = app.key + "@" + app.version
LaunchedEffect(checkKey, UserAppsState.checking) {
if (UserAppsState.checking == null && checked != checkKey) {
checked = checkKey
UserAppsState.checkUpdate(ctx, app)
}
}
val update = (UserAppsState.updates[app.key] as? UserApps.UpdateCheck.Available)?.release
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
MenuItem(
stringResource(R.string.user_apps_open, name), checked = false, enabled = idle,
detail = app.version, modifier = Modifier.weight(1f),
) { a.onUserApp(app) }
DeleteButton(name, enabled = idle && !SessionState.running) { asking = true }
}
if (update != null) MenuItem(stringResource(R.string.user_apps_update_to, update.tag), checked = false, enabled = idle && !SessionState.running) {
UserAppsState.update(ctx, app, update)
}
(UserAppsState.updates[app.key] as? UserApps.UpdateCheck.Failed)?.let { failed ->
MenuItem(stringResource(R.string.user_apps_check_updates), checked = false, enabled = idle && UserAppsState.checking == null, detail = failed.message) {
UserAppsState.checkUpdate(ctx, app)
}
}
if (asking) ConfirmDialog(
title = stringResource(R.string.flathub_remove_title, name),
text = stringResource(R.string.flathub_remove_note),
confirm = stringResource(R.string.user_apps_remove),
onConfirm = { asking = false; UserAppsState.remove(ctx, app) },
onDismiss = { asking = false },
)
}
if (UserAppsState.working == name || (UserAppsState.lastError?.startsWith(name) == true)) UserAppsProgress()
}
@Composable
private fun AddonRow(item: WowAddons.Installed, update: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions) {
val name = item.name
var asking by remember(target.addOns, name) { mutableStateOf(false) }
var progress by remember(target.addOns, name) { mutableStateOf<Int?>(null) }
val context = LocalContext.current
val scope = rememberCoroutineScope()
val delete = stringResource(R.string.common_delete)
val colors = MaterialTheme.colorScheme
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 2.dp, bottom = 2.dp)) {
Text(name, fontSize = 14.sp, color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Column(Modifier.weight(1f)) {
Text(name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
val detail = listOfNotNull(item.version, update?.let { stringResource(R.string.upd_available) }).joinToString(" · ")
if (detail.isNotEmpty()) Text(
progress?.let { stringResource(R.string.ctrl_percent, it) } ?: detail, fontSize = 12.sp,
color = if (update != null) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
if (update != null && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) {
progress = 0
scope.launch {
val message = withContext(Dispatchers.IO) { installAddon(context, update, target) { pct -> scope.launch { progress = pct } } }
progress = null
android.widget.Toast.makeText(context, message.first, android.widget.Toast.LENGTH_LONG).show()
}
}
if (!SessionState.running) IconAction(Icons.Outlined.Delete, delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true }
}
if (asking) ConfirmDialog(
@@ -58,6 +58,7 @@ import coil.size.Precision
import kotlin.math.max
internal val LocalPillButtons = compositionLocalOf { false }
internal val LocalGradientOutline = compositionLocalOf { false }
internal class GlassBackdrop {
var painter: Painter? = null
@@ -60,7 +60,7 @@ internal fun gameResources(title: String, game: Library.SteamGame?): List<GameRe
internal fun GameResourcesRow(title: String, game: Library.SteamGame?, modifier: Modifier = Modifier) {
val links = remember(title, game) { gameResources(title, game) }
if (links.isEmpty()) return
FlowRow(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
FlowRow(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
links.forEach { ResourceLink(it) }
}
}
@@ -79,14 +79,14 @@ private fun ResourceLink(link: GameResource) {
val tint = if (hot) pal.signal else pal.onSurfaceVariant
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp),
modifier = Modifier.paneItem("resource:${link.label}").heightIn(min = 44.dp).clip(shape)
modifier = Modifier.paneItem("resource:${link.label}").heightIn(min = 34.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else if (glass) Color.White.copy(alpha = 0.07f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal, restColor = if (glass) Color.White.copy(alpha = 0.12f) else Color.Transparent)
.semantics { contentDescription = description }
.hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = open)
.controllerConfirm(onClick = open).padding(horizontal = if (glass) 14.dp else 8.dp),
.controllerConfirm(onClick = open).padding(horizontal = if (glass) 11.dp else 8.dp),
) {
Text(label, fontSize = if (glass) 13.sp else 12.sp, fontWeight = FontWeight.Medium, color = if (glass && !hot) MaterialTheme.colorScheme.onBackground else tint, maxLines = 1)
Text(label, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = if (glass && !hot) MaterialTheme.colorScheme.onBackground else tint, maxLines = 1)
Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = null, tint = tint.copy(alpha = 0.65f), modifier = Modifier.size(11.dp))
}
}
@@ -18,7 +18,6 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.*
import com.droiddeck.launcher.session.SessionPrefs
@Composable
internal fun InputLayoutRow(layout: SavedInputLayout, role: InputRole, detail: String?, onManage: () -> Unit, onPick: () -> Unit) {
@@ -48,11 +47,10 @@ internal class InputLayoutPreviewView(context: Context) : View(context) {
fun update(layout: SavedInputLayout, role: InputRole) {
sourceHeight = if (role == InputRole.PRIMARY) 563 else 870
val primary = role == InputRole.PRIMARY
val steamOverlay = primary && OnScreenLayout.supportsFloatingSteamControls(SessionPrefs.steamController(context), layout)
val elements = if (steamOverlay) OnScreenLayout.editorElements(context, layout, 1000, sourceHeight) else layout.elements
val artwork = if (primary) PadKit.forOverlay(context, layout) else null
val elements = if (artwork != null) OnScreenLayout.editorElements(context, layout, 1000, sourceHeight) else layout.elements
renderer.updateCustomLayout(elements)
renderer.updateStyle(layout.style.copy(opacity = 100),
steamDeckButtons = primary && OnScreenLayout.usesSteamDeckButtons(context, layout))
renderer.updateStyle(layout.style.copy(opacity = 100), artwork)
renderer.measure(MeasureSpec.makeMeasureSpec(1000, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(sourceHeight, MeasureSpec.EXACTLY))
renderer.layout(0, 0, 1000, sourceHeight)
contentDescription = layout.name
@@ -267,18 +267,12 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
}
}
InputPage.SOURCE -> {
if (role == InputRole.PRIMARY) SettingsGroup(stringResource(R.string.input_screen_visibility)) {
ChoiceRow(host, "controller-osc", stringResource(R.string.mode_osc), stringResource(R.string.input_visibility_shared),
listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)),
oscMode) { SessionPrefs.setOscMode(context, it); oscMode = it; onChanged() }
}
if (layout != null) SettingsGroup(stringResource(R.string.ctrl_layout)) {
if (layout.editable) InputNavigationRow(stringResource(R.string.input_edit_layout), layout.name, Modifier.testTag("input-surface-${role.name.lowercase()}")) { surface = true }
else InputHint(layout.name)
InputNavigationRow(stringResource(R.string.input_saved_layouts), stringResource(R.string.input_saved_layouts_hint)) { go(InputPage.LAYOUTS) }
if (layout.editable) {
if (!OnScreenLayout.usesSteamDeckButtons(context, layout)) {
if (PadKit.forOverlay(context, layout).let { kit -> role != InputRole.PRIMARY || kit == null || layout.elements.any { !kit.artwork(it) } }) {
InputColorRow(host, layout.style.tint) { color -> update { it.withLayout(layout.copy(style = layout.style.copy(tint = color))) } }
}
SliderRow(stringResource(R.string.ctrl_opacity), null, layout.style.opacity, 1..100, step = 1,
@@ -288,6 +282,12 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
}
if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable))
}
if (role == InputRole.PRIMARY) SettingsGroup(stringResource(R.string.input_screen_visibility)) {
ChoiceRow(host, "controller-osc", stringResource(R.string.mode_osc), stringResource(R.string.input_visibility_shared),
listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)),
oscMode) { SessionPrefs.setOscMode(context, it); oscMode = it; onChanged() }
}
SettingsGroup(stringResource(R.string.input_assign_actions)) {
val users = library.usersOfBindings(preset.id)
if (users.size > 1) InputHint(stringResource(R.string.input_shared_with, users.filterNot { it.id == profileId }.joinToString { it.name }))
@@ -63,10 +63,17 @@ import com.droiddeck.launcher.session.SessionState
private data class SurfaceSnapshot(val elements: List<InputSurfaceElement>, val actions: Map<String, InputAction>,
val clicks: Map<String, InputAction>, val scale: Float, val aspect: Float)
private class GamepadScaler(private val context: android.content.Context, private val width: Int, private val height: Int) {
private class GamepadScaler(private val context: android.content.Context, private val width: Int, private val height: Int,
private val layout: SavedInputLayout) {
private fun generator(scale: Float) = LegacyGamepadLayout(context, width, height, scale = scale)
val ids = generator(1f).elements().map { it.id }.toSet()
fun rescale(stored: List<InputSurfaceElement>, from: Float, to: Float) = generator(to).rescale(stored, generator(from))
fun stock(scale: Float) = generator(scale).elements()
private fun placed(scale: Float) = OnScreenLayout.editorElements(context,
layout.copy(elements = stock(scale), aspect = 0f, rotated = emptyList(), scale = scale), width, height)
fun rescale(stored: List<InputSurfaceElement>, from: Float, to: Float) =
if (PadKit.forOverlay(context, layout) == null || OnScreenLayout.generatedSize(context, layout.copy(elements = stored, scale = from), width, height) != null)
generator(to).rescale(stored, generator(from))
else rescaleBetween(stored, placed(from), placed(to), stock(from), stock(to))
fun reset(stored: List<InputSurfaceElement>) = generator(1f).regenerate(stored).associateBy { it.id }.let { placed -> stored.map { placed[it.id] ?: it } }
}
@@ -78,21 +85,28 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
var clicks by mutableStateOf(preset.clicks)
var selected by mutableStateOf<String?>(null)
var toolsExpanded by mutableStateOf(false)
var toolsX by mutableFloatStateOf(.02f)
var toolsX by mutableFloatStateOf(-1f)
var toolsY by mutableFloatStateOf(.02f)
var snap by mutableStateOf(snap)
var adding by mutableStateOf(false)
var properties by mutableStateOf(false)
var clickProperties by mutableStateOf(false)
var history by mutableStateOf<List<SurfaceSnapshot>>(emptyList())
var canvas by mutableStateOf(IntSize.Zero)
var layoutScale by mutableFloatStateOf(layout.scale)
var aspect by mutableFloatStateOf(layout.aspect)
private var scaleBase by mutableStateOf<Triple<List<InputSurfaceElement>, List<InputSurfaceElement>, Float>?>(null)
private var scaleValue by mutableIntStateOf(100)
private var pieceBase by mutableStateOf<Triple<List<InputSurfaceElement>, List<InputSurfaceElement>, Int>?>(null)
private var pieceLayout: List<InputSurfaceElement>? = null
private val piece get() = element?.let { e -> (if (elements.any { it.id == e.id }) elements else shown).groupOf(e) }.orEmpty()
val scaleRange get() = if (piece.isEmpty()) 80..125 else 50..200
private val rescales get() = gamepad?.let { pad -> elements.any { it.id in pad.ids } } == true
val scale get() = when {
piece.isNotEmpty() -> pieceBase?.takeIf { it.second == piece && pieceLayout == elements }?.third ?: 100
scaleBase?.second == elements -> scaleValue
rescales -> (layoutScale * 100).roundToInt()
rescales -> ((if (canvas.width > 0 && canvas.height > 0 && aspect > 0f && (aspect < 1f) != (canvasAspect < 1f))
OnScreenLayout.oriented(layout, canvas.width, canvas.height).scale else layoutScale) * 100).roundToInt()
else -> 100
}
val positioned get() = (if (rescales) gamepad!!.reset(elements) else defaults?.let { elements.withPositionsOf(refit(it, defaultsFrame)) })
@@ -102,18 +116,29 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
if (from <= 0f || aspect <= 0f || abs(from / aspect - 1f) < .01f) return placed
return OnScreenLayout.fit(placed, from, 1f, (aspect * 1000).roundToInt().coerceAtLeast(1), 1000, Rect())
}
val element get() = elements.firstOrNull { it.id == selected }
val element get() = elements.firstOrNull { it.id == selected } ?: shown.firstOrNull { it.id == selected }
val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale || aspect != layout.aspect
fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale, aspect)).takeLast(40) }
fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; aspect = it.aspect; history = history.dropLast(1) } }
private fun adoptDisplayedFrame(context: android.content.Context): Boolean {
if (canvas.width <= 0 || canvas.height <= 0 || shown.isEmpty() || aspect <= 0f || (aspect < 1f) == (canvasAspect < 1f)) return false
val open = toolsExpanded
beginEdit(shown, canvasAspect, gamepad?.let { GamepadScaler(context, canvas.width, canvas.height, layout) })
toolsExpanded = open
return true
}
fun beginEdit(displayed: List<InputSurfaceElement>, aspect: Float, scaler: GamepadScaler? = gamepad) {
checkpoint()
toolsExpanded = false
elements = OnScreenLayout.editorFrame(layout.copy(elements = elements), displayed)
if (this.aspect > 0f && aspect > 0f && (this.aspect < 1f) != (aspect < 1f)) layoutScale = OnScreenLayout.oriented(layout, (aspect * 1000).roundToInt(), 1000).scale
this.aspect = aspect
scaler?.let { gamepad = it }
}
fun scaleAll(percent: Int) {
val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { checkpoint() }
fun scaleAll(context: android.content.Context, percent: Int) {
val adopted = adoptDisplayedFrame(context)
val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { if (!adopted) checkpoint() }
val factor = percent / 100f
val pad = gamepad
elements = if (base.third > 0f && pad != null) {
@@ -123,7 +148,65 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
} else base.first.scaled(factor)
scaleValue = percent; scaleBase = Triple(base.first, elements, base.third)
}
fun resetPositions() { positioned?.let { checkpoint(); elements = it; if (rescales) layoutScale = 1f } }
fun scaleSelected(context: android.content.Context, percent: Int) {
val id = selected ?: return
val adopted = adoptDisplayedFrame(context)
val base = pieceBase?.takeIf { it.second == piece && pieceLayout == elements } ?: run {
if (!adopted && canvas.width > 0 && canvas.height > 0 && shown.isNotEmpty()) {
val open = toolsExpanded
beginEdit(shown, canvasAspect)
toolsExpanded = open
} else if (!adopted) checkpoint()
val start = elements.firstOrNull { it.id == id }?.let { elements.groupOf(it) } ?: return
Triple(start, start, 100)
}
val resized = base.first.resizedAroundCentre(percent / 100f)
val byId = resized.associateBy { it.id }
elements = elements.map { byId[it.id] ?: it }
pieceBase = Triple(base.first, resized, percent)
pieceLayout = elements
}
var shown by mutableStateOf<List<InputSurfaceElement>>(emptyList())
private val canvasAspect get() = canvas.width.toFloat() / canvas.height.coerceAtLeast(1)
private fun stored(id: String): Boolean {
if (elements.any { it.id == id }) return true
if (shown.none { it.id == id }) return false
beginEdit(shown, canvasAspect)
return true
}
fun missing(context: android.content.Context): List<InputSurfaceElement> {
val pad = gamepad ?: return emptyList()
if (canvas.width <= 0 || canvas.height <= 0) return emptyList()
val ids = shown.map { it.id }.toSet()
return OnScreenLayout.editorElements(context, layout.copy(elements = pad.stock(layoutScale), aspect = 0f, rotated = emptyList(), scale = layoutScale),
canvas.width, canvas.height).filter { it.id !in ids }
}
fun restore(context: android.content.Context, element: InputSurfaceElement) {
val legacy = gamepad?.stock(layoutScale)?.firstOrNull { it.id == element.id }
val generated = OnScreenLayout.generatedSize(context, layout.copy(elements = elements), canvas.width, canvas.height) != null
if (generated && legacy != null) { checkpoint(); elements = elements + legacy }
else { beginEdit(shown, canvasAspect); elements = elements + element }
if (element.id == "builtin:keyboard" && actions[element.id] == null) actions = actions + (element.id to InputAction.Command(InputCommand.KEYBOARD))
selected = element.id
}
fun remove(id: String) {
if (elements.any { it.id == id }) checkpoint() else stored(id)
elements = elements.filterNot { it.id == id }; actions = actions - id; clicks = clicks - id; selected = null
}
fun update(element: InputSurfaceElement) {
stored(element.id)
elements = elements.map { if (it.id == element.id) element else it }
}
fun resetPositions(context: android.content.Context) {
val adopted = adoptDisplayedFrame(context)
positioned?.let { if (!adopted) checkpoint(); elements = it; if (rescales) layoutScale = 1f }
}
fun action(e: InputSurfaceElement) = preset.copy(elements = actions).action(e)
fun clickAction(e: InputSurfaceElement) = preset.copy(elements = actions, clicks = clicks).clickAction(e)
}
@@ -142,7 +225,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
val (display, metrics) = InputLibraries.primaryDisplay(context)
val gamepad = savedLayout.elements.takeIf { e -> e.any { it.id.startsWith("legacy:") } }?.let {
val (w, h) = OnScreenLayout.generatedSize(context, savedLayout, metrics.widthPixels, metrics.heightPixels) ?: (metrics.widthPixels to metrics.heightPixels)
GamepadScaler(display, w, h)
GamepadScaler(display, w, h, savedLayout)
}
val defaults = InputLibraries.defaultPositions(context, library, savedLayout)
SurfaceDraft(savedLayout, savedBindings, defaults?.first, defaults?.second ?: 0f, gamepad, ControllerPrefs.snap(context))
@@ -166,7 +249,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
InputLibraries.update(context) { latest ->
val l = latest.layouts.first { it.id == savedLayout.id }
val p = latest.preset(savedBindings.id)
latest.withLayout(l.copy(elements = draft.elements, aspect = draft.aspect, scale = draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } },
latest.withLayout(OnScreenLayout.withFrame(context, l, draft.elements, draft.aspect, draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } },
clicks = draft.clicks.filterKeys { id -> draft.elements.any { it.id == id && it.hasClick } }))
}
}.onSuccess { onChanged(); onDismiss() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
@@ -225,7 +308,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
else "${library.profile(profile).name} · ${roleLabel(role)}", onSave = { action ->
draft.checkpoint()
if (draft.clickProperties) draft.clicks = draft.clicks + (element.id to action) else draft.actions = draft.actions + (element.id to action)
draft.elements = draft.elements.map { if (it.id == element.id) properties.copy(name = properties.name.trim().ifBlank { element.name }) else it }
draft.update(properties.copy(name = properties.name.trim().ifBlank { element.name }))
draft.properties = false
})
}
@@ -245,7 +328,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
}
}
}
if (draft.adding) AlertDialog(onDismissRequest = { draft.adding = false }, title = { Text(stringResource(R.string.input_add_element)) }, confirmButton = {}, text = { Column {
if (draft.adding) AlertDialog(onDismissRequest = { draft.adding = false }, title = { Text(stringResource(R.string.input_add_element)) }, confirmButton = {}, text = { Column(Modifier.verticalScroll(rememberScrollState())) {
for (kind in InputElementKind.entries) PadTextButton(onClick = { draft.checkpoint()
val w = if (kind.control.dimensions == 2) .4f else .2f
val h = .3f
@@ -253,6 +336,11 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
val element = InputSurfaceElement(kind.control, (1f - w) / 2, (1f - h) / 2, w, h, newInputId(), kind, name)
draft.elements = draft.elements + element; draft.selected = element.id
draft.adding = false; draft.toolsExpanded = false }) { Text(stringResource(kind.label())) }
val missing = remember(draft.elements, draft.canvas) { draft.missing(context) }
if (missing.isNotEmpty()) HorizontalDivider()
for (element in missing) PadTextButton(onClick = { draft.restore(context, element); draft.adding = false; draft.toolsExpanded = false }) {
Text(PadKit.forOverlay(context, savedLayout)?.name(element.control)?.takeIf { element.name == element.control.label } ?: element.name)
}
} })
if (discard) AlertDialog(onDismissRequest = { discard = false }, title = { Text(stringResource(R.string.input_editor_discard)) },
confirmButton = { PadTextButton(onClick = onDismiss) { Text(stringResource(R.string.common_ok)) } },
@@ -266,11 +354,13 @@ private fun SurfaceCanvas(draft: SurfaceDraft, transparent: Boolean = false) {
AndroidView(factory = { InputSurfaceEditorView(it) }, modifier = Modifier.fillMaxSize().testTag("input-layout-canvas"),
update = { view ->
view.setBackgroundColor(if (transparent) android.graphics.Color.TRANSPARENT else android.graphics.Color.rgb(10, 11, 13))
view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout; view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap
view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout.copy(scale = draft.layoutScale); view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap
view.isEnabled = !draft.properties && !draft.adding
view.onSelect = { if (!draft.properties) draft.selected = it }
view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h) else null) }
view.onChange = { e -> if (!draft.properties) draft.elements = draft.elements.map { if (it.id == e.id) e else it } }
view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h, draft.layout) else null) }
view.onResize = { w, h -> draft.canvas = IntSize(w, h) }
view.onDisplayed = { draft.shown = it }
view.onChange = { changed -> if (!draft.properties) changed.associateBy { it.id }.let { byId -> draft.elements = draft.elements.map { byId[it.id] ?: it } } }
})
}
@@ -283,7 +373,8 @@ private fun FloatingSurfaceTools(draft: SurfaceDraft, onSave: () -> Unit, onLeav
val screenHeight = with(density) { maxHeight.toPx() }
val margin = with(density) { 8.dp.toPx() }
var panelSize by remember { mutableStateOf(IntSize.Zero) }
val x = (draft.toolsX * screenWidth).coerceIn(margin, (screenWidth - panelSize.width - margin).coerceAtLeast(margin))
val x = (if (draft.toolsX < 0f) (screenWidth - panelSize.width) / 2f else draft.toolsX * screenWidth)
.coerceIn(margin, (screenWidth - panelSize.width - margin).coerceAtLeast(margin))
val y = (draft.toolsY * screenHeight).coerceIn(margin, (screenHeight - panelSize.height - margin).coerceAtLeast(margin))
val position by rememberUpdatedState(Offset(x, y))
val expandedWidth = minOf(420.dp, maxWidth - 16.dp)
@@ -332,15 +423,15 @@ private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: ()
SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = onLeave)
SecondaryButton(stringResource(R.string.input_editor_add), enabled = draft.elements.size < 64, compact = true) { draft.adding = true }
SecondaryButton(stringResource(R.string.input_editor_undo), enabled = draft.history.isNotEmpty(), compact = true) { draft.undo() }
if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_reset_positions), enabled = draft.positioned != null, compact = true) { draft.resetPositions() }
if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_reset_positions), enabled = draft.positioned != null, compact = true) { draft.resetPositions(context) }
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(draft.snap, { draft.snap = it; ControllerPrefs.setSnap(context, it) })
Text(stringResource(R.string.ctrl_editor_snap))
}
PrimaryButton(stringResource(R.string.input_editor_done), compact = true, onClick = onSave)
}
if (draft.elements.isNotEmpty()) SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, 80..125, step = 5,
format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { draft.scaleAll(it) }
if (draft.elements.isNotEmpty()) SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, draft.scaleRange, step = 5,
format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { if (draft.element != null) draft.scaleSelected(context, it) else draft.scaleAll(context, it) }
}
@OptIn(ExperimentalLayoutApi::class)
@@ -352,9 +443,7 @@ private fun SurfaceSelection(draft: SurfaceDraft) {
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
PrimaryButton(stringResource(R.string.input_properties), compact = true) { draft.clickProperties = false; draft.properties = true }
if (e.hasClick) SecondaryButton(stringResource(R.string.input_click_properties), compact = true) { draft.clickProperties = true; draft.properties = true }
SecondaryButton(stringResource(R.string.input_remove_element), compact = true) {
draft.checkpoint(); draft.elements = draft.elements.filterNot { it.id == e.id }; draft.actions = draft.actions - e.id; draft.clicks = draft.clicks - e.id; draft.selected = null
}
SecondaryButton(stringResource(R.string.input_remove_element), compact = true) { draft.remove(e.id) }
}
} ?: Text(stringResource(R.string.input_editor_hint))
}
@@ -5,14 +5,20 @@ import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.view.WindowInsets
import android.widget.FrameLayout
import com.droiddeck.launcher.input.OnScreenLayout
import com.droiddeck.launcher.input.PadKit
import com.droiddeck.launcher.input.SavedInputLayout
import com.droiddeck.launcher.input.InputSurfaceElement
import com.droiddeck.launcher.input.InputSurfaceStyle
import com.droiddeck.launcher.input.dpadPiece
import com.droiddeck.launcher.input.frame
import com.droiddeck.launcher.input.groupOf
import com.droiddeck.launcher.input.snapSurfaceElement
import kotlin.math.abs
@@ -38,11 +44,13 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
set(value) { field = value; invalidate() }
var onSelect: (String?) -> Unit = {}
var onBeginEdit: (List<InputSurfaceElement>, Int, Int) -> Unit = { _, _, _ -> }
var onChange: (InputSurfaceElement) -> Unit = {}
var onChange: (List<InputSurfaceElement>) -> Unit = {}
var onResize: (Int, Int) -> Unit = { _, _ -> }
var onDisplayed: (List<InputSurfaceElement>) -> Unit = {}
private val preview = InputSurfaceView(context)
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.rgb(26, 159, 255); strokeWidth = 2 * resources.displayMetrics.density }
private val radius = 14 * resources.displayMetrics.density
private var original: InputSurfaceElement? = null
private var original: List<InputSurfaceElement> = emptyList()
private var downX = 0f
private var downY = 0f
private var corner = 0
@@ -56,19 +64,38 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
}
private fun updatePreviewStyle() {
preview.updateStyle(style, steamDeckButtons = OnScreenLayout.usesSteamDeckButtons(context, sourceLayout))
preview.updateStyle(style, PadKit.forOverlay(context, sourceLayout))
}
private var safe = Rect()
private var frameWidth = 0
private var frameHeight = 0
private fun refreshElements() {
visibleElements = sourceLayout?.let { layout ->
OnScreenLayout.editorElements(context, layout.copy(elements = elements, aspect = aspect), width, height)
OnScreenLayout.editorElements(context, layout.copy(elements = elements, aspect = aspect), frameWidth, frameHeight, safe = safe)
} ?: elements
preview.updateCustomLayout(visibleElements)
onDisplayed(visibleElements)
}
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
val fresh = OnScreenLayout.safeInsets(insets, false)
if (fresh != safe) { safe = fresh; refreshElements(); invalidate() }
return super.onApplyWindowInsets(insets)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (measuredWidth == frameWidth && measuredHeight == frameHeight) return
frameWidth = measuredWidth; frameHeight = measuredHeight
refreshElements()
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
refreshElements()
onResize(w, h)
}
override fun dispatchDraw(canvas: Canvas) {
@@ -76,13 +103,15 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
paint.style = Paint.Style.STROKE
guideX?.let { canvas.drawLine(width * it, 0f, width * it, height.toFloat(), paint) }
guideY?.let { canvas.drawLine(0f, height * it, width.toFloat(), height * it, paint) }
val e = visibleElements.firstOrNull { it.id == selected } ?: return
val e = visibleElements.firstOrNull { it.id == selected }?.let { visibleElements.groupOf(it).frame() } ?: return
val l = width * e.x; val t = height * e.y; val r = l + width * e.width; val b = t + height * e.height
paint.style = Paint.Style.STROKE; canvas.drawRect(l, t, r, b, paint)
paint.style = Paint.Style.FILL
for (x in listOf(l, r)) for (y in listOf(t, b)) canvas.drawCircle(x, y, radius / 3, paint)
}
private fun contains(e: InputSurfaceElement, x: Float, y: Float) = x / width in e.x..(e.x + e.width) && y / height in e.y..(e.y + e.height)
private fun clearGuides() { guideX = null; guideY = null; invalidate() }
override fun onInterceptTouchEvent(event: MotionEvent) = true
@@ -94,7 +123,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
MotionEvent.ACTION_DOWN -> {
clearGuides()
downX = event.x; downY = event.y; dragging = false; corner = 0
val current = visibleElements.firstOrNull { it.id == selected }
val current = visibleElements.firstOrNull { it.id == selected }?.let { visibleElements.groupOf(it).frame() }
if (current != null) {
val left = width * current.x; val top = height * current.y
val right = left + width * current.width; val bottom = top + height * current.height
@@ -102,13 +131,16 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
val vertical = if (abs(downY - top) < radius) 4 else if (abs(downY - bottom) < radius) 8 else 0
if (horizontal != 0 && vertical != 0) corner = horizontal or vertical
}
original = if (corner != 0) current else visibleElements.asReversed().firstOrNull {
downX / width in it.x..(it.x + it.width) && downY / height in it.y..(it.y + it.height)
}
selected = original?.id; onSelect(selected)
val touched = if (corner != 0) visibleElements.firstOrNull { it.id == selected }
else visibleElements.asReversed().firstOrNull { contains(it, downX, downY) }
?: visibleElements.filter { it.dpadPiece }.takeIf { it.isNotEmpty() && contains(it.frame(), downX, downY) }
?.let { pad -> pad.firstOrNull { it.id == selected } ?: pad.first() }
original = touched?.let { visibleElements.groupOf(it) }.orEmpty()
selected = touched?.id; onSelect(selected)
}
MotionEvent.ACTION_MOVE -> {
val e = original ?: return true
if (original.isEmpty()) return true
val e = original.frame()
if (!dragging && abs(event.x - downX) + abs(event.y - downY) > ViewConfiguration.get(context).scaledTouchSlop) {
dragging = true; onBeginEdit(visibleElements, width, height)
}
@@ -116,20 +148,24 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
val dx = (event.x - downX) / width; val dy = (event.y - downY) / height
val next = if (corner == 0) e.copy(x = (e.x + dx).coerceIn(0f, 1f - e.width), y = (e.y + dy).coerceIn(0f, 1f - e.height))
else {
val left = if (corner and 1 != 0) (e.x + dx).coerceIn(0f, e.x + e.width - .03f) else e.x
val top = if (corner and 4 != 0) (e.y + dy).coerceIn(0f, e.y + e.height - .03f) else e.y
val right = if (corner and 2 != 0) (e.x + e.width + dx).coerceIn(left + .03f, 1f) else e.x + e.width
val bottom = if (corner and 8 != 0) (e.y + e.height + dy).coerceIn(top + .03f, 1f) else e.y + e.height
val minW = (.03f * e.width / original.minOf { it.width }).coerceIn(.03f, e.width.coerceAtLeast(.03f))
val minH = (.03f * e.height / original.minOf { it.height }).coerceIn(.03f, e.height.coerceAtLeast(.03f))
val left = if (corner and 1 != 0) (e.x + dx).coerceIn(0f, (e.x + e.width - minW).coerceAtLeast(0f)) else e.x
val top = if (corner and 4 != 0) (e.y + dy).coerceIn(0f, (e.y + e.height - minH).coerceAtLeast(0f)) else e.y
val right = if (corner and 2 != 0) (e.x + e.width + dx).coerceIn((left + minW).coerceAtMost(1f), 1f) else e.x + e.width
val bottom = if (corner and 8 != 0) (e.y + e.height + dy).coerceIn((top + minH).coerceAtMost(1f), 1f) else e.y + e.height
e.copy(x = left, y = top, width = right - left, height = bottom - top).bounded()
}
val aligned = if (snap) snapSurfaceElement(next, visibleElements.filter { it.id != e.id }, 9 * resources.displayMetrics.density / width,
val aligned = if (snap) snapSurfaceElement(next, visibleElements.filter { v -> original.none { it.id == v.id } }, 9 * resources.displayMetrics.density / width,
9 * resources.displayMetrics.density / height, corner) else null
if (aligned != null && (aligned.x != null && aligned.x != guideX || aligned.y != null && aligned.y != guideY)) performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
guideX = aligned?.x; guideY = aligned?.y
onChange(aligned?.element ?: next)
val f = aligned?.element ?: next
val sx = f.width / e.width; val sy = f.height / e.height
onChange(original.map { it.copy(x = f.x + (it.x - e.x) * sx, y = f.y + (it.y - e.y) * sy, width = it.width * sx, height = it.height * sy) })
invalidate()
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { original = null; dragging = false; clearGuides() }
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { original = emptyList(); dragging = false; clearGuides() }
}
return true
}
@@ -37,6 +37,7 @@ import com.droiddeck.launcher.input.InputButtonIcons
import com.droiddeck.launcher.input.InputButtonShape
import com.droiddeck.launcher.input.InputButtonImages
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadKit
import com.droiddeck.launcher.input.pcKeyLabel
import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.atan2
@@ -56,10 +57,10 @@ class InputSurfaceView(
private val elementSources = ArrayList<InputSurfaceSource>()
private var customCanvas: ViewGroup? = null
private val owners = HashMap<Int, View>()
private var steamDeckButtons = false
private val deckArt by lazy(LazyThreadSafetyMode.NONE) { SteamDeckButtonArt(context) }
private var deckDpad = emptyList<HoldButton>()
private val deckDpadBounds = RectF()
private var artwork: PadKit? = null
private val art by lazy(LazyThreadSafetyMode.NONE) { PadArt(context) }
private var artworkDpad = emptyList<HoldButton>()
private val artworkDpadBounds = RectF()
private var requestedLayout = customLayout
init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) }
@@ -138,11 +139,11 @@ class InputSurfaceView(
}
}
fun updateStyle(style: InputSurfaceStyle, steamDeckButtons: Boolean = false) {
if (surfaceStyle == style && this.steamDeckButtons == steamDeckButtons) return
internal fun updateStyle(style: InputSurfaceStyle, artwork: PadKit? = null) {
if (surfaceStyle == style && this.artwork == artwork) return
val relayout = surfaceStyle.hidden != style.hidden
surfaceStyle = style
this.steamDeckButtons = steamDeckButtons
this.artwork = artwork
if (relayout) updateCustomLayout(requestedLayout)
customCanvas?.let { canvas ->
for (i in 0 until canvas.childCount) styleElement(canvas.getChildAt(i))
@@ -181,7 +182,7 @@ class InputSurfaceView(
}
private fun renderCustom(pad: PadBridge?) {
deckDpad = emptyList()
artworkDpad = emptyList()
val canvas = object : ViewGroup(context) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val layout = customLayout
@@ -199,17 +200,18 @@ class InputSurfaceView(
val x = (width * e.x).toInt(); val y = (height * e.y).toInt()
child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight)
}
updateDeckDpad(this)
updateArtworkDpad(this)
}
override fun dispatchDraw(canvas: Canvas) {
if (steamDeckButtons && deckDpad.isNotEmpty()) {
val alpha = (deckDpad.first().alpha * 255f).toInt()
val kit = artwork
if (kit != null && artworkDpad.isNotEmpty()) {
val alpha = (artworkDpad.first().alpha * 255f).toInt()
val saved = if (alpha == 255) canvas.save()
else canvas.saveLayerAlpha(deckDpadBounds, alpha)
canvas.translate(deckDpadBounds.left, deckDpadBounds.top)
val held = deckDpad.foldIndexed(0) { i, bits, button -> if (button.highlighted) bits or (1 shl i) else bits }
deckArt.dpad(canvas, deckDpadBounds.width(), deckDpadBounds.height(), held)
else canvas.saveLayerAlpha(artworkDpadBounds, alpha)
canvas.translate(artworkDpadBounds.left, artworkDpadBounds.top)
val held = artworkDpad.foldIndexed(0) { i, bits, button -> if (button.highlighted) bits or (1 shl i) else bits }
art.dpad(canvas, artworkDpadBounds.width(), artworkDpadBounds.height(), kit, held)
canvas.restoreToCount(saved)
}
super.dispatchDraw(canvas)
@@ -220,7 +222,8 @@ class InputSurfaceView(
val source = pad?.let { InputSurfaceSource(it, inputRole, element).also { s -> elementSources += s } }
canvas.addView(when (element.kind) {
InputElementKind.STICK -> StickView(context, element, source, element.floating, element.hideWhenIdle && pad != null)
InputElementKind.TRACKPAD -> TrackpadView(context, element.control == InputControl.RIGHT_PAD, captioned = element.showLabel, source = source)
InputElementKind.TRACKPAD -> TrackpadView(context, element.control == InputControl.RIGHT_PAD, captioned = element.showLabel,
stock = element.id == "legacy:${element.control.id}", source = source)
InputElementKind.DPAD -> DirectionPad(context, element, source)
else -> HoldButton(context, element, source)
}.apply { tag = element; contentDescription = element.name; styleElement(this); source?.onStateChanged = { postInvalidate() } })
@@ -229,7 +232,7 @@ class InputSurfaceView(
customCanvas = canvas
}
private fun updateDeckDpad(canvas: ViewGroup) {
private fun updateArtworkDpad(canvas: ViewGroup) {
val buttons = DIRECTIONS.mapNotNull { direction ->
val index = customLayout.indexOfFirst { element ->
element.control == direction && classic(element) && element.buttonShape == InputButtonShape.CIRCLE &&
@@ -238,8 +241,13 @@ class InputSurfaceView(
}
canvas.getChildAt(index) as? HoldButton
}
deckDpad = emptyList()
if (buttons.size != DIRECTIONS.size) return
val previous = artworkDpad
artworkDpad = if (crossed(buttons)) buttons else emptyList()
if (artworkDpad != previous) (previous + artworkDpad).forEach { it.invalidate() }
}
private fun crossed(buttons: List<HoldButton>): Boolean {
if (buttons.size != DIRECTIONS.size) return false
val (up, right, down, left) = buttons
val centerX = (left.left + right.right) / 2f
val centerY = (up.top + down.bottom) / 2f
@@ -247,9 +255,9 @@ class InputSurfaceView(
kotlin.math.abs((down.left + down.right) / 2f - centerX) > 2f ||
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
deckDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat())
deckDpad = buttons
up.bottom >= down.top || left.right >= right.left) return false
artworkDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat())
return true
}
override fun onAttachedToWindow() {
@@ -395,14 +403,14 @@ class InputSurfaceView(
override fun onDraw(canvas: Canvas) {
val lit = highlighted
val classic = classic(element)
if (steamDeckButtons && element.image.isEmpty() && element.showLabel) {
if (this in deckDpad) return
val kit = artwork
if (kit != null && element.image.isEmpty() && element.showLabel) {
if (this in artworkDpad) return
if (element.id == "builtin:keyboard" && element.icon == InputButtonIcons.KEYBOARD) {
deckArt.keyboard(canvas, width, height, lit)
art.system(canvas, width.toFloat(), height.toFloat(), PadArt.Shape.ROUND, PadArt.Icon.KEYBOARD, lit)
return
}
val native = element.id == "legacy:${element.control.id}" && element.name == element.control.label && element.icon == 0
if (native && deckArt.button(canvas, width, height, element.control, lit)) return
if (kit.native(element) && art.button(canvas, width, height, element.control, kit, lit)) return
}
drawSurface(canvas, lit, element.buttonShape, classic)
val cx = width / 2f
@@ -452,11 +460,12 @@ class InputSurfaceView(
if (pressed) feedback(this, HapticFeedbackConstants.VIRTUAL_KEY)
if (!pressed && cancelled) source?.cancel() else source?.update(if (pressed) 1f else 0f)
invalidate()
if (steamDeckButtons && this in deckDpad) customCanvas?.invalidate()
if (artwork != null && this in artworkDpad) customCanvas?.invalidate()
}
}
private inner class TrackpadView(context: Context, private val right: Boolean, private val captioned: Boolean = true,
private inner class TrackpadView(context: Context, private val right: Boolean, private val captioned: Boolean,
private val stock: Boolean,
private val source: InputSurfaceSource? = null) : Surface(context) {
private var gestureX = 0f
private var gestureY = 0f
@@ -479,8 +488,8 @@ class InputSurfaceView(
private val glow = Paint(Paint.ANTI_ALIAS_FLAG)
override fun onDraw(canvas: Canvas) {
if (!captioned) {
deckArt.trackpad(canvas, width.toFloat(), height.toFloat(), touching || clicked, fingerX, fingerY)
if (!captioned || stock && artwork?.steam == true) {
art.trackpad(canvas, width.toFloat(), height.toFloat(), touching || clicked, fingerX, fingerY)
return
}
drawSurface(canvas, clicked)
@@ -596,10 +605,11 @@ class InputSurfaceView(
if (hideWhenIdle && !touching) return
val cx = if (touching) originX else centreX()
val cy = if (touching) originY else height / 2f
if (steamDeckButtons && classic(element)) {
val kit = artwork
if (kit != null && classic(element)) {
val radius = min(width, height) / 2f - 2f * density
if (radius > 0f) {
deckArt.stick(canvas, cx, cy, radius, knobX, knobY, touching || clicking)
art.stick(canvas, cx, cy, radius, kit, knobX, knobY, touching || clicking)
if (element.showLabel) {
labelPaint.color = TEXT
drawDirectionLabels(canvas, source, false, cx, cy, radius * .66f, radius * .34f, labelPaint)
@@ -90,6 +90,7 @@ import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.layout
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
@@ -913,7 +914,6 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 2.dp),
) {
if (manage) ManageStoresChip()
Box(Modifier.weight(1f).edgeFade(scroll).horizontalScroll(scroll)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) {
for (id in keys) {
@@ -945,6 +945,7 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str
}
if (highlighted in keys) ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown)
}
if (manage) ManageStoresChip()
}
}
}
@@ -1121,14 +1122,22 @@ internal fun ArtCard(
}
val showName = LibraryDisplay.title || hot
val showDetail = LibraryDisplay.size || hot
if (showName || showDetail) Column(
verticalArrangement = Arrangement.spacedBy(1.dp),
modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth()
.background(Brush.verticalGradient(0f to Color.Transparent, 0.6f to Color.Black.copy(alpha = 0.78f), 1f to Color.Black.copy(alpha = 0.92f)))
.padding(start = 8.dp, end = 8.dp, top = 20.dp, bottom = if (download != null) 14.dp else 6.dp),
) {
if (showName) Text(title, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = if (hot) 2 else 1, overflow = TextOverflow.Ellipsis, lineHeight = 13.sp)
if (showDetail) detail()
if (showName || showDetail) {
val top = with(androidx.compose.ui.platform.LocalDensity.current) { 20.dp.roundToPx() }
val bottom = with(androidx.compose.ui.platform.LocalDensity.current) { (if (download != null) 14.dp else 6.dp).roundToPx() }
Column(
verticalArrangement = Arrangement.spacedBy(1.dp),
modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth()
.background(Brush.verticalGradient(0f to Color.Transparent, 0.6f to Color.Black.copy(alpha = 0.78f), 1f to Color.Black.copy(alpha = 0.92f)))
.layout { measurable, constraints ->
val inner = measurable.measure(constraints)
if (inner.height == 0) layout(inner.width, 0) {} else layout(inner.width, inner.height + top + bottom) { inner.place(0, top) }
}
.padding(horizontal = 8.dp),
) {
if (showName) Text(title, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = if (hot) 2 else 1, overflow = TextOverflow.Ellipsis, lineHeight = 13.sp)
if (showDetail) detail()
}
}
if (download != null) Box(Modifier.align(Alignment.BottomCenter).padding(start = 6.dp, end = 6.dp, bottom = 5.dp)) {
ProgressBarThin(download.fraction, paused = download.state == DownloadState.PAUSED, verify = download.stage == DownloadStage.VERIFY)
@@ -0,0 +1,93 @@
package com.droiddeck.launcher.ui
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.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DragHandle
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.activity.compose.BackHandler
import com.droiddeck.launcher.R
@Composable
internal fun ManageDrawerPages(offeredNow: List<SessionDrawerPage>, modifier: Modifier = Modifier, releaseSignal: Int = 0, onDone: () -> Unit) {
val ctx = LocalContext.current
val current by rememberUpdatedState(offeredNow)
val previewing = DevPreview.drawer != null
DisposableEffect(Unit) { onDispose { DrawerPages.heldFrom = null } }
DisposableEffect(previewing) { onDispose { if (previewing) DrawerPages.load(ctx) } }
val colors = MaterialTheme.colorScheme
BackHandler { onDone() }
Column(modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
stringResource(R.string.drawer_manage_pages), fontSize = 15.sp, fontWeight = FontWeight.SemiBold,
color = colors.onBackground, modifier = Modifier.weight(1f),
)
if (!DrawerPages.isDefault()) DrawerOutlineButton(stringResource(R.string.drawer_pages_reset)) { DrawerPages.reset(ctx) }
Spacer(Modifier.width(8.dp))
DrawerOutlineButton(stringResource(R.string.drawer_pages_done), onClick = onDone)
}
SortableRows(
rows = { current.map { it.name } },
commit = { names -> DrawerPages.rearrange(ctx, names.mapNotNull { n -> current.firstOrNull { it.name == n } }) },
movable = { true },
rowHeight = STORE_ROW, handleWidth = STORE_HANDLE,
releaseSignal = releaseSignal,
onGrab = { before -> DrawerPages.heldFrom = before?.mapNotNull { n -> current.firstOrNull { it.name == n } } },
onActivate = { name ->
current.firstOrNull { it.name == name }?.let { DrawerPages.setHidden(ctx, it, it !in DrawerPages.hidden) }
},
) { name, held, offset, hint, rowModifier, onFocus ->
val page = current.first { it.name == name }
val shown = page !in DrawerPages.hidden
val pal = LocalPalette.current
val label = stringResource(page.title)
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
SortRowFrame(held, offset, rowModifier.testTag("drawer-page-row-$name"), hot, src, onFocus) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(width = STORE_HANDLE, height = STORE_ROW)) {
Icon(Icons.Filled.DragHandle, null, tint = if (held) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
}
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.weight(1f).alpha(if (shown) 1f else 0.5f),
) {
Icon(page.icon, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
if (hint != null) KeyHint("Y", hint)
ToggleSwitch(
shown, DrawerPages.hideable(page), label,
Modifier.testTag("drawer-page-shown-$name").focusProperties { canFocus = false },
) { DrawerPages.setHidden(ctx, page, !it) }
}
}
}
}
@@ -221,8 +221,8 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq
}
}
private val STORE_ROW = 60.dp
private val STORE_HANDLE = 44.dp
internal val STORE_ROW = 60.dp
internal val STORE_HANDLE = 44.dp
@Composable
internal fun ManageStoresSheet() {
@@ -302,7 +302,7 @@ private fun StoreSortRow(
}
@Composable
private fun SortRowFrame(
internal fun SortRowFrame(
held: Boolean, offset: Float, modifier: Modifier, hot: Boolean, src: MutableInteractionSource, onFocus: (Boolean) -> Unit,
content: @Composable androidx.compose.foundation.layout.RowScope.() -> Unit,
) {
@@ -56,6 +56,7 @@ class DownloadRow(val key: String, val label: String, val detail: String, val pr
class ModeSettings(
val mode: String,
val resolution: String,
val resolutionPortrait: String = com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE,
val panelSize: Pair<Int, Int> = 1280 to 720,
val hdr: Boolean,
val hdrReason: String?,
@@ -116,6 +117,7 @@ class ModeSettings(
class ModeSettingsActions(
val onResolution: (String) -> Unit,
val onResolutionPortrait: (String) -> Unit = {},
val onHdr: (Boolean) -> Unit,
val onZeroCopy: (Boolean) -> Unit = {},
val onGpuDrivers: () -> Unit = {},
@@ -234,9 +236,20 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
val controlsBelow = SessionPrefs.controlsBelowWanted(context, s.mode,
if (portraitWindow) shortSide else longSide, if (portraitWindow) longSide else shortSide)
val portrait = portraitWindow && !controlsBelow
val displaySize = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(s.panelSize, s.resolution, portrait)
val sessionDisplay = com.droiddeck.launcher.session.SessionDisplay
val landscapeChoice = sessionDisplay.effectiveChoice(s.resolution, s.resolutionPortrait, false)
val portraitChoice = sessionDisplay.effectiveChoice(s.resolution, s.resolutionPortrait, true)
val activeChoice = if (portraitWindow) portraitChoice else landscapeChoice
val displaySize = sessionDisplay.resolveChoice(s.panelSize, activeChoice, portrait)
SettingsGroup(stringResource(R.string.display_session)) {
ResolutionRow(host, s.resolution, s.panelSize, a.onResolution, portrait = portrait)
ResolutionRow(host, "resolution", stringResource(R.string.display_resolution_landscape), s.resolution, landscapeChoice,
com.droiddeck.launcher.session.SessionDisplay.LINK_PORTRAIT,
if (sessionDisplay.isLink(s.resolutionPortrait)) landscapeChoice else sessionDisplay.orientCustom(s.resolutionPortrait, false),
s.panelSize, a.onResolution, portrait = false)
ResolutionRow(host, "resolution-portrait", stringResource(R.string.display_resolution_portrait), s.resolutionPortrait, portraitChoice,
com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE,
if (sessionDisplay.isLink(s.resolution)) portraitChoice else sessionDisplay.orientCustom(s.resolution, true),
s.panelSize, a.onResolutionPortrait, portrait = true)
s.picturePosition?.let { position ->
ChoiceRow(host, "picture-position", stringResource(R.string.display_picture_position), null,
listOf("top" to stringResource(R.string.display_position_top),
@@ -248,7 +261,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
}
if (s.stretch16x9 != null && (com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(s.panelSize) ||
com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize))) {
val canStretch = !com.droiddeck.launcher.session.SessionDisplay.isFollow(s.resolution) &&
val canStretch = !com.droiddeck.launcher.session.SessionDisplay.isFollow(activeChoice) &&
com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize)
ChoiceRow(host, "game-fit", stringResource(R.string.display_game_fit),
stringResource(if (canStretch) R.string.display_game_fit_hint else R.string.display_game_fit_unavailable),
@@ -707,10 +720,10 @@ internal fun SgdbKeyDialog(hasKey: Boolean, onSave: (String) -> Unit, onDismiss:
@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
@Composable
internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int, Int>) -> Unit, onDismiss: () -> Unit) {
internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int, Int>) -> Unit, onDismiss: () -> Unit, portrait: Boolean = false) {
var w by remember { mutableStateOf(initial?.first?.toString() ?: "") }
var h by remember { mutableStateOf(initial?.second?.toString() ?: "") }
val parsed = SessionPrefs.parseResolution("${w}x$h")
val parsed = if (portrait) SessionPrefs.parseOrientedResolution("${w}x$h") else SessionPrefs.parseResolution("${w}x$h")
com.droiddeck.launcher.ui.GlideAlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.mode_custom_res_title)) },
@@ -81,7 +81,7 @@ private fun MoreTile(s: FrontEndState, key: String, first: Boolean, modifier: Mo
.then(if (first) Modifier.paneEntry() else Modifier.paneItem("more:$key"))
.testTag("more-$key")
.height(112.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.12f) else colors.surface)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.12f)) else Modifier)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick)
@@ -0,0 +1,392 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.DashPathEffect
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RadialGradient
import android.graphics.RectF
import android.graphics.Shader
import android.graphics.Typeface
import com.droiddeck.launcher.input.DpadStyle
import com.droiddeck.launcher.input.FaceGlyphs
import com.droiddeck.launcher.input.InputControl
import com.droiddeck.launcher.input.PadKit
import com.droiddeck.launcher.input.StickCap
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sin
/** The on-screen controls' shared drawing: one glass material, shaped per virtual controller. */
internal class PadArt(context: Context) {
private val density = context.resources.displayMetrics.density
private val body = Paint(Paint.ANTI_ALIAS_FLAG)
private val shine = Paint(Paint.ANTI_ALIAS_FLAG)
private val edge = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val ink = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; typeface = Typeface.create("sans-serif-medium", Typeface.BOLD) }
private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND }
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
private val path = Path()
private val arm = Path()
private val bar = Path()
private val rect = RectF()
private var shineTop = Float.NaN
private var shineHeight = Float.NaN
private fun dp(value: Float) = value * density
fun button(canvas: Canvas, width: Int, height: Int, control: InputControl, kit: PadKit, pressed: Boolean): Boolean {
val w = width.toFloat()
val h = height.toFloat()
if (min(w, h) <= dp(4f)) return false
when (control) {
InputControl.A, InputControl.B, InputControl.X, InputControl.Y ->
face(canvas, w / 2f, h / 2f, min(w, h) / 2f - dp(2f), control, kit, pressed)
InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT -> shoulder(canvas, w, h, control, kit, pressed)
InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> grip(canvas, w, h, control.label, pressed)
InputControl.L3, InputControl.R3 -> small(canvas, w, h, control.label, pressed)
InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT -> arrow(canvas, w, h, control, pressed)
InputControl.SELECT, InputControl.START, InputControl.GUIDE, InputControl.QAM -> {
val (shape, icon) = systemLook(kit, control)
system(canvas, w, h, shape, icon, pressed)
}
else -> return false
}
return true
}
private fun systemLook(kit: PadKit, control: InputControl): Pair<Shape, Icon> = when {
kit.steam -> when (control) {
InputControl.SELECT -> Shape.CHIP to Icon.VIEW
InputControl.START -> Shape.CHIP to Icon.MENU
InputControl.GUIDE -> Shape.PILL to Icon.STEAM
else -> Shape.PILL to Icon.QAM
}
kit.playStation -> when (control) {
InputControl.SELECT -> Shape.PILL to if (kit == PadKit.DUALSHOCK) Icon.SHARE else Icon.CREATE
InputControl.START -> Shape.PILL to if (kit == PadKit.DUALSHOCK) Icon.OPTIONS else Icon.MENU
InputControl.GUIDE -> Shape.ROUND to Icon.HOME
else -> Shape.ROUND to Icon.QAM
}
else -> Shape.ROUND to when (control) {
InputControl.SELECT -> Icon.BACK
InputControl.START -> Icon.START
InputControl.GUIDE -> Icon.HOME
else -> Icon.QAM
}
}
fun glass(canvas: Canvas, shape: Path, pressed: Boolean, tint: Int = BODY) {
shape.computeBounds(rect, false)
body.color = if (pressed) PRESSED else tint
body.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW)
canvas.drawPath(shape, body)
body.clearShadowLayer()
if (!pressed) {
if (rect.top != shineTop || rect.height() != shineHeight) {
shineTop = rect.top; shineHeight = rect.height()
shine.shader = LinearGradient(0f, rect.top, 0f, rect.top + rect.height() * .55f, SHINE, Color.TRANSPARENT, Shader.TileMode.CLAMP)
}
canvas.drawPath(shape, shine)
}
edge.color = if (pressed) EDGE_PRESSED else EDGE
edge.strokeWidth = dp(1.25f)
canvas.drawPath(shape, edge)
}
fun circle(cx: Float, cy: Float, r: Float): Path = path.apply { reset(); addCircle(cx, cy, r, Path.Direction.CW) }
fun roundRect(l: Float, t: Float, r: Float, b: Float, radius: Float): Path = path.apply {
reset(); addRoundRect(RectF(l, t, r, b), radius, radius, Path.Direction.CW)
}
private fun corners(l: Float, t: Float, r: Float, b: Float, tl: Float, tr: Float, br: Float, bl: Float): Path = path.apply {
reset(); addRoundRect(RectF(l, t, r, b), floatArrayOf(tl, tl, tr, tr, br, br, bl, bl), Path.Direction.CW)
}
fun text(canvas: Canvas, value: String, cx: Float, cy: Float, size: Float, color: Int, maxWidth: Float = Float.MAX_VALUE) {
ink.textSize = size
val measured = ink.measureText(value)
if (measured > maxWidth) ink.textSize = size * maxWidth / measured
ink.color = color
canvas.drawText(value, cx, cy - (ink.ascent() + ink.descent()) / 2f, ink)
}
fun face(canvas: Canvas, cx: Float, cy: Float, r: Float, control: InputControl, kit: PadKit, pressed: Boolean) {
glass(canvas, circle(cx, cy, r), pressed)
when (kit.face) {
FaceGlyphs.COLOR_SYMBOLS -> symbol(canvas, cx, cy, r, control, if (pressed) ON_ACCENT else SYMBOL_COLORS[control] ?: INK)
FaceGlyphs.MONO_SYMBOLS -> symbol(canvas, cx, cy, r, control, if (pressed) ON_ACCENT else INK_SOFT)
FaceGlyphs.COLOR_LETTERS -> text(canvas, control.label, cx, cy, r * .95f, if (pressed) ON_ACCENT else LETTER_COLORS[control] ?: INK)
FaceGlyphs.MONO_LETTERS -> text(canvas, control.label, cx, cy, r * .95f, if (pressed) ON_ACCENT else INK)
}
}
private fun symbol(canvas: Canvas, cx: Float, cy: Float, r: Float, control: InputControl, color: Int) {
val s = r * .4f
line.color = color; line.strokeWidth = r * .12f
when (control) {
InputControl.A -> { canvas.drawLine(cx - s, cy - s, cx + s, cy + s, line); canvas.drawLine(cx + s, cy - s, cx - s, cy + s, line) }
InputControl.B -> canvas.drawCircle(cx, cy, s * 1.05f, line)
InputControl.X -> canvas.drawRoundRect(RectF(cx - s * .95f, cy - s * .95f, cx + s * .95f, cy + s * .95f), s * .18f, s * .18f, line)
else -> canvas.drawPath(path.apply { reset(); moveTo(cx, cy - s * 1.1f); lineTo(cx + s * 1.1f, cy + s * .85f); lineTo(cx - s * 1.1f, cy + s * .85f); close() }, line)
}
}
fun shoulder(canvas: Canvas, w: Float, h: Float, control: InputControl, kit: PadKit, pressed: Boolean) {
val inset = dp(2f)
val l = inset; val t = inset; val r = w - inset; val b = h - inset
val trigger = control == InputControl.LT || control == InputControl.RT
val big = (b - t) * if (trigger) .9f else .62f
val small = dp(5f)
val left = control == InputControl.LT || control == InputControl.LB
glass(canvas, if (left) corners(l, t, r, b, big, small, small, small) else corners(l, t, r, b, small, big, small, small), pressed)
text(canvas, kit.label(control), w / 2f, h / 2f, (b - t) * .46f, if (pressed) ON_ACCENT else INK, (r - l) * .8f)
}
/** A back grip: a capsule along the long side of its box, at most 2.2 times as long as it is thick. */
fun grip(canvas: Canvas, w: Float, h: Float, label: String, pressed: Boolean) {
val inset = dp(3f)
val thick = (min(w, h) - 2 * inset).coerceAtLeast(1f)
val long = (max(w, h) - 2 * inset).coerceAtMost(thick * 2.2f)
val bw = if (w >= h) long else thick; val bh = if (w >= h) thick else long
val cx = w / 2f; val cy = h / 2f
glass(canvas, roundRect(cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2, thick / 2), pressed)
text(canvas, label, cx, cy, thick * .42f, if (pressed) ON_ACCENT else INK_SOFT)
}
fun small(canvas: Canvas, w: Float, h: Float, label: String, pressed: Boolean) {
val r = min(w, h) / 2f * VISUAL
glass(canvas, circle(w / 2f, h / 2f, r), pressed)
text(canvas, label, w / 2f, h / 2f, r * .62f, if (pressed) ON_ACCENT else INK)
}
enum class Shape { ROUND, PILL, CHIP }
enum class Icon { VIEW, MENU, QAM, KEYBOARD, BACK, START, CREATE, HOME, STEAM, SHARE, OPTIONS }
fun system(canvas: Canvas, w: Float, h: Float, shape: Shape, icon: Icon, pressed: Boolean, ink: Int = INK) {
val cx = w / 2f; val cy = h / 2f
val size = when (shape) {
Shape.ROUND -> { val r = min(w, h) / 2f * VISUAL; glass(canvas, circle(cx, cy, r), pressed); r * 1.2f }
Shape.PILL -> { val vh = min(h * VISUAL, w * VISUAL / 2.3f); val vw = vh * 2.3f
glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh / 2), pressed); vh * 1.1f }
Shape.CHIP -> { val vh = min(h * VISUAL, w * VISUAL / 1.9f); val vw = vh * 1.9f
glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh * .32f), pressed); vh * 1.05f }
}
icon(canvas, cx, cy, size, icon, if (pressed) ON_ACCENT else ink)
}
fun icon(canvas: Canvas, cx: Float, cy: Float, size: Float, icon: Icon, color: Int) {
val u = size / 28f
line.color = color; line.strokeWidth = 3.2f * u
fill.color = color; fill.shader = null
when (icon) {
Icon.VIEW -> {
canvas.drawRoundRect(RectF(cx - 12 * u, cy - 9 * u, cx + 3 * u, cy + 3 * u), 3 * u, 3 * u, line)
fill.color = Color.argb(230, 14, 16, 20)
canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, fill)
canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, line)
}
Icon.MENU -> for (dy in intArrayOf(-7, 0, 7)) canvas.drawLine(cx - 11 * u, cy + dy * u, cx + 11 * u, cy + dy * u, line)
Icon.QAM -> for (dx in intArrayOf(-10, 0, 10)) canvas.drawCircle(cx + dx * u, cy, 3.4f * u, fill)
Icon.KEYBOARD -> {
canvas.drawRoundRect(RectF(cx - 16 * u, cy - 11 * u, cx + 16 * u, cy + 11 * u), 4.5f * u, 4.5f * u, line)
for (row in 0..1) for (col in 0..3) canvas.drawCircle(cx + (-9 + col * 6) * u, cy + (-4 + row * 5) * u, 1.7f * u, fill)
line.strokeWidth = 2.6f * u; canvas.drawLine(cx - 6 * u, cy + 6 * u, cx + 6 * u, cy + 6 * u, line)
}
Icon.BACK, Icon.START -> {
val f = if (icon == Icon.START) 1f else -1f
line.strokeWidth = 2.6f * u
canvas.drawPath(path.apply { reset(); moveTo(cx - 6 * f * u, cy - 8 * u); lineTo(cx + 7 * f * u, cy); lineTo(cx - 6 * f * u, cy + 8 * u); close() }, line)
}
Icon.CREATE -> {
line.strokeWidth = 2.8f * u
canvas.drawLine(cx - 8 * u, cy + 8 * u, cx - 2 * u, cy - 8 * u, line)
canvas.drawLine(cx + u, cy + 8 * u, cx + 4 * u, cy - 2 * u, line)
canvas.drawLine(cx + 8 * u, cy + 8 * u, cx + 9 * u, cy + 3 * u, line)
}
Icon.HOME -> canvas.drawPath(path.apply {
reset(); moveTo(cx - 13 * u, cy - u); lineTo(cx, cy - 13 * u); lineTo(cx + 13 * u, cy - u)
moveTo(cx - 9 * u, cy - 4 * u); lineTo(cx - 9 * u, cy + 11 * u); lineTo(cx + 9 * u, cy + 11 * u); lineTo(cx + 9 * u, cy - 4 * u)
}, line)
Icon.STEAM, Icon.SHARE, Icon.OPTIONS -> {
ink.letterSpacing = .12f
text(canvas, when (icon) { Icon.STEAM -> "STEAM"; Icon.SHARE -> "SHARE"; else -> "OPTIONS" }, cx, cy, 14 * u, color, size * 1.9f)
ink.letterSpacing = 0f
}
}
}
private fun chevron(canvas: Canvas, ax: Float, ay: Float, dx: Float, dy: Float, k: Float, color: Int, width: Float) {
val px = -dy; val py = dx
line.color = color; line.strokeWidth = width
canvas.drawPath(path.apply {
reset(); moveTo(ax - dx * k * .5f + px * k, ay - dy * k * .5f + py * k); lineTo(ax + dx * k * .6f, ay + dy * k * .6f)
lineTo(ax - dx * k * .5f - px * k, ay - dy * k * .5f - py * k)
}, line)
}
private fun cross(target: Path, cx: Float, cy: Float, s: Float, h: Float, rc: Float) = target.apply {
reset()
addRoundRect(RectF(cx - h, cy - s, cx + h, cy + s), rc, rc, Path.Direction.CW)
bar.reset()
bar.addRoundRect(RectF(cx - s, cy - h, cx + s, cy + h), rc, rc, Path.Direction.CW)
op(bar, Path.Op.UNION)
}
fun arrow(canvas: Canvas, w: Float, h: Float, control: InputControl, pressed: Boolean) {
val cx = w / 2f; val cy = h / 2f
val s = min(w, h) / 2f - dp(2f)
val (dx, dy) = when (control) {
InputControl.UP -> 0f to -1f
InputControl.RIGHT -> 1f to 0f
InputControl.DOWN -> 0f to 1f
else -> -1f to 0f
}
glass(canvas, roundRect(cx - s, cy - s, cx + s, cy + s, s * .32f), pressed)
chevron(canvas, cx, cy, dx, dy, s * .3f, if (pressed) ON_ACCENT else INK, s * .14f)
}
/** [held] bits: up 1, right 2, down 4, left 8. */
fun dpad(canvas: Canvas, w: Float, h: Float, kit: PadKit, held: Int, chevrons: Boolean = true, ink: Int = INK) {
val cx = w / 2f; val cy = h / 2f
val s = min(w, h) / 2f - dp(3f)
if (s <= 0f) return
val dirs = arrayOf(floatArrayOf(0f, -1f), floatArrayOf(1f, 0f), floatArrayOf(0f, 1f), floatArrayOf(-1f, 0f))
when (kit.dpad) {
DpadStyle.CROSS, DpadStyle.DISC -> {
val disc = kit.dpad == DpadStyle.DISC
val arms = if (disc) s * .78f else s
val half = if (disc) s * .25f else s * .37f
if (disc) {
glass(canvas, circle(cx, cy, s), false)
fill.shader = null; fill.color = Color.argb(18, 255, 255, 255)
canvas.drawPath(cross(arm, cx, cy, arms, half, half * .5f), fill)
edge.color = Color.argb(56, 255, 255, 255); edge.strokeWidth = dp(1f)
canvas.drawPath(arm, edge)
} else glass(canvas, cross(arm, cx, cy, arms, half, half * .43f), false)
for (i in 0..3) {
val dx = dirs[i][0]; val dy = dirs[i][1]
val on = held and (1 shl i) != 0
if (on && half > dp(2f)) {
fill.shader = null; fill.color = PRESSED
val near = half + dp(1f); val far = arms - dp(2f); val side = half - dp(2f)
rect.set(if (dx == 0f) cx - side else if (dx > 0) cx + near else cx - far, if (dy == 0f) cy - side else if (dy > 0) cy + near else cy - far,
if (dx == 0f) cx + side else if (dx > 0) cx + far else cx - near, if (dy == 0f) cy + side else if (dy > 0) cy + far else cy - near)
canvas.drawRoundRect(rect, half * .4f, half * .4f, fill)
}
val m = (arms + half) / 2f
if (chevrons) chevron(canvas, cx + dx * m, cy + dy * m, dx, dy, half * .32f, if (on) ON_ACCENT else ink, half * .17f)
}
if (!disc) { fill.shader = null; fill.color = Color.argb(18, 255, 255, 255); canvas.drawCircle(cx, cy, half * .36f, fill) }
}
DpadStyle.ARROWS -> {
fill.shader = null; fill.color = Color.argb(56, 0, 0, 0)
canvas.drawCircle(cx, cy, s, fill)
edge.color = Color.argb(36, 255, 255, 255); edge.strokeWidth = dp(1f)
canvas.drawCircle(cx, cy, s, edge)
val bw = s * .5f; val tip = s * .14f; val base = s * .38f; val top = s * .9f; val rc = s * .11f
for (i in 0..3) {
canvas.save()
canvas.rotate(i * 90f, cx, cy)
arm.reset()
arm.moveTo(cx, cy - tip); arm.lineTo(cx - bw / 2, cy - base); arm.lineTo(cx - bw / 2, cy - top + rc)
arm.quadTo(cx - bw / 2, cy - top, cx - bw / 2 + rc, cy - top); arm.lineTo(cx + bw / 2 - rc, cy - top)
arm.quadTo(cx + bw / 2, cy - top, cx + bw / 2, cy - top + rc); arm.lineTo(cx + bw / 2, cy - base); arm.close()
val on = held and (1 shl i) != 0
glass(canvas, arm, on)
val ty = cy - (base + top) / 2f; val ts = s * .07f
fill.shader = null; fill.color = if (on) ON_ACCENT else INK_SOFT
if (chevrons) canvas.drawPath(path.apply { reset(); moveTo(cx, ty - ts); lineTo(cx + ts, ty + ts * .7f); lineTo(cx - ts, ty + ts * .7f); close() }, fill)
canvas.restore()
}
}
}
}
fun stick(canvas: Canvas, cx: Float, cy: Float, radius: Float, kit: PadKit, kx: Float, ky: Float, active: Boolean) {
fill.alpha = 255
fill.shader = RadialGradient(cx, cy, radius, WELL_IN, WELL_OUT, Shader.TileMode.CLAMP)
fill.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW)
canvas.drawCircle(cx, cy, radius, fill)
fill.clearShadowLayer(); fill.shader = null
edge.color = Color.argb(61, 255, 255, 255); edge.strokeWidth = dp(1.25f)
canvas.drawCircle(cx, cy, radius, edge)
line.color = Color.argb(71, 255, 255, 255); line.strokeWidth = dp(1.4f)
for (i in 0 until 8) {
val a = i * Math.PI / 4
val c = cos(a).toFloat(); val n = sin(a).toFloat()
canvas.drawLine(cx + c * (radius - dp(7f)), cy + n * (radius - dp(7f)), cx + c * (radius - dp(3.5f)), cy + n * (radius - dp(3.5f)), line)
}
if (active && (kx != 0f || ky != 0f)) {
val angle = Math.toDegrees(atan2(ky, kx).toDouble()).toFloat()
line.color = ACCENT; line.strokeWidth = dp(3f)
val r = radius - dp(2f)
canvas.drawArc(RectF(cx - r, cy - r, cx + r, cy + r), angle - 35f, 70f, false, line)
}
val k = radius * .46f
val x = cx + kx; val y = cy + ky
if (kit.stick == StickCap.RINGED) {
line.color = if (active) ACCENT else Color.argb(140, 226, 232, 240); line.strokeWidth = dp(2.8f)
canvas.drawCircle(x, y, k * 1.14f, line)
}
glass(canvas, circle(x, y, k), false)
when (kit.stick) {
StickCap.DISHED -> {
fill.shader = RadialGradient(x, y - k * .1f, k * .74f, Color.argb(107, 0, 0, 0), Color.TRANSPARENT, Shader.TileMode.CLAMP)
canvas.drawCircle(x, y, k * .74f, fill); fill.shader = null
edge.color = if (active) ACCENT else Color.argb(51, 255, 255, 255); edge.strokeWidth = dp(1f)
canvas.drawCircle(x, y, k * .74f, edge)
}
StickCap.KNURLED -> {
line.color = if (active) ACCENT else Color.argb(66, 255, 255, 255); line.strokeWidth = dp(2.3f)
line.pathEffect = DashPathEffect(floatArrayOf(dp(1.2f), dp(1.9f)), 0f)
canvas.drawCircle(x, y, k * .9f, line); line.pathEffect = null
fill.color = Color.argb(56, 0, 0, 0); canvas.drawCircle(x, y, k * .6f, fill)
}
StickCap.RINGED -> { edge.color = Color.argb(36, 255, 255, 255); edge.strokeWidth = dp(1f); canvas.drawCircle(x, y, k * .66f, edge) }
}
}
fun trackpad(canvas: Canvas, w: Float, h: Float, touching: Boolean, fx: Float, fy: Float) {
val inset = dp(1.5f)
val radius = min(w, h) * .14f
fill.shader = null; fill.color = Color.argb(51, 14, 16, 20)
rect.set(inset, inset, w - inset, h - inset)
canvas.drawRoundRect(rect, radius, radius, fill)
edge.color = if (touching) Color.argb(191, 0x1A, 0x9F, 0xFF) else Color.argb(51, 255, 255, 255)
edge.strokeWidth = dp(if (touching) 1.5f else 1f)
canvas.drawRoundRect(rect, radius, radius, edge)
if (!touching) return
val glow = min(w, h) * .3f
fill.shader = RadialGradient(fx, fy, glow, GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP)
canvas.drawCircle(fx, fy, glow, fill); fill.shader = null
fill.color = ACCENT; canvas.drawCircle(fx, fy, dp(5f), fill)
}
companion object {
const val VISUAL = .72f
val ACCENT = Color.rgb(0x1A, 0x9F, 0xFF)
val ON_ACCENT = Color.rgb(0x03, 0x11, 0x1F)
val INK = Color.rgb(0xF4, 0xF7, 0xFB)
val INK_SOFT = Color.argb(209, 0xF4, 0xF7, 0xFB)
private val BODY = Color.argb(133, 14, 16, 20)
private val PRESSED = Color.argb(235, 0x1A, 0x9F, 0xFF)
private val SHINE = Color.argb(43, 255, 255, 255)
private val EDGE = Color.argb(77, 255, 255, 255)
private val EDGE_PRESSED = Color.argb(140, 255, 255, 255)
private val SHADOW = Color.argb(97, 0, 0, 0)
private val WELL_IN = Color.argb(140, 5, 7, 10)
private val WELL_OUT = Color.argb(71, 14, 16, 20)
private val GLOW = Color.argb(140, 0x1A, 0x9F, 0xFF)
private val LETTER_COLORS = mapOf(InputControl.A to Color.rgb(0x5C, 0xCB, 0x5F), InputControl.B to Color.rgb(0xF0, 0x50, 0x4A),
InputControl.X to Color.rgb(0x4C, 0x9B, 0xF0), InputControl.Y to Color.rgb(0xF5, 0xC0, 0x2E))
private val SYMBOL_COLORS = mapOf(InputControl.A to Color.rgb(0x8D, 0xB4, 0xF2), InputControl.B to Color.rgb(0xF2, 0x61, 0x6B),
InputControl.X to Color.rgb(0xEE, 0x93, 0xD6), InputControl.Y to Color.rgb(0x45, 0xCB, 0xAA))
}
}
@@ -6,6 +6,8 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
@@ -13,26 +15,40 @@ import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.ui.input.pointer.util.addPointerInputChange
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.findRootCoordinates
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.unit.dp
import kotlin.math.abs
internal object PageSwipe {
var locks by mutableIntStateOf(0)
var direction by mutableIntStateOf(0)
var on by mutableStateOf(true)
}
@Composable
internal fun Modifier.pageSwipe(enabled: () -> Boolean, onSwipe: (Int) -> Unit): Modifier {
internal fun Modifier.pageSwipe(enabled: () -> Boolean, edgeGuard: () -> Boolean = { false }, onSwipe: (Int) -> Unit): Modifier {
val enabledNow by rememberUpdatedState(enabled)
val edgeGuardNow by rememberUpdatedState(edgeGuard)
val onSwipeNow by rememberUpdatedState(onSwipe)
return pointerInput(Unit) {
val placed = remember { arrayOfNulls<LayoutCoordinates>(1) }
return onGloballyPositioned { placed[0] = it }.pointerInput(Unit) {
val distance = 72.dp.toPx()
val flingDistance = 32.dp.toPx()
val flingVelocity = 900.dp.toPx()
val slop = viewConfiguration.touchSlop
val edge = 32.dp.toPx()
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Final)
if (!enabledNow() || PageSwipe.locks > 0) return@awaitEachGesture
if (!PageSwipe.on || !enabledNow() || PageSwipe.locks > 0) return@awaitEachGesture
// A swipe in from the screen's edge brings back hidden system bars; it should not also turn the page.
if (edgeGuardNow()) {
val at = placed[0]?.takeIf { it.isAttached }
val x = at?.localToRoot(down.position)?.x ?: down.position.x
val width = at?.findRootCoordinates()?.size?.width?.toFloat() ?: size.width.toFloat()
if (x < edge || x > width - edge) return@awaitEachGesture
}
val tracker = VelocityTracker()
tracker.addPointerInputChange(down)
var total = Offset.Zero
@@ -48,7 +64,7 @@ internal fun Modifier.pageSwipe(enabled: () -> Boolean, onSwipe: (Int) -> Unit):
if (!mine && abs(total.x) > slop && abs(total.x) > abs(total.y) * 2f) mine = true
if (mine) change.consume()
}
if (!mine || PageSwipe.locks > 0) return@awaitEachGesture
if (!mine || !PageSwipe.on || PageSwipe.locks > 0) return@awaitEachGesture
val vx = tracker.calculateVelocity().x
val horizontal = abs(total.x) > abs(total.y) * 1.5f
val far = abs(total.x) > distance
@@ -12,20 +12,25 @@ import com.droiddeck.launcher.session.SessionDisplay
@Composable
fun ResolutionRow(
host: MenuHost, choice: String, panel: Pair<Int, Int>, onPick: (String) -> Unit,
host: MenuHost, id: String, title: String, stored: String, choice: String, link: String, followTarget: String,
panel: Pair<Int, Int>, onPick: (String) -> Unit,
chipModifier: Modifier = Modifier,
portrait: Boolean = false,
) {
val custom = "custom"
val linked = stored == link
val size = SessionDisplay.resolveChoice(panel, choice, portrait)
val screen = SessionDisplay.resolveChoice(panel, SessionDisplay.MATCH_SCREEN, portrait)
val choices = SessionDisplay.resolutionOptions(panel)
val customFollow = SessionDisplay.isFollow(choice) && choice !in choices
val selected = if (SessionDisplay.isFollow(choice)) choice
val customFollow = !linked && SessionDisplay.isFollow(choice) && choice !in choices
val selected = if (linked) link else if (SessionDisplay.isFollow(choice)) choice
else if (size == screen) SessionDisplay.MATCH_SCREEN else choice
var editCustom by remember { mutableStateOf(false) }
var editFollow by remember { mutableStateOf(false) }
val options = choices.map { value ->
val followSize = SessionDisplay.resolveChoice(panel, followTarget, portrait)
val linkLabel = stringResource(if (link == SessionDisplay.LINK_LANDSCAPE) R.string.display_follow_landscape else R.string.display_follow_portrait,
followSize.first, followSize.second)
val options = listOf(link to linkLabel) + choices.map { value ->
val dimensions = SessionDisplay.resolveChoice(panel, value, portrait)
value to if (value == SessionDisplay.MATCH_SCREEN) stringResource(R.string.display_match_screen, screen.first, screen.second)
else if (value == SessionDisplay.FOLLOW_SCREEN) stringResource(R.string.display_follow_screen)
@@ -35,18 +40,18 @@ fun ResolutionRow(
else "${dimensions.first}×${dimensions.second}"
} + listOf(SessionDisplay.FOLLOW_CUSTOM to stringResource(R.string.display_follow_screen_scaled,
if (customFollow) SessionDisplay.formatScale(SessionDisplay.followScale(choice) ?: 1f) else "…"
) + if (customFollow) " (${size.first}×${size.second})" else "") + (custom to if (selected in choices) stringResource(R.string.mode_res_custom)
) + if (customFollow) " (${size.first}×${size.second})" else "") + (custom to if (selected in choices || linked) stringResource(R.string.mode_res_custom)
else stringResource(R.string.mode_res_custom_value, size.first, size.second))
ChoiceRow(host, "resolution", stringResource(R.string.display_resolution),
ChoiceRow(host, id, title,
stringResource(R.string.common_applies_next_session),
options, if (selected in choices) selected else if (customFollow) SessionDisplay.FOLLOW_CUSTOM else custom, chipModifier = chipModifier,
options, if (linked || selected in choices) selected else if (customFollow) SessionDisplay.FOLLOW_CUSTOM else custom, chipModifier = chipModifier,
onPick = { value ->
if (value == custom) editCustom = true
else if (value == SessionDisplay.FOLLOW_CUSTOM) editFollow = true
else onPick(value) })
if (editCustom) CustomResolutionDialog(size,
onSave = { value -> editCustom = false; onPick("${value.first}x${value.second}") },
onDismiss = { editCustom = false })
onDismiss = { editCustom = false }, portrait = portrait)
if (editFollow) CustomFollowScaleDialog(SessionDisplay.followScale(choice)?.takeIf { it > 1f },
onSave = { value -> editFollow = false; onPick(SessionDisplay.followScaled(value)) },
onDismiss = { editFollow = false })
@@ -0,0 +1,76 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
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.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalView
import kotlinx.coroutines.flow.first
internal object ScreenTaps {
var count by mutableStateOf(0)
}
/** A field that opens on a heavy page can take focus after the next tap has already finished. */
@Composable
internal fun CancelPendingFocus(pending: Boolean, askedAtTap: Int, focused: Boolean, cancel: () -> Unit) {
val focusedNow by rememberUpdatedState(focused)
val cancelNow by rememberUpdatedState(cancel)
LaunchedEffect(pending, askedAtTap) {
if (!pending) return@LaunchedEffect
snapshotFlow { ScreenTaps.count }.first { it != askedAtTap }
if (!focusedNow) cancelNow()
}
}
/**
* Tapped controls do not take focus in touch mode, so a text field would otherwise keep it, and its highlight.
* [x] and [y] share coordinates with [origin], the field's own position.
*/
internal fun releaseTextField(field: EditText, origin: IntArray, x: Float, y: Float) {
val margin = 12 * field.resources.displayMetrics.density
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
field.clearFocus()
(field.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(field.windowToken, 0)
}
/** 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
val placed = remember { arrayOfNulls<LayoutCoordinates>(1) }
onGloballyPositioned { placed[0] = it }.pointerInput(view) {
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
ScreenTaps.count++
var up: Offset? = null
while (true) {
val change = awaitPointerEvent(PointerEventPass.Final).changes.firstOrNull { it.id == down.id } ?: break
if ((change.position - down.position).getDistance() > viewConfiguration.touchSlop) break
if (!change.pressed) { up = change.position; break }
}
val at = up?.let { placed[0]?.takeIf { c -> c.isAttached }?.localToWindow(it) } ?: return@awaitEachGesture
view.post {
val field = view.findFocus() as? EditText ?: return@post
releaseTextField(field, IntArray(2).also(field::getLocationInWindow), at.x, at.y)
}
}
}
}
@@ -305,7 +305,7 @@ class SecondScreenPresentation(
(onSteamMenu to onQam).takeIf { SessionState.mode == SessionService.MODE_STEAM }, onSwap,
picker = picker?.let { pick -> { pick(SecondScreenMode.DESKTOP) } }), weightParams())
}
SecondScreenMode.NONE -> Unit
SecondScreenMode.NONE, SecondScreenMode.MENU -> Unit
}
}
@@ -1,5 +1,11 @@
package com.droiddeck.launcher.ui
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.SessionPrefs
internal enum class SessionDrawerPage(val firstControl: String) {
CONTROLLER("input-profile"),
GLASSES("glasses-game"),
@@ -12,14 +18,69 @@ internal enum class SessionDrawerPage(val firstControl: String) {
SESSION("suspend"),
}
internal fun sessionDrawerPages(
internal object DrawerPages {
var order by mutableStateOf(SessionDrawerPage.entries.toList())
private set
var hidden by mutableStateOf(emptySet<SessionDrawerPage>())
private set
/** The order captured when a page row was grabbed in Arrange pages; Back restores it. */
var heldFrom: List<SessionDrawerPage>? = null
fun hideable(page: SessionDrawerPage) = page != SessionDrawerPage.SESSION
fun load(context: Context) {
order = arrange(SessionPrefs.drawerPageOrder(context))
hidden = SessionPrefs.drawerPageHidden(context).mapNotNull { name -> SessionDrawerPage.entries.firstOrNull { it.name == name } }
.filter(::hideable).toSet()
}
fun arrange(saved: List<String>): List<SessionDrawerPage> {
val all = SessionDrawerPage.entries
val out = saved.mapNotNull { name -> all.firstOrNull { it.name == name } }.distinct().toMutableList()
for (page in all.filterNot { it in out }) {
val before = all.subList(0, all.indexOf(page)).lastOrNull { it in out }
out.add(if (before == null) 0 else out.indexOf(before) + 1, page)
}
return out
}
fun setHidden(context: Context, page: SessionDrawerPage, hide: Boolean) {
hidden = if (hide && hideable(page)) hidden + page else hidden - page
if (DevPreview.drawer == null) SessionPrefs.setDrawerPageHidden(context, hidden.map { it.name }.toSet())
}
/** [placed] holds the pages on offer in their new order; pages not on offer keep their slots. */
fun rearrange(context: Context, placed: List<SessionDrawerPage>) {
if (placed.isEmpty() || !order.containsAll(placed)) return
val next = placed.iterator()
order = order.map { if (it in placed) next.next() else it }
if (DevPreview.drawer == null) SessionPrefs.setDrawerPageOrder(context, order.map { it.name })
}
fun reset(context: Context) {
order = SessionDrawerPage.entries.toList()
hidden = emptySet()
if (DevPreview.drawer != null) return
SessionPrefs.setDrawerPageOrder(context, order.map { it.name })
SessionPrefs.setDrawerPageHidden(context, emptySet())
}
fun isDefault() = order == SessionDrawerPage.entries.toList() && hidden.isEmpty()
}
internal fun offeredDrawerPages(
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> =
SessionDrawerPage.entries.filter {
DrawerPages.order.filter {
(hasGlasses || it != SessionDrawerPage.GLASSES) &&
(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 }
internal fun List<SessionDrawerPage>.step(current: SessionDrawerPage, direction: Int): SessionDrawerPage {
val index = indexOf(current).coerceAtLeast(0)
return this[Math.floorMod(index + direction, size)]
@@ -44,9 +44,11 @@ import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.material.icons.outlined.DesktopWindows
import androidx.compose.material.icons.outlined.Layers
import androidx.compose.material.icons.outlined.Pause
import androidx.compose.material.icons.outlined.PlayArrow
import androidx.compose.material.icons.outlined.PictureInPictureAlt
import androidx.compose.material.icons.automirrored.outlined.ExitToApp
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.Tune
import androidx.compose.material.icons.outlined.Speed
import androidx.compose.material.icons.outlined.SportsEsports
import androidx.compose.material3.Icon
@@ -162,7 +164,7 @@ import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_BEHAVIOR_
import kotlinx.coroutines.flow.collect
import java.util.Locale
private val SessionDrawerPage.title: Int get() = when (this) {
internal val SessionDrawerPage.title: Int get() = when (this) {
SessionDrawerPage.CONTROLLER -> R.string.drawer_page_controller
SessionDrawerPage.GLASSES -> R.string.drawer_page_glasses
SessionDrawerPage.DISPLAY -> R.string.drawer_page_display
@@ -174,7 +176,7 @@ private val SessionDrawerPage.title: Int get() = when (this) {
SessionDrawerPage.SESSION -> R.string.mode_session
}
private val SessionDrawerPage.icon get() = when (this) {
internal val SessionDrawerPage.icon get() = when (this) {
SessionDrawerPage.CONTROLLER -> Icons.Outlined.SportsEsports
SessionDrawerPage.GLASSES -> GlassesIcon
SessionDrawerPage.DISPLAY -> Icons.Outlined.DesktopWindows
@@ -229,6 +231,8 @@ class DrawerActions(
val onMicEnabled: (Boolean) -> Unit = {},
val backHold: Boolean = true,
val onBackHold: (Boolean) -> Unit = {},
val dockedMenuController: Boolean = false,
val onDockedMenuController: (Boolean) -> Unit = {},
val backActionsInverted: Boolean,
val backDoubleTapMs: Int = 500,
val onBackDoubleTapMs: (Int) -> Unit = {},
@@ -331,6 +335,7 @@ class DrawerActions(
val onSteamVr: (String) -> Unit = {},
val onTextureAnisotropy: (Int?) -> Unit = {},
val onTextureLodBias: (String?) -> Unit = {},
val onSelectMenuMode: () -> Unit = {},
val onSecondScreenMode: (SecondScreenMode) -> Unit,
val onSecondScreenDisplay: (Int) -> Unit,
val onLaunchAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit,
@@ -339,6 +344,10 @@ class DrawerActions(
val pipAutoEnter: Boolean = false,
val onPip: () -> Unit = {},
val onPause: () -> Unit = {},
val paused: Boolean = false,
val orientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
val onOrientation: (Int) -> Unit = {},
val onResume: () -> Unit = {},
val onPipAutoEnter: (Boolean) -> Unit = {},
val unfoldedControls: Boolean? = null,
val adaptiveSticks: Boolean? = null,
@@ -392,7 +401,10 @@ class DrawerActions(
internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, controllerActive: Boolean, onPageChange: (SessionDrawerPage) -> Unit, a: DrawerActions, docked: Boolean = false,
backRequest: Int = 0, onLayerChange: (Boolean) -> Unit = {}) {
val pages = sessionDrawerPages(a.glassesPresent)
val page = requestedPage.takeIf { it in pages } ?: SessionDrawerPage.CONTROLLER
val page = requestedPage.takeIf { it in pages } ?: pages.first()
var managing by rememberSaveable { mutableStateOf(false) }
var releaseSignal by remember { mutableStateOf(0) }
val drawerContext = androidx.compose.ui.platform.LocalContext.current
LaunchedEffect(requestedPage, pages) { if (page != requestedPage) onPageChange(page) }
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -509,16 +521,24 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
.blockTouches()
.focusGroup()
.controllerBack {
if (host.open != null) host.open = null else a.onClose()
when {
host.open != null -> host.open = null
managing -> DrawerPages.heldFrom?.let { held ->
DrawerPages.rearrange(drawerContext, held)
releaseSignal++
} ?: run { managing = false }
else -> a.onClose()
}
}
.padding(12.dp),
) {
val showPicker = a.secondScreenDisplays.isNotEmpty()
val roomyHeader = sheetWidth >= if (showPicker) 560.dp else 408.dp
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp)
modifier = Modifier.weight(1f).heightIn(min = 44.dp)
.then(if (roomyHeader) Modifier else Modifier.horizontalScroll(rememberScrollState())),
) {
SteamActionPill(
@@ -529,18 +549,18 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
ScreenPicker(
secondScreenModes(a.secondScreenNone, com.droiddeck.launcher.session.SessionState.deckPad, a.dashboardAvailable, a.desktopAvailable),
a.secondScreenMode, onPick = { host.open = null; a.onSecondScreenMode(it) },
onMenu = if (docked) ({ host.open = null }) else null, menuShown = docked,
onMenu = if (docked) ({ host.open = null; a.onSelectMenuMode() }) else null, menuShown = docked,
),
focus.track(page, "screen").testTag("drawer-screen-picker"),
)
} else if (roomyHeader) Spacer(Modifier.weight(1f))
SteamActionPill(
stringResource(R.string.stores_dl_pause), Icons.Outlined.Pause, focus.track(page, "pause"),
) { host.open = null; a.onPause() }
stringResource(if (a.paused) R.string.resume_session else R.string.stores_dl_pause),
if (a.paused) Icons.Outlined.PlayArrow else Icons.Outlined.Pause, focus.track(page, "pause"),
) { host.open = null; if (a.paused) a.onResume() else a.onPause() }
if (a.pipSupported) SteamActionPill(
stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, focus.track(page, "pip"),
) { host.open = null; a.onPip() }
if (docked) StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true }
val steamActions = a.steam && a.onSteamMenu != null && a.onQam != null
val qamInteraction = remember { MutableInteractionSource() }
var qamStartedOnPress by remember { mutableStateOf(false) }
@@ -570,7 +590,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
onQamConfirm = { host.open = null; a.onQam?.invoke() },
showShortcuts = !docked,
)
if (!docked) StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true }
}
StopSessionButton(modifier = focus.track(page, "stop").onGloballyPositioned { stopCoords = it }) { host.open = null; confirmStop = true }
}
a.onAchievements?.let { show ->
DrawerAchievementsRow(a.achievementsProgress, Modifier.padding(top = if (short) 6.dp else 10.dp).then(focus.track(page, "achievements"))) {
@@ -589,7 +610,15 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
DrawerBumper("RB", stringResource(R.string.drawer_next_page), modifier = focus.track(page, "next")) {
host.open = null; onPageChange(pages.step(page, 1))
}
SmallIconButton(
Icons.Outlined.Tune, stringResource(R.string.drawer_manage_pages), colors.onSurfaceVariant,
) { host.open = null; managing = !managing }
}
if (managing) ManageDrawerPages(
offeredDrawerPages(a.glassesPresent),
Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp),
releaseSignal,
) { managing = false } else {
if (page == SessionDrawerPage.GLASSES) SegmentedTabs(
glassesPages, glassesTab, modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
tabModifier = { key -> focus.track(page, "glasses-tab-$key").testTag("glasses-tab-$key") },
@@ -644,6 +673,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
}
}
SettingsGroup(stringResource(R.string.setup_orientation)) {
ChoiceRow(host, "orientation", stringResource(R.string.setup_session_orientation), null,
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
a.orientation, chipModifier = focus.track(page, "orientation"), onPick = a.onOrientation)
}
SettingsGroup(stringResource(R.string.display_image_scaling)) {
if (a.steam) SettingsRow(stringResource(R.string.display_integer_scaling), null) {
PadTextButton(
@@ -760,6 +794,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
SessionPrefs.BACK_DOUBLE_TAP_MS_OPTIONS.map { it to stringResource(R.string.back_tap_ms, it) },
a.backDoubleTapMs, chipModifier = focus.track(page, "back-double-tap"), onPick = a.onBackDoubleTapMs)
PhysicalShortcutRows(modifierFor = { focus.track(page, "physical-shortcut-${it.name}") })
if (a.secondScreenDisplays.isNotEmpty()) ToggleRow(host, "docked-menu-controller", stringResource(R.string.drawer_docked_menu_controller),
null, a.dockedMenuController,
chipModifier = focus.track(page, "docked-menu-controller"), onChange = a.onDockedMenuController)
ToggleRow(host, "corner-tap", stringResource(R.string.drawer_corner_tap),
stringResource(R.string.drawer_corner_tap_hint), a.cornerTap,
chipModifier = focus.track(page, "corner-tap"), onChange = a.onCornerTap)
@@ -926,6 +963,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
}
} }
}
}
StopConfirm(
open = confirmStop,
@@ -983,7 +1021,7 @@ private fun DrawerActionButton(text: String, icon: androidx.compose.ui.graphics.
}
@Composable
private fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, progress: Float? = null, onClick: () -> Unit) {
internal fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, progress: Float? = null, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val source = remember { MutableInteractionSource() }
@@ -1005,15 +1043,14 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val fill by animateColorAsState(if (hot) colors.error.copy(alpha = 0.18f) else Color.Transparent, Motion.tw(220), label = "dangerFill")
val shape = RoundedCornerShape(20.dp)
val shape = androidx.compose.foundation.shape.CircleShape
val stopDescription = stringResource(R.string.stop_session)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center,
modifier = modifier.heightIn(min = 44.dp).widthIn(min = 44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop")
modifier = modifier.size(44.dp).semantics { contentDescription = stopDescription }.testTag("drawer-stop")
.clip(shape).background(fill).glideBorder(hot, shape, colors.error.copy(alpha = 0.9f), colors.error.copy(alpha = 0.55f))
.hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 12.dp),
.controllerConfirm(onClick = onClick),
) {
Icon(Icons.Outlined.PowerSettingsNew, contentDescription = null, tint = colors.error, modifier = Modifier.size(18.dp))
}
@@ -1571,12 +1608,15 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
chipModifier = track("cmp-proton"),
onPick = { id -> a.onGameProton(gameProfile.appId, id) },
)
val gameTool = snap.protons.firstOrNull { it.proton.id == gameProfile.protonId }?.proton?.dir?.name
for (comp in ComponentsManager.COMPONENTS) {
val value = gameProfile.components.getValue(comp)
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val options: List<Pair<String?, String>> =
listOf(null to stringResource(R.string.comp_game_use_general)) +
if (managedDxvk) emptyList() else snap.packages.filter { it.comp == comp }.map { it.file to it.version }
if (managedDxvk) emptyList() else ComponentsManager.forTool(
comp, gameTool, snap.packages.filter { it.comp == comp }, gameProfile.componentFiles[comp],
) { it.file }.map { it.file to it.version }
DrawerStackedChoice(
host = host,
key = "game-cmp-$comp",
@@ -1659,7 +1699,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val originals = view.originals.filter { it.comp == comp }
val options = originals.map { "orig:${it.protonVersion}" to (if (it.protonVersion == build) originalLabel else stringResource(R.string.comp_original, it.protonVersion)) } +
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
ComponentsManager.forTool(comp, p.dir.name, snap.packages.filter { it.comp == comp }, st.activeFile) { it.file }.map { it.file to it.version }
if (options.isEmpty() && !managedDxvk) continue
val current = st.activeFile ?: "orig:$build"
val shown = options.firstOrNull { it.first == current }?.second
@@ -108,6 +108,8 @@ internal object SettingsIndex {
s(SettingsSection.LAUNCHER, R.string.setup_launcher_orientation, "rotate", "portrait"),
s(SettingsSection.LAUNCHER, R.string.setup_session_orientation, "rotate", "portrait"),
s(SettingsSection.LAUNCHER, R.string.setup_fullscreen),
s(SettingsSection.LAUNCHER, R.string.setup_page_swipe, "gesture"),
s(SettingsSection.LAUNCHER, R.string.setup_controller_haptics, "vibration", "rumble"),
s(SettingsSection.LAUNCHER, R.string.setup_dual_screen_launcher, "thor", "second screen", "bottom screen"),
s(SettingsSection.LAUNCHER, R.string.setup_low_storage_warning),
s(SettingsSection.LAUNCHER, R.string.mode_sgdb_key, "artwork", "steamgriddb"),
@@ -49,6 +49,12 @@ internal fun SettingsPillSearch(
val icon = remember { FocusRequester() }
var toIcon by remember { mutableStateOf(false) }
var focusOnOpen by remember { mutableStateOf(false) }
var focusTap by remember { mutableStateOf(0) }
var fieldFocused by remember { mutableStateOf(false) }
CancelPendingFocus(focusOnOpen, focusTap, fieldFocused) {
focusOnOpen = false
if (query.isEmpty()) onClose()
}
val close = { toIcon = true; focusOnOpen = false; onClose() }
BackHandler(enabled = searching) { close() }
LaunchedEffect(toIcon, searching, open <= 0.01f) {
@@ -73,15 +79,18 @@ internal fun SettingsPillSearch(
Box(Modifier.width(w).graphicsLayer { alpha = (open * 1.6f).coerceAtMost(1f) }) {
AdbTextField(
value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search,
placeholder = stringResource(R.string.settings_search), compact = true, showLabel = false, focusOnShow = focusOnOpen,
placeholder = stringResource(R.string.settings_search), compact = true, showLabel = false, focusOnShow = focusOnOpen, focusAtTap = focusTap,
clearFocus = !searching,
onFocusChange = { focused -> if (!focused && query.isEmpty() && searching) { focusOnOpen = false; onClose() } },
onFocusChange = { focused ->
fieldFocused = focused
if (!focused && query.isEmpty() && searching) { focusOnOpen = false; onClose() }
},
)
}
SmallIconButton(Icons.Filled.Close, stringResource(R.string.settings_search_clear), tint = colors.onSurfaceVariant) { close() }
}
} else {
Box(Modifier.focusRequester(icon)) { SearchIcon(stringResource(R.string.settings_search)) { focusOnOpen = true; onOpen() } }
Box(Modifier.focusRequester(icon)) { SearchIcon(stringResource(R.string.settings_search)) { focusTap = ScreenTaps.count; focusOnOpen = true; onOpen() } }
}
}
}
@@ -163,6 +163,8 @@ internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modif
}
}
internal val LocalRevealChecked = androidx.compose.runtime.compositionLocalOf { true }
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
internal fun TabStrip(
@@ -347,7 +349,7 @@ fun AnchoredMenu(
}
}
.verticalScroll(scroll),
) { content(firstItemFocus) }
) { androidx.compose.runtime.CompositionLocalProvider(LocalRevealChecked provides true) { content(firstItemFocus) } }
if (scroll.canScrollForward) Icon(
Icons.Filled.KeyboardArrowDown, contentDescription = null, tint = colors.onSurfaceVariant,
modifier = Modifier.align(Alignment.BottomCenter).size(20.dp),
@@ -377,7 +379,7 @@ fun MenuItem(
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val shift by animateFloatAsState(if (hot) 2f else 0f, Motion.sp(0.5f), label = "miShift")
val reveal = remember { androidx.compose.foundation.relocation.BringIntoViewRequester() }
if (checked) LaunchedEffect(Unit) { reveal.bringIntoView() }
if (checked && LocalRevealChecked.current) LaunchedEffect(Unit) { reveal.bringIntoView() }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.fillMaxWidth()
@@ -1,277 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RadialGradient
import android.graphics.RectF
import android.graphics.Shader
import android.graphics.Typeface
import com.droiddeck.launcher.input.InputControl
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sin
internal class SteamDeckButtonArt(context: Context) {
private val density = context.resources.displayMetrics.density
private val body = Paint(Paint.ANTI_ALIAS_FLAG)
private val shine = Paint(Paint.ANTI_ALIAS_FLAG)
private val edge = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val ink = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; typeface = Typeface.create("sans-serif-medium", Typeface.BOLD) }
private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND }
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
private val path = Path()
private val arm = Path()
private val bar = Path()
private val rect = RectF()
private var shineTop = Float.NaN
private var shineHeight = Float.NaN
private fun dp(value: Float) = value * density
private fun glass(canvas: Canvas, shape: Path, pressed: Boolean, tint: Int = BODY) {
shape.computeBounds(rect, false)
body.color = if (pressed) PRESSED else tint
body.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW)
canvas.drawPath(shape, body)
body.clearShadowLayer()
if (!pressed) {
if (rect.top != shineTop || rect.height() != shineHeight) {
shineTop = rect.top; shineHeight = rect.height()
shine.shader = LinearGradient(0f, rect.top, 0f, rect.top + rect.height() * .55f, SHINE, Color.TRANSPARENT, Shader.TileMode.CLAMP)
}
canvas.drawPath(shape, shine)
}
edge.color = if (pressed) EDGE_PRESSED else EDGE
edge.strokeWidth = dp(1.25f)
canvas.drawPath(shape, edge)
}
private fun circle(cx: Float, cy: Float, r: Float): Path = path.apply { reset(); addCircle(cx, cy, r, Path.Direction.CW) }
private fun roundRect(l: Float, t: Float, r: Float, b: Float, radius: Float): Path = path.apply {
reset(); addRoundRect(RectF(l, t, r, b), radius, radius, Path.Direction.CW)
}
private fun corners(l: Float, t: Float, r: Float, b: Float, tl: Float, tr: Float, br: Float, bl: Float): Path = path.apply {
reset(); addRoundRect(RectF(l, t, r, b), floatArrayOf(tl, tl, tr, tr, br, br, bl, bl), Path.Direction.CW)
}
private fun text(canvas: Canvas, value: String, cx: Float, cy: Float, size: Float, color: Int, maxWidth: Float = Float.MAX_VALUE) {
ink.textSize = size
val measured = ink.measureText(value)
if (measured > maxWidth) ink.textSize = size * maxWidth / measured
ink.color = color
canvas.drawText(value, cx, cy - (ink.ascent() + ink.descent()) / 2f, ink)
}
fun button(canvas: Canvas, width: Int, height: Int, control: InputControl, pressed: Boolean): Boolean {
val w = width.toFloat()
val h = height.toFloat()
if (min(w, h) <= dp(4f)) return false
when (control) {
InputControl.A, InputControl.B, InputControl.X, InputControl.Y -> {
val radius = min(w, h) / 2f - dp(2f)
glass(canvas, circle(w / 2f, h / 2f, radius), pressed)
text(canvas, control.label, w / 2f, h / 2f, radius * .95f, if (pressed) ON_ACCENT else INK)
}
InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT -> shoulder(canvas, w, h, control, pressed)
InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> grip(canvas, w, h, control.label, pressed)
InputControl.SELECT -> system(canvas, w, h, Shape.CHIP, Icon.VIEW, pressed)
InputControl.START -> system(canvas, w, h, Shape.CHIP, Icon.MENU, pressed)
InputControl.GUIDE -> system(canvas, w, h, Shape.PILL, Icon.STEAM, pressed)
InputControl.QAM -> system(canvas, w, h, Shape.PILL, Icon.QAM, pressed)
else -> return false
}
return true
}
fun keyboard(canvas: Canvas, w: Int, h: Int, pressed: Boolean) =
system(canvas, w.toFloat(), h.toFloat(), Shape.ROUND, Icon.KEYBOARD, pressed)
private fun shoulder(canvas: Canvas, w: Float, h: Float, control: InputControl, pressed: Boolean) {
val inset = dp(2f)
val l = inset; val t = inset; val r = w - inset; val b = h - inset
val trigger = control == InputControl.LT || control == InputControl.RT
val big = (b - t) * if (trigger) .9f else .62f
val small = dp(5f)
val left = control == InputControl.LT || control == InputControl.LB
glass(canvas, if (left) corners(l, t, r, b, big, small, small, small) else corners(l, t, r, b, small, big, small, small), pressed)
text(canvas, when (control) {
InputControl.LB -> "L1"
InputControl.RB -> "R1"
InputControl.LT -> "L2"
else -> "R2"
}, w / 2f, h / 2f, (b - t) * .46f, if (pressed) ON_ACCENT else INK, (r - l) * .8f)
}
/** A back grip: a capsule along the long side of its box, at most 2.2 times as long as it is thick. */
private fun grip(canvas: Canvas, w: Float, h: Float, label: String, pressed: Boolean) {
val inset = dp(3f)
val thick = (min(w, h) - 2 * inset).coerceAtLeast(1f)
val long = (max(w, h) - 2 * inset).coerceAtMost(thick * 2.2f)
val bw = if (w >= h) long else thick; val bh = if (w >= h) thick else long
val cx = w / 2f; val cy = h / 2f
glass(canvas, roundRect(cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2, thick / 2), pressed)
text(canvas, label, cx, cy, thick * .42f, if (pressed) ON_ACCENT else INK_SOFT)
}
private enum class Shape { ROUND, PILL, CHIP }
private enum class Icon { VIEW, MENU, QAM, KEYBOARD, STEAM }
private fun system(canvas: Canvas, w: Float, h: Float, shape: Shape, icon: Icon, pressed: Boolean, ink: Int = INK) {
val cx = w / 2f; val cy = h / 2f
val size = when (shape) {
Shape.ROUND -> { val r = min(w, h) / 2f * VISUAL; glass(canvas, circle(cx, cy, r), pressed); r * 1.2f }
Shape.PILL -> { val vh = min(h * VISUAL, w * VISUAL / 2.3f); val vw = vh * 2.3f
glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh / 2), pressed); vh * 1.1f }
Shape.CHIP -> { val vh = min(h * VISUAL, w * VISUAL / 1.9f); val vw = vh * 1.9f
glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh * .32f), pressed); vh * 1.05f }
}
icon(canvas, cx, cy, size, icon, if (pressed) ON_ACCENT else ink)
}
private fun icon(canvas: Canvas, cx: Float, cy: Float, size: Float, icon: Icon, color: Int) {
val u = size / 28f
line.color = color; line.strokeWidth = 3.2f * u
fill.color = color; fill.shader = null
when (icon) {
Icon.VIEW -> {
canvas.drawRoundRect(RectF(cx - 12 * u, cy - 9 * u, cx + 3 * u, cy + 3 * u), 3 * u, 3 * u, line)
fill.color = Color.argb(230, 14, 16, 20)
canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, fill)
canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, line)
}
Icon.MENU -> for (dy in intArrayOf(-7, 0, 7)) canvas.drawLine(cx - 11 * u, cy + dy * u, cx + 11 * u, cy + dy * u, line)
Icon.QAM -> for (dx in intArrayOf(-10, 0, 10)) canvas.drawCircle(cx + dx * u, cy, 3.4f * u, fill)
Icon.KEYBOARD -> {
canvas.drawRoundRect(RectF(cx - 16 * u, cy - 11 * u, cx + 16 * u, cy + 11 * u), 4.5f * u, 4.5f * u, line)
for (row in 0..1) for (col in 0..3) canvas.drawCircle(cx + (-9 + col * 6) * u, cy + (-4 + row * 5) * u, 1.7f * u, fill)
line.strokeWidth = 2.6f * u; canvas.drawLine(cx - 6 * u, cy + 6 * u, cx + 6 * u, cy + 6 * u, line)
}
Icon.STEAM -> {
ink.letterSpacing = .12f
text(canvas, "STEAM", cx, cy, 14 * u, color, size * 1.9f)
ink.letterSpacing = 0f
}
}
}
private fun chevron(canvas: Canvas, ax: Float, ay: Float, dx: Float, dy: Float, k: Float, color: Int, width: Float) {
val px = -dy; val py = dx
line.color = color; line.strokeWidth = width
canvas.drawPath(path.apply {
reset(); moveTo(ax - dx * k * .5f + px * k, ay - dy * k * .5f + py * k); lineTo(ax + dx * k * .6f, ay + dy * k * .6f)
lineTo(ax - dx * k * .5f - px * k, ay - dy * k * .5f - py * k)
}, line)
}
private fun cross(target: Path, cx: Float, cy: Float, s: Float, h: Float, rc: Float) = target.apply {
reset()
addRoundRect(RectF(cx - h, cy - s, cx + h, cy + s), rc, rc, Path.Direction.CW)
bar.reset()
bar.addRoundRect(RectF(cx - s, cy - h, cx + s, cy + h), rc, rc, Path.Direction.CW)
op(bar, Path.Op.UNION)
}
fun dpad(canvas: Canvas, w: Float, h: Float, held: Int) {
val cx = w / 2f
val cy = h / 2f
val arms = min(w, h) / 2f - dp(3f)
if (arms <= 0f) return
val half = arms * .37f
glass(canvas, cross(arm, cx, cy, arms, half, half * .43f), false)
for (i in 0..3) {
val dx = when (i) { 1 -> 1f; 3 -> -1f; else -> 0f }
val dy = when (i) { 0 -> -1f; 2 -> 1f; else -> 0f }
val on = held and (1 shl i) != 0
if (on && half > dp(2f)) {
fill.shader = null
fill.color = PRESSED
val near = half + dp(1f)
val far = arms - dp(2f)
val side = half - dp(2f)
rect.set(if (dx == 0f) cx - side else if (dx > 0) cx + near else cx - far,
if (dy == 0f) cy - side else if (dy > 0) cy + near else cy - far,
if (dx == 0f) cx + side else if (dx > 0) cx + far else cx - near,
if (dy == 0f) cy + side else if (dy > 0) cy + far else cy - near)
canvas.drawRoundRect(rect, half * .4f, half * .4f, fill)
}
val m = (arms + half) / 2f
chevron(canvas, cx + dx * m, cy + dy * m, dx, dy, half * .32f, if (on) ON_ACCENT else INK, half * .17f)
}
fill.shader = null
fill.color = Color.argb(18, 255, 255, 255)
canvas.drawCircle(cx, cy, half * .36f, fill)
}
fun stick(canvas: Canvas, cx: Float, cy: Float, radius: Float, kx: Float, ky: Float, active: Boolean) {
fill.alpha = 255
fill.shader = RadialGradient(cx, cy, radius, WELL_IN, WELL_OUT, Shader.TileMode.CLAMP)
fill.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW)
canvas.drawCircle(cx, cy, radius, fill)
fill.clearShadowLayer(); fill.shader = null
edge.color = Color.argb(61, 255, 255, 255); edge.strokeWidth = dp(1.25f)
canvas.drawCircle(cx, cy, radius, edge)
line.color = Color.argb(71, 255, 255, 255); line.strokeWidth = dp(1.4f)
for (i in 0 until 8) {
val a = i * Math.PI / 4
val c = cos(a).toFloat(); val n = sin(a).toFloat()
canvas.drawLine(cx + c * (radius - dp(7f)), cy + n * (radius - dp(7f)), cx + c * (radius - dp(3.5f)), cy + n * (radius - dp(3.5f)), line)
}
if (active && (kx != 0f || ky != 0f)) {
val angle = Math.toDegrees(atan2(ky, kx).toDouble()).toFloat()
line.color = ACCENT; line.strokeWidth = dp(3f)
val r = radius - dp(2f)
canvas.drawArc(RectF(cx - r, cy - r, cx + r, cy + r), angle - 35f, 70f, false, line)
}
val k = radius * .46f
val x = cx + kx; val y = cy + ky
line.color = if (active) ACCENT else Color.argb(140, 226, 232, 240)
line.strokeWidth = dp(2.8f)
canvas.drawCircle(x, y, k * 1.14f, line)
glass(canvas, circle(x, y, k), false)
edge.color = Color.argb(36, 255, 255, 255)
edge.strokeWidth = dp(1f)
canvas.drawCircle(x, y, k * .66f, edge)
}
fun trackpad(canvas: Canvas, w: Float, h: Float, touching: Boolean, fx: Float, fy: Float) {
if (w <= 0f || h <= 0f) return
val inset = dp(1.5f)
val radius = min(w, h) * .14f
fill.shader = null; fill.color = Color.argb(51, 14, 16, 20)
rect.set(inset, inset, w - inset, h - inset)
canvas.drawRoundRect(rect, radius, radius, fill)
edge.color = if (touching) Color.argb(191, 0x1A, 0x9F, 0xFF) else Color.argb(51, 255, 255, 255)
edge.strokeWidth = dp(if (touching) 1.5f else 1f)
canvas.drawRoundRect(rect, radius, radius, edge)
if (!touching) return
val glow = min(w, h) * .3f
fill.shader = RadialGradient(fx, fy, glow, GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP)
canvas.drawCircle(fx, fy, glow, fill); fill.shader = null
fill.color = ACCENT; canvas.drawCircle(fx, fy, dp(5f), fill)
}
companion object {
private const val VISUAL = .72f
private val ACCENT = Color.rgb(0x1A, 0x9F, 0xFF)
private val ON_ACCENT = Color.rgb(0x03, 0x11, 0x1F)
val INK = Color.rgb(0xF4, 0xF7, 0xFB)
private val INK_SOFT = Color.argb(209, 0xF4, 0xF7, 0xFB)
private val BODY = Color.argb(133, 14, 16, 20)
private val PRESSED = Color.argb(235, 0x1A, 0x9F, 0xFF)
private val SHINE = Color.argb(43, 255, 255, 255)
private val EDGE = Color.argb(77, 255, 255, 255)
private val EDGE_PRESSED = Color.argb(140, 255, 255, 255)
private val SHADOW = Color.argb(97, 0, 0, 0)
private val WELL_IN = Color.argb(140, 5, 7, 10)
private val WELL_OUT = Color.argb(71, 14, 16, 20)
private val GLOW = Color.argb(140, 0x1A, 0x9F, 0xFF)
}
}
@@ -453,7 +453,7 @@ private fun BucketCard(
modifier = modifier.paneItem("storage:${bucket.name}")
.graphicsLayer { scaleX = scale; scaleY = scale }
.clip(Shape14)
.background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
.glideBorder(hot, Shape14, pal.signal, pal.line)
.then(if (onClick != null) Modifier.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
@@ -174,7 +174,7 @@ internal fun AchievementRow(a: Achievement, compact: Boolean, modifier: Modifier
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.fillMaxWidth().clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
.glideBorder(hot, shape, pal.signal, pal.line)
.focusable(interactionSource = interaction)
.padding(if (compact) 8.dp else 10.dp),
@@ -369,7 +369,7 @@ internal fun DrawerAchievementsRow(progress: Pair<Int, Int>?, modifier: Modifier
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = modifier.fillMaxWidth().height(44.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface)
.background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.14f)) else Modifier)
.glideBorder(hot, shape, pal.signal, pal.line)
.clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = interaction, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick)
@@ -533,7 +533,7 @@ private fun AppCard(app: CardApp, size: Dp, first: Boolean, cards: HashMap<Strin
Column(
Modifier.width(size).paneItem("tile:store:${app.id}").then(if (first) Modifier.firstTile() else Modifier)
.graphicsLayer { scaleX = scale; scaleY = scale }
.clip(shape).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.clip(shape).background(colors.surface).then(if (hot) Modifier.background(pal.signal.copy(alpha = 0.10f)) else Modifier)
.glideBorder(hot, shape, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
@@ -925,6 +925,12 @@ internal fun ModeHeader(
val pal = LocalPalette.current
var searching by remember { mutableStateOf(query.isNotEmpty()) }
var focusOnOpen by remember { mutableStateOf(false) }
var focusTap by remember { mutableStateOf(0) }
var fieldFocused by remember { mutableStateOf(false) }
CancelPendingFocus(focusOnOpen, focusTap, fieldFocused) {
focusOnOpen = false
if (query.isEmpty()) searching = false
}
val open by animateFloatAsState(if (searching) 1f else 0f, Motion.sp(0.75f, 420f), label = "searchOpen")
// Closing takes the field away with focus still in it; the search button gets it once it is back on screen.
val searchIcon = remember { FocusRequester() }
@@ -955,9 +961,12 @@ internal fun ModeHeader(
Box(Modifier.width(w).graphicsLayer { alpha = (open * 1.6f).coerceAtMost(1f) }) {
AdbTextField(
value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search,
placeholder = placeholder, compact = true, showLabel = false, focusOnShow = focusOnOpen,
placeholder = placeholder, compact = true, showLabel = false, focusOnShow = focusOnOpen, focusAtTap = focusTap,
clearFocus = clearSearchFocus || !searching,
onFocusChange = { focused -> if (!focused && query.isEmpty()) { searching = false; focusOnOpen = false } },
onFocusChange = { focused ->
fieldFocused = focused
if (!focused && query.isEmpty()) { searching = false; focusOnOpen = false }
},
)
}
if (searching && closable) SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = colors.onSurfaceVariant, onClick = close)
@@ -965,7 +974,7 @@ internal fun ModeHeader(
}
}
val searchButton: @Composable () -> Unit = {
Box(Modifier.focusRequester(searchIcon)) { SearchIcon(stringResource(R.string.stores_search_open)) { searching = true; focusOnOpen = true } }
Box(Modifier.focusRequester(searchIcon)) { SearchIcon(stringResource(R.string.stores_search_open)) { focusTap = ScreenTaps.count; searching = true; focusOnOpen = true } }
}
BoxWithConstraints(Modifier.fillMaxWidth()) {
val stacked = maxWidth < NarrowPaneWidth
@@ -118,6 +118,8 @@ internal fun SortableRows(
rowHeight: androidx.compose.ui.unit.Dp,
handleWidth: androidx.compose.ui.unit.Dp,
onActivate: (String) -> Unit,
onGrab: (before: List<String>?) -> Unit = {},
releaseSignal: Int = 0,
row: @Composable (key: String, held: Boolean, offset: Float, hint: String?, modifier: Modifier, onFocus: (Boolean) -> Unit) -> Unit,
) {
val pad = LocalInputModeManager.current.inputMode == InputMode.Keyboard
@@ -129,6 +131,9 @@ internal fun SortableRows(
val rowPx = with(LocalDensity.current) { rowHeight.toPx() }
val handlePx = with(LocalDensity.current) { handleWidth.toPx() }
val list = rows()
val grab by rememberUpdatedState(onGrab)
LaunchedEffect(grabbed) { grab(if (grabbed != null) before else null) }
LaunchedEffect(releaseSignal) { if (releaseSignal > 0) grabbed = null }
Column(
Modifier.fillMaxWidth().pointerInput(Unit) {
awaitEachGesture {
@@ -365,11 +365,13 @@ internal fun AdbTextField(
onDone: (() -> Unit)? = null,
focusOnShow: Boolean = false,
showLabel: Boolean = true,
focusAtTap: Int? = null,
onBack: (() -> Unit)? = null,
) {
val context = LocalContext.current
val onBackLatest = rememberUpdatedState(onBack)
val focusAsked = remember { booleanArrayOf(false) }
val focusTapAsked = remember { arrayOfNulls<Int>(1) }
val palette = LocalPalette.current
val onValueChangeLatest = rememberUpdatedState(onValueChange)
val onNextLatest = rememberUpdatedState(onNext)
@@ -502,9 +504,12 @@ internal fun AdbTextField(
},
update = { editText ->
editText.showSoftInputOnFocus = !bottomTyping
if (focusOnShow && !focusAsked[0]) {
focusAsked[0] = true
// A new tap may ask again: a field still on screen while it closes can be opened once more.
val fresh = if (focusAtTap != null) focusTapAsked[0] != focusAtTap else !focusAsked[0]
if (focusOnShow && fresh) {
if (focusAtTap != null) focusTapAsked[0] = focusAtTap else focusAsked[0] = true
editText.post {
if (focusAtTap != null && focusAtTap != ScreenTaps.count) return@post
editText.requestFocus()
if (!bottomTypingLatest.value) (editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
@@ -10,6 +10,8 @@ import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
object CompositorHost {
private const val TAG = "DroidDeck"
@Volatile
private var started = false
@@ -55,6 +57,52 @@ object CompositorHost {
}
}
class Output internal constructor(
internal val runtimeDir: java.io.File,
internal val turnip: com.droiddeck.launcher.gpu.TurnipDriver,
internal val driverId: String?,
)
fun prepare(context: android.content.Context): Output {
val runtimeDir = java.io.File(context.filesDir, ".wayland-rt").apply { mkdirs() }
com.droiddeck.launcher.core.FileUtils.copyAsset(context, "wayland/keymap.xkb", java.io.File(runtimeDir, "keymap.xkb"))
com.droiddeck.launcher.input.VrControllers.publish(context)
val turnip = com.droiddeck.launcher.gpu.TurnipDriver(context)
com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "surface.driver-setup")
if (!started) {
displayChoice = SessionPrefs.androidDriver(context)
com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(context, SessionPrefs.androidDriver(context))
}
return Output(runtimeDir, turnip, if (started) null else turnip.install())
}
fun logToSession(context: android.content.Context) {
val waylandLog = java.io.File(com.droiddeck.launcher.session.SessionPaths.beginOrCurrent(context), "wayland.log")
WaylandCompositor.setSessionLogFile(waylandLog)
try {
android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true)
} catch (e: Exception) {
android.util.Log.w(TAG, "could not point the compositor's log at $waylandLog", e)
}
}
fun applyHdr(context: android.content.Context, mode: String) {
val on = SessionState.hdrCapable && SessionPrefs.hdr(context, mode)
SessionState.hdr = on
WaylandCompositor.nativeSetHdrOutput(on)
WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode))
android.util.Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session")
}
fun start(context: android.content.Context, output: Output, surface: Surface, size: Pair<Int, Int>, refreshHz: Float, fpsLimit: Int): Boolean {
com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "compositor.start driver=${output.driverId}")
return startOrAttach(
context, surface, output.runtimeDir.path,
output.driverId?.let { output.turnip.driverPath(it) }, output.driverId?.let { output.turnip.libraryName(it) },
context.applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz, fpsLimit,
)
}
@Synchronized
fun startOrAttach(
context: android.content.Context,
+8 -2
View File
@@ -964,13 +964,15 @@
<string name="setup_launcher_orientation_auto">اتّباع تدوير الجهاز</string>
<string name="setup_orientation_portrait">عمودي</string>
<string name="setup_session_orientation">اتجاه الجلسة</string>
<string name="setup_session_orientation_hint">يُطبَّق على Steam والألعاب وسطح المكتب ومحرّر وحدة التحكم. تدور الدقّات المُعدّة مسبقًا مع الجلسة، ويبقى العرض والارتفاع المخصّصان كما أُدخلا.</string>
<string name="setup_session_orientation_hint">يُطبَّق على Steam والألعاب وسطح المكتب ومحرّر وحدة التحكم. تدور الدقّات المُعدّة مسبقًا مع الجلسة، وعندما يتبع أحد الاتجاهين الآخر ينعكس العرض والارتفاع المخصّصان ليتطابقا.</string>
<string name="setup_orientation_auto">أفقي تلقائي</string>
<string name="setup_orientation_landscape">أفقي</string>
<string name="setup_orientation_reverse">أفقي معكوس</string>
<string name="setup_fullscreen">ملء الشاشة</string>
<string name="setup_fullscreen_on">يخفي شريطي الحالة والتنقّل في Android</string>
<string name="setup_fullscreen_off">يعرض شريطي الحالة والتنقّل في Android</string>
<string name="setup_page_swipe">التمرير بين الصفحات</string>
<string name="setup_page_swipe_hint">اسحب عبر الصفحة لتغيير علامة التبويب.</string>
<string name="setup_dual_screen_launcher">المشغّل على شاشتين</string>
<string name="setup_dual_screen_launcher_hint">يضع الوضع «تلقائي» أقسام المشغّل (Steam والمكتبة والمتاجر وغيرها) على الشاشة الثانية في الأجهزة المحمولة المزوّدة بشاشة ثانية مدمجة. ويستخدم الوضع «تشغيل» أي شاشة ثانية. أما الوضع «إيقاف» فيُبقي المشغّل على شاشة واحدة.</string>
<string name="setup_dual_screen_sessions">الجلسات على شاشتين</string>
@@ -2565,7 +2567,10 @@
<string name="phantom_warning">%1$s. %2$s\n\n%3$s</string>
<string name="display_session">شاشة الجلسة</string>
<string name="display_zero_copy">العرض بدون نسخ</string>
<string name="display_resolution">الدقة</string>
<string name="display_resolution_landscape">دقة الوضع الأفقي</string>
<string name="display_resolution_portrait">دقة الوضع العمودي</string>
<string name="display_follow_landscape">اتباع الأفقي (%1$d×%2$d)</string>
<string name="display_follow_portrait">اتباع العمودي (%1$d×%2$d)</string>
<string name="display_game_fit">ملاءمة اللعبة لنسبة 16:9</string>
<string name="display_game_fit_hint">كيفية ملاءمة ألعاب 16:9 لهذه الشاشة. يُطبَّق في الجلسة التالية.</string>
<string name="display_game_fit_unavailable">اختر «مطابقة الشاشة» أو حجمًا مخصَّصًا أضيق من 16:9.</string>
@@ -4172,6 +4177,7 @@
<string name="addons_sort_downloads">الأكثر تنزيلًا</string>
<string name="addons_category_all">كل الفئات</string>
<string name="addons_none_found">لم يتم العثور على إضافات</string>
<string name="addons_curse_busy">أغلق CurseForge أولاً</string>
<string name="addons_unreachable">تعذّر الوصول إلى %1$s</string>
<string name="addons_no_file">لا يوجد ملف لإصدار اللعبة هذا</string>
<string name="input_reset_positions">إعادة تعيين المواضع</string>
+8 -2
View File
@@ -982,13 +982,15 @@
<string name="setup_launcher_orientation_auto">Seguir la rotación del dispositivo</string>
<string name="setup_orientation_portrait">Vertical</string>
<string name="setup_session_orientation">Orientación de la sesión</string>
<string name="setup_session_orientation_hint">Se aplica a Steam, los juegos, el escritorio y el editor de controles. Los ajustes predefinidos de resolución giran con la sesión; el ancho y el alto personalizados se mantienen como se ingresaron.</string>
<string name="setup_session_orientation_hint">Se aplica a Steam, los juegos, el escritorio y el editor de controles. Los ajustes predefinidos de resolución giran con la sesión; cuando una orientación sigue a la otra, el ancho y el alto personalizados se invierten para coincidir.</string>
<string name="setup_orientation_auto">Horizontal automática</string>
<string name="setup_orientation_landscape">Horizontal</string>
<string name="setup_orientation_reverse">Horizontal invertida</string>
<string name="setup_fullscreen">Pantalla completa</string>
<string name="setup_fullscreen_on">Oculta las barras de estado y navegación de Android</string>
<string name="setup_fullscreen_off">Muestra las barras de estado y navegación de Android</string>
<string name="setup_page_swipe">Deslizar entre páginas</string>
<string name="setup_page_swipe_hint">Desliza sobre una página para cambiar de pestaña.</string>
<string name="setup_dual_screen_launcher">Lanzador de doble pantalla</string>
<string name="setup_dual_screen_launcher_hint">Automático coloca las secciones del lanzador (Steam, Biblioteca, Tiendas y las demás) en la segunda pantalla integrada de las consolas portátiles que la tienen. Activado usa cualquier segunda pantalla. Desactivado mantiene el lanzador en una sola pantalla.</string>
<string name="setup_dual_screen_sessions">Sesiones de doble pantalla</string>
@@ -2557,7 +2559,10 @@
<string name="phantom_warning">%1$s. %2$s\n\n%3$s</string>
<string name="display_session">Pantalla de la sesión</string>
<string name="display_zero_copy">Presentación sin copia</string>
<string name="display_resolution">Resolución</string>
<string name="display_resolution_landscape">Resolución horizontal</string>
<string name="display_resolution_portrait">Resolución vertical</string>
<string name="display_follow_landscape">Igual que horizontal (%1$d×%2$d)</string>
<string name="display_follow_portrait">Igual que vertical (%1$d×%2$d)</string>
<string name="display_game_fit">Ajuste de juegos 16:9</string>
<string name="display_game_fit_hint">Cómo se ajustan los juegos 16:9 a esta pantalla. Próxima sesión.</string>
<string name="display_game_fit_unavailable">Elige Igual a la pantalla o un tamaño personalizado más estrecho que 16:9.</string>
@@ -4052,6 +4057,7 @@
<string name="addons_sort_downloads">Más descargados</string>
<string name="addons_category_all">Todas las categorías</string>
<string name="addons_none_found">No se encontraron complementos</string>
<string name="addons_curse_busy">Cierra CurseForge primero</string>
<string name="addons_unreachable">No se pudo conectar con %1$s</string>
<string name="addons_no_file">No hay archivo para esta versión del juego</string>
<string name="input_reset_positions">Restablecer posiciones</string>
+8 -2
View File
@@ -952,13 +952,15 @@
<string name="setup_launcher_orientation_auto">Следва завъртането на устройството</string>
<string name="setup_orientation_portrait">Вертикална</string>
<string name="setup_session_orientation">Ориентация на сесията</string>
<string name="setup_session_orientation_hint">Прилага се за Steam, игрите, работния плот и редактора на контролера. Предварително зададените резолюции се завъртат със сесията; персонализираните ширина и височина остават както са въведени.</string>
<string name="setup_session_orientation_hint">Прилага се за Steam, игрите, работния плот и редактора на контролера. Предварително зададените резолюции се завъртат със сесията; когато едната ориентация следва другата, персонализираните ширина и височина се разменят, за да съвпадат.</string>
<string name="setup_orientation_auto">Автоматичен хоризонтален</string>
<string name="setup_orientation_landscape">Хоризонтална</string>
<string name="setup_orientation_reverse">Обърната хоризонтална</string>
<string name="setup_fullscreen">Цял екран</string>
<string name="setup_fullscreen_on">Скрива лентите за състояние и навигация на Android</string>
<string name="setup_fullscreen_off">Показва лентите за състояние и навигация на Android</string>
<string name="setup_page_swipe">Плъзгане между страниците</string>
<string name="setup_page_swipe_hint">Плъзнете по страница, за да смените раздела.</string>
<string name="setup_dual_screen_launcher">Лаунчер с два екрана</string>
<string name="setup_dual_screen_launcher_hint">Автоматично: секциите на лаунчера (Steam, Библиотека, Магазини и останалите) се показват на втория екран при преносими устройства с вграден такъв. Включено: използва се всеки втори дисплей. Изключено: лаунчерът остава на един екран.</string>
<string name="setup_dual_screen_sessions">Сесии с два екрана</string>
@@ -2461,7 +2463,10 @@
<string name="phantom_warning">%1$s. %2$s\n\n%3$s</string>
<string name="display_session">Екран на сесията</string>
<string name="display_zero_copy">Представяне без копиране</string>
<string name="display_resolution">Разделителна способност</string>
<string name="display_resolution_landscape">Резолюция в пейзажен режим</string>
<string name="display_resolution_portrait">Резолюция в портретен режим</string>
<string name="display_follow_landscape">Като пейзажния (%1$d×%2$d)</string>
<string name="display_follow_portrait">Като портретния (%1$d×%2$d)</string>
<string name="display_game_fit">Напасване на игра 16:9</string>
<string name="display_game_fit_hint">Как игрите с 16:9 се напасват на този екран. При следващата сесия.</string>
<string name="display_game_fit_unavailable">Избери „Напасване на екрана“ или собствен размер, по-тесен от 16:9.</string>
@@ -4012,6 +4017,7 @@
<string name="addons_sort_downloads">Най-изтегляни</string>
<string name="addons_category_all">Всички категории</string>
<string name="addons_none_found">Няма намерени добавки</string>
<string name="addons_curse_busy">Първо затворете CurseForge</string>
<string name="addons_unreachable">Няма връзка с %1$s</string>
<string name="addons_no_file">Няма файл за тази версия на играта</string>
<string name="input_reset_positions">Нулиране на позициите</string>
+8 -2
View File
@@ -958,13 +958,15 @@
<string name="setup_launcher_orientation_auto">Podle otočení zařízení</string>
<string name="setup_orientation_portrait">Na výšku</string>
<string name="setup_session_orientation">Orientace relace</string>
<string name="setup_session_orientation_hint">Platí pro Steam, hry, Plochu a editor ovladače. Předvolby rozlišení se otáčejí s relací; vlastní šířka a výška zůstávají, jak jsou zadány.</string>
<string name="setup_session_orientation_hint">Platí pro Steam, hry, Plochu a editor ovladače. Předvolby rozlišení se otáčejí s relací; když jedna orientace sleduje druhou, vlastní šířka a výška se prohodí, aby odpovídaly.</string>
<string name="setup_orientation_auto">Automaticky na šířku</string>
<string name="setup_orientation_landscape">Na šířku</string>
<string name="setup_orientation_reverse">Na šířku obráceně</string>
<string name="setup_fullscreen">Celá obrazovka</string>
<string name="setup_fullscreen_on">Skryje stavový a navigační panel Androidu</string>
<string name="setup_fullscreen_off">Zobrazí stavový a navigační panel Androidu</string>
<string name="setup_page_swipe">Přejíždění mezi stránkami</string>
<string name="setup_page_swipe_hint">Přejetím přes stránku přepnete kartu.</string>
<string name="setup_dual_screen_launcher">Spouštěč na dvou obrazovkách</string>
<string name="setup_dual_screen_launcher_hint">Automaticky přesune sekce spouštěče (Steam, Knihovna, Obchody a ostatní) na druhou obrazovku handheldů, které ji mají vestavěnou. Zapnuto použije libovolný druhý displej. Vypnuto ponechá spouštěč na jedné obrazovce.</string>
<string name="setup_dual_screen_sessions">Relace na dvou obrazovkách</string>
@@ -2513,7 +2515,10 @@
<string name="phantom_warning">%1$s. %2$s\n\n%3$s</string>
<string name="display_session">Obrazovka relace</string>
<string name="display_zero_copy">Zobrazení bez kopírování</string>
<string name="display_resolution">Rozlišení</string>
<string name="display_resolution_landscape">Rozlišení na šířku</string>
<string name="display_resolution_portrait">Rozlišení na výšku</string>
<string name="display_follow_landscape">Jako na šířku (%1$d×%2$d)</string>
<string name="display_follow_portrait">Jako na výšku (%1$d×%2$d)</string>
<string name="display_game_fit">Přizpůsobení hry 16:9</string>
<string name="display_game_fit_hint">Jak se hry s poměrem 16:9 přizpůsobí této obrazovce. Příští relace.</string>
<string name="display_game_fit_unavailable">Vyberte Podle obrazovky nebo vlastní velikost užší než 16:9.</string>
@@ -4092,6 +4097,7 @@
<string name="addons_sort_downloads">Nejstahovanější</string>
<string name="addons_category_all">Všechny kategorie</string>
<string name="addons_none_found">Nenalezeny žádné doplňky</string>
<string name="addons_curse_busy">Nejprve zavřete CurseForge</string>
<string name="addons_unreachable">Nelze se připojit k %1$s</string>
<string name="addons_no_file">Pro tuto verzi hry není k dispozici soubor</string>
<string name="input_reset_positions">Obnovit pozice</string>
+8 -2
View File
@@ -952,13 +952,15 @@
<string name="setup_launcher_orientation_auto">Følg enhedens rotation</string>
<string name="setup_orientation_portrait">Stående</string>
<string name="setup_session_orientation">Sessionens retning</string>
<string name="setup_session_orientation_hint">Gælder Steam, spil, skrivebordet og controllereditoren. Opløsningsforudindstillinger roterer med sessionen; brugerdefineret bredde og højde forbliver som angivet.</string>
<string name="setup_session_orientation_hint">Gælder Steam, spil, skrivebordet og controllereditoren. Opløsningsforudindstillinger roterer med sessionen; når den ene orientering følger den anden, byttes brugerdefineret bredde og højde, så de passer.</string>
<string name="setup_orientation_auto">Automatisk liggende</string>
<string name="setup_orientation_landscape">Liggende</string>
<string name="setup_orientation_reverse">Omvendt liggende</string>
<string name="setup_fullscreen">Fuldskærm</string>
<string name="setup_fullscreen_on">Skjuler Androids status- og navigationsbjælker</string>
<string name="setup_fullscreen_off">Viser Androids status- og navigationsbjælker</string>
<string name="setup_page_swipe">Stryg mellem sider</string>
<string name="setup_page_swipe_hint">Stryg hen over en side for at skifte fane.</string>
<string name="setup_dual_screen_launcher">Launcher til to skærme</string>
<string name="setup_dual_screen_launcher_hint">Automatisk placerer launcherens sektioner (Steam, Bibliotek, Butikker og resten) på den anden skærm på håndholdte enheder med en indbygget anden skærm. Til bruger enhver ekstra skærm. Fra holder launcheren på én skærm.</string>
<string name="setup_dual_screen_sessions">Sessioner på to skærme</string>
@@ -2461,7 +2463,10 @@
<string name="phantom_warning">%1$s. %2$s\n\n%3$s</string>
<string name="display_session">Sessionsskærm</string>
<string name="display_zero_copy">Præsentation uden kopiering</string>
<string name="display_resolution">Opløsning</string>
<string name="display_resolution_landscape">Opløsning i landskab</string>
<string name="display_resolution_portrait">Opløsning i portræt</string>
<string name="display_follow_landscape">Følg landskab (%1$d×%2$d)</string>
<string name="display_follow_portrait">Følg portræt (%1$d×%2$d)</string>
<string name="display_game_fit">16:9-spiltilpasning</string>
<string name="display_game_fit_hint">Hvordan 16:9-spil tilpasses denne skærm. Fra næste session.</string>
<string name="display_game_fit_unavailable">Vælg Match skærm eller en brugerdefineret størrelse, der er smallere end 16:9.</string>
@@ -4012,6 +4017,7 @@
<string name="addons_sort_downloads">Mest downloadet</string>
<string name="addons_category_all">Alle kategorier</string>
<string name="addons_none_found">Ingen tilføjelser fundet</string>
<string name="addons_curse_busy">Luk CurseForge først</string>
<string name="addons_unreachable">Kunne ikke nå %1$s</string>
<string name="addons_no_file">Ingen fil til denne spilversion</string>
<string name="input_reset_positions">Nulstil placeringer</string>
+8 -2
View File
@@ -944,13 +944,15 @@
<string name="setup_launcher_orientation_auto">Gerätedrehung folgen</string>
<string name="setup_orientation_portrait">Hochformat</string>
<string name="setup_session_orientation">Sitzungsausrichtung</string>
<string name="setup_session_orientation_hint">Gilt für Steam, Spiele, Desktop und den Controller-Editor. Auflösungsvoreinstellungen drehen sich mit der Sitzung; eigene Breite und Höhe bleiben wie eingegeben.</string>
<string name="setup_session_orientation_hint">Gilt für Steam, Spiele, Desktop und den Controller-Editor. Auflösungsvoreinstellungen drehen sich mit der Sitzung; folgt eine Ausrichtung der anderen, werden eigene Breite und Höhe passend vertauscht.</string>
<string name="setup_orientation_auto">Automatisch Querformat</string>
<string name="setup_orientation_landscape">Querformat</string>
<string name="setup_orientation_reverse">Umgekehrtes Querformat</string>
<string name="setup_fullscreen">Vollbild</string>
<string name="setup_fullscreen_on">Blendet die Status- und Navigationsleiste von Android aus</string>
<string name="setup_fullscreen_off">Zeigt die Status- und Navigationsleiste von Android an</string>
<string name="setup_page_swipe">Zwischen Seiten wischen</string>
<string name="setup_page_swipe_hint">Über eine Seite wischen, um den Tab zu wechseln.</string>
<string name="setup_dual_screen_launcher">Dual-Screen-Launcher</string>
<string name="setup_dual_screen_launcher_hint">Bei Automatisch liegen die Launcher-Bereiche (Steam, Bibliothek, Shops und die übrigen) auf dem zweiten Bildschirm von Handhelds mit integriertem zweitem Bildschirm. Ein nutzt einen beliebigen zweiten Bildschirm. Aus belässt den Launcher auf einem Bildschirm.</string>
<string name="setup_dual_screen_sessions">Dual-Screen-Sitzungen</string>
@@ -2453,7 +2455,10 @@
<string name="phantom_warning">%1$s. %2$s\n\n%3$s</string>
<string name="display_session">Sitzungsanzeige</string>
<string name="display_zero_copy">Kopierfreie Darstellung</string>
<string name="display_resolution">Auflösung</string>
<string name="display_resolution_landscape">Auflösung im Querformat</string>
<string name="display_resolution_portrait">Auflösung im Hochformat</string>
<string name="display_follow_landscape">Wie Querformat (%1$d×%2$d)</string>
<string name="display_follow_portrait">Wie Hochformat (%1$d×%2$d)</string>
<string name="display_game_fit">16:9-Spielanpassung</string>
<string name="display_game_fit_hint">Wie 16:9-Spiele auf dieses Display passen. Ab der nächsten Sitzung.</string>
<string name="display_game_fit_unavailable">Wähle „An Bildschirm anpassen“ oder eine eigene Größe schmaler als 16:9.</string>
@@ -4012,6 +4017,7 @@
<string name="addons_sort_downloads">Meistgeladen</string>
<string name="addons_category_all">Alle Kategorien</string>
<string name="addons_none_found">Keine Addons gefunden</string>
<string name="addons_curse_busy">Schließe zuerst CurseForge</string>
<string name="addons_unreachable">%1$s ist nicht erreichbar</string>
<string name="addons_no_file">Keine Datei für diese Spielversion</string>
<string name="input_reset_positions">Positionen zurücksetzen</string>
+8 -2
View File
@@ -952,13 +952,15 @@
<string name="setup_launcher_orientation_auto">Ακολουθεί την περιστροφή της συσκευής</string>
<string name="setup_orientation_portrait">Κατακόρυφος</string>
<string name="setup_session_orientation">Προσανατολισμός συνεδρίας</string>
<string name="setup_session_orientation_hint">Ισχύει για το Steam, τα παιχνίδια, την επιφάνεια εργασίας και τον επεξεργαστή χειριστηρίου. Οι προκαθορισμένες αναλύσεις περιστρέφονται με τη συνεδρία· το προσαρμοσμένο πλάτος και ύψος μένουν όπως καταχωρίστηκαν.</string>
<string name="setup_session_orientation_hint">Ισχύει για το Steam, τα παιχνίδια, την επιφάνεια εργασίας και τον επεξεργαστή χειριστηρίου. Οι προκαθορισμένες αναλύσεις περιστρέφονται με τη συνεδρία· όταν ένας προσανατολισμός ακολουθεί τον άλλον, το προσαρμοσμένο πλάτος και ύψος αντιστρέφονται ώστε να ταιριάζουν.</string>
<string name="setup_orientation_auto">Αυτόματος οριζόντιος προσανατολισμός</string>
<string name="setup_orientation_landscape">Οριζόντιος προσανατολισμός</string>
<string name="setup_orientation_reverse">Αντίστροφος οριζόντιος προσανατολισμός</string>
<string name="setup_fullscreen">Πλήρης οθόνη</string>
<string name="setup_fullscreen_on">Αποκρύπτει τις γραμμές κατάστασης και πλοήγησης του Android</string>
<string name="setup_fullscreen_off">Εμφανίζει τις γραμμές κατάστασης και πλοήγησης του Android</string>
<string name="setup_page_swipe">Σάρωση μεταξύ σελίδων</string>
<string name="setup_page_swipe_hint">Σαρώστε κατά μήκος μιας σελίδας για να αλλάξετε καρτέλα.</string>
<string name="setup_dual_screen_launcher">Εκκινητής διπλής οθόνης</string>
<string name="setup_dual_screen_launcher_hint">Η επιλογή Αυτόματα τοποθετεί τις ενότητες του εκκινητή (Steam, Βιβλιοθήκη, Καταστήματα και τις υπόλοιπες) στη δεύτερη οθόνη των φορητών κονσολών με ενσωματωμένη δεύτερη οθόνη. Η επιλογή Ενεργό χρησιμοποιεί οποιαδήποτε δεύτερη οθόνη. Η επιλογή Ανενεργό κρατά τον εκκινητή σε μία οθόνη.</string>
<string name="setup_dual_screen_sessions">Συνεδρίες διπλής οθόνης</string>
@@ -2461,7 +2463,10 @@
<string name="phantom_warning">%1$s. %2$s\n\n%3$s</string>
<string name="display_session">Οθόνη συνεδρίας</string>
<string name="display_zero_copy">Παρουσίαση χωρίς αντιγραφή</string>
<string name="display_resolution">Ανάλυση</string>
<string name="display_resolution_landscape">Ανάλυση σε οριζόντιο προσανατολισμό</string>
<string name="display_resolution_portrait">Ανάλυση σε κατακόρυφο προσανατολισμό</string>
<string name="display_follow_landscape">Ίδια με οριζόντιο (%1$d×%2$d)</string>
<string name="display_follow_portrait">Ίδια με κατακόρυφο (%1$d×%2$d)</string>
<string name="display_game_fit">Προσαρμογή παιχνιδιού 16:9</string>
<string name="display_game_fit_hint">Πώς προσαρμόζονται τα παιχνίδια 16:9 σε αυτή την οθόνη. Από την επόμενη συνεδρία.</string>
<string name="display_game_fit_unavailable">Επιλέξτε Αντιστοίχιση οθόνης ή ένα προσαρμοσμένο μέγεθος πιο στενό από 16:9.</string>
@@ -4012,6 +4017,7 @@
<string name="addons_sort_downloads">Περισσότερες λήψεις</string>
<string name="addons_category_all">Όλες οι κατηγορίες</string>
<string name="addons_none_found">Δεν βρέθηκαν πρόσθετα</string>
<string name="addons_curse_busy">Κλείστε πρώτα το CurseForge</string>
<string name="addons_unreachable">Δεν ήταν δυνατή η σύνδεση με %1$s</string>
<string name="addons_no_file">Δεν υπάρχει αρχείο για αυτή την έκδοση του παιχνιδιού</string>
<string name="input_reset_positions">Επαναφορά θέσεων</string>
+8 -2
View File
@@ -955,13 +955,15 @@
<string name="setup_launcher_orientation_auto">Seguir la rotación del dispositivo</string>
<string name="setup_orientation_portrait">Vertical</string>
<string name="setup_session_orientation">Orientación de la sesión</string>
<string name="setup_session_orientation_hint">Se aplica a Steam, los juegos, el escritorio y el editor de mandos. Los ajustes predefinidos de resolución giran con la sesión; el ancho y el alto personalizados se mantienen como se introdujeron.</string>
<string name="setup_session_orientation_hint">Se aplica a Steam, los juegos, el escritorio y el editor de mandos. Los ajustes predefinidos de resolución giran con la sesión; cuando una orientación sigue a la otra, el ancho y el alto personalizados se invierten para coincidir.</string>
<string name="setup_orientation_auto">Horizontal automática</string>
<string name="setup_orientation_landscape">Horizontal</string>
<string name="setup_orientation_reverse">Horizontal invertida</string>
<string name="setup_fullscreen">Pantalla completa</string>
<string name="setup_fullscreen_on">Oculta las barras de estado y navegación de Android</string>
<string name="setup_fullscreen_off">Muestra las barras de estado y navegación de Android</string>
<string name="setup_page_swipe">Deslizar entre páginas</string>
<string name="setup_page_swipe_hint">Desliza sobre una página para cambiar de pestaña.</string>
<string name="setup_dual_screen_launcher">Lanzador de doble pantalla</string>
<string name="setup_dual_screen_launcher_hint">Automático coloca las secciones del lanzador (Steam, Biblioteca, Tiendas y el resto) en la segunda pantalla de las consolas portátiles que la llevan integrada. Activado usa cualquier segunda pantalla. Desactivado mantiene el lanzador en una sola pantalla.</string>
<string name="setup_dual_screen_sessions">Sesiones de doble pantalla</string>
@@ -2487,7 +2489,10 @@
<string name="phantom_warning">%1$s. %2$s\n\n%3$s</string>
<string name="display_session">Pantalla de la sesión</string>
<string name="display_zero_copy">Presentación sin copia</string>
<string name="display_resolution">Resolución</string>
<string name="display_resolution_landscape">Resolución horizontal</string>
<string name="display_resolution_portrait">Resolución vertical</string>
<string name="display_follow_landscape">Igual que horizontal (%1$d×%2$d)</string>
<string name="display_follow_portrait">Igual que vertical (%1$d×%2$d)</string>
<string name="display_game_fit">Ajuste de juegos 16:9</string>
<string name="display_game_fit_hint">Cómo se ajustan los juegos 16:9 a esta pantalla. Próxima sesión.</string>
<string name="display_game_fit_unavailable">Elige Igual a la pantalla o un tamaño personalizado más estrecho que 16:9.</string>
@@ -4052,6 +4057,7 @@
<string name="addons_sort_downloads">Más descargados</string>
<string name="addons_category_all">Todas las categorías</string>
<string name="addons_none_found">No se han encontrado complementos</string>
<string name="addons_curse_busy">Cierra CurseForge primero</string>
<string name="addons_unreachable">No se pudo conectar con %1$s</string>
<string name="addons_no_file">No hay ningún archivo para esta versión del juego</string>
<string name="input_reset_positions">Restablecer posiciones</string>
+8 -2
View File
@@ -952,13 +952,15 @@
<string name="setup_launcher_orientation_auto">Seuraa laitteen kiertoa</string>
<string name="setup_orientation_portrait">Pystysuunta</string>
<string name="setup_session_orientation">Istunnon suunta</string>
<string name="setup_session_orientation_hint">Koskee Steamia, pelejä, työpöytää ja ohjainmuokkainta. Resoluution esiasetukset kääntyvät istunnon mukana; mukautettu leveys ja korkeus pysyvät syötetyn mukaisina.</string>
<string name="setup_session_orientation_hint">Koskee Steamia, pelejä, työpöytää ja ohjainmuokkainta. Resoluution esiasetukset kääntyvät istunnon mukana; kun toinen suunta seuraa toista, mukautettu leveys ja korkeus vaihtavat paikkaa vastaamaan toisiaan.</string>
<string name="setup_orientation_auto">Automaattinen vaakasuunta</string>
<string name="setup_orientation_landscape">Vaakasuunta</string>
<string name="setup_orientation_reverse">Käänteinen vaakasuunta</string>
<string name="setup_fullscreen">Koko näyttö</string>
<string name="setup_fullscreen_on">Piilottaa Androidin tila- ja navigointipalkit</string>
<string name="setup_fullscreen_off">Näyttää Androidin tila- ja navigointipalkit</string>
<string name="setup_page_swipe">Pyyhkäise sivujen välillä</string>
<string name="setup_page_swipe_hint">Vaihda välilehteä pyyhkäisemällä sivun poikki.</string>
<string name="setup_dual_screen_launcher">Kahden näytön käynnistin</string>
<string name="setup_dual_screen_launcher_hint">Automaattinen siirtää käynnistimen osiot (Steam, Kirjasto, Kaupat ja muut) käsikonsolin sisäänrakennetulle toiselle näytölle. Päällä käyttää mitä tahansa toista näyttöä. Pois päältä pitää käynnistimen yhdellä näytöllä.</string>
<string name="setup_dual_screen_sessions">Kahden näytön istunnot</string>
@@ -2461,7 +2463,10 @@
<string name="phantom_warning">%1$s. %2$s\n\n%3$s</string>
<string name="display_session">Istunnon näyttö</string>
<string name="display_zero_copy">Kopioimaton esitys</string>
<string name="display_resolution">Tarkkuus</string>
<string name="display_resolution_landscape">Vaakatilan resoluutio</string>
<string name="display_resolution_portrait">Pystytilan resoluutio</string>
<string name="display_follow_landscape">Seuraa vaakaa (%1$d×%2$d)</string>
<string name="display_follow_portrait">Seuraa pystyä (%1$d×%2$d)</string>
<string name="display_game_fit">16:9-pelin sovitus</string>
<string name="display_game_fit_hint">Miten 16:9-pelit sovitetaan tähän näyttöön. Seuraava istunto.</string>
<string name="display_game_fit_unavailable">Valitse Sovita näyttöön tai mukautettu koko, joka on 16:9:ää kapeampi.</string>
@@ -4012,6 +4017,7 @@
<string name="addons_sort_downloads">Ladatuimmat</string>
<string name="addons_category_all">Kaikki luokat</string>
<string name="addons_none_found">Lisäosia ei löytynyt</string>
<string name="addons_curse_busy">Sulje CurseForge ensin</string>
<string name="addons_unreachable">Yhteyttä palveluun %1$s ei saatu</string>
<string name="addons_no_file">Tälle peliversiolle ei ole tiedostoa</string>
<string name="input_reset_positions">Palauta sijainnit</string>
Loaded 100 of 223 files, more files were not shown because too many files have changed in this diff. Show more