SPB Git

Repository Public

Thumbnails.swift 6.1 KB 102 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Components/Thumbnails.swift3// Description: Real thumbnails for the browser: the server's preview image when it has one, a Quick Look thumbnail of the verified local copy otherwise, the system icon as the placeholder and the fallback. Memory cache + disk cache keyed by content version, so a thumbnail is fetched once per version.4import AppKit5import QuickLookThumbnailing6import SPDriveCore7import SwiftUI89@MainActor final class ThumbnailStore {10    private let memory = NSCache<NSString, NSImage>()11    private var api: APIClient?12    private var directory: URL?13    private var inflight: [String: Task<NSImage?, Never>] = [:]14    /// Versions the server had no picture of when asked, and when: asked again a little later (a new upload gets its15    /// thumbnail from the server's worker a few seconds after it lands, and the change feed does not announce it).16    private var missing: [String: Date] = [:]17    static let retryAfter: TimeInterval = 2018    /// Kinds the server makes thumbnails of.19    static func mayHaveThumbnail(_ item: DriveItem) -> Bool { !item.isFolder && (item.hasThumbnail || ["image", "pdf", "video", "heic", "office"].contains(item.previewKind)) }20    private(set) var fetched = 02122    init() { memory.countLimit = 600 }23    func configure(api: APIClient, directory: URL) { self.api = api; self.directory = directory; try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) }24    func reset() { memory.removeAllObjects(); inflight.values.forEach { $0.cancel() }; inflight.removeAll(); missing.removeAll(); api = nil }2526    /// One thumbnail per content version.27    static func key(_ item: DriveItem) -> String { "\(item.id)-\(item.versionID ?? String(item.sha256.prefix(16)))" }28    func cached(_ item: DriveItem) -> NSImage? { memory.object(forKey: ThumbnailStore.key(item) as NSString) }2930    /// The server's thumbnail of a file (nil when it has none, or when it cannot be reached and none is cached).31    func image(for item: DriveItem) async -> NSImage? {32        let key = ThumbnailStore.key(item)33        if let hit = memory.object(forKey: key as NSString) { return hit }34        if let asked = missing[key], Date().timeIntervalSince(asked) < ThumbnailStore.retryAfter { return nil }35        guard ThumbnailStore.mayHaveThumbnail(item), let api, let directory else { return nil }36        if let running = inflight[key] { return await running.value }37        let file = directory.appendingPathComponent(key + ".img")38        let task = Task<NSImage?, Never> {39            if let data = try? Data(contentsOf: file), let img = NSImage(data: data) { return img }40            guard let request = try? api.thumbnailRequest(fileID: item.id), let (data, _) = try? await api.data(for: request), let img = NSImage(data: data), img.size.width > 0 else { return nil }41            try? data.write(to: file, options: .atomic)42            return img43        }44        inflight[key] = task45        let img = await task.value46        inflight[key] = nil47        if let img { memory.setObject(img, forKey: key as NSString); fetched += 1 } else if !Task.isCancelled { missing[key] = Date() }48        return img49    }50    /// A Quick Look thumbnail of a file that is on this Mac (used when the server has no picture of it).51    func local(_ item: DriveItem, url: URL, side: CGFloat) async -> NSImage? {52        let key = ThumbnailStore.key(item) + "-ql"53        if let hit = memory.object(forKey: key as NSString) { return hit }54        let request = QLThumbnailGenerator.Request(fileAt: url, size: CGSize(width: side, height: side), scale: NSScreen.main?.backingScaleFactor ?? 2, representationTypes: .thumbnail)55        guard let rep = try? await QLThumbnailGenerator.shared.generateBestRepresentation(for: request) else { return nil }56        let img = rep.nsImage57        memory.setObject(img, forKey: key as NSString)58        return img59    }60}6162/// The picture of an item: its real thumbnail when there is one, the icon the Finder would show otherwise.63struct ItemThumbnail: View {64    let model: AppModel   // explicit: used inside table cells and menus65    let item: DriveItem66    var side: CGFloat = 9667    @State private var image: NSImage?68    @State private var loadedKey = ""6970    var body: some View {71        let key = ThumbnailStore.key(item)72        ZStack {73            if let image, loadedKey == key {74                Image(nsImage: image).resizable().interpolation(.high).aspectRatio(contentMode: .fit)75                    .clipShape(RoundedRectangle(cornerRadius: max(3, side * 0.05), style: .continuous))76                    .overlay(RoundedRectangle(cornerRadius: max(3, side * 0.05), style: .continuous).strokeBorder(SPDTheme.hairline, lineWidth: 0.5))77                    .spdElevation(.e1)78                    .transition(.opacity)79            } else {80                ItemIcon(item: item, size: side * (side > 40 ? 0.74 : 1))81            }82        }83        .frame(width: side, height: side)84        .spdMotion(.hover, value: loadedKey)85        .task(id: key) {86            if let hit = model.thumbnails.cached(item) { image = hit; loadedKey = key; return }87            guard !item.isFolder else { return }88            if ThumbnailStore.mayHaveThumbnail(item) {89                if let img = await model.thumbnails.image(for: item) { image = img; loadedKey = key; return }90                if !item.hasThumbnail, side > 40 {91                    // just uploaded: the server's worker may still be drawing it — look once more shortly92                    try? await Task.sleep(nanoseconds: UInt64((ThumbnailStore.retryAfter + 1) * 1e9))93                    if !Task.isCancelled, let img = await model.thumbnails.image(for: item) { image = img; loadedKey = key; return }94                }95            }96            // no picture on the server: draw one from the copy on this Mac, when there is one (never downloads for a thumbnail)97            if side > 40, let url = model.existingLocalCopy(of: item), let img = await model.thumbnails.local(item, url: url, side: side) { image = img; loadedKey = key }98        }99        .accessibilityHidden(true)100    }101}102
Files main
Menu

Theme