Skip to content
Draft
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
17 changes: 17 additions & 0 deletions Documentation/xtool.docc/Control.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,23 @@ iconPath: Resources/AppIcon.png
>
> Your app icon must be a png, and it should ideally have a resolution of 1024x1024px.

## Add an asset catalog

To use an Xcode asset catalog (`.xcassets`), which can hold images, colors and the app icon, add it to `xtool.yml`:

```yaml
assetCatalogs:
- Resources/Assets.xcassets
```

xtool compiles the catalog into `Assets.car` in the app bundle, so `Image("Logo", bundle: .main)` and `Color("Brand", bundle: .main)` work as usual. If the catalog contains an `AppIcon.appiconset`, xtool also adds the matching `CFBundleIcons` and `CFBundleIconName` keys to your `Info.plist`, and ignores `iconPath`.

Extensions can have their own catalog via an `assetCatalogs` key on the extension entry. Each app or extension supports one catalog.

> Note:
>
> xtool compiles catalogs itself, so it works on Linux. It supports PNG, JPEG and SVG images (SVG needs `rsvg-convert` installed), colors, and app icons with per-size entries. Single-size (1024x1024 "universal") app icons are supported, but their dark and tinted variants are ignored. PDF vectors, data sets, sticker packs and other specialized asset types are not supported. When you generate an Xcode project with `xtool dev generate-xcode-project`, the catalog is passed to Xcode unchanged.

## Add entitlements

You may need to add special [entitlements](https://developer.apple.com/documentation/bundleresources/entitlements) to your app, for example you need the `com.apple.developer.homekit` entitlement in order to connect to HomeKit devices.
Expand Down
26 changes: 26 additions & 0 deletions Package.resolved

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ let package = Package(
.package(url: "https://github.com/xtool-org/SwiftyMobileDevice", .upToNextMinor(from: "1.7.0")),
.package(url: "https://github.com/xtool-org/zsign", .upToNextMinor(from: "1.9.0")),
.package(url: "https://github.com/xtool-org/xadi", .upToNextMinor(from: "0.4.2")),
// TODO: temporary, points at the branch of xtool-org/AssetKit#2. Switch to
// .upToNextMinor(from: "<tag>") once AssetKit tags a release including it.
.package(url: "https://github.com/TartanLeGrand/AssetKit", revision: "90281d6dc0c4edef6176f9283283271198e4bafd"),

.package(url: "https://github.com/apple/swift-system", from: "1.4.0"),
.package(url: "https://github.com/apple/swift-http-types", from: "1.3.1"),
Expand Down Expand Up @@ -167,6 +170,9 @@ let package = Package(
"XToolSupport",
"PackLib",
],
resources: [
.copy("Fixtures"),
],
swiftSettings: swiftSettings,
),
.target(
Expand Down Expand Up @@ -195,6 +201,7 @@ let package = Package(
dependencies: [
"XUtils",
"XcodeProjects",
.product(name: "AssetKit", package: "AssetKit"),
.product(name: "Superutils", package: "xtool-core"),
.product(name: "Yams", package: "Yams"),
.product(name: "XcodeProjectFormat", package: "xcode-project-format"),
Expand Down
7 changes: 7 additions & 0 deletions Sources/PackLib/PackSchema.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public struct PackSchemaBase: Codable, Sendable {

public var iconPath: String?
public var resources: [String]?
public var assetCatalogs: [String]?

public var extensions: [Extension]?

Expand All @@ -30,6 +31,7 @@ public struct PackSchemaBase: Codable, Sendable {
public var bundleID: String?
public var infoPath: String
public var resources: [String]?
public var assetCatalogs: [String]?
public var entitlementsPath: String?
}
}
Expand Down Expand Up @@ -75,6 +77,11 @@ public struct PackSchema: Sendable {
throw StringError("xtool.yml: iconPath should have a 'png' path extension. Got '\(ext)'.")
}
}

let catalogLists = [base.assetCatalogs] + (base.extensions ?? []).map(\.assetCatalogs)
if catalogLists.contains(where: { ($0?.count ?? 0) > 1 }) {
throw StringError("xtool.yml: assetCatalogs supports at most one catalog per product.")
}
}

// swiftlint:disable:next force_try
Expand Down
65 changes: 61 additions & 4 deletions Sources/PackLib/Packer.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Foundation
import XUtils
import Subprocess
import AssetKit

public struct Packer: Sendable {
public let buildSettings: BuildSettings
Expand Down Expand Up @@ -100,7 +101,7 @@ public struct Packer: Sendable {

try await withThrowingTaskGroup(of: Void.self) { group in
for product in plan.allProducts {
try pack(
try await pack(
product: product,
binDir: binDir,
outputURL: product.directory(inApp: outputURL),
Expand Down Expand Up @@ -131,7 +132,7 @@ public struct Packer: Sendable {
binDir: URL,
outputURL: URL,
_ group: inout ThrowingTaskGroup<Void, Error>
) throws {
) async throws {
@Sendable func packFileToRoot(srcName: String) async throws {
let srcURL = URL(fileURLWithPath: srcName)
let destURL = outputURL.appendingPathComponent(srcURL.lastPathComponent)
Expand All @@ -152,6 +153,9 @@ public struct Packer: Sendable {
// Ensure output directory is available
try? FileManager.default.createDirectory(at: outputURL, withIntermediateDirectories: true)

let assets = try await Packer.compileAssets(for: product)
let iconPath = Packer.iconPath(for: product, assets: assets)

for command in product.resources {
group.addTask {
switch command {
Expand Down Expand Up @@ -179,11 +183,17 @@ public struct Packer: Sendable {
}
}
}
if let iconPath = product.iconPath {
if let iconPath {
group.addTask {
try await packFileToRoot(srcName: iconPath)
}
}
if let assets {
group.addTask {
try assets.write(into: outputURL)
try Task.checkCancellation()
}
}
group.addTask {
try await packFile(srcName: product.targetName, dstName: product.product)
}
Expand All @@ -196,7 +206,11 @@ public struct Packer: Sendable {
info["CFBundleSupportedPlatforms"] = Packer.cfBundleSupportedPlatforms(for: buildSettings.triple)
}

if let iconPath = product.iconPath {
if let assets {
info.merge(assets.infoPlistAdditions) { _, new in new }
}

if let iconPath {
let iconName = URL(fileURLWithPath: iconPath).deletingPathExtension().lastPathComponent
info["CFBundleIconFile"] = iconName
}
Expand All @@ -211,6 +225,49 @@ public struct Packer: Sendable {
}
}

/// The output of compiling a product's asset catalog.
struct CompiledAssets: Sendable {
/// The contents of `Assets.car`.
var carData: Data
/// Copies of the app icon renditions to place next to `Assets.car`, which SpringBoard falls back to.
var looseFiles: [LooseFile] = []
/// Keys such as `CFBundleIcons` to merge into the product's Info.plist.
var infoPlistAdditions: [String: any Sendable] = [:]

var hasAppIcon: Bool { !infoPlistAdditions.isEmpty }

/// Writes `Assets.car` and the loose icon files into a product's bundle directory.
func write(into directory: URL) throws {
try carData.write(to: directory.appendingPathComponent("Assets.car"))
for file in looseFiles {
try file.data.write(to: directory.appendingPathComponent(file.name))
}
}
}

/// The loose `iconPath` file to pack. The catalog's AppIcon takes precedence over it.
static func iconPath(for product: Plan.Product, assets: CompiledAssets?) -> String? {
guard let iconPath = product.iconPath, assets?.hasAppIcon == true else { return product.iconPath }
FileHandle.standardError.write(Data(
"warning: ignoring iconPath '\(iconPath)' because the asset catalog defines an AppIcon.\n".utf8
))
return nil
}

/// Compiles the product's asset catalog, if any.
///
/// `XcodePacker` does not use this: it hands the catalog to Xcode, where actool compiles it.
static func compileAssets(for product: Plan.Product) async throws -> CompiledAssets? {
guard let catalogPath = product.assetCatalogPath else { return nil }
let result = try await XCAssetCompiler(deploymentTarget: product.deploymentTarget)
.compile(catalog: URL(fileURLWithPath: catalogPath))
return CompiledAssets(
carData: result.carData,
looseFiles: result.appIconBundle?.looseFiles ?? [],
infoPlistAdditions: result.appIconBundle?.infoPlistAdditions ?? [:]
)
}

static func cfBundleSupportedPlatforms(for triple: String) -> [String] {
let components = triple.split(separator: "-").map(String.init)
guard let appleIndex = components.firstIndex(of: "apple"),
Expand Down
8 changes: 7 additions & 1 deletion Sources/PackLib/Planner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ public struct Planner: Sendable {
idSpecifier: schema.idSpecifier,
iconPath: schema.iconPath,
rootResources: schema.resources,
assetCatalogPath: schema.assetCatalogs?.first,
entitlementsPath: schema.entitlementsPath
)

Expand All @@ -101,6 +102,7 @@ public struct Planner: Sendable {
idSpecifier: ext.bundleID.flatMap(PackSchema.IDSpecifier.bundleID) ?? .orgID(app.bundleID),
iconPath: nil,
rootResources: ext.resources,
assetCatalogPath: ext.assetCatalogs?.first,
entitlementsPath: ext.entitlementsPath
)
}
Expand All @@ -123,6 +125,7 @@ public struct Planner: Sendable {
idSpecifier: PackSchema.IDSpecifier,
iconPath: String?,
rootResources: [String]?,
assetCatalogPath: String?,
entitlementsPath: String?
) async throws -> Plan.Product {
let library = try selectLibrary(
Expand Down Expand Up @@ -214,7 +217,8 @@ public struct Planner: Sendable {
infoPlist: infoPlist,
resources: resources,
iconPath: iconPath,
entitlementsPath: entitlementsPath
entitlementsPath: entitlementsPath,
assetCatalogPath: assetCatalogPath
)
}

Expand Down Expand Up @@ -319,6 +323,8 @@ public struct Plan: Sendable {
public var resources: [Resource]
public var iconPath: String?
public var entitlementsPath: String?
/// Path to an `.xcassets` catalog, relative to the package root.
public var assetCatalogPath: String?

public var targetName: String {
"\(self.product)-\(self.type.targetSuffix)"
Expand Down
37 changes: 36 additions & 1 deletion Sources/PackLib/XcodePacker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ public struct XcodePacker {
"$(inherited)", "@executable_path/Frameworks", "@executable_path/../../Frameworks",
])
}
if let catalogPath = product.assetCatalogPath,
let iconName = Self.appIconName(inCatalogAt: URL(fileURLWithPath: catalogPath, relativeTo: root)) {
buildSettings["ASSETCATALOG_COMPILER_APPICON_NAME"] = .string(iconName)
}
if let entitlementsPath = product.entitlementsPath {
let path = (entitlementsPath as NSString).isAbsolutePath
? entitlementsPath
Expand Down Expand Up @@ -97,12 +101,14 @@ public struct XcodePacker {
buildFiles: [],
)
let resources = try resourceReferences(for: product, at: root)
// the catalog is passed through untouched: actool compiles it as part of the Xcode build.
let catalog = try product.assetCatalogPath.map { try assetCatalogReference($0, for: product) }
groups.append(.group(.init(
objectID: nil,
name: product.product,
path: try .init(base: .group, path: product.product),
includeInIndex: nil,
children: [.fileReference(source), .fileReference(info)] + resources,
children: [.fileReference(source), .fileReference(info)] + resources + (catalog.map { [$0] } ?? []),
)))

let productFilename = "\(product.targetName).\(product.type == .application ? "app" : "appex")"
Expand Down Expand Up @@ -141,6 +147,9 @@ public struct XcodePacker {
),
)
var phases = [sourcePhase, frameworksPhase]
if catalog != nil {
phases.append(.resources(.init(objectID: nil, name: nil)))
}
if !resources.isEmpty {
phases.append(.copy(.init(
objectID: nil,
Expand Down Expand Up @@ -272,6 +281,32 @@ public struct XcodePacker {
}
}

private func assetCatalogReference(_ path: String, for product: Plan.Product) throws -> XCSchema.Reference {
let isAbsolute = (path as NSString).isAbsolutePath
let referencePath = isAbsolute ? path : ("../.." as NSString).appendingPathComponent(path)
return .fileReference(.init(
objectID: nil,
path: try .init(base: isAbsolute ? .absolute : .project, path: referencePath),
explicitFileType: .init(fileTypeID: "folder.assetcatalog"),
expectedSignature: nil,
textEncoding: nil,
lineEnding: nil,
includeInIndex: nil,
buildFiles: [.init(
objectID: nil,
buildPhase: .named(target: .init(targetName: product.targetName), kind: .resources, name: nil),
properties: buildFileProperties(),
)],
))
}

/// The basename of the `.appiconset` in the catalog, which Xcode needs as `ASSETCATALOG_COMPILER_APPICON_NAME`.
static func appIconName(inCatalogAt catalog: URL) -> String? {
let contents = (try? FileManager.default.contentsOfDirectory(atPath: catalog.path)) ?? []
return contents.sorted().first { $0.hasSuffix(".appiconset") }
.map { ($0 as NSString).deletingPathExtension }
}

private func buildFileProperties(removeHeadersOnCopy: Bool = false) -> XCSchema.BuildFileProperties {
XCSchema.BuildFileProperties(
platformFilters: [],
Expand Down
Loading