diff --git a/.github/workflows/sweetpad-lib.yaml b/.github/workflows/sweetpad-lib.yaml index 820ce110..c8e25648 100644 --- a/.github/workflows/sweetpad-lib.yaml +++ b/.github/workflows/sweetpad-lib.yaml @@ -62,6 +62,58 @@ jobs: run: cargo test --workspace --lib -- --test-threads=1 - name: Python regression checks run: python3 -B -m unittest discover -s sweetpad-lib/ci -p 'test_*.py' + - name: Check out the CoMaps interface files and asset catalog + uses: actions/checkout@v7 + with: + repository: comaps/comaps + ref: 27ea5a9b92b266abe6d1b690e02ad5c89bf95217 + path: .build/comaps-source + persist-credentials: false + sparse-checkout-cone-mode: false + sparse-checkout: | + /iphone/Maps/**/*.xib + /iphone/Maps/**/*.storyboard + /iphone/Maps/**/Contents.json + /iphone/Maps/Images.xcassets/ + /iphone/Maps/CoMapsWidgetExtension/Assets.xcassets/ + - name: Require fixture coverage for every CoMaps resource combination + if: matrix.os == 'ubuntu-24.04' + run: python3 sweetpad-cli/fixtures/resource_gaps.py .build/comaps-source/iphone/Maps --require-covered + - name: Compile CoMaps and the resource regression fixtures on Linux + run: | + cargo build -p sweetpad-cli --bin sweetpad + python3 sweetpad-cli/fixtures/comaps/compile.py target/debug/sweetpad .build/comaps-source "$RUNNER_TEMP/comaps-resources" + - name: Export Linux-built resources for UIKit + if: matrix.os == 'ubuntu-24.04' + uses: actions/upload-artifact@v7 + with: + name: comaps-resources + path: ${{ runner.temp }}/comaps-resources + if-no-files-found: error + retention-days: 1 + comaps-runtime: + name: CoMaps and resource variants · iPhone simulator + needs: linux + runs-on: macos-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v7 + - uses: actions/download-artifact@v8 + with: + name: comaps-resources + path: ${{ runner.temp }}/comaps-resources + - name: Compare Linux resources with Xcode and load both in UIKit + run: | + xcodebuild -version + python3 sweetpad-cli/fixtures/comaps/simulator.py "$RUNNER_TEMP/comaps-resources" --reference-output "$RUNNER_TEMP/comaps-xcode" + - name: Save Xcode catalogs for a failed comparison + if: failure() + uses: actions/upload-artifact@v7 + with: + name: comaps-xcode + path: ${{ runner.temp }}/comaps-xcode + if-no-files-found: ignore + retention-days: 1 check: name: fmt · clippy · test runs-on: macos-latest diff --git a/Cargo.lock b/Cargo.lock index 2f08fc15..d22bd1ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + [[package]] name = "adler2" version = "2.0.1" @@ -692,9 +698,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "font-types" -version = "0.12.6" +version = "0.12.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c92d9081c7ab3bd83ef1eecdfad090f3d966e3ce74106779664114cfe1a6274" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" dependencies = [ "bytemuck", ] @@ -910,10 +916,11 @@ dependencies = [ [[package]] name = "hayro" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4675ff5acd7ca41c0c34ccd2a3a154f5c86d8b5ec92bef0a114bfb194969e2af" +checksum = "34d3977ae664ab6eea015be3024379c83c6a3580f67d51be6884f1992bf683ba" dependencies = [ + "ab_glyph_rasterizer", "bytemuck", "fearless_simd 1.1.0", "hayro-interpret", @@ -926,43 +933,57 @@ dependencies = [ [[package]] name = "hayro-ccitt" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2866f0d976e76497480b853d5e258dab6e4b89ecfe991124e08f15dfa8fd03ad" +checksum = "adbed896e99325bc312778bb9c9c289d795d51c12775c44dd5e4352f679c7e46" [[package]] name = "hayro-cmap" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d285dc30731c8485de5fa732fbdf2b3affdf01e4da7c2135022ca6fa664bf6" +checksum = "a14afde3344be69225fec4f6f44f6a219a3a492f9d8301eb25ef608fe4b7014c" dependencies = [ "hayro-postscript", ] +[[package]] +name = "hayro-font" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ac7f0c78172573e9bd6eeb17f62c63f4d378b2a2d127c3ee9c2c7cc6fbdf78b" +dependencies = [ + "bitflags", + "hayro-cmap", + "hayro-syntax", + "kurbo", + "phf", + "rustc-hash", + "siphasher", + "skrifa 0.49.0", +] + [[package]] name = "hayro-interpret" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac9df074ff163a63864cec9b0bf640ccbff8abf4e44481df7369ce0ac172ffbe" +checksum = "166477622df4b770a0fc5889a9e4b48c7ff8595d6ec019bf71b4297b97b55fb6" dependencies = [ "bitflags", "hayro-cmap", + "hayro-font", "hayro-syntax", "kurbo", "moxcms", - "phf", "rustc-hash", "siphasher", - "skrifa 0.46.2", "smallvec", - "yoke", ] [[package]] name = "hayro-jbig2" -version = "0.3.1" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "000e025850f4592ddcaee85640db70704151f2bafd43b6f431aa5b6a2c6a35a9" +checksum = "eb5c7f3a4eb551c2bb7fa16e268f728d4bc2a5c9b090554b8dc0ee2503fb5840" dependencies = [ "fearless_simd 1.1.0", "hayro-ccitt", @@ -970,24 +991,24 @@ dependencies = [ [[package]] name = "hayro-jpeg2000" -version = "0.4.1" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "122c5f834c37a2260b9c851bb8be685cf539b2a8b94b704a931ef7d2525d5835" +checksum = "6e5e5f2b3de970707fc22fd956d8f44211602939d5e4588603afa919cb7b3740" dependencies = [ "fearless_simd 1.1.0", ] [[package]] name = "hayro-postscript" -version = "0.1.0" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa" +checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cdc818d8d265dcb42081d488f7599df4f73fb79e9d347ecedcd3c23809d2026" +checksum = "a6ced8279487b029813f6cc05399099fa34df6fa23d8f7b0d41d972c49d5b30d" dependencies = [ "flate2", "hayro-ccitt", @@ -1724,13 +1745,16 @@ dependencies = [ [[package]] name = "read-fonts" -version = "0.43.3" +version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "005c8acf251756c478b0bf402885bfd88a1476020c4c7e6060edc1aa68da38ea" +checksum = "bdaa4fffe9ff3ca2c353fa9729792805b9b3e324695ff5a081f860612e81b330" dependencies = [ "bytemuck", + "foldhash", "font-types", "once_cell", + "smallvec", + "yoke", ] [[package]] @@ -2109,12 +2133,15 @@ dependencies = [ [[package]] name = "skrifa" -version = "0.46.2" +version = "0.49.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4febebda507fb889c545a37a135517769d1391941013561292897961d1887d6" +checksum = "a7459fb60888ad9a5f367dd293fa2fb9df142cb451aa6bfd6cd66a7d6a9b739d" dependencies = [ "bytemuck", - "read-fonts 0.43.3", + "once_cell", + "read-fonts 0.46.0", + "smallvec", + "yoke", ] [[package]] @@ -2200,6 +2227,7 @@ dependencies = [ "hayro", "hkdf", "hmac", + "kurbo", "libc", "lz4_flex", "lzfse_rust", diff --git a/Cargo.toml b/Cargo.toml index 17751446..ccf0981a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,9 +44,11 @@ moxcms = "0.8.1" # the usvg and roxmltree it re-exports, and svgtypes, which usvg parses # with). Both are pure Rust; PDF and SVG are standard formats too large to # hand-roll. -hayro = { version = "0.8", default-features = false } +hayro = { version = "0.9", default-features = false } resvg = { version = "0.48", default-features = false } svgtypes = "0.16" +# Keep the original precision when measuring SF Symbols' Bézier control points. +kurbo = "0.13" # The codesign stand-in signs with an identity exported from Keychain Access: # RSA signatures, and the Triple DES and AES that a .p12 file's contents are # encrypted with. The signature formats around them are Apple's, and diff --git a/sweetpad-cli/Cargo.toml b/sweetpad-cli/Cargo.toml index 39e0ab94..9bd9e2cf 100644 --- a/sweetpad-cli/Cargo.toml +++ b/sweetpad-cli/Cargo.toml @@ -34,6 +34,7 @@ moxcms.workspace = true hayro.workspace = true resvg.workspace = true svgtypes.workspace = true +kurbo.workspace = true rsa.workspace = true des.workspace = true aes.workspace = true diff --git a/sweetpad-cli/fixtures/actool/expected/back-deployed-sha256.json b/sweetpad-cli/fixtures/actool/expected/back-deployed-sha256.json new file mode 100644 index 00000000..ea32f297 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/expected/back-deployed-sha256.json @@ -0,0 +1,5 @@ +{ + "extensions": "a8bbcd75e97087d521c01f979c533dbffa7b411baa2b84ea9488689c98edf1a9", + "no-extensions": "038a6770b0d0d6768d225c8461a4e7ded243e24cc96f464bf1a8248538ba67d7", + "swiftui": "cafdee11310f05491f146db8b83f7489fe14e9c8d24339cd94e17daff31f89ad" +} diff --git a/sweetpad-cli/fixtures/actool/regen.py b/sweetpad-cli/fixtures/actool/regen.py index 3b772256..f3aa15da 100644 --- a/sweetpad-cli/fixtures/actool/regen.py +++ b/sweetpad-cli/fixtures/actool/regen.py @@ -7,6 +7,8 @@ python3 -I sweetpad-cli/fixtures/actool/regen.py """ +import hashlib +import itertools import json import os import shutil @@ -92,19 +94,25 @@ def main(): try: catalog = os.path.join(work, "Probe.xcassets") build(spec, catalog) - for mode, flags in MODES.items(): - out = os.path.join(work, mode) + back_deployed = {} + for target, (mode, flags) in itertools.product(["18.2", "15.6"], MODES.items()): + out = os.path.join(work, f"{target}-{mode}") os.makedirs(out) subprocess.run( ["xcrun", "actool", catalog, "--compile", out, "--output-format", "human-readable-text", "--notices", "--warnings", "--output-partial-info-plist", os.path.join(out, "partial.plist"), "--app-icon", "AppIcon", "--accent-color", "AccentColor", "--platform", "iphonesimulator", - "--minimum-deployment-target", "18.2", "--target-device", "iphone", "--target-device", "ipad", + "--minimum-deployment-target", target, "--target-device", "iphone", "--target-device", "ipad", "--bundle-identifier", "dev.sweetpad.Probe", *flags, "--generate-swift-asset-symbols", os.path.join(out, "Symbols.swift"), "--generate-objc-asset-symbols", os.path.join(out, "Symbols.h"), "--generate-asset-symbol-index", os.path.join(out, "Symbols-Index.plist")], check=True, stdout=subprocess.DEVNULL) + if target == "15.6": + # The same large catalog exercises namespace collisions and thinnable assets in both APIs. + with open(os.path.join(out, "Symbols.swift"), "rb") as f: + back_deployed[mode] = hashlib.sha256(f.read()).hexdigest() + continue shutil.copy(os.path.join(out, "Symbols.swift"), os.path.join(expected, f"{mode}.swift")) if mode != "extensions": # The header and the index don't change with the mode. @@ -120,6 +128,9 @@ def main(): with open(os.path.join(expected, "index.json"), "w") as f: json.dump(index, f, indent=1, ensure_ascii=False) f.write("\n") + with open(os.path.join(expected, "back-deployed-sha256.json"), "w") as f: + json.dump(back_deployed, f, indent=2) + f.write("\n") finally: shutil.rmtree(work) diff --git a/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/Contents.json b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/Contents.json new file mode 100644 index 00000000..74d6a722 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapAccent.colorset/Contents.json b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapAccent.colorset/Contents.json new file mode 100644 index 00000000..2aa84952 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapAccent.colorset/Contents.json @@ -0,0 +1,38 @@ +{ + "info": { + "author": "xcode", + "version": 1 + }, + "colors": [ + { + "color": { + "color-space": "srgb", + "components": { + "red": "0.216", + "green": "0.396", + "blue": "0.247", + "alpha": "1.000" + } + }, + "idiom": "universal" + }, + { + "color": { + "color-space": "srgb", + "components": { + "red": "0.396", + "green": "0.580", + "blue": "0.392", + "alpha": "1.000" + } + }, + "idiom": "universal", + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ] + } + ] +} diff --git a/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIcon.appiconset/Contents.json b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIcon.appiconset/Contents.json new file mode 100644 index 00000000..91566f58 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIcon.appiconset/Contents.json @@ -0,0 +1,38 @@ +{ + "info": { + "author": "xcode", + "version": 1 + }, + "images": [ + { + "filename": "Light.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + }, + { + "filename": "Dark.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024", + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ] + }, + { + "filename": "Tinted.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024", + "appearances": [ + { + "appearance": "luminosity", + "value": "tinted" + } + ] + } + ] +} diff --git a/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIcon.appiconset/Dark.png b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIcon.appiconset/Dark.png new file mode 100644 index 00000000..e5e882c9 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIcon.appiconset/Dark.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIcon.appiconset/Light.png b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIcon.appiconset/Light.png new file mode 100644 index 00000000..94a91956 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIcon.appiconset/Light.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIcon.appiconset/Tinted.png b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIcon.appiconset/Tinted.png new file mode 100644 index 00000000..bb641b13 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIcon.appiconset/Tinted.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIndicator.imageset/Contents.json b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIndicator.imageset/Contents.json new file mode 100644 index 00000000..2e4ff8d9 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIndicator.imageset/Contents.json @@ -0,0 +1,25 @@ +{ + "info": { + "author": "xcode", + "version": 1 + }, + "images": [ + { + "filename": "Light.svg", + "idiom": "universal" + }, + { + "filename": "Dark.svg", + "idiom": "universal", + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ] + } + ], + "properties": { + "preserves-vector-representation": true + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIndicator.imageset/Dark.svg b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIndicator.imageset/Dark.svg new file mode 100644 index 00000000..ab327da8 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIndicator.imageset/Dark.svg @@ -0,0 +1 @@ + diff --git a/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIndicator.imageset/Light.svg b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIndicator.imageset/Light.svg new file mode 100644 index 00000000..d10f724e --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/MapIndicator.imageset/Light.svg @@ -0,0 +1 @@ + diff --git a/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/RouteMarker.imageset/Contents.json b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/RouteMarker.imageset/Contents.json new file mode 100644 index 00000000..f5edbba4 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/RouteMarker.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "info": { + "author": "xcode", + "version": 1 + }, + "images": [ + { + "filename": "Marker.pdf", + "idiom": "universal", + "scale": "1x" + }, + { + "idiom": "universal", + "scale": "2x" + }, + { + "idiom": "universal", + "scale": "3x" + } + ] +} diff --git a/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/RouteMarker.imageset/Marker.pdf b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/RouteMarker.imageset/Marker.pdf new file mode 100644 index 00000000..17446123 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/CoMapsSlots.xcassets/RouteMarker.imageset/Marker.pdf differ diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Contents.json b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Contents.json new file mode 100644 index 00000000..97a8662e --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info": { + "version": 1, + "author": "xcode" + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/EmptyRight.imageset/Contents.json b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/EmptyRight.imageset/Contents.json new file mode 100644 index 00000000..af85c29e --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/EmptyRight.imageset/Contents.json @@ -0,0 +1,19 @@ +{ + "images": [ + { + "idiom": "universal", + "filename": "Left.png", + "language-direction": "left-to-right", + "scale": "1x" + }, + { + "idiom": "universal", + "language-direction": "right-to-left", + "scale": "1x" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/EmptyRight.imageset/Left.png b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/EmptyRight.imageset/Left.png new file mode 100644 index 00000000..8fedfca8 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/EmptyRight.imageset/Left.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Forward.imageset/Contents.json b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Forward.imageset/Contents.json new file mode 100644 index 00000000..136d7657 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Forward.imageset/Contents.json @@ -0,0 +1,26 @@ +{ + "images": [ + { + "idiom": "universal", + "filename": "Forward.png", + "language-direction": "left-to-right", + "scale": "1x" + }, + { + "idiom": "universal", + "filename": "Forward@2x.png", + "language-direction": "left-to-right", + "scale": "2x" + }, + { + "idiom": "universal", + "filename": "Forward@3x.png", + "language-direction": "left-to-right", + "scale": "3x" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Forward.imageset/Forward.png b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Forward.imageset/Forward.png new file mode 100644 index 00000000..8fedfca8 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Forward.imageset/Forward.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Forward.imageset/Forward@2x.png b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Forward.imageset/Forward@2x.png new file mode 100644 index 00000000..a957843f Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Forward.imageset/Forward@2x.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Forward.imageset/Forward@3x.png b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Forward.imageset/Forward@3x.png new file mode 100644 index 00000000..ddb39401 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Forward.imageset/Forward@3x.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Neutral.imageset/Contents.json b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Neutral.imageset/Contents.json new file mode 100644 index 00000000..d317f566 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Neutral.imageset/Contents.json @@ -0,0 +1,13 @@ +{ + "images": [ + { + "idiom": "universal", + "filename": "Neutral.png", + "scale": "1x" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Neutral.imageset/Neutral.png b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Neutral.imageset/Neutral.png new file mode 100644 index 00000000..8fedfca8 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Neutral.imageset/Neutral.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Pair.imageset/Contents.json b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Pair.imageset/Contents.json new file mode 100644 index 00000000..5ce4f268 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Pair.imageset/Contents.json @@ -0,0 +1,20 @@ +{ + "images": [ + { + "idiom": "universal", + "filename": "Left.png", + "language-direction": "left-to-right", + "scale": "1x" + }, + { + "idiom": "universal", + "filename": "OtherRight.png", + "language-direction": "right-to-left", + "scale": "1x" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Pair.imageset/Left.png b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Pair.imageset/Left.png new file mode 100644 index 00000000..8fedfca8 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Pair.imageset/Left.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Pair.imageset/OtherRight.png b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Pair.imageset/OtherRight.png new file mode 100644 index 00000000..dceb031f Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Pair.imageset/OtherRight.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Preserved.imageset/Contents.json b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Preserved.imageset/Contents.json new file mode 100644 index 00000000..09416727 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Preserved.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images": [ + { + "idiom": "universal", + "filename": "Preserved.pdf", + "language-direction": "right-to-left" + } + ], + "properties": { + "preserves-vector-representation": true + }, + "info": { + "version": 1, + "author": "xcode" + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Preserved.imageset/Preserved.pdf b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Preserved.imageset/Preserved.pdf new file mode 100644 index 00000000..17446123 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Preserved.imageset/Preserved.pdf differ diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Reverse.imageset/Contents.json b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Reverse.imageset/Contents.json new file mode 100644 index 00000000..375ce643 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Reverse.imageset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "idiom": "universal", + "filename": "Reverse.png", + "language-direction": "right-to-left", + "scale": "1x" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Reverse.imageset/Reverse.png b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Reverse.imageset/Reverse.png new file mode 100644 index 00000000..8fedfca8 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Reverse.imageset/Reverse.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Vector.imageset/Contents.json b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Vector.imageset/Contents.json new file mode 100644 index 00000000..38b0ac9e --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Vector.imageset/Contents.json @@ -0,0 +1,16 @@ +{ + "images": [ + { + "idiom": "universal", + "filename": "Vector.pdf", + "language-direction": "left-to-right" + } + ], + "info": { + "version": 1, + "author": "xcode" + }, + "properties": { + "template-rendering-intent": "template" + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Vector.imageset/Vector.pdf b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Vector.imageset/Vector.pdf new file mode 100644 index 00000000..17446123 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/Direction.xcassets/Vector.imageset/Vector.pdf differ diff --git a/sweetpad-cli/fixtures/actool/resources/LayeredSymbols.xcassets/Badge.symbolset/Badge.svg b/sweetpad-cli/fixtures/actool/resources/LayeredSymbols.xcassets/Badge.symbolset/Badge.svg new file mode 100644 index 00000000..89933182 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/LayeredSymbols.xcassets/Badge.symbolset/Badge.svg @@ -0,0 +1,28 @@ + + + Template v.4.0 + + + + + + + + + + + + + + + + + + + + + diff --git a/sweetpad-cli/fixtures/actool/resources/LayeredSymbols.xcassets/Badge.symbolset/Contents.json b/sweetpad-cli/fixtures/actool/resources/LayeredSymbols.xcassets/Badge.symbolset/Contents.json new file mode 100644 index 00000000..03d24afa --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/LayeredSymbols.xcassets/Badge.symbolset/Contents.json @@ -0,0 +1,5 @@ +{ + "info": { "author": "xcode", "version": 1 }, + "properties": { "symbol-rendering-intent": "multicolor" }, + "symbols": [{ "filename": "Badge.svg", "idiom": "universal" }] +} diff --git a/sweetpad-cli/fixtures/actool/resources/LayeredSymbols.xcassets/Contents.json b/sweetpad-cli/fixtures/actool/resources/LayeredSymbols.xcassets/Contents.json new file mode 100644 index 00000000..319a86bd --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/LayeredSymbols.xcassets/Contents.json @@ -0,0 +1,3 @@ +{ + "info": { "author": "xcode", "version": 1 } +} diff --git a/sweetpad-cli/fixtures/actool/resources/PdfMasks.xcassets/AlphaCutout.imageset/Contents.json b/sweetpad-cli/fixtures/actool/resources/PdfMasks.xcassets/AlphaCutout.imageset/Contents.json new file mode 100644 index 00000000..73f4124f --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/PdfMasks.xcassets/AlphaCutout.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images": [ + { + "filename": "Cutout.pdf", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/PdfMasks.xcassets/AlphaCutout.imageset/Cutout.pdf b/sweetpad-cli/fixtures/actool/resources/PdfMasks.xcassets/AlphaCutout.imageset/Cutout.pdf new file mode 100644 index 00000000..e7dbbfe3 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/PdfMasks.xcassets/AlphaCutout.imageset/Cutout.pdf differ diff --git a/sweetpad-cli/fixtures/actool/resources/PdfMasks.xcassets/Contents.json b/sweetpad-cli/fixtures/actool/resources/PdfMasks.xcassets/Contents.json new file mode 100644 index 00000000..74d6a722 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/PdfMasks.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/Base.png b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/Base.png new file mode 100644 index 00000000..e8472537 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/Base.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/Contents.json b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/Contents.json new file mode 100644 index 00000000..e58b4140 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/Contents.json @@ -0,0 +1,58 @@ +{ + "images": [ + { + "filename": "Base.png", + "idiom": "universal", + "scale": "1x" + }, + { + "filename": "Narrow.png", + "idiom": "universal", + "scale": "1x", + "width-class": "compact" + }, + { + "filename": "Short.png", + "idiom": "universal", + "scale": "1x", + "height-class": "compact" + }, + { + "filename": "WideTall.png", + "idiom": "universal", + "scale": "1x", + "width-class": "regular", + "height-class": "regular" + }, + { + "filename": "NarrowShort.png", + "idiom": "universal", + "scale": "1x", + "width-class": "compact", + "height-class": "compact" + }, + { + "filename": "DarkNarrow.png", + "idiom": "universal", + "scale": "1x", + "width-class": "compact", + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ] + }, + { + "filename": "PadWideTall.png", + "idiom": "ipad", + "width-class": "regular", + "height-class": "regular", + "scale": "2x" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/DarkNarrow.png b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/DarkNarrow.png new file mode 100644 index 00000000..d8525cc3 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/DarkNarrow.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/Narrow.png b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/Narrow.png new file mode 100644 index 00000000..ea13f493 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/Narrow.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/NarrowShort.png b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/NarrowShort.png new file mode 100644 index 00000000..c9ebca49 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/NarrowShort.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/PadWideTall.png b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/PadWideTall.png new file mode 100644 index 00000000..41be3b89 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/PadWideTall.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/Short.png b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/Short.png new file mode 100644 index 00000000..b184be26 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/Short.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/WideTall.png b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/WideTall.png new file mode 100644 index 00000000..fa0cc39b Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveMarker.imageset/WideTall.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveVector.imageset/Base.svg b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveVector.imageset/Base.svg new file mode 100644 index 00000000..2d4c5cf7 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveVector.imageset/Base.svg @@ -0,0 +1 @@ + diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveVector.imageset/Contents.json b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveVector.imageset/Contents.json new file mode 100644 index 00000000..035922ad --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveVector.imageset/Contents.json @@ -0,0 +1,19 @@ +{ + "images": [ + { + "filename": "Base.svg", + "idiom": "universal", + "scale": "1x" + }, + { + "filename": "Narrow.svg", + "idiom": "universal", + "width-class": "compact", + "scale": "2x" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveVector.imageset/Narrow.svg b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveVector.imageset/Narrow.svg new file mode 100644 index 00000000..6f8430b0 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/AdaptiveVector.imageset/Narrow.svg @@ -0,0 +1 @@ + diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/Contents.json b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/Contents.json new file mode 100644 index 00000000..74d6a722 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/MapPin.imageset/Base.png b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/MapPin.imageset/Base.png new file mode 100644 index 00000000..e8472537 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/MapPin.imageset/Base.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/MapPin.imageset/Contents.json b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/MapPin.imageset/Contents.json new file mode 100644 index 00000000..2fb5a3fa --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/MapPin.imageset/Contents.json @@ -0,0 +1,19 @@ +{ + "images": [ + { + "filename": "Base.png", + "idiom": "universal", + "scale": "1x" + }, + { + "filename": "Narrow.png", + "idiom": "universal", + "scale": "1x", + "width-class": "compact" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/MapPin.imageset/Narrow.png b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/MapPin.imageset/Narrow.png new file mode 100644 index 00000000..ea13f493 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/MapPin.imageset/Narrow.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/ScaledMarker.imageset/Contents.json b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/ScaledMarker.imageset/Contents.json new file mode 100644 index 00000000..0e6870f4 --- /dev/null +++ b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/ScaledMarker.imageset/Contents.json @@ -0,0 +1,18 @@ +{ + "images": [ + { + "filename": "Marker@2x.png", + "idiom": "universal", + "scale": "2x" + }, + { + "filename": "Marker@3x.png", + "idiom": "universal", + "scale": "3x" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/ScaledMarker.imageset/Marker@2x.png b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/ScaledMarker.imageset/Marker@2x.png new file mode 100644 index 00000000..39f33bca Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/ScaledMarker.imageset/Marker@2x.png differ diff --git a/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/ScaledMarker.imageset/Marker@3x.png b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/ScaledMarker.imageset/Marker@3x.png new file mode 100644 index 00000000..631f86f8 Binary files /dev/null and b/sweetpad-cli/fixtures/actool/resources/SizeClasses.xcassets/ScaledMarker.imageset/Marker@3x.png differ diff --git a/sweetpad-cli/fixtures/comaps/CoMapsAppearances.swift b/sweetpad-cli/fixtures/comaps/CoMapsAppearances.swift new file mode 100644 index 00000000..eb97d0fa --- /dev/null +++ b/sweetpad-cli/fixtures/comaps/CoMapsAppearances.swift @@ -0,0 +1,75 @@ +import UIKit + +private struct AppearanceResources: Decodable { + let colors: [String] + let images: [String] +} + +private struct Raster { + let width: Int + let height: Int + let bytes: [UInt8] + + @MainActor init(_ name: String, in bundle: Bundle, traits: UITraitCollection) { + guard let image = UIImage(named: name, in: bundle, compatibleWith: traits), let raster = image.cgImage, + image.scale == traits.displayScale else { fatalError("Missing \(name) for \(traits) in \(bundle)") } + width = raster.width + height = raster.height + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + context.draw(raster, in: CGRect(x: 0, y: 0, width: width, height: height)) + bytes = Array(UnsafeBufferPointer(start: context.data!.assumingMemoryBound(to: UInt8.self), count: width * height * 4)) + precondition(stride(from: 3, to: bytes.count, by: 4).contains { bytes[$0] > 0 }, "Empty \(name) in \(bundle)") + } + + func check(against reference: Raster, name: String) { + precondition(width == reference.width && height == reference.height, "Wrong dimensions for \(name)") + guard bytes != reference.bytes else { return } + guard width > 2 && height > 2 else { + precondition(zip(bytes, reference.bytes).allSatisfy { abs(Int($0.0) - Int($0.1)) <= 2 }, name) + return + } + // Compare the authored fills and transparent regions. Core Graphics and resvg antialias edges differently. + // Check in both directions so added and missing solid regions both fail. + let neighbors = [-width - 1, -width, -width + 1, -1, 1, width - 1, width, width + 1] + for y in 1..<(height - 1) { + for x in 1..<(width - 1) { + let i = (y * width + x) * 4 + for channel in 0..<4 { + let j = i + channel + if abs(Int(bytes[j]) - Int(reference.bytes[j])) <= 2 { continue } + let flat = [bytes, reference.bytes].contains { data in + neighbors.allSatisfy { data[j + $0 * 4] == data[j] } + } + precondition(!flat, "\(name) at (\(x), \(y)), channel \(channel): Xcode \(reference.bytes[j]), Linux \(bytes[j])") + } + } + } + } +} + +@available(iOS 17.0, *) +@MainActor func checkCoMapsAppearances(xcode: Bundle) { + let url = Bundle.main.url(forResource: "CoMapsAppearances", withExtension: "json")! + let resources = try! JSONDecoder().decode(AppearanceResources.self, from: Data(contentsOf: url)) + for style: UIUserInterfaceStyle in [.light, .dark] { + for scale: CGFloat in [1, 2, 3] { + let traits = UITraitCollection { $0.userInterfaceStyle = style; $0.displayScale = scale } + for name in resources.colors { + guard let expected = UIColor(named: name, in: xcode, compatibleWith: traits), + let actual = UIColor(named: name, in: .main, compatibleWith: traits), + actual.resolvedColor(with: traits).cgColor == expected.resolvedColor(with: traits).cgColor else { + fatalError("Different CoMaps color \(name) for \(traits)") + } + } + for name in resources.images { + autoreleasepool { + let expected = Raster(name, in: xcode, traits: traits) + Raster(name, in: .main, traits: traits).check(against: expected, name: "\(name) \(style.rawValue) at \(scale)x") + } + } + } + } + print("Compared CoMaps appearances: \(resources.images.count) SVG sets and \(resources.colors.count) colors in light and dark at 1x, 2x and 3x") +} diff --git a/sweetpad-cli/fixtures/comaps/CoMapsGapProbe.swift b/sweetpad-cli/fixtures/comaps/CoMapsGapProbe.swift new file mode 100644 index 00000000..0a0d1793 --- /dev/null +++ b/sweetpad-cli/fixtures/comaps/CoMapsGapProbe.swift @@ -0,0 +1,183 @@ +import CryptoKit +import UIKit +import WebKit + +@objc(CoMapsProbeLayout) private final class CoMapsProbeLayout: UICollectionViewLayout {} + +@MainActor private func rgba(_ color: UIColor?) -> String { + guard let color else { return "nil" } + var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 + guard color.getRed(&r, green: &g, blue: &b, alpha: &a) else { return color.description } + return [r, g, b, a].map { String(Int(($0 * 255).rounded())) }.joined(separator: ",") +} + +@MainActor private func pixels(_ image: UIImage?, scale: CGFloat = 1) -> String { + guard let image else { return "nil" } + let format = UIGraphicsImageRendererFormat() + format.scale = scale + format.preferredRange = .standard + let size = image.size + let rendered = UIGraphicsImageRenderer(size: size, format: format).image { _ in + image.withRenderingMode(.alwaysOriginal).draw(in: CGRect(origin: .zero, size: size)) + } + let digest = SHA256.hash(data: rendered.pngData()!).map { String(format: "%02x", $0) }.joined() + return "\(size.width)x\(size.height)@\(image.scale) \(digest)" +} + +@available(iOS 17.0, *) +@MainActor private func gapObservations(_ bundle: Bundle, on parent: UIViewController) -> [String: String] { + var values: [String: String] = [:] + func nib(_ name: String) -> [Any] { UINib(nibName: name, bundle: bundle).instantiate(withOwner: nil) } + func view(_ root: UIView, _ tag: Int, _: T.Type) -> T { + guard let result = root.viewWithTag(tag) as? T else { fatalError("Missing \(T.self) with tag \(tag) in \(bundle)") } + return result + } + let controls = nib("CoMapsControls")[0] as! UIView + let button = view(controls, 101, UIButton.self) + let label = view(controls, 102, UILabel.self) + let field = view(controls, 103, UITextField.self) + let text = view(controls, 104, UITextView.self) + let plain = view(controls, 105, UITextView.self) + let pages = view(controls, 106, UIPageControl.self) + values["button.accessibility"] = button.accessibilityIdentifier + values["button.autoresizing"] = String(button.autoresizingMask.rawValue) + values["button.contentInsets"] = NSCoder.string(for: button.contentEdgeInsets) + values["button.titleInsets"] = NSCoder.string(for: button.titleEdgeInsets) + values["button.normalImage"] = pixels(button.image(for: .normal)) + values["button.selectedImage"] = pixels(button.image(for: .selected)) + let selectedConfiguration = button.preferredSymbolConfigurationForImage(in: .selected) + precondition(selectedConfiguration != nil, "Missing selected button symbol configuration in \(bundle)") + values["button.configuredImage"] = pixels(button.image(for: .selected)?.applyingSymbolConfiguration(selectedConfiguration!)) + values["button.selectedTitle"] = button.title(for: .selected) + values["label.traits"] = String(label.accessibilityTraits.rawValue) + values["label.shadowOffset"] = NSCoder.string(for: label.shadowOffset) + values["field.background"] = rgba(field.backgroundColor) + values["field.margins"] = NSCoder.string(for: field.layoutMargins) + values["text.accessibility"] = text.accessibilityIdentifier + values["text.background"] = rgba(text.backgroundColor) + values["text.richText"] = text.attributedText.string + let rich = text.attributedText.attributes(at: 0, effectiveRange: nil) + values["text.font"] = (rich[.font] as? UIFont)?.fontName + values["text.pointSize"] = (rich[.font] as? UIFont).map { String(describing: $0.pointSize) } + values["text.foreground"] = rgba(rich[.foregroundColor] as? UIColor) + values["text.viewFont"] = text.font?.fontName + values["text.viewColor"] = rgba(text.textColor) + values["text.plainText"] = plain.text + values["page.background"] = rgba(pages.backgroundColor) + values["view.runtimeReal"] = String(describing: controls.layer.cornerRadius) + + let lists = nib("CoMapsListViews")[0] as! UIView + let table = view(lists, 201, UITableView.self) + let collection = view(lists, 202, UICollectionView.self) + let search = view(lists, 203, UISearchBar.self) + let stack = view(lists, 204, UIStackView.self) + let web = view(lists, 205, WKWebView.self) + values["table.separator"] = rgba(table.separatorColor) + values["table.sectionIndex"] = rgba(table.sectionIndexBackgroundColor) + values["table.tracking"] = rgba(table.sectionIndexTrackingBackgroundColor) + values["table.separatorInset"] = NSCoder.string(for: table.separatorInset) + values["table.indicatorInsets"] = NSCoder.string(for: table.verticalScrollIndicatorInsets) + values["collection.layout"] = NSStringFromClass(type(of: collection.collectionViewLayout)) + values["search.background"] = rgba(search.backgroundColor) + values["search.barTint"] = rgba(search.barTintColor) + values["search.input"] = String(search.autocapitalizationType.rawValue) + values["search.defaultHeight"] = String(search.constraints.contains { $0.firstAttribute == .height && $0.constant == 55 }) + values["stack.background"] = rgba(stack.backgroundColor) + values["stack.margins"] = NSCoder.string(for: stack.layoutMargins) + values["stack.relativeMargins"] = String(stack.isLayoutMarginsRelativeArrangement) + values["web.background"] = rgba(web.backgroundColor) + values["web.media"] = String(web.configuration.mediaTypesRequiringUserActionForPlayback.rawValue) + + let cells = nib("CoMapsCells") + let cell = cells.compactMap { $0 as? UITableViewCell }.first! + let item = cells.compactMap { $0 as? UICollectionViewCell }.first! + let picker = view(cell, 302, UIDatePicker.self) + values["cell.tint"] = rgba(cell.tintColor) + values["cell.contentTint"] = rgba(cell.contentView.tintColor) + values["cell.contentBackground"] = rgba(cell.contentView.backgroundColor) + for (name, owner) in [("cell", cell as UIView), ("item", item.contentView)] { + let constraint = owner.constraints.first { $0.identifier == "\(name)-safe-width" } + let connected = owner.safeAreaLayoutGuide.owningView === owner && constraint?.firstItem === owner.safeAreaLayoutGuide + precondition(connected, "Disconnected \(name) safe area in \(bundle)") + values[name + ".safeArea"] = String(connected) + } + values["item.frame"] = NSCoder.string(for: item.frame) + values["item.contentFrame"] = NSCoder.string(for: item.contentView.frame) + values["picker.locale"] = picker.locale?.identifier + values["picker.frame"] = NSCoder.string(for: picker.frame) + values["picker.mode"] = String(picker.datePickerMode.rawValue) + + let navigation = UIStoryboard(name: "CoMapsNavigation", bundle: bundle).instantiateInitialViewController() as! UINavigationController + let container = view(navigation.viewControllers[0].view, 501, UIView.self) + values["container.background"] = rgba(container.backgroundColor) + values["container.embedded"] = String(navigation.viewControllers[0].children.contains { $0.view.superview === container }) + values["navigation.preferredSize"] = NSCoder.string(for: navigation.preferredContentSize) + + let adaptive = nib("CoMapsAdaptiveViews")[0] as! UIView + values["adaptive.bounds"] = NSCoder.string(for: adaptive.bounds) + let modern = nib("CoMapsAdaptiveModern")[0] as! UIView + values["adaptive.modernBounds"] = NSCoder.string(for: modern.bounds) + precondition(adaptive.bounds.size == CGSize(width: 414, height: 896) && modern.bounds.size == CGSize(width: 320, height: 480), + "Root view sizes for iOS 15.6 and iOS 17 differ in \(bundle)") + let arrow = view(adaptive, 401, UIImageView.self) + values["image.background"] = rgba(arrow.backgroundColor) + let host = UIViewController() + parent.addChild(host) + host.view.frame = CGRect(x: 0, y: 0, width: 320, height: 480) + parent.view.addSubview(host.view) + host.didMove(toParent: parent) + host.view.addSubview(adaptive) + defer { + host.willMove(toParent: nil) + host.view.removeFromSuperview() + host.removeFromParent() + } + for width: UIUserInterfaceSizeClass in [.compact, .regular] { + for height: UIUserInterfaceSizeClass in [.regular, .compact] { + host.traitOverrides.horizontalSizeClass = width + host.traitOverrides.verticalSizeClass = height + arrow.updateTraitsIfNeeded() + host.view.layoutIfNeeded() + let key = "adaptive.\(width.rawValue).\(height.rawValue)" + values[key + ".frame"] = NSCoder.string(for: arrow.frame) + values[key + ".image"] = pixels(arrow.image) + let name = width == .regular && height == .regular ? "MapIndicator" : "RouteMarker" + let named = UIImage(named: name, in: bundle, compatibleWith: arrow.traitCollection) + precondition(named != nil && arrow.image?.size == named?.size && arrow.image!.size.width > 1, + "Wrong adaptive image for \(key) in \(bundle): expected \(name), got \(String(describing: arrow.image))") + values[key + ".active"] = adaptive.constraints.filter { $0.isActive }.map { + "\($0.firstAttribute.rawValue):\($0.constant):\($0.priority.rawValue)" + }.sorted().joined(separator: ",") + } + } + for style: UIUserInterfaceStyle in [.light, .dark] { + for scale: CGFloat in [1, 2, 3] { + let traits = UITraitCollection(traitsFrom: [.init(userInterfaceStyle: style), .init(displayScale: scale)]) + traits.performAsCurrent { + let key = "asset.\(style.rawValue).\(scale)" + values[key + ".color"] = rgba(UIColor(named: "MapAccent", in: bundle, compatibleWith: traits)?.resolvedColor(with: traits)) + for name in ["MapIndicator", "RouteMarker"] { + values[key + "." + name] = pixels(UIImage(named: name, in: bundle, compatibleWith: traits), scale: scale) + } + } + } + } + return values +} + +@available(iOS 17.0, *) +@MainActor func checkCoMapsGaps(linux: Bundle, xcode: Bundle, on parent: UIViewController) { + let expected = gapObservations(xcode, on: parent) + let actual = gapObservations(linux, on: parent) + let differences = Set(expected.keys).union(actual.keys).sorted().compactMap { key -> String? in + guard expected[key] != actual[key] else { return nil } + return "\(key): Xcode \(expected[key] ?? ""), Linux \(actual[key] ?? "")" + } + precondition(differences.isEmpty, differences.joined(separator: "\n")) + precondition(expected["text.plainText"] == "First line\nSecond line" && expected["web.media"] == "0") + precondition(expected["search.barTint"] == "255,0,0,255" && expected["stack.relativeMargins"] == "true") + precondition(expected["table.indicatorInsets"] == "{44, 0, 0, 0}" && expected["picker.locale"] == "ru") + precondition(expected["search.defaultHeight"] == "false" && expected["container.embedded"] == "true") + precondition(expected["button.normalImage"] != "nil" && expected["button.configuredImage"] != expected["button.selectedImage"]) + print("Compared CoMaps interface and asset fixtures: \(expected.count) UIKit observations matched Xcode") +} diff --git a/sweetpad-cli/fixtures/comaps/CustomSymbols.swift b/sweetpad-cli/fixtures/comaps/CustomSymbols.swift new file mode 100644 index 00000000..47ff6984 --- /dev/null +++ b/sweetpad-cli/fixtures/comaps/CustomSymbols.swift @@ -0,0 +1,160 @@ +import UIKit + +private struct SymbolMaster: Hashable, Decodable { + let name, weight, size: String +} + +private struct CachedMaster: Hashable, Decodable { + let name, weight, size: String + let display: Int +} + +private struct SymbolCatalog: Decodable { + let names: [String] + let generated: Set + let cached: Set +} + +private struct SymbolPixels { + let width: Int + let height: Int + let rgba: [UInt8] + + @MainActor init(_ image: UIImage, scale: CGFloat) { + let bounds = CGRect(x: 0, y: 0, width: ceil(image.size.width) + 4, height: ceil(image.size.height) + 4) + let view = UIImageView(frame: bounds) + view.contentMode = .center + view.tintColor = UIColor(red: 0.85, green: 0.09, blue: 0.67, alpha: 1) + view.image = image + width = Int(bounds.width * scale) + height = Int(bounds.height * scale) + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + context.scaleBy(x: scale, y: scale) + view.layer.render(in: context) + rgba = Array(UnsafeBufferPointer(start: context.data!.assumingMemoryBound(to: UInt8.self), count: width * height * 4)) + } + + func difference(from reference: Self, cached: Bool, fractional: Bool, generated: Bool) -> String? { + guard width == reference.width && height == reference.height else { return "raster dimensions differ" } + guard stride(from: 3, to: reference.rgba.count, by: 4).contains(where: { reference.rgba[$0] != 0 }) else { + return "empty Xcode symbol" + } + if rgba == reference.rgba { return nil } + let offsets = [-width - 1, -width, -width + 1, -1, 0, 1, width - 1, width, width + 1] + var ink = 0, difference = 0 + for y in 0.. 0 && y > 0 && x + 1 < width && y + 1 < height, + offsets.contains(where: { reference.rgba[j + $0 * 4] != reference.rgba[j] }) else { + return "pixel (\(x), \(y)) channel \(channel): expected \(expected), got \(value)" + } + } + difference += worst + } + } + // A fractional point size also resizes the cached raster. Bound the total + // error against visible ink so a missing stroke cannot pass in a large frame. + // The largest difference between Apple's baked and interpolated weights was 2.499% of ink. + let divisor = cached && fractional ? 8 : (generated ? 40 : 50) + guard difference * divisor <= ink else { + return "difference of \(difference) channel levels over \(ink) alpha levels" + } + return nil + } +} + +@available(iOS 17.0, *) +@MainActor func checkCustomSymbols(xcode: Bundle, linuxWidget: Bundle, xcodeWidget: Bundle) { + let url = Bundle.main.url(forResource: "CoMapsSymbols", withExtension: "json")! + let catalogs = try! JSONDecoder().decode([String: SymbolCatalog].self, from: Data(contentsOf: url)) + let sizes: [(CGFloat, UIImage.SymbolWeight, UIImage.SymbolScale, CGFloat, UIUserInterfaceStyle)] = [ + (15, .regular, .medium, 2, .light), (17, .regular, .medium, 3, .light), (20, .regular, .medium, 1, .dark), + (17.03, .regular, .medium, 3, .light), (29, .bold, .large, 2, .dark), (21, .ultraLight, .small, 1, .light) + ] + let masterModes: [(String, UIImage.SymbolConfiguration?, Double?)] = [ + ("default", nil, nil), ("multicolor", .preferringMulticolor(), nil) + ] + let modes = masterModes + [ + ("monochrome", .preferringMonochrome(), nil), ("hierarchical", .init(hierarchicalColor: .systemOrange), nil), + ("palette", .init(paletteColors: [.systemIndigo, .systemYellow, .systemTeal]), nil), + ("variable 0", .preferringMulticolor(), 0), ("variable 0.75", .preferringMulticolor(), 0.75) + ] + let weights: [UIImage.SymbolWeight: String] = [.ultraLight: "Ultralight", .thin: "Thin", .light: "Light", + .regular: "Regular", .medium: "Medium", .semibold: "Semibold", .bold: "Bold", .heavy: "Heavy", .black: "Black"] + let scales: [UIImage.SymbolScale: String] = [.small: "Small", .medium: "Medium", .large: "Large"] + var cases = sizes.map { ($0, modes) } + for weight in weights.keys.sorted(by: { $0.rawValue < $1.rawValue }) { + for scale in [UIImage.SymbolScale.small, .medium, .large] where weight != .regular || scale != .medium { + cases.append(((17, weight, scale, 2, .light), masterModes)) + } + } + var comparisons = 0, failures = 0 + for (catalog, linux, native) in [("app", Bundle.main, xcode), ("widget", linuxWidget, xcodeWidget)] { + let assets = catalogs[catalog]! + for ((points, weight, size, display, style), sampleModes) in cases { + let traits = UITraitCollection { + $0.displayScale = display + $0.userInterfaceStyle = style + $0.layoutDirection = .leftToRight + } + let base = UIImage.SymbolConfiguration(pointSize: points, weight: weight, scale: size) + traits.performAsCurrent { + for name in assets.names { + let master = CachedMaster(name: name, weight: weights[weight]!, size: scales[size]!, display: Int(display)) + let cached = assets.cached.contains(master) && [15, 17, 20].contains(points.rounded()) + let generated = assets.generated.contains(SymbolMaster(name: name, weight: master.weight, size: master.size)) + for (mode, colors, variable) in sampleModes { + autoreleasepool { + let config = (colors.map { base.applying($0) } ?? base).withTraitCollection(traits) + let label = "\(catalog)/\(name) \(master.weight)-\(master.size) \(mode), \(points)pt at \(display)x" + func load(_ bundle: Bundle) -> UIImage { + let image: UIImage? + if let variable { + image = UIImage(named: name, in: bundle, variableValue: variable, configuration: config) + } else { + image = UIImage(named: name, in: bundle, with: config) + } + guard let image, image.isSymbolImage else { fatalError("Missing \(label) in \(bundle)") } + return image + } + let test = load(linux), reference = load(native) + comparisons += 1 + let reason: String? + if test.size != reference.size || test.baselineOffsetFromBottom != reference.baselineOffsetFromBottom + || test.alignmentRectInsets != reference.alignmentRectInsets { + func layout(_ image: UIImage) -> String { + let baseline = String(describing: image.baselineOffsetFromBottom) + return "\(image.size), baseline \(baseline), insets \(image.alignmentRectInsets)" + } + reason = "layout differs: Xcode \(layout(reference)), Linux \(layout(test))" + } else { + reason = SymbolPixels(test, scale: display).difference(from: SymbolPixels(reference, scale: display), + cached: cached, fractional: points != points.rounded(), generated: generated) + } + if let reason { + failures += 1 + if failures <= 20 { print("\(label): \(reason)"); fflush(stdout) } + } + } + } + } + } + } + } + precondition(failures == 0, "\(failures) of \(comparisons) custom symbol renderings differ") + print("Compared CoMaps symbols in UIKit: \(catalogs["app"]!.names.count) app and \(catalogs["widget"]!.names.count) widget sets, \(comparisons) renderings") +} diff --git a/sweetpad-cli/fixtures/comaps/IconPixels.m b/sweetpad-cli/fixtures/comaps/IconPixels.m new file mode 100644 index 00000000..249ce13c --- /dev/null +++ b/sweetpad-cli/fixtures/comaps/IconPixels.m @@ -0,0 +1,48 @@ +// The home screen asks CoreUI for an icon by idiom, size and appearance. +// Exercise the same catalog lookup on macOS without changing a simulator's home screen. +#import +#import +#import +#import + +@interface NSObject (CatalogProbe) +- (instancetype)initWithURL:(NSURL *)url error:(NSError **)error; +- (id)iconImageWithName:(NSString *)name scaleFactor:(CGFloat)scale deviceIdiom:(NSInteger)idiom + deviceSubtype:(NSUInteger)subtype displayGamut:(NSInteger)gamut layoutDirection:(NSInteger)direction + sizeClassHorizontal:(NSInteger)horizontal sizeClassVertical:(NSInteger)vertical + desiredSize:(CGSize)size appearanceName:(NSString *)appearance; +- (CGImageRef)image; +@end + +int main(int argc, char **argv) { + @autoreleasepool { + if (argc != 3 || !dlopen("/System/Library/PrivateFrameworks/CoreUI.framework/CoreUI", RTLD_LAZY)) return 1; + NSError *error = nil; + id catalog = [[NSClassFromString(@"CUICatalog") alloc] initWithURL:[NSURL fileURLWithPath:@(argv[1])] error:&error]; + if (!catalog) { NSLog(@"Could not open catalog: %@", error); return 1; } + for (NSInteger idiom = 1; idiom <= 2; idiom++) { + for (NSString *appearance in @[@"UIAppearanceAny", @"UIAppearanceDark", @"ISAppearanceTintable"]) { + id icon = [catalog iconImageWithName:@(argv[2]) scaleFactor:1 deviceIdiom:idiom deviceSubtype:0 + displayGamut:0 layoutDirection:0 sizeClassHorizontal:0 sizeClassVertical:0 + desiredSize:CGSizeMake(1024, 1024) appearanceName:appearance]; + CGImageRef image = [icon image]; + if (!image || CGImageGetWidth(image) != 1024 || CGImageGetHeight(image) != 1024) { + NSLog(@"Missing 1024px %@ for idiom %ld, %@", @(argv[2]), (long)idiom, appearance); + return 1; + } + NSMutableData *pixels = [NSMutableData dataWithLength:1024 * 1024 * 4]; + CGColorSpaceRef rgb = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); + CGContextRef context = CGBitmapContextCreate(pixels.mutableBytes, 1024, 1024, 8, 4096, rgb, + (CGBitmapInfo)kCGImageAlphaPremultipliedLast); + CGContextDrawImage(context, CGRectMake(0, 0, 1024, 1024), image); + CGContextRelease(context); + CGColorSpaceRelease(rgb); + unsigned char digest[CC_SHA256_DIGEST_LENGTH]; + CC_SHA256(pixels.bytes, (CC_LONG)pixels.length, digest); + printf("%ld %s ", (long)idiom, appearance.UTF8String); + for (size_t i = 0; i < sizeof(digest); i++) printf("%02x", digest[i]); + puts(""); + } + } + } +} diff --git a/sweetpad-cli/fixtures/comaps/ImageDirection.swift b/sweetpad-cli/fixtures/comaps/ImageDirection.swift new file mode 100644 index 00000000..ca3d27e7 --- /dev/null +++ b/sweetpad-cli/fixtures/comaps/ImageDirection.swift @@ -0,0 +1,66 @@ +import UIKit + +@available(iOS 17.0, *) +@MainActor func checkImageDirections(linux: Bundle, xcode: Bundle, on controller: UIViewController) { + let side = 64 + func mask(_ name: String, in bundle: Bundle, rtl: Bool, scale: CGFloat = 1) -> [UInt8] { + controller.traitOverrides.layoutDirection = rtl ? .rightToLeft : .leftToRight + let box = UIView(frame: CGRect(x: 0, y: 0, width: side, height: side)) + box.semanticContentAttribute = rtl ? .forceRightToLeft : .forceLeftToRight + controller.view.addSubview(box) + defer { box.removeFromSuperview() } + let view = UIImageView(frame: box.bounds) + view.semanticContentAttribute = box.semanticContentAttribute + view.tintColor = .black + box.addSubview(view) + view.traitOverrides.displayScale = scale + view.traitOverrides.userInterfaceStyle = .light + view.updateTraitsIfNeeded() + precondition(view.traitCollection.displayScale == scale, + "\(name) source scale \(scale), image view scale \(view.traitCollection.displayScale)") + let traits = view.traitCollection.modifyingTraits { + $0.layoutDirection = rtl ? .rightToLeft : .leftToRight + $0.displayScale = scale + $0.userInterfaceStyle = .light + } + guard let image = UIImage(named: name, in: bundle, compatibleWith: traits) else { + fatalError("Missing \(name) in \(bundle.bundleURL.lastPathComponent)") + } + view.image = image + box.layoutIfNeeded() + precondition(view.effectiveUserInterfaceLayoutDirection == (rtl ? .rightToLeft : .leftToRight)) + let context = CGContext(data: nil, width: side, height: side, bitsPerComponent: 8, bytesPerRow: side * 4, + space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + context.clear(box.bounds) + box.layer.render(in: context) + let pixels = context.data!.assumingMemoryBound(to: UInt8.self) + let alpha = (0..<(side * side)).map { pixels[$0 * 4 + 3] } + precondition(alpha.contains(0) && alpha.contains { $0 > 0 }, "\(name) rendered an empty or solid mask") + return alpha + } + func mirror(_ alpha: [UInt8]) -> [UInt8] { + alpha.indices.map { alpha[($0 / side) * side + side - 1 - $0 % side] } + } + func checkMirror(_ name: String, in bundle: Bundle, scale: CGFloat) { + let ltr = mask(name, in: bundle, rtl: false, scale: scale) + let rtl = mask(name, in: bundle, rtl: true, scale: scale) + precondition(ltr != rtl && mirror(ltr) == rtl, "\(name) failed to mirror at \(scale)x in \(bundle.bundleURL.lastPathComponent)") + } + for name in ["ic_24px_manager", "ic_menu_question", "ic_search_mode_list"] { + for scale: CGFloat in [1, 2, 3] { checkMirror(name, in: .main, scale: scale) } + } + let explicitRight = mask("Pair", in: xcode, rtl: true) + for bundle in [xcode, linux] { + let fixed = mask("Neutral", in: bundle, rtl: false) + precondition(fixed != mirror(fixed) && mask("Neutral", in: bundle, rtl: true) == fixed) + for name in ["Forward", "Vector", "Preserved"] { + for scale: CGFloat in [1, 2, 3] { checkMirror(name, in: bundle, scale: scale) } + } + checkMirror("Reverse", in: bundle, scale: 1) + precondition(mask("Forward", in: bundle, rtl: false) == fixed, "Wrong LTR source orientation in \(bundle)") + precondition(mask("Reverse", in: bundle, rtl: true) == fixed, "Wrong RTL source orientation in \(bundle)") + precondition(mask("Pair", in: bundle, rtl: false) == fixed, "Wrong explicit LTR artwork in \(bundle)") + precondition(explicitRight != fixed && explicitRight != mirror(fixed)) + precondition(mask("Pair", in: bundle, rtl: true) == explicitRight, "Wrong explicit RTL artwork in \(bundle)") + } +} diff --git a/sweetpad-cli/fixtures/comaps/Images.swift b/sweetpad-cli/fixtures/comaps/Images.swift new file mode 100644 index 00000000..0fdad665 --- /dev/null +++ b/sweetpad-cli/fixtures/comaps/Images.swift @@ -0,0 +1,28 @@ +import SwiftUI +import UIKit + +// The ten expressions used in the pinned CoMaps application sources. +@MainActor func checkCoMapsImages() { + let images = [UIImage(resource: .icWalk), UIImage(resource: .ic24PxEdit), UIImage(resource: .icSearch)] + precondition(images.allSatisfy { $0.size.width > 0 && $0.size.height > 0 }) + let light = UITraitCollection(userInterfaceStyle: .light) + for color in [UIColor(resource: .accent), UIColor(Color(.accent))] { + precondition(color.resolvedColor(with: light).cgColor.alpha > 0, "Empty Accent Color resource") + } + let swiftUIImages = [ + Image(.openStreetMapLogo), Image(.Brands.codeberg), Image(.Brands.mastodon), + Image(.Brands.matrix), Image(.Brands.lemmy), Image(.Brands.bluesky), Image(.Brands.pixelfed), + ] + if #available(iOS 16.0, *) { + for image in swiftUIImages { + let renderer = ImageRenderer(content: image.resizable().frame(width: 32, height: 32)) + guard let raster = renderer.cgImage else { fatalError("SwiftUI could not render a CoMaps image") } + guard let context = CGContext(data: nil, width: 32, height: 32, bitsPerComponent: 8, bytesPerRow: 32 * 4, + space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) + else { fatalError("Could not create an image mask") } + context.draw(raster, in: CGRect(x: 0, y: 0, width: 32, height: 32)) + let pixels = context.data!.assumingMemoryBound(to: UInt8.self) + precondition(stride(from: 3, to: 32 * 32 * 4, by: 4).contains { pixels[$0] != 0 }, "SwiftUI rendered an empty CoMaps image") + } + } +} diff --git a/sweetpad-cli/fixtures/comaps/NavigationControl.swift b/sweetpad-cli/fixtures/comaps/NavigationControl.swift new file mode 100644 index 00000000..0c1d38e6 --- /dev/null +++ b/sweetpad-cli/fixtures/comaps/NavigationControl.swift @@ -0,0 +1,70 @@ +import UIKit + +@objc(MWMNavigationDashboardManager) @objcMembers +private final class DashboardOwner: NSObject { + var navigationControlView: NavigationControl? + func settingsButtonAction() {} + func ttsButtonAction() {} + func stopRoutingButtonAction() {} +} + +@objc(MWMNavigationControlView) @objcMembers +private final class NavigationControl: UIView { + var speedBackground, extendedView, activeTrackRecordingButton, mapPositionButton, progressView: UIView? + var speedLabel, speedLegendLabel, speedWithLegendLabel, timeLabel: UILabel? + var distanceLabel, distanceLegendLabel, distanceWithLegendLabel: UILabel? + var trackRecordingButton, ttsButton, extendButton: UIButton? + var timePageControl: UIPageControl? + var routingProgress: NSLayoutConstraint? + func toggleInfoAction() {} + func extendAction() {} + func trackRecordingAction() {} +} + +@objc(MWMButton) private class MapButton: UIButton {} +@objc(MWMStopButton) private final class StopButton: MapButton { + @objc var localizedText: String? +} + +@available(iOS 17.0, *) +@MainActor func checkNavigationControl(_ nib: String, on parent: UIViewController) { + let owner = DashboardOwner() + let objects = UINib(nibName: nib, bundle: .main).instantiate(withOwner: owner) + guard let view = objects.first as? NavigationControl, owner.navigationControlView === view, + let speed = view.speedBackground, + let width = speed.constraints.first(where: { $0.firstAttribute == .width && $0.secondItem == nil }) else { + fatalError("Missing CoMaps speed panel or width constraint in \(nib)") + } + precondition(width.priority == .defaultHigh && width.isActive) + precondition(view.extendButton?.image(for: .normal) != nil, "Missing CoMaps menu icon in \(nib)") + let host = UIViewController() + parent.addChild(host) + host.view.frame = CGRect(x: 0, y: 0, width: 768, height: 200) + parent.view.addSubview(host.view) + host.didMove(toParent: parent) + defer { + host.willMove(toParent: nil) + host.view.removeFromSuperview() + host.removeFromParent() + } + host.view.addSubview(view) + NSLayoutConstraint.activate([ + view.leadingAnchor.constraint(equalTo: host.view.leadingAnchor), + view.trailingAnchor.constraint(equalTo: host.view.trailingAnchor), + view.topAnchor.constraint(equalTo: host.view.topAnchor), + ]) + func check(_ horizontal: UIUserInterfaceSizeClass, _ vertical: UIUserInterfaceSizeClass, _ points: CGFloat) { + host.traitOverrides.horizontalSizeClass = horizontal + host.traitOverrides.verticalSizeClass = vertical + speed.updateTraitsIfNeeded() + host.view.layoutIfNeeded() + precondition(speed.traitCollection.horizontalSizeClass == horizontal && speed.traitCollection.verticalSizeClass == vertical) + precondition(width.constant == points && speed.bounds.width == points, + "\(nib) \(horizontal.rawValue)/\(vertical.rawValue): expected \(points), got constant \(width.constant), width \(speed.bounds.width)") + } + check(.regular, .compact, 128) + check(.compact, .compact, 72) + check(.compact, .regular, 88) + check(.regular, .regular, 88) + check(.regular, .compact, 128) +} diff --git a/sweetpad-cli/fixtures/comaps/PDFMasks.swift b/sweetpad-cli/fixtures/comaps/PDFMasks.swift new file mode 100644 index 00000000..0152e6f5 --- /dev/null +++ b/sweetpad-cli/fixtures/comaps/PDFMasks.swift @@ -0,0 +1,79 @@ +import UIKit + +private struct AlphaRaster { + let width: Int + let height: Int + let pixels: [UInt8] + + @MainActor init(_ name: String, in bundle: Bundle, traits: UITraitCollection) { + guard let image = UIImage(named: name, in: bundle, compatibleWith: traits), + let raster = image.cgImage, image.scale == traits.displayScale else { + fatalError("Missing \(name) at \(traits.displayScale)x in \(bundle.bundleURL.lastPathComponent)") + } + width = raster.width + height = raster.height + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, + space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + context.setBlendMode(.copy) + context.draw(raster, in: CGRect(x: 0, y: 0, width: width, height: height)) + let rgba = context.data!.assumingMemoryBound(to: UInt8.self) + pixels = (0..<(width * height)).map { rgba[$0 * 4 + 3] } + } + + subscript(x: Int, y: Int) -> UInt8 { pixels[y * width + x] } + + func checkInterior(against reference: AlphaRaster, name: String, scale: Int) { + precondition(width == reference.width && height == reference.height, "\(name) has different dimensions at \(scale)x") + precondition(pixels.contains { $0 > 0 } && reference.pixels.contains { $0 > 0 }, + "\(name) rendered empty at \(scale)x") + guard width > 2 && height > 2 else { return } + let neighbors = [-width - 1, -width, -width + 1, -1, 1, width - 1, width, width + 1] + // Core Graphics and Hayro can antialias contours differently. Sample solid and + // clear interiors at least one pixel away from a change in the reference mask. + for y in 1..<(height - 1) { + for x in 1..<(width - 1) { + let i = y * width + x, expected = reference.pixels[i] + if (expected == 0 || expected == 255) && abs(Int(expected) - Int(pixels[i])) > 8 + && neighbors.allSatisfy({ reference.pixels[i + $0] == expected }) { + preconditionFailure("\(name) at \(scale)x (\(x), \(y)): expected interior alpha \(expected), got \(pixels[i])") + } + } + } + } +} + +@available(iOS 17.0, *) +@MainActor func checkPDFMasks(linuxMasks: Bundle, xcodeMasks: Bundle, xcodeCoMaps: Bundle) { + let list = Bundle.main.url(forResource: "CoMapsPDFs", withExtension: "json")! + let names = try! JSONDecoder().decode([String].self, from: Data(contentsOf: list)) + for scale in 1...3 { + let traits = UITraitCollection { + $0.displayScale = CGFloat(scale) + $0.layoutDirection = .leftToRight + $0.userInterfaceStyle = .light + } + for bundle in [xcodeMasks, linuxMasks] { + let mask = AlphaRaster("AlphaCutout", in: bundle, traits: traits) + precondition(mask.width == 16 * scale && mask.height == 12 * scale, "Wrong AlphaCutout dimensions at \(scale)x") + precondition(mask[0, 0] == 0 && mask[3 * scale, 3 * scale] == 255 && mask[6 * scale, 6 * scale] == 0, + "Lost the AlphaCutout mask at \(scale)x in \(bundle.bundleURL.lastPathComponent)") + precondition(abs(Int(mask[8 * scale, 6 * scale]) - 128) <= 1, "Wrong partial alpha in \(bundle)") + } + for name in names { + autoreleasepool { + let reference = AlphaRaster(name, in: xcodeCoMaps, traits: traits) + let linux = AlphaRaster(name, in: .main, traits: traits) + linux.checkInterior(against: reference, name: name, scale: scale) + if name == "ic_booking_plus" || name == "ic_booking_minus" { + for mask in [reference, linux] { + precondition(mask.width == 22 * scale && mask.height == 22 * scale, "Wrong \(name) dimensions") + precondition(mask[0, 0] == 0 && mask[11 * scale, 11 * scale] == 0 + && mask[3 * scale, 11 * scale] == 255, "Lost the \(name) ring at \(scale)x") + precondition(mask[11 * scale, 7 * scale] == (name == "ic_booking_plus" ? 0 : 255), + "Lost the \(name) cutout at \(scale)x") + } + } + } + } + } +} diff --git a/sweetpad-cli/fixtures/comaps/PickerApp.swift b/sweetpad-cli/fixtures/comaps/PickerApp.swift new file mode 100644 index 00000000..86bd70e3 --- /dev/null +++ b/sweetpad-cli/fixtures/comaps/PickerApp.swift @@ -0,0 +1,76 @@ +import UIKit + +// Supply the outlets, actions and style hook the real CoMaps XIB references. +@objc(MWMOpeningHoursTimeSelectorTableViewCell) +final class TimeSelectorCell: UITableViewCell { + @IBOutlet var openTimePicker: UIDatePicker! + @IBOutlet var closeTimePicker: UIDatePicker! + var actions: [String] = [] + @objc func openValueChanged() { actions.append("open") } + @objc func closeValueChanged() { actions.append("close") } +} + +extension UIView { + @objc var styleName: String { + get { "" } + set { } + } +} + +@main final class App: UIResponder, UIApplicationDelegate { + func application(_ application: UIApplication, configurationForConnecting session: UISceneSession, + options: UIScene.ConnectionOptions) -> UISceneConfiguration { + let config = UISceneConfiguration(name: nil, sessionRole: session.role) + config.delegateClass = Scene.self + return config + } +} + +final class Scene: UIResponder, UIWindowSceneDelegate { + var window: UIWindow? + + func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options: UIScene.ConnectionOptions) { + guard let scene = scene as? UIWindowScene else { return } + let window = UIWindow(windowScene: scene) + let controller = UIViewController() + window.rootViewController = controller + self.window = window + window.makeKeyAndVisible() + DispatchQueue.main.async { + let objects = UINib(nibName: "TimeSelector", bundle: .main).instantiate(withOwner: nil) + guard let cell = objects.first as? TimeSelectorCell, + let open = cell.openTimePicker, let close = cell.closeTimePicker else { + fatalError("TimeSelector.nib did not connect both date-picker outlets") + } + precondition(open !== close && [open, close].allSatisfy { + $0.datePickerMode == .time && $0.minuteInterval == 5 && + $0.preferredDatePickerStyle == .wheels && $0.locale?.identifier == "ru" + }, "Date-picker settings differ from the XIB") + open.sendActions(for: .valueChanged) + close.sendActions(for: .valueChanged) + precondition(cell.actions == ["open", "close"], "Date pickers called the wrong actions") + checkCoMapsImages() + guard #available(iOS 17.0, *) else { fatalError("Trait override checks need an iOS 17 or newer simulator") } + func variants(_ name: String) -> Bundle { + guard let url = Bundle.main.url(forResource: name, withExtension: "bundle"), + let bundle = Bundle(url: url) else { fatalError("Missing \(name) bundle") } + return bundle + } + let xcode = variants("XcodeVariants"), linux = variants("LinuxVariants") + for bundle in [xcode, linux] { + checkResourceVariants(in: bundle) + } + for nib in ["XcodeNavigation", "LinuxNavigation"] { checkNavigationControl(nib, on: controller) } + checkImageDirections(linux: linux, xcode: xcode, on: controller) + checkCoMapsGaps(linux: variants("LinuxSlots"), xcode: variants("XcodeSlots"), on: controller) + checkCoMapsAppearances(xcode: variants("XcodeCoMaps")) + checkPDFMasks(linuxMasks: variants("LinuxPDFMasks"), xcodeMasks: variants("XcodePDFMasks"), + xcodeCoMaps: variants("XcodeCoMaps")) + checkCustomSymbols(xcode: variants("XcodeCoMaps"), linuxWidget: variants("LinuxWidget"), + xcodeWidget: variants("XcodeWidget")) + print("CoMaps resources and variant bundles passed") + fflush(stdout) + exit(0) + } + } +} diff --git a/sweetpad-cli/fixtures/comaps/ResourceVariants.swift b/sweetpad-cli/fixtures/comaps/ResourceVariants.swift new file mode 100644 index 00000000..be7564bf --- /dev/null +++ b/sweetpad-cli/fixtures/comaps/ResourceVariants.swift @@ -0,0 +1,87 @@ +import UIKit + +private func matchesRGB(_ color: UIColor?, _ red: CGFloat, _ green: CGFloat, _ blue: CGFloat) -> Bool { + var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 + return color?.getRed(&r, green: &g, blue: &b, alpha: &a) == true && + abs(r - red) < 0.001 && abs(g - green) < 0.001 && abs(b - blue) < 0.001 && a == 1 +} + +@MainActor private func checkLabels(in bundle: Bundle) { + let objects = UINib(nibName: "AttributedLabels", bundle: bundle).instantiate(withOwner: nil) + guard let root = objects.first as? UIView else { fatalError("Missing label container in \(bundle)") } + let labels = root.subviews.compactMap { $0 as? UILabel } + precondition(labels.count == 4, "Missing labels in \(bundle)") + let single = labels[0] + guard let singleText = single.attributedText, + let bold = singleText.attribute(.font, at: 0, effectiveRange: nil) as? UIFont else { + fatalError("Missing single-run font in \(bundle)") + } + precondition(single.text == "Map details" && singleText.string == single.text) + precondition(bold.fontName == "HelveticaNeue-Bold" && bold.pointSize == 15 && single.font == bold) + guard let text = labels[1].attributedText else { fatalError("Missing mixed runs in \(bundle)") } + precondition(text.string == "Go🌍 now" && text.length == 8) + for (index, name, size) in [(0, "HelveticaNeue", 14), (4, "HelveticaNeue-Bold", 19)] { + var range = NSRange() + let font = text.attribute(.font, at: index, effectiveRange: &range) as? UIFont + precondition(font?.fontName == name && font?.pointSize == CGFloat(size)) + precondition(range == NSRange(location: index, length: 4), "Wrong UTF-16 run in \(bundle)") + } + guard let red = text.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor else { + fatalError("Missing foreground color in \(bundle)") + } + precondition(matchesRGB(red, 1, 0, 0)) + precondition(labels[2].text == "Map legend" && labels[2].textAlignment == .center) + precondition(labels[3].attributedText?.length == 0 && labels[3].text == "") +} + +@MainActor func checkResourceVariants(in bundle: Bundle) { + checkLabels(in: bundle) + let objects = UINib(nibName: "ButtonStateColors", bundle: bundle).instantiate(withOwner: nil) + guard let button = objects.first as? UIButton else { fatalError("Missing button in \(bundle)") } + precondition(matchesRGB(button.backgroundColor, 0, 1, 0), "Wrong button background in \(bundle)") + precondition(matchesRGB(button.titleColor(for: .highlighted), 1, 1, 0), "Wrong inherited title color in \(bundle)") + precondition(matchesRGB(button.titleShadowColor(for: .normal), 1, 0, 0), "Wrong normal shadow in \(bundle)") + precondition(matchesRGB(button.titleShadowColor(for: .highlighted), 0, 0, 1), "Wrong highlighted shadow in \(bundle)") + func check(_ name: String, _ width: UIUserInterfaceSizeClass, _ height: UIUserInterfaceSizeClass, + _ rgb: [UInt8], style: UIUserInterfaceStyle = .light, + idiom: UIUserInterfaceIdiom = .phone, scale: CGFloat = 1) { + let traits: UITraitCollection + if #available(iOS 17.0, *) { + traits = UITraitCollection { + $0.horizontalSizeClass = width + $0.verticalSizeClass = height + $0.userInterfaceStyle = style + $0.userInterfaceIdiom = idiom + $0.displayScale = scale + } + } else { + traits = UITraitCollection(traitsFrom: [ + .init(horizontalSizeClass: width), .init(verticalSizeClass: height), + .init(userInterfaceStyle: style), .init(userInterfaceIdiom: idiom), .init(displayScale: scale), + ]) + } + guard let image = UIImage(named: name, in: bundle, compatibleWith: traits), + let raster = image.cgImage, + let context = CGContext(data: nil, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { + fatalError("Could not read \(name) in \(bundle)") + } + context.draw(raster, in: CGRect(x: 0, y: 0, width: 1, height: 1)) + let pixel = Array(UnsafeBufferPointer(start: context.data!.assumingMemoryBound(to: UInt8.self), count: 4)) + precondition(pixel == rgb + [255], "\(name) in \(bundle.bundleURL.lastPathComponent) for \(traits): \(pixel)") + } + check("MapPin", .regular, .regular, [255, 0, 0]) + check("MapPin", .compact, .regular, [0, 0, 255]) + check("ScaledMarker", .regular, .regular, [0, 255, 0], scale: 2) + check("ScaledMarker", .regular, .regular, [0, 0, 255], scale: 3) + check("AdaptiveMarker", .regular, .compact, [0, 255, 0]) + check("AdaptiveMarker", .compact, .compact, [255, 0, 255]) + check("AdaptiveMarker", .regular, .regular, [255, 255, 0]) + check("AdaptiveMarker", .compact, .regular, [0, 255, 255], style: .dark) + check("AdaptiveMarker", .regular, .regular, [255, 128, 0], idiom: .pad, scale: 2) + for scale in [1, 2, 3] { + check("AdaptiveVector", .regular, .regular, [255, 0, 0], scale: CGFloat(scale)) + check("AdaptiveVector", .compact, .regular, [0, 0, 255], scale: CGFloat(scale)) + } +} diff --git a/sweetpad-cli/fixtures/comaps/compile.py b/sweetpad-cli/fixtures/comaps/compile.py new file mode 100644 index 00000000..a07c69c5 --- /dev/null +++ b/sweetpad-cli/fixtures/comaps/compile.py @@ -0,0 +1,112 @@ +"""Compile the CoMaps resources on Linux and export inputs for simulator.py on macOS. + +Use the CoMaps revision pinned in .github/workflows/sweetpad-lib.yaml. +""" +import argparse +from pathlib import Path +import plistlib +import shutil +import subprocess +import tempfile + +CELL = Path("UI/Editor/OpeningHours/Cells/MWMOpeningHoursTimeSelectorTableViewCell.xib") +NAVIGATION = Path("Classes/CustomViews/NavigationDashboard/Views/NavigationControlView.xib") +WIDGET = Path("CoMapsWidgetExtension/Assets.xcassets") +FIXTURES = Path(__file__).resolve().parents[1] +CATALOGS = FIXTURES / "actool/resources" +IOS_TARGET = ["--target-device", "iphone", "--target-device", "ipad", "--minimum-deployment-target", "15.6"] +COMAPS_ICONS = ["--app-icon", "Icon", "--alternate-app-icon", "Debug Icon"] + + +def write_bundle_info(bundle): + with (bundle / "Info.plist").open("wb") as f: + plistlib.dump({"CFBundleIdentifier": f"dev.sweetpad.{bundle.stem}", "CFBundleName": bundle.stem, + "CFBundlePackageType": "BNDL", "CFBundleVersion": "1"}, f) + + +def run_tool(command, binary=None): + subprocess.run(command if binary else ["xcrun", *command], executable=binary, check=True) + + +def compile_image_bundle(bundle, catalogs, binary=None): + bundle.mkdir(parents=True, exist_ok=True) + run_tool(["actool", *catalogs, "--platform", "iphonesimulator", *IOS_TARGET, "--compile", bundle], binary) + write_bundle_info(bundle) + + +def compile_variant_bundle(bundle, binary=None): + """Build the same inputs with the Linux CLI or the installed Xcode tools.""" + compile_image_bundle(bundle, [CATALOGS / "SizeClasses.xcassets", CATALOGS / "Direction.xcassets"], binary) + for source in ["Base.lproj/AttributedLabels.xib", "ButtonStateColors.xib"]: + xib = FIXTURES / "ibtool" / source + run_tool(["ibtool", "--module", "App", *IOS_TARGET, "--compile", bundle / (xib.stem + ".nib"), xib], binary) + + +def compile_gap_bundle(bundle, binary=None): + bundle.mkdir(parents=True, exist_ok=True) + run_tool(["actool", CATALOGS / "CoMapsSlots.xcassets", "--platform", "iphonesimulator", *IOS_TARGET, + "--app-icon", "MapIcon", "--output-partial-info-plist", bundle / "IconInfo.plist", + "--compile", bundle], binary) + write_bundle_info(bundle) + interfaces = FIXTURES / "ibtool/runtime/comaps" + for source in sorted(interfaces.iterdir()): + suffix = {".xib": ".nib", ".storyboard": ".storyboardc"}.get(source.suffix) + if suffix: + run_tool(["ibtool", "--module", "App", *IOS_TARGET, "--compile", + bundle / (source.stem + suffix), source], binary) + run_tool(["ibtool", "--module", "App", "--target-device", "iphone", "--target-device", "ipad", + "--minimum-deployment-target", "17.0", "--compile", bundle / "CoMapsAdaptiveModern.nib", + interfaces / "CoMapsAdaptiveViews.xib"], binary) + + +def compile_resources(binary, checkout, out): + maps = checkout / "iphone/Maps" + xibs = sorted(maps.rglob("*.xib")) + storyboards = sorted(maps.rglob("*.storyboard")) + if (len(xibs), len(storyboards)) != (78, 5): + raise SystemExit(f"Expected 78 XIBs and 5 storyboards in {maps}, found {len(xibs)} and {len(storyboards)}") + out.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + for source in [*xibs, *storyboards]: + product = (tmp / source.relative_to(maps)).with_suffix(".nib" if source.suffix == ".xib" else ".storyboardc") + product.parent.mkdir(parents=True, exist_ok=True) + command = ["ibtool", "--module", "CoMaps", "--target-device", "iphone", + "--minimum-deployment-target", "15.6", "--compile", product, source] + result = subprocess.run(command, executable=binary, capture_output=True, text=True) + if result.returncode: + raise SystemExit(f"Failed to compile {source}\n{result.stdout}{result.stderr}") + nibs = list(product.rglob("*.nib")) if source.suffix == ".storyboard" else [product] + if not nibs or not all(nib.is_file() and nib.stat().st_size for nib in nibs): + raise SystemExit(f"Missing compiled nib data for {source}") + shutil.copyfile((tmp / CELL).with_suffix(".nib"), out / "TimeSelector.nib") + shutil.copyfile((tmp / NAVIGATION).with_suffix(".nib"), out / "LinuxNavigation.nib") + shutil.copyfile(maps / NAVIGATION, out / NAVIGATION.name) + print(f"Compiled {len(xibs)} XIBs and {len(storyboards)} storyboards", flush=True) + + common = ["actool", maps / "Images.xcassets", "--platform", "iphonesimulator", + "--target-device", "iphone", "--target-device", "ipad", "--bundle-identifier", "dev.sweetpad.CoMapsProbe"] + for target in ["15.6", "17.0"]: + subprocess.run([*common, "--minimum-deployment-target", target, "--generate-swift-asset-symbols", + out / f"Symbols-{target}.swift"], executable=binary, check=True) + subprocess.run([*common, "--minimum-deployment-target", "15.6", *COMAPS_ICONS, + "--output-partial-info-plist", out / "CoMapsIconInfo.plist", "--compile", out], + executable=binary, check=True) + if not (out / "Assets.car").stat().st_size: + raise SystemExit("Empty compiled CoMaps catalog") + # Pass the original catalog to Xcode so UIKit can compare the same named images. + shutil.make_archive(str(out / "CoMapsImages"), "zip", maps, "Images.xcassets") + compile_image_bundle(out / "LinuxWidget.bundle", [maps / WIDGET], binary) + shutil.make_archive(str(out / "CoMapsWidget"), "zip", maps, WIDGET) + compile_variant_bundle(out / "LinuxVariants.bundle", binary) + compile_gap_bundle(out / "LinuxSlots.bundle", binary) + compile_image_bundle(out / "LinuxPDFMasks.bundle", [CATALOGS / "PdfMasks.xcassets"], binary) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("binary", type=Path) + parser.add_argument("checkout", type=Path) + parser.add_argument("output", type=Path) + args = parser.parse_args() + compile_resources(args.binary.resolve(), args.checkout.resolve(), args.output.resolve()) diff --git a/sweetpad-cli/fixtures/comaps/simulator.py b/sweetpad-cli/fixtures/comaps/simulator.py new file mode 100644 index 00000000..5e74eb42 --- /dev/null +++ b/sweetpad-cli/fixtures/comaps/simulator.py @@ -0,0 +1,252 @@ +"""Type-check the original CoMaps calls and load the Linux-built nib and catalog in UIKit.""" +import argparse +import hashlib +import json +from pathlib import Path +import platform +import plistlib +import shutil +import subprocess +import tempfile +import xml.etree.ElementTree as ET + +from compile import (CATALOGS, COMAPS_ICONS, FIXTURES, IOS_TARGET, NAVIGATION, WIDGET, compile_gap_bundle, compile_image_bundle, + compile_variant_bundle, write_bundle_info) + +HERE = Path(__file__).resolve().parent +BUNDLE_ID = "dev.sweetpad.CoMapsProbe" + + +def xcrun(*args): + return subprocess.check_output(["xcrun", *args], text=True).strip() + + +def create_iphone(simctl): + devices = json.loads(xcrun(*simctl, "list", "devices", "available", "-j"))["devices"] + for runtime, entries in reversed(list(devices.items())): + _, _, version = runtime.partition(".iOS-") + if not version or int(version.split("-")[0]) < 17: + continue + for device in entries: + model = device["deviceTypeIdentifier"] + if ".iPhone-" in model: + return xcrun(*simctl, "create", "SweetPad CoMaps", model, runtime) + raise SystemExit("The selected Xcode needs an iPhone simulator with iOS 17 or later") + + +def rendition_manifest(bundle): + rows = json.loads(xcrun("assetutil", "--info", bundle / "Assets.car")) + fields = ["Name", "AssetType", "RenditionName", "Idiom", "Scale", "Appearance", + "SizeClass Horizontal", "SizeClass Vertical", "LayoutDirection", "Flippable", "PixelWidth", "PixelHeight"] + # Xcode can pack the same public renditions into internal texture atlases. + return sorted(tuple(row.get(key, "") for key in fields) + for row in rows if row.get("AssetType") in {"Image", "Vector"}) + + +def compare_slots(linux, native, linux_plist, names, reader, *, icons_only=False): + fields = ["Name", "AssetType", "Idiom", "Appearance", "Scale", "RenditionName", "PixelWidth", "PixelHeight", + "Icon Index", "Sizes", "Colorspace", "ColorModel", "Encoding", "Color components", "Opaque"] + def renditions(bundle): + rows = json.loads(xcrun("assetutil", "--info", bundle / "Assets.car")) + return sorted(json.dumps({k: r[k] for k in fields if k in r}, sort_keys=True) + for r in rows if "AssetType" in r and (not icons_only or r.get("Name") in names)) + + expected, actual = renditions(native), renditions(linux) + if not expected or actual != expected: + raise SystemExit(f"Different asset slots in {linux.name}\nOnly in Xcode: {set(expected) - set(actual)}" + f"\nOnly in Linux: {set(actual) - set(expected)}") + if plistlib.loads(linux_plist.read_bytes()) != plistlib.loads((native / "IconInfo.plist").read_bytes()): + raise SystemExit(f"Different app icon Info.plist entries for {names}") + for name in names: + def icon_pixels(bundle): + return subprocess.check_output([reader, bundle / "Assets.car", name], text=True).splitlines() + native_pixels, linux_pixels = icon_pixels(native), icon_pixels(linux) + if linux_pixels != native_pixels or len(native_pixels) != 6: + raise SystemExit(f"Different {name} pixels (iPhone/iPad × default/dark/tinted):" + f"\nXcode {native_pixels}\nLinux {linux_pixels}") + if name == "MapIcon": + swatches = [(230, 30, 70, 255), (15, 45, 200, 255), (180, 180, 180, 255)] + hashes = [hashlib.sha256(bytes(rgba) * 1024**2).hexdigest() for rgba in swatches] + if [row.split()[-1] for row in native_pixels] != hashes * 2: + raise SystemExit("MapIcon did not resolve the authored swatch for every appearance and device") + print(f"Matched {len(expected)} asset slots and all six icon lookups for {', '.join(names)}", flush=True) + + +def check_design_markers(native): + with tempfile.TemporaryDirectory() as tmp: + for name, key in [("CoMapsCells", "canvasLocation"), ("CoMapsControls", "simulatedStatusBarMetrics")]: + source = FIXTURES / "ibtool/runtime/comaps" / (name + ".xib") + document = ET.parse(source) + parent, child = next((p, c) for p in document.iter() for c in p if c.get("key") == key) + parent.remove(child) + control = Path(tmp) / source.name + document.write(control, encoding="utf-8", xml_declaration=True) + output = control.with_suffix(".nib") + xcrun("ibtool", "--module", "App", *IOS_TARGET, "--compile", output, control) + if output.read_bytes() != (native / output.name).read_bytes(): + raise SystemExit(f"Removing the design-time {key} changed Xcode's {name} nib") + + +def compare_symbol_catalog(linux, native_rows, catalog, count): + def glyphs(rows): + fields = ["Idiom", "Scale", "Reference Point Size", "Template Version", "Interpolatable", "Glyph RenderingMode", + "Contains Hierarchical Layers", "Contains Multicolor Layers"] + return {(row["Name"], row["Glyph Weight"], row["Glyph Size"]): tuple(row.get(key) for key in fields) + for row in rows if row.get("AssetType") == "Vector Glyph"} + + expected = glyphs(native_rows) + actual = glyphs(json.loads(xcrun("assetutil", "--info", linux / "Assets.car"))) + sets = sorted(catalog.rglob("*.symbolset")) + names = sorted(path.stem for path in sets) + if len(sets) != count or any({key[0] for key in compiled} != set(names) for compiled in (expected, actual)): + raise SystemExit(f"Expected {count} CoMaps symbols in both catalogs for {catalog}") + # Xcode versions can also materialize interpolated masters and cache different point sizes. + # Compare the authored masters here. UIKit exercises all 27 weight/size combinations below. + sizes = {"S": "Small", "M": "Medium", "L": "Large"} + authored = set() + for path in sets: + slot, = json.loads((path / "Contents.json").read_text())["symbols"] + masters = ET.parse(path / slot["filename"]).find('.//{*}g[@id="Symbols"]') + if masters is None or not len(masters): + raise SystemExit(f"No symbol masters in {path}") + for master in masters.findall("{*}g"): + if len(master): + weight, size = master.attrib["id"].rsplit("-", 1) + authored.add((path.stem, weight, sizes[size])) + for key in sorted(authored): + if key not in expected or key not in actual or expected[key] != actual[key]: + raise SystemExit(f"Symbol master {key} differs in {catalog}: Xcode {expected.get(key)}, Linux {actual.get(key)}") + print(f"{catalog.name}: matched {len(authored)} authored masters. Additional interpolated masters: " + f"Xcode {len(expected.keys() - authored)}, Linux {len(actual.keys() - authored)}.", flush=True) + cache_keys = sorted({(row["Name"], row["Glyph Weight"], row["Glyph Size"], row["Scale"]) + for row in native_rows if row.get("AssetType") == "Image" and "Glyph Cached Index" in row}) + variant_fields = ("name", "weight", "size") + return {"names": names, + "generated": [dict(zip(variant_fields, key)) for key in sorted(expected.keys() - actual.keys())], + "cached": [dict(zip((*variant_fields, "display"), key)) for key in cache_keys]} + + +def compile_comaps_reference(resources, app, reference_output, icon_reader): + shutil.unpack_archive(resources / "CoMapsImages.zip", app.parent) + catalog = app.parent / "Images.xcassets" + bundle = app / "XcodeCoMaps.bundle" + bundle.mkdir() + write_bundle_info(bundle) + xcrun("actool", catalog, "--platform", "iphonesimulator", "--target-device", "iphone", + "--target-device", "ipad", "--minimum-deployment-target", "15.6", "--bundle-identifier", BUNDLE_ID, + *COMAPS_ICONS, "--output-partial-info-plist", bundle / "IconInfo.plist", "--compile", bundle) + rows = json.loads(xcrun("assetutil", "--info", bundle / "Assets.car")) + compare_slots(app, bundle, resources / "CoMapsIconInfo.plist", ["Icon", "Debug Icon"], icon_reader, icons_only=True) + appearances = { + "images": sorted({r["Name"] for r in rows if r.get("AssetType") == "Vector" and + r.get("Appearance") == "UIAppearanceDark" and r["RenditionName"].lower().endswith(".svg")}), + "colors": sorted({r["Name"] for r in rows if r.get("AssetType") == "Color"}), + } + if len(appearances["images"]) != 24 or len(appearances["colors"]) != 19: + raise SystemExit(f"Unexpected CoMaps appearance resources: {appearances}") + (app / "CoMapsAppearances.json").write_text(json.dumps(appearances)) + names = sorted({r["Name"] for r in rows if r.get("AssetType") == "Vector" + and r.get("RenditionName", "").lower().endswith(".pdf")}) + sets = {pdf.parent for pdf in catalog.rglob("*.pdf")} + if len(names) != len(sets) or not {"ic_booking_plus", "ic_booking_minus"}.issubset(names): + raise SystemExit(f"Expected all {len(sets)} CoMaps PDF sets including both booking controls, got {names}") + (app / "CoMapsPDFs.json").write_text(json.dumps(names)) + shutil.unpack_archive(resources / "CoMapsWidget.zip", app.parent) + widget_catalog = app.parent / WIDGET + native_widget = app / "XcodeWidget.bundle" + linux_widget = app / "LinuxWidget.bundle" + compile_image_bundle(native_widget, [widget_catalog]) + if reference_output: + reference_output.mkdir(parents=True, exist_ok=True) + for native in [bundle, native_widget]: + shutil.copyfile(native / "Assets.car", reference_output / (native.stem + ".car")) + shutil.copytree(resources / linux_widget.name, linux_widget) + widget_rows = json.loads(xcrun("assetutil", "--info", native_widget / "Assets.car")) + app_symbols = compare_symbol_catalog(app, rows, catalog, 55) + widget_symbols = compare_symbol_catalog(linux_widget, widget_rows, widget_catalog, 1) + (app / "CoMapsSymbols.json").write_text(json.dumps({"app": app_symbols, "widget": widget_symbols})) + return len(names) + + +def check(resources, simctl, simulator, reference_output): + device_sdk = xcrun("--sdk", "iphoneos", "--show-sdk-path") + sim_sdk = xcrun("--sdk", "iphonesimulator", "--show-sdk-path") + with tempfile.TemporaryDirectory() as tmp: + app = Path(tmp) / "CoMapsProbe.app" + app.mkdir() + for filename in ["TimeSelector.nib", "LinuxNavigation.nib", "Assets.car"]: + shutil.copyfile(resources / filename, app / filename) + linux = app / "LinuxVariants.bundle" + native = app / "XcodeVariants.bundle" + shutil.copytree(resources / linux.name, linux) + compile_variant_bundle(native) + linux_masks = app / "LinuxPDFMasks.bundle" + native_masks = app / "XcodePDFMasks.bundle" + shutil.copytree(resources / linux_masks.name, linux_masks) + compile_image_bundle(native_masks, [CATALOGS / "PdfMasks.xcassets"]) + icon_reader = app.parent / "icon-pixels" + subprocess.run(["xcrun", "clang", "-fobjc-arc", "-framework", "Foundation", "-framework", "CoreGraphics", + HERE / "IconPixels.m", "-o", icon_reader], check=True) + linux_slots, native_slots = app / "LinuxSlots.bundle", app / "XcodeSlots.bundle" + shutil.copytree(resources / linux_slots.name, linux_slots) + compile_gap_bundle(native_slots) + check_design_markers(native_slots) + compare_slots(linux_slots, native_slots, linux_slots / "IconInfo.plist", ["MapIcon"], icon_reader) + pdf_count = compile_comaps_reference(resources, app, reference_output, icon_reader) + xcrun("ibtool", "--module", "CoMaps", "--target-device", "iphone", "--minimum-deployment-target", "15.6", + "--compile", app / "XcodeNavigation.nib", resources / NAVIGATION.name) + expected = rendition_manifest(native) + rendition_manifest(native_masks) + actual = rendition_manifest(linux) + rendition_manifest(linux_masks) + if actual != expected: + raise SystemExit(f"Image renditions differ\nXcode: {expected}\nLinux: {actual}") + print(f"Matched {len(expected)} Xcode image and vector renditions", flush=True) + for target in ["15.6", "17.0"]: + bundle_id = f"{BUNDLE_ID}.ios{target.replace('.', '-')}" + symbols = resources / f"Symbols-{target}.swift" + swift = ["swiftc", "-module-name", "CoMapsProbe", symbols, HERE / "Images.swift"] + subprocess.run(["xcrun", "--sdk", "iphoneos", *swift, "-typecheck", "-sdk", device_sdk, "-target", f"arm64-apple-ios{target}"], check=True) + print(f"CoMaps calls type-check for iOS {target}", flush=True) + subprocess.run(["xcrun", "--sdk", "iphonesimulator", *swift, "-parse-as-library", HERE / "PickerApp.swift", + HERE / "ResourceVariants.swift", HERE / "ImageDirection.swift", HERE / "NavigationControl.swift", + HERE / "PDFMasks.swift", HERE / "CustomSymbols.swift", HERE / "CoMapsGapProbe.swift", + HERE / "CoMapsAppearances.swift", + "-sdk", sim_sdk, + "-target", f"{platform.machine()}-apple-ios{target}-simulator", "-o", app / "CoMapsProbe"], check=True) + with (app / "Info.plist").open("wb") as f: + plistlib.dump({"CFBundleIdentifier": bundle_id, "CFBundleExecutable": "CoMapsProbe", + "CFBundleName": "CoMapsProbe", "CFBundlePackageType": "APPL", + "CFBundleVersion": "1", "CFBundleShortVersionString": "1.0", "CFBundleDevelopmentRegion": "en", + "UIApplicationSceneManifest": {"UIApplicationSupportsMultipleScenes": False}, + "CFBundleSupportedPlatforms": ["iPhoneSimulator"], "MinimumOSVersion": target}, f) + subprocess.run(["codesign", "--force", "--sign", "-", app], check=True) + subprocess.run(["xcrun", *simctl, "install", simulator, app], check=True, timeout=180) + log = subprocess.run(["xcrun", *simctl, "launch", "--console-pty", "--terminate-running-process", + simulator, bundle_id], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=240) + lines = log.stdout.splitlines() + symbol_result = next((line for line in lines if line.startswith("Compared CoMaps symbols")), None) + if log.returncode or not symbol_result or "CoMaps resources and variant bundles passed" not in lines: + raise SystemExit(f"CoMaps iOS {target} probe failed\n{log.stdout}") + print(symbol_result, flush=True) + for line in lines: + if line.startswith("Compared CoMaps interface") or line.startswith("Compared CoMaps appearances"): + print(line, flush=True) + print(f"iOS {target} build passed the CoMaps nib, size-class and layout-direction checks " + f"and compared {pdf_count} PDF images with Xcode at 1x, 2x and 3x", flush=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("resources", type=Path, help="output of compile.py") + parser.add_argument("--simulator", help="reuse a simulator by UDID (otherwise create and delete a test iPhone)") + parser.add_argument("--device-set", type=Path) + parser.add_argument("--reference-output", type=Path, help="save the Xcode catalogs to reproduce a comparison") + args = parser.parse_args() + simctl = ["simctl", "--set", str(args.device_set.resolve())] if args.device_set else ["simctl"] + simulator = args.simulator or create_iphone(simctl) + try: + subprocess.run(["xcrun", *simctl, "bootstatus", simulator, "-b"], check=True, timeout=600) + check(args.resources.resolve(), simctl, simulator, args.reference_output) + finally: + if not args.simulator: + subprocess.run(["xcrun", *simctl, "shutdown", simulator], check=False, timeout=60) + subprocess.run(["xcrun", *simctl, "delete", simulator], check=True, timeout=60) diff --git a/sweetpad-cli/fixtures/ibtool/Base.lproj/AttributedLabels.xib b/sweetpad-cli/fixtures/ibtool/Base.lproj/AttributedLabels.xib new file mode 100644 index 00000000..97331185 --- /dev/null +++ b/sweetpad-cli/fixtures/ibtool/Base.lproj/AttributedLabels.xib @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sweetpad-cli/fixtures/ibtool/ButtonStateColors.xib b/sweetpad-cli/fixtures/ibtool/ButtonStateColors.xib new file mode 100644 index 00000000..6eddc558 --- /dev/null +++ b/sweetpad-cli/fixtures/ibtool/ButtonStateColors.xib @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/sweetpad-cli/fixtures/ibtool/ConstraintPrecedence.xib b/sweetpad-cli/fixtures/ibtool/ConstraintPrecedence.xib new file mode 100644 index 00000000..b8e9b5b1 --- /dev/null +++ b/sweetpad-cli/fixtures/ibtool/ConstraintPrecedence.xib @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sweetpad-cli/fixtures/ibtool/expected/AttributedLabels.nib b/sweetpad-cli/fixtures/ibtool/expected/AttributedLabels.nib new file mode 100644 index 00000000..f71d3d39 Binary files /dev/null and b/sweetpad-cli/fixtures/ibtool/expected/AttributedLabels.nib differ diff --git a/sweetpad-cli/fixtures/ibtool/expected/ButtonStateColors.nib b/sweetpad-cli/fixtures/ibtool/expected/ButtonStateColors.nib new file mode 100644 index 00000000..0a3c13ab Binary files /dev/null and b/sweetpad-cli/fixtures/ibtool/expected/ButtonStateColors.nib differ diff --git a/sweetpad-cli/fixtures/ibtool/expected/ConstraintPrecedence.nib b/sweetpad-cli/fixtures/ibtool/expected/ConstraintPrecedence.nib new file mode 100644 index 00000000..47f2522c Binary files /dev/null and b/sweetpad-cli/fixtures/ibtool/expected/ConstraintPrecedence.nib differ diff --git a/sweetpad-cli/fixtures/ibtool/runtime/comaps/CoMapsAdaptiveViews.xib b/sweetpad-cli/fixtures/ibtool/runtime/comaps/CoMapsAdaptiveViews.xib new file mode 100644 index 00000000..f63e915d --- /dev/null +++ b/sweetpad-cli/fixtures/ibtool/runtime/comaps/CoMapsAdaptiveViews.xib @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sweetpad-cli/fixtures/ibtool/runtime/comaps/CoMapsCells.xib b/sweetpad-cli/fixtures/ibtool/runtime/comaps/CoMapsCells.xib new file mode 100644 index 00000000..ebd09d0c --- /dev/null +++ b/sweetpad-cli/fixtures/ibtool/runtime/comaps/CoMapsCells.xib @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sweetpad-cli/fixtures/ibtool/runtime/comaps/CoMapsControls.xib b/sweetpad-cli/fixtures/ibtool/runtime/comaps/CoMapsControls.xib new file mode 100644 index 00000000..366d3c2a --- /dev/null +++ b/sweetpad-cli/fixtures/ibtool/runtime/comaps/CoMapsControls.xib @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + First line +Second line + + + + + + + + + + + + + + + + + + + + + diff --git a/sweetpad-cli/fixtures/ibtool/runtime/comaps/CoMapsListViews.xib b/sweetpad-cli/fixtures/ibtool/runtime/comaps/CoMapsListViews.xib new file mode 100644 index 00000000..5a6acee7 --- /dev/null +++ b/sweetpad-cli/fixtures/ibtool/runtime/comaps/CoMapsListViews.xib @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sweetpad-cli/fixtures/ibtool/runtime/comaps/CoMapsNavigation.storyboard b/sweetpad-cli/fixtures/ibtool/runtime/comaps/CoMapsNavigation.storyboard new file mode 100644 index 00000000..c3a0ee5e --- /dev/null +++ b/sweetpad-cli/fixtures/ibtool/runtime/comaps/CoMapsNavigation.storyboard @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sweetpad-cli/fixtures/resource_gaps.py b/sweetpad-cli/fixtures/resource_gaps.py new file mode 100644 index 00000000..bf99a9d8 --- /dev/null +++ b/sweetpad-cli/fixtures/resource_gaps.py @@ -0,0 +1,81 @@ +"""Find resource combinations in a checkout that lack a checked-in source fixture. + +Compare keyed Interface Builder children on their owning elements, and the +selector combinations of populated asset slots. Counts describe fixture +inputs. Confirm candidate gaps with Xcode and the runtime before treating +them as compiler bugs. Inline Rust fixtures and generated catalogs are outside +this inventory. +""" +import argparse +from collections import defaultdict +import json +import os +from pathlib import Path + +from ibtool.audit import PRUNED, documents + +HERE = Path(__file__).resolve().parent + + +def interface_features(root): + found = defaultdict(set) + for path, document in documents(root): + runtime = document.get("targetRuntime", "unspecified") + for parent in document.iter(): + for child in parent: + if child.get("key"): + feature = (runtime, parent.tag, child.tag, child.attrib["key"]) + found[feature].add(path.relative_to(root).as_posix()) + return found + + +def asset_features(root): + found = defaultdict(set) + for base, dirs, files in os.walk(root): + dirs[:] = sorted(d for d in dirs if d not in PRUNED) + folder = Path(base) + if "Contents.json" not in files or not any(p.suffix == ".xcassets" for p in folder.parents): + continue + contents = json.loads((folder / "Contents.json").read_text()) + for group in ("images", "colors", "symbols", "data"): + for slot in contents.get(group, []): + if not slot.get("filename") and not slot.get("color"): + continue + selectors = [] + for key, value in sorted(slot.items()): + if key in {"filename", "color"}: + continue + if key == "appearances": + value = sorted((a["appearance"], a["value"]) for a in value) + value = value if isinstance(value, str) else json.dumps(value, sort_keys=True, separators=(',', ':')) + selectors.append(f"{key}={value}") + kind = Path(slot.get("filename", "")).suffix.lower() or "color" + feature = (folder.suffix, group, kind, *selectors) + found[feature].add(folder.relative_to(root).as_posix()) + return found + + +def compare(observed, fixtures, limit): + missing = sorted(observed.keys() - fixtures.keys(), key=lambda f: (-len(observed[f]), f)) + return {"observed": len(observed), "present_in_fixtures": len(observed) - len(missing), + "missing": len(missing), + "examples": [{"feature": feature, "files": len(observed[feature]), "example": min(observed[feature])} + for feature in missing[:limit]]} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("checkout", type=Path) + parser.add_argument("--limit", type=int, default=10, help="maximum examples per tool") + parser.add_argument("--require-covered", action="store_true", help="fail if an observed combination has no fixture") + args = parser.parse_args() + root = args.checkout.resolve() + if not root.is_dir() or args.limit < 0: + parser.error("provide an existing checkout and a nonnegative example limit") + report = { + "ibtool": compare(interface_features(root), interface_features(HERE / "ibtool"), args.limit), + "actool": compare(asset_features(root), asset_features(HERE / "actool/resources"), args.limit), + } + print(json.dumps(report, indent=2)) + if args.require_covered and any(tool["missing"] for tool in report.values()): + raise SystemExit(1) diff --git a/sweetpad-cli/src/cli/actool/car.rs b/sweetpad-cli/src/cli/actool/car.rs index 5566185f..37ed0c46 100644 --- a/sweetpad-cli/src/cli/actool/car.rs +++ b/sweetpad-cli/src/cli/actool/car.rs @@ -15,7 +15,7 @@ //! keys take, which is how CoreUI finds the masters a symbol has. //! //! A color's rendition holds its components as an `RLOC` payload, and an -//! image's its pixels, premultiplied BGRA compressed with gzip, which CoreUI +//! image's its pixels, premultiplied BGRA or gray/alpha compressed with gzip, which CoreUI //! calls "zip". A vector image is drawn into one of those per scale, and its //! PDF or SVG is kept as a rendition of its own. A custom symbol is an SVG //! per weight and size its template draws, with the metrics that set it in @@ -28,6 +28,7 @@ use crate::cli::bom::Bom; use std::collections::BTreeSet; use std::io::Write as _; +use super::catalog::{ImageDirection, SizeClass, SizeClasses, SymbolRendering}; use super::photo::{Format as PhotoFormat, Photo}; use super::raster::Rgba; use super::vector::Format; @@ -146,6 +147,35 @@ pub struct Variant { /// CoreUI's idiom: 0 universal, 1 iPhone, 2 iPad, 3 TV, 4 CarPlay, /// 5 Watch, 6 marketing. pub idiom: u16, + pub size_classes: SizeClasses, + pub direction: ImageDirection, +} + +impl Variant { + pub const ANY: Self = Self { + appearance: Appearance::Any, + scale: 1, + idiom: 0, + size_classes: SizeClasses::ANY, + direction: ImageDirection::Fixed, + }; +} + +impl ImageDirection { + fn key(self) -> u16 { + match self { + Self::Fixed => 0, + Self::RightToLeft { .. } => 4, // CoreUI's Pointing Left + Self::LeftToRight { .. } => 5, // CoreUI's Pointing Right + } + } + + fn flags(self) -> u32 { + match self { + Self::LeftToRight { flippable: true } | Self::RightToLeft { flippable: true } => 0x40, + _ => 0, + } + } } /// An image's pixels as CoreUI keeps them: premultiplied BGRA, row by row. @@ -260,6 +290,8 @@ pub struct Glyph { /// Whether the template is a variable one, whose ultralight, regular /// and black masters CoreUI interpolates into the other weights. pub interpolatable: bool, + /// Bit 0 for multicolor layers and bit 1 for hierarchical layers. + pub layer_flags: u32, } /// The platform a catalog is for, which decides the key format. @@ -271,37 +303,14 @@ pub enum Family { Mac, } -impl Family { - /// CoreUI's attribute ids, in the order a rendition key holds them: - /// appearance 7, localization 13, scale 12, idiom 15, subtype 16, - /// identifier 17, element 1, part 2, size 3, layer 11, with app icons - /// dimension 9, an icon's size index, and with symbols dimension 9, - /// deployment target 25, glyph weight 26 and glyph size 27. - fn key_format(self, kinds: Kinds) -> &'static [u32] { - match (self, kinds.glyphs, kinds.icons) { - (Family::Ios, false, false) => &[7, 13, 12, 15, 16, 17, 1, 2], - (Family::Ios, false, true) => &[7, 13, 12, 15, 16, 9, 17, 1, 2], - (Family::Ios, true, _) => &[7, 13, 12, 15, 16, 26, 27, 9, 25, 17, 1, 2], - (Family::Mac, false, false) => &[7, 13, 1, 2, 3, 17, 11, 12], - (Family::Mac, false, true) => &[7, 13, 1, 2, 3, 17, 9, 11, 12], - (Family::Mac, true, _) => &[7, 13, 1, 2, 3, 17, 9, 11, 12, 25, 26, 27], - } - } -} - -/// The kinds of rendition a catalog has that widen its keys. -#[derive(Debug, Clone, Copy)] -struct Kinds { - glyphs: bool, - icons: bool, -} - /// The attributes of a rendition's key, the ones the stand-in sets. #[derive(Debug, Clone, Copy, Default)] struct Key { appearance: Appearance, scale: u16, idiom: u16, + size_classes: SizeClasses, + direction: u16, /// A device class within the idiom, like 1792 for the iPhone XR. subtype: u16, /// An app icon size's index. @@ -314,9 +323,8 @@ struct Key { } impl Key { - fn bytes(&self, family: Family, kinds: Kinds) -> Vec { - family - .key_format(kinds) + fn bytes(&self, family: Family, format: &[u32]) -> Vec { + format .iter() .flat_map(|attribute| { let value: u16 = match attribute { @@ -325,7 +333,10 @@ impl Key { 15 => self.idiom, 16 => self.subtype, 9 => self.dimension, + 4 => self.direction, 17 => self.identifier, + 20 => self.size_classes.horizontal as u16, + 21 => self.size_classes.vertical as u16, 1 => ELEMENT, 2 => self.part, 25 => self.deployment, @@ -492,7 +503,12 @@ impl Car { part: Part::Image as u16, ..key(identifier, variant) }; - self.bitmap(key, name, image, rendering | source); + self.bitmap( + key, + name, + image, + rendering | source | variant.direction.flags(), + ); } /// A JPEG or HEIF image's rendition: the file `data` as it is, with its @@ -540,7 +556,7 @@ impl Car { let header = Header { name, layout: 12, - flags: rendering.flags(), + flags: rendering.flags() | variant.direction.flags(), width: 0, height: 0, scale: u32::from(variant.scale) * 100, @@ -643,9 +659,8 @@ impl Car { color_space: 0, }; let variant = Variant { - appearance: Appearance::Any, - scale: 1, idiom, + ..Variant::ANY }; self.add( Key { @@ -659,9 +674,24 @@ impl Car { /// A bitmap's rendition, keyed by `key`, with the header's `flags`. fn bitmap(&mut self, key: Key, name: &str, image: &Bitmap, flags: u32) { + let gray = image + .bgra + .chunks_exact(4) + .all(|p| p[0] == p[1] && p[1] == p[2]); + let gray_alpha; + let (pixels, pixel_format, color_space, bytes_per_pixel) = if gray { + gray_alpha = image + .bgra + .chunks_exact(4) + .flat_map(|p| [p[0], p[3]]) + .collect::>(); + (gray_alpha.as_slice(), *b"GA8 ", 2, 2) + } else { + (image.bgra.as_slice(), *b"ARGB", 1, 4) + }; let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); let compressed = gzip - .write_all(&image.bgra) + .write_all(pixels) .and_then(|()| gzip.finish()) .unwrap_or_default(); let mut payload = b"MLEC".to_vec(); @@ -701,7 +731,7 @@ impl Car { ), info(1004, &[&zero, &1f32.to_le_bytes()]), info(1006, &[&1u32.to_le_bytes()]), - info(1007, &[&(w * 4).to_le_bytes()]), + info(1007, &[&(w * bytes_per_pixel).to_le_bytes()]), ]; let header = Header { name, @@ -710,8 +740,8 @@ impl Car { width: w, height: h, scale: u32::from(key.scale) * 100, - pixel_format: u32::from_be_bytes(*b"ARGB"), - color_space: 1, + pixel_format: u32::from_be_bytes(pixel_format), + color_space, }; self.add(key, header.rendition(&info, &payload)); } @@ -731,7 +761,7 @@ impl Car { let header = Header { name, layout: 9, - flags: 0x04, + flags: 0x04 | variant.direction.flags(), width: 0, height: 0, scale: 0, @@ -757,7 +787,14 @@ impl Car { } /// One master of the symbol `identifier`, from the template file `name`. - pub fn glyph(&mut self, name: &str, identifier: u16, variant: Variant, glyph: &Glyph) { + pub fn glyph( + &mut self, + name: &str, + identifier: u16, + variant: Variant, + glyph: &Glyph, + mode: SymbolRendering, + ) { let mut metrics = Vec::new(); for value in [if glyph.interpolatable { 7 } else { 3 }, glyph.point_size] { metrics.extend_from_slice(&u32::to_le_bytes(value)); @@ -785,8 +822,8 @@ impl Car { 1019, &[ &1u32.to_le_bytes(), - &u32::from(glyph.interpolatable).to_le_bytes(), - &0u32.to_le_bytes(), + &(mode as u32).to_le_bytes(), + &glyph.layer_flags.to_le_bytes(), ], )); let header = Header { @@ -817,16 +854,61 @@ impl Car { self.renditions.push((key, rendition)); } - /// Whether any rendition is a symbol's or an app icon's, which widen - /// the key format. - fn kinds(&self) -> Kinds { - Kinds { - glyphs: self.facets.iter().any(|f| f.symbol), - icons: self.facets.iter().any(|f| f.part == Part::Icon) - || self + /// CoreUI uses one key format for the whole catalog. Each size-class axis + /// is present only when a rendition selects a value on that axis (20 for + /// width, 21 for height). Symbols add weight, size and deployment target + /// (26, 27, 25). Symbols and icons both use dimension (9). + fn key_format(&self) -> Vec { + let glyphs = self.facets.iter().any(|f| f.symbol); + let directional = self.renditions.iter().any(|(key, _)| key.direction != 0); + let icons = self.facets.iter().any(|f| f.part == Part::Icon) + || self + .renditions + .iter() + .any(|(key, _)| key.part == Part::Icon as u16); + match self.family { + Family::Ios => { + let mut format = vec![7, 13, 12, 15, 16]; + if glyphs { + format.extend([26, 27, 9, 25]); + } else if icons { + format.push(9); + } + if directional { + format.push(4); + } + if self + .renditions + .iter() + .any(|(key, _)| key.size_classes.horizontal != SizeClass::Any) + { + format.push(20); + } + if self .renditions .iter() - .any(|(key, _)| key.part == Part::Icon as u16), + .any(|(key, _)| key.size_classes.vertical != SizeClass::Any) + { + format.push(21); + } + format.extend([17, 1, 2]); + format + } + Family::Mac => { + let mut format = vec![7, 13, 1, 2, 3]; + if directional { + format.push(4); + } + format.push(17); + if icons || glyphs { + format.push(9); + } + format.extend([11, 12]); + if glyphs { + format.extend([25, 26, 27]); + } + format + } } } @@ -846,12 +928,11 @@ impl Car { let index = bom.add(header); bom.variable("CARHEADER", index); - let kinds = self.kinds(); - let format = self.family.key_format(kinds); + let format = self.key_format(); let renditions = self .renditions .iter() - .map(|(key, rendition)| (key.bytes(self.family, kinds), rendition.clone())) + .map(|(key, rendition)| (key.bytes(self.family, &format), rendition.clone())) .collect(); bom.tree("RENDITIONS", renditions, Keys::Fixed(2 * format.len())); let facets = self @@ -885,7 +966,7 @@ impl Car { bom.tree("APPEARANCEKEYS", appearances, Keys::Variable); let mut key_format = b"tmfk".to_vec(); - for value in [0, count(format.len())].iter().chain(format) { + for value in [0, count(format.len())].iter().chain(&format) { key_format.extend_from_slice(&value.to_le_bytes()); } let index = bom.add(key_format); @@ -898,7 +979,7 @@ impl Car { metadata.extend_from_slice(&padded(b"sweetpad", 256)); let index = bom.add(metadata); bom.variable("EXTENDED_METADATA", index); - bom.tree("BITMAPKEYS", self.bitmap_keys(kinds), Keys::Inline); + bom.tree("BITMAPKEYS", self.bitmap_keys(&format), Keys::Inline); bom.finish() } @@ -906,8 +987,7 @@ impl Car { /// a mask with a bit set for each value its renditions take, or every /// bit for the attributes CoreUI doesn't narrow by: appearance, /// identifier, element and part. - fn bitmap_keys(&self, kinds: Kinds) -> Vec<(Vec, Vec)> { - let format = self.family.key_format(kinds); + fn bitmap_keys(&self, format: &[u32]) -> Vec<(Vec, Vec)> { self.facets .iter() .map(|facet| { @@ -917,7 +997,7 @@ impl Car { .iter() .filter(|(k, _)| k.identifier == facet.identifier) { - let values = key.bytes(self.family, kinds); + let values = key.bytes(self.family, format); for (mask, value) in masks.iter_mut().zip(values.chunks(2)) { let value = u16::from_le_bytes([value[0], value[1]]); *mask |= 1u32.checked_shl(u32::from(value)).unwrap_or(u32::MAX); @@ -947,6 +1027,8 @@ fn key(identifier: u16, variant: Variant) -> Key { appearance: variant.appearance, scale: variant.scale, idiom: variant.idiom, + size_classes: variant.size_classes, + direction: variant.direction.key(), identifier, ..Key::default() } @@ -1262,11 +1344,7 @@ pub(super) mod tests { .collect() } - const ANY: Variant = Variant { - appearance: Appearance::Any, - scale: 1, - idiom: 0, - }; + const ANY: Variant = Variant::ANY; #[test] fn a_color_is_written_as_xcode_writes_it() { @@ -1396,6 +1474,41 @@ pub(super) mod tests { assert_eq!(pixels, [0, 0, 255, 255, 128, 128, 128, 128]); } + #[test] + fn gray_bitmaps_store_premultiplied_gray_then_alpha() { + let mut car = Car::new(Family::Ios, "ios", "15.6"); + let id = car.facet("Marker", Part::Image).unwrap(); + let image = Bitmap::from_rgba(&Rgba { + width: 3, + height: 1, + pixels: vec![180, 180, 180, 255, 80, 80, 80, 128, 0, 0, 0, 0], + }); + car.image( + "Marker.png", + id, + ANY, + &image, + Rendering::Original, + Source { + vector: false, + preserved: false, + }, + ); + let data = car.write(0); + let store = Store::read(&data); + let (renditions, _) = store.tree("RENDITIONS"); + let rendition = renditions[0].1; + assert_eq!(&rendition[24..28], b" 8AG"); + let info_len = u32::from_le_bytes(rendition[168..172].try_into().unwrap()) as usize; + let mut pixels = Vec::new(); + std::io::Read::read_to_end( + &mut flate2::read::GzDecoder::new(&rendition[184 + info_len + 16..]), + &mut pixels, + ) + .unwrap(); + assert_eq!(pixels, [180, 255, 40, 128, 0, 0]); + } + #[test] fn appearances_are_listed_by_name() { let mut car = Car::new(Family::Ios, "ios", "17.0"); @@ -1459,6 +1572,7 @@ pub(super) mod tests { padding: f32::from_bits(0x3f94_c000), template_version: 0.0, interpolatable: false, + layer_flags: 0, } } @@ -1466,7 +1580,13 @@ pub(super) mod tests { fn a_glyph_is_written_as_xcode_writes_it() { let mut car = Car::new(Family::Ios, "ios", "17.0"); let id = car.symbol("Legacy").unwrap(); - car.glyph("legacy.svg", id, ANY, &legacy_regular_medium()); + car.glyph( + "legacy.svg", + id, + ANY, + &legacy_regular_medium(), + SymbolRendering::Automatic, + ); let data = car.write(0); let store = Store::read(&data); let (renditions, _) = store.tree("RENDITIONS"); @@ -1525,7 +1645,13 @@ pub(super) mod tests { sizes: &[], ..legacy_regular_medium() }; - car.glyph("variable.svg", symbol, ANY, &glyph); + car.glyph( + "variable.svg", + symbol, + ANY, + &glyph, + SymbolRendering::Automatic, + ); } let data = car.write(0); let keys = Store::read(&data).inline_tree("BITMAPKEYS"); @@ -1593,7 +1719,13 @@ pub(super) mod tests { fn a_mac_cars_keys_widen_for_symbols_too() { let mut car = Car::new(Family::Mac, "macosx", "14.0"); let id = car.symbol("Legacy").unwrap(); - car.glyph("legacy.svg", id, ANY, &legacy_regular_medium()); + car.glyph( + "legacy.svg", + id, + ANY, + &legacy_regular_medium(), + SymbolRendering::Automatic, + ); let data = car.write(0); assert_eq!( Store::read(&data).variable("KEYFORMAT"), diff --git a/sweetpad-cli/src/cli/actool/catalog.rs b/sweetpad-cli/src/cli/actool/catalog.rs index 1e6f28a9..610c46fc 100644 --- a/sweetpad-cli/src/cli/actool/catalog.rs +++ b/sweetpad-cli/src/cli/actool/catalog.rs @@ -47,13 +47,35 @@ pub struct Asset { /// other sizes, besides the bitmaps drawn from them: /// `preserves-vector-representation`. pub preserves_vector: bool, - /// A symbol set rather than an image set. - pub symbol: bool, + /// A symbol set's preferred rendering mode. + pub symbol: Option, /// Whether actool would compile anything for it: a color with a value, /// an image with a file. pub has_content: bool, } +#[derive(Debug, Clone, Copy)] +#[repr(u32)] +pub enum SymbolRendering { + Automatic = 0, + Template = 1, + Multicolor = 2, + Hierarchical = 3, + Palette = 4, +} + +impl SymbolRendering { + fn read(contents: Option<&Value>) -> Self { + match contents.and_then(|c| c.pointer("/properties/symbol-rendering-intent")?.as_str()) { + Some("template") => Self::Template, + Some("multicolor") => Self::Multicolor, + Some("hierarchical") => Self::Hierarchical, + Some("palette") => Self::Palette, + _ => Self::Automatic, + } + } +} + /// One entry of an image or app icon set's `Contents.json`. #[derive(Debug, Clone, Default)] pub struct Entry { @@ -69,8 +91,10 @@ pub struct Entry { pub appearance: bool, /// Its appearances, as `(appearance, value)`: `("luminosity", "dark")`. pub appearances: Vec<(String, String)>, + pub size_classes: SizeClasses, + pub direction: ImageDirection, /// Whether it varies by something else the stand-in doesn't compile: - /// a display gamut, locale, size class, memory or graphics class, or a + /// a display gamut, locale, memory or graphics class, or a /// device subtype, which only a watchOS app icon's slots read. pub other_traits: bool, /// The device a watchOS app icon slot is for, like `44mm`. @@ -81,6 +105,56 @@ pub struct Entry { pub type_identifier: Option, } +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum ImageDirection { + #[default] + Fixed, + LeftToRight { + flippable: bool, + }, + RightToLeft { + flippable: bool, + }, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +#[repr(u16)] +pub enum SizeClass { + #[default] + Any = 0, + Compact = 1, + Regular = 2, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct SizeClasses { + pub horizontal: SizeClass, + pub vertical: SizeClass, +} + +impl SizeClasses { + pub const ANY: Self = Self { + horizontal: SizeClass::Any, + vertical: SizeClass::Any, + }; + + fn read(entry: &Value) -> Option { + let axis = |key: &str| match entry.get(key) { + None => Some(SizeClass::Any), + Some(value) => match value.as_str()? { + // Xcode represents the Any slot by omitting the axis. + "compact" => Some(SizeClass::Compact), + "regular" => Some(SizeClass::Regular), + _ => None, + }, + }; + Some(Self { + horizontal: axis("width-class")?, + vertical: axis("height-class")?, + }) + } +} + /// One entry of a color set's `Contents.json`. #[derive(Debug, Clone, Default)] pub struct ColorEntry { @@ -126,7 +200,7 @@ impl Catalog { colors: Vec::new(), rendering: None, preserves_vector: false, - symbol: false, + symbol: None, has_content: true, })], ..Folder::default() @@ -275,7 +349,7 @@ fn read_asset(path: &Path, relative_path: String) -> Asset { .unwrap_or("universal") .to_string(), appearances: appearances(e), - other_traits: other_traits(e), + other_traits: other_traits(e) || SizeClasses::read(e) != Some(SizeClasses::ANY), color: e.get("color").cloned(), }) .collect(); @@ -294,12 +368,17 @@ fn read_asset(path: &Path, relative_path: String) -> Asset { } else { Kind::Image }; - (kind, idioms(&images), files(&images), has) + ( + kind, + idioms(&images), + files(&images, extension == "imageset"), + has, + ) } "dataset" => { let data = entries("data"); let has = data.iter().any(|e| e.get("filename").is_some()); - (Kind::Data, idioms(&data), files(&data), has) + (Kind::Data, idioms(&data), files(&data, false), has) } "icon" => (Kind::AppIcon, Vec::new(), Vec::new(), true), _ => (Kind::Other, Vec::new(), Vec::new(), true), @@ -325,7 +404,7 @@ fn read_asset(path: &Path, relative_path: String) -> Asset { colors: color_entries, rendering, preserves_vector, - symbol: extension == "symbolset", + symbol: (extension == "symbolset").then(|| SymbolRendering::read(contents.as_ref())), has_content, } } @@ -346,42 +425,62 @@ fn appearances(entry: &Value) -> Vec<(String, String)> { .collect() } -/// Whether an entry varies by a trait other than idiom, scale and -/// appearance. +/// Whether an entry uses a slot selector the compiler cannot represent. fn other_traits(entry: &Value) -> bool { entry .get("display-gamut") .and_then(Value::as_str) .is_some_and(|g| g != "sRGB") - || [ - "locale", - "width-class", - "height-class", - "memory", - "graphics-feature-set", - "subtype", - ] - .iter() - .any(|k| entry.get(*k).is_some()) + || ["locale", "memory", "graphics-feature-set", "subtype"] + .iter() + .any(|k| entry.get(*k).is_some()) } /// An image, app icon or data set's entries, as the stand-in uses them. -fn files(entries: &[Value]) -> Vec { +fn files(entries: &[Value], image_set: bool) -> Vec { let text = |e: &Value, key: &str| e.get(key).and_then(Value::as_str).map(str::to_string); + // Xcode selects a direction mode for the entire image set, counting empty + // slots too. A fixed slot disables direction, and a pair disables mirroring. + let has_slot = |direction| { + entries + .iter() + .any(|e| e.get("language-direction").and_then(Value::as_str) == direction) + }; + let directional = image_set && !has_slot(None); + let flippable = + directional && !(has_slot(Some("left-to-right")) && has_slot(Some("right-to-left"))); entries .iter() - .map(|e| Entry { - filename: text(e, "filename"), - idiom: text(e, "idiom").unwrap_or_else(|| "universal".to_string()), - scale: text(e, "scale"), - size: text(e, "size"), - platform: text(e, "platform"), - appearance: e.get("appearances").is_some(), - appearances: appearances(e), - other_traits: other_traits(e), - subtype: text(e, "subtype"), - role: text(e, "role"), - type_identifier: text(e, "universal-type-identifier"), + .map(|e| { + let size_classes = SizeClasses::read(e); + let direction = match e.get("language-direction").and_then(Value::as_str) { + Some("left-to-right") if directional => { + Some(ImageDirection::LeftToRight { flippable }) + } + Some("right-to-left") if directional => { + Some(ImageDirection::RightToLeft { flippable }) + } + None | Some("left-to-right" | "right-to-left") => Some(ImageDirection::Fixed), + _ => None, + }; + Entry { + filename: text(e, "filename"), + idiom: text(e, "idiom").unwrap_or_else(|| "universal".to_string()), + scale: text(e, "scale"), + size: text(e, "size"), + platform: text(e, "platform"), + appearance: e.get("appearances").is_some(), + appearances: appearances(e), + size_classes: size_classes.unwrap_or_default(), + direction: direction.unwrap_or_default(), + other_traits: other_traits(e) + || (image_set && direction.is_none()) + || size_classes.is_none() + || (!image_set && size_classes != Some(SizeClasses::ANY)), + subtype: text(e, "subtype"), + role: text(e, "role"), + type_identifier: text(e, "universal-type-identifier"), + } }) .collect() } diff --git a/sweetpad-cli/src/cli/actool/compile.rs b/sweetpad-cli/src/cli/actool/compile.rs index e715b21f..ab0b7b0f 100644 --- a/sweetpad-cli/src/cli/actool/compile.rs +++ b/sweetpad-cli/src/cli/actool/compile.rs @@ -16,7 +16,7 @@ use serde_json::{Map, Value, json}; use super::car::{ Appearance, Bitmap, Car, ColorSpace, Family, Glyph, Part, Rendering, Source, Variant, }; -use super::catalog::{Asset, Catalog, Kind, qualified_name}; +use super::catalog::{Asset, Catalog, Entry, Kind, SizeClasses, SymbolRendering, qualified_name}; use super::photo::Photo; use super::uti; use super::vector::{Drawing, Format}; @@ -433,6 +433,7 @@ fn add_app_icon<'a>( appearance: image.appearance, scale: image.scale, idiom: image.idiom, + ..Variant::ANY }; let file = image.entry.filename.as_deref().unwrap_or_default(); car.icon( @@ -706,8 +707,10 @@ fn add_assets<'a>( let name = qualified_name(&chain, asset); let added = match asset.kind { Kind::Color => add_color(car, &name, asset, devices, platform), - Kind::Image if asset.symbol => add_symbol(car, &name, asset, devices, platform), - Kind::Image => add_image(car, &name, asset, devices, platform), + Kind::Image => match asset.symbol { + Some(mode) => add_symbol(car, &name, asset, devices, platform, mode), + None => add_image(car, &name, asset, devices, platform), + }, Kind::Data => add_data(car, &name, asset, devices, platform), Kind::AppIcon | Kind::Other => false, }; @@ -762,6 +765,38 @@ fn add_color(car: &mut Car, name: &str, asset: &Asset, devices: &[String], platf true } +fn image_variant( + entry: &Entry, + devices: &[String], + platform: &str, +) -> Option<(Variant, Option)> { + let scale = match entry.scale.as_deref() { + Some("1x") => Some(1), + Some("2x") => Some(2), + Some("3x") => Some(3), + _ => None, + }; + if entry.size_classes != SizeClasses::ANY + && !matches!( + platform, + "iphoneos" | "iphonesimulator" | "xros" | "xrsimulator" + ) + { + return None; + } + let mut variant = variant( + &entry.idiom, + &entry.appearances, + entry.other_traits, + scale.unwrap_or(1), + devices, + platform, + )?; + variant.size_classes = entry.size_classes; + variant.direction = entry.direction; + Some((variant, scale)) +} + fn add_image(car: &mut Car, name: &str, asset: &Asset, devices: &[String], platform: &str) -> bool { let rendering = match asset.rendering.as_deref() { Some("template") => Rendering::Template, @@ -776,20 +811,7 @@ fn add_image(car: &mut Car, name: &str, asset: &Asset, devices: &[String], platf let Some(filename) = entry.filename.as_deref() else { continue; }; - let scale = match entry.scale.as_deref() { - Some("1x") => Some(1), - Some("2x") => Some(2), - Some("3x") => Some(3), - _ => None, - }; - let Some(variant) = variant( - &entry.idiom, - &entry.appearances, - entry.other_traits, - scale.unwrap_or(1), - devices, - platform, - ) else { + let Some((variant, scale)) = image_variant(entry, devices, platform) else { continue; }; let Ok(bytes) = std::fs::read(asset.dir.join(filename)) else { @@ -920,8 +942,11 @@ fn draw<'a>(drawings: &[Drawn<'a>], scales: &[u16]) -> Vec<(Variant, &'a str, Bi continue; } let same = |d: &&Drawn| { - d.variant.idiom == drawn.variant.idiom - && d.variant.appearance == drawn.variant.appearance + d.variant + == Variant { + scale: d.variant.scale, + ..drawn.variant + } }; match by_variant .iter_mut() @@ -944,7 +969,12 @@ fn draw<'a>(drawings: &[Drawn<'a>], scales: &[u16]) -> Vec<(Variant, &'a str, Bi } plan.into_iter() .filter_map(|(drawn, target)| { - let factor = f32::from(target) / f32::from(drawn.scale.unwrap_or(1)); + // SVG dimensions are in points even in an explicitly scaled slot. + let source_scale = match drawn.drawing { + Drawing::Svg(_) => 1, + Drawing::Pdf(_) => drawn.scale.unwrap_or(1), + }; + let factor = f32::from(target) / f32::from(source_scale); let bitmap = drawn.drawing.render(factor).ok()?; let variant = Variant { scale: target, @@ -972,6 +1002,7 @@ fn add_symbol( asset: &Asset, devices: &[String], platform: &str, + mode: SymbolRendering, ) -> bool { let sizing = glyph::Sizing::of(platform); let symbols: Vec<(Variant, &str, Vec)> = ordered(&asset.entries, |e| &e.idiom) @@ -998,7 +1029,7 @@ fn add_symbol( }; for (variant, filename, glyphs) in symbols { for glyph in &glyphs { - car.glyph(filename, identifier, variant, glyph); + car.glyph(filename, identifier, variant, glyph, mode); } } true @@ -1060,6 +1091,7 @@ fn variant( appearance, scale, idiom, + ..Variant::ANY }) } diff --git a/sweetpad-cli/src/cli/actool/glyph.rs b/sweetpad-cli/src/cli/actool/glyph.rs index 77a62658..a235c812 100644 --- a/sweetpad-cli/src/cli/actool/glyph.rs +++ b/sweetpad-cli/src/cli/actool/glyph.rs @@ -9,6 +9,7 @@ use std::fmt::Write as _; use std::mem::{Discriminant, discriminant}; +use kurbo::{Affine, BezPath, Rect}; use resvg::tiny_skia::PathSegment; use resvg::usvg; use usvg::roxmltree::{Document, Node}; @@ -97,16 +98,24 @@ pub fn masters(bytes: &[u8], sizing: Sizing) -> Result, String> { return None; }; let to_template = viewport.invert()?; - let (left, top, right, bottom) = control_bounds(group, to_template)?; + let source = element(id); + let bounds = control_bounds(group, to_template, source)?; Some(Outline { - left, - top, - right, - bottom, - transform: to_template.pre_concat(group.abs_transform()), + bounds, + transform: template_transform(to_template.pre_concat(group.abs_transform()), source), }) }; let regular_medium = measured("Regular-M"); + let layer_flags = element("Symbols").map_or(0, layer_flags); + // The detached master still needs the template's layer colors, opacities + // and clear-behind instructions when CoreUI selects a rendering mode. + let mut styles = String::new(); + for node in document + .descendants() + .filter(|n| n.has_tag_name((SVG_NAMESPACE, "style"))) + { + write_node(node, &mut styles, 0); + } // A variable template draws an ultralight, a regular and a black master // that CoreUI interpolates into the other weights, which takes outlines // drawn with the same commands. @@ -126,7 +135,8 @@ pub fn masters(bytes: &[u8], sizing: Sizing) -> Result, String> { continue; }; let guide = |name: &str| element(name).and_then(|n| Guide::of(n, &tree)); - let baseline = guide(&format!("Baseline-{size_name}")).map_or(outline.bottom, |g| g.y); + let baseline = + guide(&format!("Baseline-{size_name}")).map_or(outline.bounds.y1, |g| g.y); let capline = guide(&format!("Capline-{size_name}")).map_or(baseline, |g| g.y); // A variable template has margins for each master; older ones // have one pair, drawn beside the regular medium master, or as @@ -135,27 +145,28 @@ pub fn masters(bytes: &[u8], sizing: Sizing) -> Result, String> { let (left, right, against) = match (own("left"), own("right")) { (Some(l), Some(r)) => (Some(l), Some(r), &outline), _ => ( - guide("left-margin"), - guide("right-margin"), + guide("left-margin-Regular-M").or_else(|| guide("left-margin")), + guide("right-margin-Regular-M").or_else(|| guide("right-margin")), regular_medium.as_ref().unwrap_or(&outline), ), }; - let left_margin = left.map_or(0.0, |g| g.width.unwrap_or(against.left - g.x)); - let right_margin = right.map_or(0.0, |g| g.width.unwrap_or(g.x - against.right)); + let left_margin = left.map_or(0.0, |g| g.width.unwrap_or(against.bounds.x0 - g.x)); + let right_margin = right.map_or(0.0, |g| g.width.unwrap_or(g.x - against.bounds.x1)); let points = |units: f64| points(units, sizing.scale); glyphs.push(Glyph { weight, size, - svg: standalone(group, &outline, sizing.scale).into_bytes(), + svg: standalone(group, &outline, sizing.scale, &styles).into_bytes(), point_size: sizing.point_size, sizes: &[], - baseline: points(outline.bottom - baseline), + baseline: points(outline.bounds.y1 - baseline), capline: points(baseline - capline), left_margin: points(left_margin), right_margin: points(right_margin), padding: points(PADDING), template_version, interpolatable, + layer_flags, }); } } @@ -176,14 +187,24 @@ pub fn masters(bytes: &[u8], sizing: Sizing) -> Result, String> { Ok(glyphs) } +/// CoreUI advertises the layers used by the symbol as a whole on every master. +fn layer_flags(symbols: Node) -> u32 { + symbols + .descendants() + .filter_map(|n| n.attribute("class")) + .flat_map(str::split_ascii_whitespace) + .fold(0, |flags, class| match class.split_once('-') { + Some(("multicolor", _)) => flags | 1, + Some(("hierarchical", _)) => flags | 2, + _ => flags, + }) +} + /// A master's outline: its bounds in template units, and the transform from /// its group's coordinates into the template's. struct Outline { - left: f64, - top: f64, - right: f64, - bottom: f64, - transform: usvg::Transform, + bounds: Rect, + transform: Affine, } /// The kinds of segment a group's outlines are drawn with, path by path. @@ -204,17 +225,45 @@ fn commands(group: &usvg::Group) -> Vec>> { /// A path's bounds, control points and all, which is how Core Graphics /// measures a path, with a stroked path's reaching half the stroke's width /// further, in its own coordinates. -fn path_bounds(path: &usvg::Path) -> (f64, f64, f64, f64) { +fn path_bounds(path: &usvg::Path, source: Option) -> Rect { let r = path.data().bounds(); + let rendered = [r.left(), r.top(), r.right(), r.bottom()]; + // usvg resolves CSS, uses and shapes, but its coordinates are f32. Keep + // original f64 control points when they describe the same rendered path bounds. + let rect = source + .and_then(|n| n.attribute("d")) + .and_then(|d| BezPath::from_svg(d).ok()) + .map(|path| path.control_box()) + .filter(|r| same_coordinates([r.x0, r.y0, r.x1, r.y1], rendered)) + .unwrap_or_else(|| { + let [x0, y0, x1, y1] = rendered.map(f64::from); + Rect::new(x0, y0, x1, y1) + }); let half = path .stroke() .map_or(0.0, |s| f64::from(s.width().get()) / 2.0); - ( - f64::from(r.left()) - half, - f64::from(r.top()) - half, - f64::from(r.right()) + half, - f64::from(r.bottom()) + half, - ) + rect.inflate(half, half) +} + +#[allow(clippy::cast_possible_truncation, clippy::float_cmp)] // exact equality at the renderer's precision +fn same_coordinates(source: [f64; N], rendered: [f32; N]) -> bool { + source.map(|v| v as f32) == rendered +} + +fn template_transform(rendered: usvg::Transform, source: Option) -> Affine { + let coeffs = [ + rendered.sx, + rendered.ky, + rendered.kx, + rendered.sy, + rendered.tx, + rendered.ty, + ]; + source + .map(ancestor_transform) + .map(|t| [t.a, t.b, t.c, t.d, t.e, t.f]) + .filter(|t| same_coordinates(*t, coeffs)) + .map_or_else(|| Affine::new(coeffs.map(f64::from)), Affine::new) } /// The bounds of a group's paths in template units: each path's bounds @@ -222,38 +271,34 @@ fn path_bounds(path: &usvg::Path) -> (f64, f64, f64, f64) { fn control_bounds( group: &usvg::Group, to_template: usvg::Transform, -) -> Option<(f64, f64, f64, f64)> { - let mut bounds: Option<(f64, f64, f64, f64)> = None; - for node in group.children() { - let rect = match node { - usvg::Node::Group(inner) => control_bounds(inner, to_template), - usvg::Node::Path(path) => { - let ts = to_template.pre_concat(path.abs_transform()); - let (l, t, r, b) = path_bounds(path); - let corners = [(l, t), (r, t), (l, b), (r, b)].map(|(x, y)| { - ( - f64::from(ts.sx) * x + f64::from(ts.kx) * y + f64::from(ts.tx), - f64::from(ts.ky) * x + f64::from(ts.sy) * y + f64::from(ts.ty), - ) - }); - let xs = corners.map(|c| c.0); - let ys = corners.map(|c| c.1); - Some(( - xs.into_iter().fold(f64::INFINITY, f64::min), - ys.into_iter().fold(f64::INFINITY, f64::min), - xs.into_iter().fold(f64::NEG_INFINITY, f64::max), - ys.into_iter().fold(f64::NEG_INFINITY, f64::max), - )) + source: Option, +) -> Option { + let mut elements = source + .into_iter() + .flat_map(|n| n.children()) + .filter(Node::is_element); + let paired = elements.clone().count() == group.children().len(); + group + .children() + .iter() + .filter_map(|node| { + let element = elements.next().filter(|_| paired); + match node { + usvg::Node::Group(inner) => control_bounds( + inner, + to_template, + element.filter(|n| n.has_tag_name((SVG_NAMESPACE, "g"))), + ), + usvg::Node::Path(path) => { + let source = element.filter(|n| n.has_tag_name((SVG_NAMESPACE, "path"))); + let ts = + template_transform(to_template.pre_concat(path.abs_transform()), source); + Some(ts.transform_rect_bbox(path_bounds(path, source))) + } + _ => None, } - _ => None, - }; - if let Some((l, t, r, b)) = rect { - bounds = Some(bounds.map_or((l, t, r, b), |(bl, bt, br, bb)| { - (bl.min(l), bt.min(t), br.max(r), bb.max(b)) - })); - } - } - bounds + }) + .reduce(|a, b| a.union(b)) } /// A guide line, or a margin bar, in template units. @@ -396,39 +441,48 @@ fn points(units: f64, scale: f64) -> f32 { /// A master's group as an SVG of its own: its outline's bounds in points as /// the view box, and the group's children drawn through a transform that /// scales them to points and moves the outline to the origin. -fn standalone(group: Node, outline: &Outline, scale: f64) -> String { - let t = outline.transform; - let (sx, ky, kx, sy, tx, ty) = ( - f64::from(t.sx), - f64::from(t.ky), - f64::from(t.kx), - f64::from(t.sy), - f64::from(t.tx), - f64::from(t.ty), - ); +fn standalone(group: Node, outline: &Outline, scale: f64, styles: &str) -> String { + let [sx, ky, kx, sy, tx, ty] = outline.transform.as_coeffs(); + let bounds = outline.bounds; + // Transform both origins to points before subtracting. At six significant + // digits, regrouping this calculation can move an antialiased contour. let matrix = [ sx * scale, ky * scale, kx * scale, sy * scale, - (tx - outline.left) * scale, - (ty - outline.top) * scale, + tx * scale - bounds.x0 * scale, + ty * scale - bounds.y0 * scale, ]; let mut out = format!( "\n", - number((outline.right - outline.left) * scale), - number((outline.bottom - outline.top) * scale), - matrix.map(number).join(" "), + xmlns=\"{SVG_NAMESPACE}\" viewBox=\"0 0 {} {}\">", + number(bounds.width() * scale), + number(bounds.height() * scale), ); - for child in group.children() { - write_node(child, &mut out, 0); + if !styles.is_empty() { + let _ = write!(out, "{styles}"); } + let _ = write!( + out, + "", + matrix.map(number).join(" ") + ); + write_children(group, &mut out, 0); out.push_str(""); out } +fn write_children(node: Node, out: &mut String, depth: usize) { + // All stylesheets are already in the standalone SVG's defs, in document order. + for child in node + .children() + .filter(|n| !n.has_tag_name((SVG_NAMESPACE, "style"))) + { + write_node(child, out, depth); + } +} + /// A number the way Xcode writes one, like C's `%g`: six significant /// digits, and an exponent when it's very small or very large. fn number(value: f64) -> String { @@ -542,9 +596,7 @@ fn write_node(node: Node, out: &mut String, depth: usize) { } if node.has_children() { out.push('>'); - for child in node.children() { - write_node(child, out, depth + 1); - } + write_children(node, out, depth + 1); let _ = write!(out, ""); } else { out.push_str("/>"); @@ -628,6 +680,22 @@ fn escape(text: &str) -> String { mod tests { use super::*; + #[test] + fn only_annotations_on_symbol_shapes_advertise_color_layers() { + for (class, expected) in [ + ("monochrome-0", 0), + ("monochrome-0 multicolor-1:custom", 1), + ("hierarchical-0:secondary", 2), + ("multicolor-0:white hierarchical-1:primary", 3), + ] { + let svg = format!( + r#""# + ); + let document = Document::parse(&svg).unwrap(); + assert_eq!(layer_flags(document.root_element()), expected, "{class}"); + } + } + fn fixture(name: &str) -> Vec { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("fixtures/actool/symbols") @@ -635,6 +703,30 @@ mod tests { std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())) } + #[test] + fn symbol_crops_keep_the_precision_of_the_source_control_points() { + // Reduced to the extrema of the CoMaps cycling symbol. Its left edge + // falls halfway between two translations at CoreSVG's output precision. + let template = br#" + + + "#; + let glyphs = masters(template, Sizing::of("iphonesimulator")).unwrap(); + let svg = Document::parse(std::str::from_utf8(&glyphs[0].svg).unwrap()).unwrap(); + assert_eq!( + svg.root_element().attribute("viewBox"), + Some("0 0 12.325 9.10199") + ); + let drawing = svg + .descendants() + .find(|n| n.attribute("id") == Some("s")) + .unwrap(); + assert_eq!( + drawing.attribute("transform"), + Some("matrix(0.17 0 0 0.17 -2.0632 10.5489)") + ); + } + /// A master as Xcode 27's actool wrote it: weight, size, baseline, /// cap line, margins, listed sizes, and the view box and transform of /// its SVG. diff --git a/sweetpad-cli/src/cli/actool/mod.rs b/sweetpad-cli/src/cli/actool/mod.rs index 78e495de..c19983db 100644 --- a/sweetpad-cli/src/cli/actool/mod.rs +++ b/sweetpad-cli/src/cli/actool/mod.rs @@ -154,7 +154,16 @@ fn catalogs(args: &Args) -> Vec { fn generate_symbols(args: &Args) -> Result<(), String> { let frameworks = args.values("--generate-asset-symbol-framework-support"); + let platform = args.value("--platform"); + let mac_catalyst = + platform == Some("macosx") && args.value("--ui-framework-family") == Some("uikit"); let options = Options { + mac_catalyst, + api: symbols::ResourceApi::for_target( + platform, + args.value("--minimum-deployment-target"), + mac_catalyst, + ), bundle_id: args .value("--bundle-identifier") .unwrap_or_default() diff --git a/sweetpad-cli/src/cli/actool/modern.rs b/sweetpad-cli/src/cli/actool/modern.rs index 2cf2fdea..71265bf6 100644 --- a/sweetpad-cli/src/cli/actool/modern.rs +++ b/sweetpad-cli/src/cli/actool/modern.rs @@ -57,8 +57,8 @@ pub(super) fn compile<'a>( identifier, Variant { appearance, - scale: 1, idiom, + ..Variant::ANY }, 0, 1, diff --git a/sweetpad-cli/src/cli/actool/stickers.rs b/sweetpad-cli/src/cli/actool/stickers.rs index 531bae84..d523ee82 100644 --- a/sweetpad-cli/src/cli/actool/stickers.rs +++ b/sweetpad-cli/src/cli/actool/stickers.rs @@ -5,7 +5,7 @@ use std::path::{Path, PathBuf}; use serde_json::{Map, Value, json}; -use super::car::{Appearance, Bitmap, Car, Part, Rendering, Source, Variant}; +use super::car::{Bitmap, Car, Part, Rendering, Source, Variant}; use super::catalog::{Asset, Catalog}; use super::{Args, raster, write}; use crate::cli::xml_plist; @@ -95,9 +95,8 @@ pub(super) fn store_icon<'a>( return false; }; let variant = Variant { - appearance: Appearance::Any, - scale: 1, idiom: 6, + ..Variant::ANY }; let source = Source { vector: false, diff --git a/sweetpad-cli/src/cli/actool/symbols.rs b/sweetpad-cli/src/cli/actool/symbols.rs index 2024b52c..f6814aae 100644 --- a/sweetpad-cli/src/cli/actool/symbols.rs +++ b/sweetpad-cli/src/cli/actool/symbols.rs @@ -10,6 +10,9 @@ use serde_json::{Value, json}; use super::catalog::{Asset, Catalog, Folder, Kind}; +mod deployment; +pub use deployment::ResourceApi; + /// The frameworks that get accessors. #[derive(Debug, Clone, Copy)] pub struct Frameworks { @@ -31,6 +34,8 @@ impl Default for Frameworks { #[derive(Debug)] pub struct Options { pub bundle_id: String, + pub api: ResourceApi, + pub mac_catalyst: bool, /// Accessors on `Color`, `UIColor`, `NSImage` and the rest, as well as the /// resource constants. pub extensions: bool, @@ -111,20 +116,24 @@ impl<'a> Section<'a> { if asset.kind != kind || !asset.has_content { continue; } - let applies = |device: &String| { + let applies = |device: &str| { asset .idioms .iter() .any(|idiom| idiom == "universal" || idiom == device) }; - if !options.target_devices.iter().any(applies) { + // Catalyst can use an iPad rendition on a Mac, but it can be + // thinned out. A Mac or universal rendition is guaranteed. + if !options.target_devices.iter().any(|device| { + applies(device) || (options.mac_catalyst && device == "mac" && applies("ipad")) + }) { continue; } scoped.push(Scoped { catalog, asset, namespaces: namespaces(&chain), - thinnable: !options.target_devices.iter().all(applies), + thinnable: !options.target_devices.iter().all(|device| applies(device)), }); } } @@ -154,13 +163,6 @@ impl<'a> Section<'a> { } } - fn type_name(&self) -> &'static str { - match self.kind { - Kind::Color => "ColorResource", - _ => "ImageResource", - } - } - fn is_empty(&self) -> bool { self.flat.is_empty() } @@ -301,7 +303,7 @@ fn all_caps(words: &[String]) -> bool { /// `Image`, or an all-caps name kept as it is with `_` between its words. fn swift_name(name: &str, suffix: &str) -> String { let mut words = words(name); - if words.len() > 1 && words.last().is_some_and(|w| w == suffix) { + if words.len() > 1 && words.last().is_some_and(|w| w.eq_ignore_ascii_case(suffix)) { words.pop(); } let mut out = if all_caps(&words) { @@ -590,16 +592,15 @@ const UICOLOR_TAKEN: &[&str] = &[ const UIIMAGE_TAKEN: &[&str] = &["actions", "add", "checkmark", "remove", "strokedCheckmark"]; -const AVAILABLE_ALL: &str = "@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)"; - fn swift(colors: &Section, images: &Section, options: &Options) -> String { let f = options.frameworks; - let ext = options.extensions; + let api = options.api; + let import_frameworks = options.extensions || api == ResourceApi::BackDeployed; let mut out = String::from("import Foundation\n"); for (on, module) in [ - (ext && f.appkit, "AppKit"), - (ext && f.uikit, "UIKit"), - (ext && f.swiftui, "SwiftUI"), + (import_frameworks && f.appkit, "AppKit"), + (import_frameworks && f.uikit, "UIKit"), + (import_frameworks && f.swiftui, "SwiftUI"), (true, "DeveloperToolsSupport"), ] { if on { @@ -619,31 +620,41 @@ fn swift(colors: &Section, images: &Section, options: &Options) -> String { Kind::Color => "Color", _ => "Image", }; + let available = api.resource_availability(section.kind); let _ = write!( out, - "// MARK: - {title} Symbols -\n\n{AVAILABLE_ALL}\nextension DeveloperToolsSupport.{} {{\n{}\n}}\n\n", - section.type_name(), + "// MARK: - {title} Symbols -\n\n{available}\nextension {} {{\n{}\n}}\n\n", + api.resource_type(section.kind), body(§ion.tree, 1, &|item, indent| Some(resource_item( - section, item, indent + section, item, indent, api ))), ); } - if !ext { - return out; + if options.extensions { + symbol_extensions(&mut out, colors, images, options); } + if api == ResourceApi::BackDeployed { + deployment::backwards_support(&mut out, f); + } + out +} +fn symbol_extensions(out: &mut String, colors: &Section, images: &Section, options: &Options) { + let f = options.frameworks; + let api = options.api; + let swiftui = api.swiftui_availability(); out.push_str("// MARK: - Color Symbol Extensions -\n\n"); if f.appkit { - out.push_str(&accessor_extension(colors, Host::NsColor)); + out.push_str(&accessor_extension(colors, Host::NsColor, api)); } if f.uikit { - out.push_str(&accessor_extension(colors, Host::UiColor)); + out.push_str(&accessor_extension(colors, Host::UiColor, api)); } if f.swiftui { let _ = write!( out, - "#if canImport(SwiftUI)\n{AVAILABLE_ALL}\nextension SwiftUI.Color {{\n{}\n}}\n\n\ - {AVAILABLE_ALL}\nextension SwiftUI.ShapeStyle where Self == SwiftUI.Color {{\n{}\n}}\n#endif\n\n", + "#if canImport(SwiftUI)\n{swiftui}\nextension SwiftUI.Color {{\n{}\n}}\n\n\ + {swiftui}\nextension SwiftUI.ShapeStyle where Self == SwiftUI.Color {{\n{}\n}}\n#endif\n\n", body(&colors.tree, 1, &|item, indent| accessor_item( colors, Host::Color, @@ -660,15 +671,14 @@ fn swift(colors: &Section, images: &Section, options: &Options) -> String { } out.push_str("// MARK: - Image Symbol Extensions -\n\n"); if f.appkit { - out.push_str(&accessor_extension(images, Host::NsImage)); + out.push_str(&accessor_extension(images, Host::NsImage, api)); } if f.uikit { - out.push_str(&accessor_extension(images, Host::UiImage)); + out.push_str(&accessor_extension(images, Host::UiImage, api)); } out.push_str("// MARK: - Thinnable Asset Support -\n\n"); - out.push_str(&thinnable_support(Kind::Color, f, !colors.is_empty())); - out.push_str(&thinnable_support(Kind::Image, f, !images.is_empty())); - out + out.push_str(&thinnable_support(Kind::Color, f, !colors.is_empty(), api)); + out.push_str(&thinnable_support(Kind::Image, f, !images.is_empty(), api)); } /// A body's items, each with a blank line before and after. @@ -694,7 +704,7 @@ fn depth_of(indent: &str) -> usize { indent.len() / 4 } -fn resource_item(section: &Section, item: &Item, indent: &str) -> String { +fn resource_item(section: &Section, item: &Item, indent: &str, api: ResourceApi) -> String { let kind = section.kind_name(); match item { Item::Symbol(s) => { @@ -708,10 +718,10 @@ fn resource_item(section: &Section, item: &Item, indent: &str) -> String { }; format!( "{indent}/// The \"{}\" asset catalog {kind} resource.\n{watch}\ - {indent}static let {} = DeveloperToolsSupport.{}({label}: \"{}\", bundle: resourceBundle)", + {indent}static let {} = {}({label}: \"{}\", bundle: resourceBundle)", s.full_name, escaped(&s.plain), - section.type_name(), + api.resource_type(section.kind), s.full_name, ) } @@ -726,22 +736,22 @@ fn resource_item(section: &Section, item: &Item, indent: &str) -> String { full_name, type_name, &body(items, depth_of(indent) + 1, &|item, indent| { - Some(resource_item(section, item, indent)) + Some(resource_item(section, item, indent, api)) }), indent, ), } } -fn accessor_extension(section: &Section, host: Host) -> String { +fn accessor_extension(section: &Section, host: Host, api: ResourceApi) -> String { let module = if matches!(host, Host::NsColor | Host::NsImage) { "AppKit" } else { "UIKit" }; - let available = match module { - "AppKit" => "@available(macOS 14.0, *)\n@available(macCatalyst, unavailable)", - _ => "@available(iOS 17.0, tvOS 17.0, *)\n@available(watchOS, unavailable)", + let available = match host { + Host::NsColor | Host::NsImage => api.appkit_availability(section.kind), + _ => api.uikit_availability(), }; format!( "#if canImport({module})\n{available}\nextension {} {{\n{}\n}}\n#endif\n\n", @@ -825,17 +835,20 @@ fn accessor_item(section: &Section, host: Host, item: &Item, indent: &str) -> Op /// The private initializers a thinnable constant and its accessors go /// through. -fn thinnable_support(kind: Kind, f: Frameworks, has_symbols: bool) -> String { - let (resource, appkit_check, uikit_check, nstype, uitype) = match kind { +fn thinnable_support(kind: Kind, f: Frameworks, has_symbols: bool, api: ResourceApi) -> String { + let resource = api.resource_type(kind); + let available = api.resource_availability(kind); + let appkit = api.appkit_availability(kind); + let uikit = api.uikit_availability(); + let swiftui = api.swiftui_availability(); + let (appkit_check, uikit_check, nstype, uitype) = match kind { Kind::Color => ( - "ColorResource", "AppKit.NSColor(named: NSColor.Name(thinnableName), bundle: bundle) != nil", "UIKit.UIColor(named: thinnableName, in: bundle, compatibleWith: nil) != nil", "AppKit.NSColor", "UIKit.UIColor", ), _ => ( - "ImageResource", "bundle.image(forResource: NSImage.Name(thinnableName)) != nil", "UIKit.UIImage(named: thinnableName, in: bundle, compatibleWith: nil) != nil", "AppKit.NSImage", @@ -866,12 +879,12 @@ fn thinnable_support(kind: Kind, f: Frameworks, has_symbols: bool) -> String { } }; let mut out = format!( - "{AVAILABLE_ALL}\n@available(watchOS, unavailable)\nextension DeveloperToolsSupport.{resource} {{\n\n \ + "{available}\n@available(watchOS, unavailable)\nextension {resource} {{\n\n \ private init?(thinnableName: Swift.String, bundle: Foundation.Bundle) {{\n{lookup} }}\n\n}}\n\n" ); - let convenience = |guard: &str, resource: &str| { + let convenience = |guard: &str| { format!( - " private convenience init?(thinnableResource: DeveloperToolsSupport.{resource}?) {{\n\ + " private convenience init?(thinnableResource: {resource}?) {{\n\ #if {guard}\n if let resource = thinnableResource {{\n self.init(resource: resource)\n }} else {{\n return nil\n }}\n\ #else\n return nil\n#endif\n }}\n" ) @@ -879,23 +892,25 @@ fn thinnable_support(kind: Kind, f: Frameworks, has_symbols: bool) -> String { if f.appkit && has_symbols { let _ = write!( out, - "#if canImport(AppKit)\n@available(macOS 14.0, *)\n@available(macCatalyst, unavailable)\nextension {nstype} {{\n\n{}\n}}\n#endif\n\n", - convenience("!targetEnvironment(macCatalyst)", resource), + "#if canImport(AppKit)\n{appkit}\nextension {nstype} {{\n\n{}\n}}\n#endif\n\n", + convenience("!targetEnvironment(macCatalyst)"), ); } if f.uikit { let _ = write!( out, - "#if canImport(UIKit)\n@available(iOS 17.0, tvOS 17.0, *)\n@available(watchOS, unavailable)\nextension {uitype} {{\n\n{}\n}}\n#endif\n\n", - convenience("!os(watchOS)", resource), + "#if canImport(UIKit)\n{uikit}\nextension {uitype} {{\n\n{}\n}}\n#endif\n\n", + convenience("!os(watchOS)"), ); } if kind == Kind::Color && f.swiftui { - let init = " private init?(thinnableResource: DeveloperToolsSupport.ColorResource?) {\n if let resource = thinnableResource {\n self.init(resource)\n } else {\n return nil\n }\n }\n"; + let init = format!( + " private init?(thinnableResource: {resource}?) {{\n if let resource = thinnableResource {{\n self.init(resource)\n }} else {{\n return nil\n }}\n }}\n" + ); let _ = write!( out, - "#if canImport(SwiftUI)\n{AVAILABLE_ALL}\nextension SwiftUI.Color {{\n\n{init}\n}}\n\n\ - {AVAILABLE_ALL}\nextension SwiftUI.ShapeStyle where Self == SwiftUI.Color {{\n\n{init}\n}}\n#endif\n\n" + "#if canImport(SwiftUI)\n{swiftui}\nextension SwiftUI.Color {{\n\n{init}\n}}\n\n\ + {swiftui}\nextension SwiftUI.ShapeStyle where Self == SwiftUI.Color {{\n\n{init}\n}}\n#endif\n\n" ); } out @@ -991,6 +1006,8 @@ mod tests { for (name, swift) in [ ("BrandRed", "brandRed"), ("URLColor", "URL"), + ("TEXT_COLOR", "TEXT"), + ("white_color", "white"), ("myURLColor", "myURL"), ("1stColor", "_1St"), ("HTML5Color", "HTML_5"), @@ -1003,6 +1020,7 @@ mod tests { ] { assert_eq!(swift_name(name, "Color"), swift, "{name}"); } + assert_eq!(swift_name("separator_image", "Image"), "separator"); assert_eq!(objc_name("A_B"), "_A_B"); assert_eq!(objc_name("Ünïcode"), "ncode"); assert_eq!(type_name("my icons"), "MyIcons"); diff --git a/sweetpad-cli/src/cli/actool/symbols/appkit.swift b/sweetpad-cli/src/cli/actool/symbols/appkit.swift new file mode 100644 index 00000000..f86b5e1d --- /dev/null +++ b/sweetpad-cli/src/cli/actool/symbols/appkit.swift @@ -0,0 +1,26 @@ +#if canImport(AppKit) +@available(macOS 10.13, *) +@available(macCatalyst, unavailable) +extension AppKit.NSColor { + + /// Initialize a `NSColor` with a color resource. + convenience init(resource: ColorResource) { + self.init(named: NSColor.Name(resource.name), bundle: resource.bundle)! + } + +} + +protocol _ACResourceInitProtocol {} +extension AppKit.NSImage: _ACResourceInitProtocol {} + +@available(macOS 10.7, *) +@available(macCatalyst, unavailable) +extension _ACResourceInitProtocol { + + /// Initialize a `NSImage` with an image resource. + init(resource: ImageResource) { + self = resource.bundle.image(forResource: NSImage.Name(resource.name))! as! Self + } + +} +#endif diff --git a/sweetpad-cli/src/cli/actool/symbols/deployment.rs b/sweetpad-cli/src/cli/actool/symbols/deployment.rs new file mode 100644 index 00000000..86dd7113 --- /dev/null +++ b/sweetpad-cli/src/cli/actool/symbols/deployment.rs @@ -0,0 +1,130 @@ +//! Swift asset resource types entered the SDKs in the 2023 OS releases. +//! Earlier deployment targets get bundle-backed types in the generated module. +use super::{Frameworks, Kind}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ResourceApi { + System, + BackDeployed, +} + +const SYSTEM_AVAILABILITY: &str = "@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)"; + +impl ResourceApi { + pub fn for_target(platform: Option<&str>, minimum: Option<&str>, mac_catalyst: bool) -> Self { + let first_system_major = match platform { + Some("iphoneos" | "iphonesimulator" | "appletvos" | "appletvsimulator") => 17, + Some("macosx") if mac_catalyst => 17, + Some("macosx") => 14, + Some("watchos" | "watchsimulator") => 10, + // All visionOS versions provide the SDK types. With no target, + // preserve the standalone generator's SDK-based output. + _ => return Self::System, + }; + let major = minimum.and_then(|v| v.split('.').next()?.parse::().ok()); + if major.is_some_and(|v| v < first_system_major) { + Self::BackDeployed + } else { + Self::System + } + } + + pub(super) fn resource_type(self, kind: Kind) -> &'static str { + match (self, kind) { + (Self::System, Kind::Color) => "DeveloperToolsSupport.ColorResource", + (Self::System, _) => "DeveloperToolsSupport.ImageResource", + (Self::BackDeployed, Kind::Color) => "ColorResource", + (Self::BackDeployed, _) => "ImageResource", + } + } + + pub(super) fn resource_availability(self, kind: Kind) -> &'static str { + match (self, kind) { + (Self::System, _) => SYSTEM_AVAILABILITY, + (Self::BackDeployed, Kind::Color) => "@available(iOS 11.0, macOS 10.13, tvOS 11.0, *)", + (Self::BackDeployed, _) => "@available(iOS 11.0, macOS 10.7, tvOS 11.0, *)", + } + } + + pub(super) fn appkit_availability(self, kind: Kind) -> &'static str { + match (self, kind) { + (Self::System, _) => "@available(macOS 14.0, *)\n@available(macCatalyst, unavailable)", + (Self::BackDeployed, Kind::Color) => { + "@available(macOS 10.13, *)\n@available(macCatalyst, unavailable)" + } + (Self::BackDeployed, _) => { + "@available(macOS 10.7, *)\n@available(macCatalyst, unavailable)" + } + } + } + + pub(super) fn uikit_availability(self) -> &'static str { + match self { + Self::System => "@available(iOS 17.0, tvOS 17.0, *)\n@available(watchOS, unavailable)", + Self::BackDeployed => { + "@available(iOS 11.0, tvOS 11.0, *)\n@available(watchOS, unavailable)" + } + } + } + + pub(super) fn swiftui_availability(self) -> &'static str { + match self { + Self::System => SYSTEM_AVAILABILITY, + Self::BackDeployed => "@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)", + } + } +} + +// Kept as Swift so the exact initializers and their platform guards are readable. +pub(super) fn backwards_support(out: &mut String, frameworks: Frameworks) { + out.push_str(include_str!("resources.swift").trim_end()); + for (enabled, source) in [ + (frameworks.appkit, include_str!("appkit.swift")), + (frameworks.uikit, include_str!("uikit.swift")), + (frameworks.swiftui, include_str!("swiftui.swift")), + ] { + if enabled { + out.push_str("\n\n"); + out.push_str(source.trim_end()); + } + } +} + +#[cfg(test)] +mod tests { + use super::ResourceApi::{self, BackDeployed, System}; + + #[test] + fn uses_the_sdk_types_starting_with_each_platforms_first_supported_release() { + for (platform, mac_catalyst, last_old, first_new) in [ + ("iphoneos", false, "16.7.10", "17.0"), + ("iphonesimulator", false, "15.6", "17"), + ("appletvos", false, "16.6", "17.0"), + ("appletvsimulator", false, "16.6", "17.0"), + ("macosx", false, "13.6.1", "14"), + ("macosx", true, "16.4", "17.0"), + ("watchos", false, "9.6", "10.0"), + ("watchsimulator", false, "9.6", "10.0"), + ] { + assert_eq!( + ResourceApi::for_target(Some(platform), Some(last_old), mac_catalyst), + BackDeployed + ); + assert_eq!( + ResourceApi::for_target(Some(platform), Some(first_new), mac_catalyst), + System + ); + } + for platform in ["xros", "xrsimulator"] { + assert_eq!( + ResourceApi::for_target(Some(platform), Some("1.0"), false), + System + ); + } + assert_eq!(ResourceApi::for_target(None, None, false), System); + assert_eq!( + ResourceApi::for_target(Some("iphoneos"), None, false), + System + ); + } +} diff --git a/sweetpad-cli/src/cli/actool/symbols/resources.swift b/sweetpad-cli/src/cli/actool/symbols/resources.swift new file mode 100644 index 00000000..b7da6d04 --- /dev/null +++ b/sweetpad-cli/src/cli/actool/symbols/resources.swift @@ -0,0 +1,35 @@ +// MARK: - Backwards Deployment Support - + +/// A color resource. +struct ColorResource: Swift.Hashable, Swift.Sendable { + + /// An asset catalog color resource name. + fileprivate let name: Swift.String + + /// An asset catalog color resource bundle. + fileprivate let bundle: Foundation.Bundle + + /// Initialize a `ColorResource` with `name` and `bundle`. + init(name: Swift.String, bundle: Foundation.Bundle) { + self.name = name + self.bundle = bundle + } + +} + +/// An image resource. +struct ImageResource: Swift.Hashable, Swift.Sendable { + + /// An asset catalog image resource name. + fileprivate let name: Swift.String + + /// An asset catalog image resource bundle. + fileprivate let bundle: Foundation.Bundle + + /// Initialize an `ImageResource` with `name` and `bundle`. + init(name: Swift.String, bundle: Foundation.Bundle) { + self.name = name + self.bundle = bundle + } + +} diff --git a/sweetpad-cli/src/cli/actool/symbols/swiftui.swift b/sweetpad-cli/src/cli/actool/symbols/swiftui.swift new file mode 100644 index 00000000..55654646 --- /dev/null +++ b/sweetpad-cli/src/cli/actool/symbols/swiftui.swift @@ -0,0 +1,21 @@ +#if canImport(SwiftUI) +@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) +extension SwiftUI.Color { + + /// Initialize a `Color` with a color resource. + init(_ resource: ColorResource) { + self.init(resource.name, bundle: resource.bundle) + } + +} + +@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) +extension SwiftUI.Image { + + /// Initialize an `Image` with an image resource. + init(_ resource: ImageResource) { + self.init(resource.name, bundle: resource.bundle) + } + +} +#endif diff --git a/sweetpad-cli/src/cli/actool/symbols/uikit.swift b/sweetpad-cli/src/cli/actool/symbols/uikit.swift new file mode 100644 index 00000000..9c9ddfdd --- /dev/null +++ b/sweetpad-cli/src/cli/actool/symbols/uikit.swift @@ -0,0 +1,31 @@ +#if canImport(UIKit) +@available(iOS 11.0, tvOS 11.0, *) +@available(watchOS, unavailable) +extension UIKit.UIColor { + + /// Initialize a `UIColor` with a color resource. + convenience init(resource: ColorResource) { +#if !os(watchOS) + self.init(named: resource.name, in: resource.bundle, compatibleWith: nil)! +#else + self.init() +#endif + } + +} + +@available(iOS 11.0, tvOS 11.0, *) +@available(watchOS, unavailable) +extension UIKit.UIImage { + + /// Initialize a `UIImage` with an image resource. + convenience init(resource: ImageResource) { +#if !os(watchOS) + self.init(named: resource.name, in: resource.bundle, compatibleWith: nil)! +#else + self.init() +#endif + } + +} +#endif diff --git a/sweetpad-cli/src/cli/actool/tests.rs b/sweetpad-cli/src/cli/actool/tests.rs index 994d8393..0fd76878 100644 --- a/sweetpad-cli/src/cli/actool/tests.rs +++ b/sweetpad-cli/src/cli/actool/tests.rs @@ -1,6 +1,7 @@ use std::path::Path; use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; use super::catalog::Catalog; use super::symbols::{self, Frameworks, Options}; @@ -105,6 +106,8 @@ fn probe_catalog(dir: &Path) -> Catalog { fn options(extensions: bool, frameworks: Frameworks) -> Options { Options { bundle_id: "dev.sweetpad.Probe".into(), + api: symbols::ResourceApi::System, + mac_catalyst: false, extensions, frameworks, target_devices: vec!["iphone".into(), "ipad".into()], @@ -143,7 +146,9 @@ fn symbols_match_actool_in_every_mode() { uikit: false, swiftui: true, }; - for (mode, opts) in [ + let back_deployed: Value = + serde_json::from_str(&fixture("expected/back-deployed-sha256.json")).unwrap(); + for (mode, mut opts) in [ ("extensions", options(true, Frameworks::default())), ("no-extensions", options(false, Frameworks::default())), ("swiftui", options(true, swiftui)), @@ -159,6 +164,32 @@ fn symbols_match_actool_in_every_mode() { &fixture("expected/symbols.h"), &format!("{mode} header"), ); + opts.api = symbols::ResourceApi::BackDeployed; + let swift = symbols::generate(&catalogs, &opts).swift; + assert_eq!( + format!("{:x}", Sha256::digest(swift.as_bytes())), + back_deployed[mode].as_str().unwrap(), + "iOS 15.6 {mode} output differs from Xcode's actool", + ); + } +} + +#[test] +fn catalyst_keeps_ipad_only_assets_as_thinnable_resources() { + let dir = TempDir::new("sweetpad-actool-catalyst"); + let catalog = probe_catalog(&dir); + let mut opts = options(true, Frameworks::default()); + opts.target_devices = vec!["mac".into()]; + opts.mac_catalyst = true; + for api in [ + symbols::ResourceApi::BackDeployed, + symbols::ResourceApi::System, + ] { + opts.api = api; + let swift = symbols::generate(std::slice::from_ref(&catalog), &opts).swift; + assert!(swift.contains(r#"ImageResource(thinnableName: "PadOnly""#)); + assert!(swift.contains(r#"ColorResource(name: "MacOnly""#)); + assert!(!swift.contains("PhoneOnly")); } } @@ -856,6 +887,133 @@ fn platform_args(catalog: &Path, out: &Path, platform: &str) -> Args { Args::parse(&command_line) } +#[test] +fn image_direction_keys_and_mirroring_follow_the_declared_slots() { + let temp = TempDir::new("sweetpad-actool-direction"); + let catalog = temp.join("Direction.xcassets"); + let set = catalog.join("Arrow.imageset"); + std::fs::create_dir_all(&set).unwrap(); + std::fs::write(set.join("arrow.png"), png_of(8, [0, 0, 255, 255])).unwrap(); + let fixed = json!({"filename": "arrow.png", "scale": "2x"}); + let left = + json!({"filename": "arrow.png", "scale": "1x", "language-direction": "left-to-right"}); + let right = + json!({"filename": "arrow.png", "scale": "2x", "language-direction": "right-to-left"}); + let empty_right = json!({"scale": "2x", "language-direction": "right-to-left"}); + let invalid = json!({"filename": "arrow.png", "language-direction": "unknown"}); + for (entries, expected) in [ + (json!([fixed]), vec![(0, false)]), + (json!([left, invalid]), vec![(5, true)]), + (json!([right]), vec![(4, true)]), + (json!([left, right]), vec![(4, false), (5, false)]), + (json!([left, empty_right]), vec![(5, false)]), + (json!([fixed, left]), vec![(0, false), (0, false)]), + ] { + write_json(&set.join("Contents.json"), &json!({"images": entries})); + for platform in [ + "iphonesimulator", + "macosx", + "watchsimulator", + "appletvsimulator", + "xrsimulator", + ] { + let out = temp.join(platform); + compile::compile(&platform_args(&catalog, &out, platform)).unwrap(); + let data = std::fs::read(out.join("Assets.car")).unwrap(); + let store = super::car::tests::Store::read(&data); + let direction = store.variable("KEYFORMAT")[12..] + .chunks_exact(4) + .position(|attr| attr == 4u32.to_le_bytes()); + assert_eq!( + direction, + expected.iter().any(|&(d, _)| d != 0).then_some(5), + "{platform}: {entries}" + ); + let (records, _) = store.tree("RENDITIONS"); + let mut actual: Vec<_> = records + .iter() + .map(|(key, value)| { + let code = + direction.map_or(0, |i| u16::from_le_bytes([key[2 * i], key[2 * i + 1]])); + (code, value[8] & 0x40 != 0) + }) + .collect(); + actual.sort_unstable(); + assert_eq!(actual, expected, "{platform}: {entries}"); + } + } +} + +#[test] +fn only_the_size_class_axes_used_by_targeted_images_widen_the_catalog() { + let temp = TempDir::new("sweetpad-actool-size-classes"); + let catalog = temp.join("Sizes.xcassets"); + let set = catalog.join("Pin.imageset"); + std::fs::create_dir_all(&set).unwrap(); + std::fs::write(set.join("pin.png"), png_of(8, [0, 0, 255, 255])).unwrap(); + let base = json!({"idiom": "universal", "scale": "1x", "filename": "pin.png"}); + for (horizontal, vertical) in [ + (None, None), + (Some("compact"), None), + (None, Some("regular")), + (Some("compact"), Some("regular")), + ] { + let mut entries = vec![base.clone()]; + let mut slot = base.clone(); + if let Some(value) = horizontal { + slot["width-class"] = json!(value); + } + if let Some(value) = vertical { + slot["height-class"] = json!(value); + } + if slot != base { + entries.push(slot); + } + // Xcode represents the default by omitting the axis. Invalid selectors + // must never become extra copies of the default rendition. + for value in ["any", "unsupported"] { + let mut invalid = base.clone(); + invalid["width-class"] = json!(value); + entries.push(invalid); + } + write_json(&set.join("Contents.json"), &json!({"images": entries})); + for platform in [ + "iphoneos", + "iphonesimulator", + "xros", + "xrsimulator", + "macosx", + "appletvsimulator", + "watchsimulator", + ] { + let out = temp.join(platform); + compile::compile(&platform_args(&catalog, &out, platform)).unwrap(); + let records = renditions(&out.join("Assets.car")); + let supported = matches!( + platform, + "iphoneos" | "iphonesimulator" | "xros" | "xrsimulator" + ); + let width = horizontal.is_some() && supported; + let height = vertical.is_some() && supported; + let mut slots = Vec::new(); + for (key, _, _) in records { + assert_eq!(key.contains_key(&20), width, "{platform} horizontal axis"); + assert_eq!(key.contains_key(&21), height, "{platform} vertical axis"); + slots.push(( + key.get(&20).copied().unwrap_or(0), + key.get(&21).copied().unwrap_or(0), + )); + } + slots.sort_unstable(); + let mut expected = vec![(0, 0)]; + if width || height { + expected.push((u16::from(width), 2 * u16::from(height))); + } + assert_eq!(slots, expected, "{platform} {horizontal:?} {vertical:?}"); + } + } +} + #[test] fn vector_images_are_drawn_at_each_scale_the_platform_has() { let dir = TempDir::new("sweetpad-actool-vectors"); @@ -973,6 +1131,81 @@ fn a_symbol_set_goes_in_as_the_masters_its_template_draws() { ); } +#[test] +fn a_symbol_sets_rendering_intent_selects_its_coreui_mode() { + let dir = TempDir::new("sweetpad-actool-symbol-intents"); + let catalog = dir.join("Intents.xcassets"); + let cases = [ + ("automatic", 0), + ("template", 1), + ("multicolor", 2), + ("hierarchical", 3), + ("palette", 4), + ("monochrome", 0), + ]; + for (name, _) in cases { + write_json( + &catalog.join(format!("{name}.symbolset/Contents.json")), + &json!({"properties": {"symbol-rendering-intent": name}}), + ); + } + let parsed = Catalog::read(&catalog); + let modes: std::collections::BTreeMap<_, _> = parsed + .assets() + .into_iter() + .map(|(_, asset)| (asset.name.as_str(), asset.symbol.unwrap() as u32)) + .collect(); + assert_eq!(modes, cases.into()); +} + +#[test] +fn layered_symbol_masters_retain_their_styles_intent_and_shared_margins() { + let dir = TempDir::new("sweetpad-actool-symbol-layers"); + let catalog = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures/actool/resources/LayeredSymbols.xcassets"); + let out = dir.join("out"); + compile::compile(&platform_args(&catalog, &out, "iphonesimulator")).unwrap(); + let data = std::fs::read(out.join("Assets.car")).unwrap(); + let (rows, _) = super::car::tests::Store::read(&data).tree("RENDITIONS"); + assert_eq!(rows.len(), 2); + for (_, row) in rows { + let word = |at| u32::from_le_bytes(row[at..at + 4].try_into().unwrap()); + let end = 184 + word(168) as usize; + let mut fields = std::collections::BTreeMap::new(); + let mut at = 184; + while at < end { + fields.insert(word(at), at + 8); + at += 8 + word(at + 4) as usize; + } + // Xcode records multicolor intent (2) and both layer flags (3) + // even though these two static masters cannot interpolate. + let modes = fields[&1019]; + assert_eq!((word(modes + 4), word(modes + 8)), (2, 3)); + let metrics = fields[&1018]; + for (offset, expected) in [(20, 0.85), (28, 1.7)] { + assert!((f32::from_bits(word(metrics + offset)) - expected).abs() < 1e-5); + } + let svg = std::str::from_utf8(&row[end + 12..]).unwrap(); + let document = resvg::usvg::roxmltree::Document::parse(svg).unwrap(); + let css = document + .descendants() + .find(|n| n.has_tag_name("style")) + .unwrap() + .text() + .unwrap(); + for rule in [ + "-sfsymbols-clear-behind:true", + "fill:#227744", + "fill:#FFAA33", + ] { + assert!( + css.contains(rule), + "{rule} missing from the standalone master" + ); + } + } +} + #[test] fn a_set_that_preserves_vector_data_says_so_on_its_bitmaps() { let dir = TempDir::new("sweetpad-actool-preserved"); diff --git a/sweetpad-cli/src/cli/actool/vector.rs b/sweetpad-cli/src/cli/actool/vector.rs index 8a1deffa..21b2256a 100644 --- a/sweetpad-cli/src/cli/actool/vector.rs +++ b/sweetpad-cli/src/cli/actool/vector.rs @@ -235,6 +235,26 @@ pub(super) mod tests { assert_eq!(pixel(0, 19), [255, 0, 0, 255]); } + #[test] + fn pdf_alpha_masks_work_without_a_group_color_space() { + let bytes = include_bytes!( + "../../../fixtures/actool/resources/PdfMasks.xcassets/AlphaCutout.imageset/Cutout.pdf" + ); + let drawing = Drawing::parse(Format::Pdf, bytes.to_vec()).unwrap(); + for scale in [1u16, 2, 3] { + let bitmap = drawing.render(f32::from(scale)).unwrap(); + let scale = usize::from(scale); + let pixel = |x: usize, y: usize| bitmap.pixel(x * scale, y * scale); + // A black alpha mask reveals the blue fill, with a hole and a half-opacity inset. + assert_eq!(pixel(0, 0), [0; 4]); + assert_eq!(pixel(3, 3), [255, 0, 0, 255]); + assert_eq!(pixel(6, 6), [0; 4]); + let [blue, green, red, alpha] = pixel(8, 6); + assert_eq!((blue, green, red), (alpha, 0, 0)); + assert!(alpha.abs_diff(128) <= 1, "half-opacity inset: {alpha}"); + } + } + #[test] fn an_svg_rounds_up_and_counts_72_units_an_inch() { let svg = |attributes: &str| { diff --git a/sweetpad-cli/src/cli/ibtool/mod.rs b/sweetpad-cli/src/cli/ibtool/mod.rs index 335dac48..395d1847 100644 --- a/sweetpad-cli/src/cli/ibtool/mod.rs +++ b/sweetpad-cli/src/cli/ibtool/mod.rs @@ -32,6 +32,7 @@ use std::process::ExitCode; struct Args { version: bool, module: String, + deployment_major: Option, compilation_directory: Option, compile: Option, link: Option, @@ -95,6 +96,10 @@ fn parse_args(args: &[String]) -> Result { "--link" => parsed.link = path, "--output-partial-info-plist" => parsed.partial_info_plist = path, "--module" => parsed.module = value, + "--minimum-deployment-target" => { + parsed.deployment_major = + value.split('.').next().and_then(|major| major.parse().ok()); + } "--output-format" => parsed.output_format = output::Format::parse(&value)?, "--strip" => parsed.strip = path, "--flatten" => { @@ -236,7 +241,7 @@ fn compile(input: &Path, args: &Args) -> Result<(), String> { .unwrap_or("Storyboard"); if args.compile.is_none() && args.compilation_directory.is_none() { if extension == "xib" { - xib::compile(&document, &options)?; + xib::compile(&document, &options, args.deployment_major)?; } else if document.attr("targetRuntime") == Some("watchKit") { watch::compile(&document, &options)?; } else { @@ -269,7 +274,7 @@ fn compile(input: &Path, args: &Args) -> Result<(), String> { Vec::new() }; if extension == "xib" { - let compiled = xib::compile(&document, &options)?; + let compiled = xib::compile(&document, &options, args.deployment_major)?; package::write_xib( &out, &compiled, diff --git a/sweetpad-cli/src/cli/ibtool/storyboard/controllers.rs b/sweetpad-cli/src/cli/ibtool/storyboard/controllers.rs index a8194ab7..609b11dc 100644 --- a/sweetpad-cli/src/cli/ibtool/storyboard/controllers.rs +++ b/sweetpad-cli/src/cli/ibtool/storyboard/controllers.rs @@ -821,6 +821,15 @@ fn controller_metadata( nav_items: &HashMap, ) -> Result<(), String> { let controller_id = id(controller)?; + if let Some(size) = controller.children_named("value").find(|e| { + e.attr("key") == Some("contentSizeForViewInPopover") && e.attr("type") == Some("size") + }) { + let value = crate::cli::ibtool::nib::doubles(&[ + crate::cli::ibtool::uikit::number(size, "width")?.unwrap_or(0.0), + crate::cli::ibtool::uikit::number(size, "height")?.unwrap_or(0.0), + ]); + encoder.graph.set(object, "UIPreferredContentSize", value); + } let templates: Vec = segues(controller) .iter() .filter_map(|s| encoder.lookup(s.attr("id")?)) diff --git a/sweetpad-cli/src/cli/ibtool/tests.rs b/sweetpad-cli/src/cli/ibtool/tests.rs index ef10baf7..965b69ee 100644 --- a/sweetpad-cli/src/cli/ibtool/tests.rs +++ b/sweetpad-cli/src/cli/ibtool/tests.rs @@ -9,6 +9,7 @@ use super::nib::read::{self, Read}; use super::*; use crate::cli::keyed_archive::{self, Plist}; use crate::cli::testdir::TempDir; +mod comaps; mod normalize; mod operations; @@ -527,7 +528,7 @@ fn a_view_it_doesnt_know_is_refused_by_name() { - + "#, @@ -536,7 +537,7 @@ fn a_view_it_doesnt_know_is_refused_by_name() { let Err(error) = storyboard::compile(&document, &Options::default()) else { panic!("compiled"); }; - assert!(error.contains(""), "{error}"); + assert!(error.contains(""), "{error}"); } /// Renumbering a loading boundary is harmless; changing the destination of diff --git a/sweetpad-cli/src/cli/ibtool/tests/comaps.rs b/sweetpad-cli/src/cli/ibtool/tests/comaps.rs new file mode 100644 index 00000000..5cb44b89 --- /dev/null +++ b/sweetpad-cli/src/cli/ibtool/tests/comaps.rs @@ -0,0 +1,381 @@ +//! Regression probes for the constructs used by CoMaps. These inspect the +//! archive graph, including runtime setters and connection destinations. +//! Adapted from [Casper van Elteren’s CoMaps Linux patch](https://github.com/cvanelteren/comaps-ios-linux/blob/ddf82e9d55a3eb910893d37c3d9959b97e47a2d7/sweetpad.patch). +use super::*; + +fn compile_xib(body: &str) -> Result, String> { + let document = sweetpad_lib::xcscheme::parse(&format!( + r#"{body}"# + )).unwrap(); + xib::compile( + &document, + &Options { + module: "Maps", + localized: false, + }, + None, + ) + .map(|bytes| read::parse(&bytes)) +} +fn value<'a>(object: &'a read::Object, key: &str) -> &'a Read { + &object + .values + .iter() + .find(|(k, _)| k == key) + .unwrap_or_else(|| panic!("missing {key} in {object:?}")) + .1 +} +fn reference(object: &read::Object, key: &str) -> usize { + match value(object, key) { + Read::Object(id) => *id, + other => panic!("not a reference: {other:?}"), + } +} +fn string(object: &read::Object) -> &str { + match value(object, "NS.bytes") { + Read::Data(bytes) => std::str::from_utf8(bytes).unwrap(), + other => panic!("not a string: {other:?}"), + } +} +fn class<'a>(objects: &'a [read::Object], name: &str) -> &'a read::Object { + objects + .iter() + .find(|o| o.class == name) + .unwrap_or_else(|| panic!("no {name}")) +} +fn dictionary(objects: &[read::Object], id: usize) -> BTreeMap { + let refs: Vec<_> = objects[id] + .values + .iter() + .filter_map(|(key, value)| match value { + Read::Object(id) if key == nib::ELEMENT => Some(*id), + _ => None, + }) + .collect(); + refs.chunks_exact(2) + .map(|pair| (string(&objects[pair[0]]).to_owned(), pair[1])) + .collect() +} + +#[test] +fn webkit_playback_options_use_xcodes_boolean_archive_field() { + for (attributes, expected) in [ + ("", false), + (r#"none="YES""#, false), + (r#"audio="YES""#, true), + (r#"video="YES""#, true), + (r#"audio="YES" video="YES""#, true), + (r#"all="YES""#, true), + ] { + let body = format!( + r#" + + "# + ); + let objects = compile_xib(&body).unwrap(); + assert_eq!( + value( + class(&objects, "WKWebViewConfiguration"), + "mediaTypesRequiringUserActionForPlayback" + ), + &Read::Bool(expected), + "{attributes}" + ); + } +} + +#[test] +fn standalone_collection_cell_installs_its_safe_area_constraint_on_content_view() { + let source = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/fixtures/ibtool/runtime/comaps/CoMapsCells.xib" + )); + for source in [ + source.to_string(), + source.replace(r#" id="map-item-content""#, ""), + ] { + let document = sweetpad_lib::xcscheme::parse(&source).unwrap(); + let objects = read::parse(&xib::compile(&document, &Options::default(), Some(15)).unwrap()); + let cell = class(&objects, "UICollectionViewCell"); + let content = reference(cell, "UIContentView"); + let constraint = objects.iter().find(|o| o.values.iter().any(|(key, value)| { + matches!(value, Read::Object(i) if key == "NSLayoutIdentifier" && string(&objects[*i]) == "item-safe-width") + })).unwrap(); + let guide = &objects[reference(constraint, "NSFirstItem")]; + assert_eq!(reference(guide, "UILayoutGuideOwningView"), content); + } +} + +#[test] +fn attributed_text_preserves_font_color_paragraph_and_unicode_runs() { + let body = r#" + + + + + "#; + let objects = compile_xib(body).unwrap(); + let text = class(&objects, "UITextView"); + let styled = &objects[reference(text, "UIAttributedText")]; + assert_eq!(styled.class, "NSAttributedString"); + assert_eq!(string(&objects[reference(styled, "NSString")]), "Message😀"); + let attrs = dictionary(&objects, reference(styled, "NSAttributes")); + let font = &objects[attrs["NSFont"]]; + assert_eq!( + string(&objects[reference(font, "UIFontName")]), + "HelveticaNeue" + ); + assert_eq!(value(font, "UIFontPointSize"), &Read::Double(14.0)); + assert_eq!( + value(&objects[attrs["NSColor"]], "UIAlpha"), + &Read::Float(0.54) + ); + assert_eq!( + value(&objects[attrs["NSParagraphStyle"]], "NSWritingDirection"), + &Read::Int(-1) + ); + assert!( + !styled + .values + .iter() + .any(|(key, _)| key == "NSAttributeInfo") + ); + let multi = body.replace("", ""); + let objects = compile_xib(&multi).unwrap(); + let styled = class(&objects, "NSAttributedString"); + let info = &objects[reference(styled, "NSAttributeInfo")]; + assert_eq!(value(info, "NS.bytes"), &Read::Data(vec![9, 0, 1, 1])); + assert_eq!( + string(&objects[reference(styled, "NSString")]), + "Message😀é" + ); + let bad = body.replace(""# + ); + for (tag, class_name) in [("label", "UILabel"), ("textView", "UITextView")] { + let body = format!(r#"<{tag} id="text" usesAttributedText="YES">{styled}"#); + let objects = compile_xib(&body).unwrap(); + let view = class(&objects, class_name); + let archive = &objects[reference(view, "UIAttributedText")]; + let info = &objects[reference(archive, "NSAttributeInfo")]; + assert_eq!(value(info, "NS.bytes"), &Read::Data(vec![0x82, 1, 0, 1, 1])); + let wrong_key = body.replace(r#"key="attributedText""#, r#"key="other""#); + assert!( + compile_xib(&wrong_key) + .unwrap_err() + .contains("") + ); + } + let plain = + format!(r#""#); + let objects = compile_xib(&plain).unwrap(); + let label = class(&objects, "UILabel"); + assert_eq!(string(&objects[reference(label, "UIText")]), "Plain"); + assert!( + !label + .values + .iter() + .any(|(key, _)| key == "UIAttributedText") + ); +} + +#[test] +fn custom_collection_layout_is_swapped_and_connected() { + for tag in ["collectionViewLayout", "collectionViewFlowLayout"] { + let objects = compile_xib(&format!(r#" + <{tag} key="collectionViewLayout" id="layout" customClass="TransportTransitFlowLayout" customModule="CoMaps" customModuleProvider="target"> + + + + "#)).unwrap(); + let collection = class(&objects, "UICollectionView"); + let layout_id = reference(collection, "UICollectionLayout"); + let layout = &objects[layout_id]; + assert_eq!(layout.class, "UIClassSwapper"); + assert_eq!( + string(&objects[reference(layout, "UIClassName")]), + "_TtC4Maps26TransportTransitFlowLayout" + ); + assert_eq!( + string(&objects[reference(layout, "UIOriginalClassName")]), + if tag == "collectionViewLayout" { + "UICollectionViewLayout" + } else { + "UICollectionViewFlowLayout" + } + ); + let outlet = class(&objects, "UIRuntimeOutletConnection"); + assert_eq!(reference(outlet, "UIDestination"), layout_id); + let pair = class(&objects, "UINibKeyValuePair"); + assert_eq!(reference(pair, "UIObject"), layout_id); + assert_eq!(string(&objects[reference(pair, "UIKeyPath")]), "spacing"); + } +} + +#[test] +fn date_picker_retains_mode_interval_locale_style_dates_and_actions() { + let body = r#" + + + + + + "#; + let objects = compile_xib(body).unwrap(); + let picker = objects + .iter() + .position(|o| o.class == "UIDatePicker") + .unwrap(); + let mut properties = BTreeMap::new(); + for pair in objects.iter().filter(|o| o.class == "UINibKeyValuePair") { + assert_eq!(reference(pair, "UIObject"), picker); + properties.insert( + string(&objects[reference(pair, "UIKeyPath")]), + reference(pair, "UIValue"), + ); + } + for (key, expected) in [ + ("datePickerMode", 0), + ("minuteInterval", 5), + ("preferredDatePickerStyle", 1), + ] { + assert_eq!( + value(&objects[properties[key]], "NS.intval"), + &Read::Int(expected) + ); + } + let locale = &objects[properties["locale"]]; + assert_eq!(locale.class, "NSLocale"); + assert_eq!(string(&objects[reference(locale, "NS.identifier")]), "ru"); + assert_eq!( + value(&objects[properties["minimumDate"]], "NS.time"), + &Read::Double(12345.0) + ); + let action = class(&objects, "UIRuntimeEventConnection"); + assert_eq!(reference(action, "UISource"), picker); + assert_eq!( + objects[reference(action, "UIDestination")].class, + "UIProxyObject" + ); + assert_eq!(value(action, "UIEventMask"), &Read::Int(4096)); + assert_eq!( + string(&objects[reference(action, "UILabel")]), + "openValueChanged" + ); + assert!(compile_xib(&body.replace("minuteInterval=\"5\"", "minuteInterval=\"7\"")).is_err()); + assert!(compile_xib(&body.replace("style=\"wheels\"", "style=\"bogus\"")).is_err()); +} + +#[test] +fn image_traits_keep_both_images_and_the_trait_condition() { + let objects = compile_xib( + r#" + + "#, + ) + .unwrap(); + let storage = class(&objects, "_UIAttributeTraitStorage"); + assert_eq!(string(&objects[reference(storage, "UIKeyPath")]), "image"); + assert_eq!(objects[reference(storage, "UIObject")].class, "UIImageView"); + let records = &objects[reference(storage, "UIRecords")]; + let refs: Vec<_> = records + .values + .iter() + .filter_map(|(_, v)| match v { + Read::Object(i) => Some(*i), + _ => None, + }) + .collect(); + assert_eq!(refs.len(), 2); + for (record, name) in refs.iter().zip(["direction_big", "direction"]) { + let image = &objects[reference(&objects[*record], "UIValue")]; + assert_eq!(image.class, "UIImageNibPlaceholder"); + assert_eq!(string(&objects[reference(image, "UIResourceName")]), name); + } + let traits = &objects[reference(&objects[refs[0]], "UITraitCollection")]; + assert_eq!( + value( + traits, + "UITraitCollectionBuiltinTrait-_UITraitNameHorizontalSizeClass" + ), + &Read::Int(2) + ); + assert_eq!( + value( + traits, + "UITraitCollectionBuiltinTrait-_UITraitNameVerticalSizeClass" + ), + &Read::Int(2) + ); +} + +#[test] +fn placeholder_masks_exclude_only_design_time_constraints() { + let body = r#" + + + + + "#; + let objects = compile_xib(body).unwrap(); + let constraints: Vec<_> = objects + .iter() + .filter(|o| o.class == "NSLayoutConstraint") + .collect(); + assert_eq!(constraints.len(), 1); + assert_eq!(value(constraints[0], "NSConstant"), &Read::Double(100.0)); + let storage = class(&objects, "_UIRelationshipTraitStorage"); + let candidates = &objects[reference(storage, "UIRelationshipCandidates")]; + assert_eq!(candidates.values.len(), 1); + assert!( + compile_xib(&body.replace("reference=\"placeholder\"", "reference=\"missing\"")) + .unwrap_err() + .contains("unknown variation reference missing") + ); +} + +#[test] +fn attributed_runs_use_foundation_varints_and_reuse_equal_dictionaries() { + let body = format!( + r#" + + + + + "#, + "a".repeat(128) + ); + let objects = compile_xib(&body).unwrap(); + let styled = class(&objects, "NSAttributedString"); + assert_eq!( + value(&objects[reference(styled, "NSAttributeInfo")], "NS.bytes"), + &Read::Data(vec![0x82, 1, 0, 1, 1, 1, 0]) + ); + let attrs = &objects[reference(styled, "NSAttributes")]; + assert_eq!( + attrs + .values + .iter() + .filter(|(key, _)| key == nib::ELEMENT) + .count(), + 2 + ); + for bad in [ + body.replace("size=\"14\"", "size=\"NaN\""), + body.replace("", ""), + body.replace("key=\"NSFont\"", "key=\"UnknownFont\""), + ] { + assert!(compile_xib(&bad).is_err()); + } +} diff --git a/sweetpad-cli/src/cli/ibtool/tests/normalize.rs b/sweetpad-cli/src/cli/ibtool/tests/normalize.rs index a56606d2..a9485a06 100644 --- a/sweetpad-cli/src/cli/ibtool/tests/normalize.rs +++ b/sweetpad-cli/src/cli/ibtool/tests/normalize.rs @@ -274,7 +274,7 @@ pub(super) fn prepare(objects: &mut Objects, names: &Names) { appkit_layout_cache(objects); layout_cache::prepare(objects); appkit_tables(objects); - intern_strings(objects); + intern_values(objects); } fn appkit_layout_cache(objects: &mut Objects) { @@ -758,18 +758,20 @@ fn top_level_proxies(objects: &mut Objects) { } } -fn intern_strings(objects: &mut Objects) { - // NSString value sharing is an encoder optimization, not object identity - // on which UIKit relies. Intern equal values in both archives. - let mut strings = BTreeMap::new(); +fn intern_values(objects: &mut Objects) { + // Xcode can share equal NSStrings and the NSShadow values in attributed + // runs, or archive a copy per run. Compare their class and all their fields. + let mut values = BTreeMap::new(); let mut aliases = BTreeMap::new(); for (index, object) in objects .iter() .enumerate() - .filter(|(_, o)| o.class == "NSString") + .filter(|(_, o)| matches!(o.class.as_str(), "NSString" | "NSShadow")) { - let key = format!("{:?}", object.values); - let first = *strings.entry(key).or_insert(index); + let mut fields: Vec<_> = object.values.iter().collect(); + fields.sort_by(|a, b| a.0.cmp(&b.0)); + let key = (object.class.clone(), format!("{fields:?}")); + let first = *values.entry(key).or_insert(index); aliases.insert(index, first); } for object in objects { diff --git a/sweetpad-cli/src/cli/ibtool/uikit.rs b/sweetpad-cli/src/cli/ibtool/uikit.rs index 1a1ea442..8ac2da88 100644 --- a/sweetpad-cli/src/cli/ibtool/uikit.rs +++ b/sweetpad-cli/src/cli/ibtool/uikit.rs @@ -13,9 +13,11 @@ use sweetpad_lib::xcscheme::Element; use super::nib::{Graph, Id, Value, doubles}; use super::{Options, custom_class}; mod accessibility; +mod attributed; mod calibrated; mod configuration; mod controls; +mod date_picker; mod effects; mod fonts; mod framework_views; @@ -26,6 +28,7 @@ mod lists; mod more_views; mod navigation; mod prototype; +pub(super) use prototype::prepare as prepare_cell; mod traits; /// Encodes one nib's objects, from the document they're in. @@ -80,7 +83,7 @@ fn no(element: &Element, attribute: &str) -> bool { element.attr(attribute) == Some("NO") } -fn number(element: &Element, attribute: &str) -> Result, String> { +pub(super) fn number(element: &Element, attribute: &str) -> Result, String> { element .attr(attribute) .map(|text| { @@ -147,6 +150,9 @@ fn view_class(element: &Element) -> Result<&'static str, String> { "pageControl" => Ok("UIPageControl"), "segmentedControl" => Ok("UISegmentedControl"), "textView" => Ok("UITextView"), + "datePicker" => Ok("UIDatePicker"), + "collectionViewLayout" => Ok("UICollectionViewLayout"), + "collectionViewFlowLayout" => Ok("UICollectionViewFlowLayout"), "searchBar" => Ok("UISearchBar"), "toolbar" => Ok("UIToolbar"), "tabBar" => Ok("UITabBar"), @@ -536,6 +542,10 @@ impl<'a> Encoder<'a> { for child in &element.children { match child.name.as_str() { "gestureRecognizers" if child.children.is_empty() => {} + "attributedString" + if matches!(element.name.as_str(), "textView" | "label") + && child.attr("key") == Some("attributedText") => {} + "locale" | "date" if element.name == "datePicker" => {} "rect" | "autoresizingMask" | "subviews" @@ -553,6 +563,7 @@ impl<'a> Encoder<'a> { | "inset" | "tableViewCellContentView" | "collectionViewFlowLayout" + | "collectionViewLayout" | "sections" | "prototypes" | "cells" @@ -650,10 +661,11 @@ impl<'a> Encoder<'a> { } } "imageView" => self.image_view(element, object)?, + "datePicker" => self.date_picker(element, object)?, "button" => self.button(element, object)?, "textField" => self.text_field(element, object)?, "switch" => self.switch(element, object, [x, y, width, height])?, - "scrollView" => self.scroll_view(element, object), + "scrollView" => self.scroll_view(element, object)?, "stackView" => self.stack_view(element, object, &children)?, "tableViewCell" => self.table_cell(element, object)?, "navigationBar" => self.navigation_bar(element, object), @@ -1177,27 +1189,41 @@ impl<'a> Encoder<'a> { } fn label(&mut self, element: &Element, object: Id) -> Result<(), String> { - let text = element - .attr("text") - .map(str::to_string) - .or_else(|| keyed(element, "string", "text").map(|string| string.text.clone())); - if let Some(text) = text { - let text = self.text(element, "text", &text); - self.graph.set(object, "UIText", text); - } - let description = keyed(element, "fontDescription", "fontDescription"); - let size = description - .map(|d| number(d, "pointSize")) - .transpose()? - .flatten() - .unwrap_or(17.0); - let font = self.font(description)?; - self.graph.set(object, "UIFont", font); - let color = match keyed(element, "color", "textColor") { - Some(color) => self.color(color)?, - None => self.system_color("labelColor", Fallback::White(0.0, 1.0)), + let line_break = match element.attr("lineBreakMode") { + None | Some("tailTruncation") => 4, + Some("wordWrap") => 0, + Some("characterWrap") => 1, + Some("clip") => 2, + Some("headTruncation") => 3, + Some("middleTruncation") => 5, + Some(other) => return Err(format!("the line break mode {other} is unknown")), }; - self.graph.set(object, "UITextColor", color); + let offset = keyed(element, "size", "shadowOffset"); + let shadow_offset = match offset { + Some(offset) => [ + number(offset, "width")?.unwrap_or(0.0), + number(offset, "height")?.unwrap_or(0.0), + ], + None => [0.0, -1.0], + }; + let shadow_color = keyed(element, "color", "shadowColor") + .map(|c| self.color(c)) + .transpose()?; + if let Some(color) = shadow_color { + self.graph.set(object, "UIShadowColor", color); + } + self.graph + .set(object, "UIShadowOffset", doubles(&shadow_offset)); + + let size = self.label_text( + element, + object, + &attributed::LabelStyle { + line_break, + shadow_color, + shadow_offset, + }, + )?; if let Some(color) = keyed(element, "color", "highlightedColor") { let color = self.color(color)?; self.graph.set(object, "UIHighlightedColor", color); @@ -1212,8 +1238,6 @@ impl<'a> Encoder<'a> { self.graph .set(object, "UIAdjustsFontForContentSizeCategory", true); } - self.graph - .set(object, "UIShadowOffset", doubles(&[0.0, -1.0])); let baseline = match element.attr("baselineAdjustment") { Some("alignBaselines") => 0_i64, None | Some("alignCenters") => 1, @@ -1239,27 +1263,9 @@ impl<'a> Encoder<'a> { #[allow(clippy::cast_possible_truncation)] self.graph.set(object, "UIMinimumFontSize", minimum as f32); } - let line_break = match element.attr("lineBreakMode") { - None | Some("tailTruncation") => 4, - Some("wordWrap") => 0, - Some("characterWrap") => 1, - Some("clip") => 2, - Some("headTruncation") => 3, - Some("middleTruncation") => 5, - Some(other) => return Err(format!("the line break mode {other} is unknown")), - }; if line_break != 4 { self.graph.set(object, "UILineBreakMode", line_break); } - let alignment = match element.attr("textAlignment") { - None | Some("left") => 0, - Some("natural") => 4, - Some("center") => 1, - Some("right") => 2, - Some("justified") => 3, - Some(other) => return Err(format!("the text alignment {other} is unknown")), - }; - self.graph.set(object, "UITextAlignment", alignment); let scale = match (number(element, "minimumScaleFactor")?, minimum_size) { (Some(factor), _) => Some(factor), (None, Some(minimum)) => Some(minimum / size), @@ -1269,14 +1275,83 @@ impl<'a> Encoder<'a> { #[allow(clippy::cast_possible_truncation)] self.graph.set(object, "UIMinimumScaleFactor", scale as f32); } + Ok(()) + } + + fn label_text( + &mut self, + element: &Element, + object: Id, + style: &attributed::LabelStyle, + ) -> Result { + let uses_attributed = yes(element, "usesAttributedText"); + let attributed = keyed(element, "attributedString", "attributedText"); + let styled = attributed + .filter(|_| uses_attributed) + .map(|string| self.attributed_text(string, Some(style))) + .transpose()?; + if let Some(styled) = &styled { + // Even in Base.lproj, the label's plain mirror of its rich text is an NSString. + let text = self.graph.string(&styled.text); + self.graph.set(object, "UIText", text); + self.graph.set(object, "UIAttributedText", styled.archive); + } else if let Some(text) = element + .attr("text") + .or_else(|| keyed(element, "string", "text").map(|s| s.text.as_str())) + { + let text = self.text(element, "text", text); + self.graph.set(object, "UIText", text); + } else if uses_attributed || attributed.is_some() { + self.graph.set(object, "UIText", Value::Nil); + } + let description = keyed(element, "fontDescription", "fontDescription"); + let (font, size) = match styled.as_ref().and_then(|s| s.font) { + Some((font, size)) => (Value::Object(font), size), + None if styled.is_some() => { + (Value::Object(self.attributed_label_default_font()?), 17.0) + } + None if uses_attributed => (Value::Nil, 17.0), + None => ( + Value::Object(self.font(description)?), + description + .map(|d| number(d, "pointSize")) + .transpose()? + .flatten() + .unwrap_or(17.0), + ), + }; + self.graph.set(object, "UIFont", font); + let color = match ( + styled.as_ref().and_then(|s| s.color), + keyed(element, "color", "textColor"), + ) { + (Some(color), _) => color, + (None, Some(color)) => self.color(color)?, + (None, None) => self.system_color("labelColor", Fallback::White(0.0, 1.0)), + }; + self.graph.set(object, "UITextColor", color); + let alignment = match element.attr("textAlignment") { + None | Some("left") => 0, + Some("natural") => 4, + Some("center") => 1, + Some("right") => 2, + Some("justified") => 3, + Some(other) => return Err(format!("the text alignment {other} is unknown")), + }; + self.graph.set( + object, + "UITextAlignment", + styled.as_ref().map_or(alignment, |s| s.alignment), + ); self.graph.set( object, "UIDisableUpdateTextColorOnTraitCollectionChange", - !element - .children_named("nil") - .any(|e| e.attr("key") == Some("textColor")), + !uses_attributed + && !element + .children_named("nil") + .any(|e| e.attr("key") == Some("textColor")), ); - Ok(()) + Ok(size) } pub fn text(&mut self, element: &Element, key: &str, text: &str) -> Id { diff --git a/sweetpad-cli/src/cli/ibtool/uikit/attributed.rs b/sweetpad-cli/src/cli/ibtool/uikit/attributed.rs new file mode 100644 index 00000000..a23f5e2b --- /dev/null +++ b/sweetpad-cli/src/cli/ibtool/uikit/attributed.rs @@ -0,0 +1,307 @@ +//! Foundation attributed strings retain each run and its UTF-16 length. +//! NSAttributes / NSAttributeInfo follow Foundation's keyed coding format +//! (swift-corelibs-foundation, NSAttributedString.swift). +use super::controls::enumeration; +use super::{Element, Encoder, Id, Value, number}; + +pub(super) struct LabelStyle { + pub line_break: i64, + pub shadow_color: Option, + pub shadow_offset: [f64; 2], +} + +struct Run { + length: usize, + attributes: Vec<(Id, Id)>, +} + +pub(super) struct AttributedText { + pub archive: Id, + pub text: String, + pub font: Option<(Id, f64)>, + pub color: Option, + pub alignment: i64, +} + +fn check_attributes(element: &Element, allowed: &[&str]) -> Result<(), String> { + for (key, _) in &element.attributes { + if !allowed.contains(&key.as_str()) { + return Err(format!("unsupported <{}> attribute {key}", element.name)); + } + } + Ok(()) +} + +fn run_integer(mut value: usize, bytes: &mut Vec) { + while value >= 128 { + bytes.push(u8::try_from(value & 127).unwrap() | 128); + value >>= 7; + } + bytes.push(u8::try_from(value).unwrap()); +} + +impl Encoder<'_> { + pub(super) fn attributed_text( + &mut self, + element: &Element, + label: Option<&LabelStyle>, + ) -> Result { + check_attributes(element, &["key"])?; + let mut text = String::new(); + let mut runs: Vec = Vec::new(); + let mut font = None; + let mut color = None; + let mut alignment = 4; + for fragment in &element.children { + if fragment.name != "fragment" { + return Err(format!( + "unsupported attributed string child <{}>", + fragment.name + )); + } + check_attributes(fragment, &["content"])?; + let content = fragment.attr("content").unwrap_or(&fragment.text); + let mut entries = Vec::new(); + for attributes in &fragment.children { + if attributes.name != "attributes" { + return Err(format!("unsupported fragment child <{}>", attributes.name)); + } + check_attributes(attributes, &[])?; + for attribute in &attributes.children { + let key = attribute.attr("key").ok_or("a text attribute has no key")?; + let value = match (attribute.name.as_str(), key) { + ( + "color", + "NSColor" + | "NSBackgroundColor" + | "NSStrokeColor" + | "NSUnderlineColor" + | "NSStrikethroughColor", + ) => { + let value = self.color(attribute)?; + if key == "NSColor" && text.is_empty() && !content.is_empty() { + color = Some(value); + } + value + } + ("font", "NSFont") => { + check_attributes(attribute, &["key", "size", "name"])?; + let size = number(attribute, "size")? + .ok_or("an attributed font has no size")?; + if !size.is_finite() || size <= 0.0 { + return Err( + "an attributed font must have a positive finite size".into() + ); + } + let value = self.font_with_default(Some(attribute), size)?; + if !content.is_empty() { + font.get_or_insert((value, size)); + } + value + } + ("paragraphStyle", "NSParagraphStyle") => { + let (value, paragraph_alignment) = + self.attributed_paragraph(attribute, label)?; + if text.is_empty() && !content.is_empty() { + alignment = paragraph_alignment; + } + value + } + _ => { + return Err(format!( + "unsupported text attribute <{}> {key}", + attribute.name + )); + } + }; + let key = self.graph.string(key); + if entries.iter().any(|(existing, _)| *existing == key) { + return Err("duplicate attributed string attribute".into()); + } + entries.push((key, value)); + } + } + if !content.is_empty() { + let length = content.encode_utf16().count(); + text.push_str(content); + entries.sort_by_key(|(key, _)| *key); + if let Some(previous) = runs.last_mut() + && previous.attributes == entries + { + previous.length += length; + } else { + runs.push(Run { + length, + attributes: entries, + }); + } + } + } + + Ok(AttributedText { + archive: self.archive_runs(&text, runs, label), + text, + font, + color, + alignment, + }) + } + + fn archive_runs(&mut self, text: &str, mut runs: Vec, label: Option<&LabelStyle>) -> Id { + // UILabel applies its shadow across all distinct runs, even when the + // default offset is the only shadow property. UITextView does not. + if let Some(style) = label.filter(|s| { + runs.len() > 1 || s.shadow_color.is_some() || !matches!(s.shadow_offset, [0.0, -1.0]) + }) { + let [x, y] = style.shadow_offset; + let shadow = self.graph.object("NSShadow"); + self.graph.set( + shadow, + "NSShadowColor", + style.shadow_color.map_or(Value::Nil, Value::Object), + ); + if x != 0.0 { + self.graph.set(shadow, "NSShadowHoriz", x); + } + if y != 0.0 { + self.graph.set(shadow, "NSShadowVert", -y); + } + let key = self.graph.string("NSShadow"); + for run in &mut runs { + run.attributes.push((key, shadow)); + } + } + let object = self.graph.object(if label.is_some() { + "NSMutableAttributedString" + } else { + "NSAttributedString" + }); + let string = if label.is_some() { + let string = self.graph.object("NSMutableString"); + self.graph + .set(string, "NS.bytes", Value::Data(text.as_bytes().to_vec())); + string + } else { + self.graph.string(text) + }; + self.graph.set(object, "NSString", string); + let runs = runs + .into_iter() + .map(|run| { + ( + run.length, + self.graph.dictionary("NSDictionary", &run.attributes), + ) + }) + .collect::>(); + if runs.len() == 1 { + self.graph.set(object, "NSAttributes", runs[0].1); + } else if !runs.is_empty() { + let mut dictionaries = Vec::new(); + let mut bytes = Vec::new(); + for (length, attributes) in runs { + let index = dictionaries + .iter() + .position(|id| *id == attributes) + .unwrap_or_else(|| { + dictionaries.push(attributes); + dictionaries.len() - 1 + }); + run_integer(length, &mut bytes); + run_integer(index, &mut bytes); + } + let attributes = self.graph.array( + if label.is_some() { + "NSMutableArray" + } else { + "NSArray" + }, + &dictionaries, + ); + let info = self.graph.object(if label.is_some() { + "NSMutableData" + } else { + "NSData" + }); + self.graph.set(info, "NS.bytes", Value::Data(bytes)); + self.graph.set(object, "NSAttributes", attributes); + self.graph.set(object, "NSAttributeInfo", info); + } + object + } + + fn attributed_paragraph( + &mut self, + element: &Element, + label: Option<&LabelStyle>, + ) -> Result<(Id, i64), String> { + check_attributes( + element, + &["key", "alignment", "lineBreakMode", "baseWritingDirection"], + )?; + if !element.children.is_empty() { + return Err("unsupported paragraph style children".into()); + } + let alignment = enumeration( + element, + "alignment", + &[ + ("left", 0), + ("center", 1), + ("right", 2), + ("justified", 3), + ("natural", 4), + ], + 4, + )?; + let line_break = enumeration( + element, + "lineBreakMode", + &[ + ("wordWrapping", 0), + ("charWrapping", 1), + ("clipping", 2), + ("truncatingHead", 3), + ("truncatingTail", 4), + ("truncatingMiddle", 5), + ], + 0, + )?; + let direction = enumeration( + element, + "baseWritingDirection", + &[("natural", -1), ("leftToRight", 0), ("rightToLeft", 1)], + -1, + )?; + let mut values = vec![("NSTabStops", Value::Nil)]; + if let Some(label) = label { + // NSParagraphStyle archives alignment in AppKit order. UIKit + // applies the label's line-break mode to its attributed runs. + let archived_alignment = match alignment { + 1 => 2, + 2 => 1, + value => value, + }; + if archived_alignment != 0 { + values.push(("NSAlignment", Value::Int(archived_alignment))); + } + if label.line_break != 0 { + values.push(("NSLineBreakMode", Value::Int(label.line_break))); + } + values.push(("NSLineBreakStrategy", Value::Int(65535))); + if direction != -1 { + values.push(("NSWritingDirection", Value::Float(1.0))); + } + } else { + values.extend([ + ("NSAlignment", Value::Int(alignment)), + ("NSLineBreakMode", Value::Int(line_break)), + ("NSWritingDirection", Value::Int(direction)), + ]); + } + Ok(( + self.graph.shared("NSMutableParagraphStyle", values), + alignment, + )) + } +} diff --git a/sweetpad-cli/src/cli/ibtool/uikit/controls.rs b/sweetpad-cli/src/cli/ibtool/uikit/controls.rs index dc3c688a..7362e934 100644 --- a/sweetpad-cli/src/cli/ibtool/uikit/controls.rs +++ b/sweetpad-cli/src/cli/ibtool/uikit/controls.rs @@ -113,13 +113,7 @@ impl Encoder<'_> { "UIIndentationWidth", single(number(element, "indentationWidth")?.unwrap_or(10.0)), ); - if let Some(inset) = keyed(element, "inset", "separatorInset") { - let mut values = Vec::new(); - for key in ["minY", "minX", "maxY", "maxX"] { - values.push(number(inset, key)?.unwrap_or(0.0)); - } - self.graph.set(object, "UISeparatorInset", doubles(&values)); - } + self.archive_inset(element, "separatorInset", object, "UISeparatorInset")?; self.table_background(element, object, selection)?; self.graph .set(object, "UIContentConfigurationView", Value::Nil); @@ -253,12 +247,7 @@ impl Encoder<'_> { ("titleEdgeInsets", "UITitleEdgeInsets"), ("contentEdgeInsets", "UIContentEdgeInsets"), ] { - if let Some(inset) = keyed(element, "inset", key) { - let values = ["minY", "minX", "maxY", "maxX"] - .map(|key| number(inset, key).map(|v| v.unwrap_or(0.0))); - let values = values.into_iter().collect::, _>>()?; - self.graph.set(object, archive, doubles(&values)); - } + self.archive_inset(element, key, object, archive)?; } if let Some(configuration) = element.child("buttonConfiguration") { let configuration = self.button_configuration(configuration, element)?; @@ -317,7 +306,8 @@ impl Encoder<'_> { } let color = if let Some(color) = keyed(state, "color", key) { self.color(color)? - } else if self.document.child("dependencies").is_none() { + } else if value == 0 && self.document.child("dependencies").is_none() { + // Other states inherit the normal state's color in UIKit. self.system_color("blackColor", Fallback::White(0.0, 1.0)) } else { continue; @@ -328,15 +318,21 @@ impl Encoder<'_> { ("image", "UIImage"), ("backgroundImage", "UIBackgroundImage"), ] { - if let Some(name) = state.attr(key) { - let image = self.image( - name, - state.attr("catalog"), - state.child("preferredSymbolConfiguration"), - )?; + let reference = keyed(state, "imageReference", key); + let source = reference.unwrap_or(state); + if let Some(name) = reference + .and_then(|r| r.attr("image")) + .or_else(|| state.attr(key)) + { + let image = self.image(name, source.attr("catalog"), reference)?; self.graph.set(content, archive, image); } } + if let Some(preferred) = state.child("preferredSymbolConfiguration") { + let configuration = self.symbol_configuration(preferred)?; + self.graph + .set(content, "UIImageSymbolConfiguration", configuration); + } states.push((key, content)); } if element.child("buttonConfiguration").is_none() { @@ -565,7 +561,30 @@ impl Encoder<'_> { Ok(()) } - pub(super) fn scroll_view(&mut self, element: &Element, object: Id) { + pub(super) fn archive_inset( + &mut self, + element: &Element, + key: &str, + object: Id, + archive: &str, + ) -> Result<(), String> { + if let Some(inset) = keyed(element, "inset", key) { + let mut coordinates = [0.0; 4]; + for (coordinate, name) in coordinates.iter_mut().zip(["minY", "minX", "maxY", "maxX"]) { + *coordinate = number(inset, name)?.unwrap_or(0.0); + } + self.graph.set(object, archive, doubles(&coordinates)); + } + Ok(()) + } + + pub(super) fn scroll_view(&mut self, element: &Element, object: Id) -> Result<(), String> { + self.archive_inset( + element, + "scrollIndicatorInsets", + object, + "UIScrollIndicatorInsets", + )?; self.graph.set( object, "UIScrollViewIndicatorInsetAdjustmentBehavior", @@ -616,6 +635,7 @@ impl Encoder<'_> { ); } } + Ok(()) } pub(super) fn stack_view( @@ -677,9 +697,7 @@ impl Encoder<'_> { self.graph.set( object, "UIStackViewLayoutMarginsRelative", - (yes(element, "layoutMarginsRelativeArrangement") - || yes(element, "layoutMarginsRelative")) - && keyed(element, "edgeInsets", "layoutMargins").is_some() + keyed(element, "edgeInsets", "layoutMargins").is_some() || keyed(element, "directionalEdgeInsets", "directionalLayoutMargins").is_some(), ); Ok(()) diff --git a/sweetpad-cli/src/cli/ibtool/uikit/date_picker.rs b/sweetpad-cli/src/cli/ibtool/uikit/date_picker.rs new file mode 100644 index 00000000..801c473d --- /dev/null +++ b/sweetpad-cli/src/cli/ibtool/uikit/date_picker.rs @@ -0,0 +1,88 @@ +//! Date pickers use public setters through the same nib key/value pairs as +//! user-defined runtime attributes. This avoids depending on private picker +//! implementation views, which differ between wheel and calendar styles. +use super::controls::enumeration; +use super::{Element, Encoder, Id, Value, integer, number}; + +impl Encoder<'_> { + pub(super) fn date_picker(&mut self, element: &Element, object: Id) -> Result<(), String> { + self.control(element, object)?; + let mode = enumeration( + element, + "datePickerMode", + &[ + ("time", 0), + ("date", 1), + ("dateAndTime", 2), + ("countDownTimer", 3), + ], + 2, + )?; + let interval = integer(element, "minuteInterval")?.unwrap_or(1); + if !(1..=30).contains(&interval) || 60 % interval != 0 { + return Err("date picker minuteInterval must divide 60 and be between 1 and 30".into()); + } + for (path, value) in [("datePickerMode", mode), ("minuteInterval", interval)] { + let value = self + .graph + .shared("NSNumber", vec![("NS.intval", Value::Int(value))]); + self.runtime_property(object, path, value); + } + if element.attr("style").is_some() { + let style = enumeration( + element, + "style", + &[ + ("automatic", 0), + ("wheels", 1), + ("compact", 2), + ("inline", 3), + ], + 0, + )?; + let value = self + .graph + .shared("NSNumber", vec![("NS.intval", Value::Int(style))]); + self.runtime_property(object, "preferredDatePickerStyle", value); + } + if let Some(duration) = number(element, "countDownDuration")? { + if !duration.is_finite() || !(0.0..86400.0).contains(&duration) { + return Err("invalid date picker countDownDuration".into()); + } + let value = self.graph.number(duration); + self.runtime_property(object, "countDownDuration", value); + } + for child in &element.children { + match child.name.as_str() { + "locale" => { + if child.attr("key") != Some("locale") { + return Err("unsupported date picker locale key".into()); + } + let name = child + .attr("localeIdentifier") + .ok_or("a locale has no identifier")?; + let name = self.graph.string(name); + let locale = self + .graph + .shared("NSLocale", vec![("NS.identifier", Value::Object(name))]); + self.runtime_property(object, "locale", locale); + } + "date" => { + let key = child.attr("key").ok_or("a date has no key")?; + if !matches!(key, "date" | "minimumDate" | "maximumDate") { + return Err(format!("unsupported date picker date key {key}")); + } + let time = number(child, "timeIntervalSinceReferenceDate")? + .filter(|n| n.is_finite()) + .ok_or("a date has no finite reference interval")?; + let date = self + .graph + .shared("NSDate", vec![("NS.time", Value::Double(time))]); + self.runtime_property(object, key, date); + } + _ => {} + } + } + Ok(()) + } +} diff --git a/sweetpad-cli/src/cli/ibtool/uikit/effects.rs b/sweetpad-cli/src/cli/ibtool/uikit/effects.rs index 73e8227b..d049d6f3 100644 --- a/sweetpad-cli/src/cli/ibtool/uikit/effects.rs +++ b/sweetpad-cli/src/cli/ibtool/uikit/effects.rs @@ -183,20 +183,23 @@ impl Encoder<'_> { } other => return Err(format!("unsupported runtime attribute type {other:?}")), }; - let key = self.graph.string( - attribute - .attr("keyPath") - .ok_or("a runtime attribute has no key path")?, - ); - let pair = self.graph.object("UINibKeyValuePair"); - self.graph.set(pair, "UIObject", object); - self.graph.set(pair, "UIValue", value); - self.graph.set(pair, "UIKeyPath", key); - self.key_value_pairs.push(pair); + let key = attribute + .attr("keyPath") + .ok_or("a runtime attribute has no key path")?; + self.runtime_property(object, key, value); } Ok(()) } + pub(super) fn runtime_property(&mut self, object: Id, path: &str, value: Id) { + let key = self.graph.string(path); + let pair = self.graph.object("UINibKeyValuePair"); + self.graph.set(pair, "UIObject", object); + self.graph.set(pair, "UIValue", value); + self.graph.set(pair, "UIKeyPath", key); + self.key_value_pairs.push(pair); + } + pub fn document_tint(&mut self, object: Id, element: &Element) -> Result<(), String> { if keyed(element, "color", "tintColor").is_none() && let Some(tint) = keyed(self.document, "color", "tintColor") diff --git a/sweetpad-cli/src/cli/ibtool/uikit/fonts.rs b/sweetpad-cli/src/cli/ibtool/uikit/fonts.rs index 806c8a7d..9b0a21d1 100644 --- a/sweetpad-cli/src/cli/ibtool/uikit/fonts.rs +++ b/sweetpad-cli/src/cli/ibtool/uikit/fonts.rs @@ -12,6 +12,21 @@ impl Encoder<'_> { &mut self, description: Option<&Element>, default_size: f64, + ) -> Result { + self.archive_font(description, default_size, None) + } + + /// UIKit supplies this descriptor when an attributed label has no font + /// in any run. Interface Builder's explicit system font uses other options. + pub(super) fn attributed_label_default_font(&mut self) -> Result { + self.archive_font(None, 17.0, Some(0)) + } + + fn archive_font( + &mut self, + description: Option<&Element>, + default_size: f64, + descriptor_options: Option, ) -> Result { let kind = description.and_then(|d| d.attr("type")).unwrap_or("system"); let weight = description.and_then(|d| d.attr("weight")); @@ -79,9 +94,9 @@ impl Encoder<'_> { size, ) }; - let descriptor = style - .is_none() - .then(|| self.font_descriptor(description, usage, override_usage, size)); + let descriptor = style.is_none().then(|| { + self.font_descriptor(description, usage, override_usage, size, descriptor_options) + }); let name = self.graph.string(name); let mut values = vec![("UIFontName", Value::Object(name))]; if let Some(descriptor) = descriptor { @@ -110,6 +125,7 @@ impl Encoder<'_> { usage: &str, override_usage: Option<&str>, size: f64, + options: Option, ) -> Id { let custom = description.and_then(|d| d.attr("name")); let kind = description.and_then(|d| d.attr("type")).unwrap_or("system"); @@ -156,11 +172,11 @@ impl Encoder<'_> { ("UIFontDescriptorAttributes", Value::Object(attributes)), ( "UIFontDescriptorOptions", - Value::Int(if custom.is_some() { + Value::Int(options.unwrap_or(if custom.is_some() { 2_147_483_648 } else { 2_147_517_444 - }), + })), ), ], ) diff --git a/sweetpad-cli/src/cli/ibtool/uikit/framework_views.rs b/sweetpad-cli/src/cli/ibtool/uikit/framework_views.rs index 81fed63a..cea57f08 100644 --- a/sweetpad-cli/src/cli/ibtool/uikit/framework_views.rs +++ b/sweetpad-cli/src/cli/ibtool/uikit/framework_views.rs @@ -1,5 +1,5 @@ use super::controls::enumeration; -use super::{Element, Encoder, Id, Value, no, number}; +use super::{Element, Encoder, Id, Value, keyed, no, number, yes}; impl Encoder<'_> { pub(super) fn framework_view(&mut self, element: &Element, object: Id) -> Result<(), String> { @@ -69,13 +69,18 @@ impl Encoder<'_> { let store = self.graph.object("WKWebsiteDataStore"); self.graph.set(store, "isDefaultDataStore", true); self.graph.set(configuration, "websiteDataStore", store); + let media_key = "mediaTypesRequiringUserActionForPlayback"; + self.graph.set( + configuration, + media_key, + requires_playback_action(source, media_key), + ); for (attribute, default) in [ ("suppressesIncrementalRendering", false), ("allowsAirPlayForMediaPlayback", true), ("drawsBackground", true), ("allowsInlineMediaPlayback", false), ("allowsInlineMediaPlaybackAfterFullscreen", false), - ("mediaTypesRequiringUserActionForPlayback", true), ("allowsPictureInPictureMediaPlayback", true), ("ignoresViewportScaleLimits", false), ("textInteractionGesturesEnabled", true), @@ -183,3 +188,15 @@ impl Encoder<'_> { Ok(()) } } + +fn requires_playback_action(source: &Element, key: &str) -> bool { + // WKWebViewConfiguration's nib field is a boolean, including for video-only playback. + keyed(source, "audiovisualMediaTypes", key).map_or_else( + || source.attr(key).is_none_or(|value| value == "YES"), + |options| { + ["audio", "video", "all"] + .iter() + .any(|name| yes(options, name)) + }, + ) +} diff --git a/sweetpad-cli/src/cli/ibtool/uikit/images.rs b/sweetpad-cli/src/cli/ibtool/uikit/images.rs index 588deed4..d41b358f 100644 --- a/sweetpad-cli/src/cli/ibtool/uikit/images.rs +++ b/sweetpad-cli/src/cli/ibtool/uikit/images.rs @@ -76,7 +76,7 @@ impl Encoder<'_> { self.graph.set(object, "UISymbolWeight", value); } if let Some(size) = number(element, "pointSize")? { - self.graph.set(object, "UISymbolPointSize", size); + self.graph.set(object, "UIPointSize", single(size)); } Ok(self.graph.intern(object)) } diff --git a/sweetpad-cli/src/cli/ibtool/uikit/lists.rs b/sweetpad-cli/src/cli/ibtool/uikit/lists.rs index 8322c69e..e478331f 100644 --- a/sweetpad-cli/src/cli/ibtool/uikit/lists.rs +++ b/sweetpad-cli/src/cli/ibtool/uikit/lists.rs @@ -4,7 +4,8 @@ use super::{Element, Encoder, Id, Options, Value, doubles, id_of, keyed, no, num impl Encoder<'_> { pub(super) fn table_view(&mut self, element: &Element, object: Id) -> Result<(), String> { - self.scroll_view(element, object); + self.scroll_view(element, object)?; + self.table_separators(element, object)?; let style = match element.attr("style") { None | Some("plain") => 0_i64, Some("grouped") => 1, @@ -103,16 +104,74 @@ impl Encoder<'_> { Ok(()) } + fn table_separators(&mut self, element: &Element, object: Id) -> Result<(), String> { + self.archive_inset(element, "separatorInset", object, "UISeparatorInset")?; + for (key, archive) in [ + ("separatorColor", "UISeparatorColor"), + ( + "sectionIndexBackgroundColor", + "UISectionIndexBackgroundColor", + ), + ( + "sectionIndexTrackingBackgroundColor", + "UISectionIndexTrackingBackgroundColor", + ), + ] { + if let Some(color) = keyed(element, "color", key) { + let value = self.color(color)?; + self.graph.set(object, archive, value); + } + } + Ok(()) + } + pub(super) fn collection_view(&mut self, element: &Element, object: Id) -> Result<(), String> { - self.scroll_view(element, object); + self.scroll_view(element, object)?; self.graph.set(object, "UIDelegate", Value::Nil); let layout = keyed(element, "collectionViewFlowLayout", "collectionViewLayout") - .ok_or("a collection view has no flow layout")?; - let flow = self.graph.object("UICollectionViewFlowLayout"); - self.bind(id_of(layout)?, flow); - self.objects.push(flow); - self.graph.set(object, "UICollectionLayout", flow); - self.flow_layout(layout, flow)?; + .or_else(|| keyed(element, "collectionViewLayout", "collectionViewLayout")) + .ok_or("a collection view has no layout")?; + let class = super::view_class(layout)?; + let archived = self.graph.object(if layout.attr("customClass").is_some() { + "UIClassSwapper" + } else { + class + }); + self.bind(id_of(layout)?, archived); + self.objects.push(archived); + self.graph.set(object, "UICollectionLayout", archived); + if layout.name == "collectionViewFlowLayout" { + self.flow_layout(layout, archived)?; + } else { + for (attribute, _) in &layout.attributes { + if !matches!( + attribute.as_str(), + "key" + | "id" + | "customClass" + | "customModule" + | "customModuleProvider" + | "userLabel" + ) { + return Err(format!( + "unsupported collection layout attribute {attribute}" + )); + } + } + for child in &layout.children { + if !matches!( + child.name.as_str(), + "connections" | "userDefinedRuntimeAttributes" + ) { + return Err(format!( + "unsupported collection layout child <{}>", + child.name + )); + } + } + } + self.view_custom_class(layout, archived)?; + self.runtime_attributes(layout, archived)?; self.graph .set(object, "UIAllowsUserInitiatedMultipleSelection", true); self.graph.set( diff --git a/sweetpad-cli/src/cli/ibtool/uikit/more_views.rs b/sweetpad-cli/src/cli/ibtool/uikit/more_views.rs index 58e3dbb9..7f859ca7 100644 --- a/sweetpad-cli/src/cli/ibtool/uikit/more_views.rs +++ b/sweetpad-cli/src/cli/ibtool/uikit/more_views.rs @@ -124,6 +124,10 @@ impl Encoder<'_> { } fn search_bar(&mut self, element: &Element, object: Id) -> Result<(), String> { + if let Some(tint) = keyed(element, "color", "barTintColor") { + let color = self.color(tint)?; + self.graph.set(object, "UIBarTintColor", color); + } self.graph.set( object, "UISearchBarTranslucence", @@ -223,7 +227,7 @@ impl Encoder<'_> { } fn text_view(&mut self, element: &Element, object: Id) -> Result<(), String> { - self.scroll_view(element, object); + self.scroll_view(element, object)?; if let Some(detectors) = element.child("dataDetectorType") { let flags = [ ("phoneNumber", 1_i64), @@ -247,24 +251,7 @@ impl Encoder<'_> { }; self.graph.set(object, "UIDataDetectorTypes", value); } - let text = element.attr("text").unwrap_or(""); - let string = self.text(element, "text", text); - self.graph.set(object, "UIText", string); - let font = self.font(element.child("fontDescription"))?; - let paragraph = self.graph.object("NSMutableParagraphStyle"); - self.graph.set(paragraph, "NSTabStops", Value::Nil); - let font_key = self.graph.string("NSFont"); - let paragraph_key = self.graph.string("NSParagraphStyle"); - let attributes = self.graph.dictionary( - "NSDictionary", - &[(font_key, font), (paragraph_key, paragraph)], - ); - let styled = self.graph.object("NSAttributedString"); - let plain = self.graph.string(text); - self.graph.set(styled, "NSString", plain); - self.graph.set(styled, "NSAttributes", attributes); - self.graph.set(object, "UIAttributedText", styled); - self.graph.set(object, "UIFont", font); + self.text_view_content(element, object)?; self.graph.set( object, "UITextAlignment", @@ -315,4 +302,42 @@ impl Encoder<'_> { } Ok(()) } + + fn text_view_content(&mut self, element: &Element, object: Id) -> Result<(), String> { + if let Some(attributed) = keyed(element, "attributedString", "attributedText") { + let styled = self.attributed_text(attributed, None)?; + self.graph.set(object, "UIAttributedText", styled.archive); + let text = self.graph.string(&styled.text); + self.graph.set(object, "UIText", text); + if let Some((font, _)) = styled.font { + self.graph.set(object, "UIFont", font); + } + if let Some(color) = styled.color { + self.graph.set(object, "UITextColor", color); + } + } else { + let text = element + .attr("text") + .or_else(|| keyed(element, "string", "text").map(|s| s.text.as_str())) + .unwrap_or(""); + let string = self.text(element, "text", text); + self.graph.set(object, "UIText", string); + let font = self.font(element.child("fontDescription"))?; + let paragraph = self.graph.object("NSMutableParagraphStyle"); + self.graph.set(paragraph, "NSTabStops", Value::Nil); + let font_key = self.graph.string("NSFont"); + let paragraph_key = self.graph.string("NSParagraphStyle"); + let attributes = self.graph.dictionary( + "NSDictionary", + &[(font_key, font), (paragraph_key, paragraph)], + ); + let styled = self.graph.object("NSAttributedString"); + let plain = self.graph.string(text); + self.graph.set(styled, "NSString", plain); + self.graph.set(styled, "NSAttributes", attributes); + self.graph.set(object, "UIAttributedText", styled); + self.graph.set(object, "UIFont", font); + } + Ok(()) + } } diff --git a/sweetpad-cli/src/cli/ibtool/uikit/prototype.rs b/sweetpad-cli/src/cli/ibtool/uikit/prototype.rs index 13c2c9a7..e8463908 100644 --- a/sweetpad-cli/src/cli/ibtool/uikit/prototype.rs +++ b/sweetpad-cli/src/cli/ibtool/uikit/prototype.rs @@ -12,7 +12,7 @@ fn element(name: &str, attributes: &[(&str, &str)]) -> Element { text: String::new(), } } -pub(super) fn prepare(source: &Element) -> Element { +pub(in crate::cli::ibtool) fn prepare(source: &Element) -> Element { let mut cell = source.clone(); if cell.name != "collectionViewCell" { return cell; @@ -29,7 +29,12 @@ pub(super) fn prepare(source: &Element) -> Element { .attr("id") .map_or_else(|| format!("{cell_id}-contentView"), str::to_string); let legacy = cell.children[content_index].attr("id").is_none(); - if legacy { + let safe_area = cell + .children + .iter() + .position(|e| e.name == "viewLayoutGuide" && e.attr("key") == Some("safeArea")); + if legacy || safe_area.is_some() { + let guide = safe_area.map(|index| cell.children.remove(index)); let constraints = cell .children .iter() @@ -40,10 +45,16 @@ pub(super) fn prepare(source: &Element) -> Element { .iter_mut() .find(|e| e.attr("key") == Some("contentView")) .unwrap(); - content.attributes = vec![ - ("key".to_string(), "contentView".to_string()), - ("id".to_string(), content_id.clone()), - ]; + if legacy { + // UIKit creates this anonymous content view with its own drawing and clipping defaults. + content.attributes = vec![ + ("key".to_string(), "contentView".to_string()), + ("id".to_string(), content_id.clone()), + ]; + } + if let Some(guide) = guide { + content.children.push(guide); + } if let Some(mut constraints) = constraints { for constraint in &mut constraints.children { for (key, value) in &mut constraint.attributes { diff --git a/sweetpad-cli/src/cli/ibtool/uikit/traits.rs b/sweetpad-cli/src/cli/ibtool/uikit/traits.rs index 12b8b523..37ccdda7 100644 --- a/sweetpad-cli/src/cli/ibtool/uikit/traits.rs +++ b/sweetpad-cli/src/cli/ibtool/uikit/traits.rs @@ -186,6 +186,15 @@ impl Encoder<'_> { for (attribute, value) in &variation.attributes { match attribute.as_str() { "key" | "text" => {} + "image" if element.name == "imageView" => { + let base = self.graph.value(object, "UIImage").unwrap_or(Value::Nil); + let image = self.image(value, None, None)?; + attributes + .entry("image") + .or_insert_with(|| (base, Vec::new())) + .1 + .push((condition, Value::Object(image))); + } "hidden" => { let base = self.boxed_boolean(element.attr("hidden") == Some("YES")); let value = self.boxed_boolean(value == "YES"); @@ -252,11 +261,12 @@ impl Encoder<'_> { self.trait_storages .push((self.current_trait_root.unwrap_or(object), object, storage)); } - self.relationship_variations(object, &variations) + self.relationship_variations(element, object, &variations) } fn relationship_variations( &mut self, + element: &Element, object: Id, variations: &[&Element], ) -> Result<(), String> { @@ -308,17 +318,23 @@ impl Encoder<'_> { let reference = change .attr("reference") .ok_or("a variation mask entry has no reference")?; + let changes = match change.name.as_str() { + "include" => &mut added, + "exclude" => &mut removed, + other => return Err(format!("unsupported variation mask change {other}")), + }; + // Placeholder constraints exist only on IB's design canvas. They + // have no runtime object, including in trait relationship masks. + if key == "constraints" && placeholder_constraint(element, reference) { + continue; + } let target = self .lookup(reference) .ok_or_else(|| format!("unknown variation reference {reference}"))?; if !candidates.contains(&target) { candidates.push(target); } - match change.name.as_str() { - "include" => added.push(target), - "exclude" => removed.push(target), - other => return Err(format!("unsupported variation mask change {other}")), - } + changes.push(target); } if condition == "default" { let defaults: Vec<_> = original @@ -389,3 +405,14 @@ impl Encoder<'_> { self.graph.replace(root, "UINibTraitStorageListsKey", lists); } } + +fn placeholder_constraint(element: &Element, reference: &str) -> bool { + element + .children_named("constraints") + .flat_map(|list| list.children.iter()) + .any(|c| { + c.name == "constraint" + && c.attr("id") == Some(reference) + && c.attr("placeholder") == Some("YES") + }) +} diff --git a/sweetpad-cli/src/cli/ibtool/xib.rs b/sweetpad-cli/src/cli/ibtool/xib.rs index 753e6571..bc7fd418 100644 --- a/sweetpad-cli/src/cli/ibtool/xib.rs +++ b/sweetpad-cli/src/cli/ibtool/xib.rs @@ -1,22 +1,43 @@ //! An iOS XIB is one nib containing its top-level objects and connections. +use std::borrow::Cow; + use sweetpad_lib::xcscheme::Element; use super::Options; use super::storyboard::{nib_root, proxy}; -use super::uikit::Encoder; +use super::uikit::{Encoder, number, prepare_cell}; -pub(super) fn compile(document: &Element, options: &Options<'_>) -> Result, String> { +pub(super) fn compile( + document: &Element, + options: &Options<'_>, + deployment_major: Option, +) -> Result, String> { if document.attr("type") == Some("com.apple.InterfaceBuilder3.Cocoa.XIB") { return super::appkit::compile(document, options); } if document.attr("type") != Some("com.apple.InterfaceBuilder3.CocoaTouch.XIB") { return Err("this isn't an iOS XIB".to_string()); } - let elements = document.child("objects").ok_or("the XIB has no objects")?; + let objects = document.child("objects").ok_or("the XIB has no objects")?; + let elements: Vec<_> = objects + .children + .iter() + .map(|e| { + if e.name == "collectionViewCell" { + Cow::Owned(prepare_cell(e)) + } else { + Cow::Borrowed(e) + } + }) + .collect(); let mut encoder = Encoder::new(document, options); + let device_canvas = deployment_major + .filter(|v| *v < 17) + .filter(|_| document.attr("targetRuntime") == Some("iOS.CocoaTouch")) + .map(|_| legacy_canvas(document.child("device"))); let mut top = Vec::new(); - for element in &elements.children { + for element in &elements { if element.name == "placeholder" { let identifier = element .attr("placeholderIdentifier") @@ -26,10 +47,36 @@ pub(super) fn compile(document: &Element, options: &Options<'_>) -> Result) -> Result) -> (f64, f64) { + let portrait = match device.and_then(|d| d.attr("id")) { + Some("retina4_0") => (320.0, 568.0), + Some("retina4_7") => (375.0, 667.0), + Some("retina5_5") => (414.0, 736.0), + Some("retina5_9") => (375.0, 812.0), + Some("retina6_1" | "retina6_5") => (414.0, 896.0), + Some("retina6_12" | "retina3_5") => (393.0, 852.0), + Some("retina6_3") => (402.0, 874.0), + Some("retina6_7") => (430.0, 932.0), + Some("retina6_9") => (440.0, 956.0), + Some("ipad9_7") => (768.0, 1024.0), + Some("ipad10_2") => (810.0, 1080.0), + Some("ipad7_9") => (744.0, 1133.0), + _ => (600.0, 600.0), + }; + if device.and_then(|d| d.attr("orientation")) == Some("landscape") { + (portrait.1, portrait.0) + } else { + portrait + } +}