diff --git a/CHANGELOG.md b/CHANGELOG.md index ceccdbf..bcec19a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ User-visible changes to NX Library are recorded here. Entries are grouped by release, with the newest first. Engine changes also have their own [upgrade notes](docs/upstream-upgrades/README.md). +## Unreleased + +- Game icons load in the background and are cached locally between launches, so opening the collection can show a placeholder while a network game folder is slow or unavailable. + ## 0.1.4.3 — 2026-11-12 ### Added diff --git a/Sources/NXLibrary/ViewModels/AppViewModel+AppIcon.swift b/Sources/NXLibrary/ViewModels/AppViewModel+AppIcon.swift index eab4b3e..15d8e24 100644 --- a/Sources/NXLibrary/ViewModels/AppViewModel+AppIcon.swift +++ b/Sources/NXLibrary/ViewModels/AppViewModel+AppIcon.swift @@ -155,7 +155,7 @@ extension AppViewModel { self.appIconProgress[game.id] = again ? .updating : status if changed { Self.refreshIcon(of: app) - GameIconProvider.forget(game) + GameIconProvider.shared.forget(game) GameArtLoader.shared.forget(game) ArtworkPicks.shared.touch() self.logs.append(LogEntry(level: .info, message: L10n.format("Updated the app icon of %@.", [String(describing: (game.name))]))) diff --git a/Sources/NXLibrary/Views/AddGame/AddGameStepThreeView.swift b/Sources/NXLibrary/Views/AddGame/AddGameStepThreeView.swift index e9ade79..e7e2f10 100644 --- a/Sources/NXLibrary/Views/AddGame/AddGameStepThreeView.swift +++ b/Sources/NXLibrary/Views/AddGame/AddGameStepThreeView.swift @@ -3,6 +3,7 @@ import AppKit import NXLibraryCore struct AddGameStepThreeView: View { + @ObservedObject private var gameIcons = GameIconProvider.shared @ObservedObject var viewModel: AppViewModel @ObservedObject var router: AppRouter var artwork: ArtworkStore? = nil @@ -74,7 +75,7 @@ struct AddGameStepThreeView: View { if let artwork { SpotlightTileArtwork(game: game, side: side, artwork: artwork, ownIconFirst: true) } else { - Image(nsImage: GameIconProvider.squareArt(for: game) ?? GameIconProvider.icon(for: game)) + Image(nsImage: gameIcons.squareArt(for: game) ?? gameIcons.icon(for: game)) .resizable() .aspectRatio(contentMode: .fill) } diff --git a/Sources/NXLibrary/Views/Components/GameIconProvider.swift b/Sources/NXLibrary/Views/Components/GameIconProvider.swift deleted file mode 100644 index d8bd9f8..0000000 --- a/Sources/NXLibrary/Views/Components/GameIconProvider.swift +++ /dev/null @@ -1,69 +0,0 @@ -import AppKit -import NXLibraryCore - -/// The installed app has the game's icon. Before a build succeeds, use the -/// icon nxnative already extracted into the workspace instead of the generic -/// folder icon. -public enum GameIconProvider { - private static let cache = NSCache() - - public static func icon(for game: PortedGame) -> NSImage { - let key = game.uniqueKey as NSString - if let cached = cache.object(forKey: key) { return cached } - - let appURL = game.url - let isApp = appURL.pathExtension.lowercased() == "app" - && FileManager.default.fileExists( - atPath: appURL.appendingPathComponent("Contents/Info.plist").path - ) - - if isApp { - let icon = NSWorkspace.shared.icon(forFile: appURL.path) - cache.setObject(icon, forKey: key) - return icon - } - - if let workspace = game.workspacePath, let titleId = game.titleId, !titleId.isEmpty { - let extracted = URL(fileURLWithPath: workspace) - .appendingPathComponent("\(titleId)_build/extract/v0/icon.jpg") - if let icon = NSImage(contentsOf: extracted) { - cache.setObject(icon, forKey: key) - return icon - } - } - - let icon = NSWorkspace.shared.icon(forFile: appURL.path) - cache.setObject(icon, forKey: key) - return icon - } - - private static let artCache = NSCache() - - /// The app's icon changed (`AppIconWriter`): read it again. - public static func forget(_ game: PortedGame) { - cache.removeObject(forKey: game.uniqueKey as NSString) - artCache.removeObject(forKey: game.uniqueKey as NSString) - } - - /// The game's own square icon art, full bleed: the built app's icon file - /// (what Finder and the Dock show), else the icon nxnative extracted into - /// the workspace. Nil when neither exists. - public static func squareArt(for game: PortedGame) -> NSImage? { - let key = game.uniqueKey as NSString - if let cached = artCache.object(forKey: key) { return cached } - - var image: NSImage? - let appURL = game.url - if appURL.pathExtension.lowercased() == "app", let bundle = Bundle(url: appURL) { - let name = bundle.object(forInfoDictionaryKey: "CFBundleIconFile") as? String ?? "AppIcon" - let file = (name as NSString).pathExtension.isEmpty ? name + ".icns" : name - image = NSImage(contentsOf: appURL.appendingPathComponent("Contents/Resources/\(file)")) - } - if image == nil, let workspace = game.workspacePath, let titleId = game.titleId, !titleId.isEmpty { - image = NSImage(contentsOf: URL(fileURLWithPath: workspace) - .appendingPathComponent("\(titleId)_build/extract/v0/icon.jpg")) - } - if let image { artCache.setObject(image, forKey: key) } - return image - } -} diff --git a/Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift b/Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift index 4697cb4..383a47b 100644 --- a/Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift +++ b/Sources/NXLibrary/Views/Components/SpotlightTileArtwork.swift @@ -9,6 +9,7 @@ import NXLibraryCore /// generic icon. Crossfades when fetched art arrives. /// The caller applies the corner radius. struct SpotlightTileArtwork: View { + @ObservedObject private var gameIcons = GameIconProvider.shared let game: PortedGame /// Side length in points, already scaled by the caller. let side: CGFloat @@ -29,7 +30,7 @@ struct SpotlightTileArtwork: View { .resizable() .interpolation(.high) .aspectRatio(contentMode: .fill) - } else if ownIconFirst, let own = GameIconProvider.squareArt(for: game) { + } else if ownIconFirst, let own = gameIcons.squareArt(for: game) { Image(nsImage: own) .resizable() .interpolation(.high) @@ -40,7 +41,7 @@ struct SpotlightTileArtwork: View { .aspectRatio(contentMode: .fill) .transition(.opacity) } else { - Image(nsImage: GameIconProvider.icon(for: game)) + Image(nsImage: gameIcons.icon(for: game)) .resizable() .aspectRatio(contentMode: .fill) } @@ -53,7 +54,7 @@ struct SpotlightTileArtwork: View { return } picked = nil - guard !ownIconFirst || GameIconProvider.squareArt(for: game) == nil else { return } + guard !ownIconFirst || gameIcons.squareArt(for: game) == nil else { return } let key = game.id.uuidString as NSString if let memo = TileArtMemo.shared.object(forKey: key) { better = memo diff --git a/Sources/NXLibrary/Views/Components/SwitchBoxArtCover.swift b/Sources/NXLibrary/Views/Components/SwitchBoxArtCover.swift index 3040f9e..217ebd2 100644 --- a/Sources/NXLibrary/Views/Components/SwitchBoxArtCover.swift +++ b/Sources/NXLibrary/Views/Components/SwitchBoxArtCover.swift @@ -8,6 +8,7 @@ import NXLibraryCore /// is found, or when GameTDB has none, a composed cover: the blurred Title DB /// banner, the game's icon and its name. The caller applies the corner radius. struct SwitchBoxArtCover: View { + @ObservedObject private var gameIcons = GameIconProvider.shared let game: PortedGame let width: CGFloat let height: CGFloat @@ -56,7 +57,7 @@ struct SwitchBoxArtCover: View { } LinearGradient(colors: [.black.opacity(0.05), .black.opacity(0.6)], startPoint: .top, endPoint: .bottom) VStack(spacing: height * 0.05) { - Image(nsImage: icon ?? GameIconProvider.icon(for: game)) + Image(nsImage: gameIcons.squareArt(for: game) ?? icon ?? gameIcons.icon(for: game)) .resizable() .interpolation(.high) .aspectRatio(contentMode: .fill) @@ -106,7 +107,7 @@ struct SwitchBoxArtCover: View { /// The banner and Title DB icon for the composed cover (both cached on disk). private func loadComposedArt() async { - if let own = GameIconProvider.squareArt(for: game) { + if let own = gameIcons.squareArt(for: game) { icon = own } else if let titleId = game.titleId, let url = await artwork.automaticIcon(titleID: titleId, name: game.name) { diff --git a/Sources/NXLibrary/Views/Detail/GameDetailView.swift b/Sources/NXLibrary/Views/Detail/GameDetailView.swift index d5d1a2b..26a4af8 100644 --- a/Sources/NXLibrary/Views/Detail/GameDetailView.swift +++ b/Sources/NXLibrary/Views/Detail/GameDetailView.swift @@ -14,6 +14,7 @@ final class DetailsModelCache { /// with a title ID) and More like this, one band pitch (230) apart. A band below the one in focus peeks in, blurred, until /// it is focused. Input lives in GameDetailView+Input.swift. struct GameDetailView: View { + @ObservedObject private var gameIcons = GameIconProvider.shared @ObservedObject var viewModel: AppViewModel @ObservedObject var router: AppRouter @ObservedObject var settings: AppSettingsStore @@ -134,7 +135,7 @@ struct GameDetailView: View { cache.model = model return ZStack(alignment: .topLeading) { DetailsBackground(image: art.image, imageKey: art.key, - fallback: GameIconProvider.icon(for: game), + fallback: gameIcons.icon(for: game), shade: settings.settings.backgroundShade) SeleneBottomScrim() stage(model) diff --git a/Sources/NXLibrary/Views/Theme/ThemePreview.swift b/Sources/NXLibrary/Views/Theme/ThemePreview.swift index 12bce29..380ca56 100644 --- a/Sources/NXLibrary/Views/Theme/ThemePreview.swift +++ b/Sources/NXLibrary/Views/Theme/ThemePreview.swift @@ -6,6 +6,7 @@ import NXLibraryCore /// a palette that need not be active yet, over its wallpaper or, without one, /// its own moonlight backdrop. Tiles show the library's own square art. struct ThemePreview: View { + @ObservedObject private var gameIcons = GameIconProvider.shared @Environment(\.seleneCanvas) private var canvas let palette: SelenePalette let wallpaperURL: URL? @@ -18,7 +19,6 @@ struct ThemePreview: View { var shade: BackgroundShade = .balanced @Environment(\.seleneBackdropStyle) private var style - @State private var art: [NSImage] = [] @State private var videoReady = false var body: some View { @@ -59,9 +59,6 @@ struct ThemePreview: View { .animation(.easeOut(duration: 0.25), value: palette.id) .animation(.easeOut(duration: 0.25), value: wallpaperURL) } - .task(id: games.map(\.id)) { - art = games.prefix(6).map { GameIconProvider.squareArt(for: $0) ?? GameIconProvider.icon(for: $0) } - } .accessibilityHidden(true) } @@ -80,8 +77,8 @@ struct ThemePreview: View { ForEach(0..<6, id: \.self) { index in ZStack { glass - if index < art.count { - Image(nsImage: art[index]).resizable().interpolation(.high).aspectRatio(contentMode: .fill) + if index < games.count { + Image(nsImage: gameIcons.icon(for: games[index])).resizable().interpolation(.high).aspectRatio(contentMode: .fill) } } .frame(width: tile, height: tile) diff --git a/Sources/NXLibraryCore/Services/GameIconProvider.swift b/Sources/NXLibraryCore/Services/GameIconProvider.swift new file mode 100644 index 0000000..8692876 --- /dev/null +++ b/Sources/NXLibraryCore/Services/GameIconProvider.swift @@ -0,0 +1,138 @@ +import AppKit +import Combine +import ImageIO + +/// View bodies only consult memory. Disk hits run independently of slow bundle reads so an +/// unavailable share can't hold cached artwork for other games behind it. +@MainActor +public final class GameIconProvider: ObservableObject { + public static let shared = GameIconProvider() + private let placeholder = NSImage(systemSymbolName: "gamecontroller.fill", accessibilityDescription: nil) + ?? NSImage(size: NSSize(width: 64, height: 64)) + private let directory: URL + private let disk = DispatchQueue(label: "local.nxlibrary.icon-cache", qos: .utility) + private let sources = OperationQueue() + private let read: @Sendable (Revision) -> Data? + private let images = NSCache() + private var entries: [UUID: Entry] = [:] + + struct Revision: Codable, Equatable, Sendable { + let titleId: String? + let app: URL + let date: Date + let workspace: String? + } + + private struct Thumbnail: Codable { + let revision: Revision + let png: Data + } + + private struct Entry { + let revision: Revision + let token = UUID() + var loading = true + var retryAfter = Date.distantPast + } + + init(directory: URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] + .appendingPathComponent("NXLibrary/GameIcons", isDirectory: true), + read: @escaping @Sendable (Revision) -> Data? = { GameIconProvider.readThumbnail($0) }) { + self.directory = directory + self.read = read + sources.maxConcurrentOperationCount = 2 + sources.qualityOfService = .utility + images.countLimit = 128 + } + + public func icon(for game: PortedGame) -> NSImage { + squareArt(for: game) ?? placeholder + } + + public func squareArt(for game: PortedGame) -> NSImage? { + let revision = Revision(titleId: game.titleId, app: game.url, date: game.modificationDate, workspace: game.workspacePath) + let id = game.id + if let entry = entries[id], entry.revision == revision { + if let image = images.object(forKey: id as NSUUID) { return image } + if entry.loading || entry.retryAfter > Date() { return nil } + } + + let entry = Entry(revision: revision) + entries[id] = entry + images.removeObject(forKey: id as NSUUID) + let file = cacheFile(id) + let read = self.read + let sources = self.sources + disk.async { + if let data = try? Data(contentsOf: file), + let thumbnail = try? PropertyListDecoder().decode(Thumbnail.self, from: data), + thumbnail.revision == revision, let image = NSImage(data: thumbnail.png) { + Task { @MainActor in self.finish(image, id: id, entry: entry) } + return + } + sources.addOperation { + let data = read(revision) + let image = data.flatMap(NSImage.init(data:)) + Task { @MainActor in + guard self.entries[id]?.token == entry.token else { return } + if let data, image != nil { + self.disk.async { + try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), + withIntermediateDirectories: true) + if let record = try? PropertyListEncoder().encode(Thumbnail(revision: revision, png: data)) { + try? record.write(to: file, options: .atomic) + } + } + } + self.finish(image, id: id, entry: entry) + } + } + } + return nil + } + + private func finish(_ image: NSImage?, id: UUID, entry: Entry) { + guard entries[id]?.token == entry.token else { return } + entries[id]?.loading = false + if let image { + images.setObject(image, forKey: id as NSUUID) + objectWillChange.send() + } else { + entries[id]?.retryAfter = Date().addingTimeInterval(30) + } + } + + private func cacheFile(_ id: UUID) -> URL { + directory.appendingPathComponent(id.uuidString, isDirectory: false) + } + + public func forget(_ game: PortedGame) { + entries.removeValue(forKey: game.id) + images.removeObject(forKey: game.id as NSUUID) + let file = cacheFile(game.id) + disk.async { try? FileManager.default.removeItem(at: file) } + objectWillChange.send() + } + + nonisolated static func readThumbnail(_ revision: Revision) -> Data? { + var urls: [URL] = [] + if revision.app.pathExtension.lowercased() == "app", let bundle = Bundle(url: revision.app) { + let name = bundle.object(forInfoDictionaryKey: "CFBundleIconFile") as? String ?? "AppIcon" + let file = (name as NSString).pathExtension.isEmpty ? name + ".icns" : name + urls.append(revision.app.appendingPathComponent("Contents/Resources/" + file)) + } + if let path = revision.workspace, let id = revision.titleId, !id.isEmpty { + urls.append(URL(fileURLWithPath: path).appendingPathComponent("\(id)_build/extract/v0/icon.jpg")) + } + let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: 512] + for url in urls { + if let source = CGImageSourceCreateWithURL(url as CFURL, nil), + let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) { + return NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:]) + } + } + return nil + } +} diff --git a/Tests/NXLibraryCoreTests/GameIconProviderTests.swift b/Tests/NXLibraryCoreTests/GameIconProviderTests.swift new file mode 100644 index 0000000..5c8f91d --- /dev/null +++ b/Tests/NXLibraryCoreTests/GameIconProviderTests.swift @@ -0,0 +1,53 @@ +import AppKit +import XCTest +@testable import NXLibraryCore + +final class GameIconProviderTests: XCTestCase { + private func game() -> PortedGame { + PortedGame(name: "Fixture", url: URL(fileURLWithPath: "/Volumes/Test/Example.app", isDirectory: true), + platform: .macApp, sizeBytes: 1, modificationDate: Date(timeIntervalSince1970: 1000)) + } + + @MainActor + func testSlowSourceDoesNotBlockAndNextLaunchCanUseDiskOffline() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: directory) } + let game = game() + let png = try XCTUnwrap(NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 2, pixelsHigh: 2, + bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, + bytesPerRow: 0, bitsPerPixel: 32)?.representation(using: .png, properties: [:])) + let gate = DispatchSemaphore(value: 0) + let read = expectation(description: "one source read") + let provider = GameIconProvider(directory: directory) { _ in + XCTAssertFalse(Thread.isMainThread) + read.fulfill() + guard gate.wait(timeout: .now() + 3) == .success else { return nil } + return png + } + XCTAssertNil(provider.squareArt(for: game)) + await fulfillment(of: [read], timeout: 2) + XCTAssertNil(provider.squareArt(for: game)) + gate.signal() + let file = directory.appendingPathComponent(game.id.uuidString) + for _ in 0..<200 where provider.squareArt(for: game) == nil || !FileManager.default.fileExists(atPath: file.path) { + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertNotNil(provider.squareArt(for: game)) + XCTAssertTrue(FileManager.default.fileExists(atPath: file.path)) + let changed = expectation(description: "changed bundle gets a fresh lookup") + let initialDate = game.modificationDate + let nextLaunch = GameIconProvider(directory: directory) { request in + XCTAssertNotEqual(request.date, initialDate, "matching cached icon must not open the share") + changed.fulfill() + return nil + } + for _ in 0..<200 where nextLaunch.squareArt(for: game) == nil { + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertNotNil(nextLaunch.squareArt(for: game)) + var rebuilt = game + rebuilt.modificationDate = game.modificationDate.addingTimeInterval(60) + XCTAssertNil(nextLaunch.squareArt(for: rebuilt)) + await fulfillment(of: [changed], timeout: 2) + } +}