Cotton code
301 lines · 14.7 KB · SwiftRaw
// Where the package's pictures come from — on the phone AND on the Mac.//// The phone reaches `Bundle.module`: Xcode compiles `Media.xcassets` into an// `Assets.car` and puts the bundle where the generated accessor looks, so// `Image(name, bundle: .module)` is the whole answer there.//// THE MAC HAS TO READ TWO BUNDLE LAYOUTS, AND THAT IS THE WHOLE POINT OF THIS// FILE. `swift build` decides both, and it decided differently under two// toolchains this repo is built by:////   * THE COMPILED LAYOUT — what the SHIPPING app has. SwiftPM's Swift Build//     system (Xcode 27, the release lane) runs actool over a `.process`ed//     catalogue like Xcode always has, and writes a macOS-layout bundle://     `Loom_CottonPaper.bundle/Contents/Resources/Assets.car`, with no//     `Media.xcassets` anywhere in it. The pictures are reachable only//     THROUGH the catalogue — `Bundle.image(forResource:)`.//   * THE RAW LAYOUT — what the older native build system still writes//     (Xcode 26, a local `swift build` / `swift test`): a FLAT bundle with//     the imageset directories and their PNGs copied as-is, no `Assets.car`.//     There the catalogue read answers nil and the PNG is right there on//     disk.//// So a picture is asked of the compiled catalogue FIRST and read off disk// second (`CottonMedia.nsImage`). Measured 2026-09-20: reading the raw// catalogue alone left every cap, paper, stamp and tool face blank in the// shipped Mac app — the sidebar's project caps were empty circles — because// the installed bundle holds an `Assets.car` and nothing else.//// Either way the Mac never touches `.module`: its accessor looks beside the// executable and in the build directory only, and `fatalError`s when neither// has it, which an installed `CottonDB.app` never does// (`ResourceBundleGuardTests`). It FINDS the bundle by path instead —// `Contents/Resources/` of a packaged app, where `scripts/build-app.sh`// copies it, or beside the executable under a plain `swift build` / `swift// test`. Absent both, a picture answers nil and the view that asked draws its// flat stand-in, visibly; nothing pretends.//// Every picture on both hosts comes through here: the caps// (`Paper/ProjectCaps.swift`, `Boot/HomeSidebar.swift`), the papers// and their grain (`Paper/`), the stamps, the tool faces and the gallery.import SwiftUI#if canImport(UIKit)    import UIKit#elseif canImport(AppKit)    import AppKit#endifpublic enum CottonResources {    /// The SwiftPM resource bundle's name: `<package>_<target>.bundle` — the    /// look's, which holds the pictures, the faces, the palette and the    /// shipped catalogue. `CottonUI` keeps a bundle of its own for what only    /// its screens read (`CottonUIResources`), found by the same search.    public static let bundleName = "Loom_CottonPaper.bundle"    /// The package's resource bundle, wherever this build put it — or nil    /// when this build has none to find.    public static let bundle: Bundle? = {        #if canImport(UIKit)            return Bundle.module        #else            // The image holding this code second: in the app it is the main            // bundle again, but `swift test` runs from the toolchain's            // `xctest`, and only the test bundle sits beside this one.            return locate(from: Bundle.main) ?? locate(from: Bundle(for: Marker.self))        #endif    }()    private final class Marker {}    /// The Mac's search, as a function of the main bundle so a test can hand    /// it a directory: `Contents/Resources/` first (a packaged app), then the    /// executable's own directory and up to three above it (`swift build`    /// puts the bundle in `.build/<config>/`, beside the executable; `swift    /// test` runs from `.build/<config>/<name>.xctest/Contents/MacOS/`).    public static func locate(from main: Bundle) -> Bundle? {        locate(bundleName, from: main)    }    /// The same search for any of the package's bundles, by its name.    public static func locate(_ bundleName: String, from main: Bundle) -> Bundle? {        var candidates: [URL] = []        if let resources = main.resourceURL {            candidates.append(resources.appendingPathComponent(bundleName))        }        var directory = main.bundleURL        for _ in 0..<4 {            candidates.append(directory.appendingPathComponent(bundleName))            directory.deleteLastPathComponent()        }        for candidate in candidates        where FileManager.default.fileExists(atPath: candidate.path) {            if let found = Bundle(url: candidate) { return found }        }        return nil    }}public enum CottonMedia {    #if canImport(UIKit)        /// The pictures `image(_:)` and `image(_:scale:)` have made, decoded,        /// each bounded by its bytes; the system empties them under pressure.        private nonisolated(unsafe) static let named = decodedCache()        private nonisolated(unsafe) static let scaled = decodedCache()        /// Decoded catalogue pictures kept, in bytes, per cache: Home's tiles        /// and the paper's sheets fit.        private static let keptBytes = 48 << 20        private static func decodedCache() -> NSCache<NSString, UIImage> {            let cache = NSCache<NSString, UIImage>()            cache.totalCostLimit = keptBytes            return cache        }        /// Keeps `picture` at once, so the next reader draws the same image,        /// and its decoded copy in its place once the decode — off the main        /// thread, never inside a view's body — is done.        ///        /// Drawn into a plain bitmap, not `prepareForDisplay`: for a catalogue        /// image that hands back nothing, and the renderer went on        /// decompressing the catalogue's own copy in every commit (fan3 part 0).        private static func keep(_ picture: UIImage, as key: NSString, in cache: NSCache<NSString, UIImage>) {            cache.setObject(picture, forKey: key, cost: bytes(picture))            // A UIImage and the cache are safe across threads; the compiler            // cannot see it.            nonisolated(unsafe) let cache = cache            nonisolated(unsafe) let picture = picture            nonisolated(unsafe) let key = key            DispatchQueue.global(qos: .utility).async {                let format = UIGraphicsImageRendererFormat()                format.scale = picture.scale                format.opaque = false                format.preferredRange = .standard                let decoded = UIGraphicsImageRenderer(size: picture.size, format: format).image { _ in                    picture.draw(at: .zero)                }                cache.setObject(decoded, forKey: key, cost: bytes(decoded))            }        }        private static func bytes(_ image: UIImage) -> Int {            guard let cg = image.cgImage else { return 0 }            return cg.bytesPerRow * cg.height        }    #endif    #if canImport(UIKit)        /// The pictures this flavour's build left out of its catalogue: the        /// whole catalogue less the flavour's list in `apps/loom/materials.json`        /// (`scripts/ios-flavour-pictures.py` writes them beside the        /// Assets.car). Empty for a flavour that carries the whole catalogue.        private static let leftOut: Set<String> = {            guard                let url = Bundle.module.url(forResource: "left-out-pictures", withExtension: "json"),                let data = try? Data(contentsOf: url),                let names = try? JSONDecoder().decode([String].self, from: data)            else { return [] }            return Set(names)        }()        /// Nil for a name the catalogue does not hold, as ever — but a name        /// this flavour LEFT OUT is a picture it draws and does not carry, and        /// a debug build stops right here, naming it, so a walk or a test        /// finds the hole before a person sees one.        private static func absent(_ name: String) -> Image? {            expect(name)            return nil        }    #endif    /// Says that this flavour carries the picture `name`, for a view that    /// draws an imageset by `Image(_:bundle:)` rather than through `image(_:)`:    /// a debug build stops when the flavour's build left it out    /// (`apps/loom/materials.json`). Nothing on the Mac, which carries all.    public static func expect(_ name: String) {        #if canImport(UIKit)            assert(!leftOut.contains(name), "This flavour draws the picture \(name) and does not carry it: add it to the flavour's list in apps/loom/materials.json")        #endif    }    /// An imageset of `Media.xcassets`, by name — `Bundle.module` on the    /// phone, the located bundle's compiled catalogue (then its raw imageset)    /// on the Mac. Nil on a Mac build that carries no bundle, or for a name    /// the catalogue does not hold.    public static func image(_ name: String) -> Image? {        #if canImport(UIKit)            // Kept, and decoded off the main thread, as `image(_:scale:)` is:            // a catalogue image named afresh was decompressed again in the            // commit of every page that mounted it (fan3 part 0). The            // catalogue has no dark or template variants, so a decoded copy            // is the same picture.            if let kept = named.object(forKey: name as NSString) { return Image(uiImage: kept) }            guard let picture = UIImage(named: name, in: .module, compatibleWith: nil) else { return absent(name) }            keep(picture, as: name as NSString, in: named)            return Image(uiImage: picture)        #else            guard let picture = nsImage(name) else { return nil }            return Image(nsImage: picture)        #endif    }    /// An imageset drawn at a SCALE this call chooses rather than the one its    /// `Contents.json` declares — the same picture, laid out smaller or larger    /// in points.    ///    /// Its one reader is the paper's surface (`Paper/PaperPhoto.swift`). A    /// nine-sliced picture keeps its cap insets at the image's own POINT size,    /// so the only way to draw a sheet's worn corner smaller on a chip than on    /// a page is to hand SwiftUI the same pixels at a different scale. Nil for    /// the same reasons `image(_:)` is nil.    ///    /// Kept, decoded, one per name and scale: a picture made afresh on every    /// call was a new image to the renderer each time a surface laid itself    /// out, decompressed from the catalogue inside the frame's commit (fan3    /// part 0: 60–85 ms commits while the fan turned).    public static func image(_ name: String, scale: CGFloat) -> Image? {        guard scale > 0 else { return image(name) }        #if canImport(UIKit)            let key = "\(name)@\(scale)" as NSString            if let kept = scaled.object(forKey: key) { return Image(uiImage: kept) }            guard                let picture = UIImage(named: name, in: .module, compatibleWith: nil),                let bitmap = picture.cgImage            else { return absent(name) }            let sized = UIImage(cgImage: bitmap, scale: scale, orientation: .up)            keep(sized, as: key, in: scaled)            return Image(uiImage: sized)        #else            guard let picture = nsImage(name) else { return nil }            // `size` is what `Image(nsImage:)` lays out in POINTS, and the two            // layouts disagree about it: a PNG read off disk measures itself            // in the file's own pixels, while the compiled catalogue already            // divides by the scale the imageset declares (`paper-cream` is a            // 720px master at 2x — 720 points raw, 360 compiled). The            // representation's PIXELS are the one figure both agree on, so the            // arithmetic is done from there and the answer is the same picture            // on either build.            //            // On a COPY: a catalogue image belongs to the bundle and can come            // back again for the next caller, so resizing the original would            // hand the next reader this call's scale.            guard                let sized = picture.copy() as? NSImage,                let bitmap = sized.representations.first,                bitmap.pixelsWide > 0, bitmap.pixelsHigh > 0            else { return Image(nsImage: picture) }            sized.size = CGSize(                width: CGFloat(bitmap.pixelsWide) / scale,                height: CGFloat(bitmap.pixelsHigh) / scale            )            return Image(nsImage: sized)        #endif    }    #if !canImport(UIKit)        /// The Mac's picture, from whichever layout this build wrote: the        /// COMPILED catalogue first (`Assets.car`, the shipping app), the raw        /// imageset's PNG second (a local `swift build` / `swift test`). Nil        /// when there is no bundle, or when neither layout holds the name.        static func nsImage(_ name: String, in bundle: Bundle? = CottonResources.bundle) -> NSImage?        {            guard let bundle else { return nil }            if let compiled = bundle.image(forResource: NSImage.Name(name)) { return compiled }            guard let url = rawImageURL(name, in: bundle) else { return nil }            return NSImage(contentsOf: url)        }    #endif    /// The first picture (a PNG, else a JPEG: a paper or a felt is kept as    /// a JPEG) of the RAW imageset directory, under the bundle found    /// above. `nil` when there is no bundle, no such imageset, or the bundle    /// is the compiled layout (which carries no `Media.xcassets` at all).    ///    /// Both bases are tried because both exist: a macOS-layout bundle keeps    /// its resources under `Contents/Resources` (`resourceURL`), and a flat    /// SwiftPM one keeps them at the bundle root — where `resourceURL` is the    /// bundle root anyway, so the order costs nothing.    static func rawImageURL(_ name: String, in bundle: Bundle? = CottonResources.bundle) -> URL? {        guard let bundle else { return nil }        var bases: [URL] = []        if let resources = bundle.resourceURL { bases.append(resources) }        bases.append(bundle.bundleURL)        for base in bases {            let directory = base                .appendingPathComponent("Media.xcassets")                .appendingPathComponent("\(name).imageset")            guard                let files = try? FileManager.default.contentsOfDirectory(                    at: directory, includingPropertiesForKeys: nil)            else { continue }            let pictures = files.sorted(by: { $0.lastPathComponent < $1.lastPathComponent })            for kind in ["png", "jpg", "jpeg"] {                if let picture = pictures.first(where: { $0.pathExtension.lowercased() == kind }) {                    return picture                }            }        }        return nil    }}