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
2 changes: 1 addition & 1 deletion Sources/AssetKit/CAR/BitmapKeys.swift
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ enum BitmapKeys {
/// (say) preserved JPG would be misclassified as `.image` here.
private static func inferKind(from renditions: [Rendition]) -> Descriptor.Kind {
for rendition in renditions {
if case .bitmap(let body) = rendition.body, body.kind == .appIcon {
if case .bitmap(let body) = rendition.body, case .appIcon = body.kind {
return .appIcon
}
}
Expand Down
8 changes: 3 additions & 5 deletions Sources/AssetKit/CAR/RenditionKey.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,10 @@ struct RenditionKey: Hashable, Sendable {
case .bitmap(let body):
self.element = Element.bitmap.rawValue
switch body.kind {
case .appIcon:
case .appIcon(let index):
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.
self.dimension2 = index
case .image:
self.part = Part.image.rawValue
// Generic image assets don't use Dimension2 at all.
Expand Down
6 changes: 5 additions & 1 deletion Sources/AssetKit/Rendition/ImageRenderer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ enum ImageRenderer {
}

static func appIconRenditions(for appIcon: LoadedAppIcon, files: [IconFile]) throws -> [Rendition] {
let pointSizes = Set(files.map(\.pointSize)).sorted()
let iconIndices = Dictionary(uniqueKeysWithValues: pointSizes.enumerated().map {
($0.element, UInt16($0.offset + 1))
})
var out: [Rendition] = []
for file in files {
let filename = file.sourceURL.lastPathComponent
Expand Down Expand Up @@ -87,7 +91,7 @@ enum ImageRenderer {
appearance: nil,
gamut: .sRGB,
filename: filename,
kind: .appIcon
kind: .appIcon(index: iconIndices[file.pointSize]!)
)
out.append(contentsOf: try PNGSource.renditions(bytes: bytes, context: ctx))
}
Expand Down
5 changes: 3 additions & 2 deletions Sources/AssetKit/Rendition/Rendition.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ struct BitmapBody: Sendable {
/// value -- actool picks different codes for appicons vs. generic images,
/// and UIImage(named:) only finds renditions whose part matches the
/// expected category for the lookup path.
enum Kind: Sendable {
enum Kind: Sendable, Equatable {
/// `element=85, part=220`. Used by SpringBoard's icon-render pipeline.
case appIcon
/// The index distinguishes logical point sizes across scales and idioms.
case appIcon(index: UInt16)
/// `element=85, part=181`. Used by UIImage(named:) for generic image
/// assets from an `.imageset`.
case image
Expand Down
75 changes: 75 additions & 0 deletions Tests/AssetKitTests/AppIconRenditionTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import Foundation
import Testing
@testable import AssetKit

@Suite("App icon rendition keys")
struct AppIconRenditionTests {
@Test("Multiple logical icon sizes have distinct encoded CAR keys")
func multipleSizes() async throws {
let catalog = FileManager.default.temporaryDirectory
.appendingPathComponent("icons-\(UUID().uuidString).xcassets", isDirectory: true)
defer { try? FileManager.default.removeItem(at: catalog) }
try MultiSizeAppIconFixture.write(to: catalog)

let result = try await XCAssetCompiler(deploymentTarget: "17.0").compile(catalog: catalog)
let entries = try renditionEntries(in: result.carData)
#expect(entries.count == MultiSizeAppIconFixture.entries.count)
#expect(Set(entries.map(\.key)).count == entries.count, "duplicate RENDITIONS keys hide icon sizes")
for (key, width) in entries {
let points = Double(width) / Double(key.scale)
#expect(key.dimension2 == MultiSizeAppIconFixture.indices[points])
#expect(key.element == 85)
#expect(key.part == 220)
}
}

@Test("A single logical icon size keeps index 1 and images keep index 0")
func singleSize() async throws {
let catalog = try #require(Bundle.module.url(
forResource: "Test", withExtension: "xcassets", subdirectory: "Fixtures"
))
let result = try await XCAssetCompiler(
deploymentTarget: "16.0", svgRasterizer: StubSVGRasterizer()
).compile(catalog: catalog)
let entries = try renditionEntries(in: result.carData)
let icons = entries.filter { $0.key.part == 220 }
#expect(icons.count == 2)
#expect(icons.allSatisfy { $0.key.dimension2 == 1 })
let images = entries.filter { $0.key.part == 181 }
#expect(!images.isEmpty)
#expect(images.allSatisfy { $0.key.dimension2 == 0 })
}

private func renditionEntries(in data: Data) throws -> [(key: RenditionKey, width: UInt32)] {
func u32(_ bytes: Data, _ offset: Int) -> UInt32 {
bytes.withUnsafeBytes { UInt32(bigEndian: $0.loadUnaligned(fromByteOffset: offset, as: UInt32.self)) }
}
let index = Int(u32(data, 0x10))
func block(_ id: UInt32) -> Data {
let entry = index + 4 + Int(id) * 8
let start = Int(u32(data, entry))
return data.subdata(in: start..<(start + Int(u32(data, entry + 4))))
}
let variables = Int(u32(data, 0x18))
var cursor = variables + 4
var tree: Data?
for _ in 0..<u32(data, variables) {
let id = u32(data, cursor)
let length = Int(data[cursor + 4])
let name = String(decoding: data[(cursor + 5)..<(cursor + 5 + length)], as: UTF8.self)
if name == "RENDITIONS" { tree = block(id) }
cursor += 5 + length
}
let header = try #require(tree)
let leaf = block(u32(header, 8))
let count = Int(leaf[2]) << 8 | Int(leaf[3])
return try (0..<count).map { i in
let value = block(u32(leaf, 12 + i * 8))
let key = try #require(RenditionKey.decode(block(u32(leaf, 16 + i * 8))))
let width = value.withUnsafeBytes {
UInt32(littleEndian: $0.loadUnaligned(fromByteOffset: 12, as: UInt32.self))
}
return (key, width)
}
}
}
29 changes: 29 additions & 0 deletions Tests/AssetKitTests/AssetutilParseTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ struct AssetutilParseTests {
for (i, rendition) in renditions.enumerated() {
#expect(rendition["Idiom"] as? String == "phone", "rendition[\(i)] idiom")
#expect(rendition["Name"] as? String == "AppIcon", "rendition[\(i)] name")
#expect(rendition["Icon Index"] as? Int == 1, "rendition[\(i)] icon index")
#expect(rendition["Encoding"] as? String == "ARGB", "rendition[\(i)] encoding")
#expect(rendition["BitsPerComponent"] as? Int == 8, "rendition[\(i)] BitsPerComponent")
#expect(rendition["ColorModel"] as? String == "RGB", "rendition[\(i)] ColorModel")
Expand All @@ -85,6 +86,34 @@ struct AssetutilParseTests {
#expect(threeX?["RenditionName"] as? String == "icon@3x.png")
}

@Test(
"assetutil reports distinct icon indices for multiple logical sizes",
.enabled(if: ProcessLauncher.isAvailable)
)
func parsesMultipleIconSizes() async throws {
let scratch = FileManager.default.temporaryDirectory
.appendingPathComponent("xcasset-icons-\(UUID().uuidString)", isDirectory: true)
defer { try? FileManager.default.removeItem(at: scratch) }
let catalog = scratch.appendingPathComponent("Test.xcassets", isDirectory: true)
try MultiSizeAppIconFixture.write(to: catalog)
let result = try await XCAssetCompiler(deploymentTarget: "17.0").compile(catalog: catalog)
let carURL = scratch.appendingPathComponent("Assets.car")
try result.carData.write(to: carURL)
let invocation = try ProcessLauncher.run(
executable: "/usr/bin/xcrun", arguments: ["assetutil", "--info", carURL.path]
)
#expect(invocation.exitCode == 0, "assetutil stderr: \(String(decoding: invocation.stderr, as: UTF8.self))")
let entries = try #require(JSONSerialization.jsonObject(with: invocation.stdout) as? [[String: Any]])
let icons = entries.filter { $0["AssetType"] as? String == "Icon Image" }
#expect(icons.count == MultiSizeAppIconFixture.entries.count)
for icon in icons {
let width = try #require(icon["PixelWidth"] as? Double)
let scale = try #require(icon["Scale"] as? Double)
let expected = try #require(MultiSizeAppIconFixture.indices[width / scale])
#expect(icon["Icon Index"] as? Int == Int(expected))
}
}

private func assertHeader(_ header: [String: Any]?) throws {
guard let header else {
Issue.record("assetutil output missing header entry")
Expand Down
2 changes: 1 addition & 1 deletion Tests/AssetKitTests/CSIWriterTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ struct CSIWriterTests {
width: 60, height: 60,
pixelsBGRA: [UInt8](repeating: 0, count: 60 * 60 * 4),
colorSpaceID: 1,
kind: .appIcon,
kind: .appIcon(index: 1),
renditionName: "icon@2x.png"
)
let data = CSIWriter.bitmap(name: "AppIcon", body: body, scaleFactor: 200)
Expand Down
38 changes: 38 additions & 0 deletions Tests/AssetKitTests/Helpers/MultiSizeAppIconFixture.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import Foundation
@testable import AssetKit

enum MultiSizeAppIconFixture {
// actool orders logical sizes independently of source order, scale and idiom.
static let indices: [Double: UInt16] = [20: 1, 29: 2, 40: 3, 60: 4, 76: 5, 83.5: 6]
static let entries: [(Idiom, Double, Scale)] = [
(.iphone, 60, .x2), (.ipad, 20, .x1), (.iphone, 29, .x2),
(.iphone, 40, .x3), (.iphone, 20, .x2), (.iphone, 60, .x3),
(.iphone, 40, .x2), (.ipad, 20, .x2), (.ipad, 29, .x2),
(.ipad, 76, .x2), (.ipad, 83.5, .x2),
]

static func write(to catalog: URL) throws {
let directory = catalog.appendingPathComponent("AppIcon.appiconset", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
let info = CatalogContents.Info(version: 1, author: "xcode")
try JSONEncoder().encode(CatalogContents(info: info))
.write(to: catalog.appendingPathComponent("Contents.json"))

let rasterizer = StubSVGRasterizer()
var images: [AppIconContents.Image] = []
for (idiom, points, scale) in entries {
let filename = "\(idiom.rawValue)-\(points)@\(scale.rawValue).png"
let pixels = UInt32(points * Double(scale.factor))
try rasterizer.rasterize(svgData: Data(), pixelWidth: pixels, pixelHeight: pixels)
.write(to: directory.appendingPathComponent(filename))
images.append(AppIconContents.Image(
idiom: idiom,
size: "\(points)x\(points)",
scale: scale,
filename: filename
))
}
try JSONEncoder().encode(AppIconContents(images: images, info: info))
.write(to: directory.appendingPathComponent("Contents.json"))
}
}