SPB Git

Repository Public

Thumbnails.swift 5.5 KB 108 lines swift

1// SP Drive iOS2// File: Features/MyDrive/Thumbnails.swift3// Description: Thumbnails for the explorer: from the local copy when there is one (ImageIO downsampling, first page with PDFKit),4//              otherwise the server's thumbnail; cached in memory and on disk, keyed by content hash.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ImageIO9import PDFKit10import SwiftUI11import UIKit1213actor ThumbnailLoader {14    static let shared = ThumbnailLoader()15    private nonisolated(unsafe) let memory = NSCache<NSString, UIImage>() // NSCache is thread-safe16    private var inFlight: [String: Task<UIImage?, Never>] = [:]1718    init() { memory.countLimit = 400 }1920    nonisolated func cached(_ item: DriveItem) -> UIImage? { memory.object(forKey: Self.key(item) as NSString) }21    static func key(_ item: DriveItem) -> String { "\(item.id)-\(item.sha256.prefix(16))" }2223    func image(for item: DriveItem, model: (api: DriveAPI, store: DriveStore, files: LocalFiles), online: Bool) async -> UIImage? {24        let key = Self.key(item)25        if let hit = memory.object(forKey: key as NSString) { return hit }26        if let running = inFlight[key] { return await running.value }27        let task = Task<UIImage?, Never>(priority: .utility) {28            let disk = model.files.thumbnail(itemID: item.id, sha: item.sha256)29            if let data = try? Data(contentsOf: disk), let img = UIImage(data: data) { return img }30            var image: UIImage?31            if let ls = model.store.localState(item.id), let url = model.files.url(for: ls), ls.baseSHA == item.sha256 || ls.dirty {32                image = item.kind == .pdf ? Self.pdfThumbnail(url) : (item.kind == .image ? Self.downsample(url) : nil)33            }34            if image == nil, online, item.hasThumbnail, !item.isLocalOnly, let request = try? await model.api.thumbnailRequest(fileID: item.id), let data = try? await model.api.fetchSmall(request) {35                image = UIImage(data: data)36            }37            if let image, let jpeg = image.jpegData(compressionQuality: 0.8) { try? jpeg.write(to: disk, options: .atomic) }38            return image39        }40        inFlight[key] = task41        let result = await task.value42        inFlight[key] = nil43        if let result { memory.setObject(result, forKey: key as NSString) }44        return result45    }4647    /// Decodes at thumbnail size without loading the full image in memory.48    static func downsample(_ url: URL, maxPixel: CGFloat = 400) -> UIImage? {49        guard let source = CGImageSourceCreateWithURL(url as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary) else { return nil }50        let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: maxPixel]51        return CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary).map { UIImage(cgImage: $0) }52    }5354    static func pdfThumbnail(_ url: URL) -> UIImage? {55        PDFDocument(url: url)?.page(at: 0)?.thumbnail(of: CGSize(width: 400, height: 400), for: .cropBox)56    }57}5859/// Thumbnail when one exists, kind icon otherwise.60struct ItemThumbnail: View {61    @Environment(AppModel.self) private var model62    let item: DriveItem63    var size: CGFloat = 4064    @State private var image: UIImage?6566    var body: some View {67        Group {68            if let image = image ?? ThumbnailLoader.shared.cached(item) {69                Image(uiImage: image).resizable().scaledToFill().frame(width: size, height: size).clipShape(RoundedRectangle(cornerRadius: size * 0.2, style: .continuous))70                    .overlay(RoundedRectangle(cornerRadius: size * 0.2, style: .continuous).strokeBorder(.separator, lineWidth: 0.5))71            } else {72                KindIcon(kind: item.kind, size: size)73            }74        }75        .task(id: ThumbnailLoader.key(item)) {76            guard !item.isFolder, item.kind == .image || item.kind == .pdf || item.hasThumbnail else { image = nil; return }77            image = await ThumbnailLoader.shared.image(for: item, model: (model.api, model.store, model.files), online: model.network.online)78        }79        .accessibilityHidden(true)80    }81}8283/// The preview area of a card: the thumbnail fills it when one exists; otherwise the kind's symbol sits on a tint of its colour.84struct ItemPreviewTile: View {85    @Environment(AppModel.self) private var model86    let item: DriveItem87    @State private var image: UIImage?8889    var body: some View {90        Color.clear91            .overlay {92                if let image = image ?? ThumbnailLoader.shared.cached(item) {93                    Image(uiImage: image).resizable().scaledToFill()94                } else if item.isFolder {95                    ZStack { Theme.gradient.opacity(0.14); Image(systemName: "folder.fill").font(.system(size: 44, weight: .semibold)).foregroundStyle(Theme.gradient) }96                } else {97                    ZStack { Theme.color(for: item.kind).opacity(0.12); Image(systemName: item.kind.symbol).font(.system(size: 36, weight: .semibold)).foregroundStyle(Theme.color(for: item.kind)) }98                }99            }100            .clipped()101            .task(id: ThumbnailLoader.key(item)) {102                guard !item.isFolder, item.kind == .image || item.kind == .pdf || item.hasThumbnail else { image = nil; return }103                image = await ThumbnailLoader.shared.image(for: item, model: (model.api, model.store, model.files), online: model.network.online)104            }105            .accessibilityHidden(true)106    }107}108
Files main
Menu

Theme