diff --git a/README.md b/README.md index ab64e24..ec01450 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ if let bundle = result.appIconBundle { - JPG sources stored as preserved raw renditions (JPEG bytes passed through; original compression preserved) - `.colorset` (sRGB and display-P3, hex or float components, dark/light appearances) - `.appiconset` (per-idiom and per-size, with the loose-PNG fallback that SpringBoard expects alongside `Assets.car`). PNG sources only; SVG/JPG are rejected because SpringBoard's icon-render pipeline requires PNG. + - Single-size icons (Xcode 14+: one 1024x1024 `universal` / `platform: ios` entry): the iPhone, iPad and Settings/Spotlight/notification sizes are generated from the master by area-averaged downscaling, and the master is kept as the store icon. The master must be exactly 1024x1024. Dark and tinted (iOS 18) entries are skipped: the default icon is used for every appearance. ## What it deliberately doesn't support diff --git a/Sources/AssetKit/AppIcon/AppIconPlist.swift b/Sources/AssetKit/AppIcon/AppIconPlist.swift index 9a4f6b2..645e134 100644 --- a/Sources/AssetKit/AppIcon/AppIconPlist.swift +++ b/Sources/AssetKit/AppIcon/AppIconPlist.swift @@ -10,7 +10,9 @@ struct IconFile: Sendable, Hashable { var idiom: Idiom var pointSize: Double var scale: Int - var sourceURL: URL + /// Name of the file the pixels came from, or the name actool would give a generated one. + var sourceName: String + var data: Data var outputName: String } @@ -20,27 +22,18 @@ enum AppIconPlistEmitter { var ipadFiles: [String] = [] var allFiles: [IconFile] = [] - for image in appIcon.contents.images { - guard let filename = image.filename, !filename.isEmpty else { - throw XCAssetCompilerError.appIconSizeMissing(asset: appIcon.name, size: image.size) - } - let src = appIcon.directory.appendingPathComponent(filename) - guard FileManager.default.fileExists(atPath: src.path) else { - throw XCAssetCompilerError.missingReferencedFile(asset: appIcon.name, filename: filename) - } - guard let (w, _) = image.pointSize, let scale = image.scale?.factor else { - throw XCAssetCompilerError.appIconSizeMissing(asset: appIcon.name, size: image.size) - } - let bundleName = "\(appIcon.name)\(formatSize(w))x\(formatSize(w))" - let entry = IconFile( - idiom: image.idiom, - pointSize: w, - scale: scale, - sourceURL: src, + let entries = try iconEntries(for: appIcon) + for entry in entries { + let bundleName = "\(appIcon.name)\(formatSize(entry.pointSize))x\(formatSize(entry.pointSize))" + allFiles.append(IconFile( + idiom: entry.idiom, + pointSize: entry.pointSize, + scale: entry.scale, + sourceName: entry.sourceName, + data: entry.data, outputName: bundleName - ) - allFiles.append(entry) - switch image.idiom { + )) + switch entry.idiom { case .iphone: if !iphoneFiles.contains(bundleName) { iphoneFiles.append(bundleName) } case .ipad: @@ -87,6 +80,91 @@ enum AppIconPlistEmitter { ) } + private struct Entry { + var idiom: Idiom + var pointSize: Double + var scale: Int + var sourceName: String + var data: Data + } + + /// The icons to emit: one per `Contents.json` entry, or, for the single-size + /// format, the sizes generated from the 1024x1024 master. + private static func iconEntries(for appIcon: LoadedAppIcon) throws -> [Entry] { + var entries: [Entry] = [] + for image in appIcon.contents.images { + if let platform = image.platform, platform != "ios" { + throw XCAssetCompilerError.unsupportedAppIconPlatform(asset: appIcon.name, platform: platform) + } + // Dark and tinted variants (iOS 18) are not compiled yet; the default icon is used for every appearance. + if !(image.appearances ?? []).isEmpty { continue } + + guard let filename = image.filename, !filename.isEmpty else { + throw XCAssetCompilerError.appIconSizeMissing(asset: appIcon.name, size: image.size) + } + let src = appIcon.directory.appendingPathComponent(filename) + guard FileManager.default.fileExists(atPath: src.path) else { + throw XCAssetCompilerError.missingReferencedFile(asset: appIcon.name, filename: filename) + } + let data = try Data(contentsOf: src) + + if image.isSingleSizeMaster { + entries.append(contentsOf: try expandMaster(data, filename: filename, appIcon: appIcon)) + continue + } + guard let (w, _) = image.pointSize, let scale = image.scale?.factor else { + throw XCAssetCompilerError.appIconSizeMissing(asset: appIcon.name, size: image.size) + } + entries.append(Entry(idiom: image.idiom, pointSize: w, scale: scale, sourceName: filename, data: data)) + } + return entries + } + + /// Point sizes and scales actool generates from a single-size master for iOS. + private static let generatedSizes: [(idiom: Idiom, points: Double, scale: Int)] = [ + (.iphone, 20, 2), (.iphone, 20, 3), + (.iphone, 29, 2), (.iphone, 29, 3), + (.iphone, 40, 2), (.iphone, 40, 3), + (.iphone, 60, 2), (.iphone, 60, 3), + (.ipad, 20, 1), (.ipad, 20, 2), + (.ipad, 29, 1), (.ipad, 29, 2), + (.ipad, 40, 1), (.ipad, 40, 2), + (.ipad, 76, 1), (.ipad, 76, 2), + (.ipad, 83.5, 2), + ] + + private static func expandMaster(_ data: Data, filename: String, appIcon: LoadedAppIcon) throws -> [Entry] { + let master = try PNGResizer.decode(data) + guard master.width == 1024, master.height == 1024 else { + throw XCAssetCompilerError.appIconSourceSizeMismatch( + asset: appIcon.name, + filename: filename, + expected: "1024x1024", + actual: "\(master.width)x\(master.height)" + ) + } + var resized: [Int: Data] = [:] + var out: [Entry] = [] + for size in generatedSizes { + let pixels = Int((size.points * Double(size.scale)).rounded()) + if resized[pixels] == nil { + resized[pixels] = try PNGResizer.resize(master, width: pixels, height: pixels) + } + let suffix = size.scale == 1 ? "" : "@\(size.scale)x" + let name = "\(formatSize(size.points))x\(formatSize(size.points))" + out.append(Entry( + idiom: size.idiom, + pointSize: size.points, + scale: size.scale, + sourceName: "\(appIcon.name)-\(name)\(suffix).png", + data: resized[pixels]! + )) + } + // The store icon is the master itself. + out.append(Entry(idiom: .marketing, pointSize: 1024, scale: 1, sourceName: filename, data: data)) + return out + } + private static func formatSize(_ n: Double) -> String { let rounded = n.rounded() if abs(n - rounded) < 0.001 { diff --git a/Sources/AssetKit/AppIcon/PNGResizer.swift b/Sources/AssetKit/AppIcon/PNGResizer.swift new file mode 100644 index 0000000..4074e85 --- /dev/null +++ b/Sources/AssetKit/AppIcon/PNGResizer.swift @@ -0,0 +1,121 @@ +import Foundation +import PNG + +/// Area-averaging PNG downscaler, used to expand a single-size app icon +/// master into the sizes the home screen, Spotlight and Settings need. +/// +/// Averaging is done on premultiplied alpha so transparent pixels don't bleed +/// their (meaningless) colour into the edges. +enum PNGResizer { + struct Decoded { + var width: Int + var height: Int + /// Premultiplied RGBA, 0...255 as Float. + var pixels: [Float] + } + + private struct MemoryStream: PNG.BytestreamSource { + var bytes: [UInt8] + var offset = 0 + mutating func read(count: Int) -> [UInt8]? { + guard offset + count <= bytes.count else { return nil } + defer { offset += count } + return Array(bytes[offset.. Void? { + bytes.append(contentsOf: data) + return () + } + } + + static func decode(_ data: Data) throws -> Decoded { + var stream = MemoryStream(bytes: [UInt8](data)) + let image = try PNG.Image.decompress(stream: &stream) + let rgba: [PNG.RGBA] = image.unpack(as: PNG.RGBA.self) + var pixels = [Float](repeating: 0, count: rgba.count * 4) + for (i, px) in rgba.enumerated() { + let a = Float(px.a) / 255 + pixels[i * 4 + 0] = Float(px.r) * a + pixels[i * 4 + 1] = Float(px.g) * a + pixels[i * 4 + 2] = Float(px.b) * a + pixels[i * 4 + 3] = Float(px.a) + } + return Decoded(width: image.size.x, height: image.size.y, pixels: pixels) + } + + /// Returns PNG bytes of `source` scaled to `width` x `height`. + static func resize(_ source: Decoded, width: Int, height: Int) throws -> Data { + // Horizontal pass: `source.height` rows, each shrunk to `width` pixels. + let horizontal = resample( + source.pixels, outer: source.height, srcCount: source.width, dstCount: width, + srcStep: 4, srcOuterStep: source.width * 4, dstStep: 4, dstOuterStep: width * 4 + ) + // Vertical pass: `width` columns, each shrunk to `height` pixels. + let scaled = resample( + horizontal, outer: width, srcCount: source.height, dstCount: height, + srcStep: width * 4, srcOuterStep: 4, dstStep: width * 4, dstOuterStep: 4 + ) + + var rgba = [PNG.RGBA](repeating: PNG.RGBA(0, 0, 0, 0), count: width * height) + for i in 0..<(width * height) { + let a = scaled[i * 4 + 3] + guard a > 0 else { continue } + let k = 255 / a + rgba[i] = PNG.RGBA( + clamp(scaled[i * 4 + 0] * k), clamp(scaled[i * 4 + 1] * k), clamp(scaled[i * 4 + 2] * k), clamp(a) + ) + } + let image = PNG.Image( + packing: rgba, + size: (x: width, y: height), + layout: PNG.Layout(format: .rgba8(palette: [], fill: nil)) + ) + var out = MemoryDestination() + try image.compress(stream: &out) + return Data(out.bytes) + } + + private static func clamp(_ v: Float) -> UInt8 { + UInt8(max(0, min(255, v.rounded()))) + } + + /// One separable pass of box (area) resampling along an axis. Steps are in `Float` units. + private static func resample( + _ src: [Float], outer: Int, srcCount: Int, dstCount: Int, + srcStep: Int, srcOuterStep: Int, dstStep: Int, dstOuterStep: Int + ) -> [Float] { + var dst = [Float](repeating: 0, count: outer * dstCount * 4) + let ratio = Double(srcCount) / Double(dstCount) + src.withUnsafeBufferPointer { src in + dst.withUnsafeMutableBufferPointer { dst in + for d in 0.. [BOMTree.InlineKeyEntry] { + static func entries( + for assets: [(name: String, descriptor: Descriptor)], + options: OutputOptions = .legacy + ) -> [BOMTree.InlineKeyEntry] { return assets.map { asset in BOMTree.InlineKeyEntry( - key: FacetKeys.nameHash(asset.name) & 0xFFFF, + key: UInt32(FacetKeys.identifier(for: asset.name, options: options)), value: asset.descriptor.encode() ) } @@ -97,7 +108,11 @@ enum BitmapKeys { /// `renditions` is the per-asset slice -- only the renditions whose /// `name` equals this asset's name. Caller is responsible for the /// grouping; this function does not re-filter. - static func descriptor(forAsset name: String, renditions: [Rendition]) -> Descriptor? { + static func descriptor( + forAsset name: String, + renditions: [Rendition], + options: OutputOptions = .legacy + ) -> Descriptor? { let hasBitmapOrPreservedSource = renditions.contains { rendition in switch rendition.body { case .bitmap, .preservedSource: return true @@ -118,7 +133,20 @@ enum BitmapKeys { return (idiom << 16) | subtype }) - return Descriptor(kind: kind, idiomSubtypeCount: UInt32(idiomSubtypes.count)) + var descriptor = Descriptor(kind: kind, idiomSubtypeCount: UInt32(idiomSubtypes.count)) + descriptor.withDimension1 = options.contains(.dimension1Key) + if options.contains(.multisizeIcons) { + var idioms: UInt32 = 0 + var dimension2: UInt32 = 0 + for rendition in renditions { + idioms |= 1 << UInt32(rendition.idiom.rawValueByte) + dimension2 |= 1 << UInt32(RenditionKey(rendition: rendition).dimension2) + } + // the size index records are keyed with dimension2 = 0 + if kind == .appIcon { dimension2 |= 1 } + descriptor.masks = (idioms, dimension2) + } + return descriptor } /// AppIcon takes precedence over Vector takes precedence over Image: diff --git a/Sources/AssetKit/CAR/CARHeader.swift b/Sources/AssetKit/CAR/CARHeader.swift index 8bd95a8..1eb7b29 100644 --- a/Sources/AssetKit/CAR/CARHeader.swift +++ b/Sources/AssetKit/CAR/CARHeader.swift @@ -17,7 +17,11 @@ enum CARHeaderBlock { /// `assetutil --info` and Xcode-side tooling display them without /// surprises. static let defaultMainVersionString = "@(#)PROGRAM:CoreUI PROJECT:CoreUI-970.1" - static let defaultVersionString = "xcasset-compiler clean-room CAR writer (Assets.car v1)" + static let defaultVersionString = "AssetKit" + + /// What Xcode 26.5's actool writes (CoreUI 975). + static let actoolMainVersionString = "@(#)PROGRAM:CoreUI PROJECT:CoreUI-975" + static let actoolVersionString = "Xcode 26.5 (17F42) via AssetCatalogSimulatorAgent" static func data( coreuiVersion: UInt32 = 970, diff --git a/Sources/AssetKit/CAR/CARWriter.swift b/Sources/AssetKit/CAR/CARWriter.swift index 4288e0e..5f6e456 100644 --- a/Sources/AssetKit/CAR/CARWriter.swift +++ b/Sources/AssetKit/CAR/CARWriter.swift @@ -11,9 +11,11 @@ import Foundation struct CARWriter: Sendable { var deploymentTarget: String var renditions: [Rendition] + var options: OutputOptions = .legacy func write() throws -> Data { let layout = CARLayout(renditions: renditions) + let iconSizeRecords = options.contains(.multisizeIcons) ? Self.iconSizeRecords(for: renditions, options: options) : [] var bom = BOMWriter() // Canonical vars-table order, established by the call sequence @@ -21,22 +23,36 @@ struct CARWriter: Sendable { // KEYFORMAT, EXTENDED_METADATA, BITMAPKEYS. Reordering or omitting // a `setVariable` here breaks iOS lookups silently. - let headerBlockID = bom.addBlock(CARHeaderBlock.data(renditionCount: UInt32(renditions.count))) + let headerCount = UInt32(renditions.count + iconSizeRecords.count) + let headerBlockID = bom.addBlock( + options.contains(.actoolVersionStrings) + ? CARHeaderBlock.data( + coreuiVersion: 975, + renditionCount: headerCount, + mainVersionString: CARHeaderBlock.actoolMainVersionString, + versionString: CARHeaderBlock.actoolVersionString + ) + : CARHeaderBlock.data(renditionCount: headerCount) + ) bom.setVariable("CARHEADER", blockID: headerBlockID) - let renditionEntries: [BOMTree.Entry] = renditions.map { rendition in + let withDimension1 = options.contains(.dimension1Key) + var renditionEntries: [BOMTree.Entry] = renditions.map { rendition in BOMTree.Entry( - key: RenditionKey(rendition: rendition).encode(), + key: RenditionKey(rendition: rendition, options: options).encode(withDimension1: withDimension1), value: csiData(for: rendition) ) } + renditionEntries += iconSizeRecords.map { record in + BOMTree.Entry(key: record.key.encode(withDimension1: withDimension1), value: record.value) + } let renditionsTreeID = BOMTree.insert(into: &bom, entries: renditionEntries) bom.setVariable("RENDITIONS", blockID: renditionsTreeID) let facetEntries = layout.assets.map { asset in BOMTree.Entry( key: Data(asset.name.utf8), - value: FacetKeys.value(for: asset.name, kind: asset.kind) + value: FacetKeys.value(for: asset.name, kind: asset.kind, options: options) ) } let facetTreeID = BOMTree.insert(into: &bom, entries: facetEntries) @@ -48,24 +64,32 @@ struct CARWriter: Sendable { ) bom.setVariable("APPEARANCEKEYS", blockID: appearanceTreeID) - let kfmtBlockID = bom.addBlock(KeyFormatBlock.data()) + let kfmtBlockID = bom.addBlock(KeyFormatBlock.data(attributes: withDimension1 ? v2KeyFormat : v1KeyFormat)) bom.setVariable("KEYFORMAT", blockID: kfmtBlockID) - let extendedMetadataBlockID = bom.addBlock(ExtendedMetadata.data(deploymentTarget: deploymentTarget)) + let extendedMetadataBlockID = bom.addBlock( + options.contains(.actoolVersionStrings) + ? ExtendedMetadata.data( + deploymentTarget: deploymentTarget, + authoringTool: ExtendedMetadata.actoolAuthoringTool + ) + : ExtendedMetadata.data(deploymentTarget: deploymentTarget) + ) bom.setVariable("EXTENDED_METADATA", blockID: extendedMetadataBlockID) let bitmapAssets: [(name: String, descriptor: BitmapKeys.Descriptor)] = layout.assets.compactMap { asset in guard let descriptor = BitmapKeys.descriptor( forAsset: asset.name, - renditions: asset.renditions + renditions: asset.renditions, + options: options ) else { return nil } return (asset.name, descriptor) } if !bitmapAssets.isEmpty { let bitmapKeysTreeID = BOMTree.insertInlineKey( into: &bom, - entries: BitmapKeys.entries(for: bitmapAssets), + entries: BitmapKeys.entries(for: bitmapAssets, options: options), blockSize: 1024 ) bom.setVariable("BITMAPKEYS", blockID: bitmapKeysTreeID) @@ -74,6 +98,40 @@ struct CARWriter: Sendable { return bom.finalize() } + /// The app icon size index records (part 218): one per (idiom, subtype) + /// group, listing the sizes that exist for it, keyed at scale 1. + private static func iconSizeRecords( + for renditions: [Rendition], + options: OutputOptions + ) -> [(key: RenditionKey, value: Data)] { + struct Group: Hashable { + var idiom: Idiom + var subtype: UInt16 + } + var groups: [Group: [UInt16: UInt32]] = [:] + var names: [Group: String] = [:] + for rendition in renditions { + guard case .bitmap(let body) = rendition.body, body.kind == .appIcon else { continue } + let group = Group(idiom: rendition.idiom, subtype: body.subtype) + // keyed by icon index so that @1x/@2x/@3x files of one size count once + groups[group, default: [:]][body.iconIndex] = UInt32(body.iconPoints) + names[group] = rendition.name + } + return groups.map { group, sizes in + var key = RenditionKey( + scale: 1, + idiom: group.idiom.rawValueByte, + subtype: group.subtype, + identifier: FacetKeys.identifier(for: names[group]!, options: options), + element: RenditionKey.Element.bitmap.rawValue, + part: RenditionKey.Part.iconSizes.rawValue + ) + key.dimension1 = 0 + let entries = sizes.sorted { $0.key < $1.key }.map { (points: $0.value, index: UInt32($0.key)) } + return (key, CSIWriter.iconSizes(name: names[group]!, entries: entries)) + } + } + private func csiData(for rendition: Rendition) -> Data { switch rendition.body { case .bitmap(let body): diff --git a/Sources/AssetKit/CAR/CSIHeader.swift b/Sources/AssetKit/CAR/CSIHeader.swift index ad38c74..3df1fc0 100644 --- a/Sources/AssetKit/CAR/CSIHeader.swift +++ b/Sources/AssetKit/CAR/CSIHeader.swift @@ -40,6 +40,8 @@ enum CSIHeader { /// category; SVG promotes to its own layout because vector /// renditions surface a different AssetType to `assetutil`. case vector = 9 + /// App icon size index ("MSIS" body, part 218). + case iconSizes = 1010 } // swiftlint:disable:next function_parameter_count diff --git a/Sources/AssetKit/CAR/CSIWriter.swift b/Sources/AssetKit/CAR/CSIWriter.swift index 2bdeace..01c9cbe 100644 --- a/Sources/AssetKit/CAR/CSIWriter.swift +++ b/Sources/AssetKit/CAR/CSIWriter.swift @@ -112,6 +112,35 @@ enum CSIWriter { return header + tvl + envelope } + /// The app icon size index: which sizes (and icon indexes) exist for one + /// idiom / subtype group. `entries` are (width = height in points, icon index). + static func iconSizes(name: String, entries: [(points: UInt32, index: UInt32)]) -> Data { + var body = ByteWriter() + body.writeFourCC("SISM") + body.writeLE(UInt32(1)) // version + body.writeLE(UInt32(entries.count)) + for entry in entries { + body.writeLE(entry.points) + body.writeLE(entry.points) + body.writeLE(entry.index) + } + let tvl = CSITVL.encode([.sliceScaleZero, .bitmapFlag]) + let header = CSIHeader.encode( + renditionFlags: 0, + width: 0, + height: 0, + scaleFactor: 0, + pixelFormat: 0, + colorSpace: 0, + layout: .iconSizes, + name: name, + tvlLength: UInt32(tvl.count), + bitmapCount: 1, + renditionLength: UInt32(body.data.count) + ) + return header + tvl + body.data + } + static func color(name: String, body: ColorBody) -> Data { let payload = colorBody(body: body) let header = CSIHeader.encode( diff --git a/Sources/AssetKit/CAR/ExtendedMetadata.swift b/Sources/AssetKit/CAR/ExtendedMetadata.swift index 04d7f7b..00af9fe 100644 --- a/Sources/AssetKit/CAR/ExtendedMetadata.swift +++ b/Sources/AssetKit/CAR/ExtendedMetadata.swift @@ -16,7 +16,10 @@ import Foundation /// platform match recorded here. enum ExtendedMetadata { static let defaultPlatform = "ios" - static let defaultAuthoringTool = "xcasset-compiler clean-room CAR writer (Assets.car v1)" + static let defaultAuthoringTool = "AssetKit" + + static let actoolAuthoringTool = + "@(#)PROGRAM:CoreThemeDefinition PROJECT:CoreThemeDefinition-653.4 [IIO-2784.5.4]" static func data( deploymentTarget: String, diff --git a/Sources/AssetKit/CAR/FacetKeys.swift b/Sources/AssetKit/CAR/FacetKeys.swift index 2a20b56..2bc92e2 100644 --- a/Sources/AssetKit/CAR/FacetKeys.swift +++ b/Sources/AssetKit/CAR/FacetKeys.swift @@ -8,12 +8,11 @@ import Foundation /// - `numberOfAttributes u16` /// - array of `(attributeName u16, attributeValue u16)` enum FacetKeys { - static func value(for name: String, kind: Kind) -> Data { + static func value(for name: String, kind: Kind, options: OutputOptions = .legacy) -> Data { var w = ByteWriter() w.writeLE(UInt16(0)) // cursorHotSpotX w.writeLE(UInt16(0)) // cursorHotSpotY - let crc = nameHash(name) - let identifier = UInt16(crc & 0xFFFF) + let identifier = identifier(for: name, options: options) let pairs = kind.pairs(identifier: identifier) w.writeLE(UInt16(pairs.count)) for (attrName, attrValue) in pairs { @@ -50,6 +49,20 @@ enum FacetKeys { } } + /// The 16-bit NameIdentifier used in FACETKEYS and rendition keys. + /// + /// actool's hash is unknown; CRC32 truncated to 16 bits only has to be + /// consistent between the two trees. The one value observed in an actool + /// catalog (`AppIcon` -> 6849) is reproduced when asked for. + static func identifier(for name: String, options: OutputOptions) -> UInt16 { + if options.contains(.actoolIdentifiers), let known = actoolIdentifiers[name] { + return known + } + return UInt16(nameHash(name) & 0xFFFF) + } + + private static let actoolIdentifiers: [String: UInt16] = ["AppIcon": 6849] + /// CRC32 (IEEE) of the asset name, truncated to 16 bits for the identifier slot. static func nameHash(_ name: String) -> UInt32 { var crc: UInt32 = 0xFFFFFFFF diff --git a/Sources/AssetKit/CAR/KeyFormat.swift b/Sources/AssetKit/CAR/KeyFormat.swift index 292ce33..bd55922 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,21 @@ let v1KeyFormat: [AttributeID] = [ .part, ] +/// The ten-attribute layout actool 26.5 writes: `Dimension1` sits between +/// `Dimension2` and the identifier. It is always 0 in the renditions we emit. +let v2KeyFormat: [AttributeID] = [ + .appearance, + .localization, + .scale, + .idiom, + .subtype, + .dimension2, + .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/RenditionKey.swift b/Sources/AssetKit/CAR/RenditionKey.swift index 01dfb76..cdbef45 100644 --- a/Sources/AssetKit/CAR/RenditionKey.swift +++ b/Sources/AssetKit/CAR/RenditionKey.swift @@ -13,6 +13,8 @@ struct RenditionKey: Hashable, Sendable { var idiom: UInt16 var subtype: UInt16 var dimension2: UInt16 + /// Only encoded with the ten-attribute key format. + var dimension1: UInt16 = 0 var identifier: UInt16 var element: UInt16 var part: UInt16 @@ -36,25 +38,28 @@ struct RenditionKey: Hashable, Sendable { /// rather than `image`; bitmap variants rasterised from the SVG /// (which `UIImage(named:)` actually returns) live under `image`. case vectorSource = 42 + /// App icon "multisize image set" index: lists the sizes of one + /// (idiom, subtype) group. Carries no pixels. + case iconSizes = 218 } - init(rendition: Rendition) { + init(rendition: Rendition, options: OutputOptions = .legacy) { self.appearance = (rendition.appearance?.darkLuminosity == true) ? 1 : 0 self.localization = 0 self.scale = rendition.scale?.rawValueByte ?? 0 self.idiom = rendition.idiom.rawValueByte self.subtype = 0 - self.identifier = UInt16(FacetKeys.nameHash(rendition.name) & 0xFFFF) + self.identifier = FacetKeys.identifier(for: rendition.name, options: options) switch rendition.body { case .bitmap(let body): + self.subtype = body.subtype self.element = Element.bitmap.rawValue switch body.kind { case .appIcon: self.part = Part.appIcon.rawValue - // Dimension2 is the appicon "Icon Index" slot. v1 only - // emits one logical icon size per appiconset, so this is - // always 1. - self.dimension2 = 1 + // Dimension2 is the appicon "Icon Index" slot: it tells the + // sizes of one appiconset apart. + self.dimension2 = body.iconIndex case .image: self.part = Part.image.rawValue // Generic image assets don't use Dimension2 at all. @@ -104,7 +109,7 @@ struct RenditionKey: Hashable, Sendable { self.part = part } - func encode() -> Data { + func encode(withDimension1: Bool = false) -> Data { var w = ByteWriter() w.writeLE(appearance) w.writeLE(localization) @@ -112,6 +117,7 @@ struct RenditionKey: Hashable, Sendable { w.writeLE(idiom) w.writeLE(subtype) w.writeLE(dimension2) + if withDimension1 { w.writeLE(dimension1) } w.writeLE(identifier) w.writeLE(element) w.writeLE(part) diff --git a/Sources/AssetKit/CAR/TVLEntry.swift b/Sources/AssetKit/CAR/TVLEntry.swift index f2ddb68..036175a 100644 --- a/Sources/AssetKit/CAR/TVLEntry.swift +++ b/Sources/AssetKit/CAR/TVLEntry.swift @@ -26,6 +26,9 @@ enum TVLEntry { /// Type 1004 (8-byte value): slice/scale pair. Reference is `(0, 1.0f)`. case sliceScale + /// Type 1004 with scale 0: what the app icon size index records carry. + case sliceScaleZero + /// Type 1006 (4-byte value): always 1 in the reference. Likely a /// bitmap-count / has-mipmap-stages flag. case bitmapFlag @@ -60,6 +63,11 @@ enum TVLEntry { w.writeLE(UInt32(8)) w.writeLE(UInt32(0)) w.writeLE(UInt32(Float(1).bitPattern)) + case .sliceScaleZero: + w.writeLE(UInt32(1004)) + w.writeLE(UInt32(8)) + w.writeLE(UInt32(0)) + w.writeLE(UInt32(0)) case .bitmapFlag: w.writeLE(UInt32(1006)) w.writeLE(UInt32(4)) diff --git a/Sources/AssetKit/Errors.swift b/Sources/AssetKit/Errors.swift index ebeedb7..a8ceafe 100644 --- a/Sources/AssetKit/Errors.swift +++ b/Sources/AssetKit/Errors.swift @@ -9,6 +9,8 @@ public enum XCAssetCompilerError: Error, Sendable, Equatable { case unsupportedGamut(String) case multipleAppIconSets([String]) case appIconSizeMissing(asset: String, size: String) + case appIconSourceSizeMismatch(asset: String, filename: String, expected: String, actual: String) + case unsupportedAppIconPlatform(asset: String, platform: String) case notADirectory(path: String) case unsupportedAssetType(String) case malformedJPEG(reason: String) @@ -36,6 +38,10 @@ extension XCAssetCompilerError: CustomStringConvertible { return "Catalog has more than one .appiconset: \(names.joined(separator: ", "))" case .appIconSizeMissing(let asset, let size): return "AppIcon '\(asset)' declares size \(size) but no source file matched" + case .appIconSourceSizeMismatch(let asset, let filename, let expected, let actual): + return "AppIcon '\(asset)' source file '\(filename)' is \(actual) but its entry declares \(expected)" + case .unsupportedAppIconPlatform(let asset, let platform): + return "AppIcon '\(asset)' targets platform '\(platform)'; only ios is supported" case .notADirectory(let path): return "Expected an .xcassets directory at \(path)" case .unsupportedAssetType(let name): diff --git a/Sources/AssetKit/Rendition/ImageRenderer.swift b/Sources/AssetKit/Rendition/ImageRenderer.swift index 05e6107..e8cf7ab 100644 --- a/Sources/AssetKit/Rendition/ImageRenderer.swift +++ b/Sources/AssetKit/Rendition/ImageRenderer.swift @@ -59,14 +59,18 @@ enum ImageRenderer { return out } - static func appIconRenditions(for appIcon: LoadedAppIcon, files: [IconFile]) throws -> [Rendition] { + static func appIconRenditions( + for appIcon: LoadedAppIcon, + files: [IconFile], + options: OutputOptions = .legacy + ) throws -> [Rendition] { var out: [Rendition] = [] for file in files { - let filename = file.sourceURL.lastPathComponent + let filename = file.sourceName guard SourceFormat.detect(filename: filename) == .png else { throw XCAssetCompilerError.unsupportedAppIconSource(asset: appIcon.name, filename: filename) } - let bytes = try Data(contentsOf: file.sourceURL) + let bytes = file.data let scale: Scale = { switch file.scale { case 1: return .x1 @@ -89,8 +93,45 @@ enum ImageRenderer { filename: filename, kind: .appIcon ) - out.append(contentsOf: try PNGSource.renditions(bytes: bytes, context: ctx)) + var renditions = try PNGSource.renditions(bytes: bytes, context: ctx) + for i in renditions.indices { + if case .bitmap(var body) = renditions[i].body { + body.iconIndex = iconIndex(idiom: file.idiom, pointSize: file.pointSize) + body.iconPoints = file.pointSize + renditions[i].body = .bitmap(body) + } + } + out.append(contentsOf: renditions) + // actool also stores the iPhone 60pt@3x icon as a 2x rendition at + // subtype 1792 (an iPhone 6 Plus class display that scales 3x down + // to 2x), with 90pt, i.e. 1.5x of 60, as its size. + if options.contains(.multisizeIcons), file.idiom == .iphone, file.pointSize == 60, file.scale == 3 { + for var copy in renditions { + copy.scale = .x2 + if case .bitmap(var body) = copy.body { + body.subtype = 1792 + body.iconIndex = 7 + body.iconPoints = 90 + copy.body = .bitmap(body) + } + out.append(copy) + } + } } return out } + + /// See `BitmapBody.iconIndex`. + private static func iconIndex(idiom: Idiom, pointSize: Double) -> UInt16 { + if idiom == .marketing { return 8 } + switch pointSize { + case 20: return 1 + case 29: return 2 + case 40: return 3 + case 60: return 4 + case 76: return 5 + case 83.5: return 6 + default: return 1 + } + } } diff --git a/Sources/AssetKit/Rendition/Rendition.swift b/Sources/AssetKit/Rendition/Rendition.swift index 2175002..99d77d2 100644 --- a/Sources/AssetKit/Rendition/Rendition.swift +++ b/Sources/AssetKit/Rendition/Rendition.swift @@ -41,6 +41,14 @@ struct BitmapBody: Sendable { /// classification (e.g. when re-rasterising via the preserved vector /// source at a non-intrinsic size). PNG / appicon bitmaps leave it false. var derivedFromVector: Bool = false + /// App icon sizes are told apart by the key's dimension2 slot (the "icon index"): + /// 1...6 for 20, 29, 40, 60, 76 and 83.5 points, 8 for the 1024-point store icon. + /// Matches an actool-built catalog; unused for other kinds. + var iconIndex: UInt16 = 1 + /// Rendition key subtype. 0 except for the iPhone 60pt@3x copy actool stores at 1792. + var subtype: UInt16 = 0 + /// App icons: the point size this rendition is for (83.5, 90, 1024...). + var iconPoints: Double = 0 /// The source filename (e.g. "icon@2x.png"). Stored in the CSI header's /// 128-char name field; actool uses the filename here, not the asset name. var renditionName: String diff --git a/Sources/AssetKit/Schema/Contents.swift b/Sources/AssetKit/Schema/Contents.swift index ac3271c..e60f602 100644 --- a/Sources/AssetKit/Schema/Contents.swift +++ b/Sources/AssetKit/Schema/Contents.swift @@ -104,12 +104,29 @@ struct ImageSetContents: Codable, Sendable { struct AppIconContents: Codable, Sendable { struct Image: Codable, Sendable { + /// Absent in the single-size format Xcode 14+ writes + /// (`{"platform": "ios", "size": "1024x1024"}`); decoded as `.universal`. var idiom: Idiom var size: String var scale: Scale? var filename: String? var role: String? var subtype: String? + var platform: String? + /// Dark / tinted variants (iOS 18+). Absent for the default ("Any") icon. + var appearances: [Appearance]? + + init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + idiom = try c.decodeIfPresent(Idiom.self, forKey: .idiom) ?? .universal + size = try c.decode(String.self, forKey: .size) + scale = try c.decodeIfPresent(Scale.self, forKey: .scale) + filename = try c.decodeIfPresent(String.self, forKey: .filename) + role = try c.decodeIfPresent(String.self, forKey: .role) + subtype = try c.decodeIfPresent(String.self, forKey: .subtype) + platform = try c.decodeIfPresent(String.self, forKey: .platform) + appearances = try c.decodeIfPresent([Appearance].self, forKey: .appearances) + } var pointSize: (Double, Double)? { let parts = size.split(separator: "x") @@ -118,6 +135,12 @@ struct AppIconContents: Codable, Sendable { let h = Double(parts[1]) else { return nil } return (w, h) } + + /// A single 1024x1024 master that actool expands into every size the + /// target needs: universal idiom, no scale (or 1x), no appearance. + var isSingleSizeMaster: Bool { + idiom == .universal && (scale ?? .x1) == .x1 && pointSize.map { $0 == (1024, 1024) } == true + } } var images: [Image] var info: CatalogContents.Info diff --git a/Sources/AssetKit/XCAssetCompiler.swift b/Sources/AssetKit/XCAssetCompiler.swift index 56beff6..bbf63c1 100644 --- a/Sources/AssetKit/XCAssetCompiler.swift +++ b/Sources/AssetKit/XCAssetCompiler.swift @@ -60,6 +60,39 @@ public struct LooseFile: Sendable { } } +/// Where the output departs from the minimal CoreUI 970 shape this library +/// first shipped, to look like what Xcode 26.5's actool writes. App Store +/// Connect leaves an upload in processing forever for an `Assets.car` it +/// cannot read, so each difference is individually switchable while it is +/// being narrowed down. +public struct OutputOptions: OptionSet, Sendable { + public let rawValue: Int + public init(rawValue: Int) { self.rawValue = rawValue } + + /// Ten-attribute `KEYFORMAT` with `Dimension1`, a matching slot in every + /// rendition key, and the matching `BITMAPKEYS` descriptor size. + public static let dimension1Key = OutputOptions(rawValue: 1 << 0) + /// Tool mimicry, off by default: CoreUI 975 and the Xcode 26.5 tool strings + /// in `CARHEADER` and `EXTENDED_METADATA`, which claim the file was + /// written by Xcode's actool. Only useful to test whether a consumer + /// checks them; by default the header names AssetKit. + public static let actoolVersionStrings = OutputOptions(rawValue: 1 << 1) + /// The app icon "multisize" index records (part 218), the extra + /// iPhone 60pt@3x rendition actool stores at subtype 1792, and + /// `BITMAPKEYS` idiom / icon-index masks. + public static let multisizeIcons = OutputOptions(rawValue: 1 << 2) + /// The `NameIdentifier` actool computes for `AppIcon` (6849) instead of + /// the CRC32-based one used for other names. + public static let actoolIdentifiers = OutputOptions(rawValue: 1 << 3) + + /// The original output of this library. + public static let legacy: OutputOptions = [] + /// The structure of actool 26.5's output, without claiming to be it. + public static let actoolStructure: OutputOptions = [.dimension1Key, .multisizeIcons, .actoolIdentifiers] + /// Everything, including the tool strings. + public static let actool26_5: OutputOptions = actoolStructure.union(.actoolVersionStrings) +} + public struct XCAssetCompiler: Sendable { public var deploymentTarget: String /// Strategy used to rasterise `.svg` sources to PNG bytes. Defaults to @@ -67,13 +100,16 @@ public struct XCAssetCompiler: Sendable { /// when you need a different rasteriser (no PATH dep, different /// performance profile, sandbox restrictions, etc). public var svgRasterizer: any SVGRasterizer + public var options: OutputOptions public init( deploymentTarget: String, - svgRasterizer: any SVGRasterizer = RsvgConvertRasterizer() + svgRasterizer: any SVGRasterizer = RsvgConvertRasterizer(), + options: OutputOptions = .actoolStructure ) { self.deploymentTarget = deploymentTarget self.svgRasterizer = svgRasterizer + self.options = options } public func compile(catalog catalogURL: URL) async throws -> CompileResult { @@ -95,14 +131,21 @@ public struct XCAssetCompiler: Sendable { var appIconBundle: AppIconBundle? if let appIcon = loaded.appIcon { let plist = try AppIconPlistEmitter.emit(appIcon) - renditions.append(contentsOf: try ImageRenderer.appIconRenditions(for: appIcon, files: plist.iconFiles)) + renditions.append(contentsOf: try ImageRenderer.appIconRenditions( + for: appIcon, + files: plist.iconFiles, + options: options + )) var looseFiles: [LooseFile] = [] + var seen: Set = [] for file in plist.iconFiles { let suffix = file.scale == 1 ? "" : "@\(file.scale)x" let target = "\(file.outputName)\(suffix).png" - let data = try Data(contentsOf: file.sourceURL) - looseFiles.append(LooseFile(name: target, data: data)) + // iPhone and iPad entries can share a name (and, when generated, pixels). + if seen.insert(target).inserted { + looseFiles.append(LooseFile(name: target, data: file.data)) + } } appIconBundle = AppIconBundle( @@ -112,7 +155,7 @@ public struct XCAssetCompiler: Sendable { ) } - let writer = CARWriter(deploymentTarget: deploymentTarget, renditions: renditions) + let writer = CARWriter(deploymentTarget: deploymentTarget, renditions: renditions, options: options) let bytes = try writer.write() return CompileResult(carData: bytes, appIconBundle: appIconBundle) diff --git a/Tests/AssetKitTests/ActoolShapeTests.swift b/Tests/AssetKitTests/ActoolShapeTests.swift new file mode 100644 index 0000000..804f13c --- /dev/null +++ b/Tests/AssetKitTests/ActoolShapeTests.swift @@ -0,0 +1,139 @@ +import Foundation +import PNG +import Testing +@testable import AssetKit + +@Suite("actool 26.5 output shape") +struct ActoolShapeTests { + /// iPhone 20/29/40/60, iPad 20/29/40/76/83.5 and the store icon, like Tauri's catalog. + private func makeCatalog() throws -> URL { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("Shape-\(UUID().uuidString).xcassets", isDirectory: true) + let set = root.appendingPathComponent("AppIcon.appiconset", isDirectory: true) + try FileManager.default.createDirectory(at: set, withIntermediateDirectories: true) + let png = tinyPNG() + try png.write(to: set.appendingPathComponent("icon.png")) + func entry(_ idiom: String, _ size: String, _ scale: String) -> String { + #"{ "filename": "icon.png", "idiom": "\#(idiom)", "scale": "\#(scale)", "size": "\#(size)" }"# + } + let images = [ + entry("iphone", "20x20", "2x"), entry("iphone", "20x20", "3x"), + entry("iphone", "29x29", "2x"), entry("iphone", "29x29", "3x"), + entry("iphone", "40x40", "2x"), entry("iphone", "40x40", "3x"), + entry("iphone", "60x60", "2x"), entry("iphone", "60x60", "3x"), + entry("ipad", "20x20", "1x"), entry("ipad", "29x29", "1x"), entry("ipad", "40x40", "1x"), + entry("ipad", "76x76", "1x"), entry("ipad", "76x76", "2x"), entry("ipad", "83.5x83.5", "2x"), + entry("ios-marketing", "1024x1024", "1x"), + ] + let json = #"{ "images": [\#(images.joined(separator: ","))], "info": { "author": "xcode", "version": 1 } }"# + try Data(json.utf8).write(to: set.appendingPathComponent("Contents.json")) + return root + } + + private func compile(_ options: OutputOptions) async throws -> CARInspector { + let catalog = try makeCatalog() + defer { try? FileManager.default.removeItem(at: catalog) } + let result = try await XCAssetCompiler(deploymentTarget: "17.0", options: options).compile(catalog: catalog) + return CARInspector(result.carData) + } + + @Test("legacy output keeps the nine-attribute key format") + func legacy() async throws { + let car = try await compile(.legacy) + #expect(car.keyFormat == [7, 13, 12, 15, 16, 9, 17, 1, 2]) + #expect(car.renditions.allSatisfy { $0.key.count == 9 }) + #expect(car.header?.coreUI == 970) + #expect(car.renditions.allSatisfy { $0.layout == 12 }) + } + + @Test("Dimension1 adds a tenth attribute to the key format and every key") + func dimension1() async throws { + let car = try await compile(.dimension1Key) + #expect(car.keyFormat == [7, 13, 12, 15, 16, 9, 8, 17, 1, 2]) + #expect(car.renditions.allSatisfy { $0.key.count == 10 && $0.key[6] == 0 }) + #expect(car.header?.coreUI == 970) + let bitmapKeys = car.treeEntries("BITMAPKEYS") + #expect(bitmapKeys.count == 1) + #expect(bitmapKeys[0].value.count == 56) + #expect(u32(bitmapKeys[0].value, 8) == 0x2c && u32(bitmapKeys[0].value, 12) == 10) + } + + @Test("Version strings follow Xcode 26.5") + func versionStrings() async throws { + let car = try await compile(.actoolVersionStrings) + let header = try #require(car.header) + #expect(header.coreUI == 975) + #expect(header.main == "@(#)PROGRAM:CoreUI PROJECT:CoreUI-975") + #expect(header.version == "Xcode 26.5 (17F42) via AssetCatalogSimulatorAgent") + let metadata = try #require(car.variable("EXTENDED_METADATA")) + #expect(String(decoding: metadata, as: UTF8.self).contains("CoreThemeDefinition-653.4")) + } + + @Test("The default does not claim to be Xcode") + func defaultIsHonest() async throws { + let catalog = try makeCatalog() + defer { try? FileManager.default.removeItem(at: catalog) } + let result = try await XCAssetCompiler(deploymentTarget: "17.0").compile(catalog: catalog) + let car = CARInspector(result.carData) + let header = try #require(car.header) + #expect(header.coreUI == 970) + #expect(header.version == "AssetKit") + #expect(car.keyFormat.count == 10) + #expect(car.renditions.contains { $0.key[9] == 218 }) + let metadata = try #require(car.variable("EXTENDED_METADATA")) + #expect(!String(decoding: metadata, as: UTF8.self).contains("Xcode")) + } + + @Test("Full actool shape: size index records, subtype 1792 copy, masks, AppIcon identifier") + func fullShape() async throws { + let car = try await compile(.actoolStructure) + let renditions = car.renditions + // 15 files + the 60pt@3x copy + 4 index records (iPhone, iPhone 1792, iPad, store) + #expect(renditions.count == 20) + #expect(car.header?.renditionCount == 20) + #expect(Set(renditions.map(\.key)).count == renditions.count) + + // key = appearance, localization, scale, idiom, subtype, dim2, dim1, identifier, element, part + let identifier: UInt16 = 6849 + let records = renditions.filter { $0.key[9] == 218 } + #expect(records.count == 4) + #expect(records.allSatisfy { $0.layout == 1010 && $0.key[7] == identifier && $0.key[2] == 1 }) + + func sizes(idiom: UInt16, subtype: UInt16) throws -> [[UInt32]] { + let record = try #require(records.first { $0.key[3] == idiom && $0.key[4] == subtype }) + let body = record.body + #expect(String(decoding: body.prefix(4), as: UTF8.self) == "SISM") + let count = Int(u32(body, 8)) + return (0.. Data { + let rgba = [PNG.RGBA](repeating: PNG.RGBA(10, 20, 30, 255), count: 16) + let image = PNG.Image( + packing: rgba, + size: (x: 4, y: 4), + layout: PNG.Layout(format: .rgba8(palette: [], fill: nil)) + ) + var stream = MemoryBytestreamDestination() + try! image.compress(stream: &stream) + return Data(stream.bytes) +} diff --git a/Tests/AssetKitTests/Helpers/CARInspector.swift b/Tests/AssetKitTests/Helpers/CARInspector.swift new file mode 100644 index 0000000..8d30d85 --- /dev/null +++ b/Tests/AssetKitTests/Helpers/CARInspector.swift @@ -0,0 +1,108 @@ +import Foundation +@testable import AssetKit + +/// Minimal read-only view of a compiled `Assets.car`: enough to check the +/// shape of what the writer emits (there is no `assetutil` outside macOS). +struct CARInspector { + struct Rendition { + var key: [UInt16] + var csi: Data + + var layout: UInt16 { u16(csi, 36) } + var name: String { + let bytes = csi[csi.startIndex + 40.. Data { + let b = blocks[index] + return data[b.offset.. Data? { + variables[name].map(block) + } + + /// (key block, value block) pairs of the single leaf of a tree variable. + func treeEntries(_ name: String) -> [(key: Data, value: Data)] { + guard let tree = variable(name) else { return [] } + let leaf = block(Int(be32(tree, 8))) + let count = Int(be16(leaf, 2)) + let inlineKeys = tree[tree.startIndex + 20] != 0 + return (0..> 8) & 0xff), UInt8((key >> 16) & 0xff), UInt8(key >> 24)]) : block(key) + return (keyData, block(value)) + } + } + + var keyFormat: [UInt32] { + guard let kfmt = variable("KEYFORMAT") else { return [] } + let n = Int(u32(kfmt, 8)) + return (0.. String { + String(decoding: h[h.startIndex + from.. UInt32 { + (0..<4).reduce(UInt32(0)) { ($0 << 8) | UInt32(d[d.startIndex + o + $1]) } +} +private func be16(_ d: Data, _ o: Int) -> UInt16 { + (UInt16(d[d.startIndex + o]) << 8) | UInt16(d[d.startIndex + o + 1]) +} +func u32(_ d: Data, _ o: Int) -> UInt32 { + (0..<4).reduce(UInt32(0)) { $0 | (UInt32(d[d.startIndex + o + $1]) << (8 * UInt32($1))) } +} +func u16(_ d: Data, _ o: Int) -> UInt16 { + UInt16(d[d.startIndex + o]) | (UInt16(d[d.startIndex + o + 1]) << 8) +} diff --git a/Tests/AssetKitTests/SingleSizeAppIconTests.swift b/Tests/AssetKitTests/SingleSizeAppIconTests.swift new file mode 100644 index 0000000..f1168ef --- /dev/null +++ b/Tests/AssetKitTests/SingleSizeAppIconTests.swift @@ -0,0 +1,146 @@ +import Foundation +import PNG +import Testing +@testable import AssetKit + +@Suite("Single-size AppIcon") +struct SingleSizeAppIconTests { + @Test("Xcode 14+ single 1024 universal icon expands to the iPhone, iPad and store sizes") + func expandsMaster() async throws { + let catalog = try makeCatalog(entries: [ + #"{ "filename": "icon.png", "idiom": "universal", "platform": "ios", "size": "1024x1024" }"#, + ], master: solidPNG(size: 1024, rgba: (3, 246, 254, 255))) + defer { try? FileManager.default.removeItem(at: catalog) } + + let result = try await XCAssetCompiler(deploymentTarget: "17.0").compile(catalog: catalog) + #expect(result.carData.prefix(8) == Data("BOMStore".utf8)) + + // every generated rendition has a distinct key (the icon index tells sizes apart) + let appIcon = try loadAppIcon(at: catalog) + let renditions = try ImageRenderer.appIconRenditions( + for: appIcon, + files: AppIconPlistEmitter.emit(appIcon).iconFiles + ) + #expect(renditions.count == 18) + #expect(Set(renditions.map { RenditionKey(rendition: $0).encode() }).count == renditions.count) + + let bundle = try #require(result.appIconBundle) + #expect(bundle.primaryIconName == "AppIcon") + let icons = bundle.infoPlistAdditions["CFBundleIcons"] as? [String: any Sendable] + let primary = icons?["CFBundlePrimaryIcon"] as? [String: any Sendable] + #expect(primary?["CFBundleIconFiles"] as? [String] == [ + "AppIcon20x20", "AppIcon29x29", "AppIcon40x40", "AppIcon60x60", + ]) + let ipad = bundle.infoPlistAdditions["CFBundleIcons~ipad"] as? [String: any Sendable] + let ipadPrimary = ipad?["CFBundlePrimaryIcon"] as? [String: any Sendable] + #expect((ipadPrimary?["CFBundleIconFiles"] as? [String])?.contains("AppIcon83.5x83.5") == true) + + // names are unique and each file has the pixel size its name promises + let names = bundle.looseFiles.map(\.name) + #expect(Set(names).count == names.count) + let expected: [String: Int] = [ + "AppIcon60x60@2x.png": 120, "AppIcon60x60@3x.png": 180, "AppIcon76x76@2x.png": 152, + "AppIcon83.5x83.5@2x.png": 167, "AppIcon20x20.png": 20, "AppIcon1024x1024.png": 1024, + ] + for (name, pixels) in expected { + let file = try #require(bundle.looseFiles.first { $0.name == name }, "missing \(name)") + let decoded = try PNGResizer.decode(file.data) + #expect(decoded.width == pixels && decoded.height == pixels, "\(name) is \(decoded.width)") + } + } + + @Test("Dark and tinted variants are skipped, not compiled as the default icon") + func appearanceVariantsAreSkipped() throws { + // the variants point at files that do not exist: they must not even be read + let catalog = try makeCatalog(entries: [ + #"{ "filename": "icon.png", "idiom": "iphone", "scale": "2x", "size": "60x60" }"#, + #""" + { "appearances": [{ "appearance": "luminosity", "value": "dark" }], + "filename": "dark.png", "idiom": "iphone", "scale": "2x", "size": "60x60" } + """#, + #""" + { "appearances": [{ "appearance": "luminosity", "value": "tinted" }], + "filename": "tinted.png", "idiom": "iphone", "scale": "2x", "size": "60x60" } + """#, + ], master: solidPNG(size: 120, rgba: (1, 2, 3, 255))) + defer { try? FileManager.default.removeItem(at: catalog) } + + let appIcon = try loadAppIcon(at: catalog) + #expect(try AppIconPlistEmitter.emit(appIcon).iconFiles.count == 1) + } + + @Test("A master that is not 1024x1024 is rejected") + func wrongSizeThrows() throws { + let catalog = try makeCatalog(entries: [ + #"{ "filename": "icon.png", "idiom": "universal", "platform": "ios", "size": "1024x1024" }"#, + ], master: solidPNG(size: 64, rgba: (1, 2, 3, 255))) + defer { try? FileManager.default.removeItem(at: catalog) } + + let appIcon = try loadAppIcon(at: catalog) + #expect(throws: XCAssetCompilerError.self) { _ = try AppIconPlistEmitter.emit(appIcon) } + } + + @Test("A non-iOS platform is rejected") + func otherPlatformThrows() throws { + let catalog = try makeCatalog(entries: [ + #"{ "filename": "icon.png", "idiom": "universal", "platform": "watchos", "size": "1024x1024" }"#, + ], master: solidPNG(size: 16, rgba: (1, 2, 3, 255))) + defer { try? FileManager.default.removeItem(at: catalog) } + + let appIcon = try loadAppIcon(at: catalog) + #expect(throws: XCAssetCompilerError.unsupportedAppIconPlatform(asset: "AppIcon", platform: "watchos")) { + _ = try AppIconPlistEmitter.emit(appIcon) + } + } + + @Test("Downscaling averages instead of sampling, and keeps transparency") + func resizeAverages() throws { + // left half white, right half black, both opaque; 2x2 blocks average to grey at the seam only + var rgba = [PNG.RGBA]() + for _ in 0..<4 { rgba += [PNG.RGBA(255, 255, 255, 255), PNG.RGBA(0, 0, 0, 255), PNG.RGBA(255, 255, 255, 0), PNG.RGBA(0, 0, 0, 0)] } + let png = try encode(rgba, size: 4) + let decoded = try PNGResizer.decode(png) + let small = try PNGResizer.decode(PNGResizer.resize(decoded, width: 2, height: 2)) + // top-left output pixel covers white + black opaque: premultiplied average is 127.5 + #expect(abs(small.pixels[0] - 127.5) < 1) + #expect(small.pixels[3] == 255) + // top-right covers fully transparent pixels + #expect(small.pixels[7] == 0) + } +} + +private func loadAppIcon(at catalog: URL) throws -> LoadedAppIcon { + let directory = catalog.appendingPathComponent("AppIcon.appiconset") + let contents = try JSONDecoder().decode( + AppIconContents.self, + from: Data(contentsOf: directory.appendingPathComponent("Contents.json")) + ) + return LoadedAppIcon(name: "AppIcon", directory: directory, contents: contents) +} + +private func makeCatalog(entries: [String], master: Data) throws -> URL { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("SingleSize-\(UUID().uuidString).xcassets") + let set = root.appendingPathComponent("AppIcon.appiconset") + try FileManager.default.createDirectory(at: set, withIntermediateDirectories: true) + try master.write(to: set.appendingPathComponent("icon.png")) + let json = #"{ "images": [\#(entries.joined(separator: ","))], "info": { "author": "xcode", "version": 1 } }"# + try Data(json.utf8).write(to: set.appendingPathComponent("Contents.json")) + return root +} + +private func solidPNG(size: Int, rgba: (UInt8, UInt8, UInt8, UInt8)) -> Data { + let pixel = PNG.RGBA(rgba.0, rgba.1, rgba.2, rgba.3) + // swiftlint-free force try: a failure here is a broken test helper + return try! encode([PNG.RGBA](repeating: pixel, count: size * size), size: size) +} + +private func encode(_ rgba: [PNG.RGBA], size: Int) throws -> Data { + let image = PNG.Image( + packing: rgba, + size: (x: size, y: rgba.count / size), + layout: PNG.Layout(format: .rgba8(palette: [], fill: nil)) + ) + var stream = MemoryBytestreamDestination() + try image.compress(stream: &stream) + return Data(stream.bytes) +} diff --git a/docs/coreui-970-format.md b/docs/coreui-970-format.md index bdc2e24..77dc8ce 100644 --- a/docs/coreui-970-format.md +++ b/docs/coreui-970-format.md @@ -238,6 +238,30 @@ This writer's `NameIdentifier` is `CRC32-IEEE(name) & 0xFFFF`, whereas `actool`' Imagesets have no such fallback. This is why divergences #4-6 above gate `UIImage(named:)` for image assets — there's no second chance. +## App icons: what actool emits, and what is still unverified + +Observed in a catalog compiled by Xcode 26.5 from a multi-size `.appiconset` (iPhone and iPad 20/29/40/60/76/83.5 pt plus a 1024 px store icon), dumped without `assetutil`: + +- One bitmap rendition (`element=85`, `part=220`) per source file, named after the file (`AppIcon-60x60@2x.png`), not after the set. +- The `dimension2` slot is the icon index: 1, 2, 3, 4, 5, 6 for 20, 29, 40, 60, 76, 83.5 pt, and 8 for the store icon (`idiom=6`, `ios-marketing`). This writer follows that mapping, so icons of the same idiom and scale no longer collide on one key. +- Additional `part=218` records named `AppIcon` with no pixel data (one per scale / idiom / subtype). This writer does not emit them. +- The loose PNGs next to `Assets.car` are only `AppIcon60x60@2x.png` and `AppIcon76x76@2x~ipad.png`, with `CFBundleIconFiles` limited to those names plus `CFBundleIconName`. This writer emits every size, without the `~ipad` suffix. +- That catalog's `KEYFORMAT` has ten tokens (attribute 8 sits between `dimension2` and `identifier`), against nine here. + +Single-size icons (`{"platform": "ios", "size": "1024x1024"}`) are handled by generating the same per-size set from the master (area-averaged downscale), then going through the multi-size path. Whether actool emits the same renditions for a single-size source (it probably does, for the sizes the deployment target needs) has not been checked against actool output. Dark and tinted entries are skipped. + +To settle it on a Mac, compile a single-size catalog and compare: + +```sh +xcrun actool --compile out --platform iphoneos --minimum-deployment-target 17.0 \ + --app-icon AppIcon --output-partial-info-plist out/partial.plist \ + --output-format human-readable-text Single.xcassets +xcrun assetutil --info out/Assets.car | jq '.[] | {Name, RenditionName, Idiom, Scale, Appearance, PixelWidth}' +cat out/partial.plist; ls out +``` + +Run it once with the default icon only and once with dark and tinted images added, and compare the rendition list, `Appearance` values and the partial plist with this writer's output. + ## Workflow: generating a fresh `actool` reference When changing any CoreUI block-emitting code (`CAR/*.swift`, `BOM/*.swift`), the durable safety net is to generate a reference Assets.car with `actool` and compare bytes.