Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
120 changes: 99 additions & 21 deletions Sources/AssetKit/AppIcon/AppIconPlist.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -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:
Expand Down Expand Up @@ -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 {
Expand Down
121 changes: 121 additions & 0 deletions Sources/AssetKit/AppIcon/PNGResizer.swift
Original file line number Diff line number Diff line change
@@ -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..<offset + count])
}
}

private struct MemoryDestination: PNG.BytestreamDestination {
var bytes: [UInt8] = []
mutating func write(_ data: [UInt8]) -> 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<UInt8>] = image.unpack(as: PNG.RGBA<UInt8>.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<UInt8>](repeating: PNG.RGBA<UInt8>(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<UInt8>(
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..<dstCount {
let start = Double(d) * ratio
let end = start + ratio
let first = Int(start)
let last = min(srcCount - 1, Int(end.nextDown))
for line in 0..<outer {
var r = 0.0, g = 0.0, b = 0.0, a = 0.0
for s in first...last {
let weight = min(end, Double(s + 1)) - max(start, Double(s))
let base = line * srcOuterStep + s * srcStep
r += Double(src[base]) * weight
g += Double(src[base + 1]) * weight
b += Double(src[base + 2]) * weight
a += Double(src[base + 3]) * weight
}
let out = line * dstOuterStep + d * dstStep
dst[out] = Float(r / ratio)
dst[out + 1] = Float(g / ratio)
dst[out + 2] = Float(b / ratio)
dst[out + 3] = Float(a / ratio)
}
}
}
}
return dst
}
}
7 changes: 3 additions & 4 deletions Sources/AssetKit/CAR/RenditionKey.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,9 @@ struct RenditionKey: Hashable, Sendable {
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.
Expand Down
6 changes: 6 additions & 0 deletions Sources/AssetKit/Errors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand Down
27 changes: 24 additions & 3 deletions Sources/AssetKit/Rendition/ImageRenderer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,11 @@ enum ImageRenderer {
static func appIconRenditions(for appIcon: LoadedAppIcon, files: [IconFile]) 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
Expand All @@ -89,8 +89,29 @@ 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)
renditions[i].body = .bitmap(body)
}
}
out.append(contentsOf: renditions)
}
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
}
}
}
4 changes: 4 additions & 0 deletions Sources/AssetKit/Rendition/Rendition.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ 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
/// 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
Expand Down
Loading