示例工程 40-windows-scenes-macos

40-windows-scenes-macos/Sources/Ch40Demo/App.swift

swift · 2.0 KB

import AppKit
import Ch40Kit
import SwiftUI
 
@main
struct Ch40Demo {
    @MainActor
    static func main() {
        print("[40.1] 场景数量 = \(WindowCatalog.all.count)")
        print("[40.2] 主窗口尺寸 = \(Int(WindowCatalog.main.width))x\(Int(WindowCatalog.main.height))")
        print("[40.3] ID 唯一 = \(Set(WindowCatalog.all.map(\.id)).count == WindowCatalog.all.count)")
        print("[40.4] 规格有效 = \(WindowCatalog.all.allSatisfy(\.isValid))")
 
        let workspace = Workspace(documentCount: 2)
        workspace.addDocument()
        print("[40.5] 共享模型文档数 = \(workspace.documentCount)")
 
        print("[40.6] 窗口板渲染 = \(size(WindowBoard()))")
        print("[40.7] MemoryLayout<WindowSpec> = \(MemoryLayout<WindowSpec>.size) 字节")
 
        if let directory = ProcessInfo.processInfo.environment["SHOTS_DIR"] {
            write(WindowBoard(), name: "window-board.png", directory: directory)
        }
    }
 
    @MainActor
    private static func size(_ view: some View) -> String {
        guard let image = ImageRenderer(content: view).cgImage else { return "nil" }
        return "\(image.width)x\(image.height)"
    }
 
    @MainActor
    private static func write(_ view: some View, name: String, directory: String) {
        let renderer = ImageRenderer(content: view)
        renderer.scale = 2
        guard
            let image = renderer.cgImage,
            let data = NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:])
        else {
            print("[40.8] 截图失败:\(name)")
            return
        }
        let url = URL(fileURLWithPath: directory).appendingPathComponent(name)
        do {
            try FileManager.default.createDirectory(
                at: url.deletingLastPathComponent(),
                withIntermediateDirectories: true
            )
            try data.write(to: url)
            print("[40.8] 截图 = \(name) \(image.width)x\(image.height)")
        } catch {
            print("[40.8] 截图失败:\(error)")
        }
    }
}