Files
DroidDeck/tools/linuxfs/overlay/usr/local/bin/droiddeck-pad-defaults
MaxsTechReview 49a5f4aa94 ESync, FSync, NTSync + OpenNow + FEX for Desktop Apps (#197)
* Make the Compatible Proton ARM64 the default and label compatible builds

The CompatToolMapping "0" default always points at DroidDeck's Proton
ARM64 tool, and per-game picks of adopted GE/CachyOS builds are kept,
including when the shortcuts writer remaps.

The tool is named after the Proton build it runs, Proton Experimental
ARM64 (Compatible), or Proton 11.0 ARM64 (Compatible) once that newer build
is installed. Adopted builds carry the same Compatible mark, read from a
string resource the app stages into the runtime, and the Proton page
explains which builds have the prefix fixes.

The registrar is renamed steam-compatibility and the tool
droiddeck-proton-arm64. Existing installs migrate on the next session: the
old tool directory is removed, every mapping that named it moves to the new
tool, and the retired bannerlator-steam-compat script is removed from the
runtime. CI and local packaging include the renamed script.

* Drop the duplicate R import left by merging main

* Add userspace ntsync for Proton on Android

Android kernels have no /dev/ntsync and its app policy refuses futex_waitv,
so every Proton 11 build here fell back to wineserver for every wait.
libblsession now serves /dev/ntsync itself: wineserver opens a memfd region,
each sync object is a timerfd that carries its slot, and the kernel ntsync
ioctls are answered in shared memory with futexes, following the kernel
driver's wake order. Valve's Proton Experimental ARM64, GE-Proton and
proton-cachyos use it unchanged.

Locks record their owner so a killed process cannot wedge the others,
signals are held off inside each critical section, dead processes and
exiting threads are swept, and object lifetimes follow close, dup2, dup3,
close_range and received descriptors.

Fast sync is on by default under Performance > Session fixes, and
PROTON_NO_NTSYNC=1 turns it off per game.

* Add droiddeck-esync as the default sync for Proton on Android

Without a kernel ntsync driver, Proton 11 builds here fell back to
wineserver for every wait. droiddeck-esync brings eventfd and shared-memory
sync to the exact Proton build a game runs on: a pack holds that build's
ntdll.so and wineserver with the patch series in tools/droiddeck-esync
applied, and the guest runs Proton from a shadow tree that links the stock
tool and swaps in those two files. A wineserver from a pack still prefers
/dev/ntsync when a kernel driver or droiddeck-ntsync is there.

Packs are built in Valve's SDK image from each release's own wine source
(Proton Experimental ARM64 tags, GE-Proton and proton-cachyos releases); the
control build must reproduce the release binaries byte for byte, and a
signed index lists the packs. The APK bundles the packs pinned in
release.env, the app fetches newer ones, and Steam's compatibility tool
picks the pack for each Proton build, so new Proton releases get packs
without an app update.

The ntdll side reads, writes and polls its eventfds with raw system calls,
so the guest's LD_PRELOAD wrappers stay out of the sync path. The server
abandons a mutex once a thread killed by TerminateThread has really exited
and when its process dies, and a mutex's owner and recursion count change
in one atomic step, so a killed owner cannot touch the next owner's count.

droiddeck-esync is on by default and PROTON_NO_ESYNC=1 turns it off per
game; droiddeck-ntsync, the userspace ntsync, is now an opt-in toggle.

* Watch Valve's Proton releases and build droiddeck-esync packs for them

A scheduled workflow reads the Proton ARM64 builds Steam ships (anonymous
steamcmd app info) and the upstream source tags, compares them with the
previous watch state and starts the pack build for any build that has no
pack yet. The pack build applies the patch series with --fuzz=0 and runs a
smoke test of each new pack against the esstress suite before it is
published.

* Add droiddeck-fsync, keep Steam and the app on one Proton, fix DirectAudio

droiddeck-fsync: libblsession answers futex_waitv(2), which the app
sandbox refuses, in userspace, so Proton's own fsync runs on the stock
Proton files with no pack. Waiters register the words they wait on in a
table beside the fsync shared memory and sleep on a futex of their own;
FUTEX_WAKE on the fsync memory wakes the registered waiters. Slots carry
one owner word that the sweeper and the owner claim with a CAS, and the
mapping table is rebuilt under a lock held across the real munmap, so a
reused address or a recycled slot cannot lose a waiter. It stands in for
a Proton build without a pack (droiddeck-ntsync where fsync is off), takes
over for games with esync off, and the "droiddeck-fsync first" toggle
(BL_FSYNC_FIRST, also per game) puts it ahead of the packs. The games
Proton keeps off fsync and esync never get it. A launch into a prefix
whose wineserver is still running keeps that server's sync choice.

One Proton for Steam and the app: the Components page's Proton is the
default Steam uses, applied live through the client while Steam runs
(droiddeck-steam-compat) and at the next start otherwise; a choice made in
Steam's menu comes back to the app. Requests are ordered by a sequence that
never goes backwards, and the page no longer jumps back to the default
after a swap or restore.

DirectAudio: the wrapper wrote the driver key with its backslashes
stripped, so no game ever used DirectAudio. Wine 11 also loads a builtin
only from the prefix, so the driver is now linked into system32 and
syswow64 before "directaudio,pulse" is selected; mmdevapi falls back to
winepulse whenever DirectAudio cannot start.

* Pick esync, ntsync or fsync from the Steam settings' Games group

A three-way tab row above the FEX preset sets the sync Proton games use. It
writes the existing switches together (droiddeck-ntsync, droiddeck-fsync
first, droiddeck-esync), so the Performance toggles and the tabs always agree,
starts on esync and keeps the choice until it is changed again.

* Make droiddeck-fsync the default sync for Proton games

A fresh install, or one that never picked a sync, starts on fsync; a choice made
in the Steam settings' Games group still sticks. Games Proton keeps off fsync
still fall back to droiddeck-esync.

* Add wineserver to the Wine sync tabs and order them ntsync, fsync, esync, wineserver

wineserver turns every in-process sync off so games wait through wineserver;
picking any other tab turns sync back on. The tabs shrink to fit a narrow pane.

* Shorten the Wine sync description

* Answer openat2 and execveat for FEX in the session preload

FEX opens every file of its x86 rootfs with openat2(RESOLVE_IN_ROOT) and
only falls back to the host path on EXDEV. Under proot on Android openat2
answers ENOSYS, so each lookup of an x86 library silently went to the host
and missed. The exported syscall() now turns openat2 into openat once the
real call reports ENOSYS: RESOLVE_IN_ROOT paths are taken relative to the
root fd (FEX has already resolved the links inside the rootfs), and an
absolute path under RESOLVE_BENEATH fails with EXDEV as the kernel would.

execveat with an absolute path, or relative to AT_FDCWD, and without
AT_EMPTY_PATH or AT_SYMLINK_NOFOLLOW, is plain execve; it is sent as such
because proot refuses execveat with a directory fd, which FEX uses when it
re-executes itself for a child x86 program.

* Run x86 Linux games and programs through FEX

Steam: Linux-only titles that have no ARM64 build (from the client's
appinfo cache: type game, demo, application or beta) are mapped to a new
compatibility tool, droiddeck-fex ("Linux x86 (FEX)", linux to linux,
no required runtime). Valve's own "fex" tool needs pressure-vessel, which
cannot run under proot, so a mapping to it or to a Steam Linux Runtime is
replaced; any other pick the user made stays. Titles that also ship for
Windows stay on Proton. When such a title is installed and FEX or the
sniper runtime is missing, the client is asked to install them.

droiddeck-fex runs the program under the FEX that Steam installs (app
3127680), with Steam Linux Runtime 3.0 (sniper, app 1628350) as the x86
rootfs:
- the sniper platform is linked in place from its usr-mtree (relative
  links only, files/usr -> .), once per runtime version;
- the x86_64 and i386 builds of libblsession and libfakeinput go into the
  runtime's lib/<triplet>/droiddeck and its etc/ld.so.preload, mirroring
  the session's own list, so x86 programs get the pads and the session
  fixes (FEX passes their system calls straight to the kernel, so the
  ARM64 preloads cannot reach them);
- Config.json sets RootFS and the GL and Vulkan thunks, so x86 games draw
  with the device's Turnip and Mesa;
- the FEX preset and the game's own environment from the Steam settings
  apply, and ARM64 entries are dropped from LD_PRELOAD/LD_LIBRARY_PATH.
It also links ~/.steam/sdk64 and sdk32 to the client's x86 steamclient
when the client has one and nothing is there yet.

Desktop: x86_64 and i386 AppImages can be imported now; they unpack
through FEX (or unsquashfs) and record their architecture. Scripts,
AppImages and programs started in a run session use FEX automatically
when they are x86, and each added app has a "Use FEX" Auto/On/Off choice
in its edit dialog. The launchers' "still running" checks also look at
FEX processes, whose exe is FEX rather than the program. A GitHub release
without an ARM64 AppImage falls back to its x86_64 one. Decky's x86
loader starts through droiddeck-fex instead of the fex-mesa rootfs path,
which no runtime ships.

The x86 preloads are built against glibc 2.31 (Debian 11) so they load
in sniper: tools/linuxfs/build-x86-preloads.sh, run in CI and by
build_local.sh. fakeinput's stat hooks fall back to __xstat on a glibc
without a stat export, and mmap64 takes off64_t for the i386 build.

* Keep a FEX unixlib from outliving its DLL

A FEX package or original bundle without the aarch64-unix helpers left
the previous version's libarm64ecfex.so / libwow64fex.so in the Proton,
so the new DLLs loaded a unixlib built for another FEX. A swap now removes
the helpers the package does not carry; FEX then runs DLL-only, which it
already falls back to when Wine cannot load the unixlib.

* Fix the Wine sync choices an audit found

- wineserver tab: it passed Proton's environment through, so a build with
  esync built in (GE, cachyos) still ran esync and a kernel ntsync would
  still be used. It now sets PROTON_NO_ESYNC, PROTON_NO_FSYNC and
  PROTON_NO_NTSYNC (unless the game's own environment sets them).
- ntsync tab: a Proton whose wineserver has no /dev/ntsync client got
  wineserver-only sync although fsync would work. The hash cache records
  whether the wineserver has one; without it the launch goes to
  droiddeck-fsync, and no stand-in or pack turns droiddeck-ntsync on.
- A build with esync built in returned before the per-game fallbacks, so
  a game that turns esync off ran with no in-process sync. It now gets
  droiddeck-fsync, or droiddeck-ntsync where fsync is off too.
- When a pack's proton cannot start and the stock one is used, or the
  selection fails, the prefix's record now says stock, so a second
  launch into the same running prefix no longer picks the pack's ntdll.
- droiddeck-fsync: its mutex is held across fork and re-made in the
  child, a closed or replaced shm fd is forgotten (close, dup2, dup3,
  close_range, closefrom), and a waiter woken while it was leaving on a
  timeout or signal reports the wake instead of losing it.
- BL_SYNC_MIN_NOFILE applies per game to every verb, debug logs carry
  prefixes.json, the device report names the chosen sync instead of the
  three raw switches, and PATCHES.md and the proot notes describe the
  selector, the fsync default and droiddeck-fsync's futex_waitv.

* Name the runtime's scripts and files droiddeck, migrating old installs

The guest scripts are droiddeck-* now (droiddeck-session and the other 19),
as are the files the app and scripts generate (etc/droiddeck, the network
state files, the components dir, the Steam install stamp, the redist marker,
the extra-Proton wrapper and backups) and the compositor's own names
(libdroiddeckwayland, droiddeck_* sources, DROIDDECK_* switches, the
wl_output and seat names).

Installed runtimes carry on: LegacyNames moves etc/bannerlator and
share/bannerlator over and leaves relative links at the old paths before
every proot command, turns any old script into a link to its new name,
moves the generated files and points menu entries at the new scripts.
The session scripts and steam-compatibility move their markers on first
use, the components dir's desired.tsv is rewritten with it, and the
runtime counts as installed under either session script.

Kept: the banner_ahb_v1/banner_desktop_v1 wire names and BANNER_AUDIO_DIRECT
(read by prebuilt Turnip and Wine builds), Banners-Turnip and other
third-party names, BL_* switches, libblsession, and credits to Bannerlator.

* Unpack x86 AppImages without FEX, then ask Steam for FEX

Importing an x86 AppImage failed when FEX was not installed yet ("needs FEX
to unpack and no unsquashfs is installed"). AppImages now unpack with
uruntime (VHSgunzo, MIT, v0.8.1 aarch64, pinned by sha256 and shipped
unmodified with its licence), which reads SquashFS and DwarFS images of any
architecture natively. FEX's own --appimage-extract and unsquashfs stay as
fallbacks, and an ARM64 image whose own runtime cannot unpack it goes the
same way.

An x86 import with FEX missing records that FEX is wanted, so the next
Steam session requests FEX and the Steam Linux Runtime, and the program's
page says FEX is not set up yet and how to get it.

* Run Vulkan Qt Quick AppImages on Wayland

OpenNOW (Qt 6.8, Qt Quick on Vulkan) closed within two seconds in a run
mode. The session sends toolkits to gamescope's Xwayland, and Qt's xcb
backend only presents with Vulkan when Mesa's X11 WSI does, which needs
DRI3; Xwayland on KGSL has none, so Qt found no queue that can present and
aborted ("Failed to create RHI").

An AppImage that bundles Qt Quick, the Vulkan loader and Qt's Wayland
plugin now runs on gamescope's Wayland socket (the desktop's, outside
gamescope), where Turnip presents as it does for games, with Qt's xcb
backend as the fallback. SDL_VIDEODRIVER and XDG_SESSION_TYPE follow, so
helpers that pick their window system from them (OpenNOW's streamer) agree
with Qt. Everything else stays on X11; a qt file in the app's directory
(wayland or xcb) overrides the choice.

* Keep gamescope's WSI layer away from Qt apps on its Wayland socket

OpenNOW still closed at once: its FFmpeg (the Raspberry Pi fork, libavutil
61) creates its Vulkan queues internally synchronized whenever the driver
offers VK_KHR_internally_synchronized_queues, which DD-Turnip does. The
gamescope WSI layer registers every queue of a new device through
vkGetDeviceQueue, which only returns queues created without flags, so it
got VK_NULL_HANDLE and vkroots aborted on assert(obj) before Qt opened a
window.

Programs that draw on gamescope's Wayland socket do not need the layer,
which only carries X11 windows past Xwayland, so it is turned off for
them. OpenNOW bundles no Vulkan loader (it reaches Vulkan through Qt and
dlopen), so a binary that uses QVulkanInstance counts as a Vulkan app too,
and a Qt Quick app left on X11 says why in the session log.

* Keep the end of the session log, and say when FEX is missing

The session sends its output through head -c into session.log. head
writes through stdio, so it held up to 4 KB that proot's --kill-on-exit
threw away when the guest ended: every log stopped mid-line at a 4096-byte
boundary, losing exactly the lines that say why a program quit (an x86
AppImage's "x86 Linux programs need FEX" among them). dd writes each read
as it comes and keeps the same cap.

A run mode always ends with status 0 (gamescope does not pass its child's
on), so a program that could not start just closed. When the log says FEX
is missing, the ended screen now says so and how to get it.

The app reads FEX's readiness from status.json, which only a launch or an
import wrote, so it still said "not set up" after Steam installed FEX.
droiddeck-fex status rewrites it, and a Steam session ends with it while
FEX is wanted. FEX is also looked for at the tool's root and under files/,
and a tool folder without it lists what it holds.

* Let FEX and its runtime install runnable on an SD card library

A Steam library on shared storage loses the executable bits, so native
tools are staged in private directories bound over it; only Proton and
SteamLinuxRuntime folders were. FEX (3127680) installed there could never
run, droiddeck-fex saw no FEX and kept asking Steam for it. FEX and the
sniper runtime (1628350) now get private directories from their first
download, whatever their install folder is called.

* Keep fsync off in the pack smoke test

A runner whose kernel allows futex_waitv started stock Proton with fsync,
so the server-side baseline never said what the test waits for and every
pack was waved through as untestable; the esync run would have measured
fsync too.

* Judge a pack against stock's own esstress failures

Stock Proton fails esstress's dup wait all under server-side sync as well
(a Wine bug, seen on the phone too), and any stock failure made the test
call the runner unusable. A pack now fails only when it crashes, hangs or
fails a check stock passes.

* Ask Steam for FEX and its runtime one at a time

Both steam://install requests were started together, and the running client
took only the first: FEX installed, the sniper runtime FEX needs never did.
Each request now waits for the client to take it before the next.

* Bundle the first published droiddeck-esync packs in the apk

* Log how an x86 program under FEX ends

FEX keeps its own errors quiet unless asked, so a program it could not run
left nothing in the session log. Its log now goes to stderr, and the AppImage
launcher records the program's exit status or the signal that ended it.

* Show the log a failed AppImage program wrote

Programs like Eden stop themselves on a failed check and say why only in
their own log under the home folder. When the program ends badly, the end of
any log it wrote during the run is copied into the session log.

* Report where an x86 program under FEX hit an illegal instruction

A tiny x86_64 preload, built without libc, catches SIGILL and writes the
address, the instruction bytes and the mapping they belong to before the
program dies as it would have. droiddeck-fex preloads it into x86_64 programs.

* Load the fault reporter from the x86 runtime

Programs under FEX look libraries up in the x86 runtime, so the reporter is
copied there with the other preloads and named by its path inside it.

* Hand FEX its x86 runtime and thunks through the environment

Valve's FEX runs portable and reads its config beside itself, so the
Config.json droiddeck-fex writes was not seen: programs ran without the
runtime. The runtime, thunk libraries and thunk list now also go in FEX's
own environment variables, and each launch says what it was given.

* Use the sync pack built for the installed Proton release

Some Proton releases ship byte-identical ntdll.so and wineserver (Valve
11.0-2b/2c, CachyOS 0702/0703), so a pack built for a newer release
matched an older install exactly and the older install never fetched its
own pack. A pack from a newer release no longer counts as an exact match;
among matches the one built for the installed version wins, then rev.

The app ranks the pack a tool already uses the same way and only fetches
a pack that ranks higher, reads the release epoch from tools.tsv and
refetches when tools.tsv changes. A prefix whose server is still running
re-checks its recorded pack on waitforexitandrun and starts fresh when a
better one now applies.

* Keep published sync packs and revocations consistent

The publish step never replaces a pack that has an entry beside it; a
pack left without its entry by an interrupted run is replaced so the
build stops repeating. Discovery counts revocations the signed index does
not show yet, including superseded packs only the flavor releases list,
so the index is signed again. The release watch always builds every
flavor.

* Fetch the droiddeck-esync packs from DroidDeck-Components

The packs, the signed index and the apk bundle now live in the releases
of Droid-Deck/DroidDeck-Components, together with the pipeline that
builds them, so this repository keeps only the app and the guest code
that consumes them. The app's index and asset URLs point there,
release.env names the repository its bundle comes from, and the apk
builds drop bundled packs that the published index revokes.

* Stop the apk build when the published sync index cannot be read

* Ask Steam for one FEX dependency at a time

The client shows a confirmation dialog for each steam://install, and a
second request replaces the first dialog, so FEX was never installed
when the runtime was requested right after it. The next dependency is
now requested once the previous one has an app manifest.

* Use generic names in the AppImage test fixtures

* Give x86-64 apps under FEX the Vulkan thunk

Apps that bring their own glibc and Vulkan loader skipped FEX's thunk
overlay and loaded their bundled desktop Mesa drivers, which crash on the
phone's GPU during Vulkan setup. droiddeck-fex now adds an x86-64 audit
module when a program's bundled glibc and libstdc++ meet the thunk's
version needs. The module sends libvulkan.so.1 lookups to a nodelete stub
that needs FEX's thunk path. That keeps the thunk mapped when an app
unloads Vulkan and loads it again, since FEX keeps its first trampoline
links and the old addresses get reused.

The fault reporter now restores the default action before re-raising,
because FEX ignores SA_RESETHAND and the handler looped.
2026-10-04 12:43:57 -04:00

1101 lines
46 KiB
Python
Executable File

#!/usr/bin/python3
# Player 1 on the session's controller, for every emulator that would otherwise start on the
# keyboard. The session's pad is an Xbox 360 controller (libfakeinput's identity outside Steam) that
# SDL maps by itself; what an emulator lacks is a profile that points Player 1 at it. One is
# written only where the emulator has none yet - a profile the user made is never touched.
# Run at every desktop start and before every program from the rail.
import os
HOME = os.environ.get("HOME", "/root")
CONFIG = os.environ.get("XDG_CONFIG_HOME", os.path.join(HOME, ".config"))
def seed(path, text, what, done="Player 1 on the controller"):
if os.path.exists(path):
return False
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path + ".tmp", "w", encoding="utf-8") as f:
f.write(text)
os.replace(path + ".tmp", path)
print(f"droiddeck-pad-defaults: {what}: {done} ({path})")
return True
# RPCS3: its global input configuration (rpcs3::utils::get_input_config_dir() + "Default.yml").
# Without one it adds the keyboard pad handler (pad_config.cpp, cfg_input::load). SDL handler
# names from rpcs3/Input/sdl_pad_handler.cpp (button_list, init_config); the device is
# "<SDL gamepad name> <n>" (sdl_pad_handler::enumerate_devices).
RPCS3_PLAYER1 = """Player 1 Input:
Handler: SDL
Device: Xbox 360 Controller 1
Config:
Left Stick Left: LS X-
Left Stick Down: LS Y-
Left Stick Right: LS X+
Left Stick Up: LS Y+
Right Stick Left: RS X-
Right Stick Down: RS Y-
Right Stick Right: RS X+
Right Stick Up: RS Y+
Start: Start
Select: Back
PS Button: Guide
Square: West
Cross: South
Circle: East
Triangle: North
Left: Left
Down: Down
Right: Right
Up: Up
R1: RB
R2: RT
R3: RS
L1: LB
L2: LT
L3: LS
Left Stick Deadzone: 8000
Right Stick Deadzone: 8000
Left Stick Anti-Deadzone: 4259
Right Stick Anti-Deadzone: 4259
Left Trigger Threshold: 0
Right Trigger Threshold: 0
Color Value B: 20
LED battery indicator brightness: 10
Buddy Device: ""
"""
def rpcs3():
seed(os.path.join(CONFIG, "rpcs3/input_configs/global/Default.yml"), RPCS3_PLAYER1, "RPCS3")
rpcs3_shader_mode()
# RPCS3's default shader mode (Async Recompiler with Shader Interpreter) builds 6650 interpreter
# pipelines at the start of every boot, minutes on an Adreno. The async recompiler compiles only
# what a game draws, in the background, once. A new install starts with it (a config.yml that
# holds only this is merged over RPCS3's defaults); an existing one still on the default is moved
# once, and a marker keeps any later choice the user makes in RPCS3's own settings.
RPCS3_INTERPRETER = "Async Recompiler with Shader Interpreter"
RPCS3_RECOMPILER = "Async Recompiler (multi-threaded)" # the GUI says "Async Shader Recompiler"; this is the value (system_config_types.cpp)
def rpcs3_shader_mode():
d = os.path.join(CONFIG, "rpcs3")
marker = os.path.join(d, ".droiddeck-shader-mode")
if os.path.exists(marker):
return
cfg = os.path.join(d, "config.yml")
if not os.path.isfile(cfg):
if seed(cfg, f"Video:\n Shader Mode: {RPCS3_RECOMPILER}\n", "RPCS3", f"shader mode {RPCS3_RECOMPILER}"):
open(marker, "w").close()
return
with open(cfg, encoding="utf-8", errors="replace") as f:
text = f.read()
if f"Shader Mode: {RPCS3_INTERPRETER}" in text:
text = text.replace(f"Shader Mode: {RPCS3_INTERPRETER}", f"Shader Mode: {RPCS3_RECOMPILER}", 1)
with open(cfg + ".tmp", "w", encoding="utf-8") as f:
f.write(text)
os.replace(cfg + ".tmp", cfg)
print(f"droiddeck-pad-defaults: RPCS3: shader mode {RPCS3_RECOMPILER} ({cfg})")
open(marker, "w").close()
# ---- ini helpers (DuckStation and PCSX2 share one ini dialect, keys may repeat) -------------
def ini_section(lines, name):
"""(start, end) line indices of [name]'s body, or None."""
start = None
for i, l in enumerate(lines):
t = l.strip()
if t.startswith("[") and t.endswith("]"):
if start is not None:
return start, i
if t[1:-1].strip() == name:
start = i + 1
return (start, len(lines)) if start is not None else None
def patch_ini_section(path, section, body, what, needle="SDL-", require=None, done="Player 1 on the controller"):
"""Add body's lines to [section] of an ini the emulator wrote itself, unless the section
already binds a controller (needle). Missing file: nothing - the emulator writes its own
defaults on first run and this runs again."""
if not os.path.isfile(path):
return
with open(path, encoding="utf-8", errors="replace") as f:
text = f.read()
if require and require not in text:
return
lines = text.splitlines()
span = ini_section(lines, section)
if span and any(needle in l for l in lines[span[0]:span[1]]):
return
new = body.strip("\n").splitlines()
if span:
# The controller type the emulator already wrote stays; only bindings are added.
have = {l.split("=", 1)[0].strip() for l in lines[span[0]:span[1]] if "=" in l}
new = [l for l in new if not (l.split("=", 1)[0].strip() == "Type" and "Type" in have)]
end = span[1]
while end > span[0] and not lines[end - 1].strip():
end -= 1
lines[end:end] = new
else:
lines += ["", f"[{section}]"] + new
with open(path + ".tmp", "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
os.replace(path + ".tmp", path)
print(f"droiddeck-pad-defaults: {what}: {done} ({path})")
# DuckStation: SDL-<n>/<name>, axes signed (src/util/sdl_input_source.cpp); Pad1 keys from
# src/core/analog_controller.cpp. Its defaults bind the keyboard only (settings.cpp).
DUCKSTATION_PAD1 = """Type = AnalogController
Up = SDL-0/DPadUp
Down = SDL-0/DPadDown
Left = SDL-0/DPadLeft
Right = SDL-0/DPadRight
Cross = SDL-0/A
Circle = SDL-0/B
Square = SDL-0/X
Triangle = SDL-0/Y
Select = SDL-0/Back
Start = SDL-0/Start
Analog = SDL-0/Guide
L1 = SDL-0/LeftShoulder
R1 = SDL-0/RightShoulder
L2 = SDL-0/+LeftTrigger
R2 = SDL-0/+RightTrigger
L3 = SDL-0/LeftStick
R3 = SDL-0/RightStick
LLeft = SDL-0/-LeftX
LRight = SDL-0/+LeftX
LUp = SDL-0/-LeftY
LDown = SDL-0/+LeftY
RLeft = SDL-0/-RightX
RRight = SDL-0/+RightX
RUp = SDL-0/-RightY
RDown = SDL-0/+RightY
LargeMotor = SDL-0/LargeMotor
SmallMotor = SDL-0/SmallMotor
"""
def ini_get(path, section, key):
try:
with open(path, encoding="utf-8", errors="replace") as f:
lines = f.read().splitlines()
except OSError:
return None
span = ini_section(lines, section)
if not span:
return None
for l in lines[span[0]:span[1]]:
if "=" in l and l.split("=", 1)[0].strip() == key:
return l.split("=", 1)[1].strip()
return None
def ini_set(path, section, key, value):
"""Sets one key (the first of that name) in [section], adding either as needed."""
with open(path, encoding="utf-8", errors="replace") as f:
lines = f.read().splitlines()
span = ini_section(lines, section)
if span is None:
lines += ["", f"[{section}]", f"{key} = {value}"]
else:
for i in range(span[0], span[1]):
if "=" in lines[i] and lines[i].split("=", 1)[0].strip() == key:
lines[i] = f"{key} = {value}"
break
else:
end = span[1]
while end > span[0] and not lines[end - 1].strip():
end -= 1
lines.insert(end, f"{key} = {value}")
with open(path + ".tmp", "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
os.replace(path + ".tmp", path)
def drop_line(path, line):
with open(path, encoding="utf-8", errors="replace") as f:
lines = f.read().splitlines()
kept = [l for l in lines if l.replace(" ", "") != line.replace(" ", "")]
if len(kept) != len(lines):
with open(path + ".tmp", "w", encoding="utf-8") as f:
f.write("\n".join(kept) + "\n")
os.replace(path + ".tmp", path)
def system_folder(names, default):
for name in names:
for cand in (name, name.upper()):
d = os.path.join(ROMS, cand)
if os.path.isdir(d):
return d
return os.path.join(ROMS, default)
def bios_folder(base):
for name in ("bios", "BIOS", "firmware"):
d = os.path.join(base, name)
if os.path.isdir(d):
return d
d = os.path.join(base, "bios")
if os.path.isdir(ROMS):
try:
os.makedirs(d, exist_ok=True) # where the user is told to put their BIOS
except OSError:
pass
return d
# DuckStation (PS1) - set up like ARMSX2: users bring their own BIOS and games, in the ROMs folder.
# Front-end runs use -batch -bigpicture -fullscreen, so the guide button is the pause menu
# (Hotkeys OpenPauseMenu, src/core/hotkeys.cpp), not the analog toggle. Keys from
# src/core/settings.cpp: [BIOS] SearchDirectory, [GPU] Renderer ("Vulkan"), [Main]
# SetupWizardIncomplete (src/duckstation-qt/qthost.cpp).
DUCKSTATION_PAD1_GUIDE_FREE = "\n".join(l for l in DUCKSTATION_PAD1.splitlines() if not l.startswith("Analog ")) + "\n"
def duckstation():
ps1 = system_folder(("psx", "ps1"), "psx")
d = os.path.join(CONFIG, "duckstation")
ini = os.path.join(d, "settings.ini")
legacy = os.path.join(HOME, ".local/share/duckstation/settings.ini")
if not os.path.isfile(ini) and os.path.isfile(legacy):
ini = legacy
if not os.path.isfile(ini):
# A new player: everything DuckStation's first-time setup asks is answered here (it finds
# the BIOS in its folder by itself), so a game from the front end boots straight away.
bios = bios_folder(ps1)
seed(ini, "[Main]\nSetupWizardIncomplete = false\nInhibitScreensaver = false\n\n"
f"[BIOS]\nSearchDirectory = {bios}\n\n"
f"[GameList]\nRecursivePaths = {ps1}\n\n"
"[GPU]\nRenderer = Vulkan\n\n"
"[Hotkeys]\nOpenPauseMenu = Keyboard/Escape\nOpenPauseMenu = SDL-0/Guide\n\n"
"[Pad1]\n" + DUCKSTATION_PAD1_GUIDE_FREE, "DuckStation", "first-time setup, BIOS from " + bios)
return
patch_ini_section(ini, "Pad1", DUCKSTATION_PAD1_GUIDE_FREE, "DuckStation")
drop_line(ini, "Analog = SDL-0/Guide")
patch_ini_section(ini, "Hotkeys", "OpenPauseMenu = SDL-0/Guide\n", "DuckStation", needle="SDL-0/Guide",
done="the guide button opens the pause menu")
patch_ini_section(ini, "GameList", f"RecursivePaths = {ps1}\n", "DuckStation", needle=ROMS,
done="games listed from the ROMs folder")
# One set up by an earlier build still has its first-time setup pending, in the way of a game.
if ini_get(ini, "Main", "SetupWizardIncomplete") == "true":
ini_set(ini, "Main", "SetupWizardIncomplete", "false")
print("droiddeck-pad-defaults: DuckStation: first-time setup already done here")
# Keeping the screen awake goes through org.freedesktop.ScreenSaver, which nothing in the session
# provides (Android decides when the screen sleeps): DuckStation only warns it failed, every game.
if (ini_get(ini, "Main", "InhibitScreensaver") or "true") == "true":
ini_set(ini, "Main", "InhibitScreensaver", "false")
print("droiddeck-pad-defaults: DuckStation: no screensaver inhibit (no such service here)")
# Once, for a DuckStation set up before this: its own empty BIOS folder moves to the ROMs folder,
# and Automatic becomes Vulkan. A later choice in DuckStation's settings is kept.
marker = os.path.join(os.path.dirname(ini), ".droiddeck-setup")
if os.path.exists(marker):
return
current = ini_get(ini, "BIOS", "SearchDirectory") or "bios"
own = current if os.path.isabs(current) else os.path.join(os.path.dirname(ini), current)
if not (os.path.isdir(own) and os.listdir(own)):
ini_set(ini, "BIOS", "SearchDirectory", bios_folder(ps1))
print(f"droiddeck-pad-defaults: DuckStation: BIOS from {bios_folder(ps1)}")
if (ini_get(ini, "GPU", "Renderer") or "Automatic") == "Automatic":
ini_set(ini, "GPU", "Renderer", "Vulkan")
print("droiddeck-pad-defaults: DuckStation: renderer Vulkan")
open(marker, "w").close()
# PCSX2: FaceSouth/... names (pcsx2/Input/SDLInputSource.cpp), keys from SIO/Pad/PadDualshock2.cpp.
# An ini without [UI] SettingsVersion is thrown away and rebuilt, so only a complete one is patched.
PCSX2_PAD1 = """Type = DualShock2
Up = SDL-0/DPadUp
Right = SDL-0/DPadRight
Down = SDL-0/DPadDown
Left = SDL-0/DPadLeft
Triangle = SDL-0/FaceNorth
Circle = SDL-0/FaceEast
Cross = SDL-0/FaceSouth
Square = SDL-0/FaceWest
Select = SDL-0/Back
Start = SDL-0/Start
L1 = SDL-0/LeftShoulder
R1 = SDL-0/RightShoulder
L2 = SDL-0/+LeftTrigger
R2 = SDL-0/+RightTrigger
L3 = SDL-0/LeftStick
R3 = SDL-0/RightStick
Analog = SDL-0/Guide
LUp = SDL-0/-LeftY
LRight = SDL-0/+LeftX
LDown = SDL-0/+LeftY
LLeft = SDL-0/-LeftX
RUp = SDL-0/-RightY
RRight = SDL-0/+RightX
RDown = SDL-0/+RightY
RLeft = SDL-0/-RightX
LargeMotor = SDL-0/LargeMotor
SmallMotor = SDL-0/SmallMotor
"""
def pcsx2():
patch_ini_section(os.path.join(CONFIG, "PCSX2/inis/PCSX2.ini"), "Pad1", PCSX2_PAD1, "PCSX2",
require="SettingsVersion")
# Dolphin: SDL/<id>/<SDL gamepad name>; control names from InputCommon/.../SDL/SDLGamepad.h (Left Y+
# is up). A section that exists is taken whole - keys it lacks are unbound - so both are complete.
DOLPHIN_GC = """[GCPad1]
Device = SDL/0/Xbox 360 Controller
Buttons/A = `Button S`
Buttons/B = `Button W`
Buttons/X = `Button E`
Buttons/Y = `Button N`
Buttons/Z = `Shoulder R`
Buttons/Start = `Start`
Main Stick/Up = `Left Y+`
Main Stick/Down = `Left Y-`
Main Stick/Left = `Left X-`
Main Stick/Right = `Left X+`
C-Stick/Up = `Right Y+`
C-Stick/Down = `Right Y-`
C-Stick/Left = `Right X-`
C-Stick/Right = `Right X+`
Triggers/L = `Trigger L`
Triggers/R = `Trigger R`
Triggers/L-Analog = `Trigger L`
Triggers/R-Analog = `Trigger R`
D-Pad/Up = `Pad N`
D-Pad/Down = `Pad S`
D-Pad/Left = `Pad W`
D-Pad/Right = `Pad E`
Rumble/Motor = `Motor`
"""
DOLPHIN_WII = """[Wiimote1]
Device = SDL/0/Xbox 360 Controller
Source = 1
Buttons/A = `Button S`
Buttons/B = `Trigger R`
Buttons/1 = `Button W`
Buttons/2 = `Button N`
Buttons/- = `Back`
Buttons/+ = `Start`
Buttons/Home = `Shoulder R`
D-Pad/Up = `Pad N`
D-Pad/Down = `Pad S`
D-Pad/Left = `Pad W`
D-Pad/Right = `Pad E`
IR/Up = `Right Y+`
IR/Down = `Right Y-`
IR/Left = `Right X-`
IR/Right = `Right X+`
Shake/X = `Button E`
Shake/Y = `Button E`
Shake/Z = `Button E`
Rumble/Motor = `Motor`
Extension = Nunchuk
Nunchuk/Buttons/C = `Shoulder L`
Nunchuk/Buttons/Z = `Trigger L`
Nunchuk/Stick/Up = `Left Y+`
Nunchuk/Stick/Down = `Left Y-`
Nunchuk/Stick/Left = `Left X-`
Nunchuk/Stick/Right = `Left X+`
"""
# ARMSX2 - the PS2 emulator (PCSX2 with ARM64 recompilers; upstream PCSX2 interprets on ARM64). Its
# files are PCSX2's under $XDG_CONFIG_HOME/ARMSX2 (pcsx2/Pcsx2Config.cpp). The user supplies the BIOS
# and the games; they live in the ROMs folder (/root/ROMs). The guide button opens the pause menu
# (Hotkeys OpenPauseMenu) - the way out of a game started from the front end, which runs ARMSX2
# without its window (-batch -bigpicture) - so it is not also the analog toggle here.
ARMSX2_PAD1 = "\n".join(l for l in PCSX2_PAD1.splitlines() if not l.startswith("Analog ")) + "\n"
ROMS = "/root/ROMs"
def ps2_folder():
for name in ("ps2", "PS2"):
d = os.path.join(ROMS, name)
if os.path.isdir(d):
return d
return os.path.join(ROMS, "ps2")
def ps2_bios_folder():
base = ps2_folder()
for name in ("bios", "BIOS", "firmware"):
d = os.path.join(base, name)
if os.path.isdir(d):
return d
d = os.path.join(base, "bios")
if os.path.isdir(ROMS):
try:
os.makedirs(d, exist_ok=True) # where the user is told to put their BIOS
except OSError:
pass
return d
def armsx2():
root = os.path.join(CONFIG, "ARMSX2")
ini = os.path.join(root, "inis/PCSX2.ini")
old = os.path.join(CONFIG, "PCSX2")
if not os.path.isfile(ini) and os.path.isfile(os.path.join(old, "inis/PCSX2.ini")):
# Someone who played on PCSX2 here: the same settings, BIOS choice and memory cards (the
# saves), copied once. PCSX2's own folder is left as it was.
import shutil
for sub in ("inis", "memcards", "bios", "gamesettings", "cheats", "patches", "covers",
"inputprofiles", "textures"):
src = os.path.join(old, sub)
if os.path.isdir(src):
shutil.copytree(src, os.path.join(root, sub), dirs_exist_ok=True)
print(f"droiddeck-pad-defaults: ARMSX2: settings and memory cards copied from PCSX2 ({root})")
elif not os.path.isfile(ini):
# A new player: everything ARMSX2's first-time setup asks is answered here - the BIOS
# folder in the ROMs folder, the ps2 folder as its game list, the controller on Player 1 -
# and the BIOS file itself is picked below once one is there.
bios, games = ps2_bios_folder(), ps2_folder()
seed(ini, "[UI]\nSettingsVersion = 1\nSetupWizardIncomplete = false\n\n"
f"[Folders]\nBios = {bios}\n\n"
f"[GameList]\nRecursivePaths = {games}\n\n"
# Vulkan outright rather than Auto's pick: the renderer every other path here uses.
"[EmuCore/GS]\nRenderer = 14\n\n"
"[Hotkeys]\nOpenPauseMenu = Keyboard/Escape\nOpenPauseMenu = SDL-0/Guide\n\n"
"[Pad1]\n" + ARMSX2_PAD1, "ARMSX2", "first-time setup, BIOS from " + bios)
armsx2_bios(ini)
return
patch_ini_section(ini, "Pad1", ARMSX2_PAD1, "ARMSX2", require="SettingsVersion")
# The guide button is the pause menu here; PCSX2's profile (ours, copied over) had it as the
# analog toggle as well.
with open(ini, encoding="utf-8", errors="replace") as f:
lines = f.read().splitlines()
kept = [l for l in lines if l.replace(" ", "") != "Analog=SDL-0/Guide"]
if len(kept) != len(lines):
with open(ini + ".tmp", "w", encoding="utf-8") as f:
f.write("\n".join(kept) + "\n")
os.replace(ini + ".tmp", ini)
patch_ini_section(ini, "Hotkeys", "OpenPauseMenu = SDL-0/Guide\n", "ARMSX2", needle="SDL-0/Guide",
require="SettingsVersion", done="the guide button opens the pause menu")
patch_ini_section(ini, "GameList", f"RecursivePaths = {ps2_folder()}\n", "ARMSX2", needle=ROMS,
require="SettingsVersion", done="games listed from the ROMs folder")
if ini_get(ini, "UI", "SetupWizardIncomplete") == "true":
ini_set(ini, "UI", "SetupWizardIncomplete", "false")
print("droiddeck-pad-defaults: ARMSX2: first-time setup already done here")
armsx2_bios(ini)
def armsx2_bios(ini):
"""PCSX2 boots the one BIOS file named in [Filenames] BIOS (inside [Folders] Bios); its first-time
setup is what names it. With that skipped, the first dump in the folder is named here - a US one
first - while none is named or the named one is gone. A choice made in ARMSX2 is kept."""
folder = ini_get(ini, "Folders", "Bios") or ps2_bios_folder()
if not os.path.isabs(folder):
folder = os.path.join(os.path.dirname(os.path.dirname(ini)), folder)
current = ini_get(ini, "Filenames", "BIOS")
if current and os.path.isfile(os.path.join(folder, current)):
return
try:
# A PS2 BIOS dump is 4 MiB (a few are 8); the .nvm/.mec files beside it are not dumps.
dumps = sorted(f for f in os.listdir(folder)
if os.path.isfile(os.path.join(folder, f)) and 4 << 20 <= os.path.getsize(os.path.join(folder, f)) <= 8 << 20)
except OSError:
return
if not dumps:
return
us = [f for f in dumps if any(t in f.lower() for t in ("usa", "(us)", "(us,", "ntsc-u"))]
pick = (us or dumps)[0]
ini_set(ini, "Filenames", "BIOS", pick)
print(f"droiddeck-pad-defaults: ARMSX2: BIOS {pick}")
# Dolphin (PC) has no controller menu, so the guide button is its Toggle Fullscreen hotkey: out of full
# screen is Dolphin's own window with its Config / Graphics / Stop buttons. Hotkeys.ini is all-or-
# nothing - a file with one line drops every other default - so a new one carries Dolphin's defaults,
# generated from HotkeyManager.cpp's LoadDefaults (Linux branch, RetroAchievements on) plus the guide;
# an existing one only gets the guide added to its Toggle Fullscreen. The Wii remote's Home, which
# was on the guide button, is on the right shoulder button instead.
DOLPHIN_GUIDE = "`SDL/0/Xbox 360 Controller:Guide`"
DOLPHIN_HOTKEYS = """[Hotkeys]
Device = XInput2/0/Virtual core pointer
General/Open = @(Ctrl+O)
General/Toggle Pause = F10
General/Stop = Escape
General/Toggle Fullscreen = @(Alt+Return) | `SDL/0/Xbox 360 Controller:Guide`
General/Take Screenshot = F9
General/Open Achievements = @(Alt+A)
Emulation Speed/Disable Emulation Speed Limit = Tab
Stepping/Step Into = F11
Stepping/Step Over = @(Shift+F10)
Stepping/Step Out = @(Shift+F11)
Breakpoint/Toggle Breakpoint = @(Shift+F9)
Wii/Connect Wii Remote 1 = @(Alt+F5)
Wii/Connect Wii Remote 2 = @(Alt+F6)
Wii/Connect Wii Remote 3 = @(Alt+F7)
Wii/Connect Wii Remote 4 = @(Alt+F8)
Wii/Connect Balance Board = @(Alt+F9)
Load State/Load State Slot 1 = F1
Load State/Load State Slot 2 = F2
Load State/Load State Slot 3 = F3
Load State/Load State Slot 4 = F4
Load State/Load State Slot 5 = F5
Load State/Load State Slot 6 = F6
Load State/Load State Slot 7 = F7
Load State/Load State Slot 8 = F8
Save State/Save State Slot 1 = @(Shift+F1)
Save State/Save State Slot 2 = @(Shift+F2)
Save State/Save State Slot 3 = @(Shift+F3)
Save State/Save State Slot 4 = @(Shift+F4)
Save State/Save State Slot 5 = @(Shift+F5)
Save State/Save State Slot 6 = @(Shift+F6)
Save State/Save State Slot 7 = @(Shift+F7)
Save State/Save State Slot 8 = @(Shift+F8)
Other State Hotkeys/Undo Load State = F12
Other State Hotkeys/Undo Save State = @(Shift+F12)
GBA Core/Load ROM = @(`Ctrl`+`Shift`+`O`)
GBA Core/Unload ROM = @(`Ctrl`+`Shift`+`W`)
GBA Core/Reset = @(`Ctrl`+`Shift`+`R`)
GBA Volume/Volume Down = `KP_Subtract`
GBA Volume/Volume Up = `KP_Add`
GBA Volume/Volume Toggle Mute = `M`
GBA Window Size/1x = `KP_1`
GBA Window Size/2x = `KP_2`
GBA Window Size/3x = `KP_3`
GBA Window Size/4x = `KP_4`
USB Emulation Devices/Show Skylanders Portal = @(Ctrl+P)
USB Emulation Devices/Show Infinity Base = @(Ctrl+I)
"""
DOLPHIN_APPIMAGE = "/opt/appimages/dolphin.AppImage"
DOLPHIN_DATA = "/usr/share/dolphin-emu"
def dolphin_data():
"""The Dolphin build in the catalog finds its own data - the GameCube fonts, the per-game fixes
(GameSettings: GUT.ini puts Ultimate Spider-Man on the MMU), its icons and shaders - only at the
fixed /usr/share/dolphin-emu it was built for; there is no setting or variable to move it. Here it
runs from a copy unpacked under /tmp (no FUSE), so it found none of it: a GameCube game stopped
on "Windows-1252 fonts are not loaded", another on an invalid write the missing game fix would
have prevented. So the folder is unpacked from the AppImage to that path, once per AppImage."""
import shutil, subprocess, tempfile
try:
st = os.stat(DOLPHIN_APPIMAGE)
except OSError:
return
stamp = "%d:%d" % (st.st_size, int(st.st_mtime))
marker = os.path.join(DOLPHIN_DATA, ".droiddeck-from")
try:
if open(marker).read() == stamp and os.path.isfile(os.path.join(DOLPHIN_DATA, "Sys/GC/font_western.bin")):
return
except OSError:
pass
work = tempfile.mkdtemp(prefix="dolphin-data-", dir="/tmp")
try:
subprocess.run([DOLPHIN_APPIMAGE, "--appimage-extract", "usr/share/dolphin-emu/*"], cwd=work,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=600)
src = os.path.join(work, "squashfs-root/usr/share/dolphin-emu")
if not os.path.isfile(os.path.join(src, "Sys/GC/font_western.bin")):
print("droiddeck-pad-defaults: Dolphin: could not unpack its data from the AppImage")
return
new = DOLPHIN_DATA + ".new"
shutil.rmtree(new, ignore_errors=True)
shutil.move(src, new)
with open(os.path.join(new, ".droiddeck-from"), "w") as f:
f.write(stamp)
shutil.rmtree(DOLPHIN_DATA, ignore_errors=True)
os.rename(new, DOLPHIN_DATA)
print("droiddeck-pad-defaults: Dolphin: its data (fonts, per-game fixes) in " + DOLPHIN_DATA)
except (OSError, subprocess.SubprocessError) as e:
print("droiddeck-pad-defaults: Dolphin: unpacking its data failed: %s" % e)
finally:
shutil.rmtree(work, ignore_errors=True)
def dolphin():
if not os.path.isfile(DOLPHIN_APPIMAGE):
return
dolphin_data()
d = os.path.join(CONFIG, "dolphin-emu")
seed(os.path.join(d, "GCPadNew.ini"), DOLPHIN_GC, "Dolphin (GameCube)")
seed(os.path.join(d, "WiimoteNew.ini"), DOLPHIN_WII, "Dolphin (Wii)")
wii_pad = os.path.join(d, "WiimoteNew.ini")
if ini_get(wii_pad, "Wiimote1", "Buttons/Home") == "`Guide`":
ini_set(wii_pad, "Wiimote1", "Buttons/Home", "`Shoulder R`")
print("droiddeck-pad-defaults: Dolphin (Wii): Home on the right shoulder button (guide = Dolphin's window)")
hotkeys = os.path.join(d, "Hotkeys.ini")
if not os.path.isfile(hotkeys):
seed(hotkeys, DOLPHIN_HOTKEYS, "Dolphin", "the guide button shows Dolphin's window (Toggle Fullscreen)")
else:
current = ini_get(hotkeys, "Hotkeys", "General/Toggle Fullscreen")
if current is not None and DOLPHIN_GUIDE not in current:
ini_set(hotkeys, "Hotkeys", "General/Toggle Fullscreen",
(current + " | " if current else "") + DOLPHIN_GUIDE)
print("droiddeck-pad-defaults: Dolphin: the guide button shows Dolphin's window (Toggle Fullscreen)")
# Games from the ROMs folder's gamecube and wii folders, subfolders included; Vulkan; no
# NKit warning (it will not let a game start until a box is ticked - games run either way,
# the warning is about loading times, netplay and save states); no statistics question.
# Names from Dolphin's MainSettings.cpp / UISettings.cpp. Only what is not set yet is added,
# except the game folders, which are added to whatever the user has.
ini = os.path.join(d, "Dolphin.ini")
gc = system_folder(("gamecube", "gc", "ngc"), "gamecube")
wii = system_folder(("wii",), "wii")
if not os.path.isfile(ini):
os.makedirs(d, exist_ok=True)
with open(ini, "w", encoding="utf-8") as f:
f.write("[Analytics]\nEnabled = False\nPermissionAsked = True\n"
"[Core]\nGFXBackend = Vulkan\n"
"[General]\nISOPaths = 2\nISOPath0 = %s\nISOPath1 = %s\nRecursiveISOPaths = True\n"
"[Interface]\nSkipNKitWarning = True\n" % (gc, wii))
print("droiddeck-pad-defaults: Dolphin: first-time setup (Vulkan, games from %s and %s)" % (gc, wii))
return
try:
count = int(ini_get(ini, "General", "ISOPaths") or "0")
except ValueError:
count = 0
paths = [ini_get(ini, "General", "ISOPath%d" % i) for i in range(count)]
changed = []
# The whole ROMs folder as a game folder (what Dolphin's "set a games directory" was pointed at
# before) would, searched with its subfolders, have Dolphin open every PS2 and PS3 image too;
# the system folders below cover it.
if any((p or "").rstrip("/") == ROMS for p in paths):
paths = [p for p in paths if p and p.rstrip("/") != ROMS]
for i, p in enumerate(paths):
ini_set(ini, "General", "ISOPath%d" % i, p)
for i in range(len(paths), count):
ini_set(ini, "General", "ISOPath%d" % i, "")
count = len(paths)
ini_set(ini, "General", "ISOPaths", str(count))
changed.append("not the whole ROMs folder")
for folder in (gc, wii):
if folder not in paths:
ini_set(ini, "General", "ISOPath%d" % count, folder)
count += 1
paths.append(folder)
changed.append(folder)
if changed:
ini_set(ini, "General", "ISOPaths", str(count))
if ini_get(ini, "General", "RecursiveISOPaths") != "True":
ini_set(ini, "General", "RecursiveISOPaths", "True")
changed.append("subfolders")
if changed:
print("droiddeck-pad-defaults: Dolphin: games from " + ", ".join(changed))
# Once, for a Dolphin set up before this: Vulkan unless it was chosen already, and the NKit box.
marker = os.path.join(d, ".droiddeck-setup")
if os.path.exists(marker):
return
if not ini_get(ini, "Core", "GFXBackend"):
ini_set(ini, "Core", "GFXBackend", "Vulkan")
ini_set(ini, "Interface", "SkipNKitWarning", "True")
if ini_get(ini, "Analytics", "PermissionAsked") != "True":
ini_set(ini, "Analytics", "Enabled", "False")
ini_set(ini, "Analytics", "PermissionAsked", "True")
open(marker, "w").close()
print("droiddeck-pad-defaults: Dolphin: Vulkan, no NKit warning")
# Cemu: an SDLController profile for the GamePad. The uuid is "<index>_<SDL GUID>" and SDL's GUID
# carries a CRC of the device name; this is the one SDL reports for the session's pad
# ("Xbox 360 Controller (0)", 045e:028e - read from RPCS3's SDL log on the device). Mapping ids
# from VPADController.h, values from Controller.h, Cemu's own SDL default layout plus Home.
CEMU_MAP = [(1, 1), (2, 0), (3, 3), (4, 2), (5, 9), (6, 10), (7, 42), (8, 43), (9, 6), (10, 4),
(11, 11), (12, 12), (13, 13), (14, 14), (15, 7), (16, 8), (17, 45), (18, 39), (19, 44),
(20, 38), (21, 47), (22, 41), (23, 46), (24, 40), (27, 5)]
CEMU_XML = """<?xml version="1.0" encoding="UTF-8"?>
<emulated_controller>
\t<type>Wii U GamePad</type>
\t<toggle_display>0</toggle_display>
\t<controller>
\t\t<api>SDLController</api>
\t\t<uuid>0_03005e615e0400008e02000010010000</uuid>
\t\t<display_name>Xbox 360 Controller</display_name>
\t\t<rumble>0.5</rumble>
\t\t<mappings>
""" + "".join(f"\t\t\t<entry>\n\t\t\t\t<mapping>{m}</mapping>\n\t\t\t\t<button>{b}</button>\n\t\t\t</entry>\n" for m, b in CEMU_MAP) + """\t\t</mappings>
\t</controller>
</emulated_controller>
"""
# Cemu's settings, so its Getting Started dialog (shown while settings.xml is missing, and whose
# folder picker cannot reach ROMs) never blocks a launch: the Wii U games folder, Vulkan
# (Graphic api 1), and audio through Cubeb (the only backend on Linux; api 3) on the default
# device for both the TV and the GamePad speaker - some titles play everything through the
# GamePad - at full volume (Cemu's own default is 20 %). Keys from config/CemuConfig.cpp.
CEMU_SETTINGS = """<?xml version="1.0" encoding="UTF-8"?>
<content>
<mlc_path></mlc_path>
<GamePaths>
<Entry>{games}</Entry>
</GamePaths>
<Graphic>
<api>1</api>
</Graphic>
<Audio>
<api>3</api>
<TVVolume>100</TVVolume>
<PadVolume>100</PadVolume>
<TVDevice>default</TVDevice>
<PadDevice>default</PadDevice>
</Audio>
</content>
"""
def cemu():
seed(os.path.join(CONFIG, "Cemu/controllerProfiles/controller0.xml"), CEMU_XML, "Cemu")
games = system_folder(["wiiu", "wii u"], "wiiu")
seed(os.path.join(CONFIG, "Cemu/settings.xml"), CEMU_SETTINGS.format(games=games), "Cemu",
done=f"games in {games}, Vulkan, Cubeb audio on the default device")
# melonDS 1.x: raw SDL joystick indices. The session's pad has the kernel's Xbox 360 layout
# (buttons A B X Y LB RB Back Start Guide LS RS = 0..10, hat 0 for the d-pad); the d-pad values
# also take the left stick (EmuInstanceInput.cpp; encoding InputConfig/MapButton.h). The guide
# button toggles full screen (HK_FullscreenToggle), as it does in Dolphin: the front end starts
# melonDS full screen (-f), and leaving it shows the window's menus for settings.
MELONDS_GUIDE = 8
MELONDS_JOY = f"""[Instance0.Joystick]
A = 1
B = 0
X = 3
Y = 2
L = 4
R = 5
Select = 6
Start = 7
Up = 17891585
Down = 16843012
Left = 1114376
Right = 65794
HK_FullscreenToggle = {MELONDS_GUIDE}
"""
# The screen a handheld's wide panel suits best: the top screen as big as the panel's height allows
# with the bottom screen alone beside it, centred (ScreenLayout.h: Horizontal = 2, EmphTop = 1;
# melonDS's Hybrid shows the big screen a second time, small, above the bottom one; nobody needs
# it twice). Sharp pixels: no filtering, and no integer steps that leave the panel half used. Keys as
# melonDS writes them (Window.cpp windowCfg).
MELONDS_WINDOW = """[Instance0.Window0]
ScreenLayout = 2
ScreenSizing = 1
IntegerScaling = false
ScreenFilter = false
"""
# melonDS's own defaults for those, which an existing install is moved off once. Hybrid (3) was
# this preset's first layout, and moves on too.
MELONDS_WINDOW_DEFAULTS = {"ScreenLayout": ("0", "3"), "ScreenSizing": ("0",), "ScreenFilter": ("true",)}
# The window melonDS returns to when the guide button leaves full screen: 1x wide (the width of
# two DS screens side by side, Screen.cpp screenGetMinSize) and 16:9, so gamescope stretches it to
# fill the panel and the menu bar and cursor come out large enough to use. A bigger window keeps
# its menus at their real size, tiny on a handheld. Qt's saveGeometry() v3 blob: magic, version,
# frame and normal rects (x, y, right, bottom), screen, maximized, full screen, screen width, and
# the normal rect again (QWidget::restoreGeometry).
def melonds_geometry():
import base64, struct
w, h = 512, 288
try:
screen_w = int(os.environ.get("BL_WIDTH", "1920"))
except ValueError:
screen_w = 1920
rect = (0, 0, w - 1, h - 1)
blob = struct.pack(">IHH4i4iiBBi4i", 0x1D9D0CB, 3, 0, *rect, *rect, 0, 0, 0, screen_w, *rect)
return base64.b64encode(blob).decode()
def toml_get(lines, table, key):
"""The raw value of key in [table], or None."""
inside = False
for l in lines:
t = l.strip()
if t.startswith("["):
inside = t == f"[{table}]"
elif inside and "=" in t and t.split("=", 1)[0].strip() == key:
return t.split("=", 1)[1].strip()
return None
def toml_set(lines, table, key, value):
"""key = value in [table]; the table is added at the end when missing."""
start = None
for i, l in enumerate(lines):
t = l.strip()
if t.startswith("["):
if start is not None:
break
if t == f"[{table}]":
start = i
elif start is not None and "=" in t and t.split("=", 1)[0].strip() == key:
lines[i] = f"{key} = {value}"
return
if start is None:
lines += ["", f"[{table}]", f"{key} = {value}"]
return
end = start + 1
while end < len(lines) and not lines[end].strip().startswith("["):
end += 1
while end > start + 1 and not lines[end - 1].strip():
end -= 1
lines.insert(end, f"{key} = {value}")
def toml_str(path):
return '"' + path.replace("\\", "\\\\").replace('"', '\\"') + '"'
# The user's own BIOS, firmware and DSi NAND, found in the ROMs folder's nds/bios (or firmware)
# folder by what each file is: the DS BIOSes by size and checksum (the GBA BIOS is also 16 KB),
# firmware and NAND by size, the DSi boot ROMs (both 64 KB) by the 7 or 9 in their names. A path
# is only filled where melonDS has none, and external files are only switched on when a whole set
# was found - without them melonDS runs DS games on its built-in free BIOS.
DS_BIOS7_MD5 = "df692a80a5b1bc90728bc3dfc76cd948"
DS_BIOS9_MD5 = "a392174eb3e572fed6447e956bde4b25"
def nds_firmware_files():
import hashlib
base = system_folder(("nds", "ds"), "nds")
roots = [os.path.join(base, n) for n in ("bios", "BIOS", "firmware") if os.path.isdir(os.path.join(base, n))]
found = {}
for root in roots:
for d, _, files in os.walk(root):
if d[len(root):].count(os.sep) > 2:
continue
for name in sorted(files):
f = os.path.join(d, name)
try:
size = os.path.getsize(f)
except OSError:
continue
low = name.lower()
if size == 16384 or size == 4096:
with open(f, "rb") as h:
md5 = hashlib.md5(h.read()).hexdigest()
if md5 == DS_BIOS7_MD5:
found.setdefault("DS.BIOS7Path", f)
elif md5 == DS_BIOS9_MD5:
found.setdefault("DS.BIOS9Path", f)
elif size in (262144, 524288) and "dsi" not in low:
found.setdefault("DS.FirmwarePath", f)
elif size == 65536:
if "arm7" in low or "bios7" in low:
found.setdefault("DSi.BIOS7Path", f)
elif "arm9" in low or "bios9" in low:
found.setdefault("DSi.BIOS9Path", f)
elif size == 131072:
found.setdefault("DSi.FirmwarePath", f)
elif size >= 200 * 1024 * 1024 and "nand" in low:
found.setdefault("DSi.NANDPath", f)
return found
def melonds_bios(lines):
found = nds_firmware_files()
changed = []
for key, f in found.items():
table, k = key.split(".", 1)
if (toml_get(lines, table, k) or '""') == '""':
toml_set(lines, table, k, toml_str(f))
changed.append(key)
for table, flag, keys in (("Emu", "ExternalBIOSEnable", ("DS.BIOS7Path", "DS.BIOS9Path", "DS.FirmwarePath")),
("DSi", "ExternalBIOSEnable", ("DSi.BIOS7Path", "DSi.BIOS9Path", "DSi.FirmwarePath", "DSi.NANDPath"))):
if all(k in found for k in keys) and any(k in changed for k in keys):
toml_set(lines, table, flag, "true")
return changed
def melonds():
path = os.path.join(CONFIG, "melonDS/melonDS.toml")
marker = os.path.join(os.path.dirname(path), ".droiddeck-display-2")
if not os.path.isfile(path):
seed(path, "[Instance0]\nJoystickID = 0\n\n" + MELONDS_JOY + "\n" + MELONDS_WINDOW +
f'Geometry = "{melonds_geometry()}"\n', "melonDS",
"Player 1 on the controller, big top screen")
open(marker, "w").close()
with open(path, encoding="utf-8", errors="replace") as f:
text = f.read()
try:
import tomllib
joy = tomllib.loads(text).get("Instance0", {}).get("Joystick", {})
except Exception:
return
lines = text.splitlines()
done = []
if not any(isinstance(v, int) and v != -1 and k != "HK_FullscreenToggle" for k, v in joy.items()):
# Replace melonDS's own all-unbound table with ours (a TOML table can be defined only once).
out, skipping = [], False
for line in lines:
t = line.strip()
if t.startswith("["):
skipping = t == "[Instance0.Joystick]"
if not skipping:
out.append(line)
lines = "\n".join(out).rstrip("\n").splitlines() + [""] + MELONDS_JOY.rstrip("\n").splitlines()
done.append("Player 1 on the controller")
elif joy.get("HK_FullscreenToggle", -1) == -1 and MELONDS_GUIDE not in joy.values():
toml_set(lines, "Instance0.Joystick", "HK_FullscreenToggle", str(MELONDS_GUIDE))
done.append("guide button toggles full screen")
# Once, for a melonDS set up before this: the big top screen, where it is still on its own
# defaults. The marker keeps whatever the user picks in melonDS's View menu afterwards.
if not os.path.exists(marker):
for l in MELONDS_WINDOW.splitlines()[1:]:
k, v = (x.strip() for x in l.split("=", 1))
if toml_get(lines, "Instance0.Window0", k) in (None,) + MELONDS_WINDOW_DEFAULTS.get(k, ()):
toml_set(lines, "Instance0.Window0", k, v)
toml_set(lines, "Instance0.Window0", "Geometry", f'"{melonds_geometry()}"')
done.append("big top screen, 1x window")
open(marker, "w").close()
bios = melonds_bios(lines)
if bios:
done.append("BIOS " + ", ".join(bios))
if done:
with open(path + ".tmp", "w", encoding="utf-8") as f:
f.write("\n".join(lines).rstrip("\n") + "\n")
os.replace(path + ".tmp", path)
print(f"droiddeck-pad-defaults: melonDS: {'; '.join(done)} ({path})")
# PPSSPP (SDL): its pad defaults leave the shoulders, the right stick and the triggers unbound on
# SDL builds (SDLJoystick.cpp codes vs KeyMapDefaults.cpp); a [ControlMapping] that exists replaces
# every default, so this one is complete, keyboard included (device 1 keyboard, 10 pad).
PPSSPP_CONTROLS = """[ControlMapping]
Up = 1-19,10-19
Down = 1-20,10-20
Left = 1-21,10-21
Right = 1-22,10-22
Cross = 1-54,10-189
Circle = 1-52,10-190
Square = 1-29,10-191
Triangle = 1-47,10-188
Start = 1-62,10-197
Select = 1-66,10-196
L = 1-45,10-193
R = 1-51,10-192
An.Up = 1-37,10-4003
An.Down = 1-39,10-4002
An.Left = 1-38,10-4001
An.Right = 1-40,10-4000
RightAn.Up = 10-4007
RightAn.Down = 10-4006
RightAn.Left = 10-4005
RightAn.Right = 10-4004
Pause = 1-111,10-4
"""
def ppsspp():
seed(os.path.join(CONFIG, "ppsspp/PSP/SYSTEM/controls.ini"), PPSSPP_CONTROLS, "PPSSPP")
# RetroArch: the udev joypad driver finds nothing here (no udev database in the runtime); sdl2
# does, and matches this profile by vendor/product (task_autodetect.c).
RETROARCH_PROFILE = """input_driver = "sdl2"
input_device = "Xbox 360 Controller"
input_vendor_id = "1118"
input_product_id = "654"
input_b_btn = "0"
input_a_btn = "1"
input_y_btn = "2"
input_x_btn = "3"
input_select_btn = "4"
input_menu_toggle_btn = "5"
input_start_btn = "6"
input_l3_btn = "7"
input_r3_btn = "8"
input_l_btn = "9"
input_r_btn = "10"
input_up_btn = "11"
input_down_btn = "12"
input_left_btn = "13"
input_right_btn = "14"
input_l2_axis = "+4"
input_r2_axis = "+5"
input_l_x_plus_axis = "+0"
input_l_x_minus_axis = "-0"
input_l_y_plus_axis = "+1"
input_l_y_minus_axis = "-1"
input_r_x_plus_axis = "+2"
input_r_x_minus_axis = "-2"
input_r_y_plus_axis = "+3"
input_r_y_minus_axis = "-3"
"""
def retroarch():
d = os.path.join(CONFIG, "retroarch")
seed(os.path.join(d, "autoconfig/sdl2/Xbox 360 Controller.cfg"), RETROARCH_PROFILE, "RetroArch (profile)")
cfg = os.path.join(d, "retroarch.cfg")
if not os.path.isfile(cfg):
seed(cfg, 'input_joypad_driver = "sdl2"\ninput_autodetect_enable = "true"\n', "RetroArch")
return
with open(cfg, encoding="utf-8", errors="replace") as f:
lines = f.read().splitlines()
changed = False
for i, l in enumerate(lines):
if l.replace(" ", "").startswith('input_joypad_driver="udev"'):
lines[i] = 'input_joypad_driver = "sdl2"'
changed = True
if changed:
with open(cfg + ".tmp", "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
os.replace(cfg + ".tmp", cfg)
print(f"droiddeck-pad-defaults: RetroArch: joypad driver udev -> sdl2 ({cfg})")
# yuzu and its forks: Player 1 in [Controls] of <name>/qt-config.ini, which each writes at its first
# start with the keyboard bound. Bindings are input_common ParamPackages, laid out by position as the
# frontend's own auto-map does (sdl_driver.cpp GetDefaultButtonBinding); the guid is SDL's with the
# name CRC cleared (GetGUID). A key is only read while its \default is false. Done once per emulator,
# and only while Player 1 is still on the keyboard.
SWITCH_PAD = "engine:sdl,port:0,guid:030000005e0400008e02000010010000,"
SWITCH_PLAYER1 = {
"button_a": "button:1", "button_b": "button:0", "button_x": "button:3", "button_y": "button:2",
"button_lstick": "button:9", "button_rstick": "button:10", "button_l": "button:4", "button_r": "button:5",
"button_zl": "axis:2,threshold:0.5,invert:+", "button_zr": "axis:5,threshold:0.5,invert:+",
"button_plus": "button:7", "button_minus": "button:6", "button_home": "button:8",
"button_dleft": "hat:0,direction:left", "button_dup": "hat:0,direction:up",
"button_dright": "hat:0,direction:right", "button_ddown": "hat:0,direction:down",
"lstick": "axis_x:0,axis_y:1,offset_x:0,offset_y:0,invert_x:+,invert_y:+",
"rstick": "axis_x:3,axis_y:4,offset_x:0,offset_y:0,invert_x:+,invert_y:+",
}
def switch_emulators():
for name in sorted(os.listdir(CONFIG)) if os.path.isdir(CONFIG) else ():
cfg = os.path.join(CONFIG, name, "qt-config.ini")
marker = os.path.join(CONFIG, name, ".droiddeck-pad")
if os.path.exists(marker) or not os.path.isfile(cfg):
continue
with open(cfg, encoding="utf-8", errors="replace") as f:
lines = f.read().splitlines()
span = ini_section(lines, "Controls")
if not span:
continue
current = {l.split("=", 1)[0]: l.split("=", 1)[1] for l in lines[span[0]:span[1]] if "=" in l}
if "engine:keyboard" not in current.get("player_0_button_a", ""):
continue
wanted = {"player_0_connected": "true", "player_0_type": "0"}
for key, binding in SWITCH_PLAYER1.items():
wanted[f"player_0_{key}"] = f'"{SWITCH_PAD}{binding}"'
body = [l for l in lines[span[0]:span[1]]
if l.split("=", 1)[0].removesuffix("\\default") not in wanted]
while body and not body[-1].strip():
body.pop()
for key, value in wanted.items():
body += [f"{key}\\default=false", f"{key}={value}"]
lines[span[0]:span[1]] = body + [""]
with open(cfg + ".tmp", "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
os.replace(cfg + ".tmp", cfg)
open(marker, "w").close()
print(f"droiddeck-pad-defaults: {name}: Player 1 on the controller ({cfg})")
for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators):
try:
step()
except Exception as e:
print(f"droiddeck-pad-defaults: {step.__name__}: {e}")