Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f8f436987 | ||
|
|
cac85402a3 | ||
|
|
d4b0970ed2 |
+13
-1
@@ -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"
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
@@ -42,6 +42,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
}
|
||||
}
|
||||
HotkeyManager.shared.register()
|
||||
CLIService.shared.start()
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ notification: Notification) {
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,12 @@ final class ResultWindow {
|
||||
static let shared = ResultWindow()
|
||||
|
||||
private var windows: [NSWindow] = []
|
||||
/// Kept alive: the hosting controller drives the SwiftUI view we attach
|
||||
/// directly as the window's contentView. Using contentViewController
|
||||
/// would install Auto Layout constraints that force the window to the
|
||||
/// view's fitting size — it shrank whenever the layout branch changed
|
||||
/// (e.g. toggling Actual Size).
|
||||
private var hosts: [ObjectIdentifier: NSHostingController<ResultView>] = [:]
|
||||
private var nextOrigin = NSPoint(x: 60, y: 60)
|
||||
private var openCount = 0
|
||||
|
||||
@@ -13,15 +19,21 @@ final class ResultWindow {
|
||||
func show(image: CGImage) {
|
||||
let model = CaptureModel(image: image)
|
||||
let w = NSWindow()
|
||||
w.contentViewController = NSHostingController(rootView: ResultView(model: model) {
|
||||
let host = NSHostingController(rootView: ResultView(model: model) {
|
||||
w.close()
|
||||
})
|
||||
w.contentView = host.view
|
||||
hosts[ObjectIdentifier(w)] = host
|
||||
w.title = "Kapture — Screenshot" + (openCount > 0 ? " \(openCount + 1)" : "")
|
||||
w.level = .floating
|
||||
w.styleMask = [.titled, .closable, .resizable]
|
||||
w.setContentSize(NSSize(width: 694, height: 520))
|
||||
w.isReleasedWhenClosed = false
|
||||
w.setFrameOrigin(nextOrigin)
|
||||
// Activate so the FIRST click on any control (Actual Size, Copy, the
|
||||
// mode picker…) reaches it. Without this, an inactive LSUIElement
|
||||
// app's windows swallow the initial click just to activate.
|
||||
NSApp.activate(ignoringOtherApps: true)
|
||||
w.makeKeyAndOrderFront(nil)
|
||||
|
||||
windows.append(w)
|
||||
@@ -40,6 +52,7 @@ final class ResultWindow {
|
||||
Task { @MainActor in
|
||||
guard let self else { return }
|
||||
self.windows.removeAll { $0 === window }
|
||||
self.hosts[ObjectIdentifier(window)] = nil
|
||||
self.openCount = max(0, self.openCount - 1)
|
||||
}
|
||||
}
|
||||
@@ -107,7 +120,11 @@ final class CaptureModel: ObservableObject {
|
||||
/// Whether the pen is active (drag draws instead of selecting)
|
||||
@Published var tool: Tool = .select
|
||||
/// Actual-size view: 1 image pixel per screen pixel, scrollable.
|
||||
@Published var isActualSize = false
|
||||
/// Persisted so the choice carries over to new windows and launches.
|
||||
@Published var isActualSize: Bool = UserDefaults.standard.bool(forKey: CaptureModel.actualSizeKey) {
|
||||
didSet { UserDefaults.standard.set(isActualSize, forKey: CaptureModel.actualSizeKey) }
|
||||
}
|
||||
private static let actualSizeKey = "actualSizeView"
|
||||
/// Current drawing color
|
||||
@Published var drawColor: NSColor = .systemRed
|
||||
/// Stroke thickness in points (image space)
|
||||
@@ -525,8 +542,61 @@ private struct CapIconButton: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Result window
|
||||
/// Reports the hosting window's backing scale factor. Used by the
|
||||
/// actual-size view so one image pixel maps to exactly one device pixel.
|
||||
/// SwiftUI's `displayScale` environment is unreliable on macOS and does not
|
||||
/// follow the window when it moves between displays of different densities.
|
||||
private struct WindowScaleReader: NSViewRepresentable {
|
||||
let onChange: (CGFloat) -> Void
|
||||
|
||||
func makeNSView(context: Context) -> ScaleProbeView {
|
||||
let view = ScaleProbeView()
|
||||
view.onChange = onChange
|
||||
return view
|
||||
}
|
||||
|
||||
func updateNSView(_ nsView: ScaleProbeView, context: Context) {
|
||||
nsView.onChange = onChange
|
||||
}
|
||||
|
||||
final class ScaleProbeView: NSView {
|
||||
var onChange: ((CGFloat) -> Void)?
|
||||
private var observers: [NSObjectProtocol] = []
|
||||
private var lastScale: CGFloat = 0
|
||||
|
||||
override func viewDidMoveToWindow() {
|
||||
super.viewDidMoveToWindow()
|
||||
observers.forEach(NotificationCenter.default.removeObserver)
|
||||
observers = []
|
||||
report()
|
||||
guard let window else { return }
|
||||
for name in [NSWindow.didChangeBackingPropertiesNotification,
|
||||
NSWindow.didChangeScreenNotification] {
|
||||
observers.append(NotificationCenter.default.addObserver(
|
||||
forName: name, object: window, queue: .main
|
||||
) { [weak self] _ in
|
||||
self?.report()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private func report() {
|
||||
let scale = window?.backingScaleFactor ?? NSScreen.main?.backingScaleFactor ?? 2
|
||||
guard scale != lastScale else { return }
|
||||
lastScale = scale
|
||||
// Defer: this runs during layout, and the callback writes @State.
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.onChange?(scale)
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
observers.forEach(NotificationCenter.default.removeObserver)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Result window
|
||||
struct ResultView: View {
|
||||
@ObservedObject var model: CaptureModel
|
||||
let onClose: () -> Void
|
||||
@@ -714,7 +784,7 @@ struct ResultView: View {
|
||||
? "Adjust the crop — Return to apply, Esc to cancel."
|
||||
: (model.hasSelection
|
||||
? "Region selected — OCR it, or adjust it with Crop."
|
||||
: (model.isActualSize ? "Actual size — scroll to pan, drag to select." : "Drag to select a region, or Get All Text.")))
|
||||
: (model.isActualSize ? "Actual size — 1:1 pixels, scroll to pan." : "Drag to select a region, or Get All Text.")))
|
||||
: "Selectable text"))
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
@@ -871,15 +941,21 @@ struct ScreenshotPane: View {
|
||||
model.cropRect = newRect
|
||||
}
|
||||
|
||||
@Environment(\.displayScale) private var displayScale
|
||||
@State private var windowScale: CGFloat = 2
|
||||
|
||||
/// Image pixels to window points. Actual size is 1 image pixel per
|
||||
/// device pixel, i.e. 1/windowScale points.
|
||||
private var actualSizeScale: CGFloat {
|
||||
1 / max(windowScale, 0.01)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
GeometryReader { geo in
|
||||
if model.isActualSize {
|
||||
// Actual size: 1 image pixel per screen pixel (view scale =
|
||||
// 1/displayScale). Scrollable when larger than the viewport;
|
||||
// 1/windowScale). Scrollable when larger than the viewport;
|
||||
// centred when smaller.
|
||||
let scale = 1 / max(displayScale, 0.01)
|
||||
let scale = actualSizeScale
|
||||
let drawSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
|
||||
let origin = CGPoint(
|
||||
x: max(0, (geo.size.width - drawSize.width) / 2),
|
||||
@@ -898,6 +974,9 @@ struct ScreenshotPane: View {
|
||||
.frame(width: geo.size.width, height: geo.size.height)
|
||||
}
|
||||
}
|
||||
.background(WindowScaleReader { scale in
|
||||
windowScale = scale
|
||||
})
|
||||
}
|
||||
|
||||
/// The image card with annotations, selection and crop overlays, plus
|
||||
|
||||
@@ -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
@@ -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'
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
@@ -108,9 +111,9 @@ cat > "$APP/Contents/Info.plist" <<'PLIST'
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>Icon</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.11.1</string>
|
||||
<string>1.12.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>111</string>
|
||||
<string>120</string>
|
||||
<key>LSUIElement</key>
|
||||
<true/>
|
||||
<key>NSHighResolutionCapable</key>
|
||||
@@ -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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user