Skip to content

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

Covers: crop to 2:3 at import, show the chosen cover on the game page (#64)

Gauthier Piarrette8ac7a45e658d
diff --git a/Sources/HighballApp/GameDetailView.swift b/Sources/HighballApp/GameDetailView.swift
index e2eda62..21440a3 100644
--- a/Sources/HighballApp/GameDetailView.swift
+++ b/Sources/HighballApp/GameDetailView.swift
@@ -59,18 +59,24 @@ struct GameDetailView: View {
Color.clear
.aspectRatio(460 / 215, contentMode: .fit)
.frame(maxWidth: 640)
- .overlay(
- AsyncImage(url: item.artworkWide ?? item.artworkTall) { phase in
- if case .success(let image) = phase {
- image.resizable().scaledToFill()
- } else {
- ZStack {
- LinearGradient(colors: [HB.card, HB.ground], startPoint: .top, endPoint: .bottom)
- Image(systemName: "gamecontroller").font(.largeTitle).foregroundStyle(.quaternary)
+ .overlay {
+ // A chosen cover wins here as it does on the tile (#64: it never reached
+ // the page, which read the store's artwork only).
+ if let custom = state.coverStore.coverURL(for: item.id), let image = NSImage(contentsOf: custom) {
+ Image(nsImage: image).resizable().scaledToFill().id(state.coverVersion)
+ } else {
+ AsyncImage(url: item.artworkWide ?? item.artworkTall) { phase in
+ if case .success(let image) = phase {
+ image.resizable().scaledToFill()
+ } else {
+ ZStack {
+ LinearGradient(colors: [HB.card, HB.ground], startPoint: .top, endPoint: .bottom)
+ Image(systemName: "gamecontroller").font(.largeTitle).foregroundStyle(.quaternary)
+ }
}
}
}
- )
+ }
.clipped()
LinearGradient(colors: [.black.opacity(0.8), .clear], startPoint: .bottom, endPoint: .center)
.frame(maxWidth: 640)
diff --git a/Sources/HighballApp/LibraryView.swift b/Sources/HighballApp/LibraryView.swift
index 159e73a..984a0a8 100644
--- a/Sources/HighballApp/LibraryView.swift
+++ b/Sources/HighballApp/LibraryView.swift
@@ -333,31 +333,32 @@ struct CoverArt: View {
}
var body: some View {
- GeometryReader { geo in
- // A user-chosen cover always wins (coverVersion invalidates after changes).
- if let custom = state.coverStore.coverURL(for: item.id),
- let image = NSImage(contentsOf: custom) {
- Image(nsImage: image).resizable().scaledToFill()
- .frame(width: geo.size.width, height: geo.size.height)
- .clipped()
- .id(state.coverVersion)
- } else if let url {
- AsyncImage(url: url) { phase in
- switch phase {
- case .success(let image):
- image.resizable().scaledToFill()
- case .failure:
- placeholder.onAppear { stage += 1 }
- default:
- Rectangle().fill(HB.card)
+ // The tile takes the size its parent proposes; the image lives in an overlay, so its
+ // own dimensions never take part in layout and the crop is a plain clip. The previous
+ // GeometryReader-and-frame form rendered nothing on a macOS 27 beta for any image whose
+ // aspect was not exactly 2:3 (#64): a chosen cover, or Steam's wide fallback art.
+ Color.clear
+ .overlay {
+ // A user-chosen cover always wins (coverVersion invalidates after changes).
+ if let custom = state.coverStore.coverURL(for: item.id),
+ let image = NSImage(contentsOf: custom) {
+ Image(nsImage: image).resizable().scaledToFill().id(state.coverVersion)
+ } else if let url {
+ AsyncImage(url: url) { phase in
+ switch phase {
+ case .success(let image):
+ image.resizable().scaledToFill()
+ case .failure:
+ placeholder.onAppear { stage += 1 }
+ default:
+ Rectangle().fill(HB.card)
+ }
}
+ } else {
+ placeholder
}
- .frame(width: geo.size.width, height: geo.size.height)
- .clipped()
- } else {
- placeholder.frame(width: geo.size.width, height: geo.size.height)
}
- }
+ .clipped()
}
private var placeholder: some View {
diff --git a/Sources/HighballKit/Library.swift b/Sources/HighballKit/Library.swift
index f28ef28..90384f1 100644
--- a/Sources/HighballKit/Library.swift
+++ b/Sources/HighballKit/Library.swift
@@ -1,4 +1,6 @@
import Foundation
+import CoreGraphics
+import ImageIO
// The unified library (One Library, Phase 2): every playable thing across all bottles and
// sources as one flat, source-neutral list. The store is a badge and a filter, never a
@@ -193,12 +195,60 @@ public struct CoverStore: Sendable {
}
/// Copies the chosen image in (replacing any previous override).
+ /// The tile's aspect and the stored cover's cap. Covers are normalized at import: centre-
+ /// cropped to 2:3, capped at `maxHeight` pixels tall, written as PNG, orientation applied.
+ /// The crop belongs here and not to a layout: a macOS 27 beta drew nothing for a tile image
+ /// of any other aspect (#64), and a 20 MB photo should not travel the library as a texture.
+ public static let aspect: Double = 2.0 / 3.0
+ public static let maxHeight = 900
+
public func setCover(for id: String, from source: URL) throws {
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let png = try Self.normalized(imageAt: source)
clearCover(for: id)
- let ext = source.pathExtension.isEmpty ? "png" : source.pathExtension.lowercased()
- let dest = dir.appending(path: Self.filename(for: id)).appendingPathExtension(ext)
- try FileManager.default.copyItem(at: source, to: dest)
+ let dest = dir.appending(path: Self.filename(for: id)).appendingPathExtension("png")
+ try png.write(to: dest, options: .atomic)
+ }
+
+ /// The stored form of an image file: 2:3, capped, PNG. Refuses what ImageIO cannot read.
+ public static func normalized(imageAt url: URL) throws -> Data {
+ // A thumbnail request applies the EXIF orientation and pre-shrinks a huge photo before
+ // any pixel is touched; the max size keeps the crop below at full quality for covers.
+ guard let src = CGImageSourceCreateWithURL(url as CFURL, nil),
+ let image = CGImageSourceCreateThumbnailAtIndex(src, 0, [
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
+ kCGImageSourceCreateThumbnailWithTransform: true,
+ kCGImageSourceThumbnailMaxPixelSize: 4096] as CFDictionary) else {
+ throw HighballError.invalid("\(url.lastPathComponent) is not an image Highball can read. Choose a PNG, JPEG or HEIC file.")
+ }
+ return try normalized(image)
+ }
+
+ static func normalized(_ image: CGImage) throws -> Data {
+ let w = image.width, h = image.height
+ var cropW = w, cropH = h
+ if Double(w) / Double(h) > aspect { cropW = max(1, Int((Double(h) * aspect).rounded())) }
+ else { cropH = max(1, Int((Double(w) / aspect).rounded())) }
+ let rect = CGRect(x: (w - cropW) / 2, y: (h - cropH) / 2, width: cropW, height: cropH)
+ guard let cropped = image.cropping(to: rect) else { throw HighballError.invalid("could not crop the cover") }
+ let scale = min(1, Double(maxHeight) / Double(cropped.height))
+ let outW = max(1, Int((Double(cropped.width) * scale).rounded()))
+ let outH = max(1, Int((Double(cropped.height) * scale).rounded()))
+ guard let space = CGColorSpace(name: CGColorSpace.sRGB),
+ let ctx = CGContext(data: nil, width: outW, height: outH, bitsPerComponent: 8, bytesPerRow: 0,
+ space: space, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
+ throw HighballError.invalid("could not prepare the cover")
+ }
+ ctx.interpolationQuality = .high
+ ctx.draw(cropped, in: CGRect(x: 0, y: 0, width: outW, height: outH))
+ let data = NSMutableData()
+ guard let out = ctx.makeImage(),
+ let dest = CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil) else {
+ throw HighballError.invalid("could not encode the cover")
+ }
+ CGImageDestinationAddImage(dest, out, nil)
+ guard CGImageDestinationFinalize(dest) else { throw HighballError.invalid("could not encode the cover") }
+ return data as Data
}
public func clearCover(for id: String) {
diff --git a/Tests/HighballKitTests/LibraryTests.swift b/Tests/HighballKitTests/LibraryTests.swift
index 934f6bd..4546b04 100644
--- a/Tests/HighballKitTests/LibraryTests.swift
+++ b/Tests/HighballKitTests/LibraryTests.swift
@@ -1,4 +1,6 @@
import XCTest
+import CoreGraphics
+import ImageIO
@testable import HighballKit
/// The unified library's data layer (One Library Phase 2): aggregation, dedup, per-bottle
@@ -82,22 +84,55 @@ final class LibraryTests: XCTestCase {
XCTAssertEqual(store.load(), [:])
}
+ /// A real image file of the given size, for the cover tests.
+ private func makeImage(width: Int, height: Int, at url: URL, type: String = "public.png") throws {
+ let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
+ space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
+ ctx.setFillColor(CGColor(red: 0.2, green: 0.5, blue: 0.8, alpha: 1)); ctx.fill(CGRect(x: 0, y: 0, width: width, height: height))
+ let image = ctx.makeImage()!
+ let dest = CGImageDestinationCreateWithURL(url as CFURL, type as CFString, 1, nil)!
+ CGImageDestinationAddImage(dest, image, nil)
+ XCTAssertTrue(CGImageDestinationFinalize(dest))
+ }
+
+ private func size(of url: URL) -> (Int, Int)? {
+ guard let src = CGImageSourceCreateWithURL(url as CFURL, nil),
+ let props = CGImageSourceCopyPropertiesAtIndex(src, 0, nil) as? [CFString: Any],
+ let w = props[kCGImagePropertyPixelWidth] as? Int, let h = props[kCGImagePropertyPixelHeight] as? Int else { return nil }
+ return (w, h)
+ }
+
+ /// Covers are stored cropped to the tile's 2:3 and capped, as PNG, whatever came in (#64: a
+ /// macOS 27 beta drew nothing for a tile image of any other aspect, and the crop belongs
+ /// to the store, not to a layout). An unreadable file is refused, never stored.
func testCoverStoreRoundTrip() throws {
let tmp = FileManager.default.temporaryDirectory.appending(path: "hb-cover-\(UUID().uuidString)")
defer { try? FileManager.default.removeItem(at: tmp) }
+ try FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true)
let store = CoverStore(paths: HighballPaths(home: tmp))
XCTAssertNil(store.coverURL(for: "steam:620"))
- let src = tmp.appending(path: "src.png")
- try FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true)
- try Data([0x89, 0x50, 0x4E, 0x47]).write(to: src)
- try store.setCover(for: "steam:620", from: src)
- let stored = store.coverURL(for: "steam:620")
- XCTAssertEqual(stored?.lastPathComponent, "steam_620.png", "id colon sanitized, extension kept")
- // Replacing with a different extension removes the old file.
- let jpg = tmp.appending(path: "src2.jpg")
- try Data([0xFF, 0xD8]).write(to: jpg)
- try store.setCover(for: "steam:620", from: jpg)
- XCTAssertEqual(store.coverURL(for: "steam:620")?.pathExtension, "jpg")
+
+ let wide = tmp.appending(path: "wide.png"); try makeImage(width: 300, height: 100, at: wide)
+ try store.setCover(for: "steam:620", from: wide)
+ let stored = try XCTUnwrap(store.coverURL(for: "steam:620"))
+ XCTAssertEqual(stored.lastPathComponent, "steam_620.png", "id colon sanitized, always PNG")
+ let (w, h) = try XCTUnwrap(size(of: stored))
+ XCTAssertEqual(h, 100, "never upscaled")
+ XCTAssertEqual(Double(w) / Double(h), 2.0 / 3.0, accuracy: 0.02, "centre-cropped to 2:3")
+
+ let huge = tmp.appending(path: "huge.jpg"); try makeImage(width: 3000, height: 4500, at: huge, type: "public.jpeg")
+ try store.setCover(for: "steam:620", from: huge)
+ XCTAssertEqual(store.coverURL(for: "steam:620")?.pathExtension, "png", "a JPEG source is stored as PNG and replaces the old file")
+ XCTAssertEqual(try XCTUnwrap(size(of: store.coverURL(for: "steam:620")!)).1, CoverStore.maxHeight, "capped in height")
+
+ let exact = tmp.appending(path: "exact.png"); try makeImage(width: 100, height: 150, at: exact)
+ try store.setCover(for: "steam:620", from: exact)
+ XCTAssertEqual(try XCTUnwrap(size(of: store.coverURL(for: "steam:620")!)).0, 100, "an exact 2:3 image keeps its size")
+
+ let junk = tmp.appending(path: "junk.png"); try Data([0x89, 0x50, 0x4E, 0x47]).write(to: junk)
+ XCTAssertThrowsError(try store.setCover(for: "steam:620", from: junk), "four bytes are not a cover")
+ XCTAssertNotNil(store.coverURL(for: "steam:620"), "a refused file leaves the previous cover in place")
+
store.clearCover(for: "steam:620")
XCTAssertNil(store.coverURL(for: "steam:620"))
}