示例工程 39-focus-keyboard-commands

39-focus-keyboard-commands/Sources/Ch39Demo/App.swift

swift · 2.1 KB

import AppKit
import Ch39Kit
import SwiftUI
 
@main
struct Ch39Demo {
    @MainActor
    static func main() {
        let new = KeyInput(key: "n", command: true)
        print("[39.1] ⌘N → \(Keymap.resolve(new)?.rawValue ?? "nil")")
 
        let search = KeyInput(key: "f", command: true)
        print("[39.2] ⌘F → \(Keymap.resolve(search)?.rawValue ?? "nil")")
 
        let unknown = KeyInput(key: "z", command: true)
        print("[39.3] ⌘Z → \(Keymap.resolve(unknown)?.rawValue ?? "nil")")
        print("[39.4] 快捷键数量 = \(Keymap.entries.count)")
 
        print("[39.5] ⌘⇧/ 显示 = \(KeyInput(key: "/", command: true, shift: true).display)")
        print("[39.6] 快捷键卡片渲染 = \(size(ShortcutCard()))")
        print("[39.7] MemoryLayout<KeyInput> = \(MemoryLayout<KeyInput>.size) 字节")
 
        if let directory = ProcessInfo.processInfo.environment["SHOTS_DIR"] {
            write(ShortcutCard(), name: "shortcut-card.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("[39.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("[39.8] 截图 = \(name) \(image.width)x\(image.height)")
        } catch {
            print("[39.8] 截图失败:\(error)")
        }
    }
}