SPB Git

Repository Public

VQExport.swift 4.9 KB 99 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantUI/Support/VQExport.swift3// Description: PNG and PDF export of any VQuantUI view (a chart, a whole result) with `ImageRenderer`, and the4//              clipboard. The only platform-conditional code of the module lives here.5import SwiftUI6import ImageIO7import UniformTypeIdentifiers8import VQuantKit9#if canImport(AppKit)10import AppKit11#elseif canImport(UIKit)12import UIKit13#endif1415public enum VQPasteboard {16    @MainActor public static func copy(_ text: String) {17        #if canImport(AppKit)18        NSPasteboard.general.clearContents()19        NSPasteboard.general.setString(text, forType: .string)20        #elseif canImport(UIKit)21        UIPasteboard.general.string = text22        #endif23    }24}2526@MainActor27public enum VQExport {28    /// The token colours follow the system appearance, which an off-screen render does not inherit from SwiftUI's29    /// `colorScheme`: the render runs inside the appearance asked for.30    private static func withAppearance<T>(_ scheme: ColorScheme, _ body: () -> T) -> T {31        #if canImport(AppKit)32        var out: T?33        (NSAppearance(named: scheme == .dark ? .darkAqua : .aqua) ?? NSAppearance.currentDrawing()).performAsCurrentDrawingAppearance { out = body() }34        return out ?? body()35        #elseif canImport(UIKit)36        var out: T?37        UITraitCollection(userInterfaceStyle: scheme == .dark ? .dark : .light).performAsCurrent { out = body() }38        return out ?? body()39        #else40        return body()41        #endif42    }4344    private static func framed<V: View>(_ view: V, width: CGFloat, scheme: ColorScheme, theme: VQTheme, padding: CGFloat) -> some View {45        view46            .padding(padding)47            .frame(width: width, alignment: .topLeading)48            .background(VQTokens.Palette.ink0)49            .environment(\.colorScheme, scheme)50            .environment(\.vqStaticRender, true)51            .vqTheme(theme)52    }5354    /// PNG bytes of a view laid out at `width` points (height follows the content).55    public static func png<V: View>(_ view: V, width: CGFloat, colorScheme: ColorScheme = .light, theme: VQTheme = VQTheme(), scale: CGFloat = 2, padding: CGFloat = 24) -> Data? {56        let renderer = ImageRenderer(content: framed(view, width: width, scheme: colorScheme, theme: theme, padding: padding))57        renderer.scale = scale58        guard let image = withAppearance(colorScheme, { renderer.cgImage }) else { return nil }59        let data = NSMutableData()60        guard let destination = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil) else { return nil }61        CGImageDestinationAddImage(destination, image, nil)62        return CGImageDestinationFinalize(destination) ? data as Data : nil63    }6465    /// A one-page vector PDF of a view laid out at `width` points.66    public static func pdf<V: View>(_ view: V, width: CGFloat, colorScheme: ColorScheme = .light, theme: VQTheme = VQTheme(), padding: CGFloat = 24) -> Data? {67        let renderer = ImageRenderer(content: framed(view, width: width, scheme: colorScheme, theme: theme, padding: padding))68        let data = NSMutableData()69        var ok = false70        withAppearance(colorScheme) {71            renderer.render { size, draw in72                var box = CGRect(origin: .zero, size: size)73                guard let consumer = CGDataConsumer(data: data as CFMutableData), let context = CGContext(consumer: consumer, mediaBox: &box, nil) else { return }74                context.beginPDFPage(nil)75                draw(context)76                context.endPDFPage()77                context.closePDF()78                ok = true79            }80        }81        return ok ? data as Data : nil82    }8384    /// One chart of a result as PNG (title, legend, plot, note).85    public static func png(chart: VQLabResult.Chart, width: CGFloat = 720, height: CGFloat = 320, colorScheme: ColorScheme = .light, theme: VQTheme = VQTheme(), scale: CGFloat = 2) -> Data? {86        png(LabChartView(chart, height: height), width: width, colorScheme: colorScheme, theme: theme, scale: scale)87    }88    public static func pdf(chart: VQLabResult.Chart, width: CGFloat = 720, height: CGFloat = 320, colorScheme: ColorScheme = .light, theme: VQTheme = VQTheme()) -> Data? {89        pdf(LabChartView(chart, height: height), width: width, colorScheme: colorScheme, theme: theme)90    }9192    /// The chart's data as CSV text (the table view the design system asks for next to a light-theme chart).93    nonisolated public static func csv(chart: VQLabResult.Chart) -> String {94        let t = VQLabChartData.table(of: chart)95        func field(_ s: String) -> String { s.contains(",") || s.contains("\"") || s.contains("\n") ? "\"" + s.replacingOccurrences(of: "\"", with: "\"\"") + "\"" : s }96        return ([t.header] + t.rows).map { $0.map(field).joined(separator: ",") }.joined(separator: "\n") + "\n"97    }98}99
Files main
Menu

Theme