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.

45.8 KB
Raw Blame
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?
    /// Something worth knowing that does not stop Play: the game carries an anti-cheat that may close it on a Mac.
    let note: String?
    /// The game's anti-cheat is kept off Wine by its makers (Are We Anti-Cheat Yet? says Denied): it never starts.
    let blocked: String?
    let owned: Bool?
    let downloaded: Bool?
    let format: String?
    /// Xbox PC: false while the external drive holding the download is not connected.
    let available: Bool?
    /// Xbox PC: the drive the download is on ("this Mac" for the internal disk).
    let volume: String?
    var isOnUnpluggedDrive: Bool { available == false }
    /// Xbox PC: a folder with an unfinished download is not installed yet.
    var isInstalled: Bool { platform == .xbox ? downloaded == true : !installPath.isEmpty }
    var isPartialDownload: Bool { platform == .xbox && !installPath.isEmpty && downloaded != true }
    /// Owned but not downloadable (for example MSIXVC2 packages).
    var downloadBlocked: Bool { platform == .xbox && !isInstalled && !isPartialDownload && issue != nil }
    enum CodingKeys: String, CodingKey {
        case id, platform, title, artwork, issue, note, blocked, owned, downloaded, format, available, volume
        case installPath = "install_path"
    }
}
extension Launcher: Decodable {}
struct LibrarySnapshot: Decodable {
    let accounts: [AccountSummary]?
    let games: [InstalledGame]
    let warnings: [String]
    let xboxLocation: XboxLocation?
    enum CodingKeys: String, CodingKey {
        case accounts, games, warnings
        case xboxLocation = "xbox_location"
    }
}
/// Where new Xbox PC downloads go (scripts/xbox_locations.py describe()).
struct XboxLocation: Decodable, Equatable {
    let path: String
    let volume: String
    let isDefault: Bool
    let available: Bool
    let freeBytes: Int64?
    enum CodingKeys: String, CodingKey {
        case path, volume, available
        case isDefault = "default"
        case freeBytes = "free_bytes"
    }
}
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 {
    /// Where people ask for help: linked from the launch-failure alert and Diagnostics.
    static let discord = URL(string: "https://discord.gg/ttBDcF5ftz")!
    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
                        self.accountSummaries = result.accounts ?? []
                        self.xboxLocation = result.xboxLocation
                        self.sendStats(["library"], logName: "stats-library")
                    } 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. If macOS asks whether Soju may access a drive or folder, answer it; reconnect any external game drives, then refresh."]
            }
        } catch {
            scanner = nil; scanning = false
            scanWarnings = ["Could not scan installed games: " + error.localizedDescription]
        }
    }
    func launchIssue(for game: InstalledGame) -> String? {
        if !game.isInstalled { return nil }
        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 == .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
            let stable = "/Applications/Wine Stable.app/Contents/Resources/wine/bin/wine"
            if !FileManager.default.isExecutableFile(atPath: local) && !FileManager.default.isExecutableFile(atPath: upstream) && !FileManager.default.isExecutableFile(atPath: stable) {
                return "Install Steam in Stores 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 Stores (Settings, Apple GPTK) before playing."
            }
        }
        return nil
    }
    func play(_ game: InstalledGame) {
        guard game.isInstalled else { libraryIssue = "Install this game through its official launcher first."; return }
        guard !busy, !launchingGames.contains(game.id) else { return }
        if let issue = launchIssue(for: game) { libraryIssue = issue; return }
        if let blocked = game.blocked {
            // Starting it only ends in an error window from its anti-cheat: say so first, and let a player try anyway.
            let alert = NSAlert()
            alert.messageText = game.title + " won't start on a Mac"
            alert.informativeText = blocked
            alert.addButton(withTitle: "OK")
            alert.addButton(withTitle: "Try Anyway")
            guard alert.runModal() == .alertSecondButtonReturn else { return }
        }
        if game.platform == .didim, game.id.hasSuffix("-demo"), !didimSignedIn {
            requestedPage = "store"; requestedDemoPlay = game.id; 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 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)) }
                        // Steam waiting on the player or updating first is not a failure to start: name the game only.
                        self.issueTitle = reason?.hasPrefix("Steam is ") == true ? game.title : "Couldn't start " + game.title
                        self.libraryIssue = reason ?? (game.platform.opensAWindow
                            ? "Use Diagnose or open " + game.platform.title + " to check its installation and login."
                            : "Use Diagnose to check the game and your Xbox sign-in.")
                        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()
            sendStats(["play", game.id, "--launcher", game.platform.rawValue, "--title", game.title,
                        "--path", game.installPath, "--pid", String(p.processIdentifier)],
                       logName: "stats-" + game.id.replacingOccurrences(of: ":", with: "-"))
            failed = false
            preferences.opened[game.id] = Date(); savePreferences()
            starAsk.launched(game.id); starAsk.save()
            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.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)
            } }
        } catch {
            launchingGames.remove(game.id); gameLaunches.removeValue(forKey: game.id)
            libraryIssue = "Could not start the game: " + error.localizedDescription
        }
    }
    /// D2R VR Unleashed in the VR copy of the Battle.net bottle (`soju vr play`, offline).
    /// `flat` plays the same copy on the Mac screen (mouse look, W A S D) in `view`: first, third or classic.
    func playVR(_ game: InstalledGame, flat: Bool = false, view: String = "first") {
        guard !busy, !launchingGames.contains(game.id) else { return }
        do {
            let (p, url) = try task(flat ? ["vr", "flat", view] : ["vr", "play"], logName: "d2r-vr")
            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 {
                        let text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""
                        let reason = text.split(separator: "\n").last(where: { $0.hasPrefix("soju vr: ") })
                            .map { String($0.dropFirst(9)) }
                        self.issueTitle = "Couldn't start " + game.title + " in VR"
                        self.libraryIssue = reason ?? "Run Set Up VR again, then try once more."
                    }
                }
            }
            try p.run()
            activity = flat ? "Starting " + game.title + " on the Mac screen (" + (view == "classic" ? "game camera" : view + " person") + ", offline characters)…"
                : "Starting " + game.title + " in VR (offline characters)…"
            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 {
            libraryIssue = "Could not start VR: " + error.localizedDescription
        }
    }
    /// An Xbox game runs inside Soju's task: SIGTERM reaches xbox-run.py, which asks the
    /// backend to close the game and copy its saves back (or stops first-launch setup).
    func stopGame(_ game: InstalledGame) {
        guard game.platform == .xbox, let p = gameLaunches[game.id], p.isRunning, !stoppingGames.contains(game.id) else { return }
        stoppingGames.insert(game.id)
        activity = "Stopping " + game.title + " and saving…"
        p.terminate()
    }
}

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)
        case .ea: return Color(red: 0.29, green: 0.42, blue: 0.95)
        case .rockstar: return Color(red: 0.96, green: 0.70, blue: 0.20)
        case .ubisoft: return Color(red: 0.36, green: 0.55, blue: 0.98)
        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)
        }
    }
}

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 availability = "all"
    @State private var selected: InstalledGame?
    @State private var vrGame: 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) &&
            (availability == "all" || (availability == "installed") == $0.isInstalled) &&
            (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 == "discover" { DiscoverView() }
            else if page == "store" { StoreView() }
            else if page == "tv" { TVView() }
            else if page == "accounts" { AccountsView() }
            else { library }
        }
        .frame(minWidth: 1010, minHeight: 710)
        .background(Color(nsColor: .windowBackgroundColor))
        .sheet(item: $selected) { game in detail(game) }
        .sheet(item: $vrGame) { game in D2RVRSheet(model: model, game: game, close: { vrGame = nil }) }
        .sheet(isPresented: $showDiagnostics) { diagnostics }
        .alert(model.issueTitle, isPresented: Binding(get: { model.libraryIssue != nil }, set: { if !$0 { model.libraryIssue = nil; model.issueTitle = "Game needs attention" } })) {
            // A launcher that is not installed yet: take the player to where it is installed.
            if model.libraryIssue?.contains("Stores") == true {
                Button("Open Stores") { model.libraryIssue = nil; selected = nil; page = "accounts" }
            }
            Button("Show Log") { model.libraryIssue = nil; showDiagnostics = true }
            Button("Ask on Discord") { model.libraryIssue = nil; NSWorkspace.shared.open(SojuModel.discord) }
            Button("OK", role: .cancel) { model.libraryIssue = nil }
        } message: { Text(model.libraryIssue ?? "") }
        .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
            model.refresh(); model.refreshLibrary()
        }
        .onChange(of: model.requestedPage) {
            if let next = model.requestedPage { selected = nil; page = next == "platforms" ? "accounts" : next; model.requestedPage = nil }
        }
        // The browser finished a Didim Labs sign-in (soju://auth/done), whichever page started it.
        .onChange(of: model.requestedAuth) {
            guard let handoff = model.requestedAuth, handoff.count == 2 else { return }
            model.requestedAuth = nil
            AccountModel.shared.received(state: handoff[0], code: handoff[1])
        }
    }

    private var sidebar: some View {
        VStack(alignment: .leading, spacing: 6) {
            HStack(spacing: 10) {
                SojuLogo(size: 46)
                Text("Soju").font(.system(size: 28, weight: .bold, design: .rounded))
            }.padding(.bottom, 4).padding(.top, 16)
            Text("by Didim Labs")
                .font(.system(size: 12)).foregroundStyle(.secondary).padding(.bottom, 26)
            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)
            nav("discover", "Discover", "magnifyingglass", count: nil)
            nav("store", "Didim Labs", "bag", count: nil)
            Divider().padding(.vertical, 16)
            nav("accounts", "Stores", "square.stack.3d.up", count: nil)
            nav("tv", "TV & iPad", "tv", count: nil)
            Spacer()
            VStack(alignment: .leading, spacing: 9) {
                Label("On your Mac", systemImage: "desktopcomputer").font(.system(size: 13, weight: .medium))
                Text("Installed games appear automatically. Sign in to a store in Stores to add the games you own.")
                    .font(.system(size: 12)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
            }.padding(13).frame(maxWidth: .infinity, alignment: .leading)
                .background(green.opacity(0.07), in: RoundedRectangle(cornerRadius: 12))
            UpdateCard(current: model.version, busy: model.busy, upToDate: { model.startComponentUpdateWhenIdle() })
            SponsorCard()
            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: 12)).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).fixedSize(horizontal: false, vertical: true)
                Spacer()
                if let count { Text(String(count)).font(.system(size: 12)).opacity(0.65) }
            }.font(.system(size: 14, 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: 32, weight: .bold, design: .rounded))
                    Text("Pick a game. Play it, or install it from its store.").font(.system(size: 14)).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")
                Button {
                    model.installDidimGame()
                } label: {
                    Label("Add Didim Labs game", systemImage: "plus")
                }.disabled(model.busy).help("Install a native Mac game from a downloaded .zip")
            }
            if model.busy { BusyBanner() }
            if page == "library" { SojuGardenCard() }
            if page == "library", model.starAsk.shouldAsk(), let id = model.starAsk.favorite() {
                StarCard(title: model.games.first(where: { $0.id == id })?.title)
            }
            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")
            }
            Picker("Availability", selection: $availability) {
                Text("All games").tag("all")
                Text("Installed").tag("installed")
                Text("Not installed").tag("owned")
            }.pickerStyle(.segmented).frame(width: 340).accessibilityLabel("Game availability")
            if !model.scanWarnings.isEmpty {
                Label(model.scanWarnings.joined(separator: "\n"), systemImage: "exclamationmark.triangle")
                    .font(.system(size: 12)).foregroundStyle(.orange).textSelection(.enabled)
            }
            if visibleGames.isEmpty {
                Spacer()
                VStack(spacing: 14) {
                    Image(systemName: model.scanning ? "arrow.clockwise" : page == "favorites" ? "star" : "gamecontroller")
                        .font(.system(size: 46, weight: .light)).foregroundStyle(green)
                    Text(model.scanning ? "Finding your games…" : model.games.isEmpty ? "Your library starts here" : "No games to show")
                        .font(.system(size: 23, weight: .semibold))
                    Text(model.games.isEmpty ? "Open Stores to install a launcher,\nor sign in to Steam, GOG or Xbox to see the games you own." : page == "favorites" ? "Star a game in your library to keep it here." : "Try another search or platform filter.")
                        .font(.system(size: 13)).foregroundStyle(.secondary).multilineTextAlignment(.center)
                    Button(model.games.isEmpty ? "Open Stores" : "Show all games") {
                        if model.games.isEmpty { page = "accounts" }
                        else { page = "library"; query = ""; platform = "all"; availability = "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." ? "\(model.games.count) games · \(model.games.filter { $0.isInstalled }.count) installed · Stored locally"
                     : model.activity + (model.progress.map { " " + String(Int($0 * 100)) + "%" } ?? ""))
                    .lineLimit(1)
                Spacer()
                Button("Diagnostics") { showDiagnostics = true }.buttonStyle(.plain)
            }.font(.system(size: 12)).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: 10, weight: .bold)).tracking(0.7).foregroundStyle(.secondary)
                    if game.id == "battlenet:osi" && game.isInstalled {
                        Button { vrGame = game } label: {
                            Text("VR").font(.system(size: 9, weight: .heavy)).padding(.horizontal, 5).padding(.vertical, 1.5)
                                .background(Color.purple.opacity(0.18), in: Capsule()).foregroundStyle(.purple)
                        }.buttonStyle(.plain).help("Play in VR or in first person on this Mac")
                            .accessibilityLabel("VR and first person for " + game.title)
                    }
                    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: 15, weight: .semibold)).lineLimit(2)
                    .frame(height: 36, alignment: .topLeading).frame(maxWidth: .infinity, alignment: .leading)
                if let fraction = downloadFraction(game) {
                    ProgressView(value: fraction).controlSize(.small)
                        .accessibilityLabel("Download progress for " + game.title)
                        .accessibilityValue(model.downloads[game.id] ?? "")
                }
                HStack {
                    Text(status(game, issue: issue)).font(.system(size: 11)).lineLimit(1)
                        .foregroundStyle(issue == nil || game.isPartialDownload ? Color.secondary : Color.orange)
                        .help(issue == nil ? game.note ?? "" : "")
                    Spacer()
                    if model.downloads[game.id] != nil {
                        Button { model.stopDownload(game) } label: { Label("Pause", systemImage: "pause.fill") }
                            .controlSize(.small).help("Pause the download. Download again later to continue.")
                            .accessibilityLabel("Pause downloading " + game.title)
                    } else if game.platform == .xbox && model.launchingGames.contains(game.id) {
                        Button { model.stopGame(game) } label: { Label(model.stoppingGames.contains(game.id) ? "Stopping…" : "Stop", systemImage: "stop.fill") }
                            .controlSize(.small).disabled(model.stoppingGames.contains(game.id))
                            .help("Close the game. Soju copies its saves back first.")
                            .accessibilityLabel("Stop " + game.title)
                    } else if game.downloadBlocked {
                        Button { selected = game } label: { Label("Details", systemImage: "info.circle") }
                            .controlSize(.small).accessibilityLabel("Why " + game.title + " cannot be downloaded")
                    } else {
                        Button {
                            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.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)
                    }
                }
            }.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) }.disabled(!game.isInstalled || game.isOnUnpluggedDrive)
                if game.platform.opensAWindow {
                    Button("Open " + game.platform.title) { model.launch(game.platform) }.disabled(model.busy)
                }
                Button("Diagnose") { diagnose(game) }.disabled(model.busy)
                Button("Report How It Ran…") { model.report(game) }
                if game.id == "battlenet:osi" && game.isInstalled {
                    Divider()
                    Button("VR and First Person…") { vrGame = game }
                }
            }
    }

    /// "42% · 3.1 GB / 7.4 GB · 48 MB/s" -> 0.42; nil while preparing or when not downloading.
    private func downloadFraction(_ game: InstalledGame) -> Double? {
        guard let progress = model.downloads[game.id], let head = progress.split(separator: "%").first,
              head.count < progress.count, let value = Double(head) else { return nil }
        return min(max(value / 100, 0), 1)
    }
    private func status(_ game: InstalledGame, issue: String?) -> String {
        // The bar shows the percentage; the caption keeps the size and speed.
        if let progress = model.downloads[game.id] {
            let parts = progress.components(separatedBy: " · ")
            return parts.count > 1 ? parts.dropFirst().joined(separator: " · ") : progress
        }
        if game.isOnUnpluggedDrive { return "Drive not connected" }
        if game.platform == .xbox {
            if game.isPartialDownload { return "Paused" }
            if game.downloadBlocked { return "Not supported" }
        }
        return !game.isInstalled ? "Not installed" : issue != nil ? "Needs attention" : game.blocked != nil ? "Installed · blocked by anti-cheat" : game.note != nil ? "Installed · anti-cheat" : "Installed"
    }

    private func installedLabel(_ game: InstalledGame) -> String {
        guard game.isInstalled else { return "Owned · not installed" }
        if let volume = game.volume, volume != "this Mac" {
            return game.isOnUnpluggedDrive ? "On " + volume + " · drive not connected" : "Installed on " + volume
        }
        return "Installed on this Mac"
    }
    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: 12, weight: .semibold)).foregroundStyle(game.platform.accent)
                    Text(game.title).font(.system(size: 26, weight: .bold, design: .rounded))
                    Label(installedLabel(game), systemImage: !game.isInstalled ? "cloud" : game.volume.map { $0 != "this Mac" } == true ? "externaldrive" : "internaldrive").font(.system(size: 13)).foregroundStyle(.secondary)
                    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: 13)).foregroundStyle(.secondary)
                    if game.downloadBlocked, let issue = game.issue {
                        Label(issue, systemImage: "exclamationmark.triangle").font(.system(size: 13)).foregroundStyle(.orange)
                    }
                    if let issue = model.launchIssue(for: game) {
                        Label(issue, systemImage: "exclamationmark.triangle").font(.system(size: 13)).foregroundStyle(.orange)
                    } else if let blocked = game.blocked {
                        Label(blocked, systemImage: "shield.slash").font(.system(size: 13)).foregroundStyle(.orange).fixedSize(horizontal: false, vertical: true)
                    } else if let note = game.note {
                        Label(note, systemImage: "shield.lefthalf.filled").font(.system(size: 13)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
                    }
                    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: 12)).foregroundStyle(.secondary)
                    Spacer()
                }
            }
            if game.isInstalled {
                Divider()
                GameSettingsSection(game: game, close: { selected = nil })
            }
            if model.busy { BusyBanner(compact: true) }
            HStack {
                Button("Show files") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: game.installPath) }.disabled(!game.isInstalled || game.isOnUnpluggedDrive)
                Button("Diagnose") { diagnose(game) }.disabled(model.busy)
                if game.platform.opensAWindow {
                    Button("Open " + game.platform.title) { model.launch(game.platform) }.disabled(model.busy)
                }
                if game.isInstalled { Button("Report How It Ran…") { model.report(game) } }
                Spacer()
                if game.id == "battlenet:osi" && game.isInstalled {
                    Button { selected = nil; DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { vrGame = game } } label: {
                        Label("VR and First Person", systemImage: "eyeglasses")
                    }
                }
            }
            Divider()
            HStack {
                Button("Stores") { selected = nil; page = "accounts" }
                Spacer()
                Button("Close") { selected = nil }.keyboardShortcut(.cancelAction)
                if model.downloads[game.id] != nil {
                    Button("Pause Download") { model.stopDownload(game) }.keyboardShortcut(.defaultAction)
                } else if game.platform == .xbox && model.launchingGames.contains(game.id) {
                    Button(model.stoppingGames.contains(game.id) ? "Stopping…" : "Stop Game") { model.stopGame(game) }
                        .keyboardShortcut(.defaultAction).disabled(model.stoppingGames.contains(game.id))
                } else if !game.downloadBlocked {
                    Button(primaryTitle(game)) {
                        selected = nil
                        if game.isInstalled { model.play(game) } else { model.installOwnedGame(game) }
                    }
                        .buttonStyle(.borderedProminent).tint(green).keyboardShortcut(.defaultAction)
                        .disabled(model.busy || model.launchIssue(for: game) != nil || model.launchingGames.contains(game.id))
                }
            }
        }.padding(28).frame(width: 640)
    }
    private func primaryTitle(_ game: InstalledGame) -> String {
        if game.platform == .xbox {
            return game.isInstalled ? "Play" : game.isPartialDownload ? "Resume Download" : "Download"
        }
        return game.isInstalled ? "Play" : game.platform == .steam ? "Install in Steam" : "Open Galaxy"
    }
    private var diagnostics: some View {
        VStack(alignment: .leading, spacing: 16) {
            HStack {
                Text("Diagnostics").font(.system(size: 19, weight: .bold))
                Spacer()
                Button("Done") { showDiagnostics = false }.keyboardShortcut(.cancelAction)
            }
            HStack {
                if model.busy { ProgressView().controlSize(.small) }
                Text(model.activity).font(.system(size: 13)).foregroundStyle(model.failed ? Color.orange : Color.secondary)
            }
            ScrollView {
                Text(model.log).font(.system(size: 12, 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("Ask on Discord") { model.copyLog(); NSWorkspace.shared.open(SojuModel.discord) }
                    .help("Copies the log, then opens the Soju Discord so you can paste it")
                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: 40, weight: .light)).opacity(0.75)
                    Text(game.title).font(.system(size: 22, 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
        }
    }
}

/// Shown only to players who keep coming back to a game (StarAsk). One click opens the repository.
struct StarCard: View {
    @EnvironmentObject var model: SojuModel
    let title: String?
    var body: some View {
        HStack(alignment: .center, spacing: 16) {
            Image(systemName: "star.fill").font(.system(size: 32)).foregroundStyle(.yellow)
            VStack(alignment: .leading, spacing: 5) {
                Text((title.map { $0 + " keeps running on Soju." } ?? "Soju keeps working for you.") + " Would you star it on GitHub?")
                    .font(.system(size: 15, weight: .semibold)).fixedSize(horizontal: false, vertical: true)
                Text("Soju is free and open source. Stars are how other Mac players find it, and it takes one click.")
                    .font(.system(size: 13)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
            }
            Spacer(minLength: 8)
            VStack(alignment: .trailing, spacing: 6) {
                Button {
                    NSWorkspace.shared.open(StarAsk.repo); model.starAsk.finish(); model.starAsk.save()
                } label: { Label("Star on GitHub", systemImage: "star") }
                    .buttonStyle(.borderedProminent).controlSize(.large).keyboardShortcut(.defaultAction)
                HStack(spacing: 10) {
                    Button("Join Discord") { NSWorkspace.shared.open(SojuModel.discord) }.buttonStyle(.link)
                    Button("Later") { model.starAsk.later(); model.starAsk.save() }.buttonStyle(.link)
                    Button("Don't ask again") { model.starAsk.finish(); model.starAsk.save() }.buttonStyle(.link)
                }.font(.system(size: 12))
            }
        }.padding(16).frame(maxWidth: .infinity, alignment: .leading)
            .background(Color.yellow.opacity(0.10), in: RoundedRectangle(cornerRadius: 12))
            .overlay(RoundedRectangle(cornerRadius: 12).stroke(Color.yellow.opacity(0.35)))
            .accessibilityElement(children: .contain)
    }
}

/// Shown while Soju runs an operation (an engine update, an install): the buttons that start
/// games are off until it ends, so say what runs, how far it is and that Play comes back.
struct BusyBanner: View {
    @EnvironmentObject var model: SojuModel
    var compact = 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) }

    var body: some View {
        VStack(alignment: .leading, spacing: 9) {
            HStack(spacing: 10) {
                Image(systemName: "arrow.down.circle.fill").font(.system(size: compact ? 16 : 20)).foregroundStyle(green)
                Text(model.activity).font(.system(size: compact ? 13 : 15, weight: .semibold))
                Spacer()
                if let p = model.progress {
                    Text(String(Int(p * 100)) + "%").font(.system(size: compact ? 13 : 15, weight: .semibold).monospacedDigit())
                }
            }
            if let p = model.progress {
                ProgressView(value: p).tint(green)
            } else {
                ProgressView().progressViewStyle(.linear).tint(green)
            }
            Text(([model.progressDetail].filter { !$0.isEmpty } + ["Play comes back when this finishes."]).joined(separator: " · "))
                .font(.system(size: 12)).foregroundStyle(.secondary)
        }.padding(compact ? 12 : 16).frame(maxWidth: .infinity, alignment: .leading)
            .background(green.opacity(0.09), in: RoundedRectangle(cornerRadius: 12))
            .overlay(RoundedRectangle(cornerRadius: 12).stroke(green.opacity(0.25), lineWidth: 1))
            .accessibilityElement(children: .combine)
    }
}