From 0110dc3c0fee8bf1d247e08c338f2aef52403a16 Mon Sep 17 00:00:00 2001 From: Moroni Granja Date: Wed, 4 Nov 2026 13:38:02 -0300 Subject: [PATCH] fix: a GOG install launches the game, not its config tool (#1644) Blood Omen ships dxconfig.exe beside kain.exe and the shortcut pointed at the config tool: pickExe kept the first .exe the folder listing returned when no title match was found. Read the game's play task from GOG's own goggame-.info manifest first - a primary game task, or a primary launcher task for launcher games, and the product's manifest ahead of any other goggame-*.info - then the product's temp_executable; without either, rank the folder's exes so a word of the title wins, config and tool names lose, and depth then size break the remaining ties. GOG's galaxy_*.exe support installer is not the game either. The Witcher: Enhanced Edition ships galaxy_the_witcher_enhanced_edition_2.1.0.15.exe beside launcher.exe, and its build metadata names that file as the product's temp executable, so launching it starts a 32-bit installer that stops at "Path not found" under ARM64 FEX - the same dialog as the setup stub #1174 removed. Play tasks, the hint and the name search skip it. Fixes #680 Fixes #694 Only a primary launcher task counts as a launch task: GOG files the configuration tool beside a game as a non-primary launcher, so it now falls through to the executable search instead of becoming the game. The temp_executable hint is matched by basename with either separator and must resolve inside the install folder, so a nested galaxy_*.exe is skipped too and a hint cannot point outside the game. GOG runs a task from the working directory it declares, and from the install root when it declares none. That directory now reaches the sidecar and the shortcut's Start In: a game in a subfolder (System/witcher.exe) starts where GOG starts it instead of in System/, where it cannot find its Data folder. --- .../droiddeck/launcher/frontend/AddedGames.kt | 7 + .../launcher/stores/StoreGameSidecar.kt | 12 +- .../droiddeck/launcher/stores/StoreLaunch.kt | 3 +- .../launcher/stores/gog/GogBackend.kt | 1 + .../stores/gog/GogDownloadManager.java | 210 ++++++++++- .../launcher/stores/gog/GogMaintenance.kt | 4 +- .../frontend/AddedGamesStoreScanTest.kt | 39 +- .../launcher/stores/StoreGameSidecarTest.kt | 19 + .../launcher/stores/gog/GogGameExeTest.kt | 339 ++++++++++++++++++ docs/development/stores.md | 13 + 10 files changed, 625 insertions(+), 22 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/stores/gog/GogGameExeTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt index 3ffbee55f0..29974a4a54 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt @@ -426,7 +426,14 @@ object AddedGames { ?.takeIf { SessionPrefs.adoptAddedGameExe(context, folder.path, picked, it.path, rev) } val exe = adopted ?: found val guestExe = if (adopted != null) guestPath(context, adopted) ?: return else foundGuest + val storeExe = sidecar?.exeFile(folder) + val launched = adopted ?: chosen ?: storeExe?.takeIf { it.isFile } + val storeOwnExe = launched != null && storeExe != null && canonical(launched) == canonical(storeExe) + val sidecarDir = sidecar?.workdir?.takeIf { storeOwnExe }?.let { dir -> + guestPath(context, if (dir.isEmpty()) folder else File(folder, dir)) + } val guestDir = SessionPrefs.addedGameStartIn(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() } + ?: sidecarDir ?: guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return val steamId = config?.let { steamRoute(it, appId) } out.add(Game(folder, name, exe, guestExe, guestDir, appId, diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreGameSidecar.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreGameSidecar.kt index e4d828372f..da81f87cf9 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreGameSidecar.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreGameSidecar.kt @@ -11,6 +11,8 @@ class StoreGameSidecar( val title: String, val exe: String, val launcher: String? = null, + /** The working directory a store's launch task asks for: "" is the game folder, null means the exe's folder. */ + val workdir: String? = null, val args: List = emptyList(), val env: Map = emptyMap(), val installVersion: String = "", @@ -30,12 +32,12 @@ class StoreGameSidecar( fun launcherFile(folder: File): File? = launcher?.takeIf { it.isNotEmpty() }?.let { File(folder, it) } fun copy( - exe: String = this.exe, launcher: String? = this.launcher, args: List = this.args, + exe: String = this.exe, launcher: String? = this.launcher, workdir: String? = this.workdir, args: List = this.args, env: Map = this.env, installVersion: String = this.installVersion, installedAt: Long = this.installedAt, cover: String? = this.cover, hero: String? = this.hero, extra: Map = this.extra, state: String = this.state, epic: EpicOptions = this.epic, cloud: Boolean = this.cloud, achievements: Boolean = this.achievements, logo: String? = this.logo, - ) = StoreGameSidecar(store, id, title, exe, launcher, args, env, installVersion, installedAt, cover, hero, extra, state, epic, cloud, achievements, logo) + ) = StoreGameSidecar(store, id, title, exe, launcher, workdir, args, env, installVersion, installedAt, cover, hero, extra, state, epic, cloud, achievements, logo) fun toJson(): JSONObject = JSONObject().apply { put("version", VERSION) @@ -48,6 +50,7 @@ class StoreGameSidecar( if (store != Store.AMAZON) put("cloud", cloud) if (store == Store.GOG) put("achievements", achievements) if (!launcher.isNullOrEmpty()) put("launcher", launcher) + if (workdir != null) put("workdir", workdir) if (args.isNotEmpty()) put("args", JSONArray(args)) if (env.isNotEmpty()) put("env", JSONObject(env as Map<*, *>)) if (installVersion.isNotEmpty()) put("installVersion", installVersion) @@ -116,13 +119,16 @@ class StoreGameSidecar( if (exe.isEmpty() && state == STATE_INSTALLED) return null if (exe.isNotEmpty() && !relativeInside(exe)) return null val launcher = o.optString("launcher", "").replace('\\', '/').takeIf { it.isNotEmpty() && relativeInside(it) } + val workdir = if (!o.has("workdir")) null else o.optString("workdir", "") + .replace('\\', '/').removePrefix("./").trimEnd('/') + .let { if (it.isEmpty() || it == ".") "" else it.takeIf(::relativeInside) } val args = o.optJSONArray("args")?.let { a -> List(a.length()) { a.optString(it) }.filter { it.isNotEmpty() } } ?: emptyList() val env = LinkedHashMap() o.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.optString(k) } } val extra = LinkedHashMap() o.optJSONObject("extra")?.let { e -> e.keys().forEach { k -> extra[k] = e.optString(k) } } return StoreGameSidecar( - store, id, title, exe, launcher, args, env, + store, id, title, exe, launcher, workdir = workdir, args = args, env = env, installVersion = o.optString("installVersion", ""), installedAt = o.optLong("installedAt", 0L), cover = o.optString("cover", "").ifEmpty { null }, diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt index e17aac578b..378d7fa74b 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunch.kt @@ -22,7 +22,8 @@ object StoreLaunch { fun launcherText(sidecar: StoreGameSidecar): String { val exe = sidecar.exe.replace('/', '\\') - val dir = exe.substringBeforeLast('\\', "") + val dir = sidecar.workdir?.let { if (it.isEmpty()) "" else it.replace('/', '\\') } + ?: exe.substringBeforeLast('\\', "") val lines = ArrayList() lines += "@echo off" lines += "setlocal" diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt index fe21531938..fb6b0c8905 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt @@ -133,6 +133,7 @@ object GogBackend : StoreBackend { val installedLanguage = result.language?.takeIf { it.isNotEmpty() } ?: language val sidecar = StoreGameSidecar( Store.GOG, game.gameId, game.title, exe = result.exeRelative.ifEmpty { "" }, + workdir = result.workDir, installVersion = result.buildId, installedAt = System.currentTimeMillis(), cover = item.tallImageUrl ?: item.imageUrl, hero = item.imageUrl, logo = item.logoUrl ?: fetchLogo(game.gameId), diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java index 0dafce41cc..352fa5c1f6 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java @@ -23,11 +23,15 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -63,6 +67,8 @@ public final class GogDownloadManager { public List dependencies = new ArrayList<>(); public boolean dependenciesRead = false; public String language; + /** GOG's working directory for the exe: "" is the install root, null when no task declared it. */ + public String workDir; Result(String exeRelative, String buildId, long bytes) { this.exeRelative = exeRelative; this.buildId = buildId; this.bytes = bytes; } } @@ -259,7 +265,9 @@ public final class GogDownloadManager { if (clientId != null && !clientId.isEmpty()) GogPrefs.get(ctx).edit().putString("client_id_" + game.gameId, clientId).apply(); String clientSecret = manifest.optString("clientSecret", null); if (clientSecret != null && !clientSecret.isEmpty()) GogPrefs.get(ctx).edit().putString("client_secret_" + game.gameId, clientSecret).apply(); - out.result = new Result(pickExe(installPath, tempExe, game.title), gm.buildId, planned); + GameTask task = pickTask(installPath, game.gameId, tempExe, game.title); + out.result = new Result(task == null ? "" : task.path, gm.buildId, planned); + if (task != null) out.result.workDir = task.workDir; out.result.dependencies = dependencies; out.result.dependenciesRead = true; out.result.language = resolved; @@ -430,7 +438,9 @@ public final class GogDownloadManager { if (anyFailed.get()) { out.error = "one or more files failed to download"; return out; } cb.onProgress("Finishing…", 96); writeFile(new File(installPath, MARKER), ("{\"gameId\":\"" + game.gameId + "\",\"generation\":1}").getBytes("UTF-8")); - out.result = new Result(pickExe(installPath, null, game.title), "", planned); + GameTask task = pickTask(installPath, game.gameId, null, game.title); + out.result = new Result(task == null ? "" : task.path, "", planned); + if (task != null) out.result.workDir = task.workDir; return out; } catch (Exception e) { out.error = "exception: " + e.getClass().getSimpleName(); @@ -480,11 +490,14 @@ public final class GogDownloadManager { for (InstallerPart part : parts) new File(installPath, part.filename).delete(); deleteDir(new File(installPath, "tmp")); deleteDir(new File(installPath, "commonappdata")); - String exe = pickExe(installPath, null, game.title); + GameTask task = pickTask(installPath, game.gameId, null, game.title); + String exe = task == null ? "" : task.path; if (exe.isEmpty()) throw new InstallException("The installer was extracted but no game executable was found"); cb.onLog("gog: installer extracted natively; game exe " + exe); GogMaintenance.captureOffline(game.gameId, installPath, downloads); - return new Result(exe, "", total); + Result result = new Result(exe, "", total); + result.workDir = task.workDir; + return result; } catch (InstallerException e) { throw e; } catch (InstallException e) { @@ -1071,21 +1084,188 @@ public final class GogDownloadManager { dir.delete(); } - static String pickExe(File installPath, String tempExe, String title) { + /** + * GOG's own manifest names the game's play task: Blood Omen's is kain.exe while dxconfig.exe is + * its separate tool task (#680). The product's own {@code goggame-.info} decides when it has + * one; any other {@code goggame-*.info} in the folder is only the fallback. Builds without a + * manifest fall through to the hint and search below. + */ + private static GameTask declaredGameTask(File installPath, String gameId) { + File own = gameId == null || gameId.isEmpty() ? null : new File(installPath, "goggame-" + gameId + ".info"); + if (own != null && !own.isFile()) own = null; + List others = new ArrayList<>(); + File[] files = installPath.listFiles(); + if (files != null) { + Arrays.sort(files); + for (File f : files) { + if (f.equals(own) || !f.isFile() || !f.getName().startsWith("goggame-") || !f.getName().endsWith(".info")) continue; + others.add(f); + } + } + if (own != null) { + GameTask task = bestGameTask(installPath, own); + if (task != null) return task; + } + GameTask best = null; + for (File manifest : others) { + GameTask task = bestGameTask(installPath, manifest); + if (task != null && (best == null || task.rank > best.rank)) best = task; + } + return best; + } + + static final class GameTask { + final String path; + /** GOG's working directory for the task: "" is the install root, null when no task declared it. */ + final String workDir; + final int rank; + GameTask(String path, String workDir, int rank) { this.path = path; this.workDir = workDir; this.rank = rank; } + } + + /** The task this manifest would be played from, or null when it names none that exists. */ + private static GameTask bestGameTask(File installPath, File manifest) { + JSONArray tasks; + try { + tasks = new JSONObject(new String(Files.readAllBytes(manifest.toPath()), StandardCharsets.UTF_8)) + .optJSONArray("playTasks"); + } catch (Exception ignored) { + return null; // A truncated manifest is not a reason to fail an install that downloaded fine. + } + if (tasks == null) return null; + GameTask best = null; + for (int i = 0; i < tasks.length(); i++) { + JSONObject task = tasks.optJSONObject(i); + if (task == null) continue; + int rank = taskRank(task); + if (rank == 0 || (best != null && rank <= best.rank)) continue; + String path = task.optString("path", "").replace('\\', '/').replaceAll("/+", "/").replaceFirst("^(\\.?/)+", ""); + if (path.isEmpty()) continue; + File exe = new File(installPath, path); + if (!exe.isFile() || gogSupportExe(exe.getName()) || !inside(installPath, exe)) continue; + best = new GameTask(path, taskWorkDir(installPath, task), rank); + } + return best; + } + + /** + * GOG runs a task from its declared working directory, and from the installation root when the + * task declares none. The Witcher's play task is {@code System\witcher.exe}; started from + * {@code System} hand-built shortcuts cannot find the game's {@code Data} folder, so the root is + * recorded as "" and reaches the shortcut's Start In. A directory that leaves the folder, or is + * not there, falls back to the root rather than to a guess. + */ + private static String taskWorkDir(File installPath, JSONObject task) { + String dir = task.optString("workingDir", "").replace('\\', '/').replaceAll("/+", "/").trim(); + while (dir.startsWith("./")) dir = dir.substring(2); + dir = dir.replaceAll("^/+", "").replaceAll("/+$", ""); + if (dir.isEmpty() || dir.equals(".")) return ""; + File folder = new File(installPath, dir); + return folder.isDirectory() && inside(installPath, folder) ? dir : ""; + } + + /** + * GOG's categories that launch the game: a primary task wins, and a primary {@code launcher} is + * how GOG ships games that start through one. Only a primary {@code launcher} counts: GOG files + * the configuration tool beside a game as a non-primary {@code launcher}, so that one falls to + * the search rather than becoming the game. {@code tool} and {@code document} name no game. + */ + private static int taskRank(JSONObject task) { + String category = task.optString("category").toLowerCase(Locale.ROOT); + boolean primary = task.optBoolean("isPrimary", false); + if ("game".equals(category)) return primary ? 4 : 2; + if ("launcher".equals(category)) return primary ? 3 : 0; + return 0; + } + + /** + * GOG's Galaxy support executables sit in the game folder but install or patch its Galaxy files, + * never play the game. The Witcher: Enhanced Edition ships + * {@code galaxy_the_witcher_enhanced_edition_2.1.0.15.exe}, and its build metadata even names + * that file as the temp executable: launching it is the same 32-bit Inno Setup stub that stops + * at "Path not found" under ARM64 FEX (#694). Play tasks and the name search both step over it. + */ + private static boolean gogSupportExe(String path) { + return new File(path.replace('\\', '/')).getName().toLowerCase(Locale.ROOT).startsWith("galaxy_"); + } + + /** Whether the canonical path of {@code file} stays below {@code root}. */ + private static boolean inside(File root, File file) { + try { + return file.getCanonicalPath().startsWith(root.getCanonicalPath() + File.separator); + } catch (Exception e) { + return false; + } + } + + /** Exe names that belong to the config or tool shims around the game, not to the game. */ + private static final String[] TOOL_STEM_PARTS = { + "config", "setting", "setup", "install", "unins", "touchup", "crashreport", + "report", "editor", "launcher", "diagnostic", + }; + + static GameTask pickTask(File installPath, String gameId, String tempExe, String title) { + GameTask declared = declaredGameTask(installPath, gameId); + if (declared != null) return declared; if (tempExe != null) { - File hinted = new File(installPath, tempExe); - if (hinted.isFile()) return relative(installPath, hinted); + String hint = tempExe.replace('\\', '/'); + File hinted = new File(installPath, hint); + if (!gogSupportExe(hint) && hinted.isFile() && inside(installPath, hinted)) return new GameTask(relative(installPath, hinted), null, 0); } List candidates = new ArrayList<>(); collectExeRecursive(installPath, candidates); - if (candidates.isEmpty()) return ""; - String key = title.toLowerCase().replaceAll("[^a-z0-9]", ""); - File best = candidates.get(0); - for (File f : candidates) { - String n = f.getName().toLowerCase().replaceAll("\\.exe$", "").replaceAll("[^a-z0-9]", ""); - if (!n.isEmpty() && (n.equals(key) || key.startsWith(n) || n.startsWith(key))) { best = f; break; } + if (candidates.isEmpty()) return null; + String key = title.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]", ""); + List words = new ArrayList<>(); + for (String word : title.toLowerCase(Locale.ROOT).split("[^a-z0-9]+")) { + if (word.length() >= 4 && !words.contains(word)) words.add(word); } - return relative(installPath, best); + Map scores = new HashMap<>(); + for (File f : candidates) scores.put(f, exeScore(f, key, words)); + Collections.sort(candidates, (a, b) -> { + int byScore = Integer.compare(scores.get(b), scores.get(a)); + if (byScore != 0) return byScore; + int byDepth = Integer.compare(depth(installPath, a), depth(installPath, b)); + if (byDepth != 0) return byDepth; + int bySize = Long.compare(b.length(), a.length()); + if (bySize != 0) return bySize; + return relative(installPath, a).compareTo(relative(installPath, b)); + }); + return new GameTask(relative(installPath, candidates.get(0)), null, 0); + } + + static String pickExe(File installPath, String gameId, String tempExe, String title) { + GameTask task = pickTask(installPath, gameId, tempExe, title); + return task == null ? "" : task.path; + } + + /** + * A word of the game's title in the exe name is the strongest hint: Blood Omen's kain.exe beats + * the dxconfig.exe beside it (#680). Config and tool exes lose even when their name is the only + * one resembling the title, and the depth penalty keeps a bundled tool below the game's own + * folder. Before this, whatever the folder listing returned first was kept. + */ + private static int exeScore(File f, String key, List words) { + String stem = f.getName().toLowerCase(Locale.ROOT).replaceAll("\\.exe$", "").replaceAll("[^a-z0-9]", ""); + int score = 0; + if (!stem.isEmpty() && !key.isEmpty()) { + if (stem.equals(key)) score += 120; + else if (key.startsWith(stem) || stem.startsWith(key)) score += 80; + } + for (String word : words) { + if (stem.equals(word)) { score += 100; break; } + if (stem.contains(word)) { score += 40; break; } + } + for (String part : TOOL_STEM_PARTS) { + if (stem.contains(part)) { score -= 110; break; } + } + return score; + } + + private static int depth(File root, File f) { + String path = relative(root, f); + int depth = 0; + for (int i = 0; i < path.length(); i++) if (path.charAt(i) == '/') depth++; + return depth; } private static String relative(File root, File f) { @@ -1099,7 +1279,7 @@ public final class GogDownloadManager { File[] files = dir.listFiles(); if (files == null) return; for (File f : files) { - if (f.isFile() && f.getName().toLowerCase().endsWith(".exe")) { + if (f.isFile() && f.getName().toLowerCase().endsWith(".exe") && !gogSupportExe(f.getName())) { String path = f.getAbsolutePath().toLowerCase(); if (!path.contains("redist") && !path.contains("unins") && !path.contains("setup") && !path.contains("crash") && !path.contains("report") && !path.contains("helper") && !path.contains("dotnet") && !path.contains("vcredist") diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogMaintenance.kt b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogMaintenance.kt index 796e0dbcb1..20d523ec69 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogMaintenance.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogMaintenance.kt @@ -386,7 +386,9 @@ internal object GogMaintenance { transfer(context, Proposal(folder, old, target, GogOperation.UPDATE, bytes, disk), null, cancelled, callback) if (cancelled.get()) return null target.write(folder) - val result = GogDownloadManager.Result(GogDownloadManager.pickExe(folder, null, game.title), build.id, disk) + val task = GogDownloadManager.pickTask(folder, game.gameId, null, game.title) + val result = GogDownloadManager.Result(task?.path ?: "", build.id, disk) + result.workDir = task?.workDir result.language = target.language result.dependencies = target.manifest.optJSONArray("dependencies")?.strings().orEmpty() result.dependenciesRead = true diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesStoreScanTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesStoreScanTest.kt index 410d298acd..1c61034221 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesStoreScanTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesStoreScanTest.kt @@ -18,12 +18,12 @@ import org.robolectric.annotation.Config class AddedGamesStoreScanTest { private val app get() = RuntimeEnvironment.getApplication() - private fun install(store: Store, id: String, title: String, exe: String, launcher: Boolean = false): File { + private fun install(store: Store, id: String, title: String, exe: String, launcher: Boolean = false, workdir: String? = null): File { SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "") val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.installRoot(app), store), StoreInstallRoot.folderName(title, id)) File(folder, exe).apply { parentFile!!.mkdirs(); writeText("game") } File(folder, "unins000.exe").writeText("uninstaller") - var sidecar = StoreGameSidecar(store, id, title, exe, args = if (launcher) listOf("-EpicPortal") else emptyList()) + var sidecar = StoreGameSidecar(store, id, title, exe, workdir = workdir, args = if (launcher) listOf("-EpicPortal") else emptyList()) if (launcher) sidecar = StoreLaunch.writeLauncher(folder, sidecar) sidecar.write(folder) return folder @@ -81,4 +81,39 @@ class AddedGamesStoreScanTest { assertTrue(listing.contains(StoreLaunch.LAUNCHER)) assertTrue(listing.contains("\"store\":\"${Store.EPIC.id}\"")) } + + // GOG runs a task from its declared working directory; the install root when it declares none. + @Test fun aTaskWorkingDirectoryBecomesTheShortcutsStartIn() { + val folder = install(Store.GOG, "1207658924", "Witcher Game", "System/witcher.exe", workdir = "System") + val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath } + assertTrue(game.guestDir.endsWith("/Witcher Game/System")) + } + + @Test fun anEmptyTaskWorkingDirectoryIsTheGameFolder() { + val folder = install(Store.GOG, "1207658924", "Witcher Game", "System/witcher.exe", workdir = "") + val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath } + assertEquals("/root/Games/Stores/GOG/Witcher Game", game.guestDir) + } + + @Test fun aSidecarWithoutATaskDirectoryStillStartsInTheExeFolder() { + val folder = install(Store.GOG, "7", "Old Game", "bin/old.exe") + val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath } + assertTrue(game.guestDir.endsWith("/Old Game/bin")) + } + + // A picked exe that is not the store's own keeps its own folder, not the task directory. + @Test fun aPickedExeOnAGogGameStartsInItsOwnFolder() { + val folder = install(Store.GOG, "1207658924", "Witcher Game", "System/witcher.exe", workdir = "") + val tool = File(folder, "Tools/Editor.exe").apply { parentFile!!.mkdirs(); writeText("tool") } + AddedExes.put(app, AddedExes.Entry(folder.path, tool.path, picked = true)) + val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath } + assertTrue(game.guestDir.endsWith("/Witcher Game/Tools")) + } + + @Test fun pickingTheStoresOwnExeKeepsTheTaskDirectory() { + val folder = install(Store.GOG, "1207658924", "Witcher Game", "System/witcher.exe", workdir = "") + AddedExes.put(app, AddedExes.Entry(folder.path, File(folder, "System/witcher.exe").path, picked = true)) + val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath } + assertEquals("/root/Games/Stores/GOG/Witcher Game", game.guestDir) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/StoreGameSidecarTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/StoreGameSidecarTest.kt index b7ad90b56d..b4217895c2 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/StoreGameSidecarTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/StoreGameSidecarTest.kt @@ -124,6 +124,25 @@ class StoreGameSidecarTest { assertFalse(text.contains("DD_AUTH")) } + @Test fun aWorkingDirectoryTravelsWithTheSidecar() { + val root = StoreGameSidecar(Store.GOG, "1207658924", "The Witcher", "System/witcher.exe", workdir = "") + assertTrue(root.toJson().has("workdir")) + assertEquals("", StoreGameSidecar.parse(root.toJson().toString())!!.workdir) + assertEquals("bin", StoreGameSidecar.parse(root.copy(workdir = "bin").toJson().toString())!!.workdir) + assertNull(StoreGameSidecar.parse(root.copy(workdir = null).toJson().toString())!!.workdir) + assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"game.exe"}""")!!.workdir) + assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"game.exe","workdir":"../x"}""")!!.workdir) + } + + @Test fun theLauncherCdsIntoTheTaskWorkingDirectory() { + assertTrue(StoreLaunch.launcherText(sample.copy(exe = "System/witcher.exe", workdir = "")) + .contains("cd /d \"%~dp0\"\r\n")) + assertTrue(StoreLaunch.launcherText(sample.copy(exe = "bin/x64/game.exe", workdir = "bin/x64")) + .contains("cd /d \"%~dp0bin\\x64\"\r\n")) + assertTrue(StoreLaunch.launcherText(sample.copy(exe = "bin/game.exe", workdir = null)) + .contains("cd /d \"%~dp0bin\"\r\n")) + } + @Test fun epicLauncherPrefersTheClientsArguments() { val text = StoreLaunch.launcherText(sample.copy(exe = "Binaries/Win64/Celeste.exe")) val lines = text.split("\r\n") diff --git a/app/src/test/java/com/droiddeck/launcher/stores/gog/GogGameExeTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/gog/GogGameExeTest.kt new file mode 100644 index 0000000000..fab1177b04 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/gog/GogGameExeTest.kt @@ -0,0 +1,339 @@ +package com.droiddeck.launcher.stores.gog + +import java.io.File +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class GogGameExeTest { + private fun withFolder(block: (File) -> Unit) { + val root = kotlin.io.path.createTempDirectory("gog-exe").toFile() + try { + block(root) + } finally { + root.deleteRecursively() + } + } + + private fun File.exe(path: String, size: Int = 1024) { + val file = File(this, path) + file.parentFile?.mkdirs() + file.writeBytes(ByteArray(size)) + } + + // #680: Blood Omen installs dxconfig.exe next to kain.exe, and the config tool won. + @Test fun theGameExecutableWinsOverTheConfigToolInTheSameFolder() { + withFolder { root -> + root.exe("dxconfig.exe") + root.exe("kain.exe", 4096) + assertEquals("kain.exe", GogDownloadManager.pickExe(root, null, null, "Blood Omen: Legacy of Kain")) + } + } + + @Test fun aConfigToolInTheGameFolderIsNeverTheFoundExecutable() { + withFolder { root -> + root.exe("dxconfig.exe") + root.exe("bin/kain.exe", 4096) + assertEquals("bin/kain.exe", GogDownloadManager.pickExe(root, null, null, "Blood Omen: Legacy of Kain")) + } + } + + @Test fun theLauncherInTheGameRootLosesToTheGameExecutable() { + withFolder { root -> + root.exe("Launcher.exe") + root.exe("bin/witcher2.exe", 4096) + assertEquals( + "bin/witcher2.exe", + GogDownloadManager.pickExe(root, null, null, "The Witcher 2: Assassins of Kings Enhanced Edition"), + ) + } + } + + @Test fun theInstallerHintWinsOverTheSearch() { + withFolder { root -> + root.exe("dxconfig.exe") + root.exe("bin/game.exe", 4096) + assertEquals("bin/game.exe", GogDownloadManager.pickExe(root, null, "bin/game.exe", "Blood Omen: Legacy of Kain")) + } + } + + @Test fun aFolderWithoutAGameExecutableYieldsNoPath() { + withFolder { root -> + root.exe("redist/vcredist_x64.exe") + assertEquals("", GogDownloadManager.pickExe(root, null, null, "Blood Omen: Legacy of Kain")) + } + } + + @Test fun theManifestsGameTaskIsTheExecutable() { + withFolder { root -> + root.exe("dxconfig.exe") + root.exe("bin/omen.exe", 4096) + File(root, "goggame-1207659641.info").writeText( + """{"gameId":"1207659641","playTasks":[ + {"category":"tool","path":"dxconfig.exe","type":"FileTask"}, + {"category":"game","isPrimary":true,"path":"bin\\omen.exe","type":"FileTask"}, + {"category":"document","path":"manual.pdf","type":"FileTask"} + ]}""", + ) + assertEquals("bin/omen.exe", GogDownloadManager.pickExe(root, "1207659641", null, "Blood Omen: Legacy of Kain")) + } + } + + @Test fun aManifestWithOnlyAToolTaskLeavesTheSearchInCharge() { + withFolder { root -> + root.exe("dxconfig.exe") + root.exe("kain.exe", 4096) + File(root, "goggame-1207659641.info") + .writeText("""{"playTasks":[{"category":"tool","path":"dxconfig.exe","type":"FileTask"}]}""") + assertEquals("kain.exe", GogDownloadManager.pickExe(root, null, null, "Blood Omen: Legacy of Kain")) + } + } + + @Test fun aManifestPathOutsideTheGameFolderIsIgnored() { + withFolder { root -> + root.exe("kain.exe", 4096) + val outside = File(root.parentFile, "outside-${System.nanoTime()}.exe").apply { writeBytes(ByteArray(8)) } + try { + File(root, "goggame-1207659641.info").writeText( + """{"playTasks":[{"category":"game","isPrimary":true,"path":"../${outside.name}","type":"FileTask"}]}""", + ) + assertEquals("kain.exe", GogDownloadManager.pickExe(root, null, null, "Blood Omen: Legacy of Kain")) + } finally { + outside.delete() + } + } + } + + @Test fun aPrimaryLauncherTaskIsTheGameOfLauncherGames() { + withFolder { root -> + root.exe("run.exe") + root.exe("game.exe", 4096) + File(root, "goggame-7.info").writeText( + """{"playTasks":[ + {"category":"launcher","isPrimary":true,"path":"run.exe","type":"FileTask"}, + {"category":"game","path":"game.exe","type":"FileTask"} + ]}""", + ) + assertEquals("run.exe", GogDownloadManager.pickExe(root, "7", null, "Some Game")) + } + } + + @Test fun aPrimaryGameTaskBeatsAPrimaryLauncherTask() { + withFolder { root -> + root.exe("run.exe") + root.exe("game.exe", 4096) + File(root, "goggame-7.info").writeText( + """{"playTasks":[ + {"category":"launcher","isPrimary":true,"path":"run.exe","type":"FileTask"}, + {"category":"game","isPrimary":true,"path":"game.exe","type":"FileTask"} + ]}""", + ) + assertEquals("game.exe", GogDownloadManager.pickExe(root, "7", null, "Some Game")) + } + } + + @Test fun theProductsOwnManifestDecidesOverADlcManifest() { + withFolder { root -> + root.exe("base.exe") + root.exe("dlc.exe", 4096) + File(root, "goggame-7.info") + .writeText("""{"playTasks":[{"category":"game","isPrimary":true,"path":"base.exe","type":"FileTask"}]}""") + File(root, "goggame-9.info") + .writeText("""{"playTasks":[{"category":"game","isPrimary":true,"path":"dlc.exe","type":"FileTask"}]}""") + assertEquals("base.exe", GogDownloadManager.pickExe(root, "7", null, "Some Game")) + } + } + + @Test fun aDlcManifestSuppliesTheGameWhenTheProductsOwnHasNone() { + withFolder { root -> + root.exe("dxconfig.exe") + root.exe("dlc.exe", 4096) + File(root, "goggame-7.info") + .writeText("""{"playTasks":[{"category":"tool","path":"dxconfig.exe","type":"FileTask"}]}""") + File(root, "goggame-9.info") + .writeText("""{"playTasks":[{"category":"game","isPrimary":true,"path":"dlc.exe","type":"FileTask"}]}""") + assertEquals("dlc.exe", GogDownloadManager.pickExe(root, "7", null, "Some Game")) + } + } + + @Test fun theManifestBeatsTheInstallerHint() { + withFolder { root -> + root.exe("dxconfig.exe") + root.exe("kain.exe", 4096) + File(root, "goggame-7.info") + .writeText("""{"playTasks":[{"category":"game","isPrimary":true,"path":"kain.exe","type":"FileTask"}]}""") + assertEquals( + "kain.exe", + GogDownloadManager.pickExe(root, "7", "dxconfig.exe", "Blood Omen: Legacy of Kain"), + ) + } + } + + // #694: the GOG build's temp executable is its Galaxy support installer, not the game. + @Test + fun theGalaxySupportInstallerIsNeverTheGame() { + withFolder { root -> + root.exe("galaxy_the_witcher_enhanced_edition_2.1.0.15.exe", 1_300_000) + root.exe("launcher.exe") + root.exe("register.exe") + root.exe("System/witcher.exe", 4096) + assertEquals( + "System/witcher.exe", + GogDownloadManager.pickExe( + root, + "1207658924", + "galaxy_the_witcher_enhanced_edition_2.1.0.15.exe", + "The Witcher: Enhanced Edition", + ), + ) + } + } + + @Test + fun aManifestThatNamesTheGalaxySupportInstallerIsIgnored() { + withFolder { root -> + root.exe("galaxy_the_witcher_enhanced_edition_2.1.0.15.exe", 1_300_000) + root.exe("System/witcher.exe", 4096) + File(root, "goggame-1207658924.info").writeText( + """{"playTasks":[{"category":"game","isPrimary":true,"path":"galaxy_the_witcher_enhanced_edition_2.1.0.15.exe","type":"FileTask"}]}""", + ) + assertEquals( + "System/witcher.exe", + GogDownloadManager.pickExe(root, "1207658924", null, "The Witcher: Enhanced Edition"), + ) + } + } + + // GOG's own sample manifest files the Configuration Tool as a non-primary launcher task. + @Test + fun aNonPrimaryLauncherTaskIsNotTheGame() { + withFolder { root -> + root.exe("Config2_DX9.exe") + root.exe("ed6_win2_DX9.exe", 4096) + File(root, "goggame-1207658924.info").writeText( + """{"playTasks":[ + {"category":"launcher","name":"Configuration Tool","path":"Config2_DX9.exe","type":"FileTask"}, + {"category":"game","path":"ed6_win2_DX9.exe","type":"FileTask"} + ]}""", + ) + assertEquals( + "ed6_win2_DX9.exe", + GogDownloadManager.pickExe(root, "1207658924", null, "The Legend of Heroes: Trails in the Sky SC"), + ) + } + } + + @Test + fun aLoneNonPrimaryLauncherLeavesTheSearchInCharge() { + withFolder { root -> + root.exe("Config2_DX9.exe") + root.exe("ed6_win2_DX9.exe", 4096) + File(root, "goggame-1207658924.info").writeText( + """{"playTasks":[{"category":"launcher","path":"Config2_DX9.exe","type":"FileTask"}]}""", + ) + assertEquals( + "ed6_win2_DX9.exe", + GogDownloadManager.pickExe(root, "1207658924", null, "The Legend of Heroes: Trails in the Sky SC"), + ) + } + } + + @Test + fun theSupportInstallerHintIsSkippedWhateverItsFolder() { + withFolder { root -> + root.exe("support/galaxy_setup.exe", 1_300_000) + root.exe("System/witcher.exe", 4096) + assertEquals( + "System/witcher.exe", + GogDownloadManager.pickExe( + root, + "1207658924", + "support/galaxy_setup.exe", + "The Witcher: Enhanced Edition", + ), + ) + assertEquals( + "System/witcher.exe", + GogDownloadManager.pickExe( + root, + "1207658924", + "support\\galaxy_setup.exe", + "The Witcher: Enhanced Edition", + ), + ) + } + } + + @Test + fun anInstallerHintOutsideTheGameFolderIsIgnored() { + withFolder { root -> + root.exe("game.exe", 4096) + val outside = File(root.parentFile, "outside-${System.nanoTime()}.exe").apply { writeBytes(ByteArray(8)) } + try { + assertEquals( + "game.exe", + GogDownloadManager.pickExe(root, "7", "../${outside.name}", "Some Game"), + ) + } finally { + outside.delete() + } + } + } + + // GOG runs a task from the install root unless it declares a working directory. + @Test + fun aTaskWithoutAWorkingDirectoryRunsFromTheGameFolder() { + withFolder { root -> + root.exe("System/witcher.exe", 4096) + File(root, "goggame-1207658924.info").writeText( + """{"playTasks":[{"category":"game","isPrimary":true,"path":"System\\witcher.exe","type":"FileTask"}]}""", + ) + val task = GogDownloadManager.pickTask(root, "1207658924", null, "The Witcher: Enhanced Edition") + assertEquals("System/witcher.exe", task.path) + assertEquals("", task.workDir) + } + } + + @Test + fun aDeclaredWorkingDirectoryIsKept() { + withFolder { root -> + root.exe("bin/x64/game.exe", 4096) + File(root, "goggame-7.info").writeText( + """{"playTasks":[{"category":"game","isPrimary":true,"path":"bin\\x64\\game.exe","workingDir":"bin\\x64","type":"FileTask"}]}""", + ) + val task = GogDownloadManager.pickTask(root, "7", null, "Some Game") + assertEquals("bin/x64/game.exe", task.path) + assertEquals("bin/x64", task.workDir) + } + } + + @Test + fun aWorkingDirectoryThatLeavesTheGameFolderFallsBackToTheRoot() { + withFolder { root -> + root.exe("game.exe", 4096) + File(root, "goggame-7.info").writeText( + """{"playTasks":[{"category":"game","isPrimary":true,"path":"game.exe","workingDir":"../other","type":"FileTask"}]}""", + ) + assertEquals("", GogDownloadManager.pickTask(root, "7", null, "Some Game").workDir) + } + } + + // GOG manifests use doubled separators (The Witcher 3: "bin//x64//witcher3.exe"); the sidecar + // parser rejects empty path components, so both values must be collapsed before they are stored. + @Test + fun duplicateSeparatorsInTaskValuesAreCollapsed() { + withFolder { root -> + root.exe("System/witcher.exe", 4096) + File(root, "goggame-1207658924.info").writeText( + """{"playTasks":[{"category":"game","isPrimary":true,"path":"System//witcher.exe","workingDir":"System//","type":"FileTask"}]}""", + ) + val task = GogDownloadManager.pickTask(root, "1207658924", null, "The Witcher: Enhanced Edition") + assertEquals("System/witcher.exe", task.path) + assertEquals("System", task.workDir) + } + } +} diff --git a/docs/development/stores.md b/docs/development/stores.md index e2995c863b..5d11e48b65 100644 --- a/docs/development/stores.md +++ b/docs/development/stores.md @@ -244,6 +244,19 @@ self-extractor stops at "Path not found", so the values it installs are applied `witcher.exe` exits during startup. The language comes from the installed product's `goggame-.info`, and a script's own `setRegistry` entries always win over the built-in table. +A GOG game's exe comes from its own manifest first: `goggame-.info`'s play task in category +`game` (`isPrimary` first), or a primary `launcher` task for launcher games, whose `path` stays +inside the folder; any other `goggame-*.info` in the folder supplies the task only when the +product's own has none. The task's `workingDir` becomes the shortcut's Start In, and the install root +when the task declares none - GOG's own default, and what a game in a subfolder such as +`System/witcher.exe` needs to find its `Data` folder. Else the product's `temp_executable`, else a +score over the folder's `.exe` files - a word of the game's title in the name first (Blood Omen's +`kain.exe` over its `dxconfig.exe`), config and tool names (`config`, `settings`, `launcher`, +`editor`, `crashreport`, …) last, shallower and bigger ahead on a tie. GOG's `galaxy_*.exe` support +installer is never the game, whatever the manifest or the temp executable says: The Witcher ships it +beside `launcher.exe` and its own `temp_executable` names it, and starting it runs the same 32-bit +installer that fails under ARM64 with "Path not found" (issue #694). + A game's web links reach Android: `droiddeck-store-launch` sets the prefix's `HKCU\Software\Wine\WineBrowser` `Browsers` to `/usr/local/bin/droiddeck-open-url`, which is also `xdg-open` first on the game's PATH, and hands http(s) addresses to the app, which opens them in