Skip to content
2 changes: 1 addition & 1 deletion Sources/AssetKit/AppIcon/AppIconPlist.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ enum AppIconPlistEmitter {
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 {
guard let (w, _) = image.pointSize, w > 0, let scale = image.scale?.factor else {
throw XCAssetCompilerError.appIconSizeMissing(asset: appIcon.name, size: image.size)
}
let bundleName = "\(appIcon.name)\(formatSize(w))x\(formatSize(w))"
Expand Down
64 changes: 43 additions & 21 deletions Sources/AssetKit/CAR/BitmapKeys.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,19 @@ import Foundation
/// UIImage(named:) resolution for `.imageset` (and analogous) assets.
///
/// Structure (verified against actool's reference Assets.car, Xcode 26 /
/// CoreUI 970):
/// CoreUI 970, and a Xcode 27.0 per-colorspace oracle):
/// - The tree is `isPathInternal = true` and uses a `blockSize` of 1024.
/// - Each leaf entry's "key" slot is an INLINE u32 NameIdentifier (not a
/// block pointer like other trees).
/// - Each value is a 52-byte descriptor block.
/// - Each value is a 52-byte descriptor block (48 bytes for colorsets,
/// which carry one fewer trailing sentinel).
///
/// Without this tree present, `UIImage(named:)` returns nil on device even
/// though `assetutil --info` parses the file cleanly and FACETKEYS/RENDITIONS
/// resolve correctly. SpringBoard's appicon-render path does NOT depend on
/// BITMAPKEYS (the home icon still renders via the loose-PNG fallback).
enum BitmapKeys {
/// The 52-byte descriptor. Layout was derived by diffing actool's outputs
/// The descriptor. Layout was derived by diffing actool's outputs
/// for `.appiconset` vs `.imageset` (bitmap) vs `.imageset` (vector)
/// renditions. The first 7 u32s are header-like; only slot 6 varies
/// across asset kinds. The remaining 6 vary by asset kind.
Expand All @@ -30,33 +31,40 @@ enum BitmapKeys {
case image
/// SVG `.imageset` assets — vector source.
case vector
/// `.colorset` assets. actool 27.0 writes one BITMAPKEYS row per
/// colorset too (marker 0x02, variable section shaped like the
/// image one).
case color
}

/// Slot 6 of the header (the only header u32 that varies by kind).
/// `0x04` for bitmap-source assets (PNG, JPG); `0x0e` for vector
/// sources (SVG). AppIcon keeps `0x0e` -- we have no reference dump
/// for appicon-only catalogs to confirm which value it expects, and
/// the current value is verified end-to-end on device.
/// sources (SVG) and appicons; `0x02` for colors (actool 27.0
/// per-space oracle).
private var assetKindMarker: UInt32 {
switch kind {
case .image: return 0x04
case .vector, .appIcon: return 0x0e
case .color: return 0x02
}
}

func encode() -> Data {
var w = ByteWriter()
w.writeLE(UInt32(1))
w.writeLE(UInt32(0))
w.writeLE(UInt32(0x28))
w.writeLE(UInt32(9))
// Slots 3/4 are length fields: 0x28/9 for 52-byte descriptors
// (icon/image/vector), 0x24/8 for 48-byte color descriptors.
w.writeLE(UInt32(kind == .color ? 0x24 : 0x28))
w.writeLE(UInt32(kind == .color ? 8 : 9))
w.writeLE(UInt32(0xFFFFFFFF))
w.writeLE(UInt32(1))
w.writeLE(assetKindMarker)
// Variable section. Values come from the actool reference.
// AppIcon : [u32=2, u16=1, u16=1, u32=7]
// Image : [u32=1, u16=1, u16=0, u32=1]
// Vector : [u32=1, u16=1, u16=0, u32=1] (same shape as Image)
// Color : [u32=1, u16=1, u16=0, u32=1] (same shape as Image)
// The exact semantics aren't fully reverse-engineered yet, so for
// v1 we hardcode the templates per kind and pass through the
// discovered (idiom, subtype) count. Field 7 in particular seems
Expand All @@ -71,12 +79,20 @@ enum BitmapKeys {
w.writeLE(UInt16(1))
w.writeLE(UInt16(0))
w.writeLE(UInt32(1))
case .color:
// Colorsets end the variable section after the (u16, u16)
// pair: no trailing u32 (48-byte descriptor, actool 27.0
// per-space oracle).
w.writeLE(UInt16(1))
w.writeLE(UInt16(0))
}
// Three trailing -1 sentinels.
// Three trailing -1 sentinels for every kind.
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 == (kind == .color ? 48 : 52),
"BITMAPKEYS descriptor must be \(kind == .color ? 48 : 52) bytes; got \(w.offset)")
return w.data
}
}
Expand All @@ -92,29 +108,30 @@ enum BitmapKeys {
}

/// Derive the BITMAPKEYS descriptor for one asset from its rendition list.
/// Returns `nil` for color-only assets, which produce no BITMAPKEYS row.
/// Returns `nil` only for assets with no bitmap, preserved-source, or
/// color renditions (actool 27.0 writes a BITMAPKEYS row for colorsets
/// too, marker 0x02).
///
/// `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? {
let hasBitmapOrPreservedSource = renditions.contains { rendition in
let hasDescribableRendition = renditions.contains { rendition in
switch rendition.body {
case .bitmap, .preservedSource: return true
case .color: return false
case .bitmap, .preservedSource, .color: return true
// MultiSized containers only ever accompany bitmap icon
// renditions; they alone never justify a BITMAPKEYS row.
case .multiSized: return false
}
}
guard hasBitmapOrPreservedSource else { return nil }
guard hasDescribableRendition else { return nil }

let kind = inferKind(from: renditions)

// (idiom << 16) | subtype packs each (idiom, subtype) pair into a
// single UInt32 for Set uniqueness. Subtype is always 0 today; the
// packing exists to match how CoreUI would distinguish (e.g.) iPhone
// 60pt vs iPhone 76pt if subtype were ever non-zero.
// (idiom << 16) | subtype packs each tuple into a single UInt32 for Set uniqueness.
let idiomSubtypes = Set(renditions.map { rendition -> UInt32 in
let idiom = UInt32(rendition.idiom.rawValueByte)
let subtype: UInt32 = 0
let subtype = UInt32(rendition.subtype ?? 0)
return (idiom << 16) | subtype
})

Expand All @@ -125,7 +142,7 @@ enum BitmapKeys {
/// an .appiconset is a distinct CoreUI category, and a vector source
/// outranks plain bitmap because the rasterised PNG fallbacks coexist
/// with the preserved SVG body. Mixed PNG/JPEG imagesets fall through
/// to `.image`.
/// to `.image`. Color-only assets (`.colorset`) classify as `.color`.
///
/// The AppIcon arm relies on `ImageRenderer.appIconRenditions` only
/// producing `.bitmap(.appIcon)` renditions (PNG-only at that entry
Expand All @@ -142,6 +159,11 @@ enum BitmapKeys {
return .vector
}
}
for rendition in renditions {
if case .color = rendition.body {
return .color
}
}
return .image
}
}
4 changes: 4 additions & 0 deletions Sources/AssetKit/CAR/CARLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ struct CARLayout {
case .image: return .image
}
case .color: return .color
// MultiSized containers share the appicon facet; they are part of
// the same asset and only ever accompany .appIcon bitmap renditions,
// which classify the facet first anyway.
case .multiSized: return .appIcon
// Preserved-source renditions live in the `.image` category at every
// layer above the CSI body: FACETKEYS, BITMAPKEYS, and the rendition
// key all reuse the same element/part as a generic PNG imageset.
Expand Down
19 changes: 17 additions & 2 deletions Sources/AssetKit/CAR/CARWriter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,25 @@ struct CARWriter: Sendable {
// KEYFORMAT, EXTENDED_METADATA, BITMAPKEYS. Reordering or omitting
// a `setVariable` here breaks iOS lookups silently.

// KEYFORMAT is catalog-wide and actool only lists the attributes in
// use: the base eight, plus dimension2 when some rendition carries
// an Icon Index (app icons). Rendition keys pack exactly these
// tokens in this order (actool 27.0: icon cars 18-byte keys, color
// cars 16-byte keys).
let usesIconIndex = renditions.contains { rendition in
if case .bitmap(let body) = rendition.body, body.kind == .appIcon {
return true
}
return false
}
let keyFormat: [AttributeID] = usesIconIndex ? v1KeyFormat : baseKeyFormat

let headerBlockID = bom.addBlock(CARHeaderBlock.data(renditionCount: UInt32(renditions.count)))
bom.setVariable("CARHEADER", blockID: headerBlockID)

let renditionEntries: [BOMTree.Entry] = renditions.map { rendition in
BOMTree.Entry(
key: RenditionKey(rendition: rendition).encode(),
key: RenditionKey(rendition: rendition).encode(format: keyFormat),
value: csiData(for: rendition)
)
}
Expand All @@ -48,7 +61,7 @@ struct CARWriter: Sendable {
)
bom.setVariable("APPEARANCEKEYS", blockID: appearanceTreeID)

let kfmtBlockID = bom.addBlock(KeyFormatBlock.data())
let kfmtBlockID = bom.addBlock(KeyFormatBlock.data(attributes: keyFormat))
bom.setVariable("KEYFORMAT", blockID: kfmtBlockID)

let extendedMetadataBlockID = bom.addBlock(ExtendedMetadata.data(deploymentTarget: deploymentTarget))
Expand Down Expand Up @@ -79,6 +92,8 @@ struct CARWriter: Sendable {
case .bitmap(let body):
let scaleFactor = UInt32(rendition.scale?.factor ?? 1) * 100
return CSIWriter.bitmap(name: rendition.name, body: body, scaleFactor: scaleFactor)
case .multiSized(let body):
return CSIWriter.multiSized(name: rendition.name, body: body)
case .color(let body):
return CSIWriter.color(name: rendition.name, body: body)
case .preservedSource(let body):
Expand Down
4 changes: 4 additions & 0 deletions Sources/AssetKit/CAR/CSIHeader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ enum CSIHeader {
/// pixelFormat selects the decoder, not the layout).
case bitmapIcon = 12
case namedColor = 1009
/// MultiSized icon container. The body is a 'MSIS' record (version,
/// count, then per-size width/height/index); actool emits one such
/// rendition per (idiom, subtype) group of app-icon renditions.
case multiSized = 1010
/// Used by preserved-source SVG renditions in CoreUI 970. JPG keeps
/// `bitmapIcon` because JPEG sits inside CoreUI's bitmap-asset
/// category; SVG promotes to its own layout because vector
Expand Down
74 changes: 64 additions & 10 deletions Sources/AssetKit/CAR/CSIWriter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -112,32 +112,86 @@ enum CSIWriter {
return header + tvl + envelope
}

/// MultiSized icon container (layout 1010). Header dimensions, scale,
/// pixelFormat and colorSpace are all zero like named colors; TVL is the
/// same all-zero 1004 + 1006:1 pair. The name is the ASSET name (not a
/// source filename), and the body lists point sizes; 83.5 pt truncates
/// to 83, as in the reference output.
static func multiSized(name: String, body: MultiSizedBody) -> Data {
let tvl = CSITVL.encode([.colorSlice, .bitmapFlag])
var w = ByteWriter()
w.writeLE(UInt32(0x4D53_4953)) // 'MSIS' (file bytes SISM)
w.writeLE(UInt32(1)) // version
w.writeLE(UInt32(body.sizes.count))
for size in body.sizes {
w.writeLE(size.pointWidth)
w.writeLE(size.pointHeight)
w.writeLE(size.iconIndex)
}
let payload = w.data
let header = CSIHeader.encode(
renditionFlags: 0,
width: 0,
height: 0,
scaleFactor: 0,
pixelFormat: 0,
colorSpace: 0,
layout: .multiSized,
name: name,
tvlLength: UInt32(tvl.count),
bitmapCount: 1,
renditionLength: UInt32(payload.count)
)
return header + tvl + payload
}

/// Named color, in the layout actool 27.0 writes: header scale, colorSpace
/// and pixelFormat all zero; TVL (1004: zeros, 1006: 1); one body.
static func color(name: String, body: ColorBody) -> Data {
let tvl = CSITVL.encode([.colorSlice, .bitmapFlag])
let payload = colorBody(body: body)
let header = CSIHeader.encode(
renditionFlags: 0,
width: 0,
height: 0,
scaleFactor: 100,
scaleFactor: 0,
pixelFormat: 0,
colorSpace: UInt32(body.colorSpaceID),
colorSpace: 0,
layout: .namedColor,
name: name,
tvlLength: 0,
bitmapCount: 0,
tvlLength: UInt32(tvl.count),
bitmapCount: 1,
renditionLength: UInt32(payload.count)
)
return header + payload
return header + tvl + payload
}

/// 'COLR' as an LE multi-char constant (file bytes R,L,O,C), version 1,
/// colorSpaceID with flag bits, component count, then Float64 components.
/// A system color is a gray fallback (colorspace 0x102, [white, alpha])
/// followed by a second COLR record holding the name (length + UTF-8).
private static func colorBody(body: ColorBody) -> Data {
var w = ByteWriter()
w.writeFourCC("COLR")
w.writeLE(UInt32(0)) // version
w.writeLE(UInt32(0x434F_4C52))
w.writeLE(UInt32(1)) // version
if let name = body.systemName {
w.writeLE(UInt32(0x102)) // gray gamma 2.2, as actool writes it
w.writeLE(UInt32(2))
for component in body.components {
w.writeLE(component.bitPattern)
}
w.writeLE(UInt32(0x434F_4C52))
w.writeLE(UInt32(1))
w.writeLE(UInt32(name.utf8.count))
w.write(Array(name.utf8))
return w.data
}
w.writeLE(UInt32(body.colorSpaceID)) // colorSpaceID with flag bits
w.writeLE(UInt32(4)) // numberOfComponents
for component in [body.red, body.green, body.blue, body.alpha] {
w.writeLE(component.bitPattern)
w.writeLE(UInt32(body.components.count))
for component in body.components {
// actool quantizes each component to Float32 before storing it
// in the Float64 slot (Xcode 27.0 writes 1.1 as 0x3FF19999A0000000).
w.writeLE(Double(Float(component)).bitPattern)
}
return w.data
}
Expand Down
2 changes: 2 additions & 0 deletions Sources/AssetKit/CAR/FacetKeys.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ enum FacetKeys {
]
case .color:
return [
(UInt16(AttributeID.element.rawValue), RenditionKey.Element.bitmap.rawValue),
(UInt16(AttributeID.part.rawValue), RenditionKey.Part.color.rawValue),
(UInt16(AttributeID.identifier.rawValue), identifier),
]
}
Expand Down
20 changes: 19 additions & 1 deletion Sources/AssetKit/CAR/KeyFormat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,28 @@ enum AttributeID: UInt32 {
case identifier = 17
}

/// Attribute order CoreUI 970 emits in `KEYFORMAT` (and which the rendition key
/// Attribute order CoreUI emits in `KEYFORMAT` (and which the rendition key
/// tuple positions mirror exactly). Order is significant: CoreUI binary-searches
/// rendition keys by raw byte comparison after packing them into this slot
/// layout.
///
/// KEYFORMAT is per-catalog: actool emits the base eight attributes and adds
/// `dimension2` only when some rendition uses it (app icons carry an Icon
/// Index there). Verified against actool 27.0: an icon-only catalog gets 9
/// attributes, a color-only catalog gets 8, and rendition keys pack exactly
/// that many tokens in this order.
let baseKeyFormat: [AttributeID] = [
.appearance,
.localization,
.scale,
.idiom,
.subtype,
.identifier,
.element,
.part,
]

/// Key format for catalogs that use the Icon Index slot (app icons).
let v1KeyFormat: [AttributeID] = [
.appearance,
.localization,
Expand Down
Loading