diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ea70b9..e827c35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ All notable changes to Deep Field. Versions follow [Semantic Versioning](https:/ ## [Unreleased] +- A `deepfield` command for the terminal: switch scenes and presets, change any setting of the running wallpaper, trigger events, control the schedule, and render stills, videos, time-lapses, GIFs and frame sequences. Install it with `DeepField.app/Contents/MacOS/DeepField install`, and see `deepfield help`. + ## [0.4.7] - 2026-11-17 - Five new dither patterns under Image: Bayer 2×2, Blue noise, Halftone dots, Diagonal lines and White noise. diff --git a/README.md b/README.md index 2a665ed..c9404d4 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,30 @@ Focus turns on and goes back to how it was when the Focus ends. The same choices the Shortcuts app (**Apply Deep Field Preset** and **Set Deep Field Scene**), for any automation you like. +### Command line + +Everything above also works from a terminal. Link the `deepfield` command onto your PATH once: + +```bash +/Applications/DeepField.app/Contents/MacOS/DeepField install +``` + +Then change the wallpaper, its settings and presets, and render stills, videos and time-lapses: + +```bash +deepfield scene galaxy galaxyType=barred --fade 4 --style warp # switch, with a transition +deepfield set bloom=0.6 dither=blueNoise palette.core=#ffd27a # tweak what's showing +deepfield keys # this scene's settings +deepfield preset apply "Late Night"; deepfield event supernova +deepfield render shot.png --size 5120x2880 +deepfield render video loop.mp4 --duration 8 --loop +deepfield render timelapse earth.mp4 --scene liveEarth --speed 3600 +``` + +Changes go to the running app and show at once; when it isn't running they're saved for its next +launch. `deepfield help` lists every command, and `deepfield completion zsh|bash|fish` prints +tab completion for your shell. + ### A galaxy with and without dark matter The same galaxy with and without a dark matter halo, sped up diff --git a/Sources/DeepField/App/AppDelegate.swift b/Sources/DeepField/App/AppDelegate.swift index 97fd5ae..b053d0c 100644 --- a/Sources/DeepField/App/AppDelegate.swift +++ b/Sources/DeepField/App/AppDelegate.swift @@ -30,6 +30,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate { buildStatusItem() NSApp.mainMenu = MainMenu.build(target: self) if !Settings.capturingUI { + CLIServer.start() LockScreenStill.shared.start() Scheduler.shared.start() LocationProvider.shared.refreshIfFollowing() @@ -108,7 +109,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate { } } - private func setWallpaper(_ on: Bool) { + func setWallpaper(_ on: Bool) { Settings.wallpaperEnabled = on buildWindows() } @@ -243,6 +244,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate { } @objc private func skipSchedule() { Scheduler.shared.skip() } @objc private func togglePause() { userPaused.toggle(); applyPause() } + + /// The menu bar's Pause Animation, for the command line. + var animationPaused: Bool { + get { userPaused } + set { userPaused = newValue; applyPause() } + } @objc func showCustomize() { CustomizeWindowController.shared.show() } @objc private func toggleLockScreen() { ConfigStore.shared.config.lockScreenStill.toggle() } diff --git a/Sources/DeepField/App/main.swift b/Sources/DeepField/App/main.swift index d6cc597..fe7a916 100644 --- a/Sources/DeepField/App/main.swift +++ b/Sources/DeepField/App/main.swift @@ -3,6 +3,7 @@ import AppKit _ = Settings.isFirstLaunch // decided before anything below can save settings DefaultsMigration.run() // settings saved under the old bundle identifier +CLI.runIfRequested() // `deepfield COMMAND`: runs the command and exits LockScreenStillTest.runIfRequested() // dev: --lockscreen-still-test PickerCheck.runIfRequested() // dev: --check-picker DevCommands.runIfRequested() // dev CLI (--snapshot, --benchmark, ...) exits before the app starts diff --git a/Sources/DeepField/CLI/CLI.swift b/Sources/DeepField/CLI/CLI.swift new file mode 100644 index 0000000..efbe26a --- /dev/null +++ b/Sources/DeepField/CLI/CLI.swift @@ -0,0 +1,417 @@ +import AppKit + +/// The `deepfield` command. It's the app's own executable: `deepfield install` links it onto +/// the PATH, and running it under that name (or with a command as the first argument) runs the +/// command and exits instead of starting the app. Commands that read or change the wallpaper go +/// to the running app over a local message port, so they show at once; when the app isn't +/// running they work on the saved settings instead. +enum CLI { + struct Command { + let name: String + let summary: String + let usage: String + /// Runs in the app when it's running (CLIService); otherwise right here. + let service: Bool + } + + static let commands: [Command] = [ + Command(name: "status", summary: "What's showing, and whether Deep Field is running", usage: """ + deepfield status [--json] + """, service: true), + Command(name: "scene", summary: "Show the current scene, or switch to one", usage: """ + deepfield scene [NAME|random] [KEY=VALUE...] [--preset NAME] [--fade SECONDS] [--style STYLE] + + Switches the wallpaper to a scene with the settings it had last, plus any changes given. + NAME is an id or title from `deepfield scenes` ("ringedPlanet", "ringed planet"). + deepfield scene galaxy galaxyType=barred darkMatter=false + deepfield scene random --fade 4 --style warp + """, service: true), + Command(name: "scenes", summary: "List the scenes (* marks the current one)", usage: """ + deepfield scenes [--names|--json] + """, service: true), + Command(name: "get", summary: "Print settings", usage: """ + deepfield get [KEY...] [--json] + + With no keys, prints every setting as JSON. One key prints just its value (colors as hex), + so it works in scripts: bloom=$(deepfield get bloom) + """, service: true), + Command(name: "set", summary: "Change settings of the current wallpaper", usage: """ + deepfield set KEY=VALUE... [--preset NAME] [--fade SECONDS] [--style STYLE] + + Keys are the saved settings' names; `deepfield keys` lists the current scene's and + `deepfield keys --all` every one. Numbers, true/false (or on/off), hex colors and choices: + deepfield set bloom=0.6 pixelSize=4 dither=blueNoise + deepfield set palette.core=#ffd27a diskSpeed=1.5 + """, service: true), + Command(name: "keys", summary: "List settings with their values and types", usage: """ + deepfield keys [--scene NAME] [--all] [--names] [--json] + + Without --all: the scene's own settings plus the image settings. + """, service: true), + Command(name: "reset", summary: "Put settings back to their defaults", usage: """ + deepfield reset [KEY...] [--scene NAME] [--all] [--fade SECONDS] + + No arguments resets the current scene's own settings (like Customize's Reset); KEYs reset + just those; --all resets everything but frame rate and lock screen settings. + """, service: true), + Command(name: "presets", summary: "List saved, scene color and palette presets", usage: """ + deepfield presets [--scene NAME] [--names|--json] + """, service: true), + Command(name: "preset", summary: "Apply, save, delete, rename, export or import presets", usage: """ + deepfield preset apply NAME|FILE.deepfield [KEY=VALUE...] [--fade SECONDS] [--style STYLE] + deepfield preset save NAME + deepfield preset delete NAME + deepfield preset rename OLD NEW + deepfield preset export [NAME] FILE.deepfield (the current settings without NAME) + deepfield preset import FILE.deepfield... + + apply also takes a palette preset ("Synthwave") or one of the scene's color presets. + """, service: true), + Command(name: "events", summary: "List events you can trigger", usage: """ + deepfield events [--all] [--names|--json] + """, service: true), + Command(name: "event", summary: "Trigger an event now", usage: """ + deepfield event NAME|ID + deepfield event supernova + """, service: true), + Command(name: "on", summary: "Show the scene on the desktop", usage: "deepfield on", service: true), + Command(name: "off", summary: "Hide it, leaving your own desktop picture", usage: "deepfield off", service: true), + Command(name: "toggle", summary: "Switch between on and off", usage: "deepfield toggle", service: true), + Command(name: "pause", summary: "Pause the animation", usage: "deepfield pause", service: true), + Command(name: "resume", summary: "Resume the animation", usage: "deepfield resume", service: true), + Command(name: "schedule", summary: "Schedule status, on, off, or skip to the next entry", usage: """ + deepfield schedule [status|on|off|next] [--json] + """, service: true), + Command(name: "login", summary: "Launch at login: status, on or off", usage: """ + deepfield login [status|on|off] + """, service: true), + Command(name: "customize", summary: "Open the Customize window", usage: """ + deepfield customize [--section scene|sky|image|system|phone|schedule] + """, service: true), + Command(name: "render", summary: "Render an image, video, time-lapse, GIF or frames", usage: RenderCommand.usage, service: false), + Command(name: "launch", summary: "Start Deep Field", usage: "deepfield launch [--customize]", service: false), + Command(name: "quit", summary: "Quit Deep Field", usage: "deepfield quit", service: true), + Command(name: "install", summary: "Link `deepfield` into a folder on your PATH", usage: """ + deepfield install [--dir FOLDER] [--force] + + Links /usr/local/bin/deepfield (or /opt/homebrew/bin, or ~/.local/bin, the first one you + can write to) to this copy of the app. Run it again if you move the app. + """, service: false), + Command(name: "completion", summary: "Print a shell completion script", usage: """ + deepfield completion zsh|bash|fish + + zsh: deepfield completion zsh > ~/.zfunc/_deepfield (with ~/.zfunc on fpath) + bash: deepfield completion bash > ~/.local/share/bash-completion/completions/deepfield + fish: deepfield completion fish > ~/.config/fish/completions/deepfield.fish + """, service: false), + Command(name: "version", summary: "Print the version", usage: "deepfield version", service: false), + Command(name: "help", summary: "Help for a command", usage: "deepfield help [COMMAND]", service: false), + ] + + static var version: String { + Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "dev" + } + + /// Runs a command and exits when the executable was started as `deepfield` or its first + /// argument is a command; otherwise returns, and the app (or a dev command) starts. + static func runIfRequested() { + let argv = CommandLine.arguments + let invokedAs = URL(fileURLWithPath: argv.first ?? "").lastPathComponent + let args = Array(argv.dropFirst()) + let named = invokedAs == "deepfield" + guard named || args.first.map({ a in commands.contains { $0.name == a } }) == true else { return } + // Started through the `deepfield` link, Foundation takes the link's folder for the bundle, + // so settings would go to the wrong defaults domain. Run the real path instead, keeping + // the name. + if Bundle.main.bundleIdentifier == nil, let exe = Bundle.main.executableURL, + case let real = exe.resolvingSymlinksInPath(), real != exe, + real.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().pathExtension == "app" { + var cargs = argv.map { strdup($0) } + [nil] + execv(real.path, &cargs) + } + exit(run(args)) + } + + static func run(_ args: [String]) -> Int32 { + guard let name = args.first, !["-h", "--help"].contains(name) else { + print(overview) + return 0 + } + if name == "--version" || name == "-v" { print(version); return 0 } + guard let command = commands.first(where: { $0.name == name }) else { + let near = commands.map(\.name).filter { $0.hasPrefix(String(name.prefix(2))) } + stderr("deepfield: unknown command \u{201C}\(name)\u{201D}" + (near.isEmpty ? "" : " (did you mean \(near.joined(separator: ", "))?)")) + stderr("Run `deepfield help` for the list.") + return 2 + } + if args.contains("--help") || args.contains("-h") { + print("\(command.summary).\n\n\(command.usage)") + return 0 + } + let cwd = FileManager.default.currentDirectoryPath + if command.service { + let out = CLIClient.send(args, cwd: cwd) ?? { + if name == "customize" { return launch(["--customize"]) } + let o = CLIService.run(args, cwd: cwd, inApp: false) + UserDefaults.standard.synchronize() + return o + }() + FileHandle.standardOutput.write(Data(out.out.utf8)) + FileHandle.standardError.write(Data(out.err.utf8)) + return out.code + } + do { + switch name { + case "render": return try RenderCommand.run(Array(args.dropFirst()), cwd: cwd) + case "launch": return emit(launch(Array(args.dropFirst()))) + case "install": return try install(Array(args.dropFirst())) + case "completion": return try completion(Array(args.dropFirst())) + case "version": print(version); return 0 + case "help": + if let topic = args.dropFirst().first { + guard let c = commands.first(where: { $0.name == topic }) else { throw CLIError("no command \(topic)") } + print("\(c.summary).\n\n\(c.usage)") + } else if args.contains("--commands") { + commands.forEach { print("\($0.name):\($0.summary)") } + } else { + print(overview) + } + return 0 + default: return 2 + } + } catch let e as CLIError { + stderr("deepfield: \(e.message)") + return 1 + } catch { + stderr("deepfield: \(error.localizedDescription)") + return 1 + } + } + + static var overview: String { + let w = commands.map(\.name.count).max() ?? 0 + let list = commands.map { " \($0.name.padding(toLength: w + 2, withPad: " ", startingAt: 0))\($0.summary)" } + return """ + Deep Field \(version): animated space wallpapers from the command line. + + Usage: deepfield COMMAND [ARGS] + + \(list.joined(separator: "\n")) + + `deepfield help COMMAND` (or COMMAND --help) explains one. Changes go to the running app and + show at once; when it isn't running they're saved for its next launch. + """ + } + + static func stderr(_ s: String) { FileHandle.standardError.write(Data((s + "\n").utf8)) } + + private static func emit(_ o: CLIOutput) -> Int32 { + FileHandle.standardOutput.write(Data(o.out.utf8)) + FileHandle.standardError.write(Data(o.err.utf8)) + return o.code + } + + // MARK: launch + + /// The app bundle this executable is in, or the installed one. + static var appURL: URL? { + let exe = Bundle.main.executableURL?.resolvingSymlinksInPath() + let bundle = exe?.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + if let bundle, bundle.pathExtension == "app" { return bundle } + return NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.narrowstacks.DeepField") + } + + private static func launch(_ args: [String]) -> CLIOutput { + let o = CLIOutput() + if CLIClient.isRunning { + if args.contains("--customize") { return CLIClient.send(["customize"], cwd: "/") ?? o } + o.print("Deep Field is already running") + return o + } + guard let url = appURL else { o.fail("can't find Deep Field.app"); return o } + let config = NSWorkspace.OpenConfiguration() + config.arguments = args.contains("--customize") ? ["--customize"] : [] + config.activates = args.contains("--customize") + let done = DispatchSemaphore(value: 0) + var failure: Error? + NSWorkspace.shared.openApplication(at: url, configuration: config) { _, error in + failure = error + done.signal() + } + done.wait() + if let failure { o.fail("couldn't start Deep Field: \(failure.localizedDescription)"); return o } + // wait for its port, so a command right after this one reaches it + let deadline = Date().addingTimeInterval(20) + while !CLIClient.isRunning && Date() < deadline { Thread.sleep(forTimeInterval: 0.1) } + if !CLIClient.isRunning { o.warn("Deep Field started but isn't answering yet") } + return o + } + + // MARK: install + + private static func install(_ args: [String]) throws -> Int32 { + let a = try ParsedArgs(args, values: ["--dir"], flags: ["--force"]) + guard let exe = Bundle.main.executableURL?.resolvingSymlinksInPath(), + exe.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().pathExtension == "app" else { + throw CLIError("run install from the app: \"/Applications/Deep Field.app/Contents/MacOS/DeepField\" install") + } + let fm = FileManager.default + let home = fm.homeDirectoryForCurrentUser.path + let dir: String + if let d = a.value("--dir") { + dir = (d as NSString).expandingTildeInPath + } else { + let candidates = ["/usr/local/bin", "/opt/homebrew/bin", "\(home)/.local/bin"] + dir = candidates.first { fm.isWritableFile(atPath: $0) } ?? "\(home)/.local/bin" + } + try fm.createDirectory(atPath: dir, withIntermediateDirectories: true) + let link = (dir as NSString).appendingPathComponent("deepfield") + if let existing = try? fm.destinationOfSymbolicLink(atPath: link) { + if URL(fileURLWithPath: existing).resolvingSymlinksInPath() != exe && !a.has("--force") { + print("Replacing the link to \(existing)") + } + try fm.removeItem(atPath: link) + } else if fm.fileExists(atPath: link) { + guard a.has("--force") else { throw CLIError("\(link) exists and isn't a link; pass --force to replace it") } + try fm.removeItem(atPath: link) + } + try fm.createSymbolicLink(atPath: link, withDestinationPath: exe.path) + print("Linked \(link) -> \(exe.path)") + let path = (ProcessInfo.processInfo.environment["PATH"] ?? "").split(separator: ":").map(String.init) + if !path.contains(dir) { + print("\(dir) isn't on your PATH; add it in your shell profile:\n export PATH=\"\(dir):$PATH\"") + } + print("Shell completion: `deepfield completion --help`") + return 0 + } + + // MARK: completion + + private static func completion(_ args: [String]) throws -> Int32 { + guard let shell = args.first else { throw CLIError("usage: deepfield completion zsh|bash|fish") } + switch shell { + case "zsh": print(Completions.zsh) + case "bash": print(Completions.bash) + case "fish": print(Completions.fish) + default: throw CLIError("no completion for \(shell) (zsh, bash, fish)") + } + return 0 + } +} + +/// Options for one command: `--name value` (or `--name=value`) for those in `values`, bare +/// flags for those in `flags`, and everything else positional. +struct ParsedArgs { + var positional: [String] = [] + var options: [String: String] = [:] + var flags: Set = [] + + init(_ args: [String], values: Set = [], flags allowed: Set = []) throws { + var i = 0 + while i < args.count { + let a = args[i] + if a == "--" { + positional += args[(i + 1)...] + break + } + if a.hasPrefix("--") { + var name = a + var inline: String? + if let eq = a.firstIndex(of: "=") { + name = String(a[.. Bool { flags.contains(flag) } + func value(_ option: String) -> String? { options[option] } + + func double(_ option: String) throws -> Double? { + guard let s = options[option] else { return nil } + guard let x = Double(s), x.isFinite else { throw CLIError("\(option) takes a number, got \u{201C}\(s)\u{201D}") } + return x + } + + func int(_ option: String) throws -> Int? { + guard let s = options[option] else { return nil } + guard let x = Int(s) else { throw CLIError("\(option) takes a whole number, got \u{201C}\(s)\u{201D}") } + return x + } +} + +// MARK: message port + +private let portName = "com.narrowstacks.DeepField.cli" as CFString + +private struct CLIRequest: Codable { + let args: [String] + let cwd: String +} + +/// The app's end: answers commands from `deepfield` on the main thread. +enum CLIServer { + private static var port: CFMessagePort? + + static func start() { + guard port == nil else { return } + let callback: CFMessagePortCallBack = { _, _, data, _ in + let reply: CLIOutput + if let data = data as Data?, let req = try? JSONDecoder().decode(CLIRequest.self, from: data) { + reply = CLIService.run(req.args, cwd: req.cwd, inApp: true) + } else { + reply = CLIOutput() + reply.fail("bad request") + } + let out = (try? JSONEncoder().encode(reply)) ?? Data() + return Unmanaged.passRetained(out as CFData) + } + var shouldFree: DarwinBoolean = false + guard let p = CFMessagePortCreateLocal(nil, portName, callback, nil, &shouldFree) else { + NSLog("DeepField: command line port is taken (another copy running?)") + return + } + port = p + CFRunLoopAddSource(CFRunLoopGetMain(), CFMessagePortCreateRunLoopSource(nil, p, 0), .commonModes) + } +} + +/// The command's end. +enum CLIClient { + static var isRunning: Bool { CFMessagePortCreateRemote(nil, portName) != nil } + + /// The app's reply, or nil when it isn't running. + static func send(_ args: [String], cwd: String) -> CLIOutput? { + guard let remote = CFMessagePortCreateRemote(nil, portName), + let body = try? JSONEncoder().encode(CLIRequest(args: args, cwd: cwd)) else { return nil } + var reply: Unmanaged? + let status = CFMessagePortSendRequest(remote, 0, body as CFData, 5, 60, CFRunLoopMode.defaultMode.rawValue, &reply) + guard status == kCFMessagePortSuccess, let data = reply?.takeRetainedValue() as Data?, + let out = try? JSONDecoder().decode(CLIOutput.self, from: data) else { + let o = CLIOutput() + o.fail("Deep Field didn't answer (status \(status))") + return o + } + return out + } +} diff --git a/Sources/DeepField/CLI/CLIService.swift b/Sources/DeepField/CLI/CLIService.swift new file mode 100644 index 0000000..b25b84f --- /dev/null +++ b/Sources/DeepField/CLI/CLIService.swift @@ -0,0 +1,450 @@ +import AppKit +import ServiceManagement + +/// What a command prints and its exit status. Built the same way whether the command runs in +/// the app (sent over `CLIServer`'s port) or in the `deepfield` process (the app isn't running). +final class CLIOutput: Codable { + var out = "" + var err = "" + var code: Int32 = 0 + + func print(_ s: String) { out += s + "\n" } + func warn(_ s: String) { err += s + "\n" } + func fail(_ s: String, code: Int32 = 1) { + err += "deepfield: \(s)\n" + self.code = code + } +} + +/// The commands that read or change the wallpaper's state. `inApp` is true inside the running +/// app, where changes show at once (and can transition); otherwise they're saved for its next +/// launch, and commands that need the live wallpaper fail. +struct CLIService { + let cwd: String + let inApp: Bool + let o = CLIOutput() + + static func run(_ argv: [String], cwd: String, inApp: Bool) -> CLIOutput { + let s = CLIService(cwd: cwd, inApp: inApp) + do { + try s.dispatch(argv) + } catch let e as CLIError { + s.o.fail(e.message) + } catch { + s.o.fail(error.localizedDescription) + } + return s.o + } + + private var store: ConfigStore { .shared } + private var delegate: AppDelegate? { inApp ? NSApp.delegate as? AppDelegate : nil } + + private func dispatch(_ argv: [String]) throws { + guard let name = argv.first else { return } + let rest = Array(argv.dropFirst()) + switch name { + case "status": try status(rest) + case "get": try get(rest) + case "set": try set(rest) + case "scene": try scene(rest) + case "reset": try reset(rest) + case "keys": try keys(rest) + case "scenes": try scenes(rest) + case "presets": try presets(rest) + case "preset": try preset(rest) + case "events": try events(rest) + case "event": try event(rest) + case "on": try wallpaper(rest, on: true) + case "off": try wallpaper(rest, on: false) + case "toggle": try wallpaper(rest, on: !Settings.wallpaperEnabled) + case "pause": try pause(rest, true) + case "resume": try pause(rest, false) + case "schedule": try schedule(rest) + case "login": try login(rest) + case "customize": try customize(rest) + case "quit": try quit(rest) + default: throw CLIError("unknown command \(name)") + } + } + + private func requireApp(_ what: String) throws { + guard inApp else { throw CLIError("Deep Field isn't running, so there's nothing to \(what). Start it with `deepfield launch`.") } + } + + private func savedNote() { + if !inApp { o.warn("Deep Field isn't running; saved for its next launch.") } + } + + // MARK: applying changes + + private static let changeValues: Set = ["--fade", "--style", "--preset"] + + /// Shows `new`: transitions over `--fade` seconds in the running app, or cuts. + private func commit(_ new: WallpaperConfig, _ a: ParsedArgs) throws { + let fade = try a.double("--fade") ?? 0 + var style = TransitionStyle.dissolve + if let s = a.value("--style") { + guard let t = TransitionStyle.allCases.first(where: { $0.rawValue.caseInsensitiveCompare(s) == .orderedSame }) else { + throw CLIError("no transition style \u{201C}\(s)\u{201D} (choose from \(TransitionStyle.allCases.map(\.rawValue).joined(separator: ", ")))") + } + style = t + } + if inApp && fade > 0 { + store.transition(to: new, seconds: fade, style: style) + } else { + store.config = new + if !inApp { store.flush() } + } + savedNote() + } + + private func applyChanges(_ assignments: [String], preset: String?, to base: WallpaperConfig) throws -> WallpaperConfig { + var c = base + if let preset { try PresetLookup.apply(preset, to: &c, cwd: cwd) } + let (new, warnings) = try ConfigKeys.apply(try ConfigKeys.assignments(assignments), to: c) + warnings.forEach { o.warn("note: \($0)") } + return new + } + + // MARK: status + + private func status(_ args: [String]) throws { + let a = try ParsedArgs(args, flags: ["--json"]) + let c = store.config + let schedule = ScheduleStore.shared.schedule + let next = schedule.enabled ? schedule.slot(at: Date())?.next : nil + var info: [String: Any] = [ + "running": inApp, + "version": CLI.version, + "scene": c.scene.rawValue, + "sceneTitle": c.scene.title, + "wallpaper": Settings.wallpaperEnabled, + "schedule": schedule.enabled, + "focusFilter": UserDefaults.standard.data(forKey: "focusRestoreConfig") != nil, + "lockScreenStill": c.lockScreenStill, + ] + if let p = PresetStore.shared.current { info["preset"] = p.name } + if let d = delegate { info["paused"] = d.animationPaused } + if let next { info["nextScheduledChange"] = ISO8601DateFormatter().string(from: next) } + if a.has("--json") { o.print(ConfigKeys.json(info, pretty: true)); return } + o.print("Deep Field \(CLI.version), \(inApp ? "running" : "not running")") + o.print("Scene: \(c.scene.title) (\(c.scene.rawValue))") + if let p = info["preset"] as? String { o.print("Preset: \(p)") } + var desktop = Settings.wallpaperEnabled ? "shown" : "hidden" + if delegate?.animationPaused == true { desktop += ", paused" } + o.print("Desktop: \(desktop)") + var sched = schedule.enabled ? "on (\(schedule.mode == .rotate ? "rotating" : "timed"), \(schedule.entries.count) entries)" : "off" + if let next { sched += ", next change \(DateFormatter.localizedString(from: next, dateStyle: .none, timeStyle: .short))" } + o.print("Schedule: \(sched)") + if info["focusFilter"] as? Bool == true { o.print("Focus: a Focus filter is choosing the wallpaper") } + o.print("Lock screen still: \(c.lockScreenStill ? "on" : "off")") + } + + // MARK: settings + + private func get(_ args: [String]) throws { + let a = try ParsedArgs(args, flags: ["--json", "--raw"]) + let dict = ConfigKeys.object(store.config) + if a.has("--raw") { + // everything, per-scene image settings included (for `render`) + o.print(ConfigKeys.json(dict, pretty: false)) + return + } + if a.positional.isEmpty { + var shown = dict + ConfigKeys.internalKeys.forEach { shown[$0] = nil } + o.print(ConfigKeys.json(shown, pretty: true)) + return + } + let paths = ConfigKeys.allPaths(store.config) + var values: [String: Any] = [:] + for key in a.positional { + guard let v = ConfigKeys.value(at: key.split(separator: ".").map(String.init), in: dict) else { + let near = ConfigKeys.suggestions(for: key, in: paths) + throw CLIError("unknown setting \u{201C}\(key)\u{201D}" + (near.isEmpty ? "" : " (did you mean \(near.joined(separator: ", "))?)")) + } + values[key] = v + } + if a.has("--json") { + o.print(ConfigKeys.json(a.positional.count == 1 ? values[a.positional[0]]! : values, pretty: true)) + } else if a.positional.count == 1 { + o.print(ConfigKeys.display(values[a.positional[0]]!)) + } else { + for key in a.positional { o.print("\(key) = \(ConfigKeys.display(values[key]!))") } + } + } + + private func set(_ args: [String]) throws { + let a = try ParsedArgs(args, values: Self.changeValues) + guard !a.positional.isEmpty || a.value("--preset") != nil else { throw CLIError("usage: deepfield set KEY=VALUE...") } + let new = try applyChanges(a.positional, preset: a.value("--preset"), to: store.config) + try commit(new, a) + } + + private func scene(_ args: [String]) throws { + let a = try ParsedArgs(args, values: Self.changeValues) + guard let name = a.positional.first else { + o.print(store.config.scene.rawValue) + return + } + var c = store.config + c.scene = try SceneKind.named(name, current: c.scene) + let new = try applyChanges(Array(a.positional.dropFirst()), preset: a.value("--preset"), to: c) + try commit(new, a) + o.print(new.scene.title) + } + + private func reset(_ args: [String]) throws { + let a = try ParsedArgs(args, values: ["--fade", "--style", "--scene"], flags: ["--all"]) + let c = store.config + var new: WallpaperConfig + if a.has("--all") { + new = UserPreset(name: "", config: WallpaperConfig()).applied(over: c) + } else if !a.positional.isEmpty { + let defaults = ConfigKeys.object(WallpaperConfig()) + let list = try a.positional.map { key -> ConfigKeys.Assignment in + guard let v = ConfigKeys.value(at: key.split(separator: ".").map(String.init), in: defaults) else { + throw CLIError("unknown setting \u{201C}\(key)\u{201D}") + } + return ConfigKeys.Assignment(key: key, raw: ConfigKeys.isColor(v) ? ConfigKeys.display(v) : ConfigKeys.json(v, pretty: false)) + } + new = try ConfigKeys.apply(list, to: c).config + } else { + let kind = try a.value("--scene").map { try SceneKind.named($0) } ?? c.scene + new = c.resettingScene(kind) + } + try commit(new, a) + } + + private func keys(_ args: [String]) throws { + let a = try ParsedArgs(args, values: ["--scene"], flags: ["--all", "--names", "--json"]) + let c = store.config + let dict = ConfigKeys.object(c) + let list: [String] + if a.has("--all") { + list = ConfigKeys.allPaths(c) + } else { + let kind = try a.value("--scene").map { try SceneKind.named($0, listedOnly: false) } ?? c.scene + list = WallpaperConfig.sceneKeys(kind) + ConfigKeys.imageKeys + } + if a.has("--names") { list.forEach { o.print($0) }; return } + let rows = list.compactMap { key -> (String, String, String)? in + guard let v = ConfigKeys.value(at: key.split(separator: ".").map(String.init), in: dict) else { return nil } + let kind: String + if let choices = ConfigKeys.choices(for: key) { kind = choices.joined(separator: "|") } + else if ConfigKeys.isColor(v) { kind = "color" } + else if ConfigKeys.isBool(v) { kind = "bool" } + else if v is NSNumber { kind = "number" } + else if v is String { kind = "text" } + else { kind = "json" } + return (key, ConfigKeys.display(v), kind) + } + if a.has("--json") { + o.print(ConfigKeys.json(rows.map { ["key": $0.0, "value": $0.1, "type": $0.2] }, pretty: true)) + return + } + let w0 = rows.map(\.0.count).max() ?? 0, w1 = min(rows.map(\.1.count).max() ?? 0, 28) + for (k, v, t) in rows { + o.print(k.padding(toLength: w0 + 2, withPad: " ", startingAt: 0) + + v.padding(toLength: max(w1, v.count) + 2, withPad: " ", startingAt: 0) + t) + } + } + + // MARK: lists + + private func scenes(_ args: [String]) throws { + let a = try ParsedArgs(args, flags: ["--names", "--json"]) + let current = store.config.scene + if a.has("--names") { SceneKind.listed.forEach { o.print($0.rawValue) }; return } + if a.has("--json") { + o.print(ConfigKeys.json(SceneKind.listed.map { ["id": $0.rawValue, "title": $0.title, "current": $0 == current] }, pretty: true)) + return + } + let w = SceneKind.listed.map(\.rawValue.count).max() ?? 0 + for k in SceneKind.listed { + o.print("\(k == current ? "*" : " ") \(k.rawValue.padding(toLength: w + 2, withPad: " ", startingAt: 0))\(k.title)") + } + } + + private func presets(_ args: [String]) throws { + let a = try ParsedArgs(args, values: ["--scene"], flags: ["--names", "--json"]) + let kind = try a.value("--scene").map { try SceneKind.named($0) } ?? store.config.scene + let user = PresetStore.shared.presets.map(\.name) + let palettes = PaletteConfig.presets.map(\.0) + let colors = ColorPreset.all(for: kind).map(\.name) + if a.has("--names") { (user + colors + palettes).forEach { o.print($0) }; return } + if a.has("--json") { + o.print(ConfigKeys.json(["saved": user, "scene": colors, "palette": palettes, "current": PresetStore.shared.current?.name ?? NSNull()], pretty: true)) + return + } + let current = PresetStore.shared.current?.name + o.print("Saved presets:") + if user.isEmpty { o.print(" (none yet: `deepfield preset save NAME`)") } + user.forEach { o.print("\($0 == current ? "* " : " ")\($0)") } + if !colors.isEmpty { + o.print("\(kind.title) colors:") + colors.forEach { o.print(" \($0)") } + } + o.print("Palettes (disk, wormhole and star colors):") + palettes.forEach { o.print(" \($0)") } + } + + private func preset(_ args: [String]) throws { + guard let sub = args.first else { throw CLIError("usage: deepfield preset apply|save|delete|rename|export|import ...") } + let a = try ParsedArgs(Array(args.dropFirst()), values: ["--fade", "--style", "--name"], flags: []) + let p = a.positional + let presetStore = PresetStore.shared + func find(_ name: String) throws -> UserPreset { + guard let x = presetStore.presets.first(where: { $0.name.caseInsensitiveCompare(name) == .orderedSame }) else { + throw CLIError("no saved preset called \u{201C}\(name)\u{201D}") + } + return x + } + switch sub { + case "apply": + guard let name = p.first else { throw CLIError("usage: deepfield preset apply NAME|FILE [KEY=VALUE...]") } + try commit(try applyChanges(Array(p.dropFirst()), preset: name, to: store.config), a) + case "save": + guard let name = p.first else { throw CLIError("usage: deepfield preset save NAME") } + let saved = presetStore.saveCurrent(as: name) + o.print("Saved \u{201C}\(saved.name)\u{201D}") + case "delete": + guard let name = p.first else { throw CLIError("usage: deepfield preset delete NAME") } + presetStore.delete(try find(name)) + case "rename": + guard p.count == 2 else { throw CLIError("usage: deepfield preset rename OLD NEW") } + presetStore.rename(try find(p[0]), to: p[1]) + case "export": + // export [NAME] FILE: a saved preset, or the current settings + guard let path = p.last else { throw CLIError("usage: deepfield preset export [NAME] FILE.deepfield") } + let preset = p.count >= 2 ? try find(p[0]) + : UserPreset(name: a.value("--name") ?? presetStore.current?.name ?? store.config.scene.title, config: store.config) + var url = URL(fileURLWithPath: PresetLookup.resolve(path, cwd: cwd)) + if url.pathExtension.isEmpty { url.appendPathExtension(PresetStore.fileExtension) } + guard let data = PresetStore.fileData(for: preset) else { throw CLIError("couldn't encode the preset") } + try data.write(to: url, options: .atomic) + o.print(url.path) + case "import": + guard !p.isEmpty else { throw CLIError("usage: deepfield preset import FILE...") } + for path in p { + let added = try presetStore.importFile(URL(fileURLWithPath: PresetLookup.resolve(path, cwd: cwd))) + o.print("Imported \u{201C}\(added.name)\u{201D}") + } + default: + throw CLIError("unknown preset command \(sub) (apply, save, delete, rename, export, import)") + } + } + + // MARK: events + + private func events(_ args: [String]) throws { + let a = try ParsedArgs(args, flags: ["--names", "--json", "--all"]) + let current = store.config.scene + let list = EventSchedule.named.filter { a.has("--all") || a.has("--names") || $0.scene == nil || $0.scene == current } + if a.has("--names") { list.forEach { o.print($0.name) }; return } + if a.has("--json") { + o.print(ConfigKeys.json(list.map { ["name": $0.name, "id": Int($0.kind.id), "scene": $0.scene?.rawValue ?? "sky"] }, pretty: true)) + return + } + let w = list.map(\.name.count).max() ?? 0 + for e in list { + o.print("\(e.name.padding(toLength: w + 2, withPad: " ", startingAt: 0))\(String(e.kind.id).padding(toLength: 4, withPad: " ", startingAt: 0))\(e.scene?.title ?? "sky (every scene)")") + } + if !a.has("--all") { o.print("(this scene's and the sky's; --all lists every scene's)") } + } + + private func event(_ args: [String]) throws { + let a = try ParsedArgs(args) + guard let name = a.positional.first else { throw CLIError("usage: deepfield event NAME|ID (`deepfield events` lists them)") } + func norm(_ s: String) -> String { s.lowercased().filter { $0.isLetter || $0.isNumber } } + guard let e = EventSchedule.named.first(where: { norm($0.name) == norm(name) || String($0.kind.id) == name }) else { + throw CLIError("no event called \u{201C}\(name)\u{201D}; `deepfield events --all` lists them") + } + try requireApp("show") + if let s = e.scene, s != store.config.scene { + o.warn("note: \(e.name) happens in \(s.title); switch with `deepfield scene \(s.rawValue)` to see it") + } + store.demo(e.kind) + } + + // MARK: app state + + private func wallpaper(_ args: [String], on: Bool) throws { + _ = try ParsedArgs(args) + if let d = delegate { d.setWallpaper(on) } else { Settings.wallpaperEnabled = on; savedNote() } + o.print(on ? "Shown on the desktop" : "Hidden from the desktop") + } + + private func pause(_ args: [String], _ paused: Bool) throws { + _ = try ParsedArgs(args) + try requireApp(paused ? "pause" : "resume") + delegate?.animationPaused = paused + } + + private func schedule(_ args: [String]) throws { + let a = try ParsedArgs(args, flags: ["--json"]) + let st = ScheduleStore.shared + switch a.positional.first ?? "status" { + case "on", "off": + guard !st.schedule.entries.isEmpty else { throw CLIError("nothing is scheduled yet; set it up in Customize > Schedule") } + st.schedule.enabled = a.positional[0] == "on" + savedNote() + case "next", "skip": + guard st.schedule.enabled, st.schedule.mode == .rotate, st.schedule.entries.count > 1 else { + throw CLIError("skipping ahead needs a rotating schedule with more than one entry, turned on") + } + Scheduler.shared.skip() + savedNote() + case "status": + let s = st.schedule + let next = s.enabled ? s.slot(at: Date())?.next : nil + if a.has("--json") { + var info: [String: Any] = ["enabled": s.enabled, "mode": s.mode == .rotate ? "rotate" : "timed", + "entries": s.entries.count, "fadeSeconds": s.fadeSeconds, "transition": s.transition.rawValue] + if let next { info["next"] = ISO8601DateFormatter().string(from: next) } + o.print(ConfigKeys.json(info, pretty: true)) + return + } + o.print("Schedule \(s.enabled ? "on" : "off"): \(s.mode == .rotate ? "rotating" : "timed"), \(s.entries.count) entries, \(s.transition.title.lowercased()) over \(ConfigKeys.number(s.fadeSeconds)) s") + if let next { o.print("Next change at \(DateFormatter.localizedString(from: next, dateStyle: .short, timeStyle: .short))") } + default: + throw CLIError("usage: deepfield schedule [status|on|off|next]") + } + } + + private func login(_ args: [String]) throws { + let a = try ParsedArgs(args) + let service = SMAppService.mainApp + switch a.positional.first ?? "status" { + case "on": try service.register() + case "off": try service.unregister() + case "status": break + default: throw CLIError("usage: deepfield login [status|on|off]") + } + switch service.status { + case .enabled: o.print("Launches at login") + case .requiresApproval: o.print("Waiting for approval in System Settings > General > Login Items") + default: o.print("Doesn't launch at login") + } + } + + private func customize(_ args: [String]) throws { + let a = try ParsedArgs(args, values: ["--section"]) + try requireApp("open") + if let name = a.value("--section") { + guard let section = CustomizeSection.allCases.first(where: { "\($0)".caseInsensitiveCompare(name) == .orderedSame }) else { + throw CLIError("no section \u{201C}\(name)\u{201D} (choose from \(CustomizeSection.allCases.map { "\($0)" }.joined(separator: ", ")))") + } + CustomizeWindowController.shared.show(section: section) + } else { + CustomizeWindowController.shared.show() + } + } + + private func quit(_ args: [String]) throws { + _ = try ParsedArgs(args) + guard inApp else { o.print("Deep Field isn't running"); return } + // after the reply is on its way + DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { NSApp.terminate(nil) } + } +} diff --git a/Sources/DeepField/CLI/Completions.swift b/Sources/DeepField/CLI/Completions.swift new file mode 100644 index 0000000..95987c2 --- /dev/null +++ b/Sources/DeepField/CLI/Completions.swift @@ -0,0 +1,117 @@ +/// Shell completion scripts for `deepfield completion`. They ask `deepfield` itself for the +/// commands, scenes, keys, presets and events, so they stay current as those change. +enum Completions { + static let zsh = #""" + #compdef deepfield + + _deepfield() { + local -a cmds + if (( CURRENT == 2 )); then + cmds=(${(f)"$(deepfield help --commands 2>/dev/null)"}) + _describe 'command' cmds + return + fi + local cmd=$words[2] + case $cmd in + scene) + if (( CURRENT == 3 )); then + compadd -- random ${(f)"$(deepfield scenes --names 2>/dev/null)"} + else + compadd -S '=' -- ${(f)"$(deepfield keys --all --names 2>/dev/null)"} + fi ;; + set) + compadd -S '=' -- ${(f)"$(deepfield keys --all --names 2>/dev/null)"} ;; + get|reset) + compadd -- ${(f)"$(deepfield keys --all --names 2>/dev/null)"} ;; + keys|presets) + [[ $words[CURRENT-1] == --scene ]] && compadd -- ${(f)"$(deepfield scenes --names 2>/dev/null)"} ;; + preset) + if (( CURRENT == 3 )); then + compadd -- apply save delete rename export import + elif [[ $words[3] == (import|export) ]]; then + _files + else + compadd -- ${(f)"$(deepfield presets --names 2>/dev/null)"} + _files -g '*.deepfield' + fi ;; + event) + compadd -- ${(f)"$(deepfield events --all --names 2>/dev/null)"} ;; + schedule) compadd -- status on off next ;; + login) compadd -- status on off ;; + completion) compadd -- zsh bash fish ;; + help) compadd -- ${${(f)"$(deepfield help --commands 2>/dev/null)"}%%:*} ;; + customize) compadd -- --section scene sky image system phone schedule ;; + render) + case $words[CURRENT-1] in + --scene) compadd -- ${(f)"$(deepfield scenes --names 2>/dev/null)"} ;; + --preset) compadd -- ${(f)"$(deepfield presets --names 2>/dev/null)"}; _files -g '*.deepfield' ;; + --codec) compadd -- h264 hevc prores ;; + *) + if [[ $PREFIX == -* ]]; then + compadd -- --scene --preset --defaults --config --smooth --no-events --demo --size --scale \ + --time --duration --fps --speed --loop --codec --bitrate --open --quiet + else + compadd -- image video timelapse + _files + fi ;; + esac ;; + esac + } + + compdef _deepfield deepfield + """# + + static let bash = #""" + _deepfield() { + local cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} + if (( COMP_CWORD == 1 )); then + COMPREPLY=($(compgen -W "$(deepfield help --commands 2>/dev/null | cut -d: -f1)" -- "$cur")) + return + fi + case $prev in + --scene) COMPREPLY=($(compgen -W "$(deepfield scenes --names 2>/dev/null)" -- "$cur")); return ;; + --codec) COMPREPLY=($(compgen -W "h264 hevc prores" -- "$cur")); return ;; + esac + case ${COMP_WORDS[1]} in + scene) + if (( COMP_CWORD == 2 )); then + COMPREPLY=($(compgen -W "random $(deepfield scenes --names 2>/dev/null)" -- "$cur")) + else + compopt -o nospace; COMPREPLY=($(compgen -S = -W "$(deepfield keys --all --names 2>/dev/null)" -- "$cur")) + fi ;; + set) compopt -o nospace; COMPREPLY=($(compgen -S = -W "$(deepfield keys --all --names 2>/dev/null)" -- "$cur")) ;; + get|reset) COMPREPLY=($(compgen -W "$(deepfield keys --all --names 2>/dev/null)" -- "$cur")) ;; + preset) + if (( COMP_CWORD == 2 )); then COMPREPLY=($(compgen -W "apply save delete rename export import" -- "$cur")) + else COMPREPLY=($(compgen -f -- "$cur")); fi ;; + event) COMPREPLY=($(compgen -W "$(deepfield events --all --names 2>/dev/null)" -- "$cur")) ;; + schedule) COMPREPLY=($(compgen -W "status on off next" -- "$cur")) ;; + login) COMPREPLY=($(compgen -W "status on off" -- "$cur")) ;; + completion) COMPREPLY=($(compgen -W "zsh bash fish" -- "$cur")) ;; + render) + if [[ $cur == -* ]]; then + COMPREPLY=($(compgen -W "--scene --preset --defaults --config --smooth --no-events --demo --size --scale --time --duration --fps --speed --loop --codec --bitrate --open --quiet" -- "$cur")) + else + COMPREPLY=($(compgen -W "image video timelapse" -- "$cur") $(compgen -f -- "$cur")) + fi ;; + esac + } + complete -F _deepfield deepfield + """# + + static let fish = #""" + function __deepfield_cmds; deepfield help --commands 2>/dev/null | string replace ':' \t; end + complete -c deepfield -f + complete -c deepfield -n __fish_use_subcommand -a '(__deepfield_cmds)' + complete -c deepfield -n '__fish_seen_subcommand_from scene' -a 'random (deepfield scenes --names 2>/dev/null)' + complete -c deepfield -n '__fish_seen_subcommand_from get reset' -a '(deepfield keys --all --names 2>/dev/null)' + complete -c deepfield -n '__fish_seen_subcommand_from set' -a '(deepfield keys --all --names 2>/dev/null | string replace -r \'$\' =)' + complete -c deepfield -n '__fish_seen_subcommand_from preset' -a 'apply save delete rename export import (deepfield presets --names 2>/dev/null)' + complete -c deepfield -n '__fish_seen_subcommand_from event' -a '(deepfield events --all --names 2>/dev/null)' + complete -c deepfield -n '__fish_seen_subcommand_from schedule' -a 'status on off next' + complete -c deepfield -n '__fish_seen_subcommand_from login' -a 'status on off' + complete -c deepfield -n '__fish_seen_subcommand_from completion' -a 'zsh bash fish' + complete -c deepfield -n '__fish_seen_subcommand_from render' -F -a 'image video timelapse' + complete -c deepfield -n '__fish_seen_subcommand_from render keys presets' -l scene -x -a '(deepfield scenes --names 2>/dev/null)' + """# +} diff --git a/Sources/DeepField/CLI/ConfigKeys.swift b/Sources/DeepField/CLI/ConfigKeys.swift new file mode 100644 index 0000000..a01e83a --- /dev/null +++ b/Sources/DeepField/CLI/ConfigKeys.swift @@ -0,0 +1,295 @@ +import Foundation + +struct CLIError: Error { + let message: String + init(_ message: String) { self.message = message } +} + +/// Settings by key for the command line. Keys are the saved format's (WallpaperConfig's Codable +/// keys), and nested values take a dotted path (`palette.core`). Colors read and write as hex. +enum ConfigKeys { + static func object(_ c: WallpaperConfig) -> [String: Any] { + guard let data = try? JSONEncoder().encode(c), + let dict = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return [:] } + return dict + } + + static func value(at path: [String], in dict: [String: Any]) -> Any? { + var current: Any? = dict + for p in path { current = (current as? [String: Any])?[p] } + return current + } + + static func setting(_ value: Any, at path: [String], in dict: [String: Any]) -> [String: Any] { + var d = dict + guard let first = path.first else { return d } + d[first] = path.count == 1 ? value : setting(value, at: Array(path.dropFirst()), in: d[first] as? [String: Any] ?? [:]) + return d + } + + // MARK: value types + + static func isBool(_ v: Any?) -> Bool { + guard let n = v as? NSNumber else { return false } + return CFGetTypeID(n) == CFBooleanGetTypeID() + } + + static func isColor(_ v: Any?) -> Bool { + guard let d = v as? [String: Any], d.count == 3 else { return false } + return ["r", "g", "b"].allSatisfy { d[$0] is NSNumber } + } + + static func hex(_ d: [String: Any]) -> String { + func byte(_ k: String) -> Int { Int((((d[k] as? NSNumber)?.doubleValue ?? 0) * 255).rounded()).clamped(0, 255) } + return String(format: "#%02x%02x%02x", byte("r"), byte("g"), byte("b")) + } + + /// `#rgb`, `#rrggbb` or the same without `#`. + static func color(fromHex s: String) -> [String: Any]? { + var h = s.hasPrefix("#") ? String(s.dropFirst()) : s + if h.count == 3 { h = h.map { "\($0)\($0)" }.joined() } + guard h.count == 6, let v = UInt32(h, radix: 16) else { return nil } + func c(_ shift: UInt32) -> Double { (Double((v >> shift) & 0xff) / 255 * 1000).rounded() / 1000 } + return ["r": c(16), "g": c(8), "b": c(0)] + } + + /// Readable value: colors as hex, scalars bare, everything else compact JSON. + static func display(_ v: Any) -> String { + if isColor(v), let d = v as? [String: Any] { return hex(d) } + if isBool(v) { return (v as! NSNumber).boolValue ? "true" : "false" } + if let n = v as? NSNumber { return number(n.doubleValue) } + if let s = v as? String { return s } + return json(v, pretty: false) + } + + static func number(_ x: Double) -> String { + x == x.rounded() && abs(x) < 1e15 ? String(Int(x)) : String(x) + } + + static func json(_ v: Any, pretty: Bool) -> String { + var opts: JSONSerialization.WritingOptions = [.sortedKeys, .fragmentsAllowed, .withoutEscapingSlashes] + if pretty { opts.insert(.prettyPrinted) } + guard let data = try? JSONSerialization.data(withJSONObject: v, options: opts) else { return "\(v)" } + return String(decoding: data, as: UTF8.self) + } + + // MARK: keys + + /// Every settable key path: top-level keys, plus `palette.` and the like for nested + /// objects. Per-scene image storage is managed by the scene switch, so it's left out. + static func allPaths(_ c: WallpaperConfig = WallpaperConfig()) -> [String] { + var out: [String] = [] + for (key, value) in object(c) where !internalKeys.contains(key) { + if let nested = value as? [String: Any], !isColor(nested) { + out += nested.keys.map { "\(key).\($0)" } + } else { + out.append(key) + } + } + return out.sorted() + } + + static let internalKeys: Set = ["sceneImage", "sharedImage", "phoneFraming", "tdeCycleMinutes"] + static let imageKeys = ["saturation", "brightness", "contrast", "blackPoint", "highlights", "vignette", + "bloom", "bloomRadius", "bloomThreshold", "pixelSize", "levels", "dither"] + + /// The allowed values of an enum-valued key, found by reflection (property names are the + /// Codable keys). + static func choices(for key: String) -> [String]? { + guard let child = Mirror(reflecting: WallpaperConfig()).children.first(where: { $0.label == key }), + let iterable = child.value as? any CaseIterable else { return nil } + func cases(_ v: T) -> [Any] { Array(T.allCases) } + let raw = cases(iterable).compactMap { ($0 as? any RawRepresentable)?.rawValue as? String } + return raw.isEmpty ? nil : raw + } + + static func suggestions(for key: String, in paths: [String]) -> [String] { + let k = key.lowercased() + let contains = paths.filter { $0.lowercased().contains(k) || k.contains($0.lowercased()) } + if !contains.isEmpty { return Array(contains.prefix(5)) } + return Array(paths.map { ($0, editDistance($0.lowercased(), k)) }.filter { $0.1 <= 3 } + .sorted { $0.1 < $1.1 }.prefix(5).map(\.0)) + } + + private static func editDistance(_ a: String, _ b: String) -> Int { + let a = Array(a), b = Array(b) + guard !a.isEmpty, !b.isEmpty else { return max(a.count, b.count) } + var row = Array(0...b.count) + for i in 1...a.count { + var prev = row[0] + row[0] = i + for j in 1...b.count { + let cur = row[j] + row[j] = min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] == b[j - 1] ? 0 : 1)) + prev = cur + } + } + return row[b.count] + } + + // MARK: assignments + + struct Assignment { + let key: String + let raw: String + var path: [String] { key.split(separator: ".").map(String.init) } + } + + static func isAssignment(_ arg: String) -> Bool { + guard let eq = arg.firstIndex(of: "="), eq != arg.startIndex else { return false } + return !arg.hasPrefix("-") + } + + static func assignments(_ args: [String]) throws -> [Assignment] { + try args.map { arg in + guard isAssignment(arg), let eq = arg.firstIndex(of: "=") else { + throw CLIError("expected KEY=VALUE, got \u{201C}\(arg)\u{201D}") + } + return Assignment(key: String(arg[.. Any { + if isColor(current) { + if let c = color(fromHex: raw) { return c } + if let d = jsonValue(raw) as? [String: Any], isColor(d) { return d } + throw CLIError("\(key) is a color: use hex like #ff8a3d") + } + if isBool(current) { + switch raw.lowercased() { + case "true", "yes", "on", "1": return true + case "false", "no", "off", "0": return false + default: throw CLIError("\(key) is on or off: use true or false") + } + } + if current is NSNumber { + guard let x = Double(raw), x.isFinite else { throw CLIError("\(key) is a number, got \u{201C}\(raw)\u{201D}") } + return x + } + if current is String { + if let s = jsonValue(raw) as? String { return s } + return raw + } + guard let v = jsonValue(raw) else { throw CLIError("\(key) takes JSON, like \(json(current, pretty: false))") } + return v + } + + private static func jsonValue(_ raw: String) -> Any? { + try? JSONSerialization.jsonObject(with: Data(raw.utf8), options: [.fragmentsAllowed]) + } + + /// `config` with the assignments applied. `scene` goes through the scene switch, so the new + /// scene brings its own image settings; everything else merges into the saved format and is + /// decoded with the same lenient decoder as the saved settings. A value that decoder rejects + /// is an error, one it clamps is a warning. + static func apply(_ list: [Assignment], to config: WallpaperConfig, + listedScenesOnly: Bool = true) throws -> (config: WallpaperConfig, warnings: [String]) { + var base = config + var rest: [Assignment] = [] + for a in list { + if a.key == "scene" { + base.scene = try SceneKind.named(a.raw, listedOnly: listedScenesOnly) + } else { + rest.append(a) + } + } + guard !rest.isEmpty else { return (base, []) } + let paths = allPaths(base) + var dict = object(base) + var wanted: [(Assignment, Any)] = [] + for a in rest { + guard !internalKeys.contains(a.path[0]), let current = value(at: a.path, in: dict) else { + let near = suggestions(for: a.key, in: paths) + throw CLIError("unknown setting \u{201C}\(a.key)\u{201D}" + + (near.isEmpty ? "" : " (did you mean \(near.joined(separator: ", "))?)") + + "\n`deepfield keys --all` lists them") + } + let v = try parse(a.raw, like: current, key: a.key) + dict = setting(v, at: a.path, in: dict) + wanted.append((a, v)) + } + guard let data = try? JSONSerialization.data(withJSONObject: dict), + let decoded = WallpaperConfig.decode(data) else { throw CLIError("those settings don't decode") } + let after = object(decoded) + var warnings: [String] = [] + for (a, v) in wanted { + let got = value(at: a.path, in: after) + if same(v, got) { continue } + if v is String || isColor(v) || isBool(v) || got == nil { + var msg = "\u{201C}\(a.raw)\u{201D} isn't a valid value for \(a.key)" + if let c = choices(for: a.key) { msg += " (choose from \(c.joined(separator: ", ")))" } + throw CLIError(msg) + } + warnings.append("\(a.key) was clamped to \(got.map(display) ?? "?")") + } + return (decoded, warnings) + } + + private static func same(_ a: Any, _ b: Any?) -> Bool { + guard let b else { return false } + if let x = a as? NSNumber, let y = b as? NSNumber, !isBool(a), !isBool(b) { + return abs(x.doubleValue - y.doubleValue) <= 1e-6 * max(1, abs(x.doubleValue)) + } + return json(a, pretty: false) == json(b, pretty: false) + } +} + +extension Int { + func clamped(_ lo: Int, _ hi: Int) -> Int { Swift.min(Swift.max(self, lo), hi) } +} + +extension SceneKind { + /// A scene by id or title, ignoring case, spaces and punctuation ("ringed-planet", "Star + /// Close-up"). `random` picks a listed scene other than `current`. + static func named(_ name: String, listedOnly: Bool = true, current: SceneKind? = nil) throws -> SceneKind { + func norm(_ s: String) -> String { s.lowercased().filter { $0.isLetter || $0.isNumber } } + let n = norm(name) + if n == "random" || n == "shuffle" { + return SceneKind.listed.filter { $0 != current }.randomElement() ?? .blackHole + } + let pool = listedOnly ? SceneKind.listed : SceneKind.allCases + if let k = pool.first(where: { norm($0.rawValue) == n || norm($0.title) == n }) { return k } + let near = pool.filter { norm($0.rawValue).contains(n) || norm($0.title).contains(n) } + if near.count == 1 { return near[0] } + throw CLIError("no scene called \u{201C}\(name)\u{201D}" + + (near.isEmpty ? "; `deepfield scenes` lists them" : " (did you mean \(near.map(\.rawValue).joined(separator: ", "))?)")) + } +} + +/// Presets by name: the user's saved presets first, then the palette presets, then the +/// scene's own color presets; or a `.deepfield` file. +enum PresetLookup { + static func apply(_ name: String, to c: inout WallpaperConfig, cwd: String) throws { + let path = resolve(name, cwd: cwd) + if name.hasSuffix(".\(PresetStore.fileExtension)") || name.hasSuffix(".json") || FileManager.default.fileExists(atPath: path) { + c = try file(path).applied(over: c) + return + } + if let p = PresetStore.shared.presets.first(where: { $0.name.caseInsensitiveCompare(name) == .orderedSame }) { + c = p.applied(over: c) + return + } + if let p = PaletteConfig.presets.first(where: { $0.0.caseInsensitiveCompare(name) == .orderedSame }) { + c.palette = p.1 + return + } + if let p = ColorPreset.all(for: c.scene).first(where: { $0.name.caseInsensitiveCompare(name) == .orderedSame }) { + p.apply(to: &c) + return + } + throw CLIError("no preset called \u{201C}\(name)\u{201D}; `deepfield presets` lists them") + } + + static func file(_ path: String) throws -> UserPreset { + guard let data = FileManager.default.contents(atPath: path) else { throw CLIError("can't read \(path)") } + guard let dict = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + let p = PresetStore.preset(from: dict) else { throw CLIError("\(path) isn't a Deep Field preset") } + return p + } + + static func resolve(_ path: String, cwd: String) -> String { + let p = (path as NSString).expandingTildeInPath + return p.hasPrefix("/") ? p : (cwd as NSString).appendingPathComponent(p) + } +} diff --git a/Sources/DeepField/CLI/RenderCommand.swift b/Sources/DeepField/CLI/RenderCommand.swift new file mode 100644 index 0000000..4e2d3c2 --- /dev/null +++ b/Sources/DeepField/CLI/RenderCommand.swift @@ -0,0 +1,382 @@ +import AppKit +import AVFoundation +import UniformTypeIdentifiers + +/// `deepfield render`: stills, videos, time-lapses, GIFs and PNG sequences, rendered offscreen in +/// this process from the saved settings (or the defaults) plus any changes. Renders are +/// deterministic: events use the same seed as the wallpaper, and nothing is fetched. +enum RenderCommand { + static let usage = """ + deepfield render [image|video|timelapse] OUT [KEY=VALUE...] [options] + + The extension of OUT picks the format: .png .jpg .heic .tiff for a still, .mp4 .mov for + video, .gif for an animated GIF, and a folder (ending in /) for numbered PNG frames. + Starts from the current wallpaper's settings; KEY=VALUE changes them for this render only. + + Look: + --scene NAME a scene other than the current one + --preset NAME|FILE a saved preset, palette, scene color preset or .deepfield file + --defaults start from the default settings instead of yours + --config JSON settings as a JSON object + --smooth full color at full resolution, without the pixel look + --no-events no supernovae or comets in the sky (scene events still happen) + --demo NAME:SECONDS start an event at that scene time (repeatable, comma-separated) + Frame: + --size WIDTHxHEIGHT output size (default: your main display's pixels) + --scale N multiply the size (0.5 for half size) + --time SECONDS scene time of a still, or where a video starts (default: a good moment) + Motion: + --duration SECONDS video length (default 10) + --fps N frames per second (default: the wallpaper's, 24) + --speed N scene seconds per video second (default 1; timelapse: 60) + --loop[=SECONDS] blend the last second (or SECONDS) into the start, for a seamless loop + --codec h264|hevc|prores default h264 for .mp4, hevc for .mov + --bitrate MBPS video bit rate + Output: + --open open the result when it's done + --quiet no progress + + Examples: + deepfield render shot.png + deepfield render image galaxy.heic --scene galaxy --size 5120x2880 galaxyType=barred + deepfield render video loop.mp4 --duration 8 --loop + deepfield render timelapse earth.mp4 --scene liveEarth --speed 3600 --duration 12 + deepfield render frames/ --duration 2 --fps 12 + Live Earth's day runs at --speed too, so --speed 3600 shows an hour a second. + """ + + private static let stillTypes: [String: UTType] = ["png": .png, "jpg": .jpeg, "jpeg": .jpeg, "heic": .heic, + "tif": .tiff, "tiff": .tiff] + + static func run(_ argv: [String], cwd: String) throws -> Int32 { + let a = try ParsedArgs(argv, + values: ["--scene", "--preset", "--config", "--demo", "--size", "--scale", "--time", + "--duration", "--fps", "--speed", "--codec", "--bitrate"], + flags: ["--defaults", "--smooth", "--no-events", "--open", "--quiet", "--loop"]) + var positional = a.positional + var mode = "auto" + if let first = positional.first, ["image", "still", "video", "timelapse", "gif", "frames"].contains(first) { + mode = first + positional.removeFirst() + } + guard let outArg = positional.first else { throw CLIError("usage: deepfield render [image|video|timelapse] OUT [options]") } + let out = PresetLookup.resolve(outArg, cwd: cwd) + let assignments = Array(positional.dropFirst()) + + // where the output goes decides the format + var isDir: ObjCBool = false + let folder = outArg.hasSuffix("/") || (FileManager.default.fileExists(atPath: out, isDirectory: &isDir) && isDir.boolValue) + let ext = (out as NSString).pathExtension.lowercased() + let still = !folder && (stillTypes[ext] != nil || (ext == "gif" && (mode == "image" || mode == "still"))) + if (mode == "video" || mode == "timelapse" || mode == "frames") && still { + throw CLIError("\(outArg) is a still image format; use .mp4, .mov, .gif or a folder/ for \(mode)") + } + if (mode == "image" || mode == "still") && !still { + throw CLIError("\(outArg) isn't an image format (png, jpg, heic, tiff)") + } + if !folder && !still && !["mp4", "mov", "m4v", "gif"].contains(ext) { + throw CLIError("can't tell the format from \u{201C}\(outArg)\u{201D}: use .png .jpg .heic .tiff .mp4 .mov .gif or a folder/") + } + + var config = try buildConfig(a, assignments: assignments, cwd: cwd) + let size = try outputSize(a) + LiveEarthFeeds.shared.allowNetwork = false + HistoricalClouds.shared.blocking = true // a past moment waits for that day's clouds + let events = !a.has("--no-events") + let quiet = a.has("--quiet") + let time = try a.double("--time") ?? LockScreenStill.representativeTime(config) + + if still { + try renderStill(config, size: size, time: time, events: events, smooth: a.has("--smooth"), to: out, ext: ext) + } else { + let fps = try a.int("--fps") ?? config.fps + let duration = try a.double("--duration") ?? 10 + let speed = try a.double("--speed") ?? (mode == "timelapse" ? 60 : 1) + guard fps > 0, fps <= 240, duration > 0, speed != 0 else { throw CLIError("--fps, --duration and --speed must be positive") } + var blend = 0.0 + if a.has("--loop") { blend = 1 } + if let s = try a.double("--loop") { blend = s } + blend = min(blend, duration / 2) + // Live Earth's clock follows the scene's, so a time-lapse shows the day going by + if config.scene == .liveEarth { SceneParams.earthTimeLapse = 1 } + config.fps = fps + let movie = MotionPlan(config: config, width: size.width, height: size.height, smooth: a.has("--smooth"), + start: time, duration: duration, fps: fps, speed: speed, blend: blend, events: events) + let sink: FrameSink + if folder { + sink = try PNGSequenceSink(folder: out) + } else if ext == "gif" { + sink = try GIFSink(url: URL(fileURLWithPath: out), fps: fps, frames: movie.frames) + } else { + sink = try MovieSink(url: URL(fileURLWithPath: out), width: size.width, height: size.height, fps: fps, + codec: a.value("--codec"), bitrate: try a.double("--bitrate"), mov: ext == "mov") + } + try movie.render(into: sink, progress: quiet ? nil : progressPrinter(movie.frames)) + try sink.finish() + } + if !quiet { CLI.stderr("Wrote \(out)") } + if a.has("--open") { NSWorkspace.shared.open(URL(fileURLWithPath: out)) } + return 0 + } + + // MARK: settings + + private static func buildConfig(_ a: ParsedArgs, assignments: [String], cwd: String) throws -> WallpaperConfig { + var c = a.has("--defaults") ? WallpaperConfig() : savedConfig() + if let s = a.value("--scene") { c.scene = try SceneKind.named(s, listedOnly: false, current: c.scene) } + if let p = a.value("--preset") { try PresetLookup.apply(p, to: &c, cwd: cwd) } + if let json = a.value("--config") { + guard let patch = try? JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any] else { + throw CLIError("--config takes a JSON object") + } + let list = patch.map { k, v in + ConfigKeys.Assignment(key: k, raw: ConfigKeys.isColor(v) ? ConfigKeys.display(v) : ConfigKeys.json(v, pretty: false)) + } + c = try ConfigKeys.apply(list, to: c, listedScenesOnly: false).config + } + let (patched, warnings) = try ConfigKeys.apply(try ConfigKeys.assignments(assignments), to: c, listedScenesOnly: false) + warnings.forEach { CLI.stderr("note: \($0)") } + c = patched + if a.has("--smooth") { + c.pixelSize = 1 + c.levels = 256 + c.dither = .bayer8 + } + if let demo = a.value("--demo") { + for pair in demo.split(separator: ",") { + let parts = pair.split(separator: ":").map(String.init) + guard parts.count == 2, let start = Double(parts[1]), + let e = EventSchedule.named.first(where: { $0.name.caseInsensitiveCompare(parts[0]) == .orderedSame || String($0.kind.id) == parts[0] }) + else { throw CLIError("--demo takes NAME:SECONDS, like supernova:300") } + ConfigStore.shared.demoEvents[e.kind.id] = start + } + } + return c + } + + /// The running app's settings (they may not be saved yet), or the saved ones. + private static func savedConfig() -> WallpaperConfig { + if let reply = CLIClient.send(["get", "--raw"], cwd: "/"), reply.code == 0, + let c = WallpaperConfig.decode(Data(reply.out.utf8)) { + return c + } + return ConfigStore.shared.config + } + + private static func outputSize(_ a: ParsedArgs) throws -> (width: Int, height: Int) { + var w = 0, h = 0 + if let s = a.value("--size") { + let parts = s.lowercased().split(separator: "x").compactMap { Int($0) } + guard parts.count == 2, parts[0] > 0, parts[1] > 0 else { throw CLIError("--size takes WIDTHxHEIGHT, like 3840x2160") } + (w, h) = (parts[0], parts[1]) + } else if let mode = CGDisplayCopyDisplayMode(CGMainDisplayID()), mode.pixelWidth > 0 { + (w, h) = (mode.pixelWidth, mode.pixelHeight) + } else { + (w, h) = (3840, 2160) + } + if let k = try a.double("--scale") { + guard k > 0 else { throw CLIError("--scale must be positive") } + w = max(1, Int((Double(w) * k).rounded())) + h = max(1, Int((Double(h) * k).rounded())) + } + guard w * h <= 16384 * 16384 else { throw CLIError("that's too big to render") } + return (w, h) + } + + private static func progressPrinter(_ total: Int) -> (Int) -> Void { + let tty = isatty(STDERR_FILENO) != 0 + let start = Date() + return { done in + guard tty || done == total else { return } + let elapsed = Date().timeIntervalSince(start) + let eta = done > 0 ? elapsed / Double(done) * Double(total - done) : 0 + let line = "Rendering frame \(done)/\(total)" + (done < total ? String(format: ", about %.0f s left", eta) : "") + FileHandle.standardError.write(Data(((tty ? "\r\u{1B}[K" : "") + line + (done == total ? "\n" : "")).utf8)) + } + } + + // MARK: still + + private static func renderStill(_ c: WallpaperConfig, size: (width: Int, height: Int), time: Double, events: Bool, + smooth: Bool, to path: String, ext: String) throws { + let px = c.pixelSize + let w = (size.width + px - 1) / px, h = (size.height + px - 1) / px + guard let frame = FrameCapture.render(config: c, width: w, height: h, time: time, eventsEnabled: events), + let image = FrameCapture.upscaled(frame, factor: px, width: size.width, height: size.height, nearest: !smooth) + else { throw CLIError("rendering failed") } + let type = stillTypes[ext] ?? .gif + guard let dest = CGImageDestinationCreateWithURL(URL(fileURLWithPath: path) as CFURL, type.identifier as CFString, 1, nil) else { + throw CLIError("can't write \(path)") + } + let props: [CFString: Any] = [kCGImageDestinationLossyCompressionQuality: 0.95] + CGImageDestinationAddImage(dest, image, props as CFDictionary) + guard CGImageDestinationFinalize(dest) else { throw CLIError("can't write \(path)") } + } +} + +// MARK: motion + +/// The frames of a video: `frames` evenly spaced output frames, the scene clock running `speed` +/// times as fast from `start`. With `blend`, the last `blend` seconds dissolve into the frames +/// just before the start (cell by cell when dithered), so the end leads back into the start. +struct MotionPlan { + let config: WallpaperConfig + let width: Int, height: Int + let smooth: Bool + let start, duration: Double + let fps: Int + let speed, blend: Double + let events: Bool + + var frames: Int { max(1, Int((duration * Double(fps)).rounded())) } + + func render(into sink: FrameSink, progress: ((Int) -> Void)?) throws { + let px = config.pixelSize + let sw = (width + px - 1) / px, sh = (height + px - 1) / px + guard let seq = FrameCapture.Sequence(config: config, width: sw, height: sh, eventsEnabled: events) else { + throw CLIError("couldn't set up the scene") + } + let n = frames + let k = Int((blend * Double(fps)).rounded()) + let span = Double(n) / Double(fps) * speed // scene seconds the video covers + for i in 0.. 0 && i >= n - k { + let weight = Double(i - (n - k) + 1) / Double(k + 1) + let earlier = t - span + guard let b = seq.frame(time: earlier, orbitTime: earlier), + let mixed = MobileExport.dissolve(frame, b, weight: weight, cells: !smooth) else { + throw CLIError("blending frame \(i) failed") + } + frame = mixed + } + guard let image = FrameCapture.upscaled(frame, factor: px, width: width, height: height, nearest: !smooth) else { + throw CLIError("scaling frame \(i) failed") + } + try sink.append(image, index: i) + progress?(i + 1) + } + } +} + +protocol FrameSink { + func append(_ image: CGImage, index: Int) throws + func finish() throws +} + +final class PNGSequenceSink: FrameSink { + let folder: URL + init(folder: String) throws { + self.folder = URL(fileURLWithPath: folder, isDirectory: true) + try FileManager.default.createDirectory(at: self.folder, withIntermediateDirectories: true) + } + func append(_ image: CGImage, index: Int) throws { + try FrameCapture.writePNG(image, to: folder.appendingPathComponent(String(format: "frame_%05d.png", index + 1))) + } + func finish() throws {} +} + +final class GIFSink: FrameSink { + private let dest: CGImageDestination + private let frameProps: CFDictionary + private let path: String + + init(url: URL, fps: Int, frames: Int) throws { + guard let d = CGImageDestinationCreateWithURL(url as CFURL, UTType.gif.identifier as CFString, frames, nil) else { + throw CLIError("can't write \(url.path)") + } + dest = d + path = url.path + CGImageDestinationSetProperties(d, [kCGImagePropertyGIFDictionary: [kCGImagePropertyGIFLoopCount: 0]] as CFDictionary) + frameProps = [kCGImagePropertyGIFDictionary: [kCGImagePropertyGIFDelayTime: 1 / Double(fps), + kCGImagePropertyGIFUnclampedDelayTime: 1 / Double(fps)]] as CFDictionary + } + func append(_ image: CGImage, index: Int) throws { CGImageDestinationAddImage(dest, image, frameProps) } + func finish() throws { + guard CGImageDestinationFinalize(dest) else { throw CLIError("can't write \(path)") } + } +} + +/// H.264 or HEVC in MP4 or QuickTime, or ProRes 4444 in QuickTime for editing. +final class MovieSink: FrameSink { + private let writer: AVAssetWriter + private let input: AVAssetWriterInput + private let adaptor: AVAssetWriterInputPixelBufferAdaptor + private let width, height, fps: Int + + init(url: URL, width w0: Int, height h0: Int, fps: Int, codec name: String?, bitrate: Double?, mov: Bool) throws { + // 4:2:0 video needs even sizes; an odd last column or row is left out + width = w0 & ~1 + height = h0 & ~1 + self.fps = fps + let codec: AVVideoCodecType + switch name?.lowercased() ?? (mov ? "hevc" : "h264") { + case "h264", "avc": codec = .h264 + case "hevc", "h265": codec = .hevc + case "prores", "prores4444": + guard mov else { throw CLIError("ProRes needs a .mov file") } + codec = .proRes4444 + default: throw CLIError("--codec takes h264, hevc or prores") + } + try? FileManager.default.removeItem(at: url) + writer = try AVAssetWriter(outputURL: url, fileType: mov ? .mov : .mp4) + var settings: [String: Any] = [ + AVVideoCodecKey: codec, AVVideoWidthKey: width, AVVideoHeightKey: height, + AVVideoColorPropertiesKey: [AVVideoColorPrimariesKey: AVVideoColorPrimaries_ITU_R_709_2, + AVVideoTransferFunctionKey: AVVideoTransferFunction_ITU_R_709_2, + AVVideoYCbCrMatrixKey: AVVideoYCbCrMatrix_ITU_R_709_2], + ] + if codec != .proRes4444 { + // dithered frames are mostly hard-edged cells, which need more bits than camera video + let bits = bitrate.map { $0 * 1_000_000 } ?? Double(width * height * fps) * 0.25 + settings[AVVideoCompressionPropertiesKey] = [AVVideoAverageBitRateKey: bits, + AVVideoExpectedSourceFrameRateKey: fps, + AVVideoMaxKeyFrameIntervalKey: fps * 2] + } + guard writer.canApply(outputSettings: settings, forMediaType: .video) else { + throw CLIError("this Mac can't encode \(codec.rawValue) at \(width)x\(height)") + } + input = AVAssetWriterInput(mediaType: .video, outputSettings: settings) + input.expectsMediaDataInRealTime = false + adaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: input, sourcePixelBufferAttributes: [ + kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA, + kCVPixelBufferWidthKey as String: width, kCVPixelBufferHeightKey as String: height]) + guard writer.canAdd(input) else { throw CLIError("can't add a video track") } + writer.add(input) + guard writer.startWriting() else { throw CLIError("can't write \(url.path): \(writer.error?.localizedDescription ?? "")") } + writer.startSession(atSourceTime: .zero) + } + + func append(_ image: CGImage, index: Int) throws { + while !input.isReadyForMoreMediaData { + if writer.status == .failed { throw CLIError("encoding failed: \(writer.error?.localizedDescription ?? "")") } + Thread.sleep(forTimeInterval: 0.002) + } + guard let pool = adaptor.pixelBufferPool else { throw CLIError("encoding failed: \(writer.error?.localizedDescription ?? "no buffers")") } + var buffer: CVPixelBuffer? + CVPixelBufferPoolCreatePixelBuffer(nil, pool, &buffer) + guard let pb = buffer else { throw CLIError("encoding failed: no pixel buffer") } + CVPixelBufferLockBaseAddress(pb, []) + let info = CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue + if let ctx = CGContext(data: CVPixelBufferGetBaseAddress(pb), width: width, height: height, bitsPerComponent: 8, + bytesPerRow: CVPixelBufferGetBytesPerRow(pb), space: CGColorSpace(name: CGColorSpace.sRGB)!, + bitmapInfo: info) { + ctx.interpolationQuality = .none + // top-left aligned, so a dropped odd column or row comes off the right and bottom + ctx.draw(image, in: CGRect(x: 0, y: height - image.height, width: image.width, height: image.height)) + } + CVPixelBufferUnlockBaseAddress(pb, []) + guard adaptor.append(pb, withPresentationTime: CMTime(value: CMTimeValue(index), timescale: CMTimeScale(fps))) else { + throw CLIError("encoding failed: \(writer.error?.localizedDescription ?? "")") + } + } + + func finish() throws { + input.markAsFinished() + let done = DispatchSemaphore(value: 0) + writer.finishWriting { done.signal() } + while done.wait(timeout: .now()) == .timedOut { RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01)) } + if writer.status != .completed { throw CLIError("encoding failed: \(writer.error?.localizedDescription ?? "")") } + } +} diff --git a/Sources/DeepField/Config/SceneCustomization.swift b/Sources/DeepField/Config/SceneCustomization.swift index 6cf1875..f9816c0 100644 --- a/Sources/DeepField/Config/SceneCustomization.swift +++ b/Sources/DeepField/Config/SceneCustomization.swift @@ -149,6 +149,12 @@ extension WallpaperConfig { return c } + /// `kind`'s own saved keys, with its palette colors as `palette.`, for the command line. + static func sceneKeys(_ kind: SceneKind) -> [String] { + let keys = WallpaperConfig().jsonObject().keys.filter { owns(kind, key: $0) }.sorted() + return keys + ownKeys(kind).palette.map { "palette.\($0)" } + } + /// True when any of `kind`'s own settings differ from their defaults. func isCustomized(_ kind: SceneKind) -> Bool { resettingScene(kind) != self } } diff --git a/Sources/DeepField/Mobile/MobileExport.swift b/Sources/DeepField/Mobile/MobileExport.swift index 92a0447..f524a6a 100644 --- a/Sources/DeepField/Mobile/MobileExport.swift +++ b/Sources/DeepField/Mobile/MobileExport.swift @@ -187,7 +187,7 @@ enum MobileExport { return ok ? data : nil } - private static func dissolve(_ a: CGImage, _ b: CGImage, weight: Double, cells: Bool) -> CGImage? { + static func dissolve(_ a: CGImage, _ b: CGImage, weight: Double, cells: Bool) -> CGImage? { guard var pa = pixels(a), let pb = pixels(b) else { return nil } let w = a.width, h = a.height if cells { diff --git a/Sources/DeepField/Rendering/FrameCapture.swift b/Sources/DeepField/Rendering/FrameCapture.swift index 2a77585..c92128c 100644 --- a/Sources/DeepField/Rendering/FrameCapture.swift +++ b/Sources/DeepField/Rendering/FrameCapture.swift @@ -76,7 +76,7 @@ enum FrameCapture { p.cb.commit() } - /// Many frames of one config from a single bake (the phone loop). Encoding runs on the main + /// Many frames of one config from a single bake (the phone loop, command-line videos). Encoding runs on the main /// thread, like the live views (the scene state caches aren't thread-safe); call `frame` from /// any thread, and it waits for the GPU there. final class Sequence { @@ -85,15 +85,16 @@ enum FrameCapture { private let target: MTLTexture private let buffer: MTLBuffer private let width: Int, height: Int - private let events = EventSchedule(seed: 1, enabled: false) + private let events: EventSchedule - init?(config: WallpaperConfig, width w: Int, height h: Int) { + init?(config: WallpaperConfig, width w: Int, height h: Int, eventsEnabled: Bool = false) { let r = Renderer.shared guard let target = r.makeTexture(.bgra8Unorm, w, h, usage: [.renderTarget, .shaderRead]), let buffer = r.device.makeBuffer(length: w * 4 * h, options: .storageModeShared), let baked = onMain({ r.bake(width: w, height: h, config: config, wait: true) }) else { return nil } self.config = config self.baked = baked + events = EventSchedule(seed: 1, enabled: eventsEnabled) self.target = target self.buffer = buffer width = w diff --git a/Sources/DeepField/Scenes/Events.swift b/Sources/DeepField/Scenes/Events.swift index 696d7aa..614cd29 100644 --- a/Sources/DeepField/Scenes/Events.swift +++ b/Sources/DeepField/Scenes/Events.swift @@ -251,3 +251,22 @@ private final class SkyPlacements { } var entries: [UInt64: (key: Key, dirs: [SIMD3], after: Rng)] = [:] } + +extension EventSchedule { + /// Every event kind by name, with the scene it belongs to (nil for the shared sky events), for + /// the command line's `deepfield event`. + static let named: [(name: String, kind: Kind, scene: SceneKind?)] = [ + ("supernova", supernova, nil), ("comet", comet, nil), + ("farSupernova", farSupernova, .wormhole), ("throatFlare", throatFlare, .wormhole), + ("infall", infall, .wormhole), ("emergence", emergence, .wormhole), + ("cometOutburst", cometOutburst, .comet), ("tailDisconnect", tailDisconnect, .comet), + ("stellarFlare", stellarFlare, .stellarSurface), ("coronalEjection", coronalEjection, .stellarSurface), + ("prominenceEruption", prominenceEruption, .stellarSurface), ("surge", surge, .stellarSurface), + ("shellEjection", shellEjection, .planetaryNebula), ("whiteStorm", whiteStorm, .ringedPlanet), + ("substorm", substorm, .auroraOrbit), ("cometImpact", cometImpact, .gasGiant), + ("accretionOutburst", accretionOutburst, .protoplanetaryDisk), ("neutronMerger", neutronMerger, .neutronMerger), + ("blackHoleMerger", blackHoleMerger, .blackHoleMerger), ("swarmWave", swarmWave, .dysonSwarm), + ("starGlint", starGlint, .roguePlanet), ("eclipseEruption", eclipseEruption, .eclipse), + ("quasarFlare", quasarFlare, .quasar), + ] +} diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 7533fbb..59209e7 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -32,7 +32,8 @@ Everything is in `Sources/DeepField`: `ShaderSource.full` and compiled at runtime, so the build needs no Metal toolchain. - `UI/`: the SwiftUI Customize window, one file per section, plus the stage, gallery and theme. - `Mobile/`: the phone wallpaper export (portrait still, Live Photo pair, Photos library). -- `Dev/`: the command line below (snapshot, benchmark, event list, UI capture). +- `CLI/`: the user-facing `deepfield` command (see below). +- `Dev/`: the dev command line below (snapshot, benchmark, event list, UI capture). The Earth and sky maps for Aurora from Orbit and Live Earth (NASA's Black Marble city lights, Blue Marble surface for January and July, the Moon, the Yale Bright Star Catalog and NASA's Milky @@ -139,7 +140,30 @@ Deep Field keeps a still of the current scene as each screen's desktop picture. when the scene's look or your displays change, leaves alone a screen whose picture you've changed since, and puts your original pictures back when you turn the option off. -## Command line +## The `deepfield` command + +`CLI/` holds the command users run (`deepfield help` lists it). It's the app's own executable: +`main.swift` hands over to `CLI.runIfRequested()` when the process was started as `deepfield` (the +link `deepfield install` makes) or its first argument is a command name, and the app never starts. +Started through the link, it re-executes the real path so `Bundle.main` and the defaults domain +are the app's. + +Commands that read or change state (`CLIService`) are sent as JSON to the running app over a +`CFMessagePort` (`CLIServer`, started at launch) and run on its main thread, so changes show at +once and `--fade` can use the schedule's transitions. When nothing answers, the same code runs +in the command's own process on the saved settings, and commands that need the live wallpaper +(pause, event) fail. `ConfigKeys` maps `KEY=VALUE` onto the saved format: values are parsed as +the type the key already holds (hex for colors), decoded by the lenient decoder, and a value it +rejects is an error. `scene` goes through the scene switch, so a scene's own image settings come +with it. `render` runs offscreen in the command's process (`RenderCommand`) and writes stills +through ImageIO, videos through AVFoundation, GIFs and PNG sequences; Live Earth's clock follows +the scene's in videos, so `--speed` time-lapses its day. + +Try it from a build without installing: `build/DeepField.app/Contents/MacOS/DeepField status` +(a command as the first argument works too). Testing `set` and friends changes your real +settings, so `defaults export com.narrowstacks.DeepField backup.plist` first. + +## Dev command line ```bash .build/release/DeepField --snapshot out.png --time 444 [--size 3440x1440] [--scene wormhole] \