From 0e64dc4b45a8183c76796c5ad98e66a8f08fd24a Mon Sep 17 00:00:00 2001 From: Anish Pallati Date: Sat, 21 Nov 2026 21:38:59 -0500 Subject: [PATCH 1/7] feat(catalog): prefix asset names inside provides-namespace folders Signed-off-by: Anish Pallati --- Sources/AssetKit/Catalog/CatalogLoader.swift | 26 +++++++++++++---- Sources/AssetKit/Errors.swift | 3 ++ Sources/AssetKit/Schema/Contents.swift | 11 +++++++ Tests/AssetKitTests/CatalogLoaderTests.swift | 30 ++++++++++++++++++++ 4 files changed, 65 insertions(+), 5 deletions(-) diff --git a/Sources/AssetKit/Catalog/CatalogLoader.swift b/Sources/AssetKit/Catalog/CatalogLoader.swift index 55b7484..f0cc44a 100644 --- a/Sources/AssetKit/Catalog/CatalogLoader.swift +++ b/Sources/AssetKit/Catalog/CatalogLoader.swift @@ -41,9 +41,9 @@ struct CatalogLoader: Sendable { var colorSets: [LoadedColorSet] = [] var appIcons: [LoadedAppIcon] = [] - try walk(url, fileManager: fm) { entry in + try walk(url, namespace: "", fileManager: fm, decoder: decoder) { entry, namespace in let ext = entry.pathExtension - let name = entry.deletingPathExtension().lastPathComponent + let name = namespace + entry.deletingPathExtension().lastPathComponent switch ext { case "imageset": let contents = try decode(ImageSetContents.self, at: entry, decoder: decoder) @@ -52,6 +52,7 @@ struct CatalogLoader: Sendable { let contents = try decode(ColorSetContents.self, at: entry, decoder: decoder) colorSets.append(LoadedColorSet(name: name, directory: entry, contents: contents)) case "appiconset": + guard namespace.isEmpty else { throw XCAssetCompilerError.appIconSetInNamespace(name) } let contents = try decode(AppIconContents.self, at: entry, decoder: decoder) appIcons.append(LoadedAppIcon(name: name, directory: entry, contents: contents)) default: @@ -91,16 +92,31 @@ struct CatalogLoader: Sendable { } } - private func walk(_ root: URL, fileManager fm: FileManager, visit: (URL) throws -> Void) throws { + private func walk( + _ root: URL, + namespace: String, + fileManager fm: FileManager, + decoder: JSONDecoder, + visit: (URL, String) throws -> Void + ) throws { let children = try fm.contentsOfDirectory(at: root, includingPropertiesForKeys: [.isDirectoryKey]) for child in children { let values = try child.resourceValues(forKeys: [.isDirectoryKey]) guard values.isDirectory == true else { continue } let ext = child.pathExtension if ["imageset", "colorset", "appiconset"].contains(ext) { - try visit(child) + try visit(child, namespace) } else { - try walk(child, fileManager: fm, visit: visit) + let hasContents = fm.fileExists(atPath: child.appendingPathComponent("Contents.json").path) + let folder = hasContents ? try decode(FolderContents.self, at: child, decoder: decoder) : nil + let providesNamespace = folder?.properties?.providesNamespace == true + try walk( + child, + namespace: providesNamespace ? namespace + child.lastPathComponent + "/" : namespace, + fileManager: fm, + decoder: decoder, + visit: visit + ) } } } diff --git a/Sources/AssetKit/Errors.swift b/Sources/AssetKit/Errors.swift index ebeedb7..49b8d45 100644 --- a/Sources/AssetKit/Errors.swift +++ b/Sources/AssetKit/Errors.swift @@ -8,6 +8,7 @@ public enum XCAssetCompilerError: Error, Sendable, Equatable { case invalidColorComponent(String) case unsupportedGamut(String) case multipleAppIconSets([String]) + case appIconSetInNamespace(String) case appIconSizeMissing(asset: String, size: String) case notADirectory(path: String) case unsupportedAssetType(String) @@ -32,6 +33,8 @@ extension XCAssetCompilerError: CustomStringConvertible { return "Invalid color component: '\(s)'" case .unsupportedGamut(let g): return "Unsupported display-gamut: '\(g)' (expected sRGB or display-P3)" + case .appIconSetInNamespace(let name): + return "The app icon set '\(name)' must be a top level object in the asset catalog" case .multipleAppIconSets(let names): return "Catalog has more than one .appiconset: \(names.joined(separator: ", "))" case .appIconSizeMissing(let asset, let size): diff --git a/Sources/AssetKit/Schema/Contents.swift b/Sources/AssetKit/Schema/Contents.swift index ac3271c..fdd386e 100644 --- a/Sources/AssetKit/Schema/Contents.swift +++ b/Sources/AssetKit/Schema/Contents.swift @@ -85,6 +85,17 @@ struct CatalogContents: Codable, Sendable { var info: Info } +struct FolderContents: Codable, Sendable { + struct Properties: Codable, Sendable { + var providesNamespace: Bool? + + enum CodingKeys: String, CodingKey { + case providesNamespace = "provides-namespace" + } + } + var properties: Properties? +} + struct ImageSetContents: Codable, Sendable { struct Image: Codable, Sendable { var idiom: Idiom diff --git a/Tests/AssetKitTests/CatalogLoaderTests.swift b/Tests/AssetKitTests/CatalogLoaderTests.swift index a0f55f8..caba2d7 100644 --- a/Tests/AssetKitTests/CatalogLoaderTests.swift +++ b/Tests/AssetKitTests/CatalogLoaderTests.swift @@ -49,4 +49,34 @@ struct CatalogLoaderTests { #expect(loaded.colorSets.isEmpty) #expect(loaded.appIcon == nil) } + + @Test("Prefixes names inside provides-namespace folders with the folder path") + func namespaces() async throws { + let tmp = FileManager.default.temporaryDirectory + .appendingPathComponent("ns-\(UUID().uuidString).xcassets", isDirectory: true) + try FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tmp) } + let info = #""info": { "version": 1, "author": "xcode" }"# + let namespace = "{ \(info), \"properties\": { \"provides-namespace\": true } }" + let folders = [ + "Icons": namespace, + "Icons/Small": namespace, + "Icons/Plain": "{ \(info) }", + "Loose": "{ \(info) }", + ] + try Data("{ \(info) }".utf8).write(to: tmp.appendingPathComponent("Contents.json")) + for (path, contents) in folders { + let dir = tmp.appendingPathComponent(path, isDirectory: true) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + try Data(contents.utf8).write(to: dir.appendingPathComponent("Contents.json")) + } + for path in ["Top", "Icons/Star", "Icons/Small/Dot", "Icons/Plain/Square", "Loose/Circle"] { + let dir = tmp.appendingPathComponent(path + ".colorset", isDirectory: true) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + try Data("{ \"colors\": [], \(info) }".utf8).write(to: dir.appendingPathComponent("Contents.json")) + } + + let loaded = try await CatalogLoader().load(catalog: tmp) + #expect(Set(loaded.colorSets.map(\.name)) == ["Top", "Icons/Star", "Icons/Small/Dot", "Icons/Square", "Circle"]) + } } From 2287b90bdf46bcd9e87aa85c3f703d0644f3b780 Mon Sep 17 00:00:00 2001 From: Anish Pallati Date: Sat, 21 Nov 2026 21:39:10 -0500 Subject: [PATCH 2/7] fix(color): make named colors resolvable by CoreUI Signed-off-by: Anish Pallati --- Sources/AssetKit/CAR/CSIWriter.swift | 4 ++-- Sources/AssetKit/CAR/RenditionKey.swift | 10 ++++++---- Tests/AssetKitTests/CSIWriterTests.swift | 2 +- docs/coreui-970-format.md | 3 ++- 4 files changed, 11 insertions(+), 8 deletions(-) diff --git a/Sources/AssetKit/CAR/CSIWriter.swift b/Sources/AssetKit/CAR/CSIWriter.swift index 2bdeace..1318e55 100644 --- a/Sources/AssetKit/CAR/CSIWriter.swift +++ b/Sources/AssetKit/CAR/CSIWriter.swift @@ -124,7 +124,7 @@ enum CSIWriter { layout: .namedColor, name: name, tvlLength: 0, - bitmapCount: 0, + bitmapCount: 1, renditionLength: UInt32(payload.count) ) return header + payload @@ -132,7 +132,7 @@ enum CSIWriter { 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 diff --git a/Sources/AssetKit/CAR/RenditionKey.swift b/Sources/AssetKit/CAR/RenditionKey.swift index 01dfb76..6806e13 100644 --- a/Sources/AssetKit/CAR/RenditionKey.swift +++ b/Sources/AssetKit/CAR/RenditionKey.swift @@ -20,8 +20,8 @@ struct RenditionKey: Hashable, Sendable { /// CoreUI element IDs that v1 emits. Values dumped from reference /// `Assets.car` produced by actool (Xcode 26 / CoreUI 970). enum Element: UInt16 { - /// Element used by both `.image` (imageset) and `.appIcon` bitmap - /// renditions. The category is differentiated by `Part` below. + /// Element used by `.image`, `.appIcon` and `.color` renditions. The + /// category is differentiated by `Part` below. case bitmap = 85 } @@ -36,6 +36,7 @@ struct RenditionKey: Hashable, Sendable { /// rather than `image`; bitmap variants rasterised from the SVG /// (which `UIImage(named:)` actually returns) live under `image`. case vectorSource = 42 + case color = 217 } init(rendition: Rendition) { @@ -61,8 +62,9 @@ struct RenditionKey: Hashable, Sendable { self.dimension2 = 0 } case .color: - self.element = 0 - self.part = 0 + self.element = Element.bitmap.rawValue + self.part = Part.color.rawValue + self.scale = 1 self.dimension2 = 0 case .preservedSource(let body): self.element = Element.bitmap.rawValue diff --git a/Tests/AssetKitTests/CSIWriterTests.swift b/Tests/AssetKitTests/CSIWriterTests.swift index 00c17a9..7f70a15 100644 --- a/Tests/AssetKitTests/CSIWriterTests.swift +++ b/Tests/AssetKitTests/CSIWriterTests.swift @@ -58,6 +58,6 @@ struct CSIWriterTests { #expect(data.count >= 184 + 4 + 4 + 4 + 4 + 8 * 4) let payloadStart = 184 let magic = data.subdata(in: payloadStart..<(payloadStart + 4)) - #expect(Array(magic) == Array("COLR".utf8)) + #expect(Array(magic) == Array("RLOC".utf8)) } } diff --git a/docs/coreui-970-format.md b/docs/coreui-970-format.md index bdc2e24..ba83175 100644 --- a/docs/coreui-970-format.md +++ b/docs/coreui-970-format.md @@ -58,10 +58,11 @@ CoreUI mixes endianness for its magic words. The following are little-endian mul - `CTAR` → on disk: `R`, `A`, `T`, `C` - `CTSI` → on disk: `I`, `S`, `T`, `C` - `kfmt` → on disk: `t`, `m`, `f`, `k` +- `COLR`, stored as `R`, `L`, `O`, `C` on disk These are written in character order (no reversal): -- `MLEC`, `KCBC`, `COLR`, `META` +- `MLEC`, `KCBC`, `META` There's no obvious pattern in the source code for which is which; it must be matched against actool's output per block. Mixing this up produces files that look superficially correct in a hex viewer but fail at runtime. From 454f0df76533a5098b540e84b42740c1a1f3bcc8 Mon Sep 17 00:00:00 2001 From: Anish Pallati Date: Sat, 21 Nov 2026 21:39:10 -0500 Subject: [PATCH 3/7] fix(bitmap): mark bitmaps opaque only when every pixel is opaque Signed-off-by: Anish Pallati --- Sources/AssetKit/CAR/MLECBody.swift | 5 +++-- Tests/AssetKitTests/CSIWriterTests.swift | 12 ++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/Sources/AssetKit/CAR/MLECBody.swift b/Sources/AssetKit/CAR/MLECBody.swift index 8164c57..fe552dd 100644 --- a/Sources/AssetKit/CAR/MLECBody.swift +++ b/Sources/AssetKit/CAR/MLECBody.swift @@ -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 @@ -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) diff --git a/Tests/AssetKitTests/CSIWriterTests.swift b/Tests/AssetKitTests/CSIWriterTests.swift index 7f70a15..208e03f 100644 --- a/Tests/AssetKitTests/CSIWriterTests.swift +++ b/Tests/AssetKitTests/CSIWriterTests.swift @@ -60,4 +60,16 @@ struct CSIWriterTests { let magic = data.subdata(in: payloadStart..<(payloadStart + 4)) #expect(Array(magic) == Array("RLOC".utf8)) } + + @Test("MLEC flags mark a bitmap opaque only when every pixel's alpha is 255") + func mlecOpacity() { + func flags(_ alphas: [UInt8]) -> UInt32 { + let pixels: [UInt8] = alphas.flatMap { alpha -> [UInt8] in [0, 0, 0, alpha] } + let data = MLECBody.encode(width: UInt32(alphas.count), height: 1, pixelsBGRA: pixels) + return UInt32(littleEndian: data.subdata(in: 4..<8).withUnsafeBytes { $0.loadUnaligned(as: UInt32.self) }) + } + #expect(flags([255, 255]) == 3) + #expect(flags([255, 128]) == 1) + #expect(flags([0, 0]) == 1) + } } From 2fe906d7c5a99b88cf8bbc669e82097341e606cc Mon Sep 17 00:00:00 2001 From: Anish Pallati Date: Sun, 22 Nov 2026 00:13:27 -0500 Subject: [PATCH 4/7] fix(bitmapkeys): compute attribute masks from each asset's renditions Signed-off-by: Anish Pallati --- Sources/AssetKit/CAR/BitmapKeys.swift | 125 ++++------------------ Sources/AssetKit/CAR/CARWriter.swift | 2 +- Sources/AssetKit/CAR/RenditionKey.swift | 14 +++ Tests/AssetKitTests/BitmapKeysTests.swift | 21 ++++ docs/coreui-970-format.md | 20 +--- 5 files changed, 61 insertions(+), 121 deletions(-) create mode 100644 Tests/AssetKitTests/BitmapKeysTests.swift diff --git a/Sources/AssetKit/CAR/BitmapKeys.swift b/Sources/AssetKit/CAR/BitmapKeys.swift index d3e31b4..270bc88 100644 --- a/Sources/AssetKit/CAR/BitmapKeys.swift +++ b/Sources/AssetKit/CAR/BitmapKeys.swift @@ -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 ) } } @@ -97,7 +51,7 @@ 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 @@ -105,43 +59,6 @@ enum BitmapKeys { } } 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:))) } } diff --git a/Sources/AssetKit/CAR/CARWriter.swift b/Sources/AssetKit/CAR/CARWriter.swift index 4288e0e..e4872c9 100644 --- a/Sources/AssetKit/CAR/CARWriter.swift +++ b/Sources/AssetKit/CAR/CARWriter.swift @@ -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, diff --git a/Sources/AssetKit/CAR/RenditionKey.swift b/Sources/AssetKit/CAR/RenditionKey.swift index 6806e13..9adae66 100644 --- a/Sources/AssetKit/CAR/RenditionKey.swift +++ b/Sources/AssetKit/CAR/RenditionKey.swift @@ -106,6 +106,20 @@ struct RenditionKey: Hashable, Sendable { self.part = part } + func value(for attribute: AttributeID) -> UInt16 { + switch attribute { + case .appearance: return appearance + case .localization: return localization + case .scale: return scale + case .idiom: return idiom + case .subtype: return subtype + case .dimension2: return dimension2 + case .identifier: return identifier + case .element: return element + case .part: return part + } + } + func encode() -> Data { var w = ByteWriter() w.writeLE(appearance) diff --git a/Tests/AssetKitTests/BitmapKeysTests.swift b/Tests/AssetKitTests/BitmapKeysTests.swift new file mode 100644 index 0000000..be1974d --- /dev/null +++ b/Tests/AssetKitTests/BitmapKeysTests.swift @@ -0,0 +1,21 @@ +import Foundation +import Testing +@testable import AssetKit + +@Suite("BitmapKeys") +struct BitmapKeysTests { + @Test("Descriptor masks the values each attribute takes across the asset's renditions") + func masks() { + let keys = [ + RenditionKey(scale: 1, idiom: 0, identifier: 7, element: 85, part: 181), + RenditionKey(scale: 3, idiom: 2, identifier: 7, element: 85, part: 181), + ] + let data = BitmapKeys.descriptor(keys: keys) + let words = stride(from: 0, to: data.count, by: 4).map { offset in + UInt32(littleEndian: data.subdata(in: offset.. Date: Sun, 22 Nov 2026 00:15:42 -0500 Subject: [PATCH 5/7] fix(color): encode color spaces and component values like actool Signed-off-by: Anish Pallati --- Sources/AssetKit/CAR/CSIWriter.swift | 8 +-- Sources/AssetKit/Errors.swift | 3 + .../AssetKit/Rendition/ColorRenderer.swift | 7 +-- Sources/AssetKit/Rendition/Rendition.swift | 7 +-- Sources/AssetKit/Schema/Contents.swift | 59 +++++++++++++------ Tests/AssetKitTests/CSIWriterTests.swift | 2 +- Tests/AssetKitTests/ColorRendererTests.swift | 35 ++++++++--- 7 files changed, 80 insertions(+), 41 deletions(-) diff --git a/Sources/AssetKit/CAR/CSIWriter.swift b/Sources/AssetKit/CAR/CSIWriter.swift index 1318e55..31c3084 100644 --- a/Sources/AssetKit/CAR/CSIWriter.swift +++ b/Sources/AssetKit/CAR/CSIWriter.swift @@ -120,7 +120,7 @@ enum CSIWriter { height: 0, scaleFactor: 100, pixelFormat: 0, - colorSpace: UInt32(body.colorSpaceID), + colorSpace: 0, layout: .namedColor, name: name, tvlLength: 0, @@ -134,9 +134,9 @@ enum CSIWriter { var w = ByteWriter() 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 diff --git a/Sources/AssetKit/Errors.swift b/Sources/AssetKit/Errors.swift index 49b8d45..4815962 100644 --- a/Sources/AssetKit/Errors.swift +++ b/Sources/AssetKit/Errors.swift @@ -6,6 +6,7 @@ public enum XCAssetCompilerError: Error, Sendable, Equatable { case missingReferencedFile(asset: String, filename: String) case scaleFileMissing(asset: String, scale: String) case invalidColorComponent(String) + case unsupportedColorSpace(String) case unsupportedGamut(String) case multipleAppIconSets([String]) case appIconSetInNamespace(String) @@ -31,6 +32,8 @@ extension XCAssetCompilerError: CustomStringConvertible { return "Asset '\(asset)' declares scale \(scale) but no file is present for it" case .invalidColorComponent(let s): return "Invalid color component: '\(s)'" + case .unsupportedColorSpace(let s): + return "Unsupported color-space: '\(s)'" case .unsupportedGamut(let g): return "Unsupported display-gamut: '\(g)' (expected sRGB or display-P3)" case .appIconSetInNamespace(let name): diff --git a/Sources/AssetKit/Rendition/ColorRenderer.swift b/Sources/AssetKit/Rendition/ColorRenderer.swift index 0bd50ba..236c542 100644 --- a/Sources/AssetKit/Rendition/ColorRenderer.swift +++ b/Sources/AssetKit/Rendition/ColorRenderer.swift @@ -4,7 +4,7 @@ enum ColorRenderer { static func renditions(for set: LoadedColorSet) throws -> [Rendition] { var out: [Rendition] = [] for entry in set.contents.colors { - let (r, g, b, a) = try entry.color.components.asDoubles() + let body = ColorBody(components: try entry.color.values(), colorSpaceID: try entry.color.colorSpaceID()) let gamut: Gamut = { if let declared = entry.displayGamut { return declared } switch entry.color.colorSpace { @@ -19,10 +19,7 @@ enum ColorRenderer { scale: nil, appearance: appearance, gamut: gamut, - body: .color(ColorBody( - red: r, green: g, blue: b, alpha: a, - colorSpaceID: gamut.colorSpaceID - )) + body: .color(body) )) } return out diff --git a/Sources/AssetKit/Rendition/Rendition.swift b/Sources/AssetKit/Rendition/Rendition.swift index 2175002..71612fe 100644 --- a/Sources/AssetKit/Rendition/Rendition.swift +++ b/Sources/AssetKit/Rendition/Rendition.swift @@ -47,11 +47,8 @@ struct BitmapBody: Sendable { } struct ColorBody: Sendable { - var red: Double - var green: Double - var blue: Double - var alpha: Double - var colorSpaceID: UInt8 + var components: [Double] + var colorSpaceID: UInt32 } /// Source file kept verbatim inside a DWAR envelope rather than rasterised diff --git a/Sources/AssetKit/Schema/Contents.swift b/Sources/AssetKit/Schema/Contents.swift index fdd386e..e5c669d 100644 --- a/Sources/AssetKit/Schema/Contents.swift +++ b/Sources/AssetKit/Schema/Contents.swift @@ -156,28 +156,51 @@ struct ColorSetContents: Codable, Sendable { case components } - struct Components: Codable, Sendable { - var red: String - var green: String - var blue: String - var alpha: String - - func asDoubles() throws -> (r: Double, g: Double, b: Double, a: Double) { - func parse(_ s: String) throws -> Double { - if s.hasPrefix("0x") || s.hasPrefix("0X") { - let hex = String(s.dropFirst(2)) - guard let n = UInt8(hex, radix: 16) else { - throw XCAssetCompilerError.invalidColorComponent(s) - } - return Double(n) / 255 - } - guard let n = Double(s) else { + static let colorSpaceIDs: [String: UInt32] = [ + "srgb": 1, + "gray-gamma-22": 2, + "display-p3": 3, + "extended-srgb": 4, + "extended-linear-srgb": 5, + "extended-gray": 6, + ] + + func colorSpaceID() throws -> UInt32 { + guard let id = Self.colorSpaceIDs[colorSpace] else { + throw XCAssetCompilerError.unsupportedColorSpace(colorSpace) + } + return id + } + + func values() throws -> [Double] { + func parse(_ s: String?, _ name: String) throws -> Double { + guard let s else { throw XCAssetCompilerError.invalidColorComponent("missing \(name)") } + if s.hasPrefix("0x") || s.hasPrefix("0X") { + guard let n = UInt8(s.dropFirst(2), radix: 16) else { throw XCAssetCompilerError.invalidColorComponent(s) } - return n > 1 ? n / 255 : n + return Double(n) / 255 } - return (try parse(red), try parse(green), try parse(blue), try parse(alpha)) + if s.contains(".") { + guard let n = Double(s) else { throw XCAssetCompilerError.invalidColorComponent(s) } + return n + } + guard let n = Int(s) else { throw XCAssetCompilerError.invalidColorComponent(s) } + return Double(n) / 255 + } + let c = components + if ["gray-gamma-22", "extended-gray"].contains(colorSpace) { + return [try parse(c.white, "white"), try parse(c.alpha, "alpha")] } + return [try parse(c.red, "red"), try parse(c.green, "green"), try parse(c.blue, "blue"), try parse(c.alpha, "alpha")] + } + + struct Components: Codable, Sendable { + var red: String? + var green: String? + var blue: String? + var white: String? + var alpha: String? } } diff --git a/Tests/AssetKitTests/CSIWriterTests.swift b/Tests/AssetKitTests/CSIWriterTests.swift index 208e03f..be1eb4a 100644 --- a/Tests/AssetKitTests/CSIWriterTests.swift +++ b/Tests/AssetKitTests/CSIWriterTests.swift @@ -52,7 +52,7 @@ struct CSIWriterTests { @Test("Color CSI body starts with COLR magic and four IEEE-754 doubles") func colorBody() { - let body = ColorBody(red: 1, green: 0, blue: 0.5, alpha: 1, colorSpaceID: 0) + let body = ColorBody(components: [1, 0, 0.5, 1], colorSpaceID: 1) let data = CSIWriter.color(name: "Accent", body: body) // CSI header is 184 bytes; body starts at offset 184 #expect(data.count >= 184 + 4 + 4 + 4 + 4 + 8 * 4) diff --git a/Tests/AssetKitTests/ColorRendererTests.swift b/Tests/AssetKitTests/ColorRendererTests.swift index 2483c8d..2eb6280 100644 --- a/Tests/AssetKitTests/ColorRendererTests.swift +++ b/Tests/AssetKitTests/ColorRendererTests.swift @@ -34,10 +34,7 @@ struct ColorRendererTests { Issue.record("expected color body") return } - #expect(abs(body.red - 0.5) < 1e-9) - #expect(abs(body.green - 0.25) < 1e-9) - #expect(abs(body.blue - 0.75) < 1e-9) - #expect(abs(body.alpha - 1) < 1e-9) + #expect(body.components == [0.5, 0.25, 0.75, 1]) #expect(body.colorSpaceID == 1) } @@ -69,7 +66,7 @@ struct ColorRendererTests { Issue.record("expected color body") return } - #expect(body.colorSpaceID == 2) + #expect(body.colorSpaceID == 3) } @Test("Parses 0x-prefixed hex components") @@ -97,8 +94,30 @@ struct ColorRendererTests { Issue.record("expected color body") return } - #expect(abs(body.red - 1) < 1e-9) - #expect(abs(body.green - 0) < 1e-9) - #expect(abs(body.blue - 128 / 255) < 1e-9) + #expect(body.components == [1, 0, 128.0 / 255, 1]) + } + + @Test("Reads gray as white and alpha, decimals as is and integers over 255") + func parsesGrayAndIntegers() throws { + func body(_ colorSpace: String, _ components: String) throws -> ColorBody { + let json = """ + { + "info": { "version": 1, "author": "xcode" }, + "colors": [ + { "idiom": "universal", "color": { "color-space": "\(colorSpace)", "components": { \(components) } } } + ] + } + """ + let contents = try JSONDecoder().decode(ColorSetContents.self, from: Data(json.utf8)) + let set = LoadedColorSet(name: "C", directory: URL(fileURLWithPath: "/"), contents: contents) + guard case .color(let body) = try ColorRenderer.renditions(for: set)[0].body else { + throw XCAssetCompilerError.invalidColorComponent("expected color body") + } + return body + } + let gray = try body("gray-gamma-22", #""white": "0.500", "alpha": "1.000""#) + #expect(gray.components == [0.5, 1]) + let extended = try body("extended-srgb", #""red": "1", "green": "255", "blue": "1.2", "alpha": "1""#) + #expect(extended.components == [1.0 / 255, 1, 1.2, 1.0 / 255]) } } From f2dbe7ab873d72c0d5956c210def334058de57b1 Mon Sep 17 00:00:00 2001 From: Anish Pallati Date: Sun, 22 Nov 2026 00:18:36 -0500 Subject: [PATCH 6/7] fix(appearance): key light and high-contrast variants like actool Signed-off-by: Anish Pallati --- Sources/AssetKit/CAR/AppearanceKeys.swift | 23 +++++++++---------- Sources/AssetKit/CAR/CARLayout.swift | 6 +---- Sources/AssetKit/CAR/RenditionKey.swift | 2 +- .../AssetKit/Rendition/ColorRenderer.swift | 2 +- .../AssetKit/Rendition/ImageRenderer.swift | 4 ++-- Sources/AssetKit/Rendition/JPEGSource.swift | 2 +- Sources/AssetKit/Rendition/PNGSource.swift | 2 +- Sources/AssetKit/Rendition/Rendition.swift | 2 +- Sources/AssetKit/Rendition/SVGSource.swift | 2 +- Sources/AssetKit/Schema/Contents.swift | 16 +++++++++---- Tests/AssetKitTests/RenditionKeyTests.swift | 4 ++-- docs/coreui-970-format.md | 2 ++ 12 files changed, 36 insertions(+), 31 deletions(-) diff --git a/Sources/AssetKit/CAR/AppearanceKeys.swift b/Sources/AssetKit/CAR/AppearanceKeys.swift index 2733110..197b6b4 100644 --- a/Sources/AssetKit/CAR/AppearanceKeys.swift +++ b/Sources/AssetKit/CAR/AppearanceKeys.swift @@ -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) -> [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 { diff --git a/Sources/AssetKit/CAR/CARLayout.swift b/Sources/AssetKit/CAR/CARLayout.swift index 91a19b5..f7f765e 100644 --- a/Sources/AssetKit/CAR/CARLayout.swift +++ b/Sources/AssetKit/CAR/CARLayout.swift @@ -38,11 +38,7 @@ struct CARLayout { ) } - var usedAppearances: Set = [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 { diff --git a/Sources/AssetKit/CAR/RenditionKey.swift b/Sources/AssetKit/CAR/RenditionKey.swift index 9adae66..6b8a8e6 100644 --- a/Sources/AssetKit/CAR/RenditionKey.swift +++ b/Sources/AssetKit/CAR/RenditionKey.swift @@ -40,7 +40,7 @@ struct RenditionKey: Hashable, Sendable { } init(rendition: Rendition) { - self.appearance = (rendition.appearance?.darkLuminosity == true) ? 1 : 0 + self.appearance = rendition.appearance self.localization = 0 self.scale = rendition.scale?.rawValueByte ?? 0 self.idiom = rendition.idiom.rawValueByte diff --git a/Sources/AssetKit/Rendition/ColorRenderer.swift b/Sources/AssetKit/Rendition/ColorRenderer.swift index 236c542..05452b1 100644 --- a/Sources/AssetKit/Rendition/ColorRenderer.swift +++ b/Sources/AssetKit/Rendition/ColorRenderer.swift @@ -12,7 +12,7 @@ enum ColorRenderer { default: return .sRGB } }() - let appearance = entry.appearances?.first { $0.darkLuminosity } + let appearance = Appearance.keyValue(entry.appearances) out.append(Rendition( name: set.name, idiom: entry.idiom, diff --git a/Sources/AssetKit/Rendition/ImageRenderer.swift b/Sources/AssetKit/Rendition/ImageRenderer.swift index 05e6107..ec3a675 100644 --- a/Sources/AssetKit/Rendition/ImageRenderer.swift +++ b/Sources/AssetKit/Rendition/ImageRenderer.swift @@ -20,7 +20,7 @@ enum ImageRenderer { throw XCAssetCompilerError.unsupportedAssetType(filename) } let bytes = try Data(contentsOf: src) - let appearance = image.appearances?.first { $0.darkLuminosity } + let appearance = Appearance.keyValue(image.appearances) switch format { case .png: let ctx = PNGSource.Context( @@ -84,7 +84,7 @@ enum ImageRenderer { assetName: appIcon.name, idiom: file.idiom, scale: scale, - appearance: nil, + appearance: 0, gamut: .sRGB, filename: filename, kind: .appIcon diff --git a/Sources/AssetKit/Rendition/JPEGSource.swift b/Sources/AssetKit/Rendition/JPEGSource.swift index 1fc4796..a138841 100644 --- a/Sources/AssetKit/Rendition/JPEGSource.swift +++ b/Sources/AssetKit/Rendition/JPEGSource.swift @@ -9,7 +9,7 @@ enum JPEGSource { var assetName: String var idiom: Idiom var scale: Scale? - var appearance: Appearance? + var appearance: UInt16 var filename: String } diff --git a/Sources/AssetKit/Rendition/PNGSource.swift b/Sources/AssetKit/Rendition/PNGSource.swift index 6cc04b3..6b4ad6e 100644 --- a/Sources/AssetKit/Rendition/PNGSource.swift +++ b/Sources/AssetKit/Rendition/PNGSource.swift @@ -22,7 +22,7 @@ enum PNGSource { var assetName: String var idiom: Idiom var scale: Scale? - var appearance: Appearance? + var appearance: UInt16 var gamut: Gamut var filename: String var kind: BitmapBody.Kind diff --git a/Sources/AssetKit/Rendition/Rendition.swift b/Sources/AssetKit/Rendition/Rendition.swift index 71612fe..bcc7859 100644 --- a/Sources/AssetKit/Rendition/Rendition.swift +++ b/Sources/AssetKit/Rendition/Rendition.swift @@ -10,7 +10,7 @@ struct Rendition: Sendable { var name: String var idiom: Idiom var scale: Scale? - var appearance: Appearance? + var appearance: UInt16 var gamut: Gamut? var body: Body } diff --git a/Sources/AssetKit/Rendition/SVGSource.swift b/Sources/AssetKit/Rendition/SVGSource.swift index c78901e..41c73dc 100644 --- a/Sources/AssetKit/Rendition/SVGSource.swift +++ b/Sources/AssetKit/Rendition/SVGSource.swift @@ -9,7 +9,7 @@ enum SVGSource { struct Context { var assetName: String var idiom: Idiom - var appearance: Appearance? + var appearance: UInt16 var filename: String } diff --git a/Sources/AssetKit/Schema/Contents.swift b/Sources/AssetKit/Schema/Contents.swift index e5c669d..e387806 100644 --- a/Sources/AssetKit/Schema/Contents.swift +++ b/Sources/AssetKit/Schema/Contents.swift @@ -70,11 +70,19 @@ struct Appearance: Codable, Sendable, Hashable { var appearance: String var value: String - var darkLuminosity: Bool { - appearance == "luminosity" && value == "dark" + static func keyValue(_ appearances: [Appearance]?) -> UInt16 { + let appearances = appearances ?? [] + let luminosity = appearances.first { $0.appearance == "luminosity" }?.value + let highContrast = appearances.contains { $0.appearance == "contrast" && $0.value == "high" } + switch (luminosity, highContrast) { + case ("dark", false): return 1 + case ("dark", true): return 3 + case ("light", false): return 4 + case ("light", true): return 5 + case (_, true): return 2 + case (_, false): return 0 + } } - - static let dark = Appearance(appearance: "luminosity", value: "dark") } struct CatalogContents: Codable, Sendable { diff --git a/Tests/AssetKitTests/RenditionKeyTests.swift b/Tests/AssetKitTests/RenditionKeyTests.swift index 64a24f1..e167048 100644 --- a/Tests/AssetKitTests/RenditionKeyTests.swift +++ b/Tests/AssetKitTests/RenditionKeyTests.swift @@ -85,7 +85,7 @@ struct RenditionKeyTests { name: "Svg", idiom: .universal, scale: .x1, - appearance: nil, + appearance: 0, gamut: nil, body: .preservedSource(PreservedSourceBody( format: .svg, @@ -110,7 +110,7 @@ struct RenditionKeyTests { name: "Jpg", idiom: .universal, scale: .x2, - appearance: nil, + appearance: 0, gamut: nil, body: .preservedSource(PreservedSourceBody( format: .jpeg(width: 120, height: 120), diff --git a/docs/coreui-970-format.md b/docs/coreui-970-format.md index eb548a7..4094479 100644 --- a/docs/coreui-970-format.md +++ b/docs/coreui-970-format.md @@ -89,6 +89,8 @@ The APPEARANCEKEYS tree maps appearance name strings to the numeric IDs that app - iOS: `UIAppearanceAny` (0), `UIAppearanceDark` (1) - macOS: `NSAppearanceNameAqua` (0), `NSAppearanceNameDarkAqua` (1) +For iOS, actool 27.1 also writes `UIAppearanceHighContrastAny` (2), `UIAppearanceHighContrastDark` (3), `UIAppearanceLight` (4) and `UIAppearanceHighContrastLight` (5) for high-contrast and light variants, each only when a rendition uses it. + Registering only the macOS names produces a catalog where `UIImage(named:)` returns nil at runtime for every asset, even though `assetutil --info` parses cleanly. SpringBoard's appicon path doesn't depend on APPEARANCEKEYS (it falls back to loose PNGs we emit alongside `Assets.car`, see §"SpringBoard fallback" below), which masks the bug for icon-only catalogs. The `UIAppearanceAny` row (id=0) is always emitted, because every rendition key packs `appearance=0` as the default-variant marker — even in catalogs with no explicit appearance entries. The `UIAppearanceDark` row (id=1) is emitted only when at least one rendition in the catalog declares the dark variant (matches actool's reference: dark-free catalogs omit the row entirely). Each appearance ID is encoded as a single `u16 LE`. From 772d47c285c5acbe6faa62a6a543209628fb1ece Mon Sep 17 00:00:00 2001 From: Anish Pallati Date: Sun, 22 Nov 2026 00:20:16 -0500 Subject: [PATCH 7/7] fix(keys): key display-gamut variants with the displayGamut attribute Signed-off-by: Anish Pallati --- Sources/AssetKit/CAR/KeyFormat.swift | 2 ++ Sources/AssetKit/CAR/RenditionKey.swift | 19 ++++++++---- .../AssetKit/Rendition/ColorRenderer.swift | 9 +----- Tests/AssetKitTests/RenditionKeyTests.swift | 31 +++++++++++++++---- docs/coreui-970-format.md | 2 +- 5 files changed, 42 insertions(+), 21 deletions(-) diff --git a/Sources/AssetKit/CAR/KeyFormat.swift b/Sources/AssetKit/CAR/KeyFormat.swift index 292ce33..6318a94 100644 --- a/Sources/AssetKit/CAR/KeyFormat.swift +++ b/Sources/AssetKit/CAR/KeyFormat.swift @@ -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 @@ -28,6 +29,7 @@ let v1KeyFormat: [AttributeID] = [ .idiom, .subtype, .dimension2, + .displayGamut, .identifier, .element, .part, diff --git a/Sources/AssetKit/CAR/RenditionKey.swift b/Sources/AssetKit/CAR/RenditionKey.swift index 6b8a8e6..68f3c35 100644 --- a/Sources/AssetKit/CAR/RenditionKey.swift +++ b/Sources/AssetKit/CAR/RenditionKey.swift @@ -1,11 +1,11 @@ import Foundation -/// Packed rendition key matching `v1KeyFormat` (CoreUI 970, 9 attributes). +/// Packed rendition key matching `v1KeyFormat` (CoreUI 970, 10 attributes). /// /// Encoded as a sequence of little-endian `UInt16` tokens, one per attribute, /// in the order declared by `KEYFORMAT`. The pair `(attributeID, attributeValue)` /// is implicit: the position in the tuple selects which attribute the token -/// belongs to. Total size is 18 bytes (9 × u16). +/// belongs to. Total size is 20 bytes (10 u16 tokens). struct RenditionKey: Hashable, Sendable { var appearance: UInt16 var localization: UInt16 @@ -13,6 +13,7 @@ struct RenditionKey: Hashable, Sendable { var idiom: UInt16 var subtype: UInt16 var dimension2: UInt16 + var displayGamut: UInt16 var identifier: UInt16 var element: UInt16 var part: UInt16 @@ -45,6 +46,7 @@ struct RenditionKey: Hashable, Sendable { self.scale = rendition.scale?.rawValueByte ?? 0 self.idiom = rendition.idiom.rawValueByte self.subtype = 0 + self.displayGamut = rendition.gamut == .displayP3 ? 1 : 0 self.identifier = UInt16(FacetKeys.nameHash(rendition.name) & 0xFFFF) switch rendition.body { case .bitmap(let body): @@ -91,6 +93,7 @@ struct RenditionKey: Hashable, Sendable { idiom: UInt16 = 0, subtype: UInt16 = 0, dimension2: UInt16 = 0, + displayGamut: UInt16 = 0, identifier: UInt16 = 0, element: UInt16 = 0, part: UInt16 = 0 @@ -101,6 +104,7 @@ struct RenditionKey: Hashable, Sendable { self.idiom = idiom self.subtype = subtype self.dimension2 = dimension2 + self.displayGamut = displayGamut self.identifier = identifier self.element = element self.part = part @@ -114,6 +118,7 @@ struct RenditionKey: Hashable, Sendable { case .idiom: return idiom case .subtype: return subtype case .dimension2: return dimension2 + case .displayGamut: return displayGamut case .identifier: return identifier case .element: return element case .part: return part @@ -128,6 +133,7 @@ struct RenditionKey: Hashable, Sendable { w.writeLE(idiom) w.writeLE(subtype) w.writeLE(dimension2) + w.writeLE(displayGamut) w.writeLE(identifier) w.writeLE(element) w.writeLE(part) @@ -135,7 +141,7 @@ struct RenditionKey: Hashable, Sendable { } static func decode(_ data: Data) -> RenditionKey? { - guard data.count == 18 else { return nil } + guard data.count == 20 else { return nil } func u16(_ offset: Int) -> UInt16 { let lo = UInt16(data[data.index(data.startIndex, offsetBy: offset)]) let hi = UInt16(data[data.index(data.startIndex, offsetBy: offset + 1)]) @@ -148,9 +154,10 @@ struct RenditionKey: Hashable, Sendable { idiom: u16(6), subtype: u16(8), dimension2: u16(10), - identifier: u16(12), - element: u16(14), - part: u16(16) + displayGamut: u16(12), + identifier: u16(14), + element: u16(16), + part: u16(18) ) } } diff --git a/Sources/AssetKit/Rendition/ColorRenderer.swift b/Sources/AssetKit/Rendition/ColorRenderer.swift index 05452b1..4cefc28 100644 --- a/Sources/AssetKit/Rendition/ColorRenderer.swift +++ b/Sources/AssetKit/Rendition/ColorRenderer.swift @@ -5,20 +5,13 @@ enum ColorRenderer { var out: [Rendition] = [] for entry in set.contents.colors { let body = ColorBody(components: try entry.color.values(), colorSpaceID: try entry.color.colorSpaceID()) - let gamut: Gamut = { - if let declared = entry.displayGamut { return declared } - switch entry.color.colorSpace { - case "display-p3": return .displayP3 - default: return .sRGB - } - }() let appearance = Appearance.keyValue(entry.appearances) out.append(Rendition( name: set.name, idiom: entry.idiom, scale: nil, appearance: appearance, - gamut: gamut, + gamut: entry.displayGamut, body: .color(body) )) } diff --git a/Tests/AssetKitTests/RenditionKeyTests.swift b/Tests/AssetKitTests/RenditionKeyTests.swift index e167048..12a733c 100644 --- a/Tests/AssetKitTests/RenditionKeyTests.swift +++ b/Tests/AssetKitTests/RenditionKeyTests.swift @@ -3,7 +3,7 @@ import Testing @testable import AssetKit /// `risk-key-packing`: rendition key encode/decode round-trip across the -/// KEYFORMAT attribute space CoreUI 970 expects. The 9-token, 18-byte key +/// KEYFORMAT attribute space CoreUI 970 expects. The 10-token, 20-byte key /// matches actool's output verbatim — see `KeyFormat.swift`. @Suite("RenditionKey round-trip") struct RenditionKeyTests { @@ -31,7 +31,7 @@ struct RenditionKeyTests { part: 220 ) let data = key.encode() - #expect(data.count == 18) + #expect(data.count == 20) let decoded = RenditionKey.decode(data) #expect(decoded == key) } @@ -50,15 +50,16 @@ struct RenditionKeyTests { idiom: 0x0807, subtype: 0x0a09, dimension2: 0x0c0b, - identifier: 0x0e0d, - element: 0x100f, - part: 0x1211 + displayGamut: 0x0e0d, + identifier: 0x100f, + element: 0x1211, + part: 0x1413 ) let bytes = [UInt8](key.encode()) #expect(bytes == [ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, - 0x11, 0x12, + 0x11, 0x12, 0x13, 0x14, ]) } @@ -128,6 +129,24 @@ struct RenditionKeyTests { #expect(key.dimension2 == 0) } + @Test("Only a declared display-P3 gamut sets the displayGamut attribute") + func displayGamutKey() throws { + let json = """ + { + "info": { "version": 1, "author": "xcode" }, + "colors": [ + { "idiom": "universal", "color": { "color-space": "display-p3", "components": { "red": "1.0", "green": "0.0", "blue": "0.0", "alpha": "1.0" } } }, + { "idiom": "universal", "display-gamut": "sRGB", "color": { "color-space": "srgb", "components": { "red": "1.0", "green": "0.0", "blue": "0.0", "alpha": "1.0" } } }, + { "idiom": "universal", "display-gamut": "display-P3", "color": { "color-space": "display-p3", "components": { "red": "0.0", "green": "1.0", "blue": "0.0", "alpha": "1.0" } } } + ] + } + """ + let contents = try JSONDecoder().decode(ColorSetContents.self, from: Data(json.utf8)) + let set = LoadedColorSet(name: "Gamut", directory: URL(fileURLWithPath: "/"), contents: contents) + let keys = try ColorRenderer.renditions(for: set).map(RenditionKey.init(rendition:)) + #expect(keys.map(\.displayGamut) == [0, 0, 1]) + } + @Test("nameHash is stable across calls for the same name") func nameHashStable() { // CoreUI only requires the identifier to match across our own FACETKEYS diff --git a/docs/coreui-970-format.md b/docs/coreui-970-format.md index 4094479..889e2fe 100644 --- a/docs/coreui-970-format.md +++ b/docs/coreui-970-format.md @@ -208,7 +208,7 @@ JPG renditions sit in the generic-image category at every layer above the CSI bo - **FACETKEYS**: `(element=85, part=181)` for all three source formats. The asset-level entry is opaque to source format; one FACETKEYS row per asset name regardless of whether the underlying renditions are PNG, JPG, or SVG. - **BITMAPKEYS** descriptors are computed from each asset's renditions the same way for all three source formats (see section 6 above). -- **RENDITIONS tree key** (per-rendition, 18-byte packed-attribute tuple): +- **RENDITIONS tree key** (per-rendition, 20-byte packed-attribute tuple): - PNG, JPG → `(element=85, part=181)`. - SVG vector → `(element=85, part=42, scale=1)`. The reference packs every SVG vector rendition into the `scale=1` slot of CoreUI's lookup tree regardless of any `@Nx` in the source filename; encoding `scale=0` here orphans the rendition from CoreUI's scale-keyed lookups even though `assetutil --info` still parses the file cleanly. - For all source formats, the `appearance` slot still carries dark-mode variants.