diff --git a/install.ps1 b/install.ps1 index 9287cf7e3..fda15608d 100644 --- a/install.ps1 +++ b/install.ps1 @@ -16,7 +16,7 @@ # and Invoke-WebRequest throws on a cut transfer before the hash is read: # the site's build rewrites this line there (scripts/sitebootstrap.py). $mismatchAdvice = "The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that." - $defaultInstallSha256 = "5d583c967fc8e68c3f3dcc5000a3a882476d55e548c69adc952b936f92d85bc2" + $defaultInstallSha256 = "1cd472779f9a83fc33c10a464275c6defa1d7995d12091267c4c815384147909" # The pin above refuses any changed byte: this cap only stops a body that # cannot be the installer (a sign-in portal's page) before it is hashed. $maximumInstallerBytes = 8MB diff --git a/install.py b/install.py index 52e8a8c04..fbaec61db 100644 --- a/install.py +++ b/install.py @@ -2628,6 +2628,385 @@ class ReadCounter: print("\r\033[K", end="", file=self.stream, flush=True) +# --- installer/detect_android.py --------------------------------------------- + +# The three RetroArch packages published for Android, newest ABI first. +ANDROID_RETROARCH_PACKAGES = ( + "com.retroarch.aarch64", + "com.retroarch", + "com.retroarch.ra32", +) +# Where Android keeps each app's private data. +ANDROID_APP_DATA = Path("/data/data") + + +def _android_storage_root() -> Path: + """Shared storage root, the parent RetroArch builds its defaults from.""" + value = os.environ.get("EXTERNAL_STORAGE", "").strip() + return Path(value) if value else Path("/storage/emulated/0") + + +# Where each RetroArch package keeps its folders, RetroArch v1.22.2 +# (pkg/android/phoenix/build.gradle:46-95). com.retroarch and +# com.retroarch.aarch64 are each published twice under one id: by +# retroarch.com (normal, aarch64) and on Google Play (playStoreNormal, +# playStorePlus). com.retroarch.ra32 has no Google Play flavor. The Google +# Play build hands RetroArch Android/data//files as the storage its +# defaults are built from, the other builds the shared storage root +# (MainMenuActivity.java:182-183). +_ANDROID_RETROARCH_PLAY_IDS = ("com.retroarch", "com.retroarch.aarch64") +# A Google Play versionCode is the manifest's 1597175267 (AndroidManifest.xml:5) +# plus one per half week since 1609632000 (build.gradle:76, 87, 168-175), so +# it stays below that start time. The other flavors use the build time in +# seconds (build.gradle:42), above it for every build since 2021. The launcher +# writes the code to retroarch.cfg (UserPreferences.java:150), which +# RetroArch keeps (configuration.c:2623). +_ANDROID_PLAY_VERSION_CEILING = 1609632000 + + +@contextlib.contextmanager +def _refusals_expected() -> Iterator[None]: + """Probes whose refusal is the answer, not a folder to report: another + app's private data on Android, which any app may test for existence and + none may enter, has a line of its own (android_unreachable_folders).""" + outer = getattr(_SETUP_SEARCH, "active", False) + _SETUP_SEARCH.active = False + try: + yield + finally: + _SETUP_SEARCH.active = outer + + +def _android_play_build(package: str, storage: Path, cfgs: tuple[Path, ...]) -> bool | None: + """True for the Google Play build of this package, False for the + retroarch.com one, None when nothing it wrote tells them apart. + + The version code in its config decides. Without a readable config, the + folder each build writes does: the Google Play build never asks for + shared storage (MainMenuActivity.java:199-202), and only it builds its + defaults under Android/data//files/RetroArch. + """ + if package not in _ANDROID_RETROARCH_PLAY_IDS: + return False + for cfg in cfgs: + code = _retroarch_cfg_value(cfg, "bundle_assets_extract_version_current") + if code and code.isdigit() and int(code) > 0: + return int(code) < _ANDROID_PLAY_VERSION_CEILING + if _is_dir(storage / "Android" / "data" / package / "files" / "RetroArch"): + return True + if _is_dir(storage / "RetroArch"): + return False + return None + + +def _android_writable(folder: Path) -> bool: + """Whether this shell can create folder: its nearest existing parent is + writable. Android 11 and later keep Android/data/ of other apps + from Termux.""" + for parent in (folder, *folder.parents): + if _exists(parent): + return _is_dir(parent) and os.access(parent, os.W_OK) + return False + + +def _android_out_of_reach(name: str, folder: Path, what: str) -> str: + """The line said for an emulator whose BIOS folder this shell cannot write.""" + return (f"{name} is installed, but this shell cannot write its BIOS folder " + f"{folder} without root: {what} are not copied there.") + + +@_refusals_expected() +def _android_retroarch_builds() -> list[tuple[Path | None, str]]: + """Each installed RetroArch build: its system folder when this shell can + write it, else None and the line that says why. + + RetroArch v1.22.2: the launcher picks retroarch.cfg in the app external + files directory, else in the internal one + (pkg/android/phoenix-common/src/com/retroarch/browser/preferences/util/ + UserPreferences.java:36-89), and passes it as CONFIGFILE + (MainMenuActivity.java:178, read at frontend/drivers/platform_unix.c: + 1428-1444). A system_directory left at default resolves against + /RetroArch/system (platform_unix.c:1670-1697), storage being + what the launcher passes as SDCARD: Android/data//files for the + Google Play build, the shared storage root for the others. + """ + storage = _android_storage_root() + builds: list[tuple[Path | None, str]] = [] + for package in ANDROID_RETROARCH_PACKAGES: + external = storage / "Android" / "data" / package / "files" + if not _exists(ANDROID_APP_DATA / package) and not _exists(external): + continue + cfgs = (external / "retroarch.cfg", + ANDROID_APP_DATA / package / "files" / "retroarch.cfg") + play = _android_play_build(package, storage, cfgs) + play_root, shared_root = external / "RetroArch", storage / "RetroArch" + named = next(filter(None, (_retroarch_cfg_value(cfg, "system_directory") + for cfg in cfgs)), "default") + if play is None and named == "default": + builds.append((None, + f"RetroArch ({package}) is installed, but nothing it has written tells " + f"which build it is: the Google Play build reads {play_root / 'system'}, " + f"the retroarch.com build reads {shared_root / 'system'}. " + "Name the folder with --dest.")) + continue + root = play_root if play else shared_root + folder = next(filter(None, (_parse_retroarch_system_dir(cfg, root) for cfg in cfgs)), + root / "system") + private = (storage / "Android" / "data", ANDROID_APP_DATA) + if any(folder == base or base in folder.parents for base in private) \ + and not _android_writable(folder): + build = "Google Play build" if play else "retroarch.com build" + builds.append((None, _android_out_of_reach( + f"RetroArch ({build}, {package})", folder, "BIOS files"))) + continue + builds.append((folder, "")) + return builds + + +def _detect_android() -> list[tuple[str, Path]]: + """Find the RetroArch system directory of each installed build on + Android, as _android_retroarch_builds() resolves it (RetroArch v1.22.2, + platform_unix.c:1670-1697). + + With no package seen, /RetroArch is the folder of a + retroarch.com build whose private data this shell cannot see. + """ + found: list[tuple[str, Path]] = [] + builds = _android_retroarch_builds() + for folder, _line in builds: + if folder is not None and ("retroarch", folder) not in found: + found.append(("retroarch", folder)) + default_root = _android_storage_root() / "RetroArch" + if not builds and _exists(default_root): + found.append(("retroarch", default_root / "system")) + return found + + +# Android emulators that keep their BIOS outside RetroArch's folder: +# (name, package, folder, files read there). DraStic keeps it in its private +# data (GammaOS Next 14 bb28e71d, gammaos/setup.sh:345-363 extracts it to +# /data/data/com.dsemu.drastic/files/DraStic/system), which no other app +# writes without root. Flycast reads /data/ (flycast a9bd1c74, +# shell/android-studio/flycast/src/main/jni/src/Android.cpp:143-159), its +# home being Android/data/com.flycast.emulator/files, which Android 11 and +# later keep from other apps. +_ANDROID_APP_FOLDERS = ( + ("DraStic", "com.dsemu.drastic", "/data/data/com.dsemu.drastic/files/DraStic/system", + ("nds_bios_arm7.bin", "nds_bios_arm9.bin", "nds_firmware.bin")), + ("Flycast", "com.flycast.emulator", + "$STORAGE/Android/data/com.flycast.emulator/files/data", + ("dc_boot.bin", "dc_nvmem.bin")), +) + + +@_refusals_expected() +def android_unreachable_folders() -> list[str]: + """A line for each Android emulator installed here whose BIOS folder + this shell cannot write, said instead of skipping it in silence. A + RetroArch build whose folder is out of reach, or whose build cannot be + told, is among them. + + An app's private folder can be tested for existence by any app, so the + emulator is known to be installed even where its folder is out of reach. + """ + lines = [line for folder, line in _android_retroarch_builds() if folder is None] + storage = str(_android_storage_root()) + for name, package, folder, files in _ANDROID_APP_FOLDERS: + target = Path(folder.replace("$STORAGE", storage, 1)) + if folder.startswith("/data/data/"): + target = ANDROID_APP_DATA / Path(folder).relative_to("/data/data") + if not _exists(ANDROID_APP_DATA / package) and not _exists(target): + continue + if _is_dir(target) and os.access(target, os.W_OK): + continue + lines.append(_android_out_of_reach(name, target, ", ".join(files))) + return lines + + +# --- installer/detect_launchbox.py ------------------------------------------- + +def _lnk_target(lnk_path: Path, exe_name: str) -> Path | None: + """Read the target path of a Windows shortcut. + + Shortcuts embed the target as a plain local path. Scanning for it avoids + parsing the whole .lnk structure for the one field that matters here. + """ + try: + if lnk_path.stat().st_size > 64 * 1024: + return None + blob = lnk_path.read_bytes() + except OSError: + return None + pattern = re.compile( + rb"[A-Za-z]:\\[ -~]{0,260}?" + re.escape(exe_name.encode()), re.IGNORECASE + ) + match = pattern.search(blob) + if not match: + return None + return Path(match.group().decode("ascii", "replace").replace("\\", "/")) + + +def launchbox_root(os_type: str) -> Path | None: + """Locate the LaunchBox installation directory. + + LaunchBox installs wherever the user points its installer and writes no + uninstall registry key, so the Start menu shortcut is the only record of + that choice. Everything else falls back to the default location. + """ + if os_type not in ("windows", "wsl"): + return None + candidates: list[Path] = [] + appdata = os.environ.get("APPDATA", "") + if appdata: + lnk = ( + Path(appdata) + / "Microsoft" + / "Windows" + / "Start Menu" + / "Programs" + / "LaunchBox" + / "LaunchBox.lnk" + ) + if _exists(lnk): + target = _lnk_target(lnk, "LaunchBox.exe") + if target: + # The shortcut points at Core/LaunchBox.exe + candidates.append(target.parent.parent) + candidates.append(target.parent) + userprofile = os.environ.get("USERPROFILE", "") + if userprofile: + candidates.append(Path(userprofile) / "LaunchBox") + for root in candidates: + if _exists(root / "Data" / "Emulators.xml"): + return root + return None + + +def launchbox_emulators(emulators_xml: Path) -> dict[str, Path]: + """Map each emulator LaunchBox knows about to its installation directory. + + LaunchBox stores its emulator list in Data/Emulators.xml. ApplicationPath + is either absolute or relative to the LaunchBox root directory. Keys are + the lowercase executable names. + """ + found: dict[str, Path] = {} + if not _exists(emulators_xml): + return found + try: + if emulators_xml.stat().st_size > 10 * 1024 * 1024: + return found + raw = emulators_xml.read_text(encoding="utf-8", errors="replace") + # ElementTree expands internal entities, and LaunchBox writes no doctype + if " Path | None: + """Resolve the system dir of a RetroArch referenced by LaunchBox. + + Mirrors the plugin's UpdateSystemPath: read system_directory from the + retroarch.cfg sitting next to the executable, else assume system/. + """ + emu_dir = launchbox_emulators(emulators_xml).get("retroarch.exe") + if emu_dir is None: + return None + system_dir = _parse_retroarch_system_dir(emu_dir / "retroarch.cfg", emu_dir) + return system_dir or emu_dir / "system" + + +def _pcsx2_bios_dir(emu_dir: Path) -> Path: + """Resolve the BIOS folder of a PCSX2 installed under LaunchBox. + + EmuFolders (pcsx2/Pcsx2Config.cpp) enters portable mode when portable.ini + or portable.txt sits next to the executable, and then takes the data root + from the contents of portable.txt, relative to the executable. Otherwise + the data root is Documents/PCSX2. Bios defaults to "bios" below it and the + Bios key of PCSX2.ini overrides that. + """ + documents = Path(os.environ.get("USERPROFILE", str(Path.home()))) / "Documents" + portable_txt = emu_dir / "portable.txt" + portable = _exists(emu_dir / "portable.ini") or _exists(portable_txt) + if portable: + subpath = "" + with contextlib.suppress(OSError): + subpath = portable_txt.read_text( + encoding="utf-8", errors="replace" + ).strip() + data_root = emu_dir / subpath if subpath else emu_dir + else: + data_root = documents / "PCSX2" + ini = data_root / "inis" / "PCSX2.ini" + try: + for line in ini.read_text(encoding="utf-8", errors="replace").splitlines(): + if line.startswith("Bios = "): + value = line[len("Bios = "):].strip() + candidate = Path(value) + return candidate if candidate.is_absolute() else data_root / value + except OSError: + pass + return data_root / "bios" + + +def _xemu_bios_dir(emu_dir: Path) -> Path: + """Resolve the BIOS folder of a xemu managed by LaunchBox. + + Follows the plugin: xemu.toml next to the executable else the roaming + copy, with bootrom_path and flashrom_path naming a file whose directory + holds the images. Both default to bios/ under the executable. + """ + appdata = os.environ.get("APPDATA", "") + toml = emu_dir / "xemu.toml" + if not _exists(toml) and appdata: + toml = Path(appdata) / "xemu" / "xemu" / "xemu.toml" + if _exists(toml): + try: + for line in toml.read_text(encoding="utf-8", errors="replace").splitlines(): + if line.startswith(("bootrom_path", "flashrom_path")): + parts = line.split("'") + if len(parts) > 1 and _exists(Path(parts[1])): + return Path(parts[1]).parent + except OSError: + pass + return emu_dir / "bios" + + +def launchbox_bios_dirs(root: Path) -> dict[str, Path]: + """Map emulator ids to the BIOS directory LaunchBox expects for them. + + Only emulators whose destination LaunchBox itself computes are listed. + The rest keep the default locations declared in the manifest. + """ + emulators = launchbox_emulators(root / "Data" / "Emulators.xml") + dirs: dict[str, Path] = {} + emu_dir = emulators.get("pcsx2.exe") + if emu_dir: + dirs["pcsx2"] = _pcsx2_bios_dir(emu_dir) + emu_dir = emulators.get("xemu.exe") + if emu_dir: + dirs["xemu"] = _xemu_bios_dir(emu_dir) + emu_dir = emulators.get("dolphin.exe") + if emu_dir and _exists(emu_dir / "portable.txt"): + # portable.txt beside the executable moves the user directory to + # User (SetUserDirectory in Source/Core/UICommon/UICommon.cpp, + # PORTABLE_USER_DIR in Source/Core/Common/CommonPaths.h) + dirs["dolphin"] = emu_dir / "User" + return dirs + + # --- installer/paths.py ------------------------------------------------------ def _path_characters(value: object, field: str, colons: bool = True) -> str: @@ -5221,16 +5600,6 @@ def _os_name() -> str: # --- installer/detect_frontends.py ------------------------------------------- -# The three RetroArch packages published for Android, newest ABI first. -ANDROID_RETROARCH_PACKAGES = ( - "com.retroarch.aarch64", - "com.retroarch", - "com.retroarch.ra32", -) -# Where Android keeps each app's private data. -ANDROID_APP_DATA = Path("/data/data") - - def _steam_libraries() -> list[Path]: """Every Steam library, the default one first. @@ -5346,371 +5715,6 @@ def _retroarch_appimage_dirs(home: Path) -> list[Path]: return dirs -def _android_storage_root() -> Path: - """Shared storage root, the parent RetroArch builds its defaults from.""" - value = os.environ.get("EXTERNAL_STORAGE", "").strip() - return Path(value) if value else Path("/storage/emulated/0") - - -# Where each RetroArch package keeps its folders, RetroArch v1.22.2 -# (pkg/android/phoenix/build.gradle:46-95). com.retroarch and -# com.retroarch.aarch64 are each published twice under one id: by -# retroarch.com (normal, aarch64) and on Google Play (playStoreNormal, -# playStorePlus). com.retroarch.ra32 has no Google Play flavor. The Google -# Play build hands RetroArch Android/data//files as the storage its -# defaults are built from, the other builds the shared storage root -# (MainMenuActivity.java:182-183). -_ANDROID_RETROARCH_PLAY_IDS = ("com.retroarch", "com.retroarch.aarch64") -# A Google Play versionCode is the manifest's 1597175267 (AndroidManifest.xml:5) -# plus one per half week since 1609632000 (build.gradle:76, 87, 168-175), so -# it stays below that start time. The other flavors use the build time in -# seconds (build.gradle:42), above it for every build since 2021. The launcher -# writes the code to retroarch.cfg (UserPreferences.java:150), which -# RetroArch keeps (configuration.c:2623). -_ANDROID_PLAY_VERSION_CEILING = 1609632000 - - -@contextlib.contextmanager -def _refusals_expected() -> Iterator[None]: - """Probes whose refusal is the answer, not a folder to report: another - app's private data on Android, which any app may test for existence and - none may enter, has a line of its own (android_unreachable_folders).""" - outer = getattr(_SETUP_SEARCH, "active", False) - _SETUP_SEARCH.active = False - try: - yield - finally: - _SETUP_SEARCH.active = outer - - -def _android_play_build(package: str, storage: Path, cfgs: tuple[Path, ...]) -> bool | None: - """True for the Google Play build of this package, False for the - retroarch.com one, None when nothing it wrote tells them apart. - - The version code in its config decides. Without a readable config, the - folder each build writes does: the Google Play build never asks for - shared storage (MainMenuActivity.java:199-202), and only it builds its - defaults under Android/data//files/RetroArch. - """ - if package not in _ANDROID_RETROARCH_PLAY_IDS: - return False - for cfg in cfgs: - code = _retroarch_cfg_value(cfg, "bundle_assets_extract_version_current") - if code and code.isdigit() and int(code) > 0: - return int(code) < _ANDROID_PLAY_VERSION_CEILING - if _is_dir(storage / "Android" / "data" / package / "files" / "RetroArch"): - return True - if _is_dir(storage / "RetroArch"): - return False - return None - - -def _android_writable(folder: Path) -> bool: - """Whether this shell can create folder: its nearest existing parent is - writable. Android 11 and later keep Android/data/ of other apps - from Termux.""" - for parent in (folder, *folder.parents): - if _exists(parent): - return _is_dir(parent) and os.access(parent, os.W_OK) - return False - - -def _android_out_of_reach(name: str, folder: Path, what: str) -> str: - """The line said for an emulator whose BIOS folder this shell cannot write.""" - return (f"{name} is installed, but this shell cannot write its BIOS folder " - f"{folder} without root: {what} are not copied there.") - - -@_refusals_expected() -def _android_retroarch_builds() -> list[tuple[Path | None, str]]: - """Each installed RetroArch build: its system folder when this shell can - write it, else None and the line that says why. - - RetroArch v1.22.2: the launcher picks retroarch.cfg in the app external - files directory, else in the internal one - (pkg/android/phoenix-common/src/com/retroarch/browser/preferences/util/ - UserPreferences.java:36-89), and passes it as CONFIGFILE - (MainMenuActivity.java:178, read at frontend/drivers/platform_unix.c: - 1428-1444). A system_directory left at default resolves against - /RetroArch/system (platform_unix.c:1670-1697), storage being - what the launcher passes as SDCARD: Android/data//files for the - Google Play build, the shared storage root for the others. - """ - storage = _android_storage_root() - builds: list[tuple[Path | None, str]] = [] - for package in ANDROID_RETROARCH_PACKAGES: - external = storage / "Android" / "data" / package / "files" - if not _exists(ANDROID_APP_DATA / package) and not _exists(external): - continue - cfgs = (external / "retroarch.cfg", - ANDROID_APP_DATA / package / "files" / "retroarch.cfg") - play = _android_play_build(package, storage, cfgs) - play_root, shared_root = external / "RetroArch", storage / "RetroArch" - named = next(filter(None, (_retroarch_cfg_value(cfg, "system_directory") - for cfg in cfgs)), "default") - if play is None and named == "default": - builds.append((None, - f"RetroArch ({package}) is installed, but nothing it has written tells " - f"which build it is: the Google Play build reads {play_root / 'system'}, " - f"the retroarch.com build reads {shared_root / 'system'}. " - "Name the folder with --dest.")) - continue - root = play_root if play else shared_root - folder = next(filter(None, (_parse_retroarch_system_dir(cfg, root) for cfg in cfgs)), - root / "system") - private = (storage / "Android" / "data", ANDROID_APP_DATA) - if any(folder == base or base in folder.parents for base in private) \ - and not _android_writable(folder): - build = "Google Play build" if play else "retroarch.com build" - builds.append((None, _android_out_of_reach( - f"RetroArch ({build}, {package})", folder, "BIOS files"))) - continue - builds.append((folder, "")) - return builds - - -def _detect_android() -> list[tuple[str, Path]]: - """Find the RetroArch system directory of each installed build on - Android, as _android_retroarch_builds() resolves it (RetroArch v1.22.2, - platform_unix.c:1670-1697). - - With no package seen, /RetroArch is the folder of a - retroarch.com build whose private data this shell cannot see. - """ - found: list[tuple[str, Path]] = [] - builds = _android_retroarch_builds() - for folder, _line in builds: - if folder is not None and ("retroarch", folder) not in found: - found.append(("retroarch", folder)) - default_root = _android_storage_root() / "RetroArch" - if not builds and _exists(default_root): - found.append(("retroarch", default_root / "system")) - return found - - -# Android emulators that keep their BIOS outside RetroArch's folder: -# (name, package, folder, files read there). DraStic keeps it in its private -# data (GammaOS Next 14 bb28e71d, gammaos/setup.sh:345-363 extracts it to -# /data/data/com.dsemu.drastic/files/DraStic/system), which no other app -# writes without root. Flycast reads /data/ (flycast a9bd1c74, -# shell/android-studio/flycast/src/main/jni/src/Android.cpp:143-159), its -# home being Android/data/com.flycast.emulator/files, which Android 11 and -# later keep from other apps. -_ANDROID_APP_FOLDERS = ( - ("DraStic", "com.dsemu.drastic", "/data/data/com.dsemu.drastic/files/DraStic/system", - ("nds_bios_arm7.bin", "nds_bios_arm9.bin", "nds_firmware.bin")), - ("Flycast", "com.flycast.emulator", - "$STORAGE/Android/data/com.flycast.emulator/files/data", - ("dc_boot.bin", "dc_nvmem.bin")), -) - - -@_refusals_expected() -def android_unreachable_folders() -> list[str]: - """A line for each Android emulator installed here whose BIOS folder - this shell cannot write, said instead of skipping it in silence. A - RetroArch build whose folder is out of reach, or whose build cannot be - told, is among them. - - An app's private folder can be tested for existence by any app, so the - emulator is known to be installed even where its folder is out of reach. - """ - lines = [line for folder, line in _android_retroarch_builds() if folder is None] - storage = str(_android_storage_root()) - for name, package, folder, files in _ANDROID_APP_FOLDERS: - target = Path(folder.replace("$STORAGE", storage, 1)) - if folder.startswith("/data/data/"): - target = ANDROID_APP_DATA / Path(folder).relative_to("/data/data") - if not _exists(ANDROID_APP_DATA / package) and not _exists(target): - continue - if _is_dir(target) and os.access(target, os.W_OK): - continue - lines.append(_android_out_of_reach(name, target, ", ".join(files))) - return lines - - -def _lnk_target(lnk_path: Path, exe_name: str) -> Path | None: - """Read the target path of a Windows shortcut. - - Shortcuts embed the target as a plain local path. Scanning for it avoids - parsing the whole .lnk structure for the one field that matters here. - """ - try: - if lnk_path.stat().st_size > 64 * 1024: - return None - blob = lnk_path.read_bytes() - except OSError: - return None - pattern = re.compile( - rb"[A-Za-z]:\\[ -~]{0,260}?" + re.escape(exe_name.encode()), re.IGNORECASE - ) - match = pattern.search(blob) - if not match: - return None - return Path(match.group().decode("ascii", "replace").replace("\\", "/")) - - -def launchbox_root(os_type: str) -> Path | None: - """Locate the LaunchBox installation directory. - - LaunchBox installs wherever the user points its installer and writes no - uninstall registry key, so the Start menu shortcut is the only record of - that choice. Everything else falls back to the default location. - """ - if os_type not in ("windows", "wsl"): - return None - candidates: list[Path] = [] - appdata = os.environ.get("APPDATA", "") - if appdata: - lnk = ( - Path(appdata) - / "Microsoft" - / "Windows" - / "Start Menu" - / "Programs" - / "LaunchBox" - / "LaunchBox.lnk" - ) - if _exists(lnk): - target = _lnk_target(lnk, "LaunchBox.exe") - if target: - # The shortcut points at Core/LaunchBox.exe - candidates.append(target.parent.parent) - candidates.append(target.parent) - userprofile = os.environ.get("USERPROFILE", "") - if userprofile: - candidates.append(Path(userprofile) / "LaunchBox") - for root in candidates: - if _exists(root / "Data" / "Emulators.xml"): - return root - return None - - -def launchbox_emulators(emulators_xml: Path) -> dict[str, Path]: - """Map each emulator LaunchBox knows about to its installation directory. - - LaunchBox stores its emulator list in Data/Emulators.xml. ApplicationPath - is either absolute or relative to the LaunchBox root directory. Keys are - the lowercase executable names. - """ - found: dict[str, Path] = {} - if not _exists(emulators_xml): - return found - try: - if emulators_xml.stat().st_size > 10 * 1024 * 1024: - return found - raw = emulators_xml.read_text(encoding="utf-8", errors="replace") - # ElementTree expands internal entities, and LaunchBox writes no doctype - if " Path | None: - """Resolve the system dir of a RetroArch referenced by LaunchBox. - - Mirrors the plugin's UpdateSystemPath: read system_directory from the - retroarch.cfg sitting next to the executable, else assume system/. - """ - emu_dir = launchbox_emulators(emulators_xml).get("retroarch.exe") - if emu_dir is None: - return None - system_dir = _parse_retroarch_system_dir(emu_dir / "retroarch.cfg", emu_dir) - return system_dir or emu_dir / "system" - - -def _pcsx2_bios_dir(emu_dir: Path) -> Path: - """Resolve the BIOS folder of a PCSX2 installed under LaunchBox. - - EmuFolders (pcsx2/Pcsx2Config.cpp) enters portable mode when portable.ini - or portable.txt sits next to the executable, and then takes the data root - from the contents of portable.txt, relative to the executable. Otherwise - the data root is Documents/PCSX2. Bios defaults to "bios" below it and the - Bios key of PCSX2.ini overrides that. - """ - documents = Path(os.environ.get("USERPROFILE", str(Path.home()))) / "Documents" - portable_txt = emu_dir / "portable.txt" - portable = _exists(emu_dir / "portable.ini") or _exists(portable_txt) - if portable: - subpath = "" - with contextlib.suppress(OSError): - subpath = portable_txt.read_text( - encoding="utf-8", errors="replace" - ).strip() - data_root = emu_dir / subpath if subpath else emu_dir - else: - data_root = documents / "PCSX2" - ini = data_root / "inis" / "PCSX2.ini" - try: - for line in ini.read_text(encoding="utf-8", errors="replace").splitlines(): - if line.startswith("Bios = "): - value = line[len("Bios = "):].strip() - candidate = Path(value) - return candidate if candidate.is_absolute() else data_root / value - except OSError: - pass - return data_root / "bios" - - -def _xemu_bios_dir(emu_dir: Path) -> Path: - """Resolve the BIOS folder of a xemu managed by LaunchBox. - - Follows the plugin: xemu.toml next to the executable else the roaming - copy, with bootrom_path and flashrom_path naming a file whose directory - holds the images. Both default to bios/ under the executable. - """ - appdata = os.environ.get("APPDATA", "") - toml = emu_dir / "xemu.toml" - if not _exists(toml) and appdata: - toml = Path(appdata) / "xemu" / "xemu" / "xemu.toml" - if _exists(toml): - try: - for line in toml.read_text(encoding="utf-8", errors="replace").splitlines(): - if line.startswith(("bootrom_path", "flashrom_path")): - parts = line.split("'") - if len(parts) > 1 and _exists(Path(parts[1])): - return Path(parts[1]).parent - except OSError: - pass - return emu_dir / "bios" - - -def launchbox_bios_dirs(root: Path) -> dict[str, Path]: - """Map emulator ids to the BIOS directory LaunchBox expects for them. - - Only emulators whose destination LaunchBox itself computes are listed. - The rest keep the default locations declared in the manifest. - """ - emulators = launchbox_emulators(root / "Data" / "Emulators.xml") - dirs: dict[str, Path] = {} - emu_dir = emulators.get("pcsx2.exe") - if emu_dir: - dirs["pcsx2"] = _pcsx2_bios_dir(emu_dir) - emu_dir = emulators.get("xemu.exe") - if emu_dir: - dirs["xemu"] = _xemu_bios_dir(emu_dir) - emu_dir = emulators.get("dolphin.exe") - if emu_dir and _exists(emu_dir / "portable.txt"): - # portable.txt beside the executable moves the user directory to - # User (SetUserDirectory in Source/Core/UICommon/UICommon.cpp, - # PORTABLE_USER_DIR in Source/Core/Common/CommonPaths.h) - dirs["dolphin"] = emu_dir / "User" - return dirs - - # The platforms whose configuration names a folder with a control character. _UNNAMEABLE: list[str] = [] diff --git a/install.sh b/install.sh index 1ff49dfe0..d2025533b 100755 --- a/install.sh +++ b/install.sh @@ -23,7 +23,7 @@ DEFAULT_INSTALL_URL="https://raw.githubusercontent.com/Abdess/retrobios/main/ins # curl or wget stop on a cut transfer before the hash is read: the site's # build rewrites this line there (scripts/sitebootstrap.py). MISMATCH_ADVICE="The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that." -DEFAULT_INSTALL_SHA256="5d583c967fc8e68c3f3dcc5000a3a882476d55e548c69adc952b936f92d85bc2" +DEFAULT_INSTALL_SHA256="1cd472779f9a83fc33c10a464275c6defa1d7995d12091267c4c815384147909" # The pin above refuses any changed byte: this cap only stops a body that # cannot be the installer (a sign-in portal's page) before it is hashed. MAX_INSTALLER_BYTES=8388608 diff --git a/install/launchers/index.json b/install/launchers/index.json index cb79ce57d..75a611ff6 100644 --- a/install/launchers/index.json +++ b/install/launchers/index.json @@ -27,8 +27,8 @@ { "dest": "roms/ports/retrobios/install.py", "repo_path": "install.py", - "size": 1503021, - "sha256": "5d583c967fc8e68c3f3dcc5000a3a882476d55e548c69adc952b936f92d85bc2", + "size": 1503183, + "sha256": "1cd472779f9a83fc33c10a464275c6defa1d7995d12091267c4c815384147909", "executable": false }, { @@ -71,8 +71,8 @@ "muos": { "archive": { "dest": "ARCHIVE/RetroBIOS.muxapp", - "size": 1556646, - "sha256": "3726d35005eb53ad1d60c73891300bc37932ca62dd65ad5b52eae9bfc0e89cd3" + "size": 1556808, + "sha256": "9a781fdd3c8023580e7e37a789e64fe81d10149543a65419bd8213b6c4faf094" }, "members": [ { @@ -92,8 +92,8 @@ { "name": "RetroBIOS/install.py", "repo_path": "install.py", - "size": 1503021, - "sha256": "5d583c967fc8e68c3f3dcc5000a3a882476d55e548c69adc952b936f92d85bc2", + "size": 1503183, + "sha256": "1cd472779f9a83fc33c10a464275c6defa1d7995d12091267c4c815384147909", "executable": false }, { @@ -166,8 +166,8 @@ { "dest": ".config/modules/retrobios/install.py", "repo_path": "install.py", - "size": 1503021, - "sha256": "5d583c967fc8e68c3f3dcc5000a3a882476d55e548c69adc952b936f92d85bc2", + "size": 1503183, + "sha256": "1cd472779f9a83fc33c10a464275c6defa1d7995d12091267c4c815384147909", "executable": false }, { diff --git a/installer/detect_android.py b/installer/detect_android.py new file mode 100644 index 000000000..f63489d83 --- /dev/null +++ b/installer/detect_android.py @@ -0,0 +1,204 @@ +"""RetroArch builds found on Android, and the app folders Android keeps out of reach.""" + +from __future__ import annotations + +import contextlib +import os +from collections.abc import Iterator +from pathlib import Path + +from installer.config_values import _parse_retroarch_system_dir, _retroarch_cfg_value +from installer.host_fs import _SETUP_SEARCH, _exists, _is_dir + + +# The three RetroArch packages published for Android, newest ABI first. +ANDROID_RETROARCH_PACKAGES = ( + "com.retroarch.aarch64", + "com.retroarch", + "com.retroarch.ra32", +) +# Where Android keeps each app's private data. +ANDROID_APP_DATA = Path("/data/data") + + +def _android_storage_root() -> Path: + """Shared storage root, the parent RetroArch builds its defaults from.""" + value = os.environ.get("EXTERNAL_STORAGE", "").strip() + return Path(value) if value else Path("/storage/emulated/0") + + +# Where each RetroArch package keeps its folders, RetroArch v1.22.2 +# (pkg/android/phoenix/build.gradle:46-95). com.retroarch and +# com.retroarch.aarch64 are each published twice under one id: by +# retroarch.com (normal, aarch64) and on Google Play (playStoreNormal, +# playStorePlus). com.retroarch.ra32 has no Google Play flavor. The Google +# Play build hands RetroArch Android/data//files as the storage its +# defaults are built from, the other builds the shared storage root +# (MainMenuActivity.java:182-183). +_ANDROID_RETROARCH_PLAY_IDS = ("com.retroarch", "com.retroarch.aarch64") +# A Google Play versionCode is the manifest's 1597175267 (AndroidManifest.xml:5) +# plus one per half week since 1609632000 (build.gradle:76, 87, 168-175), so +# it stays below that start time. The other flavors use the build time in +# seconds (build.gradle:42), above it for every build since 2021. The launcher +# writes the code to retroarch.cfg (UserPreferences.java:150), which +# RetroArch keeps (configuration.c:2623). +_ANDROID_PLAY_VERSION_CEILING = 1609632000 + + +@contextlib.contextmanager +def _refusals_expected() -> Iterator[None]: + """Probes whose refusal is the answer, not a folder to report: another + app's private data on Android, which any app may test for existence and + none may enter, has a line of its own (android_unreachable_folders).""" + outer = getattr(_SETUP_SEARCH, "active", False) + _SETUP_SEARCH.active = False + try: + yield + finally: + _SETUP_SEARCH.active = outer + + +def _android_play_build(package: str, storage: Path, cfgs: tuple[Path, ...]) -> bool | None: + """True for the Google Play build of this package, False for the + retroarch.com one, None when nothing it wrote tells them apart. + + The version code in its config decides. Without a readable config, the + folder each build writes does: the Google Play build never asks for + shared storage (MainMenuActivity.java:199-202), and only it builds its + defaults under Android/data//files/RetroArch. + """ + if package not in _ANDROID_RETROARCH_PLAY_IDS: + return False + for cfg in cfgs: + code = _retroarch_cfg_value(cfg, "bundle_assets_extract_version_current") + if code and code.isdigit() and int(code) > 0: + return int(code) < _ANDROID_PLAY_VERSION_CEILING + if _is_dir(storage / "Android" / "data" / package / "files" / "RetroArch"): + return True + if _is_dir(storage / "RetroArch"): + return False + return None + + +def _android_writable(folder: Path) -> bool: + """Whether this shell can create folder: its nearest existing parent is + writable. Android 11 and later keep Android/data/ of other apps + from Termux.""" + for parent in (folder, *folder.parents): + if _exists(parent): + return _is_dir(parent) and os.access(parent, os.W_OK) + return False + + +def _android_out_of_reach(name: str, folder: Path, what: str) -> str: + """The line said for an emulator whose BIOS folder this shell cannot write.""" + return (f"{name} is installed, but this shell cannot write its BIOS folder " + f"{folder} without root: {what} are not copied there.") + + +@_refusals_expected() +def _android_retroarch_builds() -> list[tuple[Path | None, str]]: + """Each installed RetroArch build: its system folder when this shell can + write it, else None and the line that says why. + + RetroArch v1.22.2: the launcher picks retroarch.cfg in the app external + files directory, else in the internal one + (pkg/android/phoenix-common/src/com/retroarch/browser/preferences/util/ + UserPreferences.java:36-89), and passes it as CONFIGFILE + (MainMenuActivity.java:178, read at frontend/drivers/platform_unix.c: + 1428-1444). A system_directory left at default resolves against + /RetroArch/system (platform_unix.c:1670-1697), storage being + what the launcher passes as SDCARD: Android/data//files for the + Google Play build, the shared storage root for the others. + """ + storage = _android_storage_root() + builds: list[tuple[Path | None, str]] = [] + for package in ANDROID_RETROARCH_PACKAGES: + external = storage / "Android" / "data" / package / "files" + if not _exists(ANDROID_APP_DATA / package) and not _exists(external): + continue + cfgs = (external / "retroarch.cfg", + ANDROID_APP_DATA / package / "files" / "retroarch.cfg") + play = _android_play_build(package, storage, cfgs) + play_root, shared_root = external / "RetroArch", storage / "RetroArch" + named = next(filter(None, (_retroarch_cfg_value(cfg, "system_directory") + for cfg in cfgs)), "default") + if play is None and named == "default": + builds.append((None, + f"RetroArch ({package}) is installed, but nothing it has written tells " + f"which build it is: the Google Play build reads {play_root / 'system'}, " + f"the retroarch.com build reads {shared_root / 'system'}. " + "Name the folder with --dest.")) + continue + root = play_root if play else shared_root + folder = next(filter(None, (_parse_retroarch_system_dir(cfg, root) for cfg in cfgs)), + root / "system") + private = (storage / "Android" / "data", ANDROID_APP_DATA) + if any(folder == base or base in folder.parents for base in private) \ + and not _android_writable(folder): + build = "Google Play build" if play else "retroarch.com build" + builds.append((None, _android_out_of_reach( + f"RetroArch ({build}, {package})", folder, "BIOS files"))) + continue + builds.append((folder, "")) + return builds + + +def _detect_android() -> list[tuple[str, Path]]: + """Find the RetroArch system directory of each installed build on + Android, as _android_retroarch_builds() resolves it (RetroArch v1.22.2, + platform_unix.c:1670-1697). + + With no package seen, /RetroArch is the folder of a + retroarch.com build whose private data this shell cannot see. + """ + found: list[tuple[str, Path]] = [] + builds = _android_retroarch_builds() + for folder, _line in builds: + if folder is not None and ("retroarch", folder) not in found: + found.append(("retroarch", folder)) + default_root = _android_storage_root() / "RetroArch" + if not builds and _exists(default_root): + found.append(("retroarch", default_root / "system")) + return found + + +# Android emulators that keep their BIOS outside RetroArch's folder: +# (name, package, folder, files read there). DraStic keeps it in its private +# data (GammaOS Next 14 bb28e71d, gammaos/setup.sh:345-363 extracts it to +# /data/data/com.dsemu.drastic/files/DraStic/system), which no other app +# writes without root. Flycast reads /data/ (flycast a9bd1c74, +# shell/android-studio/flycast/src/main/jni/src/Android.cpp:143-159), its +# home being Android/data/com.flycast.emulator/files, which Android 11 and +# later keep from other apps. +_ANDROID_APP_FOLDERS = ( + ("DraStic", "com.dsemu.drastic", "/data/data/com.dsemu.drastic/files/DraStic/system", + ("nds_bios_arm7.bin", "nds_bios_arm9.bin", "nds_firmware.bin")), + ("Flycast", "com.flycast.emulator", + "$STORAGE/Android/data/com.flycast.emulator/files/data", + ("dc_boot.bin", "dc_nvmem.bin")), +) + + +@_refusals_expected() +def android_unreachable_folders() -> list[str]: + """A line for each Android emulator installed here whose BIOS folder + this shell cannot write, said instead of skipping it in silence. A + RetroArch build whose folder is out of reach, or whose build cannot be + told, is among them. + + An app's private folder can be tested for existence by any app, so the + emulator is known to be installed even where its folder is out of reach. + """ + lines = [line for folder, line in _android_retroarch_builds() if folder is None] + storage = str(_android_storage_root()) + for name, package, folder, files in _ANDROID_APP_FOLDERS: + target = Path(folder.replace("$STORAGE", storage, 1)) + if folder.startswith("/data/data/"): + target = ANDROID_APP_DATA / Path(folder).relative_to("/data/data") + if not _exists(ANDROID_APP_DATA / package) and not _exists(target): + continue + if _is_dir(target) and os.access(target, os.W_OK): + continue + lines.append(_android_out_of_reach(name, target, ", ".join(files))) + return lines diff --git a/installer/detect_frontends.py b/installer/detect_frontends.py index 64648b9d0..420872cbb 100644 --- a/installer/detect_frontends.py +++ b/installer/detect_frontends.py @@ -1,12 +1,10 @@ -"""Frontends and emulators found on this machine, Android included.""" +"""Frontends and emulators found on this machine, by path, executable, registry and setup.""" from __future__ import annotations -import contextlib import functools import os import re -import xml.etree.ElementTree as ET -from collections.abc import Callable, Iterator +from collections.abc import Callable from pathlib import Path from installer.config_values import ( @@ -16,7 +14,6 @@ from installer.config_values import ( _parse_ps1_var, _parse_retroarch_system_dir, _retroarch_cfg_dir, - _retroarch_cfg_value, ) from installer.detection_notes import note_detection from installer.detect_os import ( @@ -30,15 +27,12 @@ from installer.host_fs import _SETUP_SEARCH, _exists, _host_path, _is_dir, _is_f from installer.paths import MOVED, RETRODECK_CONFIG, shown_path from installer.platforms import display_name from installer.text import _CONTROLS - -# The three RetroArch packages published for Android, newest ABI first. -ANDROID_RETROARCH_PACKAGES = ( - "com.retroarch.aarch64", - "com.retroarch", - "com.retroarch.ra32", +from installer.detect_android import _detect_android, android_unreachable_folders +from installer.detect_launchbox import ( + _launchbox_retroarch_system_dir, + launchbox_emulators, + launchbox_root, ) -# Where Android keeps each app's private data. -ANDROID_APP_DATA = Path("/data/data") def _steam_libraries() -> list[Path]: @@ -156,371 +150,6 @@ def _retroarch_appimage_dirs(home: Path) -> list[Path]: return dirs -def _android_storage_root() -> Path: - """Shared storage root, the parent RetroArch builds its defaults from.""" - value = os.environ.get("EXTERNAL_STORAGE", "").strip() - return Path(value) if value else Path("/storage/emulated/0") - - -# Where each RetroArch package keeps its folders, RetroArch v1.22.2 -# (pkg/android/phoenix/build.gradle:46-95). com.retroarch and -# com.retroarch.aarch64 are each published twice under one id: by -# retroarch.com (normal, aarch64) and on Google Play (playStoreNormal, -# playStorePlus). com.retroarch.ra32 has no Google Play flavor. The Google -# Play build hands RetroArch Android/data//files as the storage its -# defaults are built from, the other builds the shared storage root -# (MainMenuActivity.java:182-183). -_ANDROID_RETROARCH_PLAY_IDS = ("com.retroarch", "com.retroarch.aarch64") -# A Google Play versionCode is the manifest's 1597175267 (AndroidManifest.xml:5) -# plus one per half week since 1609632000 (build.gradle:76, 87, 168-175), so -# it stays below that start time. The other flavors use the build time in -# seconds (build.gradle:42), above it for every build since 2021. The launcher -# writes the code to retroarch.cfg (UserPreferences.java:150), which -# RetroArch keeps (configuration.c:2623). -_ANDROID_PLAY_VERSION_CEILING = 1609632000 - - -@contextlib.contextmanager -def _refusals_expected() -> Iterator[None]: - """Probes whose refusal is the answer, not a folder to report: another - app's private data on Android, which any app may test for existence and - none may enter, has a line of its own (android_unreachable_folders).""" - outer = getattr(_SETUP_SEARCH, "active", False) - _SETUP_SEARCH.active = False - try: - yield - finally: - _SETUP_SEARCH.active = outer - - -def _android_play_build(package: str, storage: Path, cfgs: tuple[Path, ...]) -> bool | None: - """True for the Google Play build of this package, False for the - retroarch.com one, None when nothing it wrote tells them apart. - - The version code in its config decides. Without a readable config, the - folder each build writes does: the Google Play build never asks for - shared storage (MainMenuActivity.java:199-202), and only it builds its - defaults under Android/data//files/RetroArch. - """ - if package not in _ANDROID_RETROARCH_PLAY_IDS: - return False - for cfg in cfgs: - code = _retroarch_cfg_value(cfg, "bundle_assets_extract_version_current") - if code and code.isdigit() and int(code) > 0: - return int(code) < _ANDROID_PLAY_VERSION_CEILING - if _is_dir(storage / "Android" / "data" / package / "files" / "RetroArch"): - return True - if _is_dir(storage / "RetroArch"): - return False - return None - - -def _android_writable(folder: Path) -> bool: - """Whether this shell can create folder: its nearest existing parent is - writable. Android 11 and later keep Android/data/ of other apps - from Termux.""" - for parent in (folder, *folder.parents): - if _exists(parent): - return _is_dir(parent) and os.access(parent, os.W_OK) - return False - - -def _android_out_of_reach(name: str, folder: Path, what: str) -> str: - """The line said for an emulator whose BIOS folder this shell cannot write.""" - return (f"{name} is installed, but this shell cannot write its BIOS folder " - f"{folder} without root: {what} are not copied there.") - - -@_refusals_expected() -def _android_retroarch_builds() -> list[tuple[Path | None, str]]: - """Each installed RetroArch build: its system folder when this shell can - write it, else None and the line that says why. - - RetroArch v1.22.2: the launcher picks retroarch.cfg in the app external - files directory, else in the internal one - (pkg/android/phoenix-common/src/com/retroarch/browser/preferences/util/ - UserPreferences.java:36-89), and passes it as CONFIGFILE - (MainMenuActivity.java:178, read at frontend/drivers/platform_unix.c: - 1428-1444). A system_directory left at default resolves against - /RetroArch/system (platform_unix.c:1670-1697), storage being - what the launcher passes as SDCARD: Android/data//files for the - Google Play build, the shared storage root for the others. - """ - storage = _android_storage_root() - builds: list[tuple[Path | None, str]] = [] - for package in ANDROID_RETROARCH_PACKAGES: - external = storage / "Android" / "data" / package / "files" - if not _exists(ANDROID_APP_DATA / package) and not _exists(external): - continue - cfgs = (external / "retroarch.cfg", - ANDROID_APP_DATA / package / "files" / "retroarch.cfg") - play = _android_play_build(package, storage, cfgs) - play_root, shared_root = external / "RetroArch", storage / "RetroArch" - named = next(filter(None, (_retroarch_cfg_value(cfg, "system_directory") - for cfg in cfgs)), "default") - if play is None and named == "default": - builds.append((None, - f"RetroArch ({package}) is installed, but nothing it has written tells " - f"which build it is: the Google Play build reads {play_root / 'system'}, " - f"the retroarch.com build reads {shared_root / 'system'}. " - "Name the folder with --dest.")) - continue - root = play_root if play else shared_root - folder = next(filter(None, (_parse_retroarch_system_dir(cfg, root) for cfg in cfgs)), - root / "system") - private = (storage / "Android" / "data", ANDROID_APP_DATA) - if any(folder == base or base in folder.parents for base in private) \ - and not _android_writable(folder): - build = "Google Play build" if play else "retroarch.com build" - builds.append((None, _android_out_of_reach( - f"RetroArch ({build}, {package})", folder, "BIOS files"))) - continue - builds.append((folder, "")) - return builds - - -def _detect_android() -> list[tuple[str, Path]]: - """Find the RetroArch system directory of each installed build on - Android, as _android_retroarch_builds() resolves it (RetroArch v1.22.2, - platform_unix.c:1670-1697). - - With no package seen, /RetroArch is the folder of a - retroarch.com build whose private data this shell cannot see. - """ - found: list[tuple[str, Path]] = [] - builds = _android_retroarch_builds() - for folder, _line in builds: - if folder is not None and ("retroarch", folder) not in found: - found.append(("retroarch", folder)) - default_root = _android_storage_root() / "RetroArch" - if not builds and _exists(default_root): - found.append(("retroarch", default_root / "system")) - return found - - -# Android emulators that keep their BIOS outside RetroArch's folder: -# (name, package, folder, files read there). DraStic keeps it in its private -# data (GammaOS Next 14 bb28e71d, gammaos/setup.sh:345-363 extracts it to -# /data/data/com.dsemu.drastic/files/DraStic/system), which no other app -# writes without root. Flycast reads /data/ (flycast a9bd1c74, -# shell/android-studio/flycast/src/main/jni/src/Android.cpp:143-159), its -# home being Android/data/com.flycast.emulator/files, which Android 11 and -# later keep from other apps. -_ANDROID_APP_FOLDERS = ( - ("DraStic", "com.dsemu.drastic", "/data/data/com.dsemu.drastic/files/DraStic/system", - ("nds_bios_arm7.bin", "nds_bios_arm9.bin", "nds_firmware.bin")), - ("Flycast", "com.flycast.emulator", - "$STORAGE/Android/data/com.flycast.emulator/files/data", - ("dc_boot.bin", "dc_nvmem.bin")), -) - - -@_refusals_expected() -def android_unreachable_folders() -> list[str]: - """A line for each Android emulator installed here whose BIOS folder - this shell cannot write, said instead of skipping it in silence. A - RetroArch build whose folder is out of reach, or whose build cannot be - told, is among them. - - An app's private folder can be tested for existence by any app, so the - emulator is known to be installed even where its folder is out of reach. - """ - lines = [line for folder, line in _android_retroarch_builds() if folder is None] - storage = str(_android_storage_root()) - for name, package, folder, files in _ANDROID_APP_FOLDERS: - target = Path(folder.replace("$STORAGE", storage, 1)) - if folder.startswith("/data/data/"): - target = ANDROID_APP_DATA / Path(folder).relative_to("/data/data") - if not _exists(ANDROID_APP_DATA / package) and not _exists(target): - continue - if _is_dir(target) and os.access(target, os.W_OK): - continue - lines.append(_android_out_of_reach(name, target, ", ".join(files))) - return lines - - -def _lnk_target(lnk_path: Path, exe_name: str) -> Path | None: - """Read the target path of a Windows shortcut. - - Shortcuts embed the target as a plain local path. Scanning for it avoids - parsing the whole .lnk structure for the one field that matters here. - """ - try: - if lnk_path.stat().st_size > 64 * 1024: - return None - blob = lnk_path.read_bytes() - except OSError: - return None - pattern = re.compile( - rb"[A-Za-z]:\\[ -~]{0,260}?" + re.escape(exe_name.encode()), re.IGNORECASE - ) - match = pattern.search(blob) - if not match: - return None - return Path(match.group().decode("ascii", "replace").replace("\\", "/")) - - -def launchbox_root(os_type: str) -> Path | None: - """Locate the LaunchBox installation directory. - - LaunchBox installs wherever the user points its installer and writes no - uninstall registry key, so the Start menu shortcut is the only record of - that choice. Everything else falls back to the default location. - """ - if os_type not in ("windows", "wsl"): - return None - candidates: list[Path] = [] - appdata = os.environ.get("APPDATA", "") - if appdata: - lnk = ( - Path(appdata) - / "Microsoft" - / "Windows" - / "Start Menu" - / "Programs" - / "LaunchBox" - / "LaunchBox.lnk" - ) - if _exists(lnk): - target = _lnk_target(lnk, "LaunchBox.exe") - if target: - # The shortcut points at Core/LaunchBox.exe - candidates.append(target.parent.parent) - candidates.append(target.parent) - userprofile = os.environ.get("USERPROFILE", "") - if userprofile: - candidates.append(Path(userprofile) / "LaunchBox") - for root in candidates: - if _exists(root / "Data" / "Emulators.xml"): - return root - return None - - -def launchbox_emulators(emulators_xml: Path) -> dict[str, Path]: - """Map each emulator LaunchBox knows about to its installation directory. - - LaunchBox stores its emulator list in Data/Emulators.xml. ApplicationPath - is either absolute or relative to the LaunchBox root directory. Keys are - the lowercase executable names. - """ - found: dict[str, Path] = {} - if not _exists(emulators_xml): - return found - try: - if emulators_xml.stat().st_size > 10 * 1024 * 1024: - return found - raw = emulators_xml.read_text(encoding="utf-8", errors="replace") - # ElementTree expands internal entities, and LaunchBox writes no doctype - if " Path | None: - """Resolve the system dir of a RetroArch referenced by LaunchBox. - - Mirrors the plugin's UpdateSystemPath: read system_directory from the - retroarch.cfg sitting next to the executable, else assume system/. - """ - emu_dir = launchbox_emulators(emulators_xml).get("retroarch.exe") - if emu_dir is None: - return None - system_dir = _parse_retroarch_system_dir(emu_dir / "retroarch.cfg", emu_dir) - return system_dir or emu_dir / "system" - - -def _pcsx2_bios_dir(emu_dir: Path) -> Path: - """Resolve the BIOS folder of a PCSX2 installed under LaunchBox. - - EmuFolders (pcsx2/Pcsx2Config.cpp) enters portable mode when portable.ini - or portable.txt sits next to the executable, and then takes the data root - from the contents of portable.txt, relative to the executable. Otherwise - the data root is Documents/PCSX2. Bios defaults to "bios" below it and the - Bios key of PCSX2.ini overrides that. - """ - documents = Path(os.environ.get("USERPROFILE", str(Path.home()))) / "Documents" - portable_txt = emu_dir / "portable.txt" - portable = _exists(emu_dir / "portable.ini") or _exists(portable_txt) - if portable: - subpath = "" - with contextlib.suppress(OSError): - subpath = portable_txt.read_text( - encoding="utf-8", errors="replace" - ).strip() - data_root = emu_dir / subpath if subpath else emu_dir - else: - data_root = documents / "PCSX2" - ini = data_root / "inis" / "PCSX2.ini" - try: - for line in ini.read_text(encoding="utf-8", errors="replace").splitlines(): - if line.startswith("Bios = "): - value = line[len("Bios = "):].strip() - candidate = Path(value) - return candidate if candidate.is_absolute() else data_root / value - except OSError: - pass - return data_root / "bios" - - -def _xemu_bios_dir(emu_dir: Path) -> Path: - """Resolve the BIOS folder of a xemu managed by LaunchBox. - - Follows the plugin: xemu.toml next to the executable else the roaming - copy, with bootrom_path and flashrom_path naming a file whose directory - holds the images. Both default to bios/ under the executable. - """ - appdata = os.environ.get("APPDATA", "") - toml = emu_dir / "xemu.toml" - if not _exists(toml) and appdata: - toml = Path(appdata) / "xemu" / "xemu" / "xemu.toml" - if _exists(toml): - try: - for line in toml.read_text(encoding="utf-8", errors="replace").splitlines(): - if line.startswith(("bootrom_path", "flashrom_path")): - parts = line.split("'") - if len(parts) > 1 and _exists(Path(parts[1])): - return Path(parts[1]).parent - except OSError: - pass - return emu_dir / "bios" - - -def launchbox_bios_dirs(root: Path) -> dict[str, Path]: - """Map emulator ids to the BIOS directory LaunchBox expects for them. - - Only emulators whose destination LaunchBox itself computes are listed. - The rest keep the default locations declared in the manifest. - """ - emulators = launchbox_emulators(root / "Data" / "Emulators.xml") - dirs: dict[str, Path] = {} - emu_dir = emulators.get("pcsx2.exe") - if emu_dir: - dirs["pcsx2"] = _pcsx2_bios_dir(emu_dir) - emu_dir = emulators.get("xemu.exe") - if emu_dir: - dirs["xemu"] = _xemu_bios_dir(emu_dir) - emu_dir = emulators.get("dolphin.exe") - if emu_dir and _exists(emu_dir / "portable.txt"): - # portable.txt beside the executable moves the user directory to - # User (SetUserDirectory in Source/Core/UICommon/UICommon.cpp, - # PORTABLE_USER_DIR in Source/Core/Common/CommonPaths.h) - dirs["dolphin"] = emu_dir / "User" - return dirs - - # The platforms whose configuration names a folder with a control character. _UNNAMEABLE: list[str] = [] diff --git a/installer/detect_launchbox.py b/installer/detect_launchbox.py new file mode 100644 index 000000000..ceceb4946 --- /dev/null +++ b/installer/detect_launchbox.py @@ -0,0 +1,194 @@ +"""LaunchBox on Windows: where it lives, the emulators it lists and their BIOS folders.""" + +from __future__ import annotations + +import contextlib +import os +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +from installer.config_values import _parse_retroarch_system_dir +from installer.host_fs import _exists, _is_dir + + +def _lnk_target(lnk_path: Path, exe_name: str) -> Path | None: + """Read the target path of a Windows shortcut. + + Shortcuts embed the target as a plain local path. Scanning for it avoids + parsing the whole .lnk structure for the one field that matters here. + """ + try: + if lnk_path.stat().st_size > 64 * 1024: + return None + blob = lnk_path.read_bytes() + except OSError: + return None + pattern = re.compile( + rb"[A-Za-z]:\\[ -~]{0,260}?" + re.escape(exe_name.encode()), re.IGNORECASE + ) + match = pattern.search(blob) + if not match: + return None + return Path(match.group().decode("ascii", "replace").replace("\\", "/")) + + +def launchbox_root(os_type: str) -> Path | None: + """Locate the LaunchBox installation directory. + + LaunchBox installs wherever the user points its installer and writes no + uninstall registry key, so the Start menu shortcut is the only record of + that choice. Everything else falls back to the default location. + """ + if os_type not in ("windows", "wsl"): + return None + candidates: list[Path] = [] + appdata = os.environ.get("APPDATA", "") + if appdata: + lnk = ( + Path(appdata) + / "Microsoft" + / "Windows" + / "Start Menu" + / "Programs" + / "LaunchBox" + / "LaunchBox.lnk" + ) + if _exists(lnk): + target = _lnk_target(lnk, "LaunchBox.exe") + if target: + # The shortcut points at Core/LaunchBox.exe + candidates.append(target.parent.parent) + candidates.append(target.parent) + userprofile = os.environ.get("USERPROFILE", "") + if userprofile: + candidates.append(Path(userprofile) / "LaunchBox") + for root in candidates: + if _exists(root / "Data" / "Emulators.xml"): + return root + return None + + +def launchbox_emulators(emulators_xml: Path) -> dict[str, Path]: + """Map each emulator LaunchBox knows about to its installation directory. + + LaunchBox stores its emulator list in Data/Emulators.xml. ApplicationPath + is either absolute or relative to the LaunchBox root directory. Keys are + the lowercase executable names. + """ + found: dict[str, Path] = {} + if not _exists(emulators_xml): + return found + try: + if emulators_xml.stat().st_size > 10 * 1024 * 1024: + return found + raw = emulators_xml.read_text(encoding="utf-8", errors="replace") + # ElementTree expands internal entities, and LaunchBox writes no doctype + if " Path | None: + """Resolve the system dir of a RetroArch referenced by LaunchBox. + + Mirrors the plugin's UpdateSystemPath: read system_directory from the + retroarch.cfg sitting next to the executable, else assume system/. + """ + emu_dir = launchbox_emulators(emulators_xml).get("retroarch.exe") + if emu_dir is None: + return None + system_dir = _parse_retroarch_system_dir(emu_dir / "retroarch.cfg", emu_dir) + return system_dir or emu_dir / "system" + + +def _pcsx2_bios_dir(emu_dir: Path) -> Path: + """Resolve the BIOS folder of a PCSX2 installed under LaunchBox. + + EmuFolders (pcsx2/Pcsx2Config.cpp) enters portable mode when portable.ini + or portable.txt sits next to the executable, and then takes the data root + from the contents of portable.txt, relative to the executable. Otherwise + the data root is Documents/PCSX2. Bios defaults to "bios" below it and the + Bios key of PCSX2.ini overrides that. + """ + documents = Path(os.environ.get("USERPROFILE", str(Path.home()))) / "Documents" + portable_txt = emu_dir / "portable.txt" + portable = _exists(emu_dir / "portable.ini") or _exists(portable_txt) + if portable: + subpath = "" + with contextlib.suppress(OSError): + subpath = portable_txt.read_text( + encoding="utf-8", errors="replace" + ).strip() + data_root = emu_dir / subpath if subpath else emu_dir + else: + data_root = documents / "PCSX2" + ini = data_root / "inis" / "PCSX2.ini" + try: + for line in ini.read_text(encoding="utf-8", errors="replace").splitlines(): + if line.startswith("Bios = "): + value = line[len("Bios = "):].strip() + candidate = Path(value) + return candidate if candidate.is_absolute() else data_root / value + except OSError: + pass + return data_root / "bios" + + +def _xemu_bios_dir(emu_dir: Path) -> Path: + """Resolve the BIOS folder of a xemu managed by LaunchBox. + + Follows the plugin: xemu.toml next to the executable else the roaming + copy, with bootrom_path and flashrom_path naming a file whose directory + holds the images. Both default to bios/ under the executable. + """ + appdata = os.environ.get("APPDATA", "") + toml = emu_dir / "xemu.toml" + if not _exists(toml) and appdata: + toml = Path(appdata) / "xemu" / "xemu" / "xemu.toml" + if _exists(toml): + try: + for line in toml.read_text(encoding="utf-8", errors="replace").splitlines(): + if line.startswith(("bootrom_path", "flashrom_path")): + parts = line.split("'") + if len(parts) > 1 and _exists(Path(parts[1])): + return Path(parts[1]).parent + except OSError: + pass + return emu_dir / "bios" + + +def launchbox_bios_dirs(root: Path) -> dict[str, Path]: + """Map emulator ids to the BIOS directory LaunchBox expects for them. + + Only emulators whose destination LaunchBox itself computes are listed. + The rest keep the default locations declared in the manifest. + """ + emulators = launchbox_emulators(root / "Data" / "Emulators.xml") + dirs: dict[str, Path] = {} + emu_dir = emulators.get("pcsx2.exe") + if emu_dir: + dirs["pcsx2"] = _pcsx2_bios_dir(emu_dir) + emu_dir = emulators.get("xemu.exe") + if emu_dir: + dirs["xemu"] = _xemu_bios_dir(emu_dir) + emu_dir = emulators.get("dolphin.exe") + if emu_dir and _exists(emu_dir / "portable.txt"): + # portable.txt beside the executable moves the user directory to + # User (SetUserDirectory in Source/Core/UICommon/UICommon.cpp, + # PORTABLE_USER_DIR in Source/Core/Common/CommonPaths.h) + dirs["dolphin"] = emu_dir / "User" + return dirs diff --git a/installer/run.py b/installer/run.py index 01262b679..825bacea1 100644 --- a/installer/run.py +++ b/installer/run.py @@ -10,7 +10,7 @@ from typing import TYPE_CHECKING, TextIO from installer.console import OUTPUT, Progress, _confirm, detail from installer.datadirs import data_directory_state, data_fetch_bytes, install_data_directory from installer.destination import _missing_dest, _refuse_closed, _refuse_file, on_its_card -from installer.detect_frontends import launchbox_bios_dirs, launchbox_root +from installer.detect_launchbox import launchbox_bios_dirs, launchbox_root from installer.detect_os import detected_shown from installer.diagnosis import CheckHeld, bios_folder_index, check_lines from installer.download import download_files diff --git a/installer/setups.py b/installer/setups.py index ec16d3c5b..c9b02bf3d 100644 --- a/installer/setups.py +++ b/installer/setups.py @@ -21,7 +21,8 @@ from installer.cards import ( ) from installer.console import _ask, _quit from installer.detection_notes import note_detection -from installer.detect_frontends import _UNNAMEABLE, _android_storage_root, detect_platforms +from installer.detect_frontends import _UNNAMEABLE, detect_platforms +from installer.detect_android import _android_storage_root from installer.detect_os import ( _DETECTED_OS, _FROM_CARD, diff --git a/installer/standalone.py b/installer/standalone.py index 912ffc0fa..f17e83b1e 100644 --- a/installer/standalone.py +++ b/installer/standalone.py @@ -8,7 +8,7 @@ from pathlib import Path, PurePosixPath from typing import TYPE_CHECKING from installer.console import Progress, _confirm -from installer.detect_frontends import launchbox_bios_dirs, launchbox_root +from installer.detect_launchbox import launchbox_bios_dirs, launchbox_root from installer.download import download_files from installer.host_fs import NOT_WRITABLE, _closed_to_this_user, _exists, _is_dir, _replace_with_copy, _write_refused from installer.invocation import offline_requested diff --git a/wiki/architecture.md b/wiki/architecture.md index 172ceb909..4ffc00c02 100644 --- a/wiki/architecture.md +++ b/wiki/architecture.md @@ -501,7 +501,7 @@ those it imports: | Shared words and limits | `remote`, `regions`, `platforms`, `manifest`, `embedded`, `text`, `events`, `refusal`, `invocation`, `combinations` | | Terminal and line output | `terminal`, `console` | | Files and folders | `host_fs`, `paths`, `filesystems`, `config_values`, `local_check`, `safe_replace` | -| This machine | `detection_notes`, `detect_os`, `detect_frontends`, `cards`, `device`, `cores`, `frontend_folders`, `setups` | +| This machine | `detection_notes`, `detect_os`, `detect_android`, `detect_launchbox`, `detect_frontends`, `cards`, `device`, `cores`, `frontend_folders`, `setups` | | Sources of files | `offline`, `network`, `lists`, `pack_source`, `folder_index`, `local_copies`, `from_folders`, `diagnosis`, `download`, `datadirs`, `standalone` | | What a run keeps | `narrowing`, `choices`, `romm`, `install_record`, `game_files`, `games_index`, `game_regions`, `game_folders`, `games`, `tally`, `space`, `fetch_plan` | | Line mode | `destination`, `line_folder`, `line_menu`, `plan_words`, `plan`, `failure_causes`, `outcome` |