Skip to content

Run Windows games on Apple Silicon — free, open source, with an open compatibility database that tells you what actually works.

GOG: achievement pop-ups, and hand-added programs play as their GOG game

Gabec8de16a9b7da
diff --git a/Sources/HighballApp/AchievementToast.swift b/Sources/HighballApp/AchievementToast.swift
new file mode 100644
index 0000000..7720a48
--- /dev/null
+++ b/Sources/HighballApp/AchievementToast.swift
@@ -0,0 +1,157 @@
+import AppKit
+import SwiftUI
+import HighballKit
+
+/// The achievement pop-up: a card over the game for a few seconds, with a sound. Windowed, it sits
+/// in the game window's bottom-right corner; full screen or borderless (a window that covers its
+/// screen), in that screen's corner, above the game. It never takes focus or a click,
+/// so a game is never interrupted. Several unlocks show one after another.
+@MainActor
+final class AchievementToast {
+ static let shared = AchievementToast()
+ static let enabledDefaultsKey = "gogAchievementPopups"
+ /// On unless turned off in Settings.
+ static var isEnabled: Bool { UserDefaults.standard.object(forKey: enabledDefaultsKey) as? Bool ?? true }
+
+ private var queue: [(achievement: GOGAchievement, gameWindow: CGRect?)] = []
+ private var panel: NSPanel?
+ private var showing = false
+
+ /// `gameWindow` is the game's largest window as CGWindowList reports it, nil when it has none
+ /// on screen (the card then goes to the screen the pointer is on).
+ func show(_ achievement: GOGAchievement, gameWindow: CGRect? = nil) {
+ queue.append((achievement, gameWindow))
+ if !showing { next() }
+ }
+
+ private func next() {
+ guard !queue.isEmpty else { showing = false; return }
+ showing = true
+ let (achievement, gameWindow) = queue.removeFirst()
+ Task {
+ // The badge is loaded first so the card never appears with an empty square.
+ let badge: NSImage? = if let url = achievement.imageURL { await CachedGalleryImageLoader.shared.image(at: url) } else { nil }
+ present(achievement, badge: badge, gameWindow: gameWindow)
+ }
+ }
+
+ private func present(_ achievement: GOGAchievement, badge: NSImage?, gameWindow: CGRect?) {
+ let host = NSHostingView(rootView: AchievementCard(achievement: achievement, badge: badge))
+ let size = host.fittingSize
+ let panel = self.panel ?? Self.makePanel()
+ self.panel = panel
+ panel.contentView = host
+ let shown = Self.frame(for: size, gameWindow: gameWindow)
+ panel.setFrame(shown.offsetBy(dx: 0, dy: -12), display: false)
+ panel.alphaValue = 0
+ panel.orderFrontRegardless()
+ NSSound(named: "Glass")?.play()
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = 0.25
+ panel.animator().alphaValue = 1
+ panel.animator().setFrame(shown, display: true)
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 5.5) { [weak self] in
+ NSAnimationContext.runAnimationGroup({ context in
+ context.duration = 0.35
+ panel.animator().alphaValue = 0
+ }, completionHandler: {
+ MainActor.assumeIsolated {
+ panel.orderOut(nil)
+ self?.next()
+ }
+ })
+ }
+ }
+
+ /// Where the card goes: the bottom-right corner of the game window when it is windowed and
+ /// roomy enough, else of the game's screen (minus the menu bar and Dock), else of the screen
+ /// the pointer is on.
+ static func frame(for size: NSSize, gameWindow: CGRect?) -> NSRect {
+ let margin: CGFloat = 20
+ func corner(of box: NSRect) -> NSRect {
+ NSRect(x: box.maxX - size.width - margin, y: box.minY + margin, width: size.width, height: size.height)
+ }
+ // CGWindowList bounds start at the top left of the main display; AppKit's at the bottom left.
+ if let bounds = gameWindow, let main = NSScreen.screens.first {
+ let window = NSRect(x: bounds.minX, y: main.frame.maxY - bounds.maxY, width: bounds.width, height: bounds.height)
+ func overlap(_ screen: NSScreen) -> CGFloat {
+ let i = screen.frame.intersection(window)
+ return i.isNull ? 0 : i.width * i.height
+ }
+ if let screen = NSScreen.screens.max(by: { overlap($0) < overlap($1) }), overlap(screen) > 0 {
+ let coversScreen = window.width >= screen.frame.width * 0.9 && window.height >= screen.frame.height * 0.9
+ let inside = window.intersection(screen.visibleFrame)
+ let roomy = !inside.isNull && inside.width >= size.width + 2 * margin && inside.height >= size.height + 2 * margin
+ return corner(of: !coversScreen && roomy ? inside : screen.visibleFrame)
+ }
+ }
+ let screen = NSScreen.screens.first { NSMouseInRect(NSEvent.mouseLocation, $0.frame, false) } ?? NSScreen.main
+ return corner(of: screen?.visibleFrame ?? .zero)
+ }
+
+ private static func makePanel() -> NSPanel {
+ let panel = NSPanel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
+ panel.level = .screenSaver // above a full-screen game
+ panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary, .ignoresCycle]
+ panel.hidesOnDeactivate = false // Highball is never the active app while a game runs
+ panel.ignoresMouseEvents = true
+ panel.isOpaque = false
+ panel.backgroundColor = .clear
+ panel.hasShadow = true
+ panel.isReleasedWhenClosed = false
+ return panel
+ }
+}
+
+private struct AchievementCard: View {
+ let achievement: GOGAchievement
+ let badge: NSImage?
+
+ var body: some View {
+ HStack(alignment: .center, spacing: 12) {
+ Group {
+ if let badge {
+ Image(nsImage: badge).resizable().interpolation(.high)
+ } else {
+ Image(systemName: "trophy.fill").font(.title2).foregroundStyle(HB.amber)
+ .frame(maxWidth: .infinity, maxHeight: .infinity).background(Color.white.opacity(0.08))
+ }
+ }
+ .frame(width: 48, height: 48)
+ .clipShape(RoundedRectangle(cornerRadius: 8))
+ VStack(alignment: .leading, spacing: 2) {
+ Text(L("Achievement unlocked").uppercased())
+ .font(.caption2.weight(.semibold)).tracking(0.6).foregroundStyle(HB.amber)
+ Text(achievement.name).font(.headline).lineLimit(1)
+ if !achievement.description.isEmpty {
+ Text(achievement.description).font(.caption).foregroundStyle(.secondary).lineLimit(2)
+ }
+ if let rarity = Self.rarity(achievement) {
+ Text(rarity).font(.caption2).foregroundStyle(.secondary)
+ }
+ }
+ .frame(width: 250, alignment: .leading)
+ }
+ .padding(12)
+ // Dark whatever the game shows behind it, so the text stays readable over a bright scene.
+ .background {
+ RoundedRectangle(cornerRadius: 14).fill(.ultraThinMaterial)
+ RoundedRectangle(cornerRadius: 14).fill(Color.black.opacity(0.6))
+ }
+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Color.white.opacity(0.12)))
+ .environment(\.colorScheme, .dark)
+ .padding(1)
+ }
+
+ /// "Uncommon · 12.1% of players", or whichever half comet has.
+ static func rarity(_ a: GOGAchievement) -> String? {
+ var parts: [String] = []
+ if !a.rarityLevel.isEmpty { parts.append(L(a.rarityLevel)) }
+ if a.rarity > 0 {
+ let share = a.rarity.formatted(.number.precision(.fractionLength(a.rarity < 10 ? 1 : 0)))
+ parts.append(String(format: L("%@%% of players"), share))
+ }
+ return parts.isEmpty ? nil : parts.joined(separator: " · ")
+ }
+}
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index 6235bb1..c4c893a 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -2606,6 +2606,13 @@ final class AppState {
}
func launch(pin: Pin, in bottle: Bottle) {
+ // A program its GOG tile stands for plays as that game, with comet and cloud saves,
+ // wherever it was started from (the environment's Programs list, a tile from before).
+ if let item = gogItem(standingFor: pin, in: bottle) {
+ appendLog("\(pin.name): playing it as \(item.title) from GOG, for achievements and cloud saves")
+ gogPlay(item, in: bottle, renderer: pin.renderer)
+ return
+ }
guard let engine = engine(for: bottle) else { return }
// A pinned program's own mode behind an unaccepted licence gets the same ask as a game's
// (#61); the runner degrades any other mode the engine lacks, with a note.
@@ -3288,6 +3295,15 @@ final class AppState {
if !newIDs.isEmpty, !gogFetchInFlight { gogRefresh() }
}
+ /// The GOG tile that stands for a program added by hand (LibraryIndex.gogCoveredPins), if any.
+ /// Read off the environment's saved pins, so a launch-time mode on `pin` does not hide it.
+ private func gogItem(standingFor pin: Pin, in bottle: Bottle) -> LibraryItem? {
+ let id = "pin:\(bottle.name):\(pin.id.uuidString)"
+ guard let covered = LibraryIndex.gogCoveredPins(bottles: [bottle], gogInstalledByBottle: gogInstalledByBottle)
+ .first(where: { $0.pinItemID == id }) else { return nil }
+ return libraryItems.first { $0.id == covered.gogItemID }
+ }
+
/// A program added by hand that its GOG tile now stands for (LibraryIndex.gogCoveredPins)
/// hands its settings to that tile once: arguments the GOG task does not already pass, the
/// display, the graphics mode. Only where the GOG tile has none of its own, and only once per
@@ -3529,6 +3545,7 @@ final class AppState {
if useComet {
stage = L("Starting comet for achievements")
comet = await gogStartComet(for: game, in: bottle, engine: engine, log: cometLog)
+ if let comet { watchAchievements(of: game, item: item, bottleName: bottle.name, comet: comet, log: cometLog) }
}
if Task.isCancelled {
GOGComet(store: store).stop(comet)
@@ -3640,6 +3657,69 @@ final class AppState {
}
}
+ /// A pop-up for each achievement comet unlocks, for as long as that comet runs: its log says
+ /// which, its database says the rest. Ends by itself once comet has stopped, whichever way
+ /// the launch ended.
+ private func watchAchievements(of game: GOGStore.InstalledGame, item: LibraryItem, bottleName: String, comet: Process, log: URL) {
+ let store = gogStore
+ Task.detached { [weak self] in
+ let reader = GOGAchievements.LogReader(log: log)
+ var clientID: String??
+ var shown: Set<String> = []
+ while true {
+ let running = comet.isRunning // read before the log, so the last lines are never missed
+ let unlocks = reader.newUnlocks().filter { shown.insert($0.key).inserted }
+ if !unlocks.isEmpty {
+ if clientID == nil { clientID = GOGSaves(store: store).clientID(for: game) }
+ let database = clientID.flatMap { $0 }.flatMap { GOGComet(store: store).achievementDatabase(clientID: $0) }
+ for unlock in unlocks {
+ let achievement = GOGAchievements.details(key: unlock.key, name: unlock.name, database: database)
+ await self?.achievementUnlocked(achievement, item: item, bottleName: bottleName)
+ }
+ }
+ if !running { return }
+ try? await Task.sleep(for: .seconds(1))
+ }
+ }
+ }
+
+ private func achievementUnlocked(_ achievement: GOGAchievement, item: LibraryItem, bottleName: String) {
+ appendLog("\(item.title): achievement unlocked, “\(achievement.name)”")
+ guard AchievementToast.isEnabled else { return }
+ // The game's window, so the card lands on it: windowed, full screen or borderless.
+ let session = runningSessions.first { $0.libraryID == item.id && $0.bottleName == bottleName }
+ let prefix = bottles.first { $0.name == bottleName }?.url
+ Task {
+ var window: CGRect?
+ if let session, let prefix {
+ window = await Task.detached { Self.largestWindow(of: SessionWatch.pids(ofPrefix: prefix, markers: session.markers)) }.value
+ }
+ AchievementToast.shared.show(achievement, gameWindow: window)
+ }
+ }
+
+ /// The biggest ordinary window on screen among these processes, in CGWindowList's coordinates.
+ nonisolated private static func largestWindow(of pids: [pid_t]) -> CGRect? {
+ guard !pids.isEmpty,
+ let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] else { return nil }
+ let wanted = Set(pids)
+ return windows.compactMap { info -> CGRect? in
+ guard let pid = info[kCGWindowOwnerPID as String] as? pid_t, wanted.contains(pid),
+ (info[kCGWindowLayer as String] as? Int) == 0,
+ let bounds = info[kCGWindowBounds as String] as? NSDictionary else { return nil }
+ return CGRect(dictionaryRepresentation: bounds)
+ }.max { $0.width * $0.height < $1.width * $1.height }
+ }
+
+ /// Settings' Preview: the pop-up as a game would show it.
+ func previewAchievementPopup() {
+ var sample = GOGAchievement(key: "HIGHBALL_PREVIEW", name: L("First Steps"))
+ sample.description = L("This is how an achievement shows up while you play.")
+ sample.rarity = 31
+ sample.rarityLevel = "Common"
+ AchievementToast.shared.show(sample)
+ }
+
/// The game's cloud-save folders in this environment, empty when it has none or GOG cannot say.
private func gogSaveLocations(_ game: GOGStore.InstalledGame, in bottle: Bottle) async -> [(GOGSaves.Location, URL)] {
let saves = GOGSaves(store: gogStore)
diff --git a/Sources/HighballApp/L10n.swift b/Sources/HighballApp/L10n.swift
index 5231991..f1dfa68 100644
--- a/Sources/HighballApp/L10n.swift
+++ b/Sources/HighballApp/L10n.swift
@@ -34,6 +34,17 @@ enum L10n {
"Connect your Epic account to see and download your games.": "Connectez votre compte Epic pour voir et télécharger vos jeux.",
"Choose an .exe, .msi or .bat file, or drop it on this window.": "Choisissez un fichier .exe, .msi ou .bat, ou déposez-le sur cette fenêtre.",
"Share game activity with Discord": "Partager l’activité de jeu avec Discord",
+ "Achievement unlocked": "Succès débloqué",
+ "%@%% of players": "%@ %% des joueurs",
+ "Common": "Courant",
+ "Uncommon": "Peu courant",
+ "Epic": "Épique",
+ "Legendary": "Légendaire",
+ "First Steps": "Premiers pas",
+ "This is how an achievement shows up while you play.": "Voici comment un succès apparaît pendant que vous jouez.",
+ "Show achievement pop-ups": "Afficher les succès débloqués",
+ "Preview": "Aperçu",
+ "When a GOG game unlocks an achievement, its badge shows in the corner of the screen for a few seconds, with a sound. The game keeps focus.": "Quand un jeu GOG débloque un succès, son badge s’affiche quelques secondes dans le coin de l’écran, avec un son. Le jeu garde la main.",
"Let Discord show what you play and the game's Rich Presence while both apps are open. Off by default.": "Autoriser Discord à afficher vos jeux et leur Rich Presence lorsque les deux applications sont ouvertes. Désactivé par défaut.",
"Frame generation (Lossless Scaling, beta)": "Génération d’images (Lossless Scaling, bêta)",
"How frame generation works": "Comment fonctionne la génération d’images",
diff --git a/Sources/HighballApp/SettingsView.swift b/Sources/HighballApp/SettingsView.swift
index 81c6edf..ccba5c2 100644
--- a/Sources/HighballApp/SettingsView.swift
+++ b/Sources/HighballApp/SettingsView.swift
@@ -239,6 +239,7 @@ struct EnginePane: View {
@Environment(AppState.self) private var state
/// The updater delegate reads the same key: AppStorage so the switch redraws when flipped.
@AppStorage(UpdateChannels.betaDefaultsKey) private var betaUpdates = false
+ @AppStorage(AchievementToast.enabledDefaultsKey) private var achievementPopups = true
@State private var showLicense = false
@State private var pendingRemove: String?
@State private var engineSizes: [String: String] = [:]
@@ -281,6 +282,17 @@ struct EnginePane: View {
.font(.caption).foregroundStyle(.secondary)
}.frame(maxWidth: .infinity, alignment: .leading)
}
+ GroupBox {
+ VStack(alignment: .leading, spacing: 6) {
+ HStack {
+ Toggle(L("Show achievement pop-ups"), isOn: $achievementPopups)
+ Spacer()
+ Button(L("Preview")) { state.previewAchievementPopup() }.controlSize(.small)
+ }
+ Text(L("When a GOG game unlocks an achievement, its badge shows in the corner of the screen for a few seconds, with a sound. The game keeps focus."))
+ .font(.caption).foregroundStyle(.secondary)
+ }.frame(maxWidth: .infinity, alignment: .leading)
+ }
if let update = state.engineUpdate {
GroupBox {
HStack {
diff --git a/Sources/HighballKit/GOGAchievements.swift b/Sources/HighballKit/GOGAchievements.swift
new file mode 100644
index 0000000..5206f29
--- /dev/null
+++ b/Sources/HighballKit/GOGAchievements.swift
@@ -0,0 +1,91 @@
+import Foundation
+import SQLite3
+
+/// Achievements unlocked while a GOG game runs, for the pop-up. comet logs each unlock
+/// ("Unlocking achievement KEY, Name") and keeps the game's achievement list, with each one's
+/// description, badge and rarity, in its own database under its home; both are read here, nothing
+/// is fetched from gog.com but the badge image.
+public struct GOGAchievement: Sendable, Equatable {
+ public let key: String
+ public let name: String
+ public var description = ""
+ public var imageURL: URL?
+ /// Share of players who have it, in percent; 0 when comet has no figure.
+ public var rarity: Double = 0
+ /// GOG's word for that share ("Common", "Uncommon", "Rare", "Epic", "Legendary").
+ public var rarityLevel = ""
+
+ public init(key: String, name: String) {
+ self.key = key
+ self.name = name
+ }
+}
+
+public enum GOGAchievements {
+ /// The unlocks in a stretch of comet's log, in order, as (key, name). A name may hold commas;
+ /// a key never does.
+ public static func unlocks(in text: String) -> [(key: String, name: String)] {
+ text.split(whereSeparator: \.isNewline).compactMap { line in
+ guard let match = line.firstMatch(of: #/Unlocking achievement ([^\s,]+), (.*)$/#) else { return nil }
+ return (String(match.1), String(match.2).trimmingCharacters(in: .whitespaces))
+ }
+ }
+
+ /// comet's database for a game: gameplay/<client id>/<user id>/gameplay.db under its home.
+ /// The newest when more than one account has played it here.
+ public static func database(home: URL, clientID: String) -> URL? {
+ let dir = home.appending(path: "Library/Application Support/comet/gameplay/\(clientID)", directoryHint: .isDirectory)
+ let users = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? []
+ return users.map { $0.appending(path: "gameplay.db") }
+ .filter { FileManager.default.fileExists(atPath: $0.path) }
+ .max { modified($0) < modified($1) }
+ }
+
+ private static func modified(_ url: URL) -> Date {
+ ((try? FileManager.default.attributesOfItem(atPath: url.path))?[.modificationDate] as? Date) ?? .distantPast
+ }
+
+ /// The unlocked achievement as comet knows it, or only its key and logged name when the
+ /// database cannot say. Opened read-only: comet keeps writing to it.
+ public static func details(key: String, name: String, database: URL?) -> GOGAchievement {
+ var achievement = GOGAchievement(key: key, name: name)
+ guard let database else { return achievement }
+ var db: OpaquePointer?
+ defer { sqlite3_close(db) }
+ guard sqlite3_open_v2(database.path, &db, SQLITE_OPEN_READONLY, nil) == SQLITE_OK else { return achievement }
+ sqlite3_busy_timeout(db, 500)
+ var statement: OpaquePointer?
+ defer { sqlite3_finalize(statement) }
+ let sql = "SELECT name, description, image_url_unlocked, rarity, rarity_level_description FROM achievement WHERE key = ?"
+ guard sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK else { return achievement }
+ // SQLITE_TRANSIENT: SQLite copies the key before this call returns.
+ sqlite3_bind_text(statement, 1, key, -1, unsafeBitCast(-1, to: sqlite3_destructor_type.self))
+ guard sqlite3_step(statement) == SQLITE_ROW else { return achievement }
+ func text(_ column: Int32) -> String { sqlite3_column_text(statement, column).map { String(cString: $0) } ?? "" }
+ if !text(0).isEmpty { achievement = GOGAchievement(key: key, name: text(0)) }
+ achievement.description = text(1)
+ achievement.imageURL = URL(string: text(2)).flatMap { $0.scheme == "https" ? $0 : nil }
+ achievement.rarity = sqlite3_column_double(statement, 3)
+ achievement.rarityLevel = text(4)
+ return achievement
+ }
+
+ /// Reads comet's log as it grows: each call returns the unlocks written since the last.
+ /// Only whole lines are taken, so a line comet is halfway through writing waits for the next call.
+ public final class LogReader: @unchecked Sendable {
+ let log: URL
+ private var offset: UInt64 = 0
+
+ public init(log: URL) { self.log = log }
+
+ public func newUnlocks() -> [(key: String, name: String)] {
+ guard let handle = try? FileHandle(forReadingFrom: log) else { return [] }
+ defer { try? handle.close() }
+ guard (try? handle.seek(toOffset: offset)) != nil, let data = try? handle.readToEnd(),
+ let lastNewline = data.lastIndex(of: UInt8(ascii: "\n")) else { return [] }
+ let whole = data[data.startIndex...lastNewline]
+ offset += UInt64(whole.count)
+ return GOGAchievements.unlocks(in: String(decoding: whole, as: UTF8.self))
+ }
+ }
+}
diff --git a/Sources/HighballKit/GOGComet.swift b/Sources/HighballKit/GOGComet.swift
index 4b6c303..e2ad462 100644
--- a/Sources/HighballKit/GOGComet.swift
+++ b/Sources/HighballKit/GOGComet.swift
@@ -72,6 +72,9 @@ public struct GOGComet: Sendable {
try? FileManager.default.removeItem(at: authCopy)
}
+ /// comet's database of a game's achievements, for the unlock pop-up (GOGAchievements).
+ public func achievementDatabase(clientID: String) -> URL? { GOGAchievements.database(home: home, clientID: clientID) }
+
/// Whether comet came up and is listening, read from its log ("Listening on port 9977").
public static func isListening(log: URL) -> Bool {
((try? String(contentsOf: log, encoding: .utf8)) ?? "").contains("Listening on port")
diff --git a/Tests/HighballKitTests/GOGStoreTests.swift b/Tests/HighballKitTests/GOGStoreTests.swift
index 248d3c2..b24a7f5 100644
--- a/Tests/HighballKitTests/GOGStoreTests.swift
+++ b/Tests/HighballKitTests/GOGStoreTests.swift
@@ -377,4 +377,60 @@ final class GOGStoreTests: XCTestCase {
let notHere = LibraryItem(source: .gog, id: "gog:7", title: "X", bottleName: nil, installed: false, gogID: "7")
XCTAssertFalse(Uninstall.isActionable(Uninstall.route(for: notHere)))
}
+
+ /// comet's unlock lines, as v0.4.0 writes them; a name may hold a comma.
+ func testAchievementUnlocksAreReadOffCometsLog() {
+ let log = """
+ [2026-10-28T14:15:48Z INFO comet::api::handlers] Uploading new achievements
+ [2026-10-28T14:32:50Z INFO comet::api::handlers::utils] Unlocking achievement HILT_ACHIEVEMENT, Choose to be Chosen
+ [2026-10-28T14:40:01Z INFO comet::api::handlers::utils] Unlocking achievement A_2, Well, That Happened
+ """
+ let unlocks = GOGAchievements.unlocks(in: log)
+ XCTAssertEqual(unlocks.map(\.key), ["HILT_ACHIEVEMENT", "A_2"])
+ XCTAssertEqual(unlocks.map(\.name), ["Choose to be Chosen", "Well, That Happened"])
+ }
+
+ /// Each read returns only what is new, and a line still being written waits for the next read.
+ func testAchievementLogReaderTakesWholeNewLinesOnce() throws {
+ let log = FileManager.default.temporaryDirectory.appending(path: "comet-\(UUID().uuidString).log")
+ defer { try? FileManager.default.removeItem(at: log) }
+ try "x Unlocking achievement ONE, First\nx Unlocking achievement TWO, Sec".write(to: log, atomically: true, encoding: .utf8)
+ let reader = GOGAchievements.LogReader(log: log)
+ XCTAssertEqual(reader.newUnlocks().map(\.key), ["ONE"])
+ XCTAssertTrue(reader.newUnlocks().isEmpty)
+ let handle = try FileHandle(forWritingTo: log)
+ try handle.seekToEnd()
+ try handle.write(contentsOf: Data("ond\n".utf8))
+ try handle.close()
+ XCTAssertEqual(reader.newUnlocks().map(\.name), ["Second"])
+ }
+
+ /// The pop-up's details come from comet's database, found by client id; a key it lacks keeps
+ /// the logged name.
+ func testAchievementDetailsComeFromCometsDatabase() throws {
+ let home = FileManager.default.temporaryDirectory.appending(path: "comet-home-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: home) }
+ let dir = home.appending(path: "Library/Application Support/comet/gameplay/5353/1001")
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let file = dir.appending(path: "gameplay.db")
+ let sql = """
+ CREATE TABLE achievement (id INTEGER PRIMARY KEY, key TEXT UNIQUE NOT NULL, name TEXT NOT NULL, description TEXT NOT NULL,
+ visible_while_locked INTEGER NOT NULL, unlock_time TEXT, image_url_locked TEXT NOT NULL, image_url_unlocked TEXT NOT NULL,
+ changed INTEGER NOT NULL, rarity REAL NOT NULL DEFAULT 0.0, rarity_level_description TEXT NOT NULL DEFAULT "",
+ rarity_level_slug TEXT NOT NULL DEFAULT "");
+ INSERT INTO achievement VALUES (1, 'HARTFELT', 'The Third Thing', 'Defeat Hartman', 0, NULL,
+ 'https://images.gog.com/a_gac_60.jpg', 'https://images.gog.com/b_gac_60.jpg', 0, 12.1, 'Uncommon', 'uncommon');
+ """
+ _ = try Shell.capture("/usr/bin/sqlite3", [file.path, sql])
+ let db = GOGAchievements.database(home: home, clientID: "5353")
+ XCTAssertEqual(db?.lastPathComponent, "gameplay.db")
+ XCTAssertNil(GOGAchievements.database(home: home, clientID: "9999"))
+ let found = GOGAchievements.details(key: "HARTFELT", name: "logged", database: db)
+ XCTAssertEqual(found.name, "The Third Thing")
+ XCTAssertEqual(found.description, "Defeat Hartman")
+ XCTAssertEqual(found.imageURL?.absoluteString, "https://images.gog.com/b_gac_60.jpg")
+ XCTAssertEqual(found.rarity, 12.1, accuracy: 0.001)
+ XCTAssertEqual(found.rarityLevel, "Uncommon")
+ XCTAssertEqual(GOGAchievements.details(key: "OTHER", name: "logged", database: db), GOGAchievement(key: "OTHER", name: "logged"))
+ }
}