diff --git a/Package.swift b/Package.swift index 110f09d..4cf9bf6 100644 --- a/Package.swift +++ b/Package.swift @@ -4,10 +4,22 @@ import PackageDescription let package = Package( name: "Kapture", platforms: [.macOS(.v13)], + products: [ + .executable(name: "Kapture", targets: ["Kapture"]), + // Command-line client for agents and scripts; talks to the running + // menu-bar app over distributed notifications (no extra permissions). + // Named kapture-cli because "Kapture" and "kapture" collide on the + // case-insensitive filesystem; the cask installs it as `kapture`. + .executable(name: "kapture-cli", targets: ["KaptureCLI"]), + ], targets: [ .executableTarget( name: "Kapture", path: "Sources/Kapture" - ) + ), + .executableTarget( + name: "KaptureCLI", + path: "Sources/KaptureCLI" + ), ] ) diff --git a/Sources/Kapture/App.swift b/Sources/Kapture/App.swift index fda2767..b3f3930 100644 --- a/Sources/Kapture/App.swift +++ b/Sources/Kapture/App.swift @@ -42,6 +42,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } } HotkeyManager.shared.register() + CLIService.shared.start() } func applicationWillTerminate(_ notification: Notification) { diff --git a/Sources/Kapture/CLIService.swift b/Sources/Kapture/CLIService.swift new file mode 100644 index 0000000..1c9ac2d --- /dev/null +++ b/Sources/Kapture/CLIService.swift @@ -0,0 +1,211 @@ +import AppKit +import ImageIO +import UniformTypeIdentifiers + +/// Serves `kapture` CLI requests from the running menu-bar app. The CLI +/// writes a JSON request into `~/Library/Application Support/Kapture/cli` +/// and posts a distributed notification carrying its id; this service +/// captures and writes the JSON response alongside it. Captures use the +/// app's own Screen Recording grant, so the CLI needs no permissions. +final class CLIService { + static let shared = CLIService() + + static let notificationName = "dev.tzgyn.kapture.cli.request" + static let requestKey = "id" + + private var observer: NSObjectProtocol? + + private var directory: URL { + FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] + .appendingPathComponent("Kapture/cli", isDirectory: true) + } + + private func requestURL(_ id: String) -> URL { + directory.appendingPathComponent("\(id).request.json") + } + + private func responseURL(_ id: String) -> URL { + directory.appendingPathComponent("\(id).response.json") + } + + func start() { + guard observer == nil else { return } + try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + observer = DistributedNotificationCenter.default().addObserver( + forName: .init(Self.notificationName), object: nil, queue: .main + ) { [weak self] note in + guard let id = note.userInfo?[Self.requestKey] as? String else { return } + self?.handle(id: id) + } + CaptureController.log("cli: listening") + } + + // MARK: - Requests + + private func handle(id: String) { + let url = requestURL(id) + defer { try? FileManager.default.removeItem(at: url) } + guard let data = try? Data(contentsOf: url), + let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { + respond(id: id, ["ok": false, "error": "Malformed request"]) + return + } + switch request["command"] as? String { + case "list": + respond(id: id, [ + "ok": true, + "windows": windows().map { window in + [ + "id": Int(window.id), + "app": window.app, + "title": window.title, + "width": Int(window.bounds.width), + "height": Int(window.bounds.height), + ] as [String: Any] + }, + ]) + case "capture": + handleCapture(id: id, request: request) + default: + respond(id: id, ["ok": false, "error": "Unknown command"]) + } + } + + private func handleCapture(id: String, request: [String: Any]) { + guard CGPreflightScreenCaptureAccess() else { + respond(id: id, ["ok": false, "error": "Kapture does not have Screen Recording permission"]) + return + } + let outPath = request["out"] as? String + + if request["screen"] as? Bool == true { + guard let screen = NSScreen.screens.first else { + respond(id: id, ["ok": false, "error": "No screen available"]) + return + } + capture(rect: screen.frame, windowID: nil, out: outPath, id: id) + return + } + + if let number = request["windowID"] as? NSNumber, + let window = windows().first(where: { Int($0.id) == number.intValue }) { + capture(rect: window.bounds, windowID: window.id, out: outPath, id: id) + return + } + + guard let window = bestWindow(for: request["app"] as? String) else { + let error = (request["app"] as? String).map { "No on-screen window found for app \"\($0)\"" } + ?? "No window found" + respond(id: id, ["ok": false, "error": error]) + return + } + capture(rect: window.bounds, windowID: window.id, out: outPath, id: id) + } + + private func capture(rect: NSRect, windowID: CGWindowID?, out: String?, id: String) { + ScreenCapture.shared.capture(rect, excludingWindowIDs: [], windowID: windowID) { [weak self] image in + DispatchQueue.main.async { + guard let self else { return } + guard let image else { + self.respond(id: id, ["ok": false, "error": "Capture failed (Screen Recording permission?)"]) + return + } + let url = out.map { URL(fileURLWithPath: $0) } + ?? FileManager.default.temporaryDirectory.appendingPathComponent("kapture-\(Self.timestamp()).png") + guard let dest = CGImageDestinationCreateWithURL(url as CFURL, UTType.png.identifier as CFString, 1, nil) else { + self.respond(id: id, ["ok": false, "error": "Could not create \(url.path)"]) + return + } + CGImageDestinationAddImage(dest, image, nil) + guard CGImageDestinationFinalize(dest) else { + self.respond(id: id, ["ok": false, "error": "Could not write \(url.path)"]) + return + } + CaptureController.log("cli: captured \(image.width)x\(image.height) -> \(url.path)") + self.respond(id: id, ["ok": true, "path": url.path, "width": image.width, "height": image.height]) + } + } + } + + private func respond(id: String, _ body: [String: Any]) { + guard let data = try? JSONSerialization.data(withJSONObject: body) else { return } + try? data.write(to: responseURL(id), options: .atomic) + } + + // MARK: - Windows + + private struct WindowInfo { + let id: CGWindowID + let pid: Int + let app: String + let title: String + let bounds: NSRect + } + + /// On-screen layer-0 windows, front to back, own panels excluded. + private func windows() -> [WindowInfo] { + guard let list = CGWindowListCopyWindowInfo( + [.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID + ) as? [[String: Any]] else { return [] } + + let ownPid = Int(ProcessInfo.processInfo.processIdentifier) + return list.compactMap { info in + guard let id = info[kCGWindowNumber as String] as? CGWindowID, + let layer = info[kCGWindowLayer as String] as? Int, layer == 0, + let pid = info[kCGWindowOwnerPID as String] as? Int, pid != ownPid, + let bounds = info[kCGWindowBounds as String] as? [String: CGFloat], + (bounds["Width"] ?? 0) >= 80, (bounds["Height"] ?? 0) >= 60 else { return nil } + let cgRect = NSRect( + x: bounds["X"] ?? 0, y: bounds["Y"] ?? 0, + width: bounds["Width"] ?? 0, height: bounds["Height"] ?? 0 + ) + return WindowInfo( + id: id, + pid: pid, + app: info[kCGWindowOwnerName as String] as? String ?? "", + title: info[kCGWindowName as String] as? String ?? "", + bounds: Self.cgToAppKit(cgRect) + ) + } + } + + private func bestWindow(for query: String?) -> WindowInfo? { + let candidates = windows() + guard let query, !query.isEmpty else { + if let front = NSWorkspace.shared.frontmostApplication, + let window = candidates.first(where: { $0.pid == front.processIdentifier }) { + return window + } + return candidates.first + } + let needle = query.lowercased() + if let window = candidates.first(where: { $0.app.lowercased().contains(needle) }) { + return window + } + for app in NSWorkspace.shared.runningApplications { + let name = (app.localizedName ?? "").lowercased() + let bundle = (app.bundleIdentifier ?? "").lowercased() + if name.contains(needle) || bundle.contains(needle), + let window = candidates.first(where: { $0.pid == app.processIdentifier }) { + return window + } + } + return nil + } + + private static func cgToAppKit(_ rect: NSRect) -> NSRect { + guard let main = NSScreen.screens.first else { return rect } + return NSRect( + x: rect.origin.x, + y: main.frame.height - rect.origin.y - rect.height, + width: rect.width, + height: rect.height + ) + } + + private static func timestamp() -> String { + let formatter = DateFormatter() + formatter.dateFormat = "yyyyMMdd-HHmmss" + return formatter.string(from: Date()) + } +} diff --git a/Sources/KaptureCLI/main.swift b/Sources/KaptureCLI/main.swift new file mode 100644 index 0000000..eb72423 --- /dev/null +++ b/Sources/KaptureCLI/main.swift @@ -0,0 +1,254 @@ +import AppKit +import Foundation + +// kapture — command-line client for the Kapture menu-bar app. +// +// It does not capture by itself: requests go to the running app, which +// already holds the Screen Recording permission and owns all window / +// display capture logic. Requests and responses are JSON files in +// ~/Library/Application Support/Kapture/cli, signalled by a distributed +// notification carrying the request id. + +let helpText = """ +kapture — screenshot capture for agents and scripts + +USAGE + kapture capture [options] Capture a window or the main display to a PNG + kapture list [--json] List on-screen windows (id, app, title, size) + kapture --help Show this help + +CAPTURE OPTIONS + --app App whose frontmost window to capture. Matches + localized names and bundle ids, case-insensitive + substring. Default: the frontmost app's window. + --window-id Capture a specific window id from `kapture list`. + --screen Capture the main display instead of a window. + --out Output PNG path (default: a new file in $TMPDIR). + --json Print {"ok","path","width","height"} instead of + just the path. + +BEHAVIOR + Prints the absolute PNG path on stdout (exit 0). Errors go to stderr. + Requires the Kapture menu-bar app (Homebrew cask); it is launched + automatically if it is not running. + +EXAMPLES + kapture capture --app Xcode --out /tmp/xcode.png + kapture capture --app Safari --json + kapture list + kapture capture --window-id 1234 --out shot.png + kapture capture --screen +""" + +// MARK: - Bridge + +enum Bridge { + static let notificationName = "dev.tzgyn.kapture.cli.request" + static let appBundleID = "dev.tzgyn.kapture" + + static var directory: URL { + FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] + .appendingPathComponent("Kapture/cli", isDirectory: true) + } + + static func appIsRunning() -> Bool { + NSWorkspace.shared.runningApplications.contains { + $0.bundleIdentifier == appBundleID || $0.localizedName == "Kapture" + } + } + + static func launchApp() { + // Prefer the bundle this CLI lives inside, so a dev CLI launches its + // own app build rather than a stale installed copy with the same id. + let executable = URL(fileURLWithPath: CommandLine.arguments[0]).resolvingSymlinksInPath() + let appBundle = executable + .deletingLastPathComponent() // Contents/MacOS + .deletingLastPathComponent() // Contents + .deletingLastPathComponent() // Kapture.app + let task = Process() + task.executableURL = URL(fileURLWithPath: "/usr/bin/open") + if appBundle.pathExtension == "app" { + task.arguments = [appBundle.path] + } else { + task.arguments = ["-b", appBundleID] + } + task.standardOutput = FileHandle.nullDevice + task.standardError = FileHandle.nullDevice + try? task.run() + task.waitUntilExit() + } + + /// Send a request to the app and wait for its response. Posts the + /// notification repeatedly so a still-starting app can pick it up. + static func send(_ request: [String: Any], timeout: TimeInterval = 12) -> [String: Any]? { + try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let id = UUID().uuidString + let requestURL = directory.appendingPathComponent("\(id).request.json") + let responseURL = directory.appendingPathComponent("\(id).response.json") + defer { + try? FileManager.default.removeItem(at: requestURL) + try? FileManager.default.removeItem(at: responseURL) + } + guard let data = try? JSONSerialization.data(withJSONObject: request), + (try? data.write(to: requestURL, options: .atomic)) != nil else { + return nil + } + + if !appIsRunning() { launchApp() } + + let deadline = Date().addingTimeInterval(timeout) + var lastPost = Date.distantPast + while Date() < deadline { + if Date().timeIntervalSince(lastPost) > 0.3 { + lastPost = Date() + DistributedNotificationCenter.default().postNotificationName( + .init(notificationName), object: nil, + userInfo: ["id": id], deliverImmediately: true + ) + } + if let responseData = try? Data(contentsOf: responseURL), + let object = (try? JSONSerialization.jsonObject(with: responseData)) as? [String: Any] { + return object + } + usleep(50_000) + } + return nil + } +} + +// MARK: - Output helpers + +func fail(_ message: String, code: Int32) -> Never { + FileHandle.standardError.write(("kapture: " + message + "\n").data(using: .utf8)!) + exit(code) +} + +func usageError(_ message: String) -> Never { + FileHandle.standardError.write(("kapture: " + message + "\n\n" + helpText + "\n").data(using: .utf8)!) + exit(2) +} + +func printJSON(_ object: [String: Any]) { + guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) else { return } + print(String(data: data, encoding: .utf8) ?? "{}") +} + +func timestamp() -> String { + let formatter = DateFormatter() + formatter.dateFormat = "yyyyMMdd-HHmmss" + return formatter.string(from: Date()) +} + +// MARK: - Commands + +func runCapture(_ args: [String]) { + var app: String? + var windowID: Int? + var screen = false + var out: String? + var json = false + + var index = 0 + while index < args.count { + switch args[index] { + case "--app": + index += 1 + guard index < args.count else { usageError("--app needs a value") } + app = args[index] + case "--window-id": + index += 1 + guard index < args.count, let id = Int(args[index]) else { usageError("--window-id needs a number") } + windowID = id + case "--screen": + screen = true + case "--out": + index += 1 + guard index < args.count else { usageError("--out needs a path") } + out = args[index] + case "--json": + json = true + default: + usageError("unknown option \"\(args[index])\"") + } + index += 1 + } + + let outURL = URL(fileURLWithPath: (out.map { ($0 as NSString).expandingTildeInPath } + ?? FileManager.default.temporaryDirectory.appendingPathComponent("kapture-\(timestamp()).png").path)) + + var request: [String: Any] = ["command": "capture", "screen": screen, "out": outURL.path] + if let app { request["app"] = app } + if let windowID { request["windowID"] = windowID } + + guard let response = Bridge.send(request) else { + fail("the Kapture app did not respond. Is it installed and running?", code: 3) + } + guard (response["ok"] as? Bool) == true else { + fail(response["error"] as? String ?? "capture failed", code: 1) + } + if json { + printJSON([ + "ok": true, + "path": response["path"] as? String ?? outURL.path, + "width": response["width"] as? Int ?? 0, + "height": response["height"] as? Int ?? 0, + ]) + } else { + print(response["path"] as? String ?? outURL.path) + } +} + +func runList(_ args: [String]) { + var json = false + for arg in args { + switch arg { + case "--json": json = true + default: usageError("unknown option \"\(arg)\"") + } + } + guard let response = Bridge.send(["command": "list"]) else { + fail("the Kapture app did not respond. Is it installed and running?", code: 3) + } + guard (response["ok"] as? Bool) == true else { + fail(response["error"] as? String ?? "could not list windows", code: 1) + } + let windows = response["windows"] as? [[String: Any]] ?? [] + if json { + printJSON(["ok": true, "windows": windows]) + return + } + func pad(_ text: String, _ width: Int) -> String { + text.count >= width ? String(text.prefix(width - 1)) + "…" : text.padding(toLength: width, withPad: " ", startingAt: 0) + } + print("\(pad("ID", 8)) \(pad("APP", 20)) \(pad("TITLE", 50)) SIZE") + for window in windows { + let id = window["id"] as? Int ?? 0 + let app = window["app"] as? String ?? "" + let title = window["title"] as? String ?? "" + let width = window["width"] as? Int ?? 0 + let height = window["height"] as? Int ?? 0 + print("\(pad(String(id), 8)) \(pad(app, 20)) \(pad(title, 50)) \(width)x\(height)") + } +} + +// MARK: - Main + +var arguments = Array(CommandLine.arguments.dropFirst()) +guard let command = arguments.first else { + print(helpText) + exit(2) +} +arguments.removeFirst() + +switch command { +case "capture": + runCapture(arguments) +case "list": + runList(arguments) +case "--help", "-h", "help": + print(helpText) +case "--version", "-v": + print("kapture (bundled with the Kapture app)") +default: + usageError("unknown command \"\(command)\"") +} diff --git a/build-app.sh b/build-app.sh index 49c4aac..052d0ca 100755 --- a/build-app.sh +++ b/build-app.sh @@ -89,6 +89,9 @@ fi rm -rf "$APP" mkdir -p "$APP/Contents/MacOS" cp "$BIN" "$APP/Contents/MacOS/Kapture" +# CLI client for agents/scripts; installed on PATH as `kapture` by the +# Homebrew cask (binary target: kapture). +cp ".build/release/kapture-cli" "$APP/Contents/MacOS/kapture-cli" cat > "$APP/Contents/Info.plist" <<'PLIST' @@ -108,9 +111,9 @@ cat > "$APP/Contents/Info.plist" <<'PLIST' CFBundleIconFile Icon CFBundleShortVersionString - 1.11.3 + 1.12.0 CFBundleVersion - 113 + 120 LSUIElement NSHighResolutionCapable @@ -124,9 +127,13 @@ PLIST chmod +x scripts/make-icon.sh ./scripts/make-icon.sh +# Nested executable: sign it explicitly so the bundle seal and notarization +# see a Developer ID signature rather than SwiftPM's ad-hoc one. if [ -n "$SIGN_KEYCHAIN" ]; then + codesign --force --options runtime --sign "$CERT" --keychain "$SIGN_KEYCHAIN" "$APP/Contents/MacOS/kapture-cli" codesign --force --options runtime --sign "$CERT" --keychain "$SIGN_KEYCHAIN" "$APP" else + codesign --force --sign "$CERT" "$APP/Contents/MacOS/kapture-cli" codesign --force --sign "$CERT" "$APP" fi