Skip to content

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

Mac shortcuts carry the game's own icon (ux-plan item 8)

Gauthier Piarretteec4c9ba605b6
diff --git a/Sources/HighballApp/AppState.swift b/Sources/HighballApp/AppState.swift
index 892d606..62c1706 100644
--- a/Sources/HighballApp/AppState.swift
+++ b/Sources/HighballApp/AppState.swift
@@ -988,12 +988,34 @@ final class AppState {
let url = PlayLink.url(for: target, token: PlayLink.token(in: paths))
let cover = coverStore.coverURL(for: item.id) ?? item.artworkTall
do {
- let app = try MacAppStub.write(title: item.title, libraryID: item.id, url: url, cover: cover)
+ let app = try MacAppStub.write(title: item.title, libraryID: item.id, url: url, cover: cover, icon: programIcon(for: item))
appendLog("made \(app.lastPathComponent) in ~/Applications/Highball")
NSWorkspace.shared.activateFileViewerSelecting([app])
} catch { fail(error) }
}
+ /// The game's own icon as a PNG under covers/icons, read from its executable (the largest
+ /// .exe in its folder, or a pin's own), or nil when there is none to read.
+ func programIcon(for item: LibraryItem) -> URL? {
+ guard let bottleName = item.bottleName, let bottle = bottles.first(where: { $0.name == bottleName }) else { return nil }
+ let exe: URL?
+ switch item.source {
+ case .steam:
+ guard let game = gamesByBottle[bottleName]?.first(where: { $0.appid == item.steamAppID }), !game.installdir.isEmpty else { return nil }
+ exe = PEIcon.bestExecutable(in: bottle.driveC.appending(path: "Program Files (x86)/Steam/steamapps/common/\(game.installdir)"))
+ case .epic:
+ exe = item.epicAppName.flatMap { epicInstalls[$0] }.flatMap { PEIcon.bestExecutable(in: URL(fileURLWithPath: $0)) }
+ case .pin:
+ exe = item.pinID.flatMap { id in bottle.settings.pins.first { $0.id == id } }.map { $0.executableURL(driveC: bottle.driveC) }
+ }
+ guard let exe, let png = PEIcon.png(from: exe) else { return nil }
+ let dir = paths.home.appending(path: "covers/icons", directoryHint: .isDirectory)
+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let file = dir.appending(path: MacAppStub.bundleID(for: item.id) + ".png")
+ guard (try? png.write(to: file, options: .atomic)) != nil else { return nil }
+ return file
+ }
+
/// A Mac app for a launcher (Steam, Epic, …) that opens it, installing it first if needed
/// (issue #53). Highball's own icon stands in for a cover.
func makeMacApp(forLauncher id: String, short: String) {
diff --git a/Sources/HighballKit/MacAppStub.swift b/Sources/HighballKit/MacAppStub.swift
index 470ed5b..d43d809 100644
--- a/Sources/HighballKit/MacAppStub.swift
+++ b/Sources/HighballKit/MacAppStub.swift
@@ -51,7 +51,7 @@ public enum MacAppStub {
/// Writes (or rewrites) the bundle and returns its location. `cover` is any image file; it
/// becomes the icon when sips and iconutil can convert it, and the stub still works without.
@discardableResult
- public static func write(title: String, libraryID: String, url: URL, cover: URL?) throws -> URL {
+ public static func write(title: String, libraryID: String, url: URL, cover: URL?, icon: URL? = nil) throws -> URL {
let fm = FileManager.default
let name = appName(for: title)
let app = folder().appending(path: "\(name).app", directoryHint: .isDirectory)
@@ -63,7 +63,9 @@ public enum MacAppStub {
let script = contents.appending(path: "MacOS/launch")
try launchScript(url: url).write(to: script, atomically: true, encoding: .utf8)
try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: script.path)
- if let cover { try? makeIcon(from: cover, to: contents.appending(path: "Resources/icon.icns")) }
+ // The program's own icon when it has one (item 8), else the cover cropped square.
+ if let icon { try? makeIcon(from: icon, to: contents.appending(path: "Resources/icon.icns")) }
+ else if let cover { try? makeIcon(from: cover, to: contents.appending(path: "Resources/icon.icns")) }
// Ad-hoc signature: a stable identity for macOS, no certificate needed for a local file.
_ = try? Shell.run("/usr/bin/codesign", ["--force", "--sign", "-", app.path])
return app
diff --git a/Sources/HighballKit/PEIcon.swift b/Sources/HighballKit/PEIcon.swift
new file mode 100644
index 0000000..a573f8c
--- /dev/null
+++ b/Sources/HighballKit/PEIcon.swift
@@ -0,0 +1,147 @@
+import Foundation
+import CoreGraphics
+import ImageIO
+import UniformTypeIdentifiers
+
+/// The icon a Windows program carries in its own resources, for the Mac shortcuts (ux-plan item
+/// 8: a shortcut used to get the store cover cropped square, which reads as "some picture" in the
+/// Dock next to real app icons). Reads the PE resource tree for RT_GROUP_ICON, takes the largest
+/// entry (256x256 PNG in anything built this decade, a 32-bit DIB in older programs), and hands
+/// back PNG bytes. Anything it does not understand (16-colour icons, packed executables) is nil,
+/// and the caller falls back to the cover.
+public enum PEIcon {
+ /// PNG bytes of the largest icon in `exe`, or nil.
+ public static func png(from exe: URL) -> Data? {
+ guard let data = try? Data(contentsOf: exe, options: .mappedIfSafe) else { return nil }
+ return png(fromPE: data)
+ }
+
+ /// The program most likely to be the game in a folder: the largest .exe up to three levels
+ /// down whose name does not say installer, crash handler or redistributable.
+ public static func bestExecutable(in dir: URL) -> URL? {
+ let fm = FileManager.default
+ let excluded = ["unins", "setup", "redist", "crash", "report", "vc_redist", "vcredist", "dxsetup", "dotnet", "directx", "easyanticheat", "installscript", "launcher_", "helper"]
+ guard let e = fm.enumerator(at: dir, includingPropertiesForKeys: [.fileSizeKey, .isRegularFileKey], options: [.skipsHiddenFiles]) else { return nil }
+ var best: (URL, Int)?
+ for case let url as URL in e {
+ if e.level > 3 { e.skipDescendants(); continue }
+ guard url.pathExtension.lowercased() == "exe" else { continue }
+ let name = url.lastPathComponent.lowercased()
+ if excluded.contains(where: { name.contains($0) }) { continue }
+ let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0
+ if best == nil || size > best!.1 { best = (url, size) }
+ }
+ return best?.0
+ }
+
+ // MARK: PE resources
+
+ static func png(fromPE d: Data) -> Data? {
+ guard d.count > 0x40, d[0] == 0x4D, d[1] == 0x5A else { return nil }
+ let pe = Int(u32(d, 0x3C))
+ guard pe + 24 < d.count, u32(d, pe) == 0x4550 else { return nil }
+ let sections = Int(u16(d, pe + 6)), optSize = Int(u16(d, pe + 20)), opt = pe + 24
+ guard opt + 2 <= d.count else { return nil }
+ let magic = u16(d, opt)
+ let ddOffset = opt + (magic == 0x20B ? 112 : 96) // data directories, PE32+ or PE32
+ guard ddOffset + 8 * 3 <= d.count else { return nil }
+ let rsrcRVA = Int(u32(d, ddOffset + 8 * 2)), rsrcSize = Int(u32(d, ddOffset + 8 * 2 + 4))
+ guard rsrcRVA > 0, rsrcSize > 0 else { return nil }
+ // Section table: rva -> file offset.
+ var secs: [(va: Int, size: Int, raw: Int)] = []
+ let table = opt + optSize
+ for i in 0..<sections {
+ let s = table + 40 * i
+ guard s + 40 <= d.count else { return nil }
+ secs.append((Int(u32(d, s + 12)), Int(u32(d, s + 8)), Int(u32(d, s + 20))))
+ }
+ func off(_ rva: Int) -> Int? {
+ for s in secs where rva >= s.va && rva < s.va + max(s.size, 1) { return rva - s.va + s.raw }
+ return nil
+ }
+ guard let root = off(rsrcRVA) else { return nil }
+ // Resource directory: Type -> Name/ID -> Language -> data entry.
+ func entries(_ dirOff: Int) -> [(id: UInt32, isDir: Bool, next: Int)] {
+ guard dirOff + 16 <= d.count else { return [] }
+ let named = Int(u16(d, dirOff + 12)), ids = Int(u16(d, dirOff + 14))
+ var out: [(UInt32, Bool, Int)] = []
+ for i in 0..<(named + ids) {
+ let e = dirOff + 16 + 8 * i
+ guard e + 8 <= d.count else { break }
+ let id = u32(d, e), val = u32(d, e + 4)
+ out.append((id, val & 0x8000_0000 != 0, Int(val & 0x7FFF_FFFF)))
+ }
+ return out
+ }
+ func firstLeaf(_ dirOff: Int, depth: Int = 0) -> Int? {
+ for e in entries(dirOff) {
+ if e.isDir { if depth < 2, let leaf = firstLeaf(root + e.next, depth: depth + 1) { return leaf } }
+ else { return root + e.next }
+ }
+ return nil
+ }
+ func leafData(_ dataEntry: Int) -> Data? {
+ guard dataEntry + 16 <= d.count else { return nil }
+ let rva = Int(u32(d, dataEntry)), size = Int(u32(d, dataEntry + 4))
+ guard let o = off(rva), o + size <= d.count, size > 0 else { return nil }
+ return d.subdata(in: o..<(o + size))
+ }
+ func typeDir(_ type: UInt32) -> Int? { entries(root).first { $0.id == type && $0.isDir }.map { root + $0.next } }
+ guard let groups = typeDir(14), let icons = typeDir(3) else { return nil }
+ guard let groupLeaf = firstLeaf(groups), let group = leafData(groupLeaf), group.count >= 6 else { return nil }
+ // GRPICONDIR: reserved, type, count, then 14-byte entries: w, h, colours, reserved, planes, bits, bytes, id.
+ let count = Int(u16(group, 4))
+ var bestID: UInt32?, bestScore = -1
+ for i in 0..<count {
+ let e = 6 + 14 * i
+ guard e + 14 <= group.count else { break }
+ let w = group[e] == 0 ? 256 : Int(group[e]), bits = Int(u16(group, e + 6)), id = UInt32(u16(group, e + 12))
+ let score = w * 1000 + bits
+ if score > bestScore { bestScore = score; bestID = id }
+ }
+ guard let wanted = bestID else { return nil }
+ for e in entries(icons) where e.id == wanted && e.isDir {
+ guard let leaf = firstLeaf(root + e.next), let icon = leafData(leaf) else { continue }
+ if icon.count > 8, icon[0] == 0x89, icon[1] == 0x50, icon[2] == 0x4E, icon[3] == 0x47 { return icon }
+ return pngFromDIB(icon)
+ }
+ return nil
+ }
+
+ /// A 32-bit BITMAPINFOHEADER icon (XOR rows bottom-up, BGRA, then the AND mask) as PNG.
+ static func pngFromDIB(_ dib: Data) -> Data? {
+ guard dib.count >= 40 else { return nil }
+ let headerSize = Int(u32(dib, 0)), width = Int(Int32(bitPattern: u32(dib, 4))), height2 = Int(Int32(bitPattern: u32(dib, 8)))
+ let bits = Int(u16(dib, 14)), compression = u32(dib, 16)
+ guard headerSize == 40, bits == 32, compression == 0, width > 0, height2 > 0 else { return nil }
+ let height = height2 / 2, rowBytes = width * 4
+ guard 40 + rowBytes * height <= dib.count else { return nil }
+ var pixels = [UInt8](repeating: 0, count: rowBytes * height)
+ for y in 0..<height {
+ let src = 40 + (height - 1 - y) * rowBytes
+ for x in 0..<width {
+ let s = src + x * 4, t = y * rowBytes + x * 4
+ let b = dib[s], g = dib[s + 1], r = dib[s + 2], a = dib[s + 3]
+ pixels[t] = r; pixels[t + 1] = g; pixels[t + 2] = b; pixels[t + 3] = a
+ }
+ }
+ // Icons without an alpha channel in the XOR data leave every alpha at zero; treat as opaque.
+ if !pixels.enumerated().contains(where: { $0.offset % 4 == 3 && $0.element != 0 }) {
+ for i in stride(from: 3, to: pixels.count, by: 4) { pixels[i] = 255 }
+ }
+ guard let provider = CGDataProvider(data: Data(pixels) as CFData),
+ let image = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: rowBytes,
+ space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue),
+ provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent) else { return nil }
+ let out = NSMutableData()
+ guard let dest = CGImageDestinationCreateWithData(out, UTType.png.identifier as CFString, 1, nil) else { return nil }
+ CGImageDestinationAddImage(dest, image, nil)
+ guard CGImageDestinationFinalize(dest) else { return nil }
+ return out as Data
+ }
+
+ private static func u16(_ d: Data, _ o: Int) -> UInt16 { o + 2 <= d.count ? UInt16(d[o]) | UInt16(d[o + 1]) << 8 : 0 }
+ private static func u32(_ d: Data, _ o: Int) -> UInt32 {
+ o + 4 <= d.count ? UInt32(d[o]) | UInt32(d[o + 1]) << 8 | UInt32(d[o + 2]) << 16 | UInt32(d[o + 3]) << 24 : 0
+ }
+}
diff --git a/Tests/HighballKitTests/PEIconTests.swift b/Tests/HighballKitTests/PEIconTests.swift
new file mode 100644
index 0000000..ce693fc
--- /dev/null
+++ b/Tests/HighballKitTests/PEIconTests.swift
@@ -0,0 +1,53 @@
+import XCTest
+@testable import HighballKit
+
+/// A shortcut's icon comes from the program itself when it has one (ux-plan item 8).
+final class PEIconTests: XCTestCase {
+ func testDIBIconBecomesPNGWithTheRowsTheRightWayUp() throws {
+ // A 2x2 32-bit icon: bottom row first in the file (blue, green), then the top row (red, opaque white).
+ var dib = Data(count: 40)
+ func put32(_ v: UInt32, _ o: Int) { for i in 0..<4 { dib[o + i] = UInt8((v >> (8 * i)) & 0xFF) } }
+ put32(40, 0); put32(2, 4); put32(4, 8) // header size, width 2, height 2*2
+ dib[12] = 1; dib[14] = 32 // planes, bits
+ let bottom: [UInt8] = [255, 0, 0, 255, 0, 255, 0, 255] // BGRA: blue, green
+ let top: [UInt8] = [0, 0, 255, 255, 255, 255, 255, 255] // red, white
+ dib.append(contentsOf: bottom); dib.append(contentsOf: top); dib.append(contentsOf: [0, 0, 0, 0]) // AND mask
+ let png = try XCTUnwrap(PEIcon.pngFromDIB(dib))
+ XCTAssertEqual([UInt8](png.prefix(4)), [0x89, 0x50, 0x4E, 0x47])
+ let image = try XCTUnwrap(CGImageSourceCreateImageAtIndex(XCTUnwrap(CGImageSourceCreateWithData(png as CFData, nil)), 0, nil))
+ XCTAssertEqual(image.width, 2); XCTAssertEqual(image.height, 2)
+ // Top-left must be red: the file stores rows bottom-up and the converter flips them.
+ let ctx = try XCTUnwrap(CGContext(data: nil, width: 2, height: 2, bitsPerComponent: 8, bytesPerRow: 8, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
+ ctx.draw(image, in: CGRect(x: 0, y: 0, width: 2, height: 2))
+ let px = try XCTUnwrap(ctx.data).assumingMemoryBound(to: UInt8.self)
+ XCTAssertEqual([px[0], px[1], px[2]], [255, 0, 0], "top-left is red") // CGContext row 0 is the top
+ }
+
+ func testRejectsWhatItDoesNotUnderstand() {
+ XCTAssertNil(PEIcon.png(fromPE: Data("not a program".utf8)))
+ XCTAssertNil(PEIcon.pngFromDIB(Data(count: 39)))
+ }
+
+ func testBestExecutableIsTheLargestThatIsNotAnInstaller() throws {
+ let dir = FileManager.default.temporaryDirectory.appending(path: "hb-exe-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ try FileManager.default.createDirectory(at: dir.appending(path: "bin"), withIntermediateDirectories: true)
+ try Data(count: 10).write(to: dir.appending(path: "game.exe"))
+ try Data(count: 5000).write(to: dir.appending(path: "unins000.exe"))
+ try Data(count: 3000).write(to: dir.appending(path: "bin/Game-Win64-Shipping.exe"))
+ try Data(count: 9000).write(to: dir.appending(path: "UnityCrashHandler64.exe"))
+ XCTAssertEqual(PEIcon.bestExecutable(in: dir)?.lastPathComponent, "Game-Win64-Shipping.exe")
+ }
+
+ func testARealProgramOnThisMacWhenThereIsOne() throws {
+ let candidates = [
+ "Library/Application Support/Highball/bottles/Gaming/drive_c/highball/ahk/AutoHotkeyU64.exe",
+ "Library/Application Support/Highball/bottles/Gaming/drive_c/Program Files (x86)/Steam/steamapps/common/Five Nights at Freddy's/FiveNightsatFreddys.exe",
+ ].map { FileManager.default.homeDirectoryForCurrentUser.appending(path: $0) }
+ guard let exe = candidates.first(where: { FileManager.default.fileExists(atPath: $0.path) }) else { throw XCTSkip("no Windows program with an icon on this Mac") }
+ let png = try XCTUnwrap(PEIcon.png(from: exe), "\(exe.lastPathComponent) carries an icon")
+ let source = try XCTUnwrap(CGImageSourceCreateWithData(png as CFData, nil))
+ let image = try XCTUnwrap(CGImageSourceCreateImageAtIndex(source, 0, nil))
+ XCTAssertGreaterThanOrEqual(image.width, 32)
+ }
+}