Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ if let bundle = result.appIconBundle {
- JPG sources stored as preserved raw renditions (JPEG bytes passed through; original compression preserved)
- `.colorset` (sRGB and display-P3, hex or float components, dark/light appearances)
- `.appiconset` (per-idiom and per-size, with the loose-PNG fallback that SpringBoard expects alongside `Assets.car`). PNG sources only; SVG/JPG are rejected because SpringBoard's icon-render pipeline requires PNG.
- Single-size icons (Xcode 14+: one 1024x1024 `universal` / `platform: ios` entry): the iPhone, iPad and Settings/Spotlight/notification sizes are generated from the master by area-averaged downscaling, and the master is kept as the store icon. The master must be exactly 1024x1024. Dark and tinted (iOS 18) entries are skipped: the default icon is used for every appearance.

## What it deliberately doesn't support

Expand Down
120 changes: 99 additions & 21 deletions Sources/AssetKit/AppIcon/AppIconPlist.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ struct IconFile: Sendable, Hashable {
var idiom: Idiom
var pointSize: Double
var scale: Int
var sourceURL: URL
/// Name of the file the pixels came from, or the name actool would give a generated one.
var sourceName: String
var data: Data
var outputName: String
}

Expand All @@ -20,27 +22,18 @@ enum AppIconPlistEmitter {
var ipadFiles: [String] = []
var allFiles: [IconFile] = []

for image in appIcon.contents.images {
guard let filename = image.filename, !filename.isEmpty else {
throw XCAssetCompilerError.appIconSizeMissing(asset: appIcon.name, size: image.size)
}
let src = appIcon.directory.appendingPathComponent(filename)
guard FileManager.default.fileExists(atPath: src.path) else {
throw XCAssetCompilerError.missingReferencedFile(asset: appIcon.name, filename: filename)
}
guard let (w, _) = image.pointSize, let scale = image.scale?.factor else {
throw XCAssetCompilerError.appIconSizeMissing(asset: appIcon.name, size: image.size)
}
let bundleName = "\(appIcon.name)\(formatSize(w))x\(formatSize(w))"
let entry = IconFile(
idiom: image.idiom,
pointSize: w,
scale: scale,
sourceURL: src,
let entries = try iconEntries(for: appIcon)
for entry in entries {
let bundleName = "\(appIcon.name)\(formatSize(entry.pointSize))x\(formatSize(entry.pointSize))"
allFiles.append(IconFile(
idiom: entry.idiom,
pointSize: entry.pointSize,
scale: entry.scale,
sourceName: entry.sourceName,
data: entry.data,
outputName: bundleName
)
allFiles.append(entry)
switch image.idiom {
))
switch entry.idiom {
case .iphone:
if !iphoneFiles.contains(bundleName) { iphoneFiles.append(bundleName) }
case .ipad:
Expand Down Expand Up @@ -87,6 +80,91 @@ enum AppIconPlistEmitter {
)
}

private struct Entry {
var idiom: Idiom
var pointSize: Double
var scale: Int
var sourceName: String
var data: Data
}

/// The icons to emit: one per `Contents.json` entry, or, for the single-size
/// format, the sizes generated from the 1024x1024 master.
private static func iconEntries(for appIcon: LoadedAppIcon) throws -> [Entry] {
var entries: [Entry] = []
for image in appIcon.contents.images {
if let platform = image.platform, platform != "ios" {
throw XCAssetCompilerError.unsupportedAppIconPlatform(asset: appIcon.name, platform: platform)
}
// Dark and tinted variants (iOS 18) are not compiled yet; the default icon is used for every appearance.
if !(image.appearances ?? []).isEmpty { continue }

guard let filename = image.filename, !filename.isEmpty else {
throw XCAssetCompilerError.appIconSizeMissing(asset: appIcon.name, size: image.size)
}
let src = appIcon.directory.appendingPathComponent(filename)
guard FileManager.default.fileExists(atPath: src.path) else {
throw XCAssetCompilerError.missingReferencedFile(asset: appIcon.name, filename: filename)
}
let data = try Data(contentsOf: src)

if image.isSingleSizeMaster {
entries.append(contentsOf: try expandMaster(data, filename: filename, appIcon: appIcon))
continue
}
guard let (w, _) = image.pointSize, let scale = image.scale?.factor else {
throw XCAssetCompilerError.appIconSizeMissing(asset: appIcon.name, size: image.size)
}
entries.append(Entry(idiom: image.idiom, pointSize: w, scale: scale, sourceName: filename, data: data))
}
return entries
}

/// Point sizes and scales actool generates from a single-size master for iOS.
private static let generatedSizes: [(idiom: Idiom, points: Double, scale: Int)] = [
(.iphone, 20, 2), (.iphone, 20, 3),
(.iphone, 29, 2), (.iphone, 29, 3),
(.iphone, 40, 2), (.iphone, 40, 3),
(.iphone, 60, 2), (.iphone, 60, 3),
(.ipad, 20, 1), (.ipad, 20, 2),
(.ipad, 29, 1), (.ipad, 29, 2),
(.ipad, 40, 1), (.ipad, 40, 2),
(.ipad, 76, 1), (.ipad, 76, 2),
(.ipad, 83.5, 2),
]

private static func expandMaster(_ data: Data, filename: String, appIcon: LoadedAppIcon) throws -> [Entry] {
let master = try PNGResizer.decode(data)
guard master.width == 1024, master.height == 1024 else {
throw XCAssetCompilerError.appIconSourceSizeMismatch(
asset: appIcon.name,
filename: filename,
expected: "1024x1024",
actual: "\(master.width)x\(master.height)"
)
}
var resized: [Int: Data] = [:]
var out: [Entry] = []
for size in generatedSizes {
let pixels = Int((size.points * Double(size.scale)).rounded())
if resized[pixels] == nil {
resized[pixels] = try PNGResizer.resize(master, width: pixels, height: pixels)
}
let suffix = size.scale == 1 ? "" : "@\(size.scale)x"
let name = "\(formatSize(size.points))x\(formatSize(size.points))"
out.append(Entry(
idiom: size.idiom,
pointSize: size.points,
scale: size.scale,
sourceName: "\(appIcon.name)-\(name)\(suffix).png",
data: resized[pixels]!
))
}
// The store icon is the master itself.
out.append(Entry(idiom: .marketing, pointSize: 1024, scale: 1, sourceName: filename, data: data))
return out
}

private static func formatSize(_ n: Double) -> String {
let rounded = n.rounded()
if abs(n - rounded) < 0.001 {
Expand Down
121 changes: 121 additions & 0 deletions Sources/AssetKit/AppIcon/PNGResizer.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import Foundation
import PNG

/// Area-averaging PNG downscaler, used to expand a single-size app icon
/// master into the sizes the home screen, Spotlight and Settings need.
///
/// Averaging is done on premultiplied alpha so transparent pixels don't bleed
/// their (meaningless) colour into the edges.
enum PNGResizer {
struct Decoded {
var width: Int
var height: Int
/// Premultiplied RGBA, 0...255 as Float.
var pixels: [Float]
}

private struct MemoryStream: PNG.BytestreamSource {
var bytes: [UInt8]
var offset = 0
mutating func read(count: Int) -> [UInt8]? {
guard offset + count <= bytes.count else { return nil }
defer { offset += count }
return Array(bytes[offset..<offset + count])
}
}

private struct MemoryDestination: PNG.BytestreamDestination {
var bytes: [UInt8] = []
mutating func write(_ data: [UInt8]) -> Void? {
bytes.append(contentsOf: data)
return ()
}
}

static func decode(_ data: Data) throws -> Decoded {
var stream = MemoryStream(bytes: [UInt8](data))
let image = try PNG.Image.decompress(stream: &stream)
let rgba: [PNG.RGBA<UInt8>] = image.unpack(as: PNG.RGBA<UInt8>.self)
var pixels = [Float](repeating: 0, count: rgba.count * 4)
for (i, px) in rgba.enumerated() {
let a = Float(px.a) / 255
pixels[i * 4 + 0] = Float(px.r) * a
pixels[i * 4 + 1] = Float(px.g) * a
pixels[i * 4 + 2] = Float(px.b) * a
pixels[i * 4 + 3] = Float(px.a)
}
return Decoded(width: image.size.x, height: image.size.y, pixels: pixels)
}

/// Returns PNG bytes of `source` scaled to `width` x `height`.
static func resize(_ source: Decoded, width: Int, height: Int) throws -> Data {
// Horizontal pass: `source.height` rows, each shrunk to `width` pixels.
let horizontal = resample(
source.pixels, outer: source.height, srcCount: source.width, dstCount: width,
srcStep: 4, srcOuterStep: source.width * 4, dstStep: 4, dstOuterStep: width * 4
)
// Vertical pass: `width` columns, each shrunk to `height` pixels.
let scaled = resample(
horizontal, outer: width, srcCount: source.height, dstCount: height,
srcStep: width * 4, srcOuterStep: 4, dstStep: width * 4, dstOuterStep: 4
)

var rgba = [PNG.RGBA<UInt8>](repeating: PNG.RGBA<UInt8>(0, 0, 0, 0), count: width * height)
for i in 0..<(width * height) {
let a = scaled[i * 4 + 3]
guard a > 0 else { continue }
let k = 255 / a
rgba[i] = PNG.RGBA<UInt8>(
clamp(scaled[i * 4 + 0] * k), clamp(scaled[i * 4 + 1] * k), clamp(scaled[i * 4 + 2] * k), clamp(a)
)
}
let image = PNG.Image(
packing: rgba,
size: (x: width, y: height),
layout: PNG.Layout(format: .rgba8(palette: [], fill: nil))
)
var out = MemoryDestination()
try image.compress(stream: &out)
return Data(out.bytes)
}

private static func clamp(_ v: Float) -> UInt8 {
UInt8(max(0, min(255, v.rounded())))
}

/// One separable pass of box (area) resampling along an axis. Steps are in `Float` units.
private static func resample(
_ src: [Float], outer: Int, srcCount: Int, dstCount: Int,
srcStep: Int, srcOuterStep: Int, dstStep: Int, dstOuterStep: Int
) -> [Float] {
var dst = [Float](repeating: 0, count: outer * dstCount * 4)
let ratio = Double(srcCount) / Double(dstCount)
src.withUnsafeBufferPointer { src in
dst.withUnsafeMutableBufferPointer { dst in
for d in 0..<dstCount {
let start = Double(d) * ratio
let end = start + ratio
let first = Int(start)
let last = min(srcCount - 1, Int(end.nextDown))
for line in 0..<outer {
var r = 0.0, g = 0.0, b = 0.0, a = 0.0
for s in first...last {
let weight = min(end, Double(s + 1)) - max(start, Double(s))
let base = line * srcOuterStep + s * srcStep
r += Double(src[base]) * weight
g += Double(src[base + 1]) * weight
b += Double(src[base + 2]) * weight
a += Double(src[base + 3]) * weight
}
let out = line * dstOuterStep + d * dstStep
dst[out] = Float(r / ratio)
dst[out + 1] = Float(g / ratio)
dst[out + 2] = Float(b / ratio)
dst[out + 3] = Float(a / ratio)
}
}
}
}
return dst
}
}
48 changes: 38 additions & 10 deletions Sources/AssetKit/CAR/BitmapKeys.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ enum BitmapKeys {
var kind: Kind
/// Number of distinct (idiom, subtype) tuples this asset is keyed on.
var idiomSubtypeCount: UInt32
/// With `dimension1Key`: the descriptor covers ten key attributes.
var withDimension1 = false
/// With `multisizeIcons`: bitmask of idioms (bit n = idiom n) and of
/// dimension2 values present, as actool writes them.
var masks: (idioms: UInt32, dimension2: UInt32)?

enum Kind {
case appIcon
Expand All @@ -48,8 +53,9 @@ enum BitmapKeys {
var w = ByteWriter()
w.writeLE(UInt32(1))
w.writeLE(UInt32(0))
w.writeLE(UInt32(0x28))
w.writeLE(UInt32(9))
let attributeCount: UInt32 = withDimension1 ? 10 : 9
w.writeLE(attributeCount * 4 + 4)
w.writeLE(attributeCount)
w.writeLE(UInt32(0xFFFFFFFF))
w.writeLE(UInt32(1))
w.writeLE(assetKindMarker)
Expand All @@ -61,31 +67,36 @@ enum BitmapKeys {
// v1 we hardcode the templates per kind and pass through the
// discovered (idiom, subtype) count. Field 7 in particular seems
// to track that count.
w.writeLE(idiomSubtypeCount)
w.writeLE(masks?.idioms ?? idiomSubtypeCount)
switch kind {
case .appIcon:
w.writeLE(UInt16(1)) // (u16, u16) tuple
w.writeLE(UInt16(1))
w.writeLE(UInt32(7))
w.writeLE(masks?.dimension2 ?? UInt32(7))
case .image, .vector:
w.writeLE(UInt16(1))
w.writeLE(UInt16(0))
w.writeLE(UInt32(1))
w.writeLE(masks?.dimension2 ?? UInt32(1))
}
// Dimension1 is always 0: a mask with only bit 0.
if withDimension1 { w.writeLE(UInt32(1)) }
// Three trailing -1 sentinels.
w.writeLE(UInt32(0xFFFFFFFF))
w.writeLE(UInt32(0xFFFFFFFF))
w.writeLE(UInt32(0xFFFFFFFF))
precondition(w.offset == 52, "BITMAPKEYS descriptor must be 52 bytes; got \(w.offset)")
precondition(w.offset == (withDimension1 ? 56 : 52), "BITMAPKEYS descriptor has the wrong size: \(w.offset)")
return w.data
}
}

/// Per-asset BITMAPKEYS entry: `(NameIdentifier, descriptor bytes)`.
static func entries(for assets: [(name: String, descriptor: Descriptor)]) -> [BOMTree.InlineKeyEntry] {
static func entries(
for assets: [(name: String, descriptor: Descriptor)],
options: OutputOptions = .legacy
) -> [BOMTree.InlineKeyEntry] {
return assets.map { asset in
BOMTree.InlineKeyEntry(
key: FacetKeys.nameHash(asset.name) & 0xFFFF,
key: UInt32(FacetKeys.identifier(for: asset.name, options: options)),
value: asset.descriptor.encode()
)
}
Expand All @@ -97,7 +108,11 @@ enum BitmapKeys {
/// `renditions` is the per-asset slice -- only the renditions whose
/// `name` equals this asset's name. Caller is responsible for the
/// grouping; this function does not re-filter.
static func descriptor(forAsset name: String, renditions: [Rendition]) -> Descriptor? {
static func descriptor(
forAsset name: String,
renditions: [Rendition],
options: OutputOptions = .legacy
) -> Descriptor? {
let hasBitmapOrPreservedSource = renditions.contains { rendition in
switch rendition.body {
case .bitmap, .preservedSource: return true
Expand All @@ -118,7 +133,20 @@ enum BitmapKeys {
return (idiom << 16) | subtype
})

return Descriptor(kind: kind, idiomSubtypeCount: UInt32(idiomSubtypes.count))
var descriptor = Descriptor(kind: kind, idiomSubtypeCount: UInt32(idiomSubtypes.count))
descriptor.withDimension1 = options.contains(.dimension1Key)
if options.contains(.multisizeIcons) {
var idioms: UInt32 = 0
var dimension2: UInt32 = 0
for rendition in renditions {
idioms |= 1 << UInt32(rendition.idiom.rawValueByte)
dimension2 |= 1 << UInt32(RenditionKey(rendition: rendition).dimension2)
}
// the size index records are keyed with dimension2 = 0
if kind == .appIcon { dimension2 |= 1 }
descriptor.masks = (idioms, dimension2)
}
return descriptor
}

/// AppIcon takes precedence over Vector takes precedence over Image:
Expand Down
6 changes: 5 additions & 1 deletion Sources/AssetKit/CAR/CARHeader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ enum CARHeaderBlock {
/// `assetutil --info` and Xcode-side tooling display them without
/// surprises.
static let defaultMainVersionString = "@(#)PROGRAM:CoreUI PROJECT:CoreUI-970.1"
static let defaultVersionString = "xcasset-compiler clean-room CAR writer (Assets.car v1)"
static let defaultVersionString = "AssetKit"

/// What Xcode 26.5's actool writes (CoreUI 975).
static let actoolMainVersionString = "@(#)PROGRAM:CoreUI PROJECT:CoreUI-975"
static let actoolVersionString = "Xcode 26.5 (17F42) via AssetCatalogSimulatorAgent"

static func data(
coreuiVersion: UInt32 = 970,
Expand Down
Loading