Skip to content
Open
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
23 changes: 11 additions & 12 deletions Sources/AssetKit/CAR/AppearanceKeys.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,24 @@ import Foundation
/// the catalog's used-appearances set to `entries(used:)`.
enum AppearanceKeys {
static let any: UInt16 = 0
static let dark: UInt16 = 1

static let names: [UInt16: String] = [
0: "UIAppearanceAny",
1: "UIAppearanceDark",
2: "UIAppearanceHighContrastAny",
3: "UIAppearanceHighContrastDark",
4: "UIAppearanceLight",
5: "UIAppearanceHighContrastLight",
]

static func entries(used: Set<UInt16>) -> [BOMTree.Entry] {
var rows: [BOMTree.Entry] = []
// `UIAppearanceAny` (id=0) is always present in the reference, even
// when every rendition has an explicit appearance, because CoreUI
// packs `appearance=0` as the default-variant marker in rendition
// keys regardless of whether a dark variant exists.
rows.append(BOMTree.Entry(
key: Data("UIAppearanceAny".utf8),
value: Self.encodeID(any)
))
if used.contains(dark) {
rows.append(BOMTree.Entry(
key: Data("UIAppearanceDark".utf8),
value: Self.encodeID(dark)
))
used.union([any]).sorted().compactMap { id in
names[id].map { BOMTree.Entry(key: Data($0.utf8), value: encodeID(id)) }
}
return rows
}

private static func encodeID(_ id: UInt16) -> Data {
Expand Down
125 changes: 21 additions & 104 deletions Sources/AssetKit/CAR/BitmapKeys.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,85 +8,39 @@ import Foundation
/// - 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 descriptor `(1, 0, byteCount, attributeCount)` followed
/// by one u32 per KEYFORMAT attribute. Appearance, identifier, element and
/// part are 0xFFFFFFFF, and every other attribute is a mask with bit
/// `1 << value` set for each value the asset's renditions use.
///
/// 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
/// 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.
struct Descriptor {
var kind: Kind
/// Number of distinct (idiom, subtype) tuples this asset is keyed on.
var idiomSubtypeCount: UInt32

enum Kind {
case appIcon
/// PNG and JPEG `.imageset` assets — bitmap source.
case image
/// SVG `.imageset` assets — vector source.
case vector
}

/// 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.
private var assetKindMarker: UInt32 {
switch kind {
case .image: return 0x04
case .vector, .appIcon: return 0x0e
}
}

func encode() -> Data {
var w = ByteWriter()
w.writeLE(UInt32(1))
w.writeLE(UInt32(0))
w.writeLE(UInt32(0x28))
w.writeLE(UInt32(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)
// 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
// to track that count.
w.writeLE(idiomSubtypeCount)
switch kind {
case .appIcon:
w.writeLE(UInt16(1)) // (u16, u16) tuple
w.writeLE(UInt16(1))
w.writeLE(UInt32(7))
case .image, .vector:
w.writeLE(UInt16(1))
w.writeLE(UInt16(0))
w.writeLE(UInt32(1))
static func descriptor(keys: [RenditionKey], attributes: [AttributeID] = v1KeyFormat) -> Data {
var w = ByteWriter()
w.writeLE(UInt32(1))
w.writeLE(UInt32(0))
w.writeLE(UInt32(4 * (attributes.count + 1)))
w.writeLE(UInt32(attributes.count))
for attribute in attributes {
switch attribute {
case .appearance, .identifier, .element, .part:
w.writeLE(UInt32.max)
default:
w.writeLE(keys.reduce(UInt32(0)) { $0 | 1 << UInt32($1.value(for: attribute)) })
}
// 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)")
return w.data
}
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: Data)]) -> [BOMTree.InlineKeyEntry] {
return assets.map { asset in
BOMTree.InlineKeyEntry(
key: FacetKeys.nameHash(asset.name) & 0xFFFF,
value: asset.descriptor.encode()
value: asset.descriptor
)
}
}
Expand All @@ -97,51 +51,14 @@ 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]) -> Data? {
let hasBitmapOrPreservedSource = renditions.contains { rendition in
switch rendition.body {
case .bitmap, .preservedSource: return true
case .color: return false
}
}
guard hasBitmapOrPreservedSource 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.
let idiomSubtypes = Set(renditions.map { rendition -> UInt32 in
let idiom = UInt32(rendition.idiom.rawValueByte)
let subtype: UInt32 = 0
return (idiom << 16) | subtype
})

return Descriptor(kind: kind, idiomSubtypeCount: UInt32(idiomSubtypes.count))
}

/// AppIcon takes precedence over Vector takes precedence over Image:
/// 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`.
///
/// The AppIcon arm relies on `ImageRenderer.appIconRenditions` only
/// producing `.bitmap(.appIcon)` renditions (PNG-only at that entry
/// point). If that invariant slips, an appiconset whose source was
/// (say) preserved JPG would be misclassified as `.image` here.
private static func inferKind(from renditions: [Rendition]) -> Descriptor.Kind {
for rendition in renditions {
if case .bitmap(let body) = rendition.body, body.kind == .appIcon {
return .appIcon
}
}
for rendition in renditions {
if case .preservedSource(let body) = rendition.body, case .svg = body.format {
return .vector
}
}
return .image
return descriptor(keys: renditions.map(RenditionKey.init(rendition:)))
}
}
6 changes: 1 addition & 5 deletions Sources/AssetKit/CAR/CARLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,7 @@ struct CARLayout {
)
}

var usedAppearances: Set<UInt16> = [AppearanceKeys.any]
for rendition in renditions where rendition.appearance?.darkLuminosity == true {
usedAppearances.insert(AppearanceKeys.dark)
}
self.usedAppearances = usedAppearances
self.usedAppearances = Set(renditions.map(\.appearance)).union([AppearanceKeys.any])
}

private static func facetKind(for rendition: Rendition) -> FacetKeys.Kind {
Expand Down
2 changes: 1 addition & 1 deletion Sources/AssetKit/CAR/CARWriter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ struct CARWriter: Sendable {
let extendedMetadataBlockID = bom.addBlock(ExtendedMetadata.data(deploymentTarget: deploymentTarget))
bom.setVariable("EXTENDED_METADATA", blockID: extendedMetadataBlockID)

let bitmapAssets: [(name: String, descriptor: BitmapKeys.Descriptor)] =
let bitmapAssets: [(name: String, descriptor: Data)] =
layout.assets.compactMap { asset in
guard let descriptor = BitmapKeys.descriptor(
forAsset: asset.name,
Expand Down
12 changes: 6 additions & 6 deletions Sources/AssetKit/CAR/CSIWriter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -120,23 +120,23 @@ enum CSIWriter {
height: 0,
scaleFactor: 100,
pixelFormat: 0,
colorSpace: UInt32(body.colorSpaceID),
colorSpace: 0,
layout: .namedColor,
name: name,
tvlLength: 0,
bitmapCount: 0,
bitmapCount: 1,
renditionLength: UInt32(payload.count)
)
return header + payload
}

private static func colorBody(body: ColorBody) -> Data {
var w = ByteWriter()
w.writeFourCC("COLR")
w.writeFourCC("RLOC")
w.writeLE(UInt32(0)) // version
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(body.colorSpaceID)
w.writeLE(UInt32(body.components.count))
for component in body.components {
w.writeLE(component.bitPattern)
}
return w.data
Expand Down
2 changes: 2 additions & 0 deletions Sources/AssetKit/CAR/KeyFormat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ enum AttributeID: UInt32 {
case idiom = 15
case subtype = 16
case identifier = 17
case displayGamut = 24
}

/// Attribute order CoreUI 970 emits in `KEYFORMAT` (and which the rendition key
Expand All @@ -28,6 +29,7 @@ let v1KeyFormat: [AttributeID] = [
.idiom,
.subtype,
.dimension2,
.displayGamut,
.identifier,
.element,
.part,
Expand Down
5 changes: 3 additions & 2 deletions Sources/AssetKit/CAR/MLECBody.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Foundation
/// Layout verified against actool's reference Assets.car:
///
/// MLEC magic 4 bytes
/// compressionType u32 (0 = raw, 3 = LZFSE)
/// flags u32 (bit 1 marks the bitmap opaque)
/// bytesPerPixel u32 (4 for BGRA8)
/// chunkCount u32 (1 or 3)
/// then chunkCount * KCBC chunks
Expand Down Expand Up @@ -39,7 +39,8 @@ enum MLECBody {

var w = ByteWriter()
w.writeFourCC("MLEC")
w.writeLE(UInt32(3)) // compressionType = 3 (LZFSE)
let opaque = stride(from: 3, to: pixelsBGRA.count, by: 4).allSatisfy { pixelsBGRA[$0] == 255 }
w.writeLE(UInt32(opaque ? 3 : 1))
w.writeLE(UInt32(4)) // bytesPerPixel (BGRA8 = 4)
w.writeLE(chunkCount)

Expand Down
Loading