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.

Didim Labs native Mac games: install from a downloaded zip after a signature check, list in the library, play and track until quit

mikey924f6bb21d7d43
diff --git a/README.ko.md b/README.ko.md
index ca50c0ad594..48063b39f5c 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -146,6 +146,10 @@ scripts/play.sh gog-kill # GOG 보틀 종료 (창을 닫으면 메뉴
게임은 아직 폭넓게 테스트하지 않았습니다. 커널 안티치트(EAC/BattlEye)가 필요한 게임은 Wine에서 돌지 않습니다.
+## Didim Labs 게임 (맥 네이티브)
+
+Didim Labs가 만든 애플 실리콘 네이티브 게임은 내려받은 .zip으로 설치합니다(Library → Add Didim Labs game, 또는 `soju didim install <zip>`). 설치 전에 게임 서명을 확인하고, Windows나 Wine 없이 바로 실행됩니다. 세이브는 `~/Library/Application Support`에 남습니다.
+
## Xbox PC / Microsoft Store (Xodus 백엔드, 실험 기능)
Microsoft 계정으로 로그인해 보유 게임과 PC Game Pass 게임을 가져오고, Microsoft Store를 검색하고, 게임을 내려받고 실행할 수 있습니다. **게임 실행은 실험 기능입니다.** M4 Pro·macOS 26.5에서 Retro Classics가 메인 화면까지 실행되는 것을 확인했고, 다른 게임은 아직 확인하지 않았습니다. 게임별 Wine 설정은 `resources/xbox-compat.json`에 있습니다. 실행 방식은 맥에서 여러 게임이 실행된 MACxus와 같습니다. 실행하려면 CX 엔진과 Apple GPTK가 필요합니다. Xbox PC를 설정하면 엔진이 설치되고, GPTK는 Battle.net·Epic·GOG처럼 Platforms에서 추가합니다.
diff --git a/README.md b/README.md
index 4df23277231..4ab8ea653e3 100644
--- a/README.md
+++ b/README.md
@@ -12,6 +12,7 @@ owned library cached by **GOG GALAXY**. Installed and uninstalled games share th
same library, with availability filters and official-client install actions.
**Discover** searches Steam, GOG and Microsoft Store listings and prices, with links to buy from the stores.
**Xbox PC (experimental):** sign in to a Microsoft account to import owned and PC Game Pass games, download them through the [Xodus](https://github.com/xodus-gaming/xodus) backend and start them on Soju's engine. Retro Classics reaches its main menu on Soju; other games are untested. Purchases, downloads and updates stay with the official stores.
+**Didim Labs games:** native Apple Silicon games from Didim Labs install from their downloaded .zip (Library → Add Didim Labs game, or `soju didim install <zip>`) and run without Windows or Wine; Soju checks the game's signature first.
Epic and Battle.net account imports are not included yet. Compatibility varies by game.
![Soju unified game library](docs/assets/soju-library.png)
diff --git a/app/Library.swift b/app/Library.swift
index c5f129927d3..236d3d18bee 100644
--- a/app/Library.swift
+++ b/app/Library.swift
@@ -111,6 +111,7 @@ extension SojuModel {
if !FileManager.default.fileExists(atPath: game.installPath) {
return "This game folder is unavailable. Reconnect its drive and refresh."
}
+ if game.platform == .didim { return nil }
if game.platform == .steam {
let local = base.appendingPathComponent("steam-runtime/bin/wine").path
let upstream = base.appendingPathComponent("steam-wine/bin/wine").path
@@ -144,6 +145,8 @@ extension SojuModel {
}
if self.stoppingGames.remove(game.id) != nil {
self.activity = game.title + " stopped."
+ } else if process.terminationStatus == 0 && game.platform == .didim {
+ self.activity = game.title + " closed."
} else if process.terminationStatus != 0 {
let text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""
let reason = text.split(separator: "\n").last(where: { $0.hasPrefix("soju: ") }).map { String($0.dropFirst(6)) }
@@ -161,10 +164,10 @@ extension SojuModel {
try p.run()
failed = false
preferences.opened[game.id] = Date(); savePreferences()
- activity = "Opening " + game.title + " through " + game.platform.title + "…"
+ activity = game.platform == .didim ? "Playing " + game.title + "…" : "Opening " + game.title + " through " + game.platform.title + "…"
// An Xbox game runs inside this process, so it counts as running until it exits.
// Other clients may stay alive for hours: there it is only a launch request.
- if game.platform != .xbox { DispatchQueue.main.asyncAfter(deadline: .now() + 8) { [weak self, weak p] in
+ if !game.platform.runsInSoju { 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)
} }
@@ -225,6 +228,7 @@ private extension Launcher {
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)
case .xbox: return Color(red: 0.24, green: 0.66, blue: 0.33)
+ case .didim: return Color(red: 0.79, green: 0.36, blue: 0.27)
}
}
}
@@ -345,6 +349,11 @@ struct LibraryView: View {
} label: {
Label(model.scanning ? "Scanning…" : "Refresh", systemImage: "arrow.clockwise")
}.disabled(model.scanning || model.busy).help("Rescan local installation records")
+ Button {
+ model.installDidimGame()
+ } label: {
+ Label("Add Didim Labs game", systemImage: "plus")
+ }.disabled(model.busy).help("Install a native Mac game from a downloaded .zip")
}
HStack(spacing: 12) {
HStack(spacing: 8) {
@@ -446,7 +455,7 @@ struct LibraryView: View {
if !game.isInstalled { model.installOwnedGame(game) }
else if issue == nil { model.play(game) } else { selected = game }
} label: {
- Label(!game.isInstalled ? (game.isPartialDownload ? "Resume" : game.platform.ownedActionTitle) : model.launchingGames.contains(game.id) ? (game.platform == .xbox ? "Running" : "Starting…") : issue == nil ? "Play" : "Details", systemImage: !game.isInstalled ? "arrow.down.circle" : issue == nil ? "play.fill" : "exclamationmark.circle")
+ Label(!game.isInstalled ? (game.isPartialDownload ? "Resume" : game.platform.ownedActionTitle) : model.launchingGames.contains(game.id) ? (game.platform.runsInSoju ? "Running" : "Starting…") : issue == nil ? "Play" : "Details", systemImage: !game.isInstalled ? "arrow.down.circle" : issue == nil ? "play.fill" : "exclamationmark.circle")
}.buttonStyle(.borderedProminent).tint(green).controlSize(.small)
.disabled(model.busy || model.launchingGames.contains(game.id))
.accessibilityLabel((!game.isInstalled ? (game.isPartialDownload ? "Resume downloading " : game.platform.ownedActionTitle + " ") : issue == nil ? "Play " : "Check ") + game.title)
@@ -514,7 +523,7 @@ struct LibraryView: View {
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(installedLabel(game), systemImage: !game.isInstalled ? "cloud" : game.volume.map { $0 != "this Mac" } == true ? "externaldrive" : "internaldrive").font(.system(size: 12)).foregroundStyle(.secondary)
- Text(game.platform == .xbox ? "Downloaded from the Microsoft Store. Xbox PC support is experimental: not every game works. The first launch may download about 600 MB of Xbox runtime files and take a few minutes to set up." : "Opens through " + game.platform.title + ". You may need to sign in or finish an update in the launcher.")
+ Text(game.platform == .didim ? "A native Mac game from Didim Labs. It runs without Windows or Wine." : game.platform == .xbox ? "Downloaded from the Microsoft Store. Xbox PC support is experimental: not every game works. The first launch may download about 600 MB of Xbox runtime files and take a few minutes to set up." : "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 game.downloadBlocked, let issue = game.issue {
Label(issue, systemImage: "exclamationmark.triangle").font(.system(size: 12)).foregroundStyle(.orange)
@@ -522,7 +531,7 @@ struct LibraryView: View {
if let issue = model.launchIssue(for: game) {
Label(issue, systemImage: "exclamationmark.triangle").font(.system(size: 12)).foregroundStyle(.orange)
}
- Text(game.platform == .xbox ? (game.isInstalled ? "Files are in " + game.installPath + ". Saves sync with your Xbox account when the game exits." : "This game is in your Xbox library. Download it to play; compatibility varies by game.") : game.isInstalled ? "Installation detected. Compatibility varies by game and Mac." : "This game is in your imported library. Open its launcher to install it; compatibility varies by game.")
+ Text(game.platform == .didim ? "Files are in " + game.installPath + ". Saves stay in ~/Library/Application Support." : game.platform == .xbox ? (game.isInstalled ? "Files are in " + game.installPath + ". Saves sync with your Xbox account when the game exits." : "This game is in your Xbox library. Download it to play; compatibility varies by game.") : game.isInstalled ? "Installation detected. Compatibility varies by game and Mac." : "This game is in your imported library. Open its launcher to install it; compatibility varies by game.")
.font(.system(size: 11)).foregroundStyle(.secondary)
Spacer()
}
diff --git a/app/Soju.swift b/app/Soju.swift
index 6c9eec26270..d2ab79d71dc 100644
--- a/app/Soju.swift
+++ b/app/Soju.swift
@@ -1,9 +1,14 @@
import SwiftUI
import AppKit
+import UniformTypeIdentifiers
enum Launcher: String, CaseIterable, Identifiable {
- case battlenet, steam, epic, gog, xbox
+ case battlenet, steam, epic, gog, xbox, didim
var id: String { rawValue }
+ /// Platforms with something to install on the Platforms page (not native Didim Labs games).
+ static var installable: [Launcher] { allCases.filter { $0 != .didim } }
+ /// Games that run as a task of Soju until they quit, instead of through an open launcher.
+ var runsInSoju: Bool { self == .xbox || self == .didim }
var title: String {
switch self {
case .battlenet: return "Battle.net"
@@ -11,17 +16,19 @@ enum Launcher: String, CaseIterable, Identifiable {
case .epic: return "Epic Games"
case .gog: return "GOG GALAXY"
case .xbox: return "Xbox PC"
+ case .didim: return "Didim Labs"
}
}
var detail: String {
switch self {
case .steam: return "Windows library · D3D11 with DXMT"
case .xbox: return "Microsoft Store library · experimental"
+ case .didim: return "Native Mac games"
default: return "Windows library · Apple D3DMetal"
}
}
/// Xbox PC has no Windows client to open; sign-in and downloads run in Soju.
- var opensAWindow: Bool { self != .xbox }
+ var opensAWindow: Bool { self != .xbox && self != .didim }
var accountName: String {
switch self {
case .steam: return "Steam account"
@@ -29,6 +36,7 @@ enum Launcher: String, CaseIterable, Identifiable {
case .epic: return "Epic account"
case .battlenet: return "Blizzard account"
case .xbox: return "Microsoft account"
+ case .didim: return "Didim Labs"
}
}
/// Action for an owned game that is not on this Mac yet.
@@ -37,6 +45,7 @@ enum Launcher: String, CaseIterable, Identifiable {
case .steam: return "Install"
case .gog: return "Galaxy"
case .xbox: return "Download"
+ case .didim: return "Install"
default: return "Open"
}
}
@@ -47,6 +56,7 @@ enum Launcher: String, CaseIterable, Identifiable {
case .epic: return "shield.lefthalf.filled"
case .gog: return "square.grid.2x2.fill"
case .xbox: return "xbox.logo"
+ case .didim: return "cat.fill"
}
}
var executable: String {
@@ -56,6 +66,7 @@ enum Launcher: String, CaseIterable, Identifiable {
case .epic: return "epic-bottle/drive_c/Program Files/Epic Games/Launcher/Portal/Binaries/Win64/EpicGamesLauncher.exe"
case .gog: return "gog-bottle/drive_c/Program Files/GOG Galaxy/GalaxyClient.exe"
case .xbox: return "xbox-bottle/drive_c/ProgramData/Soju/xbox.json"
+ case .didim: return "didim-games"
}
}
}
@@ -100,7 +111,7 @@ enum Launcher: String, CaseIterable, Identifiable {
init() { refresh(); refreshLibrary() }
func refresh() {
- installed = Set(Launcher.allCases.filter {
+ installed = Set(Launcher.installable.filter {
FileManager.default.fileExists(atPath: base.appendingPathComponent($0.executable).path)
})
}
@@ -172,7 +183,7 @@ enum Launcher: String, CaseIterable, Identifiable {
}
func installSelection() {
- let selected = Launcher.allCases.filter { selection.contains($0) }.map(\.rawValue)
+ let selected = Launcher.installable.filter { selection.contains($0) }.map(\.rawValue)
guard !selected.isEmpty else { return }
run(["install", selected.joined(separator: ",")], title: "Installing selected launchers…")
}
@@ -213,6 +224,18 @@ enum Launcher: String, CaseIterable, Identifiable {
run(["gptk", url.path], title: "Installing Apple GPTK…")
}
+ /// A Didim Labs game zip (bought and downloaded outside Soju) installs into didim-games.
+ func installDidimGame() {
+ let panel = NSOpenPanel()
+ panel.title = "Choose a Didim Labs game"
+ panel.message = "Select the game .zip you downloaded."
+ panel.allowedContentTypes = [.zip]
+ panel.canChooseDirectories = false
+ panel.directoryURL = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first
+ guard panel.runModal() == .OK, let url = panel.url else { return }
+ run(["didim", "install", url.path], title: "Installing the game…")
+ }
+
func copyLog() {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(log, forType: .string)
@@ -247,7 +270,7 @@ struct PlatformsView: View {
} label: { Image(systemName: "ellipsis.circle").font(.title2) }.menuStyle(.borderlessButton).fixedSize()
}
LazyVGrid(columns: columns, spacing: 16) {
- ForEach(Launcher.allCases) { launcher in
+ ForEach(Launcher.installable) { launcher in
card(launcher)
}
}
diff --git a/scripts/desktop-action.sh b/scripts/desktop-action.sh
index e3cb6cefdd1..867ea97f63e 100755
--- a/scripts/desktop-action.sh
+++ b/scripts/desktop-action.sh
@@ -19,6 +19,10 @@ case "$ACTION" in
case "${1:-}" in setup|play|status) exec python3 "$ROOT/scripts/d2r-vr.py" "$1" ;;
flat) exec python3 "$ROOT/scripts/d2r-vr.py" play --flat ;;
*) echo "Unknown VR action."; exit 64 ;; esac ;;
+ didim)
+ case "${1:-}" in install) exec python3 "$ROOT/scripts/didim_games.py" install "${2:?Choose the game zip}" ;;
+ remove) exec python3 "$ROOT/scripts/didim_games.py" remove "${2:?Choose a game}" ;;
+ *) echo "Unknown Didim Labs action."; exit 64 ;; esac ;;
xbox)
case "${1:-}" in login|logout|kill|status) exec bash "$ROOT/scripts/xbox.sh" "$1" ;;
location) exec bash "$ROOT/scripts/xbox.sh" location "${2:?Choose a folder}" ;;
diff --git a/scripts/didim_games.py b/scripts/didim_games.py
new file mode 100755
index 00000000000..aa11aee334a
--- /dev/null
+++ b/scripts/didim_games.py
@@ -0,0 +1,140 @@
+#!/usr/bin/env python3
+"""Native Mac games from Didim Labs: install from a downloaded zip, list, remove.
+
+A game zip holds one .app whose Contents/Resources/soju-game.json names it:
+ {"schema": 1, "id": "dont-sell-the-cat", "title": "Don't Sell the Cat",
+ "publisher": "Didim Labs", "version": "1.0", "cover": "soju-cover.png"}
+Games install to $SOJU_BASE/didim-games/<id>/. No network, no accounts.
+"""
+import argparse
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+ID = re.compile(r'[a-z0-9][a-z0-9-]{0,63}')
+MAX_MANIFEST = 64 * 1024
+
+
+def base():
+ return Path(os.environ.get('SOJU_BASE', str(Path.home() / '.battlenet-macos'))).expanduser().absolute()
+
+
+def games_dir():
+ return base() / 'didim-games'
+
+
+def read_manifest(app):
+ path = app / 'Contents/Resources/soju-game.json'
+ if not path.is_file() or path.is_symlink():
+ raise ValueError('This is not a Soju game: soju-game.json is missing.')
+ data = path.read_bytes()
+ if len(data) > MAX_MANIFEST:
+ raise ValueError('The game manifest is too large.')
+ item = json.loads(data.decode('utf-8'))
+ if not isinstance(item, dict) or item.get('schema') != 1:
+ raise ValueError('Unsupported game manifest.')
+ if not isinstance(item.get('id'), str) or not ID.fullmatch(item['id']):
+ raise ValueError('Invalid game ID in the manifest.')
+ for key in ('title', 'publisher', 'version'):
+ if not isinstance(item.get(key), str) or not item[key].strip() or len(item[key]) > 200:
+ raise ValueError('The manifest is missing ' + key + '.')
+ cover = item.get('cover')
+ if cover is not None and (not isinstance(cover, str) or '/' in cover or cover.startswith('.')):
+ raise ValueError('Invalid cover name in the manifest.')
+ return item
+
+
+def inside(root, path):
+ try:
+ path.resolve().relative_to(root.resolve())
+ return True
+ except ValueError:
+ return False
+
+
+def install(archive):
+ archive = Path(archive).expanduser().absolute()
+ if not archive.is_file() or archive.suffix.lower() != '.zip':
+ raise ValueError('Choose the game .zip you downloaded.')
+ target_root = games_dir()
+ target_root.mkdir(parents=True, exist_ok=True, mode=0o700)
+ with tempfile.TemporaryDirectory(dir=target_root, prefix='.unpack-') as tmp:
+ tmp = Path(tmp)
+ # ditto keeps bundle symlinks, permissions and code signatures intact.
+ subprocess.run(['/usr/bin/ditto', '-x', '-k', str(archive), str(tmp)], check=True)
+ for p in tmp.rglob('*'):
+ if p.is_symlink() and not inside(tmp, p):
+ raise ValueError('The archive contains a link outside the game.')
+ apps = [p for p in tmp.iterdir() if p.suffix == '.app' and p.is_dir()]
+ if len(apps) != 1:
+ raise ValueError('The archive must contain exactly one .app.')
+ app = apps[0]
+ item = read_manifest(app)
+ # Downloads carry quarantine; the bundle is checked before it is trusted.
+ subprocess.run(['/usr/bin/xattr', '-dr', 'com.apple.quarantine', str(app)], check=False,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ check = subprocess.run(['/usr/bin/codesign', '--verify', '--deep', '--strict', str(app)],
+ capture_output=True, text=True)
+ if check.returncode != 0:
+ raise ValueError('The game signature is invalid or damaged: ' + check.stderr.strip()[:300])
+ dest = target_root / item['id']
+ old = target_root / ('.old-' + item['id'])
+ if old.exists(): shutil.rmtree(old)
+ if dest.exists(): dest.rename(old)
+ dest.mkdir(mode=0o700)
+ app.rename(dest / app.name)
+ record = dict(item, schema=1, app=app.name)
+ (dest / '.soju-didim.json').write_text(json.dumps(record, ensure_ascii=False), encoding='utf-8')
+ if old.exists(): shutil.rmtree(old)
+ print('Installed ' + item['title'] + ' ' + item['version'] + ' (' + item['publisher'] + ').')
+
+
+def installed(soju_base=None):
+ """Installed games as library entries (used by game-library.py with its own base)."""
+ games = []
+ root = Path(soju_base) / 'didim-games' if soju_base else games_dir()
+ if not root.is_dir(): return games
+ for record_path in sorted(root.glob('*/.soju-didim.json')):
+ folder = record_path.parent
+ if folder.name.startswith('.'): continue
+ item = json.loads(record_path.read_text(encoding='utf-8'))
+ if item.get('schema') != 1 or item.get('id') != folder.name or not ID.fullmatch(folder.name):
+ raise ValueError('mismatched game record')
+ app = folder / item['app']
+ if app.suffix != '.app' or '/' in item['app'] or not app.is_dir():
+ raise ValueError('missing game bundle')
+ cover = app / 'Contents/Resources' / item['cover'] if item.get('cover') else None
+ games.append(dict(uid=item['id'], title=item['title'], app=str(app), folder=str(folder),
+ artwork=str(cover) if cover and cover.is_file() else None,
+ version=item['version'], publisher=item['publisher']))
+ return games
+
+
+def remove(uid):
+ if not ID.fullmatch(uid or ''): raise ValueError('Choose a game ID.')
+ dest = games_dir() / uid
+ if not (dest / '.soju-didim.json').is_file(): raise ValueError('This game is not installed.')
+ shutil.rmtree(dest)
+ print('Removed ' + uid + '. Saves stay in ~/Library/Application Support.')
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('action', choices=['install', 'list', 'remove'])
+ parser.add_argument('target', nargs='?')
+ args = parser.parse_args()
+ try:
+ if args.action == 'install': install(args.target or '')
+ elif args.action == 'remove': remove(args.target)
+ else: print(json.dumps(installed(), ensure_ascii=False))
+ except (OSError, ValueError, json.JSONDecodeError, subprocess.CalledProcessError) as error:
+ print('soju: ' + str(error), file=sys.stderr); sys.exit(1)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/game-library.py b/scripts/game-library.py
index efeabe467b5..5b00a77e601 100644
--- a/scripts/game-library.py
+++ b/scripts/game-library.py
@@ -15,6 +15,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
from game_artwork import executable_icon
from library_services import saved_accounts
import xbox_locations
+import didim_games
from urllib.parse import quote
FOLDERS = {'steam': 'steam-bottle', 'epic': 'epic-bottle',
@@ -329,12 +330,24 @@ class Library:
except (OSError, ValueError, KeyError, TypeError, AttributeError):
self.warn('xbox', 'A download record could not be read. Download the game again to repair it.')
+ def didim(self):
+ # Native Mac games from Didim Labs: no Windows client or engine involved.
+ try: found = didim_games.installed(self.base)
+ except (OSError, ValueError, KeyError, TypeError):
+ self.warn('didim', 'A Didim Labs game record could not be read. Install the game again.'); return
+ for item in found:
+ key = 'didim:' + item['uid']
+ self.games[key] = dict(id=key, platform='didim', title=item['title'].strip()[:300],
+ install_path=item['folder'], artwork=item['artwork'], issue=None,
+ arguments=[item['app']])
+
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.')
+ self.didim()
accounts, owned, warnings = saved_accounts(self.base)
self.warnings.extend(warnings)
for game in owned:
@@ -360,6 +373,10 @@ class Library:
game = self.games.get(game_id)
if game is None: raise ValueError('This game is no longer installed. Refresh the library.')
root = Path(__file__).resolve().parent
+ if game['platform'] == 'didim':
+ if install: raise ValueError('This game is installed. Use Play instead.')
+ # -W keeps Soju's task alive until the game quits, so Stop and Running work.
+ return ['/usr/bin/open', '-W', '-n', game['arguments'][0]]
if game['platform'] == 'xbox':
# A game on an unplugged drive is never downloaded again onto the Mac.
if game.get('available') is False: raise ValueError(game['issue'])
@@ -402,6 +419,8 @@ def main():
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)
+ if game['platform'] == 'didim':
+ print('Native Mac game. Files: ' + game['install_path'], flush=True); return
command = ['/bin/bash', str(Path(__file__).resolve().parent / 'doctor.sh'), game['platform']]
else: command = lib.command(args.game_id, install=args.action == 'install')
if args.dry_run: print(json.dumps(command)); return
diff --git a/scripts/soju b/scripts/soju
index 616b220d60d..55923f8b92b 100755
--- a/scripts/soju
+++ b/scripts/soju
@@ -22,6 +22,8 @@ Usage:
soju game <id> Play a game from the unified library
soju game-install <id> Open the official launcher to install an owned game
soju search <term> Search Steam, GOG and the Microsoft Store (--country US|KR|GB|DE|JP)
+ soju didim install <game.zip> Install a native Mac game from Didim Labs
+ soju didim list|remove <id> List or remove installed Didim Labs games
soju --version Print the Soju version
soju battlenet Launch Battle.net (default bottle)
soju d2r Launch Diablo II: Resurrected directly
@@ -70,6 +72,7 @@ case "${1:-}" in
game-install) shift; exec python3 "$ROOT/scripts/game-library.py" install "$@" ;;
library) exec python3 "$ROOT/scripts/game-library.py" list ;;
game) shift; exec python3 "$ROOT/scripts/game-library.py" launch "$@" ;;
+ didim) shift; exec python3 "$ROOT/scripts/didim_games.py" "$@" ;;
--version) cat "$ROOT/VERSION" ;;
app) exec bash "$ROOT/scripts/install-app.sh" ;;
install) shift; exec bash "$ROOT/install.sh" "$@" ;;
diff --git a/tests/test_didim.py b/tests/test_didim.py
new file mode 100644
index 00000000000..ecce6d7e12b
--- /dev/null
+++ b/tests/test_didim.py
@@ -0,0 +1,89 @@
+"""Didim Labs native games: zip install, library entry, launch argv, tamper and manifest checks."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+
+ROOT = Path(__file__).resolve().parents[1]
+SCRIPT = ROOT / 'scripts/didim_games.py'
+LIBRARY = ROOT / 'scripts/game-library.py'
+
+
+def make_zip(folder, manifest, tamper=False, sign=True):
+ app = folder / 'Test Game.app'
+ (app / 'Contents/MacOS').mkdir(parents=True)
+ (app / 'Contents/Resources').mkdir()
+ exe = app / 'Contents/MacOS/Test Game'
+ exe.write_text('#!/bin/sh\nexit 0\n'); exe.chmod(0o755)
+ (app / 'Contents/Info.plist').write_text(
+ '<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>'
+ '<key>CFBundleExecutable</key><string>Test Game</string>'
+ '<key>CFBundleIdentifier</key><string>com.example.testgame</string></dict></plist>')
+ if manifest is not None:
+ (app / 'Contents/Resources/soju-game.json').write_text(json.dumps(manifest))
+ (app / 'Contents/Resources/cover.png').write_bytes(b'\x89PNG\r\n\x1a\n')
+ if sign:
+ subprocess.run(['/usr/bin/codesign', '--force', '--deep', '-s', '-', str(app)], check=True, capture_output=True)
+ if tamper:
+ (app / 'Contents/Resources/cover.png').write_bytes(b'changed')
+ archive = folder / 'game.zip'
+ subprocess.run(['/usr/bin/ditto', '-c', '-k', '--keepParent', str(app), str(archive)], check=True)
+ return archive
+
+
+GOOD = {'schema': 1, 'id': 'test-game', 'title': 'Test Game', 'publisher': 'Didim Labs',
+ 'version': '1.0', 'cover': 'cover.png'}
+
+
[email protected](sys.platform == 'darwin', 'needs ditto and codesign')
+class DidimGames(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory(); self.dir = Path(self.tmp.name)
+ self.base = self.dir / 'base'
+ self.env = dict(os.environ, SOJU_BASE=str(self.base))
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def run_script(self, *args):
+ return subprocess.run([sys.executable, str(SCRIPT), *args], env=self.env, capture_output=True, text=True)
+
+ def test_install_list_launch_remove(self):
+ archive = make_zip(self.dir, GOOD)
+ subprocess.run(['/usr/bin/xattr', '-w', 'com.apple.quarantine', '0083;00000000;Safari;', str(archive)], check=True)
+ result = self.run_script('install', str(archive))
+ self.assertEqual(result.returncode, 0, result.stderr)
+ app = self.base / 'didim-games/test-game/Test Game.app'
+ self.assertTrue(app.is_dir())
+ listed = subprocess.run([sys.executable, str(LIBRARY), 'list', '--base', str(self.base)],
+ capture_output=True, text=True, check=True)
+ games = [g for g in json.loads(listed.stdout)['games'] if g['platform'] == 'didim']
+ self.assertEqual([g['id'] for g in games], ['didim:test-game'])
+ self.assertIsNone(games[0]['issue'])
+ self.assertTrue(games[0]['artwork'].endswith('cover.png'))
+ argv = subprocess.run([sys.executable, str(LIBRARY), 'launch', 'didim:test-game', '--dry-run', '--base', str(self.base)],
+ capture_output=True, text=True, check=True)
+ self.assertEqual(json.loads(argv.stdout), ['/usr/bin/open', '-W', '-n', str(app)])
+ self.assertEqual(self.run_script('install', str(archive)).returncode, 0) # reinstall replaces
+ self.assertEqual(self.run_script('remove', 'test-game').returncode, 0)
+ self.assertFalse((self.base / 'didim-games/test-game').exists())
+
+ def test_tampered_game_is_rejected(self):
+ result = self.run_script('install', str(make_zip(self.dir, GOOD, tamper=True)))
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn('signature', result.stderr)
+ self.assertEqual(list((self.base / 'didim-games').glob('test-game')), [])
+
+ def test_bad_manifests_are_rejected(self):
+ for manifest in [None, dict(GOOD, schema=2), dict(GOOD, id='../x'), dict(GOOD, cover='../x.png'), dict(GOOD, title='')]:
+ with self.subTest(manifest=manifest):
+ folder = Path(tempfile.mkdtemp(dir=self.dir))
+ self.assertNotEqual(self.run_script('install', str(make_zip(folder, manifest))).returncode, 0)
+ self.assertEqual(list((self.base / 'didim-games').glob('[!.]*')), [])
+
+
+if __name__ == '__main__':
+ unittest.main()