Sources/Orgstar/DevelopmentHooks.swift

b5449dec59a00fac6867954166c6c612ffd6aee4
orgstar/Sources/Orgstar/DevelopmentHooks.swift history · blame · raw

37 lines · 2184 bytes

 1import AppKit
 2
 3/// Switches for checking the app from scripts, read from the environment:
 4/// - `ORGSTAR_DATA_DIR`: where the index and roots live (see `WorkspaceModel.defaultDirectory`).
 5/// - `ORGSTAR_OPEN`: a file to select at launch.
 6/// - `ORGSTAR_ROOT`: a folder to add at launch.
 7/// - `ORGSTAR_WINDOW`: a window to open at launch (`agenda`, `settings`); the snapshot renders it.
 8/// - `ORGSTAR_COMMAND`: a command to run at launch (`app.import-emacs`); a sheet it opens is
 9///   what the snapshot renders.
10/// - `ORGSTAR_SNAPSHOT`: after `ORGSTAR_SNAPSHOT_DELAY` seconds (default 3), render the main
11///   window to this PNG path and quit. Rendering from inside the app needs no screen-recording
12///   permission.
13enum DevelopmentHooks {
14    static var fileToOpen: String? { ProcessInfo.processInfo.environment["ORGSTAR_OPEN"] }
15    static var rootToAdd: String? { ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] }
16    static var windowToOpen: String? { ProcessInfo.processInfo.environment["ORGSTAR_WINDOW"] }
17    static var commandToRun: String? { ProcessInfo.processInfo.environment["ORGSTAR_COMMAND"] }
18
19    @MainActor
20    static func scheduleSnapshot() {
21        let environment = ProcessInfo.processInfo.environment
22        guard let path = environment["ORGSTAR_SNAPSHOT"] else { return }
23        let delay = Double(environment["ORGSTAR_SNAPSHOT_DELAY"] ?? "") ?? 3
24        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
25            let visible = NSApp.windows.filter(\.isVisible)
26            let chosen = windowToOpen.flatMap { id in visible.first { $0.identifier?.rawValue.lowercased().contains(id) == true } } ?? visible.first
27            let window = chosen?.attachedSheet ?? chosen
28            if let view = window?.contentView?.superview,
29               let bitmap = view.bitmapImageRepForCachingDisplay(in: view.bounds) {
30                view.cacheDisplay(in: view.bounds, to: bitmap)
31                try? bitmap.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: path))
32            }
33            if let chosen, let sheet = chosen.attachedSheet { chosen.endSheet(sheet) }
34            NSApp.terminate(nil)
35        }
36    }
37}