hex/crates/capture/helper/main.swift
Kit Langton a65a5e375f
feat(screenshots): record the screen, and keep captures until you close them (#1371)
* Talk over a screenshot: dictation words go with the shot

* Regenerate the screenshot editor goldens with the words row

* Cover the card held while someone talks over it

* Add the listening card's goldens

* Record the screen from Screenshots, ending in the corner card and a trim editor

* Move the capture timeline out, add the recording goldens and feature map

* Keep the replay's start on Windows quiet

* Keep the timeline move's imports and the replay start quiet off macOS

* Clear the record shortcut without returning its change

* Fix the macOS lints the recording left

* screenshots: only the open editor takes a dictation

A dictation taken while only the corner card showed used to talk over the
shot: the card held, showed "Listening…", and the words opened the shot in
the editor. That took the shortcut's normal paste away from everyone who
never asked for it.

Now only an open editor takes the words. While the card shows, a dictation
pastes as it did before the Lab, the card keeps its few seconds, and its
listening pill, hold and the narration path that opened the shot are gone.
The card's own card/listen/heard API goes with it, so nothing else can reach
the shot but the editor.

The i18n Screenshots rows move to i18n/labs.rs, where the Labs rows live,
so the main table stays under the source cap after dev's merge.

* screenshots: the editor's pieces come from the kit, and a shot grows in from where it was taken

The editor's toolbar was hand-made: five canvas-drawn tool glyphs in bespoke
hover chips, a bare ✕, a bare microphone, and action buttons stretched past
the kit's own height. The card's ✕ was a filled button beside them. They now
come from the rest of Hex: the tools are line icons beside the theme's own,
drawn by rune-kit icon buttons that fill while a tool is picked, ✕ and the
microphone and clear-words are the kit's ghost icon buttons like a capsule's,
and Copy, Save and Send to… are the kit's buttons at their own size. The
trim handles take the kit's corner.

A shot now grows in from the rectangle it was taken from. The card's overlay
is the whole display, so it can start anywhere on it: an area or window shot
starts at exactly the rectangle captured, at that size and place, and springs
into its corner slot on one spring that never overshoots its size, leaving
the same way. A whole-display shot keeps the slide in from the edge, and
Reduce Motion still only fades.

* screenshots: regenerate the editor and card goldens for the look pass

* docs: the card grows in from the shot's rectangle, and the editor is the kit's

* screenshots: a recording saves itself to the screenshots folder, as a shot does

* screenshots: cards stay until closed, stack in the corner, and take CleanShot's keys

* screenshots: Restore Last Capture in the menu bar brings back the card closed last

* screenshots: a Captures pane lists the last 30 days of shots and recordings

* screenshots: goldens for the card stack and the Captures pane, and its playground paths

* screenshots: the card's Return and the editor's file are macOS-only

* screenshots: pin that cards of any shape share the corner's right edge

* screenshots: keep macos_rune.rs and app_settings.rs under the file cap
2026-11-09 08:18:56 -08:00

172 lines
7.8 KiB
Swift

// scrawl-helper: the parts of Scrawl that need Swift-only Apple frameworks.
//
// scrawl-helper devices cabled iPhones/iPads (USB registry) as JSON
// scrawl-helper mirror --out FILE.mov [--device ID] [--microphone UID --microphone-name NAME | --no-microphone]
// live mirror window + native recording (JSON lines)
// scrawl-helper transcribe FILE [--locale ID] SpeechAnalyzer transcript with word timings
// scrawl-helper transcribe-stream [--locale ID] the same while recording: PCM on stdin, JSON lines (LiveTranscribe.swift)
// scrawl-helper speech-model [--install] [--locale ID] the speech model's status; install it (JSON lines)
// scrawl-helper frames MOVIE --out-dir DIR (--every MS | --at MS,MS…) [--max-edge PX]
// scrawl-helper audio MOVIE OUT.wav 16 kHz mono PCM of every audio track, mixed
// scrawl-helper probe MOVIE duration and video size
// scrawl-helper shrink MOVIE --out FILE.mov [--max-edge PX] [--bitrate BPS] HEVC copy, same timeline
// scrawl-helper export PLAN.json shareable .mp4: crop/camera, burned-in ink, audio (Export.swift)
// scrawl-helper permissions what Scrawl has been granted, as JSON
// scrawl-helper sck-probe [--watch SECONDS] can this process capture with ScreenCaptureKit (ScreenProbe.swift)
// scrawl-helper qr TEXT half-block QR code for `scrawl link`
//
// Every timestamp in the output is integer milliseconds. Scrawl drives the long-running
// `mirror` command over stdin (`stop`, `cancel`) and reads its events from stdout.
import AppKit
import CoreImage
import Foundation
func renderQR(_ message: String) -> String? {
guard let filter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
filter.setValue(Data(message.utf8), forKey: "inputMessage")
filter.setValue("L", forKey: "inputCorrectionLevel")
guard let image = filter.outputImage else { return nil }
let extent = image.extent.integral
let width = Int(extent.width)
let height = Int(extent.height)
guard width > 0, height > 0 else { return nil }
var pixels = [UInt8](repeating: 255, count: width * height * 4)
let context = CIContext(options: [.useSoftwareRenderer: true])
context.render(
image,
toBitmap: &pixels,
rowBytes: width * 4,
bounds: extent,
format: .RGBA8,
colorSpace: CGColorSpaceCreateDeviceRGB()
)
func isDark(_ x: Int, _ y: Int) -> Bool {
guard x >= 0, x < width, y >= 0, y < height else { return false }
// CIImage origin is bottom-left; flip y so top row renders first.
let flippedY = (height - 1) - y
return pixels[(flippedY * width + x) * 4] < 128
}
let pad = 1
var lines: [String] = []
var y = -pad
while y < height + pad {
var line = ""
for x in -pad ..< (width + pad) {
let top = isDark(x, y)
let bottom = (y + 1 < height + pad) ? isDark(x, y + 1) : false
switch (top, bottom) {
case (true, true): line.append("█")
case (true, false): line.append("▀")
case (false, true): line.append("▄")
case (false, false): line.append(" ")
}
}
lines.append(line)
y += 2
}
return lines.joined(separator: "\n")
}
func emit(_ object: Any) {
guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes]) else { return }
FileHandle.standardOutput.write(data + Data("\n".utf8))
}
func fail(_ message: String) -> Never {
FileHandle.standardError.write(Data("scrawl-helper: \(message)\n".utf8))
exit(1)
}
struct HelperError: LocalizedError {
let errorDescription: String?
init(_ message: String) { errorDescription = message }
}
func option(_ name: String, in arguments: [String]) -> String? {
guard let index = arguments.firstIndex(of: name), index + 1 < arguments.count else { return nil }
return arguments[index + 1]
}
/// Runs async work from a synchronous entry point, keeping the main queue free for AVFoundation.
func runAsync(_ body: @escaping () async throws -> Void) -> Never {
Task {
do {
try await body()
exit(0)
} catch {
fail(error.localizedDescription)
}
}
dispatchMain()
}
let arguments = Array(CommandLine.arguments.dropFirst())
switch arguments.first {
case "devices":
emit(Phone.cabled())
case "mirror":
let preview = arguments.contains("--preview")
let hidden = arguments.contains("--hidden")
let out = option("--out", in: arguments).map { URL(filePath: $0) }
if !preview && out == nil { fail("mirror needs --out FILE.mov or --preview") }
Mirror.run(
output: out, previewOnly: preview, hiddenPreview: hidden, deviceID: option("--device", in: arguments),
microphone: option("--microphone", in: arguments).map { ($0, option("--microphone-name", in: arguments) ?? $0) },
narration: !arguments.contains("--no-microphone")
)
case "transcribe":
guard arguments.count >= 2 else { fail("transcribe needs a file") }
runAsync { emit(try await Transcriber.transcribe(URL(filePath: arguments[1]), preferred: option("--locale", in: arguments))) }
case "transcribe-stream":
runAsync { try await LiveTranscriber.run(preferred: option("--locale", in: arguments)) }
case "speech-model":
let install = arguments.contains("--install")
runAsync { await SpeechModel.run(install: install, preferred: option("--locale", in: arguments)) }
case "frames":
guard arguments.count >= 2, let dir = option("--out-dir", in: arguments) else {
fail("frames needs MOVIE --out-dir DIR (--every MS | --at MS,MS…)")
}
let maxEdge = option("--max-edge", in: arguments).flatMap(Int.init) ?? 0
let every = option("--every", in: arguments).flatMap(Int.init)
let at = option("--at", in: arguments)?.split(separator: ",").compactMap { Int($0) }
runAsync {
emit(try await Media.frames(movie: URL(filePath: arguments[1]), outDir: URL(filePath: dir), everyMs: every, atMs: at, maxEdge: maxEdge))
}
case "audio":
guard arguments.count >= 3 else { fail("audio needs MOVIE OUT.wav") }
runAsync { emit(try await Media.exportAudio(movie: URL(filePath: arguments[1]), wav: URL(filePath: arguments[2]))) }
case "shrink":
guard arguments.count >= 2, let out = option("--out", in: arguments) else { fail("shrink needs MOVIE --out FILE.mov") }
let maxEdge = option("--max-edge", in: arguments).flatMap(Int.init) ?? 1600
let bitRate = option("--bitrate", in: arguments).flatMap(Int.init) ?? 2_500_000
runAsync {
emit(try await Media.shrink(movie: URL(filePath: arguments[1]), out: URL(filePath: out), maxEdge: maxEdge, bitRate: bitRate))
}
case "trim":
guard arguments.count >= 2, let out = option("--out", in: arguments),
let from = option("--from", in: arguments).flatMap(Int.init),
let to = option("--to", in: arguments).flatMap(Int.init)
else { fail("trim needs MOVIE --out FILE.mp4 --from MS --to MS") }
runAsync {
emit(try await Media.trim(movie: URL(filePath: arguments[1]), out: URL(filePath: out), fromMs: from, toMs: to))
}
case "export":
guard arguments.count >= 2 else { fail("export needs PLAN.json") }
runAsync { try await Exporter.run(plan: URL(filePath: arguments[1])) }
case "probe":
guard arguments.count >= 2 else { fail("probe needs MOVIE") }
runAsync { emit(try await Media.probe(URL(filePath: arguments[1]))) }
case "permissions":
emit(Permissions.statuses())
case "sck-probe":
let watch = option("--watch", in: arguments).flatMap(Double.init)
runAsync { await ScreenProbe.run(watch: watch) }
case "qr":
guard arguments.count >= 2, let qr = renderQR(arguments[1]) else {
fail("qr needs a text argument")
}
emit(["qr": qr])
default:
fail("usage: scrawl-helper devices|mirror|transcribe|transcribe-stream|speech-model|frames|audio|probe|export|shrink|trim|permissions|sck-probe|qr …")
}