Skip to content

armgit / soju

Public Imported from GitHub
0

Play Windows games on Apple Silicon Macs. Free, open-source app that installs the official Battle.net, Steam, Epic and GOG launchers and lists your games in one library.

feat: unify installed games across four launchers (#33)

Mikek83650503520d
diff --git a/README.ko.md b/README.ko.md
index 63dc0227fff..a92f1aeb293 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -1,5 +1,9 @@
# Soju (한국어)
+**v1.5.0:** 설치된 게임을 한 라이브러리에서 검색·필터·즐겨찾기하고 실행할 수 있습니다. 런처 설치와 업데이트는 Platforms에서 관리합니다. 미설치 보유 게임 동기화와 스토어 검색은 아직 포함되지 않습니다.
+
+[Desktop / download](docs/DESKTOP.md)
+
> **Apple Silicon 맥용 무료 오픈소스 게임 런처 도구.**
맥에서 **Battle.net·Steam·Epic Games Launcher·GOG GALAXY**를 설치하고 실행하세요.
diff --git a/README.md b/README.md
index 05061f4681a..7ca11e8472b 100644
--- a/README.md
+++ b/README.md
@@ -1,20 +1,25 @@
# Soju
-> **Free, open-source game launcher toolkit for Apple Silicon Macs.**
+> **Free, open-source game library and launcher for Apple Silicon Macs.**
-Set up **Battle.net, Steam, Epic Games Launcher and GOG GALAXY** on your Mac.
-Soju provides terminal setup, separate Wine environments and a Mac launch app for
-each store. Sign in to your existing accounts and play supported Windows games.
+Bring installed games from **Battle.net, Steam, Epic Games and GOG GALAXY**
+into one native Mac library. Search, filter, favorite and launch games through
+their official Windows clients. The Platforms page handles launcher setup,
+component updates and diagnostics; the CLI and individual shortcuts remain available.
-The interface is each store's own launcher; Soju currently ships a CLI and
-launcher-specific shortcuts. Compatibility varies by game and system.
+The library reads local installation records in Soju's Windows environments.
+Accounts, purchases, downloads and game updates stay with each official client.
+Uninstalled owned games and store search are not included in this release.
+Compatibility varies by game and system.
+
+![Soju unified game library](docs/assets/soju-library.png)
The tools are free and open source. The main Wine engine is built from
CodeWeavers' published sources; Steam uses a separate wine-stable setup.
Apple's proprietary GPTK/D3DMetal is downloaded separately. Games and store
clients are not included.
-**Current scripts: [v1.3.6](https://github.com/BCD1210/soju/releases/tag/v1.3.6).**
+**Current release: [v1.5.0](https://github.com/BCD1210/soju/releases/tag/v1.5.0).**
The compatibility examples below were verified on M4 Pro / macOS 26.5.
D2R and Hogwarts Legacy are examples of supported games, not the scope of the project.
@@ -80,7 +85,7 @@ soju install # then: soju battlenet / soju d2r / soju steam / soju epic / so
The installer asks which launchers you want **before downloading anything**. Steam-only installs skip the CX engine and Apple GPTK. Steam rendering components are downloaded with SHA-256 verification and installed in a Soju-owned Wine 11.0 runtime. Battle.net, Epic and GOG use the shared CX engine and your separately downloaded Apple GPTK. Each official client keeps its own bottle and shortcut in `~/Applications`.
-[Download Soju for Mac](https://github.com/BCD1210/soju/releases/download/v1.4.0/Soju-1.4.0-macos-arm64.zip) — the native desktop preview brings installation, launching, component updates and diagnostics into one window. See [desktop setup and requirements](docs/DESKTOP.md).
+[Download Soju for Mac](https://github.com/BCD1210/soju/releases/download/v1.5.0/Soju-1.5.0-macos-arm64.zip) — the native desktop preview includes a unified installed-game library, favorites, game launching and platform management. See [desktop setup and requirements](docs/DESKTOP.md).
## Everyday commands
diff --git a/README.zh.md b/README.zh.md
index 601edd630d9..54bdb0c433b 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -1,5 +1,9 @@
# Soju(简体中文)
+**v1.5.0:** 在统一游戏库中搜索、筛选、收藏和启动已安装的游戏。通过 Platforms 管理启动器安装与更新。此版本暂不包含未安装游戏的账户同步或商店搜索。
+
+[Desktop / download](docs/DESKTOP.md)
+
> **面向 Apple Silicon Mac 的免费开源游戏启动工具。**
在 Mac 上安装和运行 **Battle.net、Steam、Epic Games Launcher 和 GOG GALAXY**。
diff --git a/VERSION b/VERSION
index 88c5fb891dc..bc80560fad6 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.4.0
+1.5.0
diff --git a/app/Library.swift b/app/Library.swift
new file mode 100644
index 00000000000..6e434bff071
--- /dev/null
+++ b/app/Library.swift
@@ -0,0 +1,444 @@
+import SwiftUI
+import AppKit
+
+struct InstalledGame: Decodable, Identifiable {
+ let id: String
+ let platform: Launcher
+ let title: String
+ let installPath: String
+ let artwork: String?
+ let issue: String?
+ enum CodingKeys: String, CodingKey {
+ case id, platform, title, artwork, issue
+ case installPath = "install_path"
+ }
+}
+extension Launcher: Decodable {}
+struct LibrarySnapshot: Decodable {
+ let games: [InstalledGame]
+ let warnings: [String]
+}
+struct LibraryPreferences: Codable {
+ var favorites: Set<String> = []
+ var opened: [String: Date] = [:]
+ static func load() -> Self {
+ guard let data = UserDefaults.standard.data(forKey: "soju.library.v1"),
+ let value = try? JSONDecoder().decode(Self.self, from: data) else { return Self() }
+ return value
+ }
+}
+
+extension SojuModel {
+ func savePreferences() {
+ if let data = try? JSONEncoder().encode(preferences) {
+ UserDefaults.standard.set(data, forKey: "soju.library.v1")
+ }
+ }
+ func favorite(_ game: InstalledGame) {
+ if preferences.favorites.contains(game.id) { preferences.favorites.remove(game.id) }
+ else { preferences.favorites.insert(game.id) }
+ savePreferences()
+ }
+ func refreshLibrary() {
+ guard !scanning else { return }
+ scanning = true
+ do {
+ let (p, url) = try task(["library"], logName: "library-scan")
+ scanner = p
+ p.terminationHandler = { [weak self] process in
+ // Decode off the main thread; a library can contain many games.
+ let data = (try? Data(contentsOf: url)) ?? Data()
+ let result = try? JSONDecoder().decode(LibrarySnapshot.self, from: data)
+ DispatchQueue.main.async {
+ guard let self, self.scanner === process else { return }
+ self.scanning = false; self.scanner = nil
+ if process.terminationStatus == 0, let result {
+ self.games = result.games; self.scanWarnings = result.warnings
+ } else {
+ self.scanWarnings = ["Could not refresh your library. Check that Python 3 is installed, then retry."]
+ }
+ }
+ }
+ try p.run()
+ DispatchQueue.main.asyncAfter(deadline: .now() + 25) { [weak self, weak p] in
+ guard let self, let p, self.scanner === p, p.isRunning else { return }
+ p.terminate()
+ self.scanning = false; self.scanner = nil
+ self.scanWarnings = ["Scanning took too long. Reconnect any external game drives and refresh."]
+ }
+ } catch {
+ scanner = nil; scanning = false
+ scanWarnings = ["Could not scan installed games: " + error.localizedDescription]
+ }
+ }
+ func launchIssue(for game: InstalledGame) -> String? {
+ if let issue = game.issue { return issue }
+ if !FileManager.default.fileExists(atPath: game.installPath) {
+ return "This game folder is unavailable. Reconnect its drive and refresh."
+ }
+ if game.platform == .steam {
+ let local = base.appendingPathComponent("steam-runtime/bin/wine").path
+ let stable = "/Applications/Wine Stable.app/Contents/Resources/wine/bin/wine"
+ if !FileManager.default.isExecutableFile(atPath: local) && !FileManager.default.isExecutableFile(atPath: stable) {
+ return "Install Steam in Platforms to prepare its Windows environment."
+ }
+ } else {
+ if !FileManager.default.isExecutableFile(atPath: base.appendingPathComponent("cx26-engine/bin/wine").path) {
+ return "Install this platform to prepare its Windows environment."
+ }
+ if !FileManager.default.fileExists(atPath: base.appendingPathComponent("cx26-engine/lib/external/libd3dshared.dylib").path) {
+ return "Add Apple's Game Porting Toolkit in Platforms before playing."
+ }
+ }
+ return nil
+ }
+ func play(_ game: InstalledGame) {
+ guard !busy, !launchingGames.contains(game.id) else { return }
+ if let issue = launchIssue(for: game) { libraryIssue = issue; return }
+ do {
+ let (p, url) = try task(["game", game.id], logName: "game-" + game.id.replacingOccurrences(of: ":", with: "-"))
+ launchingGames.insert(game.id); gameLaunches[game.id] = p
+ p.terminationHandler = { [weak self] process in
+ DispatchQueue.main.async {
+ guard let self else { return }
+ if self.gameLaunches[game.id] === process {
+ self.gameLaunches.removeValue(forKey: game.id)
+ self.launchingGames.remove(game.id)
+ }
+ if process.terminationStatus != 0 {
+ self.libraryIssue = "Could not launch " + game.title + ". Use Diagnose or open " + game.platform.title + " to check its installation and login."
+ if !self.busy {
+ self.failed = true; self.activity = game.title + " needs attention."
+ if let data = try? Data(contentsOf: url) { self.log = String(decoding: data.suffix(60000), as: UTF8.self) }
+ }
+ }
+ }
+ }
+ try p.run()
+ failed = false
+ preferences.opened[game.id] = Date(); savePreferences()
+ activity = "Opening " + game.title + " through " + game.platform.title + "…"
+ // Clients may stay alive for hours: this is a launch request, not a game-running signal.
+ DispatchQueue.main.asyncAfter(deadline: .now() + 8) { [weak self, weak p] in
+ guard let self, let p, self.gameLaunches[game.id] === p else { return }
+ self.launchingGames.remove(game.id)
+ }
+ } catch {
+ launchingGames.remove(game.id); gameLaunches.removeValue(forKey: game.id)
+ libraryIssue = "Could not start the game: " + error.localizedDescription
+ }
+ }
+}
+
+private extension Launcher {
+ var accent: Color {
+ switch self {
+ case .battlenet: return Color(red: 0.28, green: 0.63, blue: 0.91)
+ case .steam: return Color(red: 0.36, green: 0.67, blue: 0.77)
+ case .epic: return Color(red: 0.82, green: 0.64, blue: 0.40)
+ case .gog: return Color(red: 0.70, green: 0.47, blue: 0.87)
+ }
+ }
+}
+
+struct LibraryView: View {
+ @EnvironmentObject var model: SojuModel
+ @State private var page = "library"
+ @State private var query = ""
+ @State private var platform = "all"
+ @State private var order = "name"
+ @State private var selected: InstalledGame?
+ @State private var showDiagnostics = false
+ @Environment(\.colorScheme) private var scheme
+ private var green: Color { scheme == .dark ? Color(red: 0.42, green: 0.83, blue: 0.67) : Color(red: 0.12, green: 0.34, blue: 0.28) }
+ private var visibleGames: [InstalledGame] {
+ model.games.filter {
+ (page != "favorites" || model.preferences.favorites.contains($0.id)) &&
+ (platform == "all" || $0.platform.rawValue == platform) &&
+ (query.isEmpty || $0.title.localizedStandardContains(query))
+ }.sorted {
+ if order == "recent" {
+ let a = model.preferences.opened[$0.id] ?? .distantPast
+ let b = model.preferences.opened[$1.id] ?? .distantPast
+ if a != b { return a > b }
+ }
+ let comparison = $0.title.localizedStandardCompare($1.title)
+ return comparison == .orderedSame ? $0.id < $1.id : comparison == .orderedAscending
+ }
+ }
+
+ var body: some View {
+ HStack(spacing: 0) {
+ sidebar
+ Divider()
+ if page == "platforms" { PlatformsView().frame(maxWidth: .infinity, maxHeight: .infinity) }
+ else { library }
+ }
+ .frame(minWidth: 1010, minHeight: 710)
+ .background(Color(nsColor: .windowBackgroundColor))
+ .sheet(item: $selected) { game in detail(game) }
+ .sheet(isPresented: $showDiagnostics) { diagnostics }
+ .alert("Game needs attention", isPresented: Binding(get: { model.libraryIssue != nil }, set: { if !$0 { model.libraryIssue = nil } })) {
+ Button("View details") { model.libraryIssue = nil; showDiagnostics = true }
+ Button("OK", role: .cancel) { model.libraryIssue = nil }
+ } message: { Text(model.libraryIssue ?? "") }
+ .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
+ model.refresh(); model.refreshLibrary()
+ }
+ }
+
+ private var sidebar: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ HStack(spacing: 10) {
+ Image(systemName: "leaf.fill").font(.title2).foregroundStyle(green)
+ Text("Soju").font(.system(size: 26, weight: .bold, design: .rounded))
+ }.padding(.bottom, 4).padding(.top, 16)
+ Text("ALL YOUR GAMES. ONE HOME.")
+ .font(.system(size: 8, weight: .semibold)).tracking(1).foregroundStyle(.secondary).padding(.bottom, 30)
+ nav("library", "Library", "square.grid.2x2", count: model.games.count)
+ nav("favorites", "Favorites", "star", count: model.games.filter { model.preferences.favorites.contains($0.id) }.count)
+ Divider().padding(.vertical, 16)
+ nav("platforms", "Platforms", "square.stack.3d.up", count: nil)
+ Spacer()
+ VStack(alignment: .leading, spacing: 9) {
+ Label("On your Mac", systemImage: "desktopcomputer").font(.system(size: 12, weight: .medium))
+ Text("Installed games appear automatically. Your accounts stay with each platform.")
+ .font(.system(size: 11)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ }.padding(13).background(green.opacity(0.07), in: RoundedRectangle(cornerRadius: 12))
+ HStack {
+ Text("v" + model.version).foregroundStyle(.secondary)
+ Spacer()
+ Button { NSWorkspace.shared.open(URL(string: "https://github.com/BCD1210/soju/releases")!) } label: {
+ Image(systemName: "arrow.up.right.square")
+ }.buttonStyle(.plain).help("Project and app updates")
+ }.font(.system(size: 11)).padding(.top, 14)
+ }.padding(20).frame(width: 205).background(Color.primary.opacity(0.025))
+ }
+ private func nav(_ id: String, _ title: String, _ symbol: String, count: Int?) -> some View {
+ Button {
+ page = id
+ } label: {
+ HStack(spacing: 11) {
+ Image(systemName: symbol).frame(width: 18)
+ Text(title)
+ Spacer()
+ if let count { Text(String(count)).font(.system(size: 11)).opacity(0.65) }
+ }.font(.system(size: 13, weight: page == id ? .semibold : .regular))
+ .padding(.horizontal, 11).padding(.vertical, 11).contentShape(Rectangle())
+ .background(page == id ? green.opacity(0.13) : .clear, in: RoundedRectangle(cornerRadius: 9))
+ .foregroundStyle(page == id ? green : Color.primary)
+ }.buttonStyle(.plain).accessibilityLabel(title)
+ }
+ private var library: some View {
+ VStack(alignment: .leading, spacing: 20) {
+ HStack(alignment: .center) {
+ VStack(alignment: .leading, spacing: 7) {
+ Text(page == "favorites" ? "Your favorites" : "Your library")
+ .font(.system(size: 30, weight: .bold, design: .rounded))
+ Text("Pick a game. We’ll open the right launcher.").font(.system(size: 13)).foregroundStyle(.secondary)
+ }
+ Spacer()
+ Button {
+ model.refresh(); model.refreshLibrary()
+ } label: {
+ Label(model.scanning ? "Scanning…" : "Refresh", systemImage: "arrow.clockwise")
+ }.disabled(model.scanning || model.busy).help("Rescan local installation records")
+ }
+ HStack(spacing: 12) {
+ HStack(spacing: 8) {
+ Image(systemName: "magnifyingglass").foregroundStyle(.secondary)
+ TextField("Search your games", text: $query).textFieldStyle(.plain)
+ .accessibilityLabel("Search games")
+ if !query.isEmpty { Button { query = "" } label: { Image(systemName: "xmark.circle.fill") }.buttonStyle(.plain) }
+ }.padding(10).background(Color.primary.opacity(0.05), in: RoundedRectangle(cornerRadius: 9))
+ Picker("Platform", selection: $platform) {
+ Text("All platforms").tag("all")
+ ForEach(Launcher.allCases) { Text($0.title).tag($0.rawValue) }
+ }.labelsHidden().frame(width: 150).accessibilityLabel("Filter by platform")
+ Picker("Sort", selection: $order) {
+ Text("Name").tag("name")
+ Text("Recently opened").tag("recent")
+ }.labelsHidden().frame(width: 145).accessibilityLabel("Sort games")
+ }
+ if !model.scanWarnings.isEmpty {
+ Label(model.scanWarnings.joined(separator: "\n"), systemImage: "exclamationmark.triangle")
+ .font(.system(size: 11)).foregroundStyle(.orange).textSelection(.enabled)
+ }
+ if visibleGames.isEmpty {
+ Spacer()
+ VStack(spacing: 14) {
+ Image(systemName: model.scanning ? "arrow.clockwise" : page == "favorites" ? "star" : "gamecontroller")
+ .font(.system(size: 44, weight: .light)).foregroundStyle(green)
+ Text(model.scanning ? "Finding your games…" : model.games.isEmpty ? "Your library starts here" : "No games to show")
+ .font(.system(size: 21, weight: .semibold))
+ Text(model.games.isEmpty ? "Install a game through one of your platforms, then refresh.\nThis library shows games installed in Soju’s Windows environments." : page == "favorites" ? "Star a game in your library to keep it here." : "Try another search or platform filter.")
+ .font(.system(size: 12)).foregroundStyle(.secondary).multilineTextAlignment(.center)
+ Button(model.games.isEmpty ? "Manage platforms" : "Show all games") {
+ if model.games.isEmpty { page = "platforms" }
+ else { page = "library"; query = ""; platform = "all" }
+ }.buttonStyle(.borderedProminent).tint(green)
+ }.frame(maxWidth: .infinity)
+ Spacer()
+ } else {
+ ScrollView {
+ LazyVGrid(columns: [GridItem(.adaptive(minimum: 180, maximum: 280), spacing: 18)], spacing: 20) {
+ ForEach(visibleGames) { game in gameCard(game) }
+ }.padding(.vertical, 3)
+ }
+ }
+ HStack(spacing: 8) {
+ Circle().fill(model.failed ? Color.orange : green).frame(width: 5, height: 5)
+ Text(model.activity == "Ready when you are." ? "\(model.games.count) installed games · Stored locally" : model.activity)
+ .lineLimit(1)
+ Spacer()
+ Button("Diagnostics") { showDiagnostics = true }.buttonStyle(.plain)
+ }.font(.system(size: 11)).foregroundStyle(.secondary)
+ }.padding(28).frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+
+ private func gameCard(_ game: InstalledGame) -> some View {
+ let issue = model.launchIssue(for: game)
+ return VStack(alignment: .leading, spacing: 0) {
+ Button { selected = game } label: { GameArtwork(game: game).frame(height: 205).clipped() }
+ .buttonStyle(.plain).accessibilityLabel("Details for " + game.title)
+ VStack(alignment: .leading, spacing: 11) {
+ HStack(spacing: 5) {
+ Circle().fill(game.platform.accent).frame(width: 5, height: 5)
+ Text(game.platform.title.uppercased()).font(.system(size: 9, weight: .bold)).tracking(0.7).foregroundStyle(.secondary)
+ Spacer()
+ Button { model.favorite(game) } label: {
+ Image(systemName: model.preferences.favorites.contains(game.id) ? "star.fill" : "star")
+ .foregroundStyle(model.preferences.favorites.contains(game.id) ? Color.yellow : Color.secondary)
+ }.buttonStyle(.plain).accessibilityLabel((model.preferences.favorites.contains(game.id) ? "Unfavorite " : "Favorite ") + game.title)
+ }
+ Text(game.title).font(.system(size: 14, weight: .semibold)).lineLimit(2)
+ .frame(height: 36, alignment: .topLeading).frame(maxWidth: .infinity, alignment: .leading)
+ HStack {
+ Text(issue == nil ? "Installed" : "Needs attention").font(.system(size: 10))
+ .foregroundStyle(issue == nil ? Color.secondary : Color.orange)
+ Spacer()
+ Button {
+ if issue == nil { model.play(game) } else { selected = game }
+ } label: {
+ Label(model.launchingGames.contains(game.id) ? "Starting…" : issue == nil ? "Play" : "Details", systemImage: issue == nil ? "play.fill" : "exclamationmark.circle")
+ }.buttonStyle(.borderedProminent).tint(green).controlSize(.small)
+ .disabled(model.busy || model.launchingGames.contains(game.id))
+ .accessibilityLabel((issue == nil ? "Play " : "Check ") + game.title)
+ }
+ }.padding(14)
+ }.background(Color(nsColor: .controlBackgroundColor), in: RoundedRectangle(cornerRadius: 14))
+ .clipShape(RoundedRectangle(cornerRadius: 14))
+ .overlay(RoundedRectangle(cornerRadius: 14).stroke(Color.primary.opacity(0.07), lineWidth: 1))
+ .contextMenu {
+ Button("Show details") { selected = game }
+ Button("Show in Finder") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: game.installPath) }
+ Button("Open " + game.platform.title) { model.launch(game.platform) }.disabled(model.busy)
+ Button("Diagnose") { diagnose(game) }.disabled(model.busy)
+ }
+ }
+
+ private func diagnose(_ game: InstalledGame) {
+ selected = nil
+ model.run(["game-doctor", game.id], title: "Checking " + game.title + "…")
+ showDiagnostics = true
+ }
+ private func detail(_ game: InstalledGame) -> some View {
+ VStack(alignment: .leading, spacing: 20) {
+ HStack(alignment: .top, spacing: 22) {
+ GameArtwork(game: game).frame(width: 165, height: 225).clipped().clipShape(RoundedRectangle(cornerRadius: 12))
+ VStack(alignment: .leading, spacing: 13) {
+ Text(game.platform.title).font(.system(size: 11, weight: .semibold)).foregroundStyle(game.platform.accent)
+ Text(game.title).font(.system(size: 24, weight: .bold, design: .rounded))
+ Label("Installed on this Mac", systemImage: "internaldrive").font(.system(size: 12)).foregroundStyle(.secondary)
+ Text("Opens through " + game.platform.title + ". You may need to sign in or finish an update in the launcher.")
+ .font(.system(size: 12)).foregroundStyle(.secondary)
+ if let issue = model.launchIssue(for: game) {
+ Label(issue, systemImage: "exclamationmark.triangle").font(.system(size: 12)).foregroundStyle(.orange)
+ }
+ Text("Installation detected. Compatibility varies by game and Mac.")
+ .font(.system(size: 11)).foregroundStyle(.secondary)
+ Spacer()
+ }
+ }
+ HStack {
+ Button("Show files") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: game.installPath) }
+ Button("Diagnose") { diagnose(game) }.disabled(model.busy)
+ Button("Open " + game.platform.title) { model.launch(game.platform) }.disabled(model.busy)
+ Spacer()
+ }
+ Divider()
+ HStack {
+ Button("Platforms") { selected = nil; page = "platforms" }
+ Spacer()
+ Button("Close") { selected = nil }.keyboardShortcut(.cancelAction)
+ Button("Play") { selected = nil; model.play(game) }
+ .buttonStyle(.borderedProminent).tint(green)
+ .disabled(model.busy || model.launchIssue(for: game) != nil || model.launchingGames.contains(game.id))
+ }
+ }.padding(28).frame(width: 640)
+ }
+ private var diagnostics: some View {
+ VStack(alignment: .leading, spacing: 16) {
+ HStack {
+ Text("Diagnostics").font(.title2.bold())
+ Spacer()
+ Button("Done") { showDiagnostics = false }.keyboardShortcut(.cancelAction)
+ }
+ HStack {
+ if model.busy { ProgressView().controlSize(.small) }
+ Text(model.activity).font(.system(size: 12)).foregroundStyle(model.failed ? Color.orange : Color.secondary)
+ }
+ ScrollView {
+ Text(model.log).font(.system(size: 11, design: .monospaced)).textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }.padding(12).background(Color.primary.opacity(0.04), in: RoundedRectangle(cornerRadius: 9))
+ HStack {
+ Button("Check all platforms") { model.run(["doctor"], title: "Checking your setup…") }.disabled(model.busy)
+ Spacer()
+ Button("Copy log", action: model.copyLog)
+ Button("Open logs") { NSWorkspace.shared.open(model.base.appendingPathComponent("logs")) }
+ }
+ }.padding(24).frame(width: 720, height: 480)
+ }
+}
+
+struct GameArtwork: View {
+ let game: InstalledGame
+ @State private var artwork: NSImage?
+ private static let cache: NSCache<NSString, NSImage> = {
+ let value = NSCache<NSString, NSImage>(); value.countLimit = 150
+ value.totalCostLimit = 64 * 1024 * 1024; return value
+ }()
+ var body: some View {
+ ZStack {
+ LinearGradient(colors: [game.platform.accent.opacity(0.55), Color(red: 0.06, green: 0.09, blue: 0.13)], startPoint: .topLeading, endPoint: .bottomTrailing)
+ if let artwork {
+ if game.artwork?.lowercased().hasSuffix(".ico") == true {
+ Image(nsImage: artwork).resizable().scaledToFit().padding(38).shadow(color: .black.opacity(0.35), radius: 16, y: 8)
+ } else {
+ GeometryReader { proxy in
+ Image(nsImage: artwork).resizable().scaledToFill().frame(width: proxy.size.width, height: proxy.size.height).clipped()
+ }
+ }
+ } else {
+ VStack(spacing: 18) {
+ Image(systemName: game.platform.symbol).font(.system(size: 38, weight: .light)).opacity(0.75)
+ Text(game.title).font(.system(size: 20, weight: .bold, design: .rounded)).multilineTextAlignment(.center).lineLimit(3)
+ }.foregroundStyle(.white).padding(22)
+ }
+ }.accessibilityHidden(true)
+ .task(id: game.artwork) {
+ artwork = nil
+ guard let path = game.artwork else { return }
+ if let cached = Self.cache.object(forKey: path as NSString) { artwork = cached; return }
+ let result: NSImage? = await Task.detached(priority: .utility) {
+ guard let attributes = try? FileManager.default.attributesOfItem(atPath: path),
+ let size = attributes[.size] as? NSNumber, size.intValue < 16 * 1024 * 1024 else { return nil }
+ return NSImage(contentsOfFile: path)
+ }.value
+ guard !Task.isCancelled else { return }
+ if let result { Self.cache.setObject(result, forKey: path as NSString, cost: Int(result.size.width * result.size.height * 4)) }
+ artwork = result
+ }
+ }
+}
diff --git a/app/Soju.swift b/app/Soju.swift
index a9a45b6e684..4ca7c30fff6 100644
--- a/app/Soju.swift
+++ b/app/Soju.swift
@@ -34,6 +34,14 @@ enum Launcher: String, CaseIterable, Identifiable {
}
@MainActor final class SojuModel: ObservableObject {
+ @Published var games: [InstalledGame] = []
+ @Published var scanning = false
+ @Published var scanWarnings: [String] = []
+ @Published var launchingGames: Set<String> = []
+ @Published var libraryIssue: String?
+ @Published var preferences = LibraryPreferences.load()
+ var gameLaunches: [String: Process] = [:]
+ var scanner: Process?
@Published var installed: Set<Launcher> = []
@Published var busy = false
@Published var activity = "Ready when you are."
@@ -49,7 +57,7 @@ enum Launcher: String, CaseIterable, Identifiable {
private var poller: Timer?
var version: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "dev" }
- init() { refresh() }
+ init() { refresh(); refreshLibrary() }
func refresh() {
installed = Set(Launcher.allCases.filter {
@@ -57,7 +65,7 @@ enum Launcher: String, CaseIterable, Identifiable {
})
}
- private func task(_ args: [String], logName: String) throws -> (Process, URL) {
+ func task(_ args: [String], logName: String) throws -> (Process, URL) {
let dir = base.appendingPathComponent("logs")
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let url = dir.appendingPathComponent(logName + ".log")
@@ -96,7 +104,7 @@ enum Launcher: String, CaseIterable, Identifiable {
self.busy = false; self.operation = nil
self.failed = process.terminationStatus != 0
self.activity = self.failed ? "Needs attention — see the details below." : "Finished."
- self.refresh()
+ self.refresh(); self.refreshLibrary()
}
}
try p.run()
@@ -138,7 +146,7 @@ enum Launcher: String, CaseIterable, Identifiable {
self.failed = true; self.activity = launcher.title + " needs attention."
if let data = try? Data(contentsOf: url) { self.log = String(decoding: data.suffix(60000), as: UTF8.self) }
}
- self.refresh()
+ self.refresh(); self.refreshLibrary()
}
}
try p.run()
@@ -166,7 +174,7 @@ enum Launcher: String, CaseIterable, Identifiable {
}
}
-struct SojuView: View {
+struct PlatformsView: View {
@EnvironmentObject var model: SojuModel
@Environment(\.colorScheme) private var scheme
private var green: Color { scheme == .dark ? Color(red: 0.42, green: 0.83, blue: 0.67) : Color(red: 0.12, green: 0.34, blue: 0.28) }
@@ -183,7 +191,7 @@ struct SojuView: View {
.padding(.horizontal, 9).padding(.vertical, 5)
.background(green.opacity(0.09), in: Capsule()).foregroundStyle(green)
}
- Text("Your Windows launchers. At home on your Mac.").foregroundStyle(.secondary)
+ Text("Install and manage your official Windows launchers.").foregroundStyle(.secondary)
}
Spacer()
Menu {
@@ -230,11 +238,11 @@ struct SojuView: View {
}
}.padding(14).background(Color.primary.opacity(0.035), in: RoundedRectangle(cornerRadius: 12))
HStack {
- Text("Steam installs without Apple GPTK. Each launcher keeps its own library and login.")
+ Text("Accounts, purchases and updates stay with each official launcher.")
Spacer()
Text("v" + model.version)
}.font(.system(size: 10)).foregroundStyle(.secondary)
- }.padding(28).frame(minWidth: 820, idealWidth: 900, minHeight: 650, idealHeight: 720)
+ }.padding(28).frame(minWidth: 730, idealWidth: 850, minHeight: 610, idealHeight: 680)
.background(Color(nsColor: .windowBackgroundColor))
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in model.refresh() }
}
@@ -297,11 +305,11 @@ final class SojuDelegate: NSObject, NSApplicationDelegate {
@StateObject private var model = SojuModel()
var body: some Scene {
Window("Soju", id: "main") {
- SojuView().environmentObject(model).onAppear {
+ LibraryView().environmentObject(model).onAppear {
delegate.isBusy = { model.busy }
NSApp.setActivationPolicy(.regular)
NSApp.activate(ignoringOtherApps: true)
}
- }.defaultSize(width: 900, height: 720)
+ }.defaultSize(width: 1140, height: 780)
}
}
diff --git a/docs/DESKTOP.md b/docs/DESKTOP.md
index 135b89029d4..fb1d4bcfdf9 100644
--- a/docs/DESKTOP.md
+++ b/docs/DESKTOP.md
@@ -1,15 +1,17 @@
# Soju for Mac
-[Download v1.4.0](https://github.com/BCD1210/soju/releases/download/v1.4.0/Soju-1.4.0-macos-arm64.zip)
+[Download v1.5.0](https://github.com/BCD1210/soju/releases/download/v1.5.0/Soju-1.5.0-macos-arm64.zip)
1. Unzip and move **Soju.app** into Applications or ~/Applications.
-2. Open it and select Battle.net, Steam, Epic Games or GOG GALAXY.
-3. Click **Install selected**. Existing installations are detected.
-4. Use **Open**, **Diagnose**, and **Update components** from the same window.
+2. Open **Platforms** to install or open Battle.net, Steam, Epic Games or GOG GALAXY.
+3. Install games through the official clients and return to **Library**.
+4. Search, filter by platform, star favorites and click a game's **Play** button.
+ Use **Refresh** after installing a game or reconnecting an external game drive.
+5. Open a game's details for **Diagnose**, **Show files** and its official launcher.
-![Soju desktop](assets/soju-desktop.png)
+![Soju unified library](assets/soju-library.png)
-This is the first native desktop preview. The app is ad-hoc signed, not
+The app is a native desktop preview. It is ad-hoc signed, not
Developer ID signed or notarized. If macOS blocks the downloaded app, review
the source and use macOS Privacy & Security's Open Anyway flow if you trust it.
A local source build is also available: `bash scripts/install-app.sh`.
@@ -27,16 +29,43 @@ Soju does not collect telemetry or upload diagnostic logs. Copy log is manual.
For Apple GPTK, install the selected non-Steam launcher to prepare the engine,
download Apple's evaluation environment, open its DMG, then choose
-**Apple GPTK → Add mounted toolkit**. Retry installation if it stopped.
+**Platforms → Apple GPTK → Add mounted toolkit**. Retry installation if it stopped.
The official clients retain their own login, library, downloads and game updates.
Soju does not handle store passwords. Close launchers and games before updating
their runtime. Closing Soju does not force running launchers or games to quit.
+## Library scope and privacy
+
+This release detects games installed in Soju's four Windows environments:
+
+- Steam: app manifests and mapped library folders, including external drives.
+- Epic: local installation manifests, excluding DLC-only records.
+- Battle.net: Agent's product database and installed game build records.
+- GOG: Galaxy's installation database, with a fallback for standard game folders.
+
+Native Mac games, other Wine managers, uninstalled owned games, account syncing,
+store search and purchases inside Soju are outside this release's library scope.
+Unknown Battle.net product codes are shown with a shortcut to the official client;
+Soju does not guess how to launch them. **Installed** does not mean compatibility
+has been verified. Anti-cheat, game requirements, store logins and updates still apply.
+
+Artwork comes from Steam's local cache or icons already installed with games.
+Extracted icons are cached under `~/.battlenet-macos/library-artwork`.
+Favorites and recent launch requests stay in the app's local preferences.
+Scanning does not read store passwords or tokens and does not contact store APIs.
+Play sends the official launcher a request; Soju does not claim to track whether
+a game is running or how many hours were played.
+
+CLI equivalents: `soju library` prints installed games as JSON;
+`soju game <id>` launches an ID from that list. Each launch rechecks the current
+installation record. `python3 scripts/game-library.py launch <id> --dry-run`
+prints the argument list without starting a game.
+
## Updates and recovery
**Update components** checks the CX engine and configures the pinned Steam
-components. Get new app releases from the project menu → Project & releases.
+components. Get new app releases from the link at the bottom of the sidebar or Platforms → Project & releases.
The app does not replace itself automatically.
Steam uses `~/.battlenet-macos/steam-runtime`; Homebrew's Wine app is preserved.
diff --git a/docs/assets/soju-library.png b/docs/assets/soju-library.png
new file mode 100644
index 00000000000..7313647e163
Binary files /dev/null and b/docs/assets/soju-library.png differ
diff --git a/docs/index.html b/docs/index.html
index 40b0f685a86..7005428a2c1 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -3,17 +3,17 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
-<title>Soju — Free, open-source game launcher toolkit for Apple Silicon Macs</title>
-<meta name="description" content="Set up Battle.net, Steam, Epic Games Launcher and GOG GALAXY on Apple Silicon with Soju, a free, open-source launcher toolkit. Separate Wine environments, Mac launch shortcuts, and documented fixes.">
+<title>Soju — Free, open-source game library for Apple Silicon Macs</title>
+<meta name="description" content="One native Mac library for games installed through Battle.net, Steam, Epic and GOG. Search, favorite, launch and diagnose games on Apple Silicon with Soju.">
<link rel="canonical" href="https://bcd1210.github.io/soju/">
-<meta property="og:title" content="Soju — Your Windows launchers, on your Mac">
+<meta property="og:title" content="Soju — Your games, one home on your Mac">
<meta property="og:description" content="A free, open-source launcher toolkit for Apple Silicon. Battle.net, Steam, Epic and GOG — with documented setup and compatibility.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://bcd1210.github.io/soju/">
<meta name="twitter:card" content="summary_large_image">
-<meta property="og:image" content="https://bcd1210.github.io/soju/assets/soju-launcher-demo-poster.jpg">
-<meta property="og:image:alt" content="Soju launcher preview with a real Epic Games Launcher capture">
-<meta name="twitter:image" content="https://bcd1210.github.io/soju/assets/soju-launcher-demo-poster.jpg">
+<meta property="og:image" content="https://bcd1210.github.io/soju/assets/soju-library.png">
+<meta property="og:image:alt" content="Soju unified library with installed Battle.net, Steam, Epic and GOG games">
+<meta name="twitter:image" content="https://bcd1210.github.io/soju/assets/soju-library.png">
<meta name="twitter:title" content="Soju — Open-source game launching for Mac">
<meta name="twitter:description" content="Set up Battle.net, Steam, Epic and GOG on Apple Silicon. Free launcher tools, separate Wine environments, and tested game examples.">
<link rel="stylesheet" href="style.css">
@@ -31,15 +31,21 @@
<main>
<header class="hero">
<p class="eyebrow">FREE &amp; OPEN SOURCE · APPLE SILICON</p>
-<h1>Your Windows launchers.<br>On your Mac.</h1>
-<p class="lead">Soju is an open-source game launcher toolkit for Apple Silicon.
-Set up Battle.net, Steam, Epic Games Launcher and GOG GALAXY, sign in to your
-existing accounts, and play supported Windows games.</p>
-<p>Terminal setup. A separate Mac launch app for each launcher.
-Choose the stores you use; Soju keeps their Wine environments separate.</p>
+<h1>Your games.<br>One home on your Mac.</h1>
+<p class="lead">A free, open-source game library for Apple Silicon.
+Find installed games from Battle.net, Steam, Epic and GOG in one native Mac app.
+Search your library, save favorites and play through the official launchers.</p>
+<p>Set up and manage your platforms in Soju. Accounts, purchases and game updates
+stay with each store. Compatibility depends on the game and your Mac.</p>
<div class="actions"><a class="btn" href="#install">Install Soju</a>
<a href="https://github.com/BCD1210/soju">Explore the source</a></div>
</header>
+<section id="library" aria-labelledby="library-title">
+<h2 id="library-title">Installed games, together.</h2>
+<p>Local detection, platform filters, favorites and game-specific diagnostics.
+No new Soju account. No library uploads. Uninstalled owned games and store search are planned separately.</p>
+<img src="assets/soju-library.png" width="1140" height="780" style="width:100%;height:auto;border-radius:16px" alt="Soju's unified library showing four installed games across Battle.net, Steam, Epic and GOG">
+</section>
<section id="demo" aria-labelledby="demo-title">
<h2 id="demo-title">See the games running on a Mac.</h2>
@@ -76,14 +82,14 @@ poster="assets/soju-launcher-demo-poster.jpg" aria-label="Soju launcher preview"
<article class="platform"><h3>Epic Games Launcher</h3><p>Sign in, install games and return to the launcher from its tray.</p><code>soju epic</code></article>
<article class="platform"><h3>GOG GALAXY</h3><p>Access your account and library. Game compatibility is still being explored.</p><code>soju gog</code></article>
</div>
-<p class="note">Soju provides setup tools and launcher-specific Mac apps.
-You use each store's own interface and library.</p>
+<p class="note">Soju combines installed games in one library. Each official launcher retains
+its own login, purchases, downloads and game updates.</p>
</section>
<section id="install" aria-labelledby="install-title">
<h2 id="install-title">Choose your launchers. Get set up.</h2>
-<p><a class="btn" href="https://github.com/BCD1210/soju/releases/download/v1.4.0/Soju-1.4.0-macos-arm64.zip">Download Soju for Mac</a></p>
-<p>The native desktop preview installs, opens, updates and diagnoses all four launchers in one window.
+<p><a class="btn" href="https://github.com/BCD1210/soju/releases/download/v1.5.0/Soju-1.5.0-macos-arm64.zip">Download Soju for Mac</a></p>
+<p>The native desktop preview combines your installed games and manages all four launchers.
Apple Silicon · app UI: macOS 14+ · Steam component build: macOS 26+.
<a href="https://github.com/BCD1210/soju/blob/main/docs/DESKTOP.md">Setup and signing notes</a>.</p>
<p>Prefer the terminal? Select launchers before any downloads. Steam-only installs skip the CX engine and Apple GPTK.</p>
diff --git a/scripts/build-app.sh b/scripts/build-app.sh
index bb54f6dcc9d..8e28741ed4a 100755
--- a/scripts/build-app.sh
+++ b/scripts/build-app.sh
@@ -10,7 +10,7 @@ trap 'rm -rf "$STAGE"' EXIT
APP="$STAGE/Soju.app"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/soju"
swiftc -swift-version 5 -parse-as-library -O -target arm64-apple-macosx14.0 \
- "$ROOT/app/Soju.swift" -o "$APP/Contents/MacOS/Soju"
+ "$ROOT/app/Soju.swift" "$ROOT/app/Library.swift" -o "$APP/Contents/MacOS/Soju"
for dir in scripts tools patches third_party resources; do
ditto "$ROOT/$dir" "$APP/Contents/Resources/soju/$dir"
done
diff --git a/scripts/desktop-action.sh b/scripts/desktop-action.sh
index 0bd47e54a52..e305cd301ea 100755
--- a/scripts/desktop-action.sh
+++ b/scripts/desktop-action.sh
@@ -6,6 +6,9 @@ BASE="${SOJU_BASE:-$HOME/.battlenet-macos}"
export SOJU_BASE="$BASE"
ACTION="${1:-}"; shift || true
case "$ACTION" in
+ library) exec python3 "$ROOT/scripts/game-library.py" list ;;
+ game) exec python3 "$ROOT/scripts/game-library.py" launch "${1:?Choose a game}" ;;
+ game-doctor) exec python3 "$ROOT/scripts/game-library.py" diagnose "${1:?Choose a game}" ;;
doctor) exec bash "$ROOT/scripts/doctor.sh" "$@" ;;
launch)
case "${1:-}" in battlenet|steam|epic|gog) exec bash "$ROOT/scripts/play.sh" "$1" ;;
diff --git a/scripts/game-library.py b/scripts/game-library.py
new file mode 100644
index 00000000000..df34c7484e4
--- /dev/null
+++ b/scripts/game-library.py
@@ -0,0 +1,332 @@
+#!/usr/bin/env python3
+"""Read installed games locally. No account APIs, tokens, telemetry or network.
+
+Launches are reconstructed from current manifests, never from a cached command.
+All launcher arguments are passed as an argv array without a shell.
+"""
+import argparse
+import json
+import os
+from pathlib import Path, PureWindowsPath
+import re
+import sqlite3
+import sys
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from game_artwork import executable_icon
+from urllib.parse import quote
+
+FOLDERS = {'steam': 'steam-bottle', 'epic': 'epic-bottle',
+ 'battlenet': 'bottle', 'gog': 'gog-bottle'}
+CLIENTS = {
+ 'steam': 'Program Files (x86)/Steam/steam.exe',
+ 'epic': 'Program Files/Epic Games/Launcher/Portal/Binaries/Win64/EpicGamesLauncher.exe',
+ 'battlenet': 'Program Files (x86)/Battle.net/Battle.net.exe',
+ 'gog': 'Program Files/GOG Galaxy/GalaxyClient.exe',
+}
+# Product UIDs differ from the Battle.net launch command's product codes.
+BNET = {
+ 'osi': ('Diablo II: Resurrected', 'OSI'),
+ 'diablo3': ('Diablo III', 'D3'), 'fen': ('Diablo IV', 'Fen'),
+ 'wow': ('World of Warcraft', 'WoW'),
+ 's2': ('StarCraft II', 'S2'), 's1': ('StarCraft: Remastered', 'S1'),
+ 'w3': ('Warcraft III', 'W3'), 'hs_beta': ('Hearthstone', 'WTCG'),
+ 'heroes': ('Heroes of the Storm', 'Hero'), 'prometheus': ('Overwatch 2', 'Pro'),
+}
+MAX_METADATA = 16 * 1024 * 1024
+
+
+def read_bytes(path):
+ with path.open('rb') as stream:
+ data = stream.read(MAX_METADATA + 1)
+ if len(data) > MAX_METADATA:
+ raise ValueError('metadata is too large')
+ return data
+
+
+def read_json(path):
+ value = json.loads(read_bytes(path).decode('utf-8-sig'))
+ if not isinstance(value, dict):
+ raise ValueError('expected a metadata object')
+ return value
+
+
+def case_path(root, parts):
+ """Resolve Windows' case-insensitive filenames on a case-sensitive volume."""
+ for part in parts:
+ if part in ('', '.'):
+ continue
+ if part == '..' or '\x00' in part:
+ raise ValueError('invalid path component')
+ target = root / part
+ if not target.exists() and root.is_dir():
+ target = next((p for p in root.iterdir() if p.name.casefold() == part.casefold()), target)
+ root = target
+ return root
+
+
+def windows_path(prefix, text):
+ if not isinstance(text, str) or not text or '\x00' in text:
+ raise ValueError('missing Windows path')
+ p = PureWindowsPath(text)
+ if not re.fullmatch(r'[A-Za-z]:', p.drive) or not p.root:
+ raise ValueError('expected an absolute mapped Windows drive')
+ drive = p.drive[0].lower()
+ root = prefix / 'drive_c' if drive == 'c' else prefix / 'dosdevices' / (drive + ':')
+ return case_path(root, p.parts[1:])
+
+
+def vdf(data):
+ # Steam KeyValues: quoted strings, escaped quotes/backslashes, comments, objects.
+ tokens = re.findall(r'"(?:\\.|[^"\\])*"|[{}]|//[^\n]*|[^\s{}"]+', data)
+ tokens = [t for t in tokens if not t.startswith('//')]
+ at = 0
+ def value(t):
+ if t.startswith('"'):
+ return re.sub(r'\\(["\\])', r'\1', t[1:-1])
+ return t
+ def obj(depth=0, nested=False):
+ nonlocal at
+ if depth > 32:
+ raise ValueError('KeyValues nesting too deep')
+ result = {}
+ while at < len(tokens):
+ key = tokens[at]; at += 1
+ if key == '}':
+ if not nested: raise ValueError('unexpected closing brace')
+ return result
+ if key == '{' or at == len(tokens): raise ValueError('invalid KeyValues')
+ item = tokens[at]; at += 1
+ if item == '}': raise ValueError('missing value')
+ result[value(key)] = obj(depth + 1, True) if item == '{' else value(item)
+ if nested: raise ValueError('unclosed KeyValues object')
+ return result
+ return obj()
+
+
+def protobuf(data):
+ """Bounded wire reader for Agent's local ProductDb (no generated dependency)."""
+ at = 0
+ def integer():
+ nonlocal at
+ n = 0
+ for shift in range(0, 70, 7):
+ if at >= len(data): raise ValueError('truncated protobuf')
+ c = data[at]; at += 1; n |= (c & 127) << shift
+ if c < 128: return n
+ raise ValueError('invalid varint')
+ result = {}
+ while at < len(data):
+ tag = integer(); field, wire = tag >> 3, tag & 7
+ if not field: raise ValueError('invalid protobuf field')
+ if wire == 0: item = integer()
+ elif wire in (1, 2, 5):
+ size = integer() if wire == 2 else (8 if wire == 1 else 4)
+ if size > len(data) - at: raise ValueError('truncated protobuf value')
+ item = data[at:at + size]; at += size
+ else: raise ValueError('unsupported protobuf wire type')
+ result.setdefault(field, []).append(item)
+ return result
+
+
+def first_file(paths):
+ return next((str(p) for p in paths if p.is_file()), None)
+
+
+class Library:
+ def __init__(self, base):
+ self.base = Path(base).expanduser().absolute()
+ self.games = {}
+ self.warnings = []
+
+ def warn(self, platform, message):
+ text = platform + ': ' + message
+ if text not in self.warnings: self.warnings.append(text)
+
+ def add(self, platform, uid, title, location, arguments, artwork=None, ready=True):
+ if not isinstance(uid, str) or not re.fullmatch(r'[A-Za-z0-9_.:-]{1,200}', uid):
+ raise ValueError('invalid game identifier')
+ if not isinstance(title, str) or not title.strip(): raise ValueError('missing game name')
+ if not location.is_dir(): return
+ key = platform + ':' + uid
+ issue = None
+ prefix = self.base / FOLDERS[platform]
+ if not (prefix / 'drive_c' / CLIENTS[platform]).is_file():
+ issue = 'Install this platform in Platforms, then try again.'
+ elif not ready: issue = 'Finish the installation or update in the official launcher.'
+ elif not arguments: issue = 'Open the official launcher to play this title.'
+ self.games[key] = dict(id=key, platform=platform, title=title.strip()[:300],
+ install_path=str(location), artwork=artwork,
+ issue=issue, arguments=arguments)
+
+ def steam(self):
+ prefix = self.base / FOLDERS['steam']
+ client = prefix / 'drive_c/Program Files (x86)/Steam'
+ roots = {client}
+ for f in [client / 'steamapps/libraryfolders.vdf', client / 'config/libraryfolders.vdf']:
+ if not f.is_file(): continue
+ try:
+ for key, item in vdf(read_bytes(f).decode('utf-8-sig'))['libraryfolders'].items():
+ if key.isdigit():
+ roots.add(windows_path(prefix, item['path'] if isinstance(item, dict) else item))
+ except (OSError, ValueError, KeyError, TypeError, AttributeError):
+ self.warn('steam', 'Some library folders could not be read. Open Steam and refresh.')
+ for root in sorted(roots):
+ if root != client and not root.is_dir():
+ self.warn('steam', 'A library drive is unavailable. Reconnect it and refresh.')
+ for f in sorted((root / 'steamapps').glob('appmanifest_*.acf')):
+ try:
+ item = vdf(read_bytes(f).decode('utf-8-sig'))['AppState']
+ uid = item['appid']
+ if not uid.isdigit() or f.stem != 'appmanifest_' + uid:
+ raise ValueError('mismatched Steam app ID')
+ location = case_path(root / 'steamapps/common', PureWindowsPath(item['installdir']).parts)
+ if PureWindowsPath(item['installdir']).drive: raise ValueError('invalid relative path')
+ artroot = client / 'appcache/librarycache'
+ art = first_file([artroot / uid / 'library_600x900.jpg',
+ artroot / (uid + '_library_600x900.jpg'),
+ artroot / uid / 'header.jpg', artroot / (uid + '_header.jpg')])
+ ready = bool(int(item.get('StateFlags', '0')) & 4)
+ self.add('steam', uid, item['name'], location, ['steam://rungameid/' + uid], art, ready)
+ except (OSError, ValueError, KeyError, TypeError, AttributeError):
+ self.warn('steam', 'An installation record could not be read. Refresh after Steam finishes updating.')
+
+ def epic(self):
+ prefix = self.base / FOLDERS['epic']
+ manifests = prefix / 'drive_c/ProgramData/Epic/EpicGamesLauncher/Data/Manifests'
+ for f in sorted(manifests.glob('*.item')):
+ try:
+ item = read_json(f)
+ uid = item['AppName']
+ if item.get('MainGameAppName') not in (None, '', uid): continue # DLC
+ location = windows_path(prefix, item['InstallLocation'])
+ namespace, catalog = item.get('CatalogNamespace'), item.get('CatalogItemId')
+ parts = [namespace, catalog, uid] if namespace and catalog else [uid]
+ if any(not isinstance(p, str) for p in parts): raise ValueError('invalid Epic ID')
+ uri = 'com.epicgames.launcher://apps/' + quote(':'.join(parts), safe='')
+ uri += '?action=launch&silent=true'
+ art = first_file(sorted(location.glob('*.ico')))
+ ready = not item.get('bIsIncompleteInstall', False)
+ executable = item.get('LaunchExecutable')
+ if executable:
+ relative = PureWindowsPath(executable)
+ if relative.drive or relative.root: raise ValueError('invalid executable path')
+ exe = case_path(location, relative.parts)
+ ready = ready and exe.is_file()
+ art = art or executable_icon(exe, self.base / 'library-artwork')
+ self.add('epic', uid, item['DisplayName'], location, [uri], art, ready)
+ except (OSError, ValueError, KeyError, TypeError, AttributeError):
+ self.warn('epic', 'An installation record could not be read. Refresh after Epic finishes updating.')
+
+ def battlenet(self):
+ prefix = self.base / FOLDERS['battlenet']
+ path = prefix / 'drive_c/ProgramData/Battle.net/Agent/product.db'
+ if not path.is_file(): return
+ records = protobuf(read_bytes(path)).get(1, [])
+ for record in records:
+ try:
+ fields = protobuf(record)
+ uid = fields[1][0].decode('utf-8')
+ if uid in ('agent', 'battle.net', 'bna'): continue
+ settings = protobuf(fields[3][0])
+ location = windows_path(prefix, settings[1][0].decode('utf-8'))
+ # An Agent record can outlive an uninstall or partial download.
+ if not (location / '.build.info').is_file(): continue
+ title, code = BNET.get(uid.casefold(), (location.name, None))
+ arguments = ['--exec=launch ' + code] if code else []
+ art = first_file(sorted(location.glob('*.ico')))
+ if not art:
+ executables = [p for p in location.glob('*.exe') if not any(word in p.name.lower() for word in ('launcher', 'uninstall', 'error', 'crash'))]
+ executables.sort(key=lambda p: p.stat().st_size, reverse=True)
+ for exe in executables[:4]:
+ art = executable_icon(exe, self.base / 'library-artwork')
+ if art: break
+ self.add('battlenet', uid, title, location, arguments, art)
+ except (OSError, ValueError, KeyError, IndexError, TypeError, AttributeError):
+ self.warn('battlenet', 'An installation record could not be read. Refresh after Battle.net finishes updating.')
+
+ def gog(self):
+ prefix = self.base / FOLDERS['gog']
+ cdrive = prefix / 'drive_c'
+ entries = {}
+ database = cdrive / 'ProgramData/GOG.com/Galaxy/storage/galaxy-2.0.db'
+ if database.is_file():
+ try:
+ db = sqlite3.connect(database.as_uri() + '?mode=ro', uri=True, timeout=1)
+ try:
+ db.execute('PRAGMA query_only=ON')
+ rows = db.execute('SELECT i.productId, i.installationPath, p.name FROM InstalledBaseProducts i LEFT JOIN Products p ON p.id = i.productId').fetchall()
+ for uid, path, name in rows:
+ entries[str(uid)] = (windows_path(prefix, path), path, name)
+ finally: db.close()
+ except (sqlite3.Error, OSError, ValueError):
+ self.warn('gog', 'Galaxy installation records are unavailable; checking standard game folders.')
+ for pattern in ['GOG Games/*/goggame-*.info', 'Program Files/GOG Galaxy/Games/*/goggame-*.info',
+ 'Program Files (x86)/GOG Galaxy/Games/*/goggame-*.info']:
+ for f in cdrive.glob(pattern):
+ uid = f.stem.removeprefix('goggame-')
+ path = 'C:\\' + str(f.parent.relative_to(cdrive)).replace('/', '\\')
+ entries.setdefault(uid, (f.parent, path, f.parent.name))
+ for uid, (location, winpath, title) in entries.items():
+ try:
+ if not uid.isdigit(): raise ValueError('invalid GOG ID')
+ info = location / ('goggame-' + uid + '.info')
+ if not info.is_file(): continue
+ item = read_json(info)
+ if str(item.get('gameId')) != uid: raise ValueError('mismatched GOG ID')
+ if str(item.get('rootGameId', uid)) != uid: continue # DLC
+ title = item.get('name') or title or location.name
+ art = first_file([location / ('goggame-' + uid + '.ico')])
+ args = ['/command=runGame', '/gameId=' + uid, '/path=' + winpath]
+ self.add('gog', uid, title, location, args, art)
+ except (OSError, ValueError, KeyError, TypeError):
+ self.warn('gog', 'An installation record could not be read. Verify this game in Galaxy.')
+
+ def scan(self):
+ self.games = {}; self.warnings = []
+ for platform in FOLDERS:
+ try: getattr(self, platform)()
+ except (OSError, ValueError, KeyError, TypeError, sqlite3.Error):
+ self.warn(platform, 'Installation records are temporarily unavailable. Open the launcher and refresh.')
+ return {'games': [{k: v for k, v in g.items() if k != 'arguments'}
+ for g in sorted(self.games.values(), key=lambda g: (g['title'].casefold(), g['id']))],
+ 'warnings': self.warnings}
+
+ def command(self, game_id):
+ self.scan()
+ game = self.games.get(game_id)
+ if game is None: raise ValueError('This game is no longer installed. Refresh the library.')
+ if game['issue']: raise ValueError(game['issue'])
+ root = Path(__file__).resolve().parent
+ return ['/bin/bash', str(root / 'play.sh'), game['platform']] + game['arguments']
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('action', choices=['list', 'launch', 'diagnose'], nargs='?', default='list')
+ parser.add_argument('game_id', nargs='?')
+ parser.add_argument('--base', default=os.environ.get('SOJU_BASE', str(Path.home() / '.battlenet-macos')))
+ parser.add_argument('--dry-run', action='store_true', help='Print launch argv without starting anything')
+ args = parser.parse_args()
+ lib = Library(args.base)
+ try:
+ if args.action == 'list':
+ print(json.dumps(lib.scan(), ensure_ascii=False)); return
+ if not args.game_id: parser.error('choose a game ID from the list')
+ if args.action == 'diagnose':
+ lib.scan()
+ game = lib.games.get(args.game_id)
+ if not game: raise ValueError('This game is no longer installed. Refresh the library.')
+ print(game['title'] + ' — ' + game['platform'], flush=True)
+ print(game['issue'] or 'Installation found. Checking the platform environment…', flush=True)
+ command = ['/bin/bash', str(Path(__file__).resolve().parent / 'doctor.sh'), game['platform']]
+ else: command = lib.command(args.game_id)
+ if args.dry_run: print(json.dumps(command)); return
+ env = dict(os.environ, SOJU_BASE=str(lib.base))
+ for key in ['WINEPREFIX', 'ENGINE']: env.pop(key, None)
+ os.execve(command[0], command, env)
+ except (OSError, ValueError) as error:
+ print('soju: ' + str(error), file=sys.stderr); sys.exit(1)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/game_artwork.py b/scripts/game_artwork.py
new file mode 100644
index 00000000000..353796cbed2
--- /dev/null
+++ b/scripts/game_artwork.py
@@ -0,0 +1,76 @@
+"""Extract a game's existing Windows icon locally; never downloads artwork."""
+import hashlib
+from pathlib import Path
+import struct
+
+
+def executable_icon(executable, cache):
+ try:
+ stat = executable.stat()
+ key = hashlib.sha256((str(executable) + str(stat.st_mtime_ns) + str(stat.st_size)).encode()).hexdigest()
+ output = Path(cache) / (key + '.ico')
+ if output.is_file(): return str(output)
+ with executable.open('rb') as stream:
+ def read(at, size):
+ if at < 0 or size < 0 or size > 8 * 1024 * 1024 or at + size > stat.st_size:
+ raise ValueError('invalid PE offset')
+ stream.seek(at); data = stream.read(size)
+ if len(data) != size: raise ValueError('truncated executable')
+ return data
+ def number(at, form='<I'):
+ return struct.unpack(form, read(at, struct.calcsize(form)))[0]
+ if read(0, 2) != b'MZ': return None
+ pe = number(0x3c)
+ if read(pe, 4) != b'PE\x00\x00': return None
+ sections, optional_size = number(pe + 6, '<H'), number(pe + 20, '<H')
+ if not 1 <= sections <= 96: return None
+ optional = pe + 24
+ magic = number(optional, '<H')
+ directory = 112 if magic == 0x20b else 96 if magic == 0x10b else None
+ if directory is None or optional_size < directory + 24: return None
+ resource_rva = number(optional + directory + 16)
+ segments = []
+ for i in range(sections):
+ section = optional + optional_size + i * 40
+ virtual_size, address, raw_size, raw = struct.unpack('<IIII', read(section + 8, 16))
+ segments.append((address, raw_size, raw))
+ def offset(rva):
+ for address, size, raw in segments:
+ if address <= rva < address + size: return raw + rva - address
+ raise ValueError('resource outside file sections')
+ base = offset(resource_rva)
+ def entries(relative):
+ named, ids = struct.unpack('<HH', read(base + relative + 12, 4))
+ if named + ids > 4096: raise ValueError('too many resources')
+ return [struct.unpack('<II', read(base + relative + 16 + i * 8, 8)) for i in range(named + ids)]
+ types = dict(entries(0))
+ def resource(kind, identity=None):
+ node = types[kind]
+ if not node & 0x80000000: raise ValueError('expected resource directory')
+ choices = dict(entries(node & 0x7fffffff))
+ node = choices[identity] if identity is not None else next(iter(choices.values()))
+ for _ in range(4):
+ if not node & 0x80000000:
+ rva, size = struct.unpack('<II', read(base + node, 8))
+ return read(offset(rva), size)
+ children = entries(node & 0x7fffffff)
+ node = children[0][1]
+ raise ValueError('resource nesting too deep')
+ group = resource(14)
+ reserved, kind, count = struct.unpack_from('<HHH', group)
+ if reserved != 0 or kind != 1 or not 1 <= count <= 128 or len(group) < 6 + count * 14:
+ return None
+ header = bytearray(struct.pack('<HHH', 0, 1, count))
+ payload = bytearray(); start = 6 + count * 16
+ for i in range(count):
+ entry = group[6 + i * 14:20 + i * 14]
+ identity = struct.unpack_from('<H', entry, 12)[0]
+ icon = resource(3, identity)
+ header.extend(entry[:8] + struct.pack('<II', len(icon), start + len(payload)))
+ payload.extend(icon)
+ if len(payload) > 8 * 1024 * 1024: raise ValueError('icon too large')
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_bytes(header + payload)
+ return str(output)
+ except (OSError, ValueError, KeyError, IndexError, StopIteration, struct.error):
+ return None
diff --git a/scripts/gog-launch.py b/scripts/gog-launch.py
new file mode 100644
index 00000000000..9338f7d664d
--- /dev/null
+++ b/scripts/gog-launch.py
@@ -0,0 +1,27 @@
+#!/usr/bin/env python3
+"""Galaxy uses exit 255 for a successful handoff to an already running client.
+
+Preserve every other failure. Match its explicit success message, not just 255,
+and stream output instead of retaining an unbounded copy of the client log.
+"""
+import subprocess
+import sys
+
+SUCCESS = b"returned exit code -1 (Message passed in argument has been sent successfully to another client.)"
+
+
+def main():
+ if len(sys.argv) < 2:
+ return 64
+ forwarded = False
+ with subprocess.Popen(sys.argv[1:], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as process:
+ for line in process.stdout:
+ forwarded = forwarded or SUCCESS in line
+ sys.stdout.buffer.write(line)
+ sys.stdout.buffer.flush()
+ code = process.wait()
+ return 0 if code == 255 and forwarded else code
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/scripts/play.sh b/scripts/play.sh
index 7e0ae7db0a0..d6f4cbf8fad 100755
--- a/scripts/play.sh
+++ b/scripts/play.sh
@@ -117,7 +117,7 @@ case "$MODE" in
BN_EXE="C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"
BN_ARGS="--disable-gpu-compositing --from-launcher --in-process-gpu --use-gl=swiftshader"
export WINE_DOCK_REOPEN_CMD="'$ENGINE/bin/wine' '$BN_EXE' $BN_ARGS"
- exec "$ENGINE/bin/wine" "$BN_EXE" $BN_ARGS
+ exec "$ENGINE/bin/wine" "$BN_EXE" $BN_ARGS "${@:2}"
;;
d2r) # Launch the game directly (offline / previous session)
start_reaper
@@ -186,7 +186,7 @@ case "$MODE" in
# would send, without paying for a whole second client start-up
# (tools/soju-gog-restore.c, built by create-gog-bottle.sh).
export WINE_DOCK_REOPEN_CMD="'$ENGINE/bin/wine' '${SOJU_BASE:-$HOME/.battlenet-macos}/gog-support/soju-gog-restore.exe'"
- exec "$ENGINE/bin/wine" "$GOG" "${@:2}"
+ exec python3 "$(dirname "${BASH_SOURCE[0]}")/gog-launch.py" "$ENGINE/bin/wine" "$GOG" "${@:2}"
;;
gog-kill) # Stop everything in the GOG bottle
pkill -f "soju-reaper.sh $WINEPREFIX" 2>/dev/null || true
diff --git a/scripts/soju b/scripts/soju
index defbdee37cc..d88a3e6acac 100755
--- a/scripts/soju
+++ b/scripts/soju
@@ -18,6 +18,8 @@ soju: open-source Windows launchers on Apple Silicon
Usage:
soju install Choose and install any of the four launchers
soju app Build, install and open the native Soju app
+ soju library List installed games as JSON
+ soju game <id> Play a game from the unified library
soju --version Print the Soju version
soju battlenet Launch Battle.net (default bottle)
soju d2r Launch Diablo II: Resurrected directly
@@ -46,6 +48,8 @@ EOF
}
case "${1:-}" in
+ library) exec python3 "$ROOT/scripts/game-library.py" list ;;
+ game) shift; exec python3 "$ROOT/scripts/game-library.py" launch "$@" ;;
--version) cat "$ROOT/VERSION" ;;
app) exec bash "$ROOT/scripts/install-app.sh" ;;
install) shift; exec bash "$ROOT/install.sh" "$@" ;;
diff --git a/tests/test_library.py b/tests/test_library.py
new file mode 100644
index 00000000000..6a8b6551f44
--- /dev/null
+++ b/tests/test_library.py
@@ -0,0 +1,182 @@
+import importlib.util
+import json
+from pathlib import Path
+import sqlite3
+import subprocess
+import tempfile
+import unittest
+
+ROOT = Path(__file__).resolve().parents[1]
+spec = importlib.util.spec_from_file_location('library', ROOT / 'scripts/game-library.py')
+library = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(library)
+
+
+def field(n, data):
+ def integer(value):
+ result = bytearray()
+ while value >= 128:
+ result.append((value & 127) | 128); value >>= 7
+ result.append(value); return bytes(result)
+ return integer(n * 8 + 2) + integer(len(data)) + data
+
+
+class LibraryTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory(prefix="soju library ' ")
+ self.addCleanup(self.temp.cleanup)
+ self.base = Path(self.temp.name)
+ self.lib = library.Library(self.base)
+ for platform, folder in library.FOLDERS.items():
+ self.put(self.base / folder / 'drive_c' / library.CLIENTS[platform], '')
+
+ def put(self, path, data):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(data if isinstance(data, bytes) else data.encode())
+ return path
+
+ def steam(self, uid='123', title='A game', folder='A game', flags=4, root=None):
+ root = root or self.base / 'steam-bottle/drive_c/Program Files (x86)/Steam'
+ game = root / 'steamapps/common' / folder
+ game.mkdir(parents=True, exist_ok=True)
+ manifest = f'"AppState" {{ "appid" "{uid}" "name" "{title}" "StateFlags" "{flags}" "installdir" "{folder}" }}'
+ self.put(root / 'steamapps' / ('appmanifest_' + uid + '.acf'), manifest)
+ return root, game
+
+ def epic(self, uid='epic-app', **changes):
+ item = dict(AppName=uid, DisplayName='An Epic Game', InstallLocation='C:\\Games\\Epic',
+ CatalogNamespace='namespace', CatalogItemId='catalog', LaunchExecutable='Game.exe')
+ item.update(changes)
+ self.put(self.base / 'epic-bottle/drive_c/Games/Epic/Game.exe', '')
+ self.put(self.base / 'epic-bottle/drive_c/ProgramData/Epic/EpicGamesLauncher/Data/Manifests' / (uid + '.item'), json.dumps(item))
+
+ def bnet(self, uid='osi', folder='Diablo'):
+ prefix = self.base / 'bottle'
+ self.put(prefix / 'drive_c/Games' / folder / '.build.info', 'build')
+ record = field(1, uid.encode()) + field(3, field(1, ('C:/Games/' + folder).encode()))
+ self.put(prefix / 'drive_c/ProgramData/Battle.net/Agent/product.db', field(1, record))
+
+ def gog(self, uid='77', name='GOG game'):
+ path = self.base / 'gog-bottle/drive_c/Custom/GOG game'
+ self.put(path / ('goggame-' + uid + '.info'), json.dumps(dict(gameId=uid, rootGameId=uid, name=name)))
+ database = self.base / 'gog-bottle/drive_c/ProgramData/GOG.com/Galaxy/storage/galaxy-2.0.db'
+ database.parent.mkdir(parents=True, exist_ok=True)
+ with sqlite3.connect(database) as db:
+ db.execute('CREATE TABLE InstalledBaseProducts (productId INTEGER, installationPath TEXT)')
+ db.execute('CREATE TABLE Products (id INTEGER, name TEXT)')
+ db.execute('INSERT INTO InstalledBaseProducts VALUES (?, ?)', (uid, 'C:\\Custom\\GOG game'))
+ db.execute('INSERT INTO Products VALUES (?, ?)', (uid, name))
+ return database
+
+ def test_four_platforms_and_launch_argv(self):
+ self.steam(); self.epic(); self.bnet(); database = self.gog()
+ before = database.read_bytes()
+ result = self.lib.scan()
+ self.assertEqual(len(result['games']), 4)
+ self.assertEqual(result['warnings'], [])
+ self.assertEqual(self.lib.command('steam:123')[-2:], ['steam', 'steam://rungameid/123'])
+ self.assertEqual(self.lib.command('battlenet:osi')[-2:], ['battlenet', '--exec=launch OSI'])
+ self.assertEqual(self.lib.command('epic:epic-app')[-1], 'com.epicgames.launcher://apps/namespace%3Acatalog%3Aepic-app?action=launch&silent=true')
+ self.assertEqual(self.lib.command('gog:77')[-3:], ['/command=runGame', '/gameId=77', '/path=C:\\Custom\\GOG game'])
+ self.assertEqual(before, database.read_bytes(), 'Scanning must never modify Galaxy')
+ self.assertNotIn('arguments', result['games'][0])
+
+ def test_external_steam_library_and_case_insensitive_path(self):
+ root = self.base / 'external/My Games'
+ self.steam(root=root)
+ prefix = self.base / 'steam-bottle'
+ (prefix / 'dosdevices').mkdir()
+ (prefix / 'dosdevices/d:').symlink_to(self.base / 'external', target_is_directory=True)
+ self.put(prefix / 'drive_c/Program Files (x86)/Steam/steamapps/libraryfolders.vdf',
+ '"libraryfolders" { "0" { "path" "D:\\\\my games" } "1" { "path" "D:\\\\My Games" } }')
+ self.assertEqual([g['id'] for g in self.lib.scan()['games']], ['steam:123'])
+
+ def test_invalid_record_does_not_hide_other_platforms(self):
+ root, _ = self.steam(); self.epic(); self.bnet()
+ self.put(root / 'steamapps/appmanifest_broken.acf', '"AppState" { "appid"')
+ self.put(self.base / 'epic-bottle/drive_c/ProgramData/Epic/EpicGamesLauncher/Data/Manifests/broken.item', '{')
+ result = self.lib.scan()
+ self.assertEqual(len(result['games']), 3)
+ self.assertEqual(len(result['warnings']), 2)
+
+ def test_launch_rescans_deleted_installation(self):
+ _, game = self.steam()
+ self.lib.scan(); game.rmdir()
+ with self.assertRaisesRegex(ValueError, 'no longer installed'): self.lib.command('steam:123')
+
+ def test_partial_download_requires_official_launcher(self):
+ self.steam(flags=2)
+ self.epic(bIsIncompleteInstall=True)
+ self.assertEqual(len(self.lib.scan()['games']), 2)
+ for key in ['steam:123', 'epic:epic-app']:
+ with self.assertRaisesRegex(ValueError, 'Finish'): self.lib.command(key)
+
+ def test_missing_launcher_detected(self):
+ self.steam()
+ (self.base / 'steam-bottle/drive_c' / library.CLIENTS['steam']).unlink()
+ with self.assertRaisesRegex(ValueError, 'Install this platform'): self.lib.command('steam:123')
+
+ def test_unmapped_battlenet_title_is_visible_but_not_guessed(self):
+ self.bnet('future', 'Future game')
+ result = self.lib.scan()
+ self.assertEqual(result['games'][0]['title'], 'Future game')
+ with self.assertRaisesRegex(ValueError, 'official launcher'): self.lib.command('battlenet:future')
+
+ def test_gog_fallback_and_dlc_filter(self):
+ root = self.base / 'gog-bottle/drive_c/GOG Games/Sample'
+ for uid, parent in [('10', '10'), ('11', '10')]:
+ self.put(root / ('goggame-' + uid + '.info'), json.dumps(dict(gameId=uid, rootGameId=parent, name='Sample')))
+ self.assertEqual([g['id'] for g in self.lib.scan()['games']], ['gog:10'])
+ self.epic(MainGameAppName='other-app')
+ self.assertEqual(len(self.lib.scan()['games']), 1)
+
+ def test_titles_never_become_commands(self):
+ self.steam(title='$(touch SHOULD_NOT_EXIST); `false` & ★')
+ result = subprocess.run(['python3', str(ROOT / 'scripts/game-library.py'), 'launch', 'steam:123',
+ '--dry-run', '--base', str(self.base)], capture_output=True, text=True, check=True)
+ command = json.loads(result.stdout)
+ self.assertEqual(command[-2:], ['steam', 'steam://rungameid/123'])
+ with self.assertRaises(ValueError): self.lib.command('steam:123; echo BAD')
+ self.assertFalse((self.base / 'SHOULD_NOT_EXIST').exists())
+
+ def test_path_traversal_and_malformed_binary_rejected(self):
+ for path in ['C:\\Games\\..\\Secrets', '\\\\server\\share', '/etc/passwd', 'relative', 'C:\\a\x00b']:
+ with self.assertRaises(ValueError): library.windows_path(self.base, path)
+ for data in [b'\x0a\xff', b'\x00', b'\x0a\x10abc', b'\xff' * 11]:
+ with self.assertRaises(ValueError): library.protobuf(data)
+ with self.assertRaises(ValueError): library.vdf('"key" { "bad" }')
+
+ def test_steam_manifest_identity_must_match_filename(self):
+ root, _ = self.steam()
+ manifest = root / 'steamapps/appmanifest_123.acf'
+ manifest.write_text(manifest.read_text().replace('"123"', '"456"'))
+ self.assertEqual(self.lib.scan()['games'], [])
+
+ def test_invalid_executable_artwork_is_ignored(self):
+ from game_artwork import executable_icon
+ broken = self.put(self.base / 'broken.exe', b'MZ' + bytes(100))
+ self.assertIsNone(executable_icon(broken, self.base / 'art'))
+ self.assertFalse((self.base / 'art').exists())
+
+ def test_gog_successful_handoff_is_not_reported_as_failure(self):
+ success = "Initialization strategy returned exit code -1 (Message passed in argument has been sent successfully to another client.)"
+ for message, code, expected in [(success, 255, 0), ('Unexpected failure', 255, 255), (success, 1, 1), ('Started', 0, 0)]:
+ result = subprocess.run(['python3', str(ROOT / 'scripts/gog-launch.py'),
+ 'python3', '-c', 'import sys; print(sys.argv[1]); sys.exit(int(sys.argv[2]))',
+ message, str(code)], capture_output=True, text=True)
+ self.assertEqual(result.returncode, expected)
+ self.assertIn(message, result.stdout)
+
+ def test_offline_external_library_shows_a_warning(self):
+ prefix = self.base / 'steam-bottle'
+ self.put(prefix / 'drive_c/Program Files (x86)/Steam/steamapps/libraryfolders.vdf',
+ '\"libraryfolders\" { \"0\" { \"path\" \"D:\\\\Games\" } }')
+ result = self.lib.scan()
+ self.assertEqual(result['games'], [])
+ self.assertIn('drive is unavailable', result['warnings'][0])
+
+ def test_no_installations_is_valid_empty_library(self):
+ self.assertEqual(self.lib.scan(), {'games': [], 'warnings': []})
+
+
+if __name__ == '__main__': unittest.main()