Cotton code
138 lines · 6.3 KB · SwiftRaw
// A POSTER, A BACKDROP OR A STILL BY ITS MEDIA KEY: the core brings the file to the phone (`media.ensure`), and it is// decoded off the main thread at the size it is drawn, never larger (MOTION.md "Budget"). Until it lands, its// skeleton stands in the same frame, so nothing moves when it fades in over it (180 ms). The invented library's keys// (`drawn:<seed>`) are drawn here instead, so a walk needs no files.#if os(iOS)import CottonKitimport SwiftUIimport UIKit/// The pictures already decoded, by key and size, and the one way to the core's files.final class CinemasPictures: @unchecked Sendable {    private let core: (any CottonCalling)?    private let cache = NSCache<NSString, UIImage>()    init(core: (any CottonCalling)?) {        self.core = core        cache.countLimit = 400    }    private struct Ask: Encodable, Sendable { let key: String }    private struct Landed: Decodable, Sendable { let path: String }    func cached(_ key: String, _ size: CGSize) -> UIImage? { cache.object(forKey: Self.name(key, size)) }    /// The picture last drawn for `key`, at whatever size: the player stands it behind its spinner on the tap.    func latest(_ key: String) -> UIImage? { cache.object(forKey: key as NSString) }    func image(_ key: String, _ size: CGSize, scale: CGFloat) async -> UIImage? {        if let hit = cached(key, size) { return hit }        guard let core, let path = try? await core.call(CottonMethod.mediaEnsure, Ask(key: key), as: Landed.self).path else { return nil }        let pixels = CGSize(width: size.width * scale, height: size.height * scale)        let decoded = await Task.detached(priority: .userInitiated) { () -> UIImage? in            guard let whole = UIImage(contentsOfFile: path) else { return nil }            return await whole.byPreparingThumbnail(ofSize: Self.fill(whole.size, pixels)) ?? whole        }.value        if let decoded {            cache.setObject(decoded, forKey: Self.name(key, size))            cache.setObject(decoded, forKey: key as NSString)        }        return decoded    }    /// The size that fills `box` keeping the picture's shape.    private static func fill(_ size: CGSize, _ box: CGSize) -> CGSize {        guard size.width > 0, size.height > 0 else { return box }        let k = max(box.width / size.width, box.height / size.height)        return CGSize(width: (size.width * k).rounded(.up), height: (size.height * k).rounded(.up))    }    private static func name(_ key: String, _ size: CGSize) -> NSString { "\(key)@\(Int(size.width))x\(Int(size.height))" as NSString }}private struct CinemasPicturesKey: EnvironmentKey {    static let defaultValue = CinemasPictures(core: nil)}extension EnvironmentValues {    var cinemasPictures: CinemasPictures {        get { self[CinemasPicturesKey.self] }        set { self[CinemasPicturesKey.self] = newValue }    }}/// One picture filling its frame; the frame is the caller's, so the skeleton and the picture stand in the same place.struct CinemasPicture: View {    let key: String?    /// The words a drawn poster carries (a poster's title); a backdrop or a still carries none.    var title: String?    /// The title's id: a title with no picture, or one that will not come, is drawn from it (PUNCH Both 1), the same    /// every time.    var seed: String?    /// The core's drawn picture for the title (`Item.art`); drawn from `seed` when an older core sent none.    var art: CinemasArt?    @Environment(\.cinemasPictures) private var pictures    @Environment(\.displayScale) private var scale    @State private var image: UIImage?    @State private var failed = false    var body: some View {        GeometryReader { box in            ZStack {                CinemasInk.raised                if let key, key.hasPrefix("drawn:") {                    CinemasDrawn(art: art ?? .standIn(seed ?? String(key.dropFirst(6))), name: title)                } else if let image {                    Image(uiImage: image)                        .resizable()                        .scaledToFill()                        .frame(width: box.size.width.drawableOrZero, height: box.size.height.drawableOrZero)                        .clipped()                        .overlay(alignment: .bottomLeading) {                            // A poster that is a frame from the film carries no name of its own: the name sits over                            // its foot (PUNCH, his real library). A small thumbnail has its name beside it.                            if let title, box.size.width >= 80 { named(title, width: box.size.width) }                        }                        .transition(.opacity.animation(CinemasMotion.skeletonToPoster))                } else if key == nil || failed {                    CinemasDrawn(art: art ?? .standIn(seed ?? title ?? key ?? ""), name: title)                } else {                    Color.white.opacity(0.06).cinemasShimmer()                }            }            .task(id: "\(key ?? "")@\(Int(box.size.width.drawableOrZero))") {                #if COTTON_DEV                if box.size.width.drawable == nil || box.size.height.drawable == nil {                    print("cinemas-walk: picture \(key ?? "-") given \(box.size)")                }                #endif                guard let key, !key.hasPrefix("drawn:"), box.size.width.drawableOrZero > 0, box.size.height.drawableOrZero > 0 else { return }                if let hit = pictures.cached(key, box.size) {                    image = hit                    return                }                let landed = await pictures.image(key, box.size, scale: scale)                withAnimation(CinemasMotion.skeletonToPoster) {                    image = landed                    failed = landed == nil                }            }        }        .accessibilityHidden(true)    }    private func named(_ title: String, width: CGFloat) -> some View {        Text(title)            .font(CinemasFonts.sans(max(9, width * 0.085), 700))            .foregroundStyle(.white)            .lineLimit(2)            .truncationMode(.tail)            .shadow(color: .black.opacity(0.6), radius: 2, y: 1)            .padding(width * 0.07)            .frame(maxWidth: .infinity, alignment: .leading)            .background(LinearGradient(colors: [.clear, .black.opacity(0.75)], startPoint: .top, endPoint: .bottom))    }}#endif