diff --git a/README.md b/README.md index ab64e24..1627583 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,22 @@ if let bundle = result.appIconBundle { } ``` +For a tvOS catalog, select the platform explicitly: + +```swift +let compiler = XCAssetCompiler(deploymentTarget: "17.0", platform: .tvOS) +let result = try await compiler.compile(catalog: catalogURL) +``` + +The default platform remains iOS. In a mixed catalog, iOS selects its +`.appiconset` and ignores TV-only Brand Assets; tvOS selects its `.brandassets` +and ignores the iOS app icon. Merge the returned `appIconBundle` metadata into +the app's Info.plist. tvOS names the small stack in `CFBundleIcons` and maps +the supplied Top Shelf roles into `TVTopShelfImage`. +tvOS compilation rejects distinct facet names that collide in the current +16-bit CoreUI identifier mapping, so a layer cannot alias another asset. +Branding elements must also have unique names across their roles and types. + ## What it supports - `.imageset` @@ -38,13 +54,26 @@ 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. +- tvOS `.brandassets` with a 400×240 primary icon and an optional 1280×768 + marketing icon, each containing two embedded PNG layers with default canvas + and frame geometry. Layer relationships and qualified names are retained in + CoreUI LayerStack renditions; flattened previews are emitted separately. + Top Shelf image roles and app icon metadata are returned in `appIconBundle`. + Sources must use sRGB, the `tv` idiom, and distinct 1x/2x scales (marketing + icons use 1x only), with an opaque background layer. ## What it deliberately doesn't support - `.pdf` vector sources (the CoreUI 970 DWAR envelope path is SVG-flavoured; adding PDF would need a separate `pixelFormat`) - Multi-rendition fanout — actool emits multiple compression variants per asset (`deepmap-lzfse`, `deepmap2`, `palette-img`); this writer emits one rendition per `(idiom, scale, appearance)` tuple per source format. Sufficient for iOS 16+. - Data sets, sticker sets, AR reference objects -- macOS / tvOS / watchOS asset variants beyond what the structural attribute IDs encode +- Standalone `.imagestack` assets, custom tvOS layer geometry, referenced layers, additional layers, and dark or + display-P3 Brand Assets. Unsupported forms are rejected, rather than flattened + or emitted with incomplete layer relationships. +- Apple's undocumented blurred radiosity renditions for tvOS focus effects. + The current output's icon-loading and focus behavior still needs native tvOS + runtime validation; structural CAR compatibility does not prove that behavior. +- macOS / watchOS asset variants beyond what the structural attribute IDs encode These can be added; the format mechanisms in `Sources/AssetKit/CAR/` are general enough. @@ -60,7 +89,11 @@ output is byte-deterministic across Linux and macOS. swift test ``` -The test suite includes a macOS-only gate (`AssetutilParseTests`) that compiles a fixture catalog and verifies Apple's own `xcrun assetutil --info` parses the bytes and reports the expected rendition fields. This is the durable verification for CoreUI format compatibility and gates merges via CI. +The test suite includes macOS-only gates that compile iOS and tvOS fixture +catalogs and verify Apple's own `xcrun assetutil --info` parses the bytes and +reports the expected rendition fields. These checks run in CI. Linux tests +cover layer ordering and references, mixed-catalog platform selection, the +observed LayerStack record layout, compositing, and unsupported geometry. ## License diff --git a/Sources/AssetKit/CAR/BitmapKeys.swift b/Sources/AssetKit/CAR/BitmapKeys.swift index d3e31b4..7421e7e 100644 --- a/Sources/AssetKit/CAR/BitmapKeys.swift +++ b/Sources/AssetKit/CAR/BitmapKeys.swift @@ -15,14 +15,15 @@ import Foundation /// 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. + /// The 52-byte descriptor. The tvOS reference identifies slots 6 and 7 + /// as masks of the emitted scale and idiom key values. Existing iOS + /// templates are retained separately to preserve their output. struct Descriptor { var kind: Kind - /// Number of distinct (idiom, subtype) tuples this asset is keyed on. + /// The original iOS template's (idiom, subtype) tuple count. var idiomSubtypeCount: UInt32 + var scaleMask: UInt32 = 0 + var idiomMask: UInt32 = 0 enum Kind { case appIcon @@ -32,19 +33,16 @@ enum BitmapKeys { 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 { + /// Preserve the original iOS template values in this tvOS change. + /// The tvOS path derives its scale mask from actual rendition keys. + private var legacyScaleMask: UInt32 { switch kind { case .image: return 0x04 case .vector, .appIcon: return 0x0e } } - func encode() -> Data { + func encode(platform: XCAssetCompiler.Platform = .iOS) -> Data { var w = ByteWriter() w.writeLE(UInt32(1)) w.writeLE(UInt32(0)) @@ -52,22 +50,24 @@ enum BitmapKeys { w.writeLE(UInt32(9)) w.writeLE(UInt32(0xFFFFFFFF)) w.writeLE(UInt32(1)) - w.writeLE(assetKindMarker) - // Variable section. Values come from the actool reference. + w.writeLE(platform == .tvOS ? scaleMask : legacyScaleMask) + // The remaining original iOS template fields vary by kind. // 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: + // tvOS uses the observed common (1, 0, 1) suffix and actual + // idiom mask; iOS retains its existing template byte-for-byte. + w.writeLE(platform == .tvOS ? idiomMask : idiomSubtypeCount) + switch (platform, kind) { + case (.tvOS, _): + w.writeLE(UInt16(1)) + w.writeLE(UInt16(0)) + w.writeLE(UInt32(1)) + case (.iOS, .appIcon): w.writeLE(UInt16(1)) // (u16, u16) tuple w.writeLE(UInt16(1)) w.writeLE(UInt32(7)) - case .image, .vector: + case (.iOS, .image), (.iOS, .vector): w.writeLE(UInt16(1)) w.writeLE(UInt16(0)) w.writeLE(UInt32(1)) @@ -82,11 +82,13 @@ enum BitmapKeys { } /// 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)], platform: XCAssetCompiler.Platform = .iOS + ) -> [BOMTree.InlineKeyEntry] { return assets.map { asset in BOMTree.InlineKeyEntry( key: FacetKeys.nameHash(asset.name) & 0xFFFF, - value: asset.descriptor.encode() + value: asset.descriptor.encode(platform: platform) ) } } @@ -100,7 +102,7 @@ enum BitmapKeys { static func descriptor(forAsset name: String, renditions: [Rendition]) -> Descriptor? { let hasBitmapOrPreservedSource = renditions.contains { rendition in switch rendition.body { - case .bitmap, .preservedSource: return true + case .bitmap, .preservedSource, .layerStack: return true case .color: return false } } @@ -118,7 +120,15 @@ enum BitmapKeys { return (idiom << 16) | subtype }) - return Descriptor(kind: kind, idiomSubtypeCount: UInt32(idiomSubtypes.count)) + let keys = renditions.map(RenditionKey.init) + let scaleMask = keys.reduce(UInt32(0)) { $0 | (UInt32(1) << UInt32($1.scale)) } + let idiomMask = keys.reduce(UInt32(0)) { $0 | (UInt32(1) << UInt32($1.idiom)) } + return Descriptor( + kind: kind, + idiomSubtypeCount: UInt32(idiomSubtypes.count), + scaleMask: scaleMask, + idiomMask: idiomMask + ) } /// AppIcon takes precedence over Vector takes precedence over Image: diff --git a/Sources/AssetKit/CAR/CARLayout.swift b/Sources/AssetKit/CAR/CARLayout.swift index 91a19b5..cbe6841 100644 --- a/Sources/AssetKit/CAR/CARLayout.swift +++ b/Sources/AssetKit/CAR/CARLayout.swift @@ -50,7 +50,7 @@ struct CARLayout { case .bitmap(let body): switch body.kind { case .appIcon: return .appIcon - case .image: return .image + case .image, .layerStackPreview: return .image } case .color: return .color // Preserved-source renditions live in the `.image` category at every @@ -58,6 +58,7 @@ struct CARLayout { // key all reuse the same element/part as a generic PNG imageset. // The source format only shows up in the CSI header's pixelFormat. case .preservedSource: return .image + case .layerStack: return .image } } } diff --git a/Sources/AssetKit/CAR/CARWriter.swift b/Sources/AssetKit/CAR/CARWriter.swift index 4288e0e..836de0e 100644 --- a/Sources/AssetKit/CAR/CARWriter.swift +++ b/Sources/AssetKit/CAR/CARWriter.swift @@ -11,6 +11,7 @@ import Foundation struct CARWriter: Sendable { var deploymentTarget: String var renditions: [Rendition] + var platform: XCAssetCompiler.Platform = .iOS func write() throws -> Data { let layout = CARLayout(renditions: renditions) @@ -48,10 +49,13 @@ struct CARWriter: Sendable { ) bom.setVariable("APPEARANCEKEYS", blockID: appearanceTreeID) - let kfmtBlockID = bom.addBlock(KeyFormatBlock.data()) + let keyFormat = platform == .tvOS ? tvKeyFormat : v1KeyFormat + let kfmtBlockID = bom.addBlock(KeyFormatBlock.data(attributes: keyFormat)) bom.setVariable("KEYFORMAT", blockID: kfmtBlockID) - let extendedMetadataBlockID = bom.addBlock(ExtendedMetadata.data(deploymentTarget: deploymentTarget)) + let extendedMetadataBlockID = bom.addBlock(ExtendedMetadata.data( + deploymentTarget: deploymentTarget, platform: platform.rawValue + )) bom.setVariable("EXTENDED_METADATA", blockID: extendedMetadataBlockID) let bitmapAssets: [(name: String, descriptor: BitmapKeys.Descriptor)] = @@ -65,7 +69,7 @@ struct CARWriter: Sendable { if !bitmapAssets.isEmpty { let bitmapKeysTreeID = BOMTree.insertInlineKey( into: &bom, - entries: BitmapKeys.entries(for: bitmapAssets), + entries: BitmapKeys.entries(for: bitmapAssets, platform: platform), blockSize: 1024 ) bom.setVariable("BITMAPKEYS", blockID: bitmapKeysTreeID) @@ -81,6 +85,8 @@ struct CARWriter: Sendable { return CSIWriter.bitmap(name: rendition.name, body: body, scaleFactor: scaleFactor) case .color(let body): return CSIWriter.color(name: rendition.name, body: body) + case .layerStack(let body): + return CSIWriter.layerStack(body: body) case .preservedSource(let body): // SVG renditions are scale-free; the reference leaves // scaleFactor=0 for them. JPGs respect the @Nx suffix the same diff --git a/Sources/AssetKit/CAR/CSIHeader.swift b/Sources/AssetKit/CAR/CSIHeader.swift index ad38c74..121891d 100644 --- a/Sources/AssetKit/CAR/CSIHeader.swift +++ b/Sources/AssetKit/CAR/CSIHeader.swift @@ -27,6 +27,8 @@ enum CSIHeader { /// renderer on the DWAR-wrapped body. static let pixelFormatSVG: UInt32 = 0x53564720 + static let pixelFormatData: UInt32 = 0x44415441 + /// Layout types observed in the reference. The names are derived from /// CoreUI symbol names where known. enum Layout: UInt16 { @@ -40,6 +42,8 @@ enum CSIHeader { /// category; SVG promotes to its own layout because vector /// renditions surface a different AssetType to `assetutil`. case vector = 9 + case layerStack = 1002 + case layerStackPreview = 0 } // swiftlint:disable:next function_parameter_count diff --git a/Sources/AssetKit/CAR/CSIWriter.swift b/Sources/AssetKit/CAR/CSIWriter.swift index 2bdeace..636fee3 100644 --- a/Sources/AssetKit/CAR/CSIWriter.swift +++ b/Sources/AssetKit/CAR/CSIWriter.swift @@ -9,7 +9,10 @@ import Foundation /// COLR block for color). enum CSIWriter { static func bitmap(name: String, body: BitmapBody, scaleFactor: UInt32) -> Data { - let tvl = CSITVL.encode([ + let preview = body.kind == .layerStackPreview + let tvl = CSITVL.encode(preview ? [ + .bitmapDescriptor(width: 0, height: 0), .sliceScale, .bitmapFlag, .bytesPerRow(width: body.width), + ] : [ .bitmapDescriptor(width: body.width, height: body.height), .destRect(width: body.width, height: body.height), .sliceScale, @@ -42,7 +45,7 @@ enum CSIWriter { scaleFactor: scaleFactor, pixelFormat: CSIHeader.pixelFormatARGB, colorSpace: UInt32(body.colorSpaceID), - layout: .bitmapIcon, + layout: preview ? .layerStackPreview : .bitmapIcon, name: body.renditionName, tvlLength: UInt32(tvl.count), bitmapCount: 1, diff --git a/Sources/AssetKit/CAR/KeyFormat.swift b/Sources/AssetKit/CAR/KeyFormat.swift index 292ce33..4a87812 100644 --- a/Sources/AssetKit/CAR/KeyFormat.swift +++ b/Sources/AssetKit/CAR/KeyFormat.swift @@ -9,6 +9,7 @@ enum AttributeID: UInt32 { case element = 1 case part = 2 case appearance = 7 + case dimension1 = 8 case dimension2 = 9 case scale = 12 case localization = 13 @@ -33,6 +34,18 @@ let v1KeyFormat: [AttributeID] = [ .part, ] +let tvKeyFormat: [AttributeID] = [ + .appearance, + .localization, + .scale, + .idiom, + .subtype, + .dimension1, + .identifier, + .element, + .part, +] + /// `kfmt` block payload. enum KeyFormatBlock { static let magic: UInt32 = 0x6B666D74 // 'kfmt' as LE multi-char constant diff --git a/Sources/AssetKit/CAR/LayerStackCSI.swift b/Sources/AssetKit/CAR/LayerStackCSI.swift new file mode 100644 index 0000000..811859b --- /dev/null +++ b/Sources/AssetKit/CAR/LayerStackCSI.swift @@ -0,0 +1,77 @@ +import Foundation + +extension CSIWriter { + static func layerStack(body: LayerStackBody) -> Data { + var metadata = ByteWriter() + writeLayerReferences(body, into: &metadata) + + // Stock two-layer metadata observed in actool's CoreUI 969 output. + // Its remaining fields are not generalised to custom frame geometry. + var flags = ByteWriter() + flags.writeLE(UInt32(2)) + flags.writeZeros(12) + flags.write(byte: 1) + flags.writeZeros(12) + flags.write(byte: 1) + flags.writeZeros(4) + writeTLV(1020, flags.data, into: &metadata) + + var layout = ByteWriter() + layout.writeLE(UInt32(2)) + layout.writeZeros(44) + writeTLV(1021, layout.data, into: &metadata) + metadata.write(CSITVL.encode([.sliceScale])) + + let uti = Array("public.layeredimage".utf8) + [0] + var type = ByteWriter() + type.writeLE(UInt32(uti.count)) + type.writeLE(UInt32(0)) + type.write(uti) + writeTLV(1005, type.data, into: &metadata) + metadata.write(CSITVL.encode([.bitmapFlag])) + + let payload = DWAREnvelope.encode(flags: 0, payload: []) + let header = CSIHeader.encode( + renditionFlags: 0, + width: body.width, + height: body.height, + scaleFactor: 100, + pixelFormat: CSIHeader.pixelFormatData, + colorSpace: 0, + layout: .layerStack, + name: "Contents.json", + tvlLength: UInt32(metadata.offset), + bitmapCount: 1, + renditionLength: UInt32(payload.count) + ) + return header + metadata.data + payload + } + + private static func writeLayerReferences(_ body: LayerStackBody, into metadata: inout ByteWriter) { + var references = ByteWriter() + references.writeLE(UInt32(2)) + for name in [body.backgroundName, body.foregroundName] { + references.writeZeros(16) + references.writeLE(body.width) + references.writeLE(body.height) + references.writeLE(UInt32(0)) + references.writeLE(Float(1).bitPattern) + // The length includes this word and the three attribute pairs. + references.writeLE(UInt32(16)) + references.writeLE(UInt16(AttributeID.element.rawValue)) + references.writeLE(RenditionKey.Element.bitmap.rawValue) + references.writeLE(UInt16(AttributeID.part.rawValue)) + references.writeLE(RenditionKey.Part.image.rawValue) + references.writeLE(UInt16(AttributeID.identifier.rawValue)) + references.writeLE(UInt16(FacetKeys.nameHash(name) & 0xFFFF)) + } + references.writeLE(UInt32(0)) + writeTLV(1012, references.data, into: &metadata) + } + + private static func writeTLV(_ tag: UInt32, _ value: Data, into writer: inout ByteWriter) { + writer.writeLE(tag) + writer.writeLE(UInt32(value.count)) + writer.write(value) + } +} diff --git a/Sources/AssetKit/CAR/RenditionKey.swift b/Sources/AssetKit/CAR/RenditionKey.swift index 01dfb76..b1eb7ae 100644 --- a/Sources/AssetKit/CAR/RenditionKey.swift +++ b/Sources/AssetKit/CAR/RenditionKey.swift @@ -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 layerStackPreview = 208 } init(rendition: Rendition) { @@ -59,6 +60,9 @@ struct RenditionKey: Hashable, Sendable { self.part = Part.image.rawValue // Generic image assets don't use Dimension2 at all. self.dimension2 = 0 + case .layerStackPreview: + self.part = Part.layerStackPreview.rawValue + self.dimension2 = 0 } case .color: self.element = 0 @@ -79,6 +83,10 @@ struct RenditionKey: Hashable, Sendable { // resulting bitmap from UIImage(named:). self.part = Part.image.rawValue } + case .layerStack: + self.element = Element.bitmap.rawValue + self.part = Part.image.rawValue + self.dimension2 = 0 } } diff --git a/Sources/AssetKit/Catalog/CatalogLoader.swift b/Sources/AssetKit/Catalog/CatalogLoader.swift index 55b7484..51811c8 100644 --- a/Sources/AssetKit/Catalog/CatalogLoader.swift +++ b/Sources/AssetKit/Catalog/CatalogLoader.swift @@ -5,6 +5,8 @@ struct LoadedCatalog: Sendable { var imageSets: [LoadedImageSet] var colorSets: [LoadedColorSet] var appIcon: LoadedAppIcon? + var brandAssets: [LoadedBrandAssets] = [] + var imageStacks: [LoadedImageStack] = [] } struct LoadedImageSet: Sendable { @@ -25,10 +27,44 @@ struct LoadedAppIcon: Sendable { var contents: AppIconContents } +struct LoadedBrandAssets: Sendable { + struct Element: Sendable { + enum Content: Sendable { + case imageStack(LoadedImageStack) + case imageSet(LoadedImageSet) + } + + var definition: BrandAssetsContents.Asset + var content: Content + } + + var name: String + var directory: URL + var elements: [Element] +} + +struct LoadedImageStack: Sendable { + var name: String + var directory: URL + var contents: ImageStackContents + var layers: [LoadedImageStackLayer] +} + +struct LoadedImageStackLayer: Sendable { + enum Content: Sendable { + case imageSet(LoadedImageSet) + case reference(String) + } + + var name: String + var properties: ImageStackLayerContents.Properties? + var content: Content +} + struct CatalogLoader: Sendable { init() {} - func load(catalog url: URL) async throws -> LoadedCatalog { + func load(catalog url: URL, platform: XCAssetCompiler.Platform = .iOS) async throws -> LoadedCatalog { let fm = FileManager.default var isDir: ObjCBool = false guard fm.fileExists(atPath: url.path, isDirectory: &isDir), isDir.boolValue else { @@ -40,6 +76,8 @@ struct CatalogLoader: Sendable { var imageSets: [LoadedImageSet] = [] var colorSets: [LoadedColorSet] = [] var appIcons: [LoadedAppIcon] = [] + var brandAssets: [LoadedBrandAssets] = [] + var imageStacks: [LoadedImageStack] = [] try walk(url, fileManager: fm) { entry in let ext = entry.pathExtension @@ -52,8 +90,14 @@ 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 platform == .iOS else { return } let contents = try decode(AppIconContents.self, at: entry, decoder: decoder) appIcons.append(LoadedAppIcon(name: name, directory: entry, contents: contents)) + case "brandassets": + guard platform == .tvOS else { return } + brandAssets.append(try loadBrandAssets(at: entry, decoder: decoder)) + case "imagestack": + imageStacks.append(try loadImageStack(at: entry, decoder: decoder)) default: if !ext.isEmpty { throw XCAssetCompilerError.unsupportedAssetType("\(name).\(ext)") @@ -69,10 +113,115 @@ struct CatalogLoader: Sendable { url: url, imageSets: imageSets, colorSets: colorSets, - appIcon: appIcons.first + appIcon: appIcons.first, + brandAssets: brandAssets, + imageStacks: imageStacks ) } + private func loadBrandAssets(at directory: URL, decoder: JSONDecoder) throws -> LoadedBrandAssets { + let name = directory.deletingPathExtension().lastPathComponent + let contents = try decode(BrandAssetsContents.self, at: directory, decoder: decoder) + let elements = try contents.assets.map { asset -> LoadedBrandAssets.Element in + guard asset.idiom == .tv else { + throw XCAssetCompilerError.invalidBrandAsset(asset: name, reason: "The idiom must be tv") + } + let assetURL = try referencedDirectory(asset.filename, within: directory, asset: name) + switch asset.role { + case .primaryAppIcon: + guard assetURL.pathExtension == "imagestack" else { + throw XCAssetCompilerError.invalidBrandAsset( + asset: name, reason: "A primary app icon must reference an .imagestack" + ) + } + return LoadedBrandAssets.Element( + definition: asset, + content: .imageStack(try loadImageStack(at: assetURL, decoder: decoder)) + ) + case .topShelfImage, .topShelfImageWide: + guard assetURL.pathExtension == "imageset" else { + throw XCAssetCompilerError.invalidBrandAsset( + asset: name, reason: "A Top Shelf image must reference an .imageset" + ) + } + let imageSet = LoadedImageSet( + name: assetURL.deletingPathExtension().lastPathComponent, + directory: assetURL, + contents: try decode(ImageSetContents.self, at: assetURL, decoder: decoder) + ) + return LoadedBrandAssets.Element(definition: asset, content: .imageSet(imageSet)) + } + } + return LoadedBrandAssets(name: name, directory: directory, elements: elements) + } + + private func loadImageStack(at directory: URL, decoder: JSONDecoder) throws -> LoadedImageStack { + let name = directory.deletingPathExtension().lastPathComponent + let contents = try decode(ImageStackContents.self, at: directory, decoder: decoder) + guard !contents.layers.isEmpty else { + throw XCAssetCompilerError.invalidImageStack(asset: name, reason: "The stack has no layers") + } + let layers = try contents.layers.map { layer -> LoadedImageStackLayer in + let layerURL = try referencedDirectory(layer.filename, within: directory, asset: name) + guard layerURL.pathExtension == "imagestacklayer" else { + throw XCAssetCompilerError.invalidImageStack( + asset: name, reason: "A layer must reference an .imagestacklayer" + ) + } + let layerName = layerURL.deletingPathExtension().lastPathComponent + let metadataURL = layerURL.appendingPathComponent("Contents.json") + let metadata: ImageStackLayerContents + if FileManager.default.fileExists(atPath: metadataURL.path) { + metadata = try decode(ImageStackLayerContents.self, at: layerURL, decoder: decoder) + } else { + metadata = ImageStackLayerContents(info: nil, properties: nil) + } + let images = try FileManager.default.contentsOfDirectory( + at: layerURL, includingPropertiesForKeys: [.isDirectoryKey] + ).filter { url in + guard url.pathExtension == "imageset" else { return false } + return try url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true + } + if let reference = metadata.properties?.contentReference { + guard images.isEmpty, + reference.type == "image-set", + reference.matchingStyle == "fully-qualified-name", + !reference.name.isEmpty else { + throw XCAssetCompilerError.invalidImageStack( + asset: name, reason: "Layer '\(layerName)' has an invalid image-set reference" + ) + } + return LoadedImageStackLayer( + name: layerName, properties: metadata.properties, content: .reference(reference.name) + ) + } + guard images.count == 1, let imageURL = images.first else { + throw XCAssetCompilerError.invalidImageStack( + asset: name, reason: "Layer '\(layerName)' must contain exactly one .imageset" + ) + } + let imageSet = LoadedImageSet( + name: imageURL.deletingPathExtension().lastPathComponent, + directory: imageURL, + contents: try decode(ImageSetContents.self, at: imageURL, decoder: decoder) + ) + return LoadedImageStackLayer(name: layerName, properties: metadata.properties, content: .imageSet(imageSet)) + } + return LoadedImageStack(name: name, directory: directory, contents: contents, layers: layers) + } + + private func referencedDirectory(_ filename: String, within directory: URL, asset: String) throws -> URL { + let child = directory.appendingPathComponent(filename, isDirectory: true) + guard !filename.isEmpty, + filename != ".", filename != "..", + !filename.contains("/"), + !filename.contains("\\"), + (try? child.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true else { + throw XCAssetCompilerError.missingReferencedFile(asset: asset, filename: filename) + } + return child + } + private func decode(_ type: T.Type, at directory: URL, decoder: JSONDecoder) throws -> T { let contentsURL = directory.appendingPathComponent("Contents.json") guard FileManager.default.fileExists(atPath: contentsURL.path) else { @@ -97,7 +246,7 @@ struct CatalogLoader: Sendable { let values = try child.resourceValues(forKeys: [.isDirectoryKey]) guard values.isDirectory == true else { continue } let ext = child.pathExtension - if ["imageset", "colorset", "appiconset"].contains(ext) { + if ["imageset", "colorset", "appiconset", "brandassets", "imagestack"].contains(ext) { try visit(child) } else { try walk(child, fileManager: fm, visit: visit) diff --git a/Sources/AssetKit/Errors.swift b/Sources/AssetKit/Errors.swift index ebeedb7..dd2feed 100644 --- a/Sources/AssetKit/Errors.swift +++ b/Sources/AssetKit/Errors.swift @@ -13,6 +13,10 @@ public enum XCAssetCompilerError: Error, Sendable, Equatable { case unsupportedAssetType(String) case malformedJPEG(reason: String) case unsupportedAppIconSource(asset: String, filename: String) + case invalidBrandAsset(asset: String, reason: String) + case invalidImageStack(asset: String, reason: String) + case multipleBrandAssetSets([String]) + case assetIdentifierCollision(first: String, second: String, identifier: UInt16) case svgDimensionsMissing(asset: String, filename: String) case svgRasterizationFailed(asset: String, filename: String, underlying: String) } @@ -44,6 +48,14 @@ extension XCAssetCompilerError: CustomStringConvertible { return "Malformed JPEG: \(reason)" case .unsupportedAppIconSource(let asset, let filename): return "AppIcon '\(asset)' source file '\(filename)' is not a PNG; only .png is supported for app icons" + case .invalidBrandAsset(let asset, let reason): + return "Invalid Brand Assets '\(asset)': \(reason)" + case .invalidImageStack(let asset, let reason): + return "Invalid Image Stack '\(asset)': \(reason)" + case .multipleBrandAssetSets(let names): + return "Catalog has more than one .brandassets: \(names.joined(separator: ", "))" + case .assetIdentifierCollision(let first, let second, let identifier): + return "Asset names '\(first)' and '\(second)' map to the same CoreUI identifier \(identifier)" case .svgDimensionsMissing(let asset, let filename): return "SVG asset '\(asset)' file '\(filename)' has no usable width/height or viewBox; cannot determine intrinsic size" case .svgRasterizationFailed(let asset, let filename, let underlying): diff --git a/Sources/AssetKit/Rendition/BrandAssetsRenderer.swift b/Sources/AssetKit/Rendition/BrandAssetsRenderer.swift new file mode 100644 index 0000000..382b1a6 --- /dev/null +++ b/Sources/AssetKit/Rendition/BrandAssetsRenderer.swift @@ -0,0 +1,229 @@ +import Foundation + +enum BrandAssetsRenderer { + struct Output { + var renditions: [Rendition] + var appIconBundle: AppIconBundle + } + + static func render(_ brand: LoadedBrandAssets, svgRasterizer: any SVGRasterizer) throws -> Output { + var sourceNames: Set = [] + for element in brand.elements { + let name: String + switch element.content { + case .imageStack(let stack): name = stack.name + case .imageSet(let imageSet): name = imageSet.name + } + guard sourceNames.insert(name).inserted else { + throw XCAssetCompilerError.invalidBrandAsset( + asset: brand.name, reason: "Multiple branding assets use the name '\(name)'" + ) + } + } + let icons = brand.elements.filter { $0.definition.role == .primaryAppIcon } + guard let primary = icons.first(where: { $0.definition.size == "400x240" }) else { + throw XCAssetCompilerError.invalidBrandAsset( + asset: brand.name, reason: "A 400x240 primary app icon is required" + ) + } + guard case .imageStack(let primaryStack) = primary.content else { + throw XCAssetCompilerError.invalidBrandAsset(asset: brand.name, reason: "The primary icon is not a stack") + } + let iconSizes = icons.map(\.definition.size) + guard Set(iconSizes).count == iconSizes.count, + iconSizes.allSatisfy({ ["400x240", "1280x768"].contains($0) }) else { + throw XCAssetCompilerError.invalidBrandAsset( + asset: brand.name, reason: "Primary app icons support one 400x240 stack and one 1280x768 stack" + ) + } + + var renditions: [Rendition] = [] + var topShelf: [String: String] = [:] + for element in brand.elements { + let size = try dimensions(element.definition.size, asset: brand.name) + switch element.content { + case .imageStack(let stack): + let marketing = element.definition.size == "1280x768" + renditions.append(contentsOf: try renderStack( + stack, + primaryName: primaryStack.name, + width: size.width, + height: size.height, + marketing: marketing, + svgRasterizer: svgRasterizer + )) + case .imageSet(let imageSet): + let key = element.definition.role == .topShelfImage + ? "TVTopShelfPrimaryImage" : "TVTopShelfPrimaryImageWide" + guard topShelf[key] == nil else { + throw XCAssetCompilerError.invalidBrandAsset(asset: brand.name, reason: "Duplicate Top Shelf role") + } + let images = try renderImages(imageSet, svgRasterizer: svgRasterizer) + try validateDimensions(images, width: size.width, height: size.height, asset: imageSet.name) + renditions.append(contentsOf: images) + topShelf[key] = imageSet.name + } + } + + var plist: [String: any Sendable] = [ + "CFBundleIcons": ["CFBundlePrimaryIcon": primaryStack.name], + ] + if !topShelf.isEmpty { + plist["TVTopShelfImage"] = topShelf + } + return Output( + renditions: renditions, + appIconBundle: AppIconBundle( + primaryIconName: primaryStack.name, + infoPlistAdditions: plist, + looseFiles: [] + ) + ) + } + + private static func renderStack( + _ stack: LoadedImageStack, + primaryName: String, + width: UInt32, + height: UInt32, + marketing: Bool, + svgRasterizer: any SVGRasterizer + ) throws -> [Rendition] { + guard stack.layers.count == 2, stack.contents.properties?.canvasSize == nil else { + throw XCAssetCompilerError.invalidImageStack( + asset: stack.name, reason: "Only two embedded PNG layers with default canvas geometry are supported" + ) + } + var layers: [[Rendition]] = [] + for layer in stack.layers { + guard layer.properties?.frameSize == nil, + layer.properties?.frameCenter == nil, + case .imageSet(var imageSet) = layer.content else { + throw XCAssetCompilerError.invalidImageStack( + asset: stack.name, reason: "Layer '\(layer.name)' must use embedded content and default frame geometry" + ) + } + imageSet.name = "\(stack.name)/\(layer.name)/\(imageSet.name)" + var images = try renderImages(imageSet, svgRasterizer: svgRasterizer) + try validateDimensions(images, width: width, height: height, asset: imageSet.name) + for index in images.indices { + if marketing && images[index].scale != .x1 { + throw XCAssetCompilerError.invalidImageStack( + asset: stack.name, reason: "Marketing icon layers support only the 1x scale" + ) + } + images[index].idiom = marketing ? .marketing : .tv + } + layers.append(images) + } + + let foreground = layers[0] + let background = layers[1] + guard Set(foreground.compactMap(\.scale)) == Set(background.compactMap(\.scale)) else { + throw XCAssetCompilerError.invalidImageStack(asset: stack.name, reason: "The layer scales must match") + } + for rendition in background { + guard case .bitmap(let body) = rendition.body, + stride(from: 3, to: body.pixelsBGRA.count, by: 4).allSatisfy({ body.pixelsBGRA[$0] == 255 }) else { + throw XCAssetCompilerError.invalidImageStack(asset: stack.name, reason: "The background layer must be opaque") + } + } + let foregroundName = try requireLayerName(foreground, asset: stack.name) + let backgroundName = try requireLayerName(background, asset: stack.name) + let descriptor = Rendition( + name: primaryName, + idiom: marketing ? .marketing : .universal, + scale: .x1, + appearance: nil, + gamut: nil, + body: .layerStack(LayerStackBody( + width: width, height: height, + backgroundName: backgroundName, foregroundName: foregroundName + )) + ) + var previews: [Rendition] = [] + for front in foreground { + guard let back = background.first(where: { $0.scale == front.scale }), + case .bitmap(let frontPixels) = front.body, + case .bitmap(let backPixels) = back.body else { + throw XCAssetCompilerError.invalidImageStack(asset: stack.name, reason: "The layer variants do not match") + } + var pixels = frontPixels.pixelsBGRA + for offset in stride(from: 0, to: pixels.count, by: 4) { + let inverseAlpha = UInt16(255 - frontPixels.pixelsBGRA[offset + 3]) + for channel in 0..<3 { + let value = UInt16(frontPixels.pixelsBGRA[offset + channel]) + + (UInt16(backPixels.pixelsBGRA[offset + channel]) * inverseAlpha + 127) / 255 + pixels[offset + channel] = UInt8(value) + } + pixels[offset + 3] = 255 + } + let scale = front.scale ?? .x1 + previews.append(Rendition( + name: primaryName, + idiom: marketing ? .marketing : .tv, + scale: scale, + appearance: nil, + gamut: .sRGB, + body: .bitmap(BitmapBody( + width: frontPixels.width, height: frontPixels.height, + pixelsBGRA: pixels, + colorSpaceID: 1, + kind: .layerStackPreview, + renditionName: "ZZZZFlattenedImage-\(scale.factor).1.0-gamut0" + )) + )) + } + return foreground + background + [descriptor] + previews + } + + private static func renderImages(_ set: LoadedImageSet, svgRasterizer: any SVGRasterizer) throws -> [Rendition] { + let images = set.contents.images.filter { $0.filename != nil } + guard !images.isEmpty, + images.allSatisfy({ image in + image.idiom == .tv && + image.appearances?.isEmpty != false && + (image.displayGamut == nil || image.displayGamut == .sRGB) && + (image.scale == .x1 || image.scale == .x2) && + image.filename.map { SourceFormat.detect(filename: $0) == .png } == true + }), + images.contains(where: { $0.scale == .x1 }), + Set(images.compactMap(\.scale)).count == images.count else { + throw XCAssetCompilerError.invalidBrandAsset( + asset: set.name, reason: "Brand images require sRGB tv PNG sources at distinct 1x or 2x scales" + ) + } + return try ImageRenderer.renditions(for: set, svgRasterizer: svgRasterizer) + } + + private static func validateDimensions( + _ images: [Rendition], width: UInt32, height: UInt32, asset: String + ) throws { + for rendition in images { + let scale = UInt32(rendition.scale?.factor ?? 1) + guard case .bitmap(let body) = rendition.body, + UInt64(body.width) == UInt64(width) * UInt64(scale), + UInt64(body.height) == UInt64(height) * UInt64(scale) else { + throw XCAssetCompilerError.invalidBrandAsset( + asset: asset, reason: "The PNG dimensions do not match the declared size and scale" + ) + } + } + } + + private static func requireLayerName(_ renditions: [Rendition], asset: String) throws -> String { + guard let name = renditions.first?.name else { + throw XCAssetCompilerError.invalidImageStack(asset: asset, reason: "The layer has no image") + } + return name + } + + private static func dimensions(_ value: String, asset: String) throws -> (width: UInt32, height: UInt32) { + let parts = value.split(separator: "x", omittingEmptySubsequences: false) + guard parts.count == 2, + let width = UInt32(parts[0]), let height = UInt32(parts[1]), width > 0, height > 0 else { + throw XCAssetCompilerError.invalidBrandAsset(asset: asset, reason: "Invalid size '\(value)'") + } + return (width, height) + } +} diff --git a/Sources/AssetKit/Rendition/Rendition.swift b/Sources/AssetKit/Rendition/Rendition.swift index 2175002..44b93b5 100644 --- a/Sources/AssetKit/Rendition/Rendition.swift +++ b/Sources/AssetKit/Rendition/Rendition.swift @@ -5,6 +5,7 @@ struct Rendition: Sendable { case bitmap(BitmapBody) case color(ColorBody) case preservedSource(PreservedSourceBody) + case layerStack(LayerStackBody) } var name: String @@ -15,6 +16,13 @@ struct Rendition: Sendable { var body: Body } +struct LayerStackBody: Sendable { + var width: UInt32 + var height: UInt32 + var backgroundName: String + var foregroundName: String +} + struct BitmapBody: Sendable { /// Which CoreUI rendition category this bitmap belongs to. Determines the /// `(element, part)` pair we encode in the rendition key and FACETKEYS @@ -27,6 +35,7 @@ struct BitmapBody: Sendable { /// `element=85, part=181`. Used by UIImage(named:) for generic image /// assets from an `.imageset`. case image + case layerStackPreview } var width: UInt32 diff --git a/Sources/AssetKit/Schema/BrandAssets.swift b/Sources/AssetKit/Schema/BrandAssets.swift new file mode 100644 index 0000000..810f217 --- /dev/null +++ b/Sources/AssetKit/Schema/BrandAssets.swift @@ -0,0 +1,71 @@ +import Foundation + +struct BrandAssetsContents: Codable, Sendable { + struct Asset: Codable, Sendable { + enum Role: String, Codable, Sendable { + case primaryAppIcon = "primary-app-icon" + case topShelfImage = "top-shelf-image" + case topShelfImageWide = "top-shelf-image-wide" + } + + var filename: String + var idiom: Idiom + var role: Role + var size: String + } + + var assets: [Asset] + var info: CatalogContents.Info +} + +struct ImageStackContents: Codable, Sendable { + struct Layer: Codable, Sendable { + var filename: String + } + + struct Properties: Codable, Sendable { + var canvasSize: AssetSize? + } + + var layers: [Layer] + var info: CatalogContents.Info + var properties: Properties? +} + +struct ImageStackLayerContents: Codable, Sendable { + struct Properties: Codable, Sendable { + struct ContentReference: Codable, Sendable { + var type: String + var name: String + var matchingStyle: String + + enum CodingKeys: String, CodingKey { + case type, name + case matchingStyle = "matching-style" + } + } + + var contentReference: ContentReference? + var frameSize: AssetSize? + var frameCenter: AssetPoint? + + enum CodingKeys: String, CodingKey { + case contentReference = "content-reference" + case frameSize = "frame-size" + case frameCenter = "frame-center" + } + } + + var info: CatalogContents.Info? + var properties: Properties? +} + +struct AssetSize: Codable, Sendable, Equatable { + var width: Double + var height: Double +} + +struct AssetPoint: Codable, Sendable, Equatable { + var x: Double + var y: Double +} diff --git a/Sources/AssetKit/XCAssetCompiler.swift b/Sources/AssetKit/XCAssetCompiler.swift index 56beff6..2bf79e0 100644 --- a/Sources/AssetKit/XCAssetCompiler.swift +++ b/Sources/AssetKit/XCAssetCompiler.swift @@ -5,9 +5,9 @@ public struct CompileResult: Sendable { /// contained no assets (callers receive a structurally valid empty CAR). public var carData: Data - /// Glue needed to ship an `.appiconset` as part of an iOS app bundle. - /// `nil` if the catalog contained no `.appiconset`. Present iff the - /// catalog contained exactly one `.appiconset`. + /// Bundle metadata for the selected platform's app icon. iOS uses an + /// `.appiconset`; tvOS uses the primary stack in a `.brandassets` bundle. + /// `nil` when the catalog has no icon for the selected platform. public var appIconBundle: AppIconBundle? public init(carData: Data, appIconBundle: AppIconBundle? = nil) { @@ -16,18 +16,15 @@ public struct CompileResult: Sendable { } } -/// iOS-app-bundle glue derived from the catalog's `.appiconset`. The .car -/// alone is not enough to ship an iOS app icon: SpringBoard's icon-render -/// pipeline falls back to a set of loose PNGs in the bundle root, and the -/// `Info.plist` must declare them. +/// Platform-specific app icon and Top Shelf bundle metadata. iOS additionally +/// needs loose PNGs for SpringBoard's icon-render fallback path. public struct AppIconBundle: Sendable { - /// The basename of the `.appiconset` (e.g. "AppIcon"), used as the - /// `CFBundleIconName` value. + /// The selected icon asset name, such as an iOS `.appiconset` basename + /// or the small tvOS image stack's name. public var primaryIconName: String - /// Plist keys to merge into the app's `Info.plist`. Includes - /// `CFBundleIconName`, `CFBundleIcons`, `CFBundleIcons~ipad`, and the - /// flat `CFBundleIconFiles` fallback list. + /// Plist keys to merge into the app's `Info.plist`. iOS emits its icon + /// fallback keys; tvOS emits `CFBundleIcons` and `TVTopShelfImage` roles. public var infoPlistAdditions: [String: any Sendable] /// Loose PNG files that must be copied into the app bundle root @@ -35,7 +32,7 @@ public struct AppIconBundle: Sendable { /// `AppIcon60x60@2x.png`). SpringBoard's icon-rendering pipeline reads /// these directly when CoreUI's rendition lookup misses (which happens /// when our CRC32-derived NameIdentifier differs from actool's hash) -- - /// without these files, home-screen icons fail to render. + /// without these files, home-screen icons fail to render. Empty for tvOS. public var looseFiles: [LooseFile] public init( @@ -61,7 +58,13 @@ public struct LooseFile: Sendable { } public struct XCAssetCompiler: Sendable { + public enum Platform: String, Sendable { + case iOS = "ios" + case tvOS = "atv" + } + public var deploymentTarget: String + public var platform: Platform /// Strategy used to rasterise `.svg` sources to PNG bytes. Defaults to /// `RsvgConvertRasterizer`, which shells out to `rsvg-convert`. Replace /// when you need a different rasteriser (no PATH dep, different @@ -70,15 +73,21 @@ public struct XCAssetCompiler: Sendable { public init( deploymentTarget: String, + platform: Platform = .iOS, svgRasterizer: any SVGRasterizer = RsvgConvertRasterizer() ) { self.deploymentTarget = deploymentTarget + self.platform = platform self.svgRasterizer = svgRasterizer } public func compile(catalog catalogURL: URL) async throws -> CompileResult { let loader = CatalogLoader() - let loaded = try await loader.load(catalog: catalogURL) + let loaded = try await loader.load(catalog: catalogURL, platform: platform) + + if let stack = loaded.imageStacks.first { + throw XCAssetCompilerError.unsupportedAssetType("\(stack.name).imagestack") + } var renditions: [Rendition] = [] @@ -93,7 +102,7 @@ public struct XCAssetCompiler: Sendable { } var appIconBundle: AppIconBundle? - if let appIcon = loaded.appIcon { + if platform == .iOS, let appIcon = loaded.appIcon { let plist = try AppIconPlistEmitter.emit(appIcon) renditions.append(contentsOf: try ImageRenderer.appIconRenditions(for: appIcon, files: plist.iconFiles)) @@ -112,9 +121,32 @@ public struct XCAssetCompiler: Sendable { ) } - let writer = CARWriter(deploymentTarget: deploymentTarget, renditions: renditions) + if platform == .tvOS { + guard loaded.brandAssets.count <= 1 else { + throw XCAssetCompilerError.multipleBrandAssetSets(loaded.brandAssets.map(\.name)) + } + if let brand = loaded.brandAssets.first { + let output = try BrandAssetsRenderer.render(brand, svgRasterizer: svgRasterizer) + renditions.append(contentsOf: output.renditions) + appIconBundle = output.appIconBundle + } + try validateFacetIdentifiers(renditions) + } + + let writer = CARWriter(deploymentTarget: deploymentTarget, renditions: renditions, platform: platform) let bytes = try writer.write() return CompileResult(carData: bytes, appIconBundle: appIconBundle) } + + private func validateFacetIdentifiers(_ renditions: [Rendition]) throws { + var namesByIdentifier: [UInt16: String] = [:] + for name in Set(renditions.map(\.name)).sorted() { + let identifier = UInt16(FacetKeys.nameHash(name) & 0xFFFF) + if let other = namesByIdentifier[identifier] { + throw XCAssetCompilerError.assetIdentifierCollision(first: other, second: name, identifier: identifier) + } + namesByIdentifier[identifier] = name + } + } } diff --git a/Tests/AssetKitTests/AssetutilParseTests.swift b/Tests/AssetKitTests/AssetutilParseTests.swift index ec43691..9838faf 100644 --- a/Tests/AssetKitTests/AssetutilParseTests.swift +++ b/Tests/AssetKitTests/AssetutilParseTests.swift @@ -96,7 +96,7 @@ struct AssetutilParseTests { } } -private enum ProcessLauncher { +enum ProcessLauncher { struct Invocation { var exitCode: Int32 var stdout: Data diff --git a/Tests/AssetKitTests/BrandAssetsTests.swift b/Tests/AssetKitTests/BrandAssetsTests.swift new file mode 100644 index 0000000..3bc7977 --- /dev/null +++ b/Tests/AssetKitTests/BrandAssetsTests.swift @@ -0,0 +1,364 @@ +import Foundation +import Testing +import PNG +@testable import AssetKit + +@Suite("Brand Assets") +struct BrandAssetsTests { + @Test("Brand asset children are not flattened into ordinary imagesets") + func preservesBrandAssetHierarchy() async throws { + let fixture = try BrandFixture() + defer { fixture.remove() } + + let catalog = try await CatalogLoader().load(catalog: fixture.url, platform: .tvOS) + #expect(catalog.imageSets.isEmpty) + let brand = try #require(catalog.brandAssets.first) + #expect(brand.name == "TVAppIcon") + #expect(brand.elements.map(\.definition.role) == [.primaryAppIcon, .topShelfImage]) + guard case .imageStack(let stack) = brand.elements[0].content else { + Issue.record("The primary icon was not loaded as an image stack") + return + } + #expect(stack.layers.map(\.name) == ["Front", "Back"]) + } + + @Test("Layer properties preserve an image-set reference and frame geometry") + func referenceAndFrame() async throws { + let fixture = try BrandFixture() + defer { fixture.remove() } + let layer = "TVAppIcon.brandassets/App Icon.imagestack/Front.imagestacklayer" + try FileManager.default.removeItem(at: fixture.url.appendingPathComponent("\(layer)/Content.imageset")) + try fixture.write("\(layer)/Contents.json", """ + { + "properties": { + "content-reference": { + "type": "image-set", "name": "Shared/Front", "matching-style": "fully-qualified-name" + }, + "frame-size": { "width": 100, "height": 90 }, + "frame-center": { "x": 70, "y": 50 } + } + } + """) + let catalog = try await CatalogLoader().load(catalog: fixture.url, platform: .tvOS) + let brand = try #require(catalog.brandAssets.first) + guard case .imageStack(let stack) = brand.elements[0].content else { + Issue.record("The primary icon was not loaded as an image stack") + return + } + let front = try #require(stack.layers.first) + guard case .reference(let name) = front.content else { + Issue.record("The image-set reference was lost") + return + } + #expect(name == "Shared/Front") + #expect(front.properties?.frameSize == AssetSize(width: 100, height: 90)) + #expect(front.properties?.frameCenter == AssetPoint(x: 70, y: 50)) + } + + @Test("tvOS compilation preserves layers, emits its primary icon, and selects platform metadata") + func compilesTVBrandAssets() async throws { + let fixture = try BrandFixture(renderable: true) + defer { fixture.remove() } + let loaded = try await CatalogLoader().load(catalog: fixture.url, platform: .tvOS) + let output = try BrandAssetsRenderer.render(try #require(loaded.brandAssets.first), svgRasterizer: StubSVGRasterizer()) + let descriptor = try #require(output.renditions.first { if case .layerStack = $0.body { return true }; return false }) + guard case .layerStack(let stack) = descriptor.body else { return } + #expect(stack.backgroundName == "App Icon/Back/Content") + #expect(stack.foregroundName == "App Icon/Front/Content") + #expect(descriptor.idiom == .universal) + let preview = try #require(output.renditions.first { + if case .bitmap(let body) = $0.body { return body.kind == .layerStackPreview } + return false + }) + guard case .bitmap(let pixels) = preview.body else { return } + #expect(Array(pixels.pixelsBGRA.prefix(4)) == [127, 0, 128, 255]) + + let result = try await XCAssetCompiler(deploymentTarget: "17.0", platform: .tvOS).compile(catalog: fixture.url) + let bundle = try #require(result.appIconBundle) + #expect(bundle.primaryIconName == "App Icon") + #expect(bundle.looseFiles.isEmpty) + #expect((bundle.infoPlistAdditions["CFBundleIcons"] as? [String: String])?["CFBundlePrimaryIcon"] == "App Icon") + #expect((bundle.infoPlistAdditions["TVTopShelfImage"] as? [String: String])?["TVTopShelfPrimaryImage"] == "Top Shelf") + } + + @Test("Default iOS compilation ignores TV Brand Assets and preserves its AppIcon") + func mixedCatalogSelectsPlatform() async throws { + let fixture = try BrandFixture(renderable: true) + defer { fixture.remove() } + try fixture.write("AppIcon.appiconset/Contents.json", """ + { "info": { "version": 1, "author": "xcode" }, + "images": [{ "idiom": "iphone", "size": "60x60", "scale": "2x", "filename": "icon.png" }] } + """) + try fixture.writePNG("AppIcon.appiconset/icon.png", width: 120, height: 120, color: PNG.RGBA(255, 0, 0, 255)) + let ios = XCAssetCompiler(deploymentTarget: "16.0") + let mixed = try await ios.compile(catalog: fixture.url) + #expect(mixed.appIconBundle?.primaryIconName == "AppIcon") + let tvos = try await XCAssetCompiler(deploymentTarget: "17.0", platform: .tvOS).compile(catalog: fixture.url) + #expect(tvos.appIconBundle?.primaryIconName == "App Icon") + + try FileManager.default.copyItem( + at: fixture.url.appendingPathComponent("AppIcon.appiconset"), + to: fixture.url.appendingPathComponent("Alternative.appiconset") + ) + let tvWithAlternative = try await XCAssetCompiler(deploymentTarget: "17.0", platform: .tvOS).compile(catalog: fixture.url) + #expect(tvWithAlternative.carData == tvos.carData) + try FileManager.default.removeItem(at: fixture.url.appendingPathComponent("Alternative.appiconset")) + + try fixture.write("TVAppIcon.brandassets/Contents.json", "{}") + let iosIgnoringBrand = try await ios.compile(catalog: fixture.url) + #expect(iosIgnoringBrand.carData == mixed.carData) + try FileManager.default.removeItem(at: fixture.url.appendingPathComponent("TVAppIcon.brandassets")) + let iosOnly = try await ios.compile(catalog: fixture.url) + #expect(mixed.carData == iosOnly.carData) + } + + @Test("Marketing icons share the primary facet and retain their own layer names") + func marketingVariant() async throws { + let fixture = try BrandFixture(renderable: true) + defer { fixture.remove() } + let brandDirectory = fixture.url.appendingPathComponent("TVAppIcon.brandassets") + let metadataURL = brandDirectory.appendingPathComponent("Contents.json") + var metadata = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: metadataURL)) as? [String: Any]) + var assets = try #require(metadata["assets"] as? [[String: String]]) + assets.append(["filename": "App Icon - Large.imagestack", "idiom": "tv", + "role": "primary-app-icon", "size": "1280x768"]) + metadata["assets"] = assets + try JSONSerialization.data(withJSONObject: metadata).write(to: metadataURL) + try FileManager.default.copyItem( + at: brandDirectory.appendingPathComponent("App Icon.imagestack"), + to: brandDirectory.appendingPathComponent("App Icon - Large.imagestack") + ) + for name in ["Front", "Back"] { + try fixture.writePNG("TVAppIcon.brandassets/App Icon - Large.imagestack/\(name).imagestacklayer/Content.imageset/image.png", + width: 1280, height: 768, color: PNG.RGBA(255, 0, 255, 255)) + } + let catalog = try await CatalogLoader().load(catalog: fixture.url, platform: .tvOS) + let output = try BrandAssetsRenderer.render(try #require(catalog.brandAssets.first), svgRasterizer: StubSVGRasterizer()) + let marketing = try #require(output.renditions.first { + if case .layerStack = $0.body { return $0.idiom == .marketing } + return false + }) + guard case .layerStack(let body) = marketing.body else { return } + #expect(marketing.name == "App Icon") + #expect(body.width == 1280 && body.height == 768) + #expect(body.backgroundName == "App Icon - Large/Back/Content") + #expect(body.foregroundName == "App Icon - Large/Front/Content") + let children = output.renditions.filter { $0.name.hasPrefix("App Icon - Large/") } + #expect(children.count == 2) + #expect(children.allSatisfy { $0.idiom == .marketing && $0.scale == .x1 }) + } + + @Test("A Top Shelf name cannot alias an image-stack child identifier") + func rejectsIdentifierCollision() async throws { + let fixture = try BrandFixture(renderable: true) + defer { fixture.remove() } + let brand = fixture.url.appendingPathComponent("TVAppIcon.brandassets") + let metadataURL = brand.appendingPathComponent("Contents.json") + var metadata = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: metadataURL)) as? [String: Any]) + var assets = try #require(metadata["assets"] as? [[String: String]]) + assets[0]["filename"] = "App Icon - Small.imagestack" + assets[1]["filename"] = "TopShelf4014.imageset" + metadata["assets"] = assets + try JSONSerialization.data(withJSONObject: metadata).write(to: metadataURL) + try FileManager.default.moveItem(at: brand.appendingPathComponent("App Icon.imagestack"), + to: brand.appendingPathComponent("App Icon - Small.imagestack")) + try FileManager.default.moveItem(at: brand.appendingPathComponent("Top Shelf.imageset"), + to: brand.appendingPathComponent("TopShelf4014.imageset")) + #expect(FacetKeys.nameHash("App Icon - Small/Back/Content") & 0xFFFF == FacetKeys.nameHash("TopShelf4014") & 0xFFFF) + do { + _ = try await XCAssetCompiler(deploymentTarget: "17.0", platform: .tvOS).compile(catalog: fixture.url) + Issue.record("Distinct facet names with colliding identifiers compiled") + } catch XCAssetCompilerError.assetIdentifierCollision(let first, let second, let identifier) { + #expect(Set([first, second]) == Set(["App Icon - Small/Back/Content", "TopShelf4014"])) + #expect(identifier == 53544) + } + } + + @Test("Primary icon and Top Shelf roles cannot export the same asset name") + func rejectsRoleNameCollision() async throws { + let fixture = try BrandFixture(renderable: true) + defer { fixture.remove() } + let brand = fixture.url.appendingPathComponent("TVAppIcon.brandassets") + let metadataURL = brand.appendingPathComponent("Contents.json") + var metadata = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: metadataURL)) as? [String: Any]) + var assets = try #require(metadata["assets"] as? [[String: String]]) + assets[1]["filename"] = "App Icon.imageset" + metadata["assets"] = assets + try JSONSerialization.data(withJSONObject: metadata).write(to: metadataURL) + try FileManager.default.moveItem(at: brand.appendingPathComponent("Top Shelf.imageset"), + to: brand.appendingPathComponent("App Icon.imageset")) + await #expect(throws: XCAssetCompilerError.self) { + _ = try await XCAssetCompiler(deploymentTarget: "17.0", platform: .tvOS).compile(catalog: fixture.url) + } + } + + @Test("tvOS bitmap descriptors encode emitted scale and idiom masks") + func bitmapMasks() throws { + let stack = LayerStackBody(width: 400, height: 240, backgroundName: "Back", foregroundName: "Front") + let descriptor = Rendition(name: "Icon", idiom: .universal, scale: .x1, appearance: nil, + gamut: nil, body: .layerStack(stack)) + var marketing = descriptor + marketing.idiom = .marketing + func preview(_ scale: Scale, _ idiom: Idiom) -> Rendition { + Rendition(name: "Icon", idiom: idiom, scale: scale, appearance: nil, gamut: .sRGB, + body: .bitmap(BitmapBody(width: 1, height: 1, pixelsBGRA: [0, 0, 0, 255], + colorSpaceID: 1, kind: .layerStackPreview, renditionName: "preview"))) + } + let value = try #require(BitmapKeys.descriptor(forAsset: "Icon", renditions: [ + descriptor, marketing, preview(.x1, .tv), preview(.x2, .tv), preview(.x1, .marketing), + ])) + let bytes = [UInt8](value.encode(platform: .tvOS)) + func word(_ offset: Int) -> UInt32 { + UInt32(bytes[offset]) | UInt32(bytes[offset + 1]) << 8 | + UInt32(bytes[offset + 2]) << 16 | UInt32(bytes[offset + 3]) << 24 + } + #expect(bytes.count == 52) + #expect(word(24) == 0x06) + #expect(word(28) == 0x49) + #expect(word(32) == 1 && word(36) == 1) + } + + @Test("Custom layer geometry is rejected rather than silently discarded") + func rejectsCustomGeometry() async throws { + let fixture = try BrandFixture(renderable: true) + defer { fixture.remove() } + try fixture.write("TVAppIcon.brandassets/App Icon.imagestack/Front.imagestacklayer/Contents.json", """ + { "properties": { "frame-center": { "x": 100, "y": 100 } } } + """) + await #expect(throws: XCAssetCompilerError.self) { + _ = try await XCAssetCompiler(deploymentTarget: "17.0", platform: .tvOS).compile(catalog: fixture.url) + } + } + + @Test("Unverified layer counts are rejected", arguments: [1, 3]) + func rejectsLayerCount(_ count: Int) async throws { + let fixture = try BrandFixture() + defer { fixture.remove() } + let filenames = (0.. UInt32 { + UInt32(record[offset]) | UInt32(record[offset + 1]) << 8 | + UInt32(record[offset + 2]) << 16 | UInt32(record[offset + 3]) << 24 + } + #expect(record.count == 470) + #expect(word(12) == 400 && word(16) == 240) + #expect(word(24) == CSIHeader.pixelFormatData) + #expect(word(36) == 1002) + #expect(word(168) == 274) + #expect(word(184) == 1012 && word(188) == 104) + #expect(word(192) == 2) + #expect(word(212) == 400 && word(216) == 240) + #expect(word(260) == 400 && word(264) == 240) + #expect(word(236) == 0x00b50002) + #expect(word(284) == 0x00b50002) + #expect(word(240) == (FacetKeys.nameHash("Back") & 0xFFFF) << 16 | 17) + #expect(word(288) == (FacetKeys.nameHash("Front") & 0xFFFF) << 16 | 17) + #expect(word(296) == 1020 && word(300) == 34) + #expect(word(338) == 1021 && word(342) == 48) + #expect(Array(record.suffix(12)) == Array("DWAR".utf8) + [UInt8](repeating: 0, count: 8)) + } + + @Test("Apple assetutil parses the tvOS stack catalog", .enabled(if: ProcessLauncher.isAvailable)) + func appleParsesTVBrandAssets() async throws { + let fixture = try BrandFixture(renderable: true) + defer { fixture.remove() } + let result = try await XCAssetCompiler(deploymentTarget: "17.0", platform: .tvOS).compile(catalog: fixture.url) + let car = fixture.url.appendingPathComponent("Assets.car") + try result.carData.write(to: car) + let invocation = try ProcessLauncher.run(executable: "/usr/bin/xcrun", arguments: ["assetutil", "--info", car.path]) + #expect(invocation.exitCode == 0, "\(String(decoding: invocation.stderr, as: UTF8.self))") + let entries = try #require(JSONSerialization.jsonObject(with: invocation.stdout) as? [[String: Any]]) + #expect(entries.first?["Platform"] as? String == "atv") + let names = Set(entries.compactMap { $0["Name"] as? String }) + #expect(names.contains("App Icon")) + #expect(names.contains("App Icon/Front/Content")) + #expect(names.contains("App Icon/Back/Content")) + #expect(names.contains("Top Shelf")) + } +} + +private struct BrandFixture { + let url: URL + + init(renderable: Bool = false) throws { + url = FileManager.default.temporaryDirectory + .appendingPathComponent("brand-\(UUID().uuidString).xcassets", isDirectory: true) + try write("Contents.json", """ + { "info": { "version": 1, "author": "xcode" } } + """) + try write("TVAppIcon.brandassets/Contents.json", """ + { + "info": { "version": 1, "author": "xcode" }, + "assets": [ + { "filename": "App Icon.imagestack", "idiom": "tv", "role": "primary-app-icon", "size": "400x240" }, + { "filename": "Top Shelf.imageset", "idiom": "tv", "role": "top-shelf-image", "size": "120x120" } + ] + } + """) + try write("TVAppIcon.brandassets/App Icon.imagestack/Contents.json", """ + { + "info": { "version": 1, "author": "xcode" }, + "layers": [ + { "filename": "Front.imagestacklayer" }, + { "filename": "Back.imagestacklayer" } + ] + } + """) + for name in ["Back", "Front"] { + try write("TVAppIcon.brandassets/App Icon.imagestack/\(name).imagestacklayer/Content.imageset/Contents.json", """ + { + "info": { "version": 1, "author": "xcode" }, + "images": [{ "idiom": "tv", "scale": "1x", "filename": "image.png" }] + } + """) + } + try write("TVAppIcon.brandassets/Top Shelf.imageset/Contents.json", """ + { + "info": { "version": 1, "author": "xcode" }, + "images": [{ "idiom": "tv", "scale": "1x", "filename": "image.png" }] + } + """) + if renderable { + try writePNG("TVAppIcon.brandassets/App Icon.imagestack/Front.imagestacklayer/Content.imageset/image.png", + width: 400, height: 240, color: PNG.RGBA(255, 0, 0, 128)) + try writePNG("TVAppIcon.brandassets/App Icon.imagestack/Back.imagestacklayer/Content.imageset/image.png", + width: 400, height: 240, color: PNG.RGBA(0, 0, 255, 255)) + try writePNG("TVAppIcon.brandassets/Top Shelf.imageset/image.png", + width: 120, height: 120, color: PNG.RGBA(0, 255, 0, 255)) + } + } + + func write(_ path: String, _ json: String) throws { + let file = url.appendingPathComponent(path) + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(json.utf8).write(to: file) + } + + func remove() { + try? FileManager.default.removeItem(at: url) + } + + func writePNG(_ path: String, width: Int, height: Int, color: PNG.RGBA) throws { + let image = PNG.Image( + packing: [PNG.RGBA](repeating: color, count: width * height), + size: (x: width, y: height), layout: PNG.Layout(format: .rgba8(palette: [], fill: nil)) + ) + var stream = MemoryBytestreamDestination() + try image.compress(stream: &stream, level: 0) + try Data(stream.bytes).write(to: url.appendingPathComponent(path)) + } +} diff --git a/docs/coreui-970-format.md b/docs/coreui-970-format.md index bdc2e24..bdca951 100644 --- a/docs/coreui-970-format.md +++ b/docs/coreui-970-format.md @@ -230,6 +230,53 @@ Implementation: [Sources/AssetKit/CAR/CSIWriter.swift](../Sources/AssetKit/CAR/C Older Xcode releases (11 through 13 era) converted SVG to PDF internally and stored the PDF stream as a CoreUI vector rendition body. Modern actool no longer does the PDF round-trip: it stores the SVG XML directly, LZFSE-compressed inside the DWAR envelope. Anything you may have read about `preserves-vector-representation` triggering an SVG-to-PDF intermediate is the older shape. +## tvOS Brand Assets + +The explicit tvOS compiler path writes deployment platform `atv` and uses +`Dimension1` (attribute 8) in the sixth key slot. The default iOS path keeps its +existing `Dimension2` (attribute 9) key format. These are platform-specific +choices, not interchangeable names for the same attribute. + +The tvOS stack format was compared with the `Assets.car` in the public +[Provenance 3.3.0 tvOS release](https://github.com/Provenance-Emu/Provenance/releases/tag/3.3.0). +Its header identifies CoreUI 969, storage version 17, and Xcode 26.0. No source +artwork or compiled catalog from that release is bundled here. + +The primary facet is named for the small stack, not the `.brandassets` folder. +It contains a universal 400×240 LayerStack descriptor and, when supplied, a +marketing-idiom 1280×768 descriptor. The small stack's child images use the TV +idiom; the marketing children use the marketing idiom. Each layer has its own +qualified facet, such as `App Icon - Small/Back/Content`. The descriptor references +those facets in back-to-front order, retaining the source's separate layers. + +The observed stock two-layer CSI descriptor is 470 bytes: + +- The 184-byte CSI header uses layout 1002, pixel format `DATA`, scale 100, + and the rendition name `Contents.json`. +- Its 274-byte TVL block contains tags 1012, 1020, 1021, 1004, 1005, and 1006. +- Tag 1012 carries the layer references, dimensions, and stock rendering values. + Its facet identifiers are derived from the emitted child names so each link + resolves within the new catalog. +- Tags 1020 and 1021 preserve the observed stock two-layer values. Their other + semantics are not inferred, and custom geometry and other layer counts are + rejected. +- The UTI is `public.layeredimage`; the body is an empty, uncompressed DWAR + envelope. + +The tvOS `BITMAPKEYS` descriptor's slots 6 and 7 are scale and idiom bitmasks, +derived from the actual emitted key values. For the reference primary facet, +scales 1 and 2 give `0x06`; idioms 0, 3, and 6 give `0x49`. Child layer and +Top Shelf descriptors independently corroborate these masks. The tvOS writer +computes them rather than reusing the fixed iOS templates described above. +The existing iOS output is retained in this change. + +The same facet also carries separately composited previews at part 208, layout +0. They use premultiplied front-over-back compositing and LZFSE bitmap payloads. +The reference additionally contains larger, blurred radiosity images at part +209. That undocumented codec and its runtime requirements have not been +established here. Matching the descriptor and parsing the catalog are separate +from verifying tvOS icon loading and focus effects on an Apple TV. + ## SpringBoard fallback (loose-PNG escape hatch) The library emits loose PNGs into the bundle root alongside `Assets.car`, named per `CFBundleIconFiles` (e.g. `AppIcon60x60@2x.png`). These are not redundant with the CAR-embedded renditions — they exist because SpringBoard's home-screen icon-render pipeline uses the loose-PNG fallback whenever CoreUI's rendition lookup misses.