Sources/Orgstar/DevelopmentHooks.swift
41 lines · 2454 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`: commands to run at launch, separated by commas (`app.import-emacs`); a
9/// sheet or prompt they open is what the snapshot renders.
10/// - `ORGSTAR_APPEARANCE`: `dark` or `light`, instead of the system's.
11/// - `ORGSTAR_SNAPSHOT`: after `ORGSTAR_SNAPSHOT_DELAY` seconds (default 3), render the main
12/// window to this PNG path and quit. Rendering from inside the app needs no screen-recording
13/// permission.
14enum DevelopmentHooks {
15 static var fileToOpen: String? { ProcessInfo.processInfo.environment["ORGSTAR_OPEN"] }
16 static var rootToAdd: String? { ProcessInfo.processInfo.environment["ORGSTAR_ROOT"] }
17 static var windowToOpen: String? { ProcessInfo.processInfo.environment["ORGSTAR_WINDOW"] }
18 static var commandToRun: String? { ProcessInfo.processInfo.environment["ORGSTAR_COMMAND"] }
19
20 @MainActor
21 static func scheduleSnapshot() {
22 let environment = ProcessInfo.processInfo.environment
23 if let appearance = environment["ORGSTAR_APPEARANCE"] {
24 NSApp.appearance = NSAppearance(named: appearance == "dark" ? .darkAqua : .aqua)
25 }
26 guard let path = environment["ORGSTAR_SNAPSHOT"] else { return }
27 let delay = Double(environment["ORGSTAR_SNAPSHOT_DELAY"] ?? "") ?? 3
28 DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
29 let visible = NSApp.windows.filter(\.isVisible)
30 let chosen = windowToOpen.flatMap { id in visible.first { $0.identifier?.rawValue.lowercased().contains(id) == true } } ?? visible.first
31 let window = chosen?.attachedSheet ?? chosen
32 if let view = window?.contentView?.superview,
33 let bitmap = view.bitmapImageRepForCachingDisplay(in: view.bounds) {
34 view.cacheDisplay(in: view.bounds, to: bitmap)
35 try? bitmap.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: path))
36 }
37 if let chosen, let sheet = chosen.attachedSheet { chosen.endSheet(sheet) }
38 NSApp.terminate(nil)
39 }
40 }
41}