Compare commits

..
2 Commits
Author SHA1 Message Date
TZGyn 6501aaefac Let crops extend past the image edges into blank padding
Crop handles can now be dragged outside the image; the extra area
applies as transparent padding (verified pixel-exact), capped at one
image dimension per side. Edges snap to the image borders within 10
points, and a Reset button in the crop bar restores the current image's
region. The crop canvas shows padding as a flat blank surface that
disappears as handles move back inside.

Generated with OpenCode

Assisted-by: Kimi:k3
2026-10-31 20:22:49 +08:00
TZGyn 6f8f436987 Add a kapture CLI so agents can capture windows and screens
kapture capture --app <name> (or --window-id / --screen) writes a PNG and
prints its path; kapture list enumerates on-screen windows. The CLI is a
thin client: requests go to the running menu-bar app over distributed
notifications plus JSON files in Application Support, so captures use the
app's Screen Recording grant and its window/display logic — no second
permission. The app launches automatically when needed, and the bundled
CLI opens its own app bundle rather than a stale installed copy.

Built as `kapture-cli` (Kapture/kapture collide on the case-insensitive
filesystem), signed nested in the app bundle, and installed on PATH as
`kapture` by the Homebrew cask's binary stanza.

Generated with OpenCode

Assisted-by: Kimi:k3
2026-10-27 23:38:43 +08:00
6 changed files with 593 additions and 26 deletions
+13 -1
View File
@@ -4,10 +4,22 @@ import PackageDescription
let package = Package( let package = Package(
name: "Kapture", name: "Kapture",
platforms: [.macOS(.v13)], 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: [ targets: [
.executableTarget( .executableTarget(
name: "Kapture", name: "Kapture",
path: "Sources/Kapture" path: "Sources/Kapture"
) ),
.executableTarget(
name: "KaptureCLI",
path: "Sources/KaptureCLI"
),
] ]
) )
+1
View File
@@ -42,6 +42,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
} }
} }
HotkeyManager.shared.register() HotkeyManager.shared.register()
CLIService.shared.start()
} }
func applicationWillTerminate(_ notification: Notification) { func applicationWillTerminate(_ notification: Notification) {
+211
View File
@@ -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())
}
}
+105 -23
View File
@@ -182,6 +182,12 @@ final class CaptureModel: ObservableObject {
if tool == .crop { tool = .select } if tool == .crop { tool = .select }
} }
/// Reset the crop handles to the current image's region — undoes any
/// in-progress adjustment, including padding.
func resetCrop() {
cropRect = CGRect(origin: cropOffset, size: CGSize(width: image.width, height: image.height))
}
/// Apply the pending crop rect and leave crop mode. /// Apply the pending crop rect and leave crop mode.
func applyCrop() { func applyCrop() {
guard let rect = cropRect else { return } guard let rect = cropRect else { return }
@@ -293,17 +299,26 @@ final class CaptureModel: ObservableObject {
} }
/// Crop to `rect` in the DISPLAYED image's pixel space (the original /// Crop to `rect` in the DISPLAYED image's pixel space (the original
/// image once a crop exists). Strokes are translated into the new /// image once a crop exists). The rect may extend past the image: the
/// coordinate space; strokes fully outside the crop are dropped. The /// outside becomes transparent padding. Strokes are translated into the
/// previous state is pushed onto the crop undo stack. /// new coordinate space; strokes fully outside the crop are dropped.
/// The previous state is pushed onto the crop undo stack.
func crop(to rectInDisplayedSpace: CGRect) { func crop(to rectInDisplayedSpace: CGRect) {
let source = originalImage ?? image let source = originalImage ?? image
let bounds = CGRect(origin: .zero, size: CGSize(width: source.width, height: source.height)) let sourceBounds = CGRect(origin: .zero, size: CGSize(width: source.width, height: source.height))
let rect = rectInDisplayedSpace.integral.intersection(bounds) let rect = rectInDisplayedSpace.integral
// No-op when the crop matches what's already visible. // No-op when the crop matches what's already visible.
let currentVisible = CGRect(origin: cropOffset, size: CGSize(width: image.width, height: image.height)) let currentVisible = CGRect(origin: cropOffset, size: CGSize(width: image.width, height: image.height))
guard rect.width >= 2, rect.height >= 2, rect != currentVisible, guard rect.width >= 2, rect.height >= 2, rect != currentVisible else { return }
let cropped = source.cropping(to: rect) else { return }
let cropped: CGImage
if sourceBounds.contains(rect) {
guard let cut = source.cropping(to: rect) else { return }
cropped = cut
} else {
guard let padded = Self.paddedCrop(source: source, rect: rect) else { return }
cropped = padded
}
cropHistory.append((image: image, strokes: strokes, redoStack: redoStack, offset: cropOffset)) cropHistory.append((image: image, strokes: strokes, redoStack: redoStack, offset: cropOffset))
image = cropped image = cropped
if originalImage == nil { originalImage = source } if originalImage == nil { originalImage = source }
@@ -330,6 +345,33 @@ final class CaptureModel: ObservableObject {
statusMessage = "Cropped to \(Int(rect.width))×\(Int(rect.height))." statusMessage = "Cropped to \(Int(rect.width))×\(Int(rect.height))."
} }
/// Crop with padding: a transparent bitmap the size of the crop rect,
/// with the source image drawn at its offset — parts of the rect beyond
/// the source stay blank.
static func paddedCrop(source: CGImage, rect: CGRect) -> CGImage? {
let w = Int(rect.width), h = Int(rect.height)
guard w > 0, h > 0 else { return nil }
guard let rep = NSBitmapImageRep(
bitmapDataPlanes: nil, pixelsWide: w, pixelsHigh: h,
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0
) else { return nil }
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
// This context is y-up and a CGImage's top edge lands on the
// destination rect's maxY. The source's top-left maps to the
// output's (-rect.minX, -rect.minY) in top-left space.
let ctx = NSGraphicsContext.current!.cgContext
ctx.draw(source, in: NSRect(
x: -rect.minX,
y: rect.height + rect.minY - CGFloat(source.height),
width: CGFloat(source.width),
height: CGFloat(source.height)
))
NSGraphicsContext.restoreGraphicsState()
return rep.cgImage
}
func runOCR(over selectionOnly: CGRect? = nil) { func runOCR(over selectionOnly: CGRect? = nil) {
guard !isOCRRunning else { return } guard !isOCRRunning else { return }
isOCRRunning = true isOCRRunning = true
@@ -711,7 +753,7 @@ struct ResultView: View {
.font(.caption) .font(.caption)
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
} else { } else {
Label("Drag the corners or edges to adjust the crop", systemImage: "hand.draw") Label("Drag the corners or edges — past the edge for blank space", systemImage: "hand.draw")
.font(.caption) .font(.caption)
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
} }
@@ -719,6 +761,11 @@ struct ResultView: View {
Spacer() Spacer()
if model.tool == .crop { if model.tool == .crop {
CapCapsuleButton(
title: "Reset", icon: "arrow.counterclockwise",
help: "Reset the crop to the current image"
) { model.resetCrop() }
CapCapsuleButton( CapCapsuleButton(
title: "Cancel", icon: "xmark", title: "Cancel", icon: "xmark",
help: "Cancel cropping (Esc)", help: "Cancel cropping (Esc)",
@@ -914,9 +961,25 @@ struct ScreenshotPane: View {
} }
} }
/// Snap crop edges to the image borders when they get within
/// `threshold` pixels (view-scale adjusted by the caller).
private static func snapped(_ rect: CGRect, to bounds: CGRect, threshold: CGFloat) -> CGRect {
var r = rect
if abs(r.minX - bounds.minX) < threshold { r.origin.x = bounds.minX }
if abs(r.minY - bounds.minY) < threshold { r.origin.y = bounds.minY }
if abs(r.maxX - bounds.maxX) < threshold { r.origin.x = bounds.maxX - r.width }
if abs(r.maxY - bounds.maxY) < threshold { r.origin.y = bounds.maxY - r.height }
return r
}
private func updateCropDrag(_ value: DragGesture.Value, scale: CGFloat, origin: CGPoint) { private func updateCropDrag(_ value: DragGesture.Value, scale: CGFloat, origin: CGPoint) {
guard let current = model.cropRect else { return } guard let current = model.cropRect else { return }
let bounds = CGRect(origin: .zero, size: imageSize) let bounds = CGRect(origin: .zero, size: imageSize)
// The crop may extend past the image (padding), capped at the
// image's largest side per edge so a runaway drag can't build a
// gigantic bitmap.
let cap = max(bounds.width, bounds.height)
let limit = bounds.insetBy(dx: -cap, dy: -cap)
if cropDrag == nil { if cropDrag == nil {
let cropView = CGRect( let cropView = CGRect(
x: origin.x + current.minX * scale, y: origin.y + current.minY * scale, x: origin.x + current.minX * scale, y: origin.y + current.minY * scale,
@@ -929,14 +992,15 @@ struct ScreenshotPane: View {
// Started outside the crop rect: draw a fresh one anchored // Started outside the crop rect: draw a fresh one anchored
// where the drag began (handled by the .se anchor math). // where the drag began (handled by the .se anchor math).
let anchor = toImagePoint(value.startLocation, scale: scale, origin: origin) let anchor = toImagePoint(value.startLocation, scale: scale, origin: origin)
guard bounds.contains(anchor) else { return } guard limit.contains(anchor) else { return }
cropDrag = .se cropDrag = .se
cropStartRect = CGRect(origin: anchor, size: .zero) cropStartRect = CGRect(origin: anchor, size: .zero)
} }
} }
guard let drag = cropDrag else { return } guard let drag = cropDrag else { return }
let delta = CGSize(width: value.translation.width / scale, height: value.translation.height / scale) let delta = CGSize(width: value.translation.width / scale, height: value.translation.height / scale)
let newRect = Self.resizedCropRect(from: cropStartRect, drag: drag, delta: delta, bounds: bounds) var newRect = Self.resizedCropRect(from: cropStartRect, drag: drag, delta: delta, bounds: limit)
newRect = Self.snapped(newRect, to: bounds, threshold: 10 / max(scale, 0.01))
guard newRect.width >= 1, newRect.height >= 1 else { return } guard newRect.width >= 1, newRect.height >= 1 else { return }
model.cropRect = newRect model.cropRect = newRect
} }
@@ -988,12 +1052,26 @@ struct ScreenshotPane: View {
let strokeOffset = strokeDisplayOffset let strokeOffset = strokeDisplayOffset
return ZStack { return ZStack {
// Card behind the image // Backing: normally a rounded card behind the image; in crop
RoundedRectangle(cornerRadius: 10) // mode a flat canvas covering the image AND any padding the
.fill(CapStyle.card) // crop rect extends into.
.shadow(color: Color.black.opacity(0.08), radius: 8, y: 2) if model.tool == .crop, let crop = model.cropRect {
.frame(width: drawSize.width, height: drawSize.height) let cropView = CGRect(
.position(x: cardRect.midX, y: cardRect.midY) x: origin.x + crop.minX * scale, y: origin.y + crop.minY * scale,
width: crop.width * scale, height: crop.height * scale
)
let backing = cardRect.union(cropView)
Rectangle()
.fill(CapStyle.card)
.frame(width: backing.width, height: backing.height)
.position(x: backing.midX, y: backing.midY)
} else {
RoundedRectangle(cornerRadius: 10)
.fill(CapStyle.card)
.shadow(color: Color.black.opacity(0.08), radius: 8, y: 2)
.frame(width: drawSize.width, height: drawSize.height)
.position(x: cardRect.midX, y: cardRect.midY)
}
Image(nsImage: NSImage(cgImage: displayedImage, size: .zero)) Image(nsImage: NSImage(cgImage: displayedImage, size: .zero))
.resizable() .resizable()
@@ -1047,12 +1125,15 @@ struct ScreenshotPane: View {
.allowsHitTesting(false) .allowsHitTesting(false)
} }
// Card hairline border // Card hairline border (hidden in crop mode: the crop rect
RoundedRectangle(cornerRadius: 10) // frames the canvas, and the border would cut across padding)
.strokeBorder(CapStyle.border, lineWidth: 1) if model.tool != .crop {
.frame(width: drawSize.width, height: drawSize.height) RoundedRectangle(cornerRadius: 10)
.position(x: cardRect.midX, y: cardRect.midY) .strokeBorder(CapStyle.border, lineWidth: 1)
.allowsHitTesting(false) .frame(width: drawSize.width, height: drawSize.height)
.position(x: cardRect.midX, y: cardRect.midY)
.allowsHitTesting(false)
}
if model.tool == .crop, let crop = model.cropRect { if model.tool == .crop, let crop = model.cropRect {
let cropView = CGRect( let cropView = CGRect(
@@ -1100,7 +1181,8 @@ struct ScreenshotPane: View {
context.stroke(dot, with: .color(.black.opacity(0.4)), lineWidth: 1) context.stroke(dot, with: .color(.black.opacity(0.4)), lineWidth: 1)
} }
} }
.clipShape(cardClip) // Not clipped to the card: the crop rect can extend past
// the image into padding, and its handles must show.
.allowsHitTesting(false) .allowsHitTesting(false)
} }
+254
View File
@@ -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 <name|bundle-id> App whose frontmost window to capture. Matches
localized names and bundle ids, case-insensitive
substring. Default: the frontmost app's window.
--window-id <id> Capture a specific window id from `kapture list`.
--screen Capture the main display instead of a window.
--out <path> 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)\"")
}
+9 -2
View File
@@ -89,6 +89,9 @@ fi
rm -rf "$APP" rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS" mkdir -p "$APP/Contents/MacOS"
cp "$BIN" "$APP/Contents/MacOS/Kapture" 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' cat > "$APP/Contents/Info.plist" <<'PLIST'
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
@@ -108,9 +111,9 @@ cat > "$APP/Contents/Info.plist" <<'PLIST'
<key>CFBundleIconFile</key> <key>CFBundleIconFile</key>
<string>Icon</string> <string>Icon</string>
<key>CFBundleShortVersionString</key> <key>CFBundleShortVersionString</key>
<string>1.11.3</string> <string>1.13.0</string>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
<string>113</string> <string>130</string>
<key>LSUIElement</key> <key>LSUIElement</key>
<true/> <true/>
<key>NSHighResolutionCapable</key> <key>NSHighResolutionCapable</key>
@@ -124,9 +127,13 @@ PLIST
chmod +x scripts/make-icon.sh chmod +x scripts/make-icon.sh
./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 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" codesign --force --options runtime --sign "$CERT" --keychain "$SIGN_KEYCHAIN" "$APP"
else else
codesign --force --sign "$CERT" "$APP/Contents/MacOS/kapture-cli"
codesign --force --sign "$CERT" "$APP" codesign --force --sign "$CERT" "$APP"
fi fi